2 2 import * as fs
from "node:fs";
3 3 import * as path
from "node:path";
4 4 import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext }
from "@earendil-works/pi-coding-agent";
5 5 import { loadConfig, type LlmiterateConfig, type NotifyPolicy }
from "./config";
6 -import { compilePathFilter, projectStoreDir, shouldIncludeCompiledPath, type CompiledPathFilter }
from "./path-filter";
7 -import { parseMarkerPrompts, type MarkerPrompt }
from "./parser";
6 +import { compilePathFilter, globToRegExp, projectStoreDir, shouldIncludeCompiledPath, type CompiledPathFilter }
from "./path-filter";
7 +import { isLlmiterateDisabled, parseMarkerPrompts, type MarkerPrompt }
from "./parser";
8 8 import { buildAgentPrompt }
from "./prompt";
9 9 import { emptyState, loadState, saveState, type LlmiterateState, type MarkerRunState }
from "./state";
10 10 import { previewText, toSlash }
from "./util";
11 -import { acquireLock, findProjectRoot, realPath, releaseLock, type LockHandle }
from "./lock";
11 +import { acquireLock, realPath, releaseLock, type LockHandle }
from "./lock";
12 12 import { LLMITERATE_WORKER_ENV, PiRpcWorker }
from "./rpc";
13 13 import { openInEditor, renderLatestSessionLog }
from "./log";
14 -import { renderLlmiterateUi }
from "./ui";
14 +import { renderLlmiterateStatus }
from "./ui";
15 15 import { ProjectWatcher }
from "./watcher";
16 16 import type { LlmiterateRun, RpcEvent, RpcMessage, RpcTextPart, RpcToolResult }
from "./types";
53 53 const STATE_PROMPT_PREVIEW_CHARS
= 120;
54 54 const ERROR_PREVIEW_CHARS
= 160;
55 -const COMMAND_USAGE
= "Usage: /llmiterate [show|hide|status|scan|reset|reload|log]";
55 +const COMMAND_USAGE
= "Usage: /llmiterate [on|off|status|log|explain <path>]";
56 +const COMPLETED_COMMANDS
= [
"on",
"off",
"status",
"log",
"explain"]
as const;
57 58 export function createLlmiterateExtension(deps
: LlmiterateExtensionDeps = {}) {
58 59 return function llmiterate(pi
: ExtensionAPI) {
67 68 class LlmiterateController {
68 69 private runtime
?: WatchRuntime;
69 70 private sessionCtx
?: ExtensionContext;
70 - private panelVisible
= false;
71 71 private nextRunId
= 1;
72 72 private activeRunId
?: number;
73 73 private activeJob
= false;
95 95 this.pi.
on(
"session_start",
async (_event, ctx)
=> this.
onSessionStart(ctx));
96 96 this.pi.
on(
"session_shutdown",
async ()
=> this.
onSessionShutdown());
97 97 this.pi.
registerCommand(
"llmiterate", {
98 - description:
"Toggle/show llmiterate watcher UI. Args: show | hide | status | scan | reset | reload | log",
98 + description:
"Toggle llmiterate for current cwd. Args: on | off | status | log | explain <path>",
99 + getArgumentCompletions: (prefix
: string)
=> {
100 + if (prefix.
trimStart().
includes(
" "))
return null;
101 + const items
= COMPLETED_COMMANDS
102 + .
filter((command)
=> command.
startsWith(prefix.
trimStart()))
103 + .
map((command)
=> ({ value: command, label: command }));
104 + return items.
length ? items
: null;
99 106 handler:
async (args, ctx)
=> {
100 - this.
runCommand(args.
trim().
toLowerCase(), ctx);
107 + this.
runCommand(args, ctx);
101 108 this.
updateUi(ctx);
106 113 private
onSessionStart(ctx: ExtensionContext):
void {
107 114 this.sessionCtx
= ctx;
108 - this.
start(ctx.cwd);
109 115 this.
updateUi(ctx);
112 118 private
onSessionShutdown():
void {
120 + this.
updateUi(this.sessionCtx);
114 121 this.sessionCtx
= undefined;
115 122 this.activeRunId
= undefined;
118 - private
runCommand(command: string, ctx: ExtensionCommandContext):
void {
125 + private
runCommand(args: string, ctx: ExtensionCommandContext):
void {
126 + const { command, rest }
= parseCommandArgs(args);
119 127 switch (command) {
120 - case "": this.panelVisible
= !this.panelVisible;
return;
122 - case "status": this.panelVisible
= true;
return;
123 - case "hide": this.panelVisible
= false;
return;
124 - case "scan": this.
scanCommand(ctx);
return;
125 - case "reset": this.
resetCommand(ctx);
return;
126 - case "reload": this.
reloadCommand(ctx);
return;
128 + case "": this.
toggleCommand(ctx);
return;
129 + case "on": this.
onCommand(ctx);
return;
130 + case "off": this.
offCommand(ctx);
return;
131 + case "status": this.
statusCommand(ctx);
return;
127 132 case "log": this.
logCommand(ctx);
return;
133 + case "explain": this.
explainCommand(rest, ctx);
return;
134 + case "scan": this.
scanCommand(ctx);
return;
135 + case "forget": this.
forgetCommand(ctx);
return;
136 + case "reload": this.
reloadCommand(ctx);
return;
128 137 default: ctx.ui.
notify(COMMAND_USAGE,
"warning");
132 - private
scanCommand(ctx: ExtensionCommandContext):
void {
133 - if (this.
notifyIfStandby(ctx)) {
134 - this.panelVisible
= true;
141 + private
toggleCommand(ctx: ExtensionCommandContext):
void {
142 + if (this.runtime) this.
offCommand(ctx);
143 + else this.
onCommand(ctx);
146 + private
onCommand(ctx: ExtensionCommandContext):
void {
147 + if (this.runtime
&& !this.runtime.lockError) {
148 + ctx.ui.
notify(
`llmiterate already on: ${this.runtime.root}`,
"info");
152 + this.
start(ctx.cwd);
153 + if (
!this.runtime)
return;
154 + if (
!this.runtime.config.enabled) {
155 + ctx.ui.
notify(
"llmiterate disabled by config",
"warning");
159 + if (this.
notifyIfStandby(ctx))
return;
161 + const count
= this.
scanAll();
162 + ctx.ui.
notify(
`llmiterate on: ${this.runtime.root}${count ? `; queued ${count}` : ""}`,
"info");
165 + private
offCommand(ctx: ExtensionCommandContext):
void {
166 + if (
!this.runtime) {
167 + ctx.ui.
notify(
"llmiterate already off",
"info");
172 + ctx.ui.
notify(
"llmiterate off",
"info");
175 + private
scanCommand(ctx: ExtensionCommandContext):
void {
176 + if (
!this.runtime) {
177 + ctx.ui.
notify(
"llmiterate off; run /llmiterate on",
"warning");
180 + if (this.
notifyIfStandby(ctx))
return;
138 182 const count
= this.
scanAll();
139 - this.panelVisible
= true;
140 183 ctx.ui.
notify(
`llmiterate scan queued ${count} new prompt(s)`,
"info");
143 - private
resetCommand(ctx: ExtensionCommandContext):
void {
186 + private
forgetCommand(ctx: ExtensionCommandContext):
void {
144 187 if (this.
notifyIfStandby(ctx))
return;
146 189 if (this.runtime) {
150 193 this.
stopWorker();
151 194 this.runs.
length = 0;
152 195 this.activeRunId
= undefined;
153 - ctx.ui.
notify(
"llmiterate state reset",
"info");
196 + ctx.ui.
notify(
"llmiterate forgot run state",
"info");
156 199 private
reloadCommand(ctx: ExtensionCommandContext):
void {
157 - this.
start(ctx.cwd);
200 + if (
!this.runtime) {
201 + ctx.ui.
notify(
"llmiterate off; run /llmiterate on",
"warning");
204 + const cwd
= this.runtime.cwd;
158 206 ctx.ui.
notify(
"llmiterate config/watcher reloaded",
"info");
209 + private
statusCommand(ctx: ExtensionCommandContext):
void {
210 + ctx.ui.
notify(this.
statusText(ctx.cwd),
"info");
161 213 private
logCommand(ctx: ExtensionCommandContext):
void {
162 - if (
!this.runtime)
return;
214 + if (
!this.runtime) {
215 + ctx.ui.
notify(
"llmiterate off; no active worker log",
"warning");
164 219 const target
= renderLatestSessionLog(
sessionDir(this.runtime), path.
join(this.runtime.storeDir,
"logs"));
171 226 if (error) ctx.ui.
notify(
`llmiterate log written: ${target.markdownFile} (${error})`,
"warning");
229 + private
explainCommand(targetPath: string, ctx: ExtensionCommandContext):
void {
230 + const target
= targetPath.
trim();
232 + ctx.ui.
notify(
"Usage: /llmiterate explain <path>",
"warning");
235 + ctx.ui.
notify(
explainPath(ctx.cwd, target),
"info");
238 + private
statusText(cwd: string): string {
239 + const runtime
= this.runtime;
240 + if (
!runtime)
return `llmiterate off\nscope: ${realPath(cwd)}`;
242 + const active
= this.
activeRun();
244 + runtime.lockError
? "llmiterate standby" : "llmiterate on",
245 + `scope: ${runtime.root}`,
246 + ...(runtime.lockError
? [
`reason: ${runtime.lockError}`,
"action: use existing same-cwd watcher, stop it, or choose another cwd"]
: []),
247 + `filters: include ${runtime.config.include.length}, exclude ${runtime.config.exclude.length}, .gitignore/.ignore on`,
248 + `watch dirs: ${runtime.watcher?.watcherCount ?? 0}`,
249 + `watch errors: ${runtime.watcher?.errorCount ?? 0}`,
250 + `queued: ${this.queuedRunCount()}`,
251 + `running: ${active ? `${active.projectFile}:${active.block.startLine}` : "none"}`,
252 + `failed: ${this.runs.filter((run) => run.status === "error").length}`,
253 + `state: ${runtime.storeDir}`,
174 257 private
notifyIfStandby(ctx: ExtensionCommandContext): boolean {
175 258 if (
!this.runtime?.lockError)
return false;
176 - ctx.ui.
notify(
`llmiterate inactive: ${this.runtime.lockError}`,
"warning");
259 + ctx.ui.
notify(
`llmiterate standby: ${this.runtime.root} already watched (${this.runtime.lockError})`,
"warning");
180 263 private
start(cwd: string):
void {
183 - const root
= findProjectRoot(cwd);
266 + const root
= realPath(cwd);
184 267 const config
= loadConfig(
root);
185 268 const storeDir
= projectStoreDir(
root);
188 - cwd:
realPath(cwd),
190 273 pathFilter:
compilePathFilter(config),
285 368 private
enqueueRun(block: MarkerPrompt, projectFile: string, absoluteFile: string):
void {
286 369 this.runs.
unshift(this.
createRun(block, projectFile, absoluteFile));
287 - this.
maybeNotify(
"queued",
`llmiterate queued ${projectFile}:${block.startLine}`);
288 370 this.
startNextRun();
289 371 this.
updateUi(this.sessionCtx);
426 508 if (run.
status === "error")
return;
427 509 run.
status = "done";
428 510 this.
setMarkerStatus(run,
"done");
429 - this.
maybeNotify(
"done",
`llmiterate done ${run.projectFile}:${run.block.startLine}`);
430 511 this.
touchRun(run);
488 569 private
updateUi(ctx: ExtensionContext
| undefined):
void {
489 - renderLlmiterateUi(ctx, this.panelVisible, this.runs, {
570 + renderLlmiterateStatus(ctx, {
490 571 config: this.runtime?.config,
491 572 lockError: this.runtime?.lockError,
492 573 watchErrors: this.runtime?.watcher?.errorCount
?? 0,
505 586 return path.
join(runtime.storeDir,
"sessions");
589 +function parseCommandArgs(args
: string)
: { command
: string; rest
: string } {
590 + const trimmed
= args.
trim();
591 + if (
!trimmed)
return { command:
"", rest:
"" };
592 + const match
= trimmed.
match(
/^(\S+)(?:\s+([\s\S]*))?$/);
593 + return { command: (match?.[
1]
?? "").
toLowerCase(), rest: match?.[
2]
?? "" };
596 +function explainPath(cwd
: string, target
: string)
: string {
597 + const scope
= realPath(cwd);
598 + const abs
= path.
resolve(scope, target);
599 + const rel
= toSlash(path.
relative(scope, abs));
600 + const config
= loadConfig(scope);
601 + const stat
= statFile(abs);
602 + const directory
= stat?.
isDirectory()
=== true;
603 + const include
= firstMatchingGlob(config.include, rel, directory);
604 + const exclude
= firstMatchingGlob(config.exclude, rel, directory);
605 + const unsafe
= !rel
|| rel.
startsWith(
"..")
|| path.
isAbsolute(rel);
606 + const tooLarge
= stat?.
isFile()
&& stat.
size > config.maxFileBytes;
607 + const text
= stat?.
isFile()
&& !tooLarge
? readUtf8(abs)
: undefined;
608 + const disabled
= text
!== undefined && isLlmiterateDisabled(text, rel, config.commentPrefixes);
609 + const markers
= text
!== undefined && !disabled
? parseMarkerPrompts(rel, text, config.commentPrefixes).
length : 0;
610 + const status
= explainStatus({ unsafe, stat, include, exclude, tooLarge, disabled, markers });
615 + `included: ${include ?? "no"}`,
616 + `excluded: ${exclude ?? "no"}`,
617 + `ignored: .gitignore/.ignore respected during scan/watch`,
618 + `size: ${stat?.isFile() ? `${formatBytes(stat.size)} / ${formatBytes(config.maxFileBytes)}` : "not a file"}`,
619 + `markers: ${disabled ? "disabled by !llmiterate" : markers}`,
620 + `status: ${status}`,
624 +function firstMatchingGlob(globs
: readonly string[], rel
: string, directory
: boolean)
: string | undefined {
625 + for (
const glob
of globs) {
626 + const pattern
= globToRegExp(glob);
627 + if (pattern.
test(rel)
|| (directory
&& pattern.
test(
`${rel}/`)))
return glob;
632 +function explainStatus(input
: {
634 + stat
: fs.
Stats | undefined;
635 + include
: string | undefined;
636 + exclude
: string | undefined;
637 + tooLarge
: boolean | undefined;
641 + if (input.unsafe)
return "outside scope";
642 + if (
!input.stat)
return "missing";
643 + if (
!input.stat.
isFile())
return "not a file";
644 + if (
!input.include)
return "not included";
645 + if (input.exclude)
return "excluded";
646 + if (input.tooLarge)
return "too large";
647 + if (input.
disabled)
return "disabled";
648 + if (input.markers
=== 0)
return "no llmiterate marker";
652 +function formatBytes(bytes
: number)
: string {
653 + if (bytes
< 1024)
return `${bytes} B`;
654 + if (bytes
< 1024 * 1024)
return `${(bytes / 1024).toFixed(1)} KB`;
655 + return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
508 658 function statFile(absPath
: string)
: fs.
Stats | undefined {
509 659 try {
return fs.
statSync(absPath); }
catch {
return undefined; }
516 666 function shouldNotify(policy
: NotifyPolicy, kind
: "queued" | "done" | "error")
: boolean {
517 - if (policy
=== "off")
return false;
518 - if (policy
=== "all")
return true;
519 - if (policy
=== "done")
return kind
=== "done" || kind
=== "error";
520 - return kind
=== "error";
667 + return policy
!== "off" && kind
=== "error";
523 670 function sessionName(run
: LlmiterateRun)
: string {