@cryer/star-cli 0.3.7 → 0.3.9

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/messages.ts","../src/config/schema.ts","../src/snapshot/git-tree.ts"],"sourcesContent":["import type { CoreMessage, ToolCallPart } from \"ai\";\n\nexport type { CoreMessage };\n\n// Side-band metadata the model never sees. It rides next to a persisted\n// message (the __starMeta jsonl key) so turn-boundary scans can tell a real\n// user turn from a loop-injected user message:\n// - \"nudge\": auto-continue / resume-after-cutoff steering injected mid-turn\n// - \"bg-report\": a finished background subagent's report, delivered mid-turn\n// - \"tool-image\": images a tool (read_image/screenshot) attached mid-turn\nexport interface MessageMeta {\n synthetic?: \"nudge\" | \"bg-report\" | \"tool-image\";\n}\n\nexport interface StarMessage {\n message: CoreMessage;\n meta?: MessageMeta;\n}\n\nexport function toStarMessage(message: CoreMessage | StarMessage): StarMessage {\n return \"role\" in message ? { message } : message;\n}\n\nexport function toCoreMessages(messages: readonly StarMessage[]): CoreMessage[] {\n return messages.map((star) => star.message);\n}\n\n// A synthetic user message belongs to the turn that precedes it: it is never\n// a turn boundary for /undo, /rewind or compaction turn splitting.\nexport function isSyntheticUserMessage(star: StarMessage): boolean {\n return star.message.role === \"user\" && star.meta?.synthetic !== undefined;\n}\n\n// Plain-text content of a message: string content as-is; for array content,\n// the text parts joined with a space (tool calls, images and tool results\n// contribute nothing). Shared by the agent loop (/redo labels) and the CLI\n// (history rendering, conversation copy) so the extraction rule lives once.\nexport function coreMessageText(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\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\n// A tool call that has no real execution result must still be closed with a\n// synthetic tool message, or the stored history can no longer be sent to the\n// API. Three scenarios, three wordings:\n// - MISSING_TOOL_RESULT_TEXT: reconcileToolCalls/reconcileStarMessages repair\n// a persisted history whose session ended before the results were written\n// (crash, kill, older version) — the call may never have run at all.\n// - INTERRUPTED_TOOL_RESULT_TEXT: the user pressed Esc while the call was\n// still streaming in or executing (agent loop abort paths).\n// - UNFINISHED_TOOL_RESULT_TEXT: execution stopped for any other reason\n// (e.g. an error mid-batch) before the call produced a result.\nexport const MISSING_TOOL_RESULT_TEXT = \"tool result missing (session was interrupted)\";\nexport const INTERRUPTED_TOOL_RESULT_TEXT = \"Tool execution interrupted by user.\";\nexport const UNFINISHED_TOOL_RESULT_TEXT =\n \"Tool execution interrupted before a result was produced.\";\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// StarMessage counterpart of reconcileToolCalls: same repair, preserving the\n// side-band meta of every surviving message. Synthetic filler results carry\n// no meta.\nexport function reconcileStarMessages(messages: readonly StarMessage[]): StarMessage[] {\n const result: StarMessage[] = [];\n let pending: { toolCallId: string; toolName: string }[] = [];\n\n const flushPending = () => {\n for (const call of pending) {\n result.push({\n message: {\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 }\n pending = [];\n };\n\n for (const star of messages) {\n const message = star.message;\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(star);\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// Synthetic user messages (auto-continue nudges, background reports, tool\n// images) belong to the turn they sit in, so the scan skips them and the\n// boundary lands on the real user message that opened the turn. A leading\n// system message is never touched. Returns the trimmed list and how many\n// messages were dropped (0 = nothing to retract).\nexport function retractLastTurn(messages: StarMessage[]): {\n messages: StarMessage[];\n removed: number;\n} {\n for (let i = messages.length - 1; i >= 0; i--) {\n const star = messages[i];\n if (star && star.message.role === \"user\" && !isSyntheticUserMessage(star)) {\n return { messages: messages.slice(0, i), removed: messages.length - i };\n }\n }\n return { messages, removed: 0 };\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 // Sampling temperature forwarded on every request. Unset = the AI SDK's\n // own default applies (ai@4 sends 0 — it does NOT omit the field). Some\n // endpoints reject anything but one explicit value (e.g. kimi-for-coding:\n // \"invalid temperature: only 1 is allowed\") — set it here. No upper\n // bound: ranges vary by provider and the server validates.\n temperature: z.number().min(0).optional(),\n // Per-model overrides of the top-level stream watchdog timeouts (unset =\n // the global values apply). Raise streamIdleTimeoutSec for relays that\n // buffer long generations and stall mid-stream between flushes.\n streamIdleTimeoutSec: z.number().positive().optional(),\n streamFirstChunkTimeoutSec: z.number().positive().optional(),\n // Text-only models: set false so image-producing tools (read_image,\n // screenshot) decline with a text error instead of attaching images the\n // endpoint would reject with an unrecoverable 4xx. Unset = images allowed.\n vision: z.boolean().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 // Rules that force a confirmation prompt in auto mode (same tool(glob)\n // syntax as allow/deny) — e.g. ask = [\"bash(git push *)\"]. Priority:\n // deny > ask > allow > mode default. Only meaningful in auto mode (ask\n // mode already prompts; readonly/plan are unaffected; yolo bypasses all).\n ask: z.array(z.string()).default([]),\n // Extra likely-secret file globs extending core/sensitive.ts's hardcoded\n // list (same single-* glob semantics as rules, matched case-insensitively\n // against the basename and the full normalized path). Global config only —\n // the project-config sandbox drops the whole [permissions] table.\n sensitive: 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 // Optional [[models]] name for cheap auxiliary LLM calls (compaction\n // summaries, session titles, turn completion checks) — Claude Code routes\n // these to a Haiku-class model. Unset = the active main model does them.\n smallModel: z.string().optional(),\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 // content has started streaming; the wait for the first content part gets\n // a longer allowance (control/metadata parts don't count as content).\n streamIdleTimeoutSec: z.number().positive().default(20),\n // Seconds to wait for the very first content part before giving up; slow\n // thinking-model endpoints can stay silent for minutes after accepting\n // the request.\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 // web_fetch SSRF guard escape hatch: by default target hosts are resolved\n // before connecting and private/reserved ranges are refused (loopback,\n // RFC1918, link-local incl. the cloud metadata address 169.254.169.254,\n // ULA, and localhost/.local/.internal names; redirect hops re-checked).\n // true disables the guard for intranet use. Global config only — not in\n // the project-config sandbox whitelist.\n webFetchAllowPrivateHosts: z.boolean().default(false),\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 { execFile } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readdir, rm, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { gitTreesDir } from \"../config/paths\";\nimport { isSensitivePath } from \"../core/sensitive\";\n\nconst GIT_TIMEOUT_MS = 10_000;\n// gc repacks the object store and legitimately takes longer than the budget\n// every other git invocation gets; it runs rarely, so it can afford to wait.\nconst GC_TIMEOUT_MS = 60_000;\nconst GIT_MAX_BUFFER = 8 * 1024 * 1024;\n// `git gc --auto` runs after this many successful tree captures per repo\n// (each capture adds a tree plus blobs, and nothing else ever prunes them).\nconst GC_INTERVAL = 50;\n// The agent loop calls trackTree at the start of every turn; without a\n// negative cache a directory whose tracking fails (huge tree hitting the git\n// timeout, unreadable repo) would burn that timeout on every single turn.\nconst TRACK_FAILURE_TTL_MS = 5 * 60 * 1000;\n// Every captured tree is pinned under refs/star/<timestamp>-<random> so a\n// `gc --auto` prune (default gc.pruneExpire of two weeks) can never drop a\n// live /undo target. The namespace is trimmed to the newest this many refs,\n// matching the per-file snapshot stack cap.\nconst MAX_PINNED_REFS = 50;\nconst PINNED_REF_PREFIX = \"refs/star/\";\n\n// Likely-secret files that must never enter the internal snapshot repos,\n// pinned into each repo's info/exclude so `git add -A` skips them even in\n// projects with no .gitignore and `git clean -fd` on restore leaves them\n// alone. Mirrors isSensitivePath (src/core/sensitive.ts), including the\n// template exemptions.\nconst SENSITIVE_EXCLUDE_PATTERNS = [\n \".env\",\n \".env.*\",\n \"!.env.example\",\n \"!.env.sample\",\n \"!.env.template\",\n \"id_rsa\",\n \"id_dsa\",\n \"id_ecdsa\",\n \"id_ed25519\",\n \".npmrc\",\n \".netrc\",\n \".pgpass\",\n \"*.pem\",\n \"*.key\",\n \"*.p12\",\n \"*.pfx\",\n \"**/.aws/credentials\",\n \"**/.kube/config\",\n];\n\n// Forced config for every invocation: no CRLF translation (a file captured\n// with LF endings must restore byte-identically even on a machine whose\n// global config sets core.autocrlf=true) and no LFS filters rewriting blob\n// contents. Command-line -c beats repo/global/system config, so repos\n// created before this fix are covered too.\nconst GIT_CONFIG_ARGS = [\n \"-c\",\n \"core.autocrlf=false\",\n \"-c\",\n \"core.eol=native\",\n \"-c\",\n \"filter.lfs.process=\",\n \"-c\",\n \"filter.lfs.smudge=\",\n \"-c\",\n \"filter.lfs.clean=\",\n];\n\n// The child gets the parent environment minus every GIT_* variable (matched\n// case-insensitively: Windows env keys are). A star launched from a git hook\n// or rebase inherits GIT_DIR/GIT_INDEX_FILE pointing at the user's repo, and\n// GIT_INDEX_FILE redirects index writes even past an explicit --git-dir.\nfunction gitEnv(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined && !key.toUpperCase().startsWith(\"GIT_\")) env[key] = value;\n }\n return env;\n}\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[], timeoutMs = GIT_TIMEOUT_MS): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(\n \"git\",\n [...GIT_CONFIG_ARGS, ...args],\n { timeout: timeoutMs, maxBuffer: GIT_MAX_BUFFER, encoding: \"utf8\", env: gitEnv() },\n (error, stdout) => {\n resolve(error ? null : stdout.trim());\n },\n );\n });\n}\n\nlet gitAvailable: boolean | null = null;\n\n// Expiry timestamps (Date.now) of the per-directory failure negative cache.\nconst trackFailureUntil = new Map<string, number>();\n// Successful captures per repo since process start, driving the periodic gc.\nconst trackCounts = new Map<string, number>();\n// Repos whose index was already scrubbed of excluded entries this process.\nconst scrubbedRepos = new Set<string>();\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// Test hook: drop every piece of cached state (availability probe, failure\n// negative cache, gc counters, scrub bookkeeping, capture chains).\nexport function resetGitTreeCaches(): void {\n gitAvailable = null;\n trackFailureUntil.clear();\n trackCounts.clear();\n scrubbedRepos.clear();\n trackChains.clear();\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// Removes a project's internal snapshot repo. Called when the project's last\n// session is cleared: the captured trees only make sense as /undo//redo\n// targets for session turns, and with no session left they are unreachable\n// disk usage. In-memory bookkeeping goes too, or a later session in the same\n// process would trust a failure cache / gc counter for a repo that no longer\n// exists.\nexport async function removeTreeRepo(cwd: string): Promise<void> {\n const dir = treeRepoDir(cwd);\n trackFailureUntil.delete(path.resolve(cwd));\n trackCounts.delete(dir);\n scrubbedRepos.delete(dir);\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n}\n\n// Deletes every tree repo whose owning project has no surviving session.\n// remainingCwds are the cwd values of the sessions still on disk; repos are\n// keyed by resolved path (see treeRepoDir), so a basename compare keeps\n// exactly those.\nexport async function pruneTreeReposExcept(remainingCwds: Iterable<string>): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(gitTreesDir());\n } catch {\n return;\n }\n const keep = new Set<string>();\n for (const cwd of remainingCwds) keep.add(path.basename(treeRepoDir(cwd)));\n await Promise.all(\n entries\n .filter((entry) => !keep.has(entry))\n .map((entry) =>\n rm(path.join(gitTreesDir(), entry), { recursive: true, force: true }).catch(() => {}),\n ),\n );\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 try {\n // Owner-only like the session directories: tree objects hold file\n // contents the user never committed anywhere else.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n if (!existsSync(path.join(dir, \"HEAD\"))) {\n const out = await runGit([\"init\", \"--bare\", dir]);\n if (out === null) return null;\n // Belt and braces for fresh repos; runGit's forced -c flags already\n // cover repos created before the repo-local setting existed.\n await runGit([`--git-dir=${dir}`, \"config\", \"core.autocrlf\", \"false\"]);\n }\n // Rewritten on every call: repos created before the exclusion existed\n // pick it up here without any migration step.\n await mkdir(path.join(dir, \"info\"), { recursive: true });\n await writeFile(\n path.join(dir, \"info\", \"exclude\"),\n `${SENSITIVE_EXCLUDE_PATTERNS.join(\"\\n\")}\\n`,\n \"utf8\",\n );\n } catch {\n return null;\n }\n return dir;\n}\n\nfunction repoArgs(dir: string, cwd: string): string[] {\n return [`--git-dir=${dir}`, `--work-tree=${cwd}`];\n}\n\n// Drops index entries that match the exclude rules. Ignore patterns only keep\n// untracked files out of `git add`; a path already in the index — tracked by\n// a pre-exclusion star, or put back by read-tree of an old tree — stays until\n// explicitly removed, so both trackTree and restoreTree scrub it.\nasync function untrackExcluded(dir: string, cwd: string): Promise<boolean> {\n const base = repoArgs(dir, cwd);\n const listed = await runGit([...base, \"ls-files\", \"-z\", \"-c\", \"-i\", \"--exclude-standard\"]);\n if (listed === null) return false;\n const files = listed.split(\"\\0\").filter(Boolean);\n if (files.length === 0) return true;\n const removed = await runGit([\n ...base,\n \"rm\",\n \"--cached\",\n \"--ignore-unmatch\",\n \"-q\",\n \"--\",\n ...files.map((file) => `:(literal)${file}`),\n ]);\n return removed !== null;\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) and excluded\n// likely-secret files never enter the tree, which is exactly what the restore\n// side relies on. A recent failure makes further attempts no-ops until\n// TRACK_FAILURE_TTL_MS has passed.\nexport function trackTree(cwd: string): Promise<string | null> {\n // Serialize captures per directory: the agent loop starts a turn's capture\n // concurrently and a quick second turn (or the /undo path) can arrive while\n // it still runs — two overlapping captures would race on the internal\n // repo's index.lock, and the loser's spurious failure would poison the\n // negative cache for five minutes. trackTreeUncached never rejects, so the\n // chain cannot wedge; each call still captures its own tree, in order.\n const key = path.resolve(cwd);\n const next = (trackChains.get(key) ?? Promise.resolve(null)).then(() => trackTreeGuarded(cwd));\n trackChains.set(key, next);\n return next;\n}\n\n// Per-cwd promise chains serializing trackTree (see above). Values stay\n// settled promises between captures; the map is keyed by directory, so it\n// stays tiny.\nconst trackChains = new Map<string, Promise<string | null>>();\n\nasync function trackTreeGuarded(cwd: string): Promise<string | null> {\n if (isGuardedDir(cwd)) return null;\n const key = path.resolve(cwd);\n const failedUntil = trackFailureUntil.get(key);\n if (failedUntil !== undefined && Date.now() < failedUntil) return null;\n const tree = await trackTreeUncached(cwd);\n if (tree === null) {\n trackFailureUntil.set(key, Date.now() + TRACK_FAILURE_TTL_MS);\n return null;\n }\n trackFailureUntil.delete(key);\n return tree;\n}\n\n// Pins a captured tree under refs/star/<timestamp>-<random> so gc --auto\n// never prunes a live /undo target, then trims the namespace to the newest\n// MAX_PINNED_REFS refs: for-each-ref sorts by refname, and equal-length\n// millisecond timestamps make that order chronological. Pure housekeeping —\n// a failure here never fails the capture.\nasync function pinTree(base: string[], tree: string): Promise<void> {\n const ref = `${PINNED_REF_PREFIX}${Date.now()}-${randomBytes(4).toString(\"hex\")}`;\n if ((await runGit([...base, \"update-ref\", ref, tree])) === null) return;\n const listed = await runGit([...base, \"for-each-ref\", \"--format=%(refname)\", PINNED_REF_PREFIX]);\n if (listed === null) return;\n const refs = listed.split(\"\\n\").filter(Boolean);\n const stale = refs.slice(0, Math.max(0, refs.length - MAX_PINNED_REFS));\n await Promise.all(stale.map((name) => runGit([...base, \"update-ref\", \"-d\", name])));\n}\n\nasync function trackTreeUncached(cwd: string): Promise<string | 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 (!scrubbedRepos.has(dir)) {\n if (!(await untrackExcluded(dir, cwd))) return null;\n scrubbedRepos.add(dir);\n }\n if ((await runGit([...base, \"add\", \"-A\"])) === null) return null;\n const tree = await runGit([...base, \"write-tree\"]);\n if (tree === null) return null;\n await pinTree(base, tree);\n const count = (trackCounts.get(dir) ?? 0) + 1;\n trackCounts.set(dir, count);\n if (count % GC_INTERVAL === 0) {\n // Pure housekeeping: the result is ignored so a gc failure never fails\n // the turn, matching the module's silent-degradation style.\n await runGit([`--git-dir=${dir}`, \"gc\", \"--auto\"], GC_TIMEOUT_MS);\n }\n return tree;\n}\n\n// Restores the working tree to a captured tree: index reset to the tree,\n// every index file checked out over the work tree, then untracked\n// (post-snapshot) files cleaned. `clean` keeps ignored files, so dependencies\n// and excluded secrets survive. checkout-index -a only writes paths present\n// in the index, so scrubbing excluded entries after read-tree guarantees a\n// tree captured before the exclusion existed still cannot overwrite the\n// user's current .env (or delete it via clean, which also skips it).\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 = await ensureTreeRepo(cwd);\n if (!dir) return false;\n const base = repoArgs(dir, cwd);\n if ((await runGit([...base, \"read-tree\", hash])) === null) return false;\n if (!(await untrackExcluded(dir, cwd))) 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 // Restore never touches excluded likely-secret paths (trees captured\n // before the exclusion may still list them); keep the preview honest.\n if (line !== \"\" && !isSensitivePath(line)) names.add(line);\n }\n return [...names];\n}\n"],"mappings":";;;;;;;AAmBO,SAAS,cAAc,SAAiD;AAC7E,SAAO,UAAU,UAAU,EAAE,QAAQ,IAAI;AAC3C;AAEO,SAAS,eAAe,UAAiD;AAC9E,SAAO,SAAS,IAAI,CAAC,SAAS,KAAK,OAAO;AAC5C;AAIO,SAAS,uBAAuB,MAA4B;AACjE,SAAO,KAAK,QAAQ,SAAS,UAAU,KAAK,MAAM,cAAc;AAClE;AAMO,SAAS,gBAAgB,SAA0C;AACxE,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,QAAQ;AACxB,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,WAAO,QACJ,OAAO,CAAC,SAAS,KAAK,SAAS,MAAM,EACrC,IAAI,CAAC,SAAU,UAAU,OAAO,KAAK,OAAO,EAAG,EAC/C,KAAK,GAAG;AAAA,EACb;AACA,SAAO;AACT;AA8BO,IAAM,2BAA2B;AACjC,IAAM,+BAA+B;AACrC,IAAM,8BACX;AA4CK,SAAS,sBAAsB,UAAiD;AACrF,QAAM,SAAwB,CAAC;AAC/B,MAAI,UAAsD,CAAC;AAE3D,QAAM,eAAe,MAAM;AACzB,eAAW,QAAQ,SAAS;AAC1B,aAAO,KAAK;AAAA,QACV,SAAS;AAAA,UACP,MAAM;AAAA,UACN,SAAS;AAAA,YACP;AAAA,cACE,MAAM;AAAA,cACN,YAAY,KAAK;AAAA,cACjB,UAAU,KAAK;AAAA,cACf,QAAQ;AAAA,YACV;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AACA,cAAU,CAAC;AAAA,EACb;A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