@bastani/atomic 0.9.79 → 0.9.80

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  7. package/dist/builtin/workflows/package.json +1 -1
  8. package/dist/builtin/workflows/src/extension/index.bundle.mjs +2 -11
  9. package/dist/core/package-manager-storage-adapters.d.ts +11 -3
  10. package/dist/core/package-manager-storage-adapters.d.ts.map +1 -1
  11. package/dist/core/package-manager-storage-adapters.js +45 -4
  12. package/dist/core/package-manager-storage-adapters.js.map +1 -1
  13. package/dist/core/resource-loader-core.d.ts.map +1 -1
  14. package/dist/core/resource-loader-core.js +2 -0
  15. package/dist/core/resource-loader-core.js.map +1 -1
  16. package/dist/core/storage/host-adapters.d.ts +12 -0
  17. package/dist/core/storage/host-adapters.d.ts.map +1 -0
  18. package/dist/core/storage/host-adapters.js +51 -0
  19. package/dist/core/storage/host-adapters.js.map +1 -0
  20. package/dist/core/storage/session/released-history-files.d.ts.map +1 -1
  21. package/dist/core/storage/session/released-history-files.js +5 -0
  22. package/dist/core/storage/session/released-history-files.js.map +1 -1
  23. package/dist/main.d.ts.map +1 -1
  24. package/dist/main.js +3 -0
  25. package/dist/main.js.map +1 -1
  26. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  27. package/dist/modes/interactive-engine/remote-renderer.js +5 -4
  28. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  29. package/dist/utils/child-process.d.ts.map +1 -1
  30. package/dist/utils/child-process.js +10 -1
  31. package/dist/utils/child-process.js.map +1 -1
  32. package/docs/packages/authoring.md +1 -1
  33. package/docs/sdk.md +2 -0
  34. package/docs/settings.md +1 -1
  35. package/docs/storage.md +14 -2
  36. package/docs/workflows/operations.md +1 -1
  37. package/npm-shrinkwrap.json +32 -32
  38. package/package.json +3 -3
@@ -121,10 +121,15 @@ async function processStartTime(pid) {
121
121
  return null;
122
122
  return output.stdout.replace(/[^A-Za-z0-9]+/g, "");
123
123
  }
124
+ /** Neutral working directory so background OS probes never hold a handle on the caller's cwd (#4655). */
125
+ function probeWorkingDirectory() {
126
+ return process.platform === "win32" ? process.env.SystemRoot || process.env.windir || "C:\\Windows" : "/";
127
+ }
124
128
  /** Runs a short command; `ran` is false when it could not be started or did not finish in time. */
125
129
  function run(command, args, env) {
126
130
  return new Promise((resolve) => {
127
131
  execFile(command, args, {
132
+ cwd: probeWorkingDirectory(),
128
133
  encoding: "utf8",
129
134
  timeout: START_TIME_TIMEOUT_MS,
130
135
  windowsHide: true,
@@ -1 +1 @@
1
- {"version":3,"file":"released-history-files.js","sourceRoot":"","sources":["../../../../src/core/storage/session/released-history-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACnF,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC/F,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EACN,qBAAqB,EACrB,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IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;YAC1D,IAAI,CAAC;gBACJ,4GAA4G;gBAC5G,MAAM,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAC,CAAC;YACrE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,OAAO,IAAI,iBAAiB,CAC3B,mBAAmB,EACnB,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,EAC/C,EAAE,KAAK,EAAE,CACT,CAAC;YACH,CAAC;YACD,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC1B,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,MAAM,CAAC,WAAW;YACjB,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QAClC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { constants, readFileSync, readlinkSync, rmdirSync, rmSync } from \"node:fs\";\nimport { copyFile, mkdir, open, readdir, readFile, rename, rm, rmdir } from \"node:fs/promises\";\nimport { hostname, release } from \"node:os\";\nimport { join } from \"node:path\";\nimport { BroadcastChannel, isMainThread, receiveMessageOnPort } from \"node:worker_threads\";\nimport { getErrnoCode } from \"../../tools/errno.ts\";\nimport {\n\tSESSION_TEMP_DIR_MODE,\n\tSESSION_TEMP_FILE_MODE,\n\tsanitizeTempPathComponent,\n} from \"../../tools/session-temp-dir.ts\";\nimport { powershellCandidates } from \"../../tools/windows-directory-security.ts\";\nimport { SessionSpillError } from \"../errors.js\";\nimport type { SessionHistoryDirectory, SessionHistoryFiles } from \"./memory-session-store.js\";\n\n/** The start time recorded for a process whose start time could not be told. */\nconst UNKNOWN_START = \"unknown\";\n/** A process directory's pid/start owner and optional instance nonce; old nonce-free names remain sweepable. */\nconst PROCESS_DIRECTORY_NAME = /^([1-9][0-9]*)-([A-Za-z0-9]+)(?:-[a-f0-9]{32})?$/;\n/** Generated once for this owner, not per store: even identical pid/start pairs must never share exit cleanup. */\nconst PROCESS_NONCE = randomBytes(16).toString(\"hex\");\n/** How long a lookup of a process's start time may take before it counts as one that cannot tell. */\nconst START_TIME_TIMEOUT_MS = 30_000;\n\n/** Where released sessions' history is kept under an agent directory: a directory per host, then one per process. */\nexport function releasedHistoryDirectory(agentDir: string): string {\n\treturn join(agentDir, \"released-history\");\n}\n\nlet identity: Promise<string | undefined> | undefined;\n\n/** A boot and PID namespace in which a pid/start-time pair identifies the same owner for every reader. */\nfunction namespaceIdentity(): Promise<string | undefined> {\n\tidentity ??= (async () => {\n\t\tif (process.platform === \"linux\") {\n\t\t\ttry {\n\t\t\t\tconst ownNamespace = readlinkSync(\"/proc/self/ns/pid\");\n\t\t\t\t// NSpid lists IDs from the proc mount's namespace down to ours. More than one means a foreign view,\n\t\t\t\t// even if the numeric IDs happen to coincide. Missing/unreadable status is not proof of a matching view.\n\t\t\t\tconst status = readFileSync(\"/proc/self/status\", \"utf8\");\n\t\t\t\tconst procPid = /^NSpid:[ \\t]+([0-9]+)[ \\t]*$/m.exec(status);\n\t\t\t\tif (procPid?.[1] !== String(process.pid)) return undefined;\n\t\t\t\tconst namespace = /^pid:\\[([0-9]+)\\]$/.exec(ownNamespace);\n\t\t\t\tconst boot = readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim();\n\t\t\t\tif (namespace === null || boot.length === 0) return undefined;\n\t\t\t\treturn `linux-${namespace[1]}-${boot}`;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tif (process.platform === \"darwin\") {\n\t\t\tconst boot = await run(\"sysctl\", [\"-n\", \"kern.boottime\"]);\n\t\t\tconst seconds = /sec = ([0-9]+), usec = ([0-9]+)/.exec(boot.stdout);\n\t\t\treturn boot.ran && boot.exitCode === 0 && seconds !== null\n\t\t\t\t? `darwin-${release()}-${seconds[1]}-${seconds[2]}`\n\t\t\t\t: undefined;\n\t\t}\n\t\tif (process.platform === \"win32\") {\n\t\t\tfor (const executable of powershellCandidates()) {\n\t\t\t\tconst boot = await run(executable, [\n\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\"-Command\",\n\t\t\t\t\t\"(Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime.ToFileTimeUtc()\",\n\t\t\t\t]);\n\t\t\t\tif (boot.ran)\n\t\t\t\t\treturn boot.exitCode === 0 && /^[0-9]+$/.test(boot.stdout)\n\t\t\t\t\t\t? `win32-${release()}-${boot.stdout}`\n\t\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t})();\n\treturn identity;\n}\n\nasync function hostDirectory(agentDir: string): Promise<string> {\n\t// An unknown identity is never swept; the process-directory nonce still isolates owners with identical PIDs.\n\tconst key = (await namespaceIdentity()) ?? `${process.platform}-unknown-${process.pid}-${await ownStartTime()}`;\n\tconst host = hostname();\n\t// Hash the complete identity: truncating a long hostname must not drop the namespace or boot from the key.\n\tconst digest = createHash(\"sha256\")\n\t\t.update(JSON.stringify([host, key]))\n\t\t.digest(\"hex\");\n\treturn join(releasedHistoryDirectory(agentDir), `${sanitizeTempPathComponent(host, \"host\")}-${digest}`);\n}\n\n/**\n * When process `pid` started, as a token only ever compared with another reading of it: undefined when no process has\n * that pid, null when this platform, or that process, cannot tell.\n */\nasync function processStartTime(pid: number): Promise<string | null | undefined> {\n\tif (process.platform === \"linux\") {\n\t\tif ((await namespaceIdentity()) === undefined) return null;\n\t\ttry {\n\t\t\t// Clock ticks from boot to the process's start. `/proc` is answered by the kernel, never from a disk.\n\t\t\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\t\t\tconst start = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n\t\t\treturn start !== undefined && /^[0-9]+$/.test(start) ? start : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (process.platform === \"win32\") {\n\t\tfor (const executable of powershellCandidates()) {\n\t\t\tconst output = await run(executable, [\n\t\t\t\t\"-NoProfile\",\n\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\"-Command\",\n\t\t\t\t`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`,\n\t\t\t]);\n\t\t\tif (output.ran) return output.exitCode === 0 && /^[0-9]+$/.test(output.stdout) ? output.stdout : null;\n\t\t}\n\t\treturn null;\n\t}\n\tconst output = await run(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)], { LC_ALL: \"C\", TZ: \"UTC\" });\n\tif (!output.ran) return null;\n\t// An unsuccessful or malformed lookup cannot establish that an owner has been replaced.\n\tif (output.exitCode === 1 && output.stdout.length === 0) return undefined;\n\tif (\n\t\toutput.exitCode !== 0 ||\n\t\t!/^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[ \\t]+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ \\t]+[0-9]{1,2}[ \\t]+[0-9]{2}:[0-9]{2}:[0-9]{2}[ \\t]+[0-9]{4}$/.test(\n\t\t\toutput.stdout,\n\t\t)\n\t)\n\t\treturn null;\n\treturn output.stdout.replace(/[^A-Za-z0-9]+/g, \"\");\n}\n\n/** Runs a short command; `ran` is false when it could not be started or did not finish in time. */\nfunction run(\n\tcommand: string,\n\targs: readonly string[],\n\tenv?: NodeJS.ProcessEnv,\n): Promise<{ readonly ran: boolean; readonly exitCode: number; readonly stdout: string }> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\n\t\t\tcommand,\n\t\t\targs,\n\t\t\t{\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\ttimeout: START_TIME_TIMEOUT_MS,\n\t\t\t\twindowsHide: true,\n\t\t\t\t...(env === undefined ? {} : { env: { ...process.env, ...env } }),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tconst exitCode = (error as { readonly code?: unknown } | null)?.code;\n\t\t\t\tresolve({\n\t\t\t\t\tran: error === null || (typeof exitCode === \"number\" && error.killed !== true),\n\t\t\t\t\texitCode: typeof exitCode === \"number\" ? exitCode : 0,\n\t\t\t\t\tstdout: stdout.trim(),\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n}\n\nlet ownStart: Promise<string> | undefined;\n\n/** This process's start time, read once for the process; {@link UNKNOWN_START} when it cannot be told. */\nfunction ownStartTime(): Promise<string> {\n\townStart ??= processStartTime(process.pid).then((start) => start ?? UNKNOWN_START);\n\treturn ownStart;\n}\n\n/** Whether a process has `pid`; only ESRCH proves absence, and permission failures remain unknown. */\nfunction processExists(pid: number): boolean | undefined {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn getErrnoCode(error) === \"ESRCH\" ? false : undefined;\n\t}\n}\n\n/**\n * Whether the process that created the directory named for `pid` and `start` may still run: a process has that pid\n * and started at that time, or has that pid and one of the two start times cannot be told.\n */\nasync function ownerMayRun(pid: number, start: string): Promise<boolean> {\n\tconst exists = processExists(pid);\n\tif (exists === false) return false;\n\tif (exists === undefined) return true;\n\tconst current = pid === process.pid ? await ownStartTime() : await processStartTime(pid);\n\treturn current == null || current === UNKNOWN_START || start === UNKNOWN_START || current === start;\n}\n\n/**\n * Removes the directories that processes on this host left under `agentDir` when they ended without removing them,\n * such as one killed with SIGKILL: those whose pid no process has, or has with another start time. A directory whose\n * process may still run is kept, and so is anything this module does not create. Never rejects: what cannot be removed\n * now is left to the next sweep.\n */\nexport async function sweepReleasedHistory(agentDir: string): Promise<void> {\n\tif ((await namespaceIdentity()) === undefined) return;\n\tconst host = await hostDirectory(agentDir);\n\tlet names: string[];\n\ttry {\n\t\tnames = await readdir(host);\n\t} catch {\n\t\treturn;\n\t}\n\tawait Promise.all(\n\t\tnames.map(async (name) => {\n\t\t\tconst owner = PROCESS_DIRECTORY_NAME.exec(name);\n\t\t\tif (owner === null || (await ownerMayRun(Number(owner[1]), owner[2] as string))) return;\n\t\t\tawait rm(join(host, name), { recursive: true, force: true }).catch(() => undefined);\n\t\t}),\n\t);\n}\n\n/** Agent directories this process has swept, or is sweeping. */\nconst swept = new Set<string>();\n\n/** Sweeps `agentDir` in the background, once for this process; see {@link sweepReleasedHistory}. */\nexport function sweepReleasedHistoryOnce(agentDir: string): void {\n\tif (swept.has(agentDir)) return;\n\tswept.add(agentDir);\n\tvoid sweepReleasedHistory(agentDir);\n}\n\n/** Each agent directory's process directory, once this thread has created it. */\nconst processDirectories = new Map<string, Promise<string | SessionSpillError>>();\n/** Process directories this thread created a store's directory in. */\nconst usedProcessDirectories = new Set<string>();\n/** Store directories this thread created and has not removed. */\nconst openDirectories = new Set<string>();\n\n/** The process directory under `agentDir`, created once; one that could not be created is tried again next time. */\nfunction processDirectory(agentDir: string): Promise<string | SessionSpillError> {\n\tlet directory = processDirectories.get(agentDir);\n\tif (directory === undefined) {\n\t\tconst creating = createProcessDirectory(agentDir).then((created) => {\n\t\t\tif (created instanceof SessionSpillError) processDirectories.delete(agentDir);\n\t\t\treturn created;\n\t\t});\n\t\tprocessDirectories.set(agentDir, creating);\n\t\tdirectory = creating;\n\t}\n\treturn directory;\n}\n\nasync function createProcessDirectory(agentDir: string): Promise<string | SessionSpillError> {\n\tconst path = join(await hostDirectory(agentDir), `${process.pid}-${await ownStartTime()}-${PROCESS_NONCE}`);\n\ttry {\n\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t} catch (cause) {\n\t\treturn new SessionSpillError(\"spill-dir-refused\", { directory: path, errno: getErrnoCode(cause) }, { cause });\n\t}\n\tusedProcessDirectories.add(path);\n\tif (!isMainThread) registry.postMessage({ directory: path });\n\tremoveAtExit();\n\treturn path;\n}\n\nlet exitCleanupInstalled = false;\n\n/** Process-local, including workers whose main thread owns no store. Registration never delays a release. */\nconst registry = new BroadcastChannel(\"atomic-released-history-directories\");\nregistry.unref();\nif (isMainThread) {\n\tregistry.onmessage = ({ data }) => registerWorkerDirectory(data);\n\tremoveAtExit();\n\tregistry.postMessage({ announce: true });\n} else {\n\tregistry.onmessage = ({ data }) => {\n\t\tif (data.announce === true) for (const directory of usedProcessDirectories) registry.postMessage({ directory });\n\t};\n}\n\nfunction registerWorkerDirectory(data: { readonly directory?: string }): void {\n\tif (typeof data.directory !== \"string\") return;\n\tusedProcessDirectories.add(data.directory);\n\tregistry.postMessage({ registered: data.directory });\n}\n\nfunction removeAtExit(): void {\n\tif (exitCleanupInstalled) return;\n\texitCleanupInstalled = true;\n\tprocess.once(\"exit\", removeDirectories);\n}\n\n/**\n * Removes at once what this thread keeps on disk, as it exits. Main removes only the nonce-bearing directories\n * created by itself or registered workers; a worker thread removes its own stores' directories.\n */\nfunction removeDirectories(): void {\n\tif (isMainThread) {\n\t\t// A worker can report readiness on its parent port before this channel's event callback runs.\n\t\t// Node and Bun accept BroadcastChannel here; Bun's declaration still only lists MessagePort.\n\t\tconst port = registry as unknown as Parameters<typeof receiveMessageOnPort>[0];\n\t\tfor (let message = receiveMessageOnPort(port); message !== undefined; message = receiveMessageOnPort(port))\n\t\t\tregisterWorkerDirectory(message.message);\n\t}\n\tfor (const path of isMainThread ? usedProcessDirectories : openDirectories) {\n\t\ttry {\n\t\t\trmSync(path, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Nothing can report it while the thread ends; the next sweep removes what is left once the process is gone.\n\t\t}\n\t}\n\topenDirectories.clear();\n\tif (isMainThread) return;\n\tfor (const path of usedProcessDirectories) {\n\t\ttry {\n\t\t\trmdirSync(path);\n\t\t} catch {\n\t\t\t// Another thread's stores are still in it.\n\t\t}\n\t}\n}\n\n/** A store's directory is gone; once this thread has none, its process directory goes too, unless a thread uses it. */\nasync function closed(path: string): Promise<void> {\n\topenDirectories.delete(path);\n\tif (openDirectories.size > 0) return;\n\tfor (const directory of usedProcessDirectories) await rmdir(directory).catch(() => undefined);\n}\n\n/** Writes `data` at `position` of the file at `path`, creating the file when `position` is 0. */\nasync function writeAt(path: string, data: Uint8Array, position: number): Promise<void> {\n\tconst handle = await open(path, position === 0 ? \"w\" : \"r+\", SESSION_TEMP_FILE_MODE);\n\tlet failure: unknown;\n\ttry {\n\t\tfor (let written = 0; written < data.byteLength; ) {\n\t\t\tconst { bytesWritten } = await handle.write(data, written, data.byteLength - written, position + written);\n\t\t\twritten += bytesWritten;\n\t\t}\n\t} catch (error) {\n\t\tfailure = error;\n\t}\n\ttry {\n\t\tawait handle.close();\n\t} catch (closeFailure) {\n\t\tif (failure === undefined) throw closeFailure;\n\t\tif (failure instanceof Error) Object.defineProperty(failure, \"cleanupCause\", { value: closeFailure });\n\t}\n\tif (failure !== undefined) throw failure;\n}\n\n/**\n * Writes the file at `path` whole, a copy of `previous` followed by `data`, into a file of its own that is renamed to\n * `path` once complete: a write cut short, by a failure or by the process being killed, never leaves part of a file\n * under that name.\n */\nasync function writeWhole(\n\tpath: string,\n\tdata: Uint8Array,\n\tprevious: { readonly path: string; readonly bytes: number } | undefined,\n): Promise<void> {\n\tconst staging = `${path}.partial`;\n\ttry {\n\t\t// FICLONE requests reflinks where supported; Node falls back to a plain copy otherwise.\n\t\tif (previous !== undefined) await copyFile(previous.path, staging, constants.COPYFILE_FICLONE);\n\t\tawait writeAt(staging, data, previous?.bytes ?? 0);\n\t\tawait rename(staging, path);\n\t} catch (error) {\n\t\tawait rm(staging, { force: true }).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nfunction historyDirectory(path: string): SessionHistoryDirectory {\n\tconst fileAt = (file: number) => join(path, String(file));\n\treturn {\n\t\tpath,\n\t\tasync write(file, data, previous) {\n\t\t\tconst before = previous === undefined ? undefined : { path: fileAt(previous.file), bytes: previous.bytes };\n\t\t\ttry {\n\t\t\t\tawait writeWhole(fileAt(file), data, before);\n\t\t\t} catch (error) {\n\t\t\t\tif (getErrnoCode(error) !== \"ENOENT\") throw error;\n\t\t\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\t\tawait writeWhole(fileAt(file), data, before);\n\t\t\t}\n\t\t},\n\t\tread: (file) => readFile(fileAt(file)),\n\t\tasync removeFile(file) {\n\t\t\tawait rm(fileAt(file), { force: true });\n\t\t},\n\t\tasync remove() {\n\t\t\tawait rm(path, { recursive: true, force: true });\n\t\t\tawait closed(path);\n\t\t},\n\t};\n}\n\n/**\n * Released sessions' history in `<agentDir>/released-history/<host-identity>/<pid>-<start>-<nonce>/`: host identity includes\n * hostname, platform, boot, and Linux PID namespace. Store directories/files are owner-only (0700/0600) on POSIX;\n * Windows inherits the agent directory's ACL. The last handle closing removes its store directory. Main-thread exit\n * removes registered worker directories too, even after terminate(); worker-only SDK imports cannot install main\n * cleanup. Normal worker exit removes its stores. A matching namespace/boot's next startup sweeps killed owners;\n * uncertain identities and owners are always kept.\n */\nexport function releasedHistoryFiles(agentDir: string): SessionHistoryFiles {\n\tsweepReleasedHistoryOnce(agentDir);\n\treturn {\n\t\tasync createDirectory() {\n\t\t\tconst parent = await processDirectory(agentDir);\n\t\t\tif (parent instanceof SessionSpillError) return parent;\n\t\t\tconst path = join(parent, randomBytes(6).toString(\"hex\"));\n\t\t\ttry {\n\t\t\t\t// Recursive: the process directory goes when this thread's last store closes, and comes back with the next.\n\t\t\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\t} catch (cause) {\n\t\t\t\treturn new SessionSpillError(\n\t\t\t\t\t\"spill-dir-refused\",\n\t\t\t\t\t{ directory: path, errno: getErrnoCode(cause) },\n\t\t\t\t\t{ cause },\n\t\t\t\t);\n\t\t\t}\n\t\t\topenDirectories.add(path);\n\t\t\treturn historyDirectory(path);\n\t\t},\n\t\treport(degradation) {\n\t\t\tprocess.emitWarning(degradation);\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"released-history-files.js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,CAC3B,mBAAmB,EACnB,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,EAC/C,EAAE,KAAK,EAAE,CACT,CAAC;YACH,CAAC;YACD,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC1B,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,MAAM,CAAC,WAAW;YACjB,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QAClC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { constants, readFileSync, readlinkSync, rmdirSync, rmSync } from \"node:fs\";\nimport { copyFile, mkdir, open, readdir, readFile, rename, rm, rmdir } from \"node:fs/promises\";\nimport { hostname, release } from \"node:os\";\nimport { join } from \"node:path\";\nimport { BroadcastChannel, isMainThread, receiveMessageOnPort } from \"node:worker_threads\";\nimport { getErrnoCode } from \"../../tools/errno.ts\";\nimport {\n\tSESSION_TEMP_DIR_MODE,\n\tSESSION_TEMP_FILE_MODE,\n\tsanitizeTempPathComponent,\n} from \"../../tools/session-temp-dir.ts\";\nimport { powershellCandidates } from \"../../tools/windows-directory-security.ts\";\nimport { SessionSpillError } from \"../errors.js\";\nimport type { SessionHistoryDirectory, SessionHistoryFiles } from \"./memory-session-store.js\";\n\n/** The start time recorded for a process whose start time could not be told. */\nconst UNKNOWN_START = \"unknown\";\n/** A process directory's pid/start owner and optional instance nonce; old nonce-free names remain sweepable. */\nconst PROCESS_DIRECTORY_NAME = /^([1-9][0-9]*)-([A-Za-z0-9]+)(?:-[a-f0-9]{32})?$/;\n/** Generated once for this owner, not per store: even identical pid/start pairs must never share exit cleanup. */\nconst PROCESS_NONCE = randomBytes(16).toString(\"hex\");\n/** How long a lookup of a process's start time may take before it counts as one that cannot tell. */\nconst START_TIME_TIMEOUT_MS = 30_000;\n\n/** Where released sessions' history is kept under an agent directory: a directory per host, then one per process. */\nexport function releasedHistoryDirectory(agentDir: string): string {\n\treturn join(agentDir, \"released-history\");\n}\n\nlet identity: Promise<string | undefined> | undefined;\n\n/** A boot and PID namespace in which a pid/start-time pair identifies the same owner for every reader. */\nfunction namespaceIdentity(): Promise<string | undefined> {\n\tidentity ??= (async () => {\n\t\tif (process.platform === \"linux\") {\n\t\t\ttry {\n\t\t\t\tconst ownNamespace = readlinkSync(\"/proc/self/ns/pid\");\n\t\t\t\t// NSpid lists IDs from the proc mount's namespace down to ours. More than one means a foreign view,\n\t\t\t\t// even if the numeric IDs happen to coincide. Missing/unreadable status is not proof of a matching view.\n\t\t\t\tconst status = readFileSync(\"/proc/self/status\", \"utf8\");\n\t\t\t\tconst procPid = /^NSpid:[ \\t]+([0-9]+)[ \\t]*$/m.exec(status);\n\t\t\t\tif (procPid?.[1] !== String(process.pid)) return undefined;\n\t\t\t\tconst namespace = /^pid:\\[([0-9]+)\\]$/.exec(ownNamespace);\n\t\t\t\tconst boot = readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim();\n\t\t\t\tif (namespace === null || boot.length === 0) return undefined;\n\t\t\t\treturn `linux-${namespace[1]}-${boot}`;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tif (process.platform === \"darwin\") {\n\t\t\tconst boot = await run(\"sysctl\", [\"-n\", \"kern.boottime\"]);\n\t\t\tconst seconds = /sec = ([0-9]+), usec = ([0-9]+)/.exec(boot.stdout);\n\t\t\treturn boot.ran && boot.exitCode === 0 && seconds !== null\n\t\t\t\t? `darwin-${release()}-${seconds[1]}-${seconds[2]}`\n\t\t\t\t: undefined;\n\t\t}\n\t\tif (process.platform === \"win32\") {\n\t\t\tfor (const executable of powershellCandidates()) {\n\t\t\t\tconst boot = await run(executable, [\n\t\t\t\t\t\"-NoProfile\",\n\t\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\t\"-Command\",\n\t\t\t\t\t\"(Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime.ToFileTimeUtc()\",\n\t\t\t\t]);\n\t\t\t\tif (boot.ran)\n\t\t\t\t\treturn boot.exitCode === 0 && /^[0-9]+$/.test(boot.stdout)\n\t\t\t\t\t\t? `win32-${release()}-${boot.stdout}`\n\t\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t})();\n\treturn identity;\n}\n\nasync function hostDirectory(agentDir: string): Promise<string> {\n\t// An unknown identity is never swept; the process-directory nonce still isolates owners with identical PIDs.\n\tconst key = (await namespaceIdentity()) ?? `${process.platform}-unknown-${process.pid}-${await ownStartTime()}`;\n\tconst host = hostname();\n\t// Hash the complete identity: truncating a long hostname must not drop the namespace or boot from the key.\n\tconst digest = createHash(\"sha256\")\n\t\t.update(JSON.stringify([host, key]))\n\t\t.digest(\"hex\");\n\treturn join(releasedHistoryDirectory(agentDir), `${sanitizeTempPathComponent(host, \"host\")}-${digest}`);\n}\n\n/**\n * When process `pid` started, as a token only ever compared with another reading of it: undefined when no process has\n * that pid, null when this platform, or that process, cannot tell.\n */\nasync function processStartTime(pid: number): Promise<string | null | undefined> {\n\tif (process.platform === \"linux\") {\n\t\tif ((await namespaceIdentity()) === undefined) return null;\n\t\ttry {\n\t\t\t// Clock ticks from boot to the process's start. `/proc` is answered by the kernel, never from a disk.\n\t\t\tconst stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n\t\t\tconst start = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n\t\t\treturn start !== undefined && /^[0-9]+$/.test(start) ? start : null;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (process.platform === \"win32\") {\n\t\tfor (const executable of powershellCandidates()) {\n\t\t\tconst output = await run(executable, [\n\t\t\t\t\"-NoProfile\",\n\t\t\t\t\"-NonInteractive\",\n\t\t\t\t\"-Command\",\n\t\t\t\t`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`,\n\t\t\t]);\n\t\t\tif (output.ran) return output.exitCode === 0 && /^[0-9]+$/.test(output.stdout) ? output.stdout : null;\n\t\t}\n\t\treturn null;\n\t}\n\tconst output = await run(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)], { LC_ALL: \"C\", TZ: \"UTC\" });\n\tif (!output.ran) return null;\n\t// An unsuccessful or malformed lookup cannot establish that an owner has been replaced.\n\tif (output.exitCode === 1 && output.stdout.length === 0) return undefined;\n\tif (\n\t\toutput.exitCode !== 0 ||\n\t\t!/^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[ \\t]+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ \\t]+[0-9]{1,2}[ \\t]+[0-9]{2}:[0-9]{2}:[0-9]{2}[ \\t]+[0-9]{4}$/.test(\n\t\t\toutput.stdout,\n\t\t)\n\t)\n\t\treturn null;\n\treturn output.stdout.replace(/[^A-Za-z0-9]+/g, \"\");\n}\n\n/** Neutral working directory so background OS probes never hold a handle on the caller's cwd (#4655). */\nfunction probeWorkingDirectory(): string {\n\treturn process.platform === \"win32\" ? process.env.SystemRoot || process.env.windir || \"C:\\\\Windows\" : \"/\";\n}\n\n/** Runs a short command; `ran` is false when it could not be started or did not finish in time. */\nfunction run(\n\tcommand: string,\n\targs: readonly string[],\n\tenv?: NodeJS.ProcessEnv,\n): Promise<{ readonly ran: boolean; readonly exitCode: number; readonly stdout: string }> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\n\t\t\tcommand,\n\t\t\targs,\n\t\t\t{\n\t\t\t\tcwd: probeWorkingDirectory(),\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\ttimeout: START_TIME_TIMEOUT_MS,\n\t\t\t\twindowsHide: true,\n\t\t\t\t...(env === undefined ? {} : { env: { ...process.env, ...env } }),\n\t\t\t},\n\t\t\t(error, stdout) => {\n\t\t\t\tconst exitCode = (error as { readonly code?: unknown } | null)?.code;\n\t\t\t\tresolve({\n\t\t\t\t\tran: error === null || (typeof exitCode === \"number\" && error.killed !== true),\n\t\t\t\t\texitCode: typeof exitCode === \"number\" ? exitCode : 0,\n\t\t\t\t\tstdout: stdout.trim(),\n\t\t\t\t});\n\t\t\t},\n\t\t);\n\t});\n}\n\nlet ownStart: Promise<string> | undefined;\n\n/** This process's start time, read once for the process; {@link UNKNOWN_START} when it cannot be told. */\nfunction ownStartTime(): Promise<string> {\n\townStart ??= processStartTime(process.pid).then((start) => start ?? UNKNOWN_START);\n\treturn ownStart;\n}\n\n/** Whether a process has `pid`; only ESRCH proves absence, and permission failures remain unknown. */\nfunction processExists(pid: number): boolean | undefined {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn getErrnoCode(error) === \"ESRCH\" ? false : undefined;\n\t}\n}\n\n/**\n * Whether the process that created the directory named for `pid` and `start` may still run: a process has that pid\n * and started at that time, or has that pid and one of the two start times cannot be told.\n */\nasync function ownerMayRun(pid: number, start: string): Promise<boolean> {\n\tconst exists = processExists(pid);\n\tif (exists === false) return false;\n\tif (exists === undefined) return true;\n\tconst current = pid === process.pid ? await ownStartTime() : await processStartTime(pid);\n\treturn current == null || current === UNKNOWN_START || start === UNKNOWN_START || current === start;\n}\n\n/**\n * Removes the directories that processes on this host left under `agentDir` when they ended without removing them,\n * such as one killed with SIGKILL: those whose pid no process has, or has with another start time. A directory whose\n * process may still run is kept, and so is anything this module does not create. Never rejects: what cannot be removed\n * now is left to the next sweep.\n */\nexport async function sweepReleasedHistory(agentDir: string): Promise<void> {\n\tif ((await namespaceIdentity()) === undefined) return;\n\tconst host = await hostDirectory(agentDir);\n\tlet names: string[];\n\ttry {\n\t\tnames = await readdir(host);\n\t} catch {\n\t\treturn;\n\t}\n\tawait Promise.all(\n\t\tnames.map(async (name) => {\n\t\t\tconst owner = PROCESS_DIRECTORY_NAME.exec(name);\n\t\t\tif (owner === null || (await ownerMayRun(Number(owner[1]), owner[2] as string))) return;\n\t\t\tawait rm(join(host, name), { recursive: true, force: true }).catch(() => undefined);\n\t\t}),\n\t);\n}\n\n/** Agent directories this process has swept, or is sweeping. */\nconst swept = new Set<string>();\n\n/** Sweeps `agentDir` in the background, once for this process; see {@link sweepReleasedHistory}. */\nexport function sweepReleasedHistoryOnce(agentDir: string): void {\n\tif (swept.has(agentDir)) return;\n\tswept.add(agentDir);\n\tvoid sweepReleasedHistory(agentDir);\n}\n\n/** Each agent directory's process directory, once this thread has created it. */\nconst processDirectories = new Map<string, Promise<string | SessionSpillError>>();\n/** Process directories this thread created a store's directory in. */\nconst usedProcessDirectories = new Set<string>();\n/** Store directories this thread created and has not removed. */\nconst openDirectories = new Set<string>();\n\n/** The process directory under `agentDir`, created once; one that could not be created is tried again next time. */\nfunction processDirectory(agentDir: string): Promise<string | SessionSpillError> {\n\tlet directory = processDirectories.get(agentDir);\n\tif (directory === undefined) {\n\t\tconst creating = createProcessDirectory(agentDir).then((created) => {\n\t\t\tif (created instanceof SessionSpillError) processDirectories.delete(agentDir);\n\t\t\treturn created;\n\t\t});\n\t\tprocessDirectories.set(agentDir, creating);\n\t\tdirectory = creating;\n\t}\n\treturn directory;\n}\n\nasync function createProcessDirectory(agentDir: string): Promise<string | SessionSpillError> {\n\tconst path = join(await hostDirectory(agentDir), `${process.pid}-${await ownStartTime()}-${PROCESS_NONCE}`);\n\ttry {\n\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t} catch (cause) {\n\t\treturn new SessionSpillError(\"spill-dir-refused\", { directory: path, errno: getErrnoCode(cause) }, { cause });\n\t}\n\tusedProcessDirectories.add(path);\n\tif (!isMainThread) registry.postMessage({ directory: path });\n\tremoveAtExit();\n\treturn path;\n}\n\nlet exitCleanupInstalled = false;\n\n/** Process-local, including workers whose main thread owns no store. Registration never delays a release. */\nconst registry = new BroadcastChannel(\"atomic-released-history-directories\");\nregistry.unref();\nif (isMainThread) {\n\tregistry.onmessage = ({ data }) => registerWorkerDirectory(data);\n\tremoveAtExit();\n\tregistry.postMessage({ announce: true });\n} else {\n\tregistry.onmessage = ({ data }) => {\n\t\tif (data.announce === true) for (const directory of usedProcessDirectories) registry.postMessage({ directory });\n\t};\n}\n\nfunction registerWorkerDirectory(data: { readonly directory?: string }): void {\n\tif (typeof data.directory !== \"string\") return;\n\tusedProcessDirectories.add(data.directory);\n\tregistry.postMessage({ registered: data.directory });\n}\n\nfunction removeAtExit(): void {\n\tif (exitCleanupInstalled) return;\n\texitCleanupInstalled = true;\n\tprocess.once(\"exit\", removeDirectories);\n}\n\n/**\n * Removes at once what this thread keeps on disk, as it exits. Main removes only the nonce-bearing directories\n * created by itself or registered workers; a worker thread removes its own stores' directories.\n */\nfunction removeDirectories(): void {\n\tif (isMainThread) {\n\t\t// A worker can report readiness on its parent port before this channel's event callback runs.\n\t\t// Node and Bun accept BroadcastChannel here; Bun's declaration still only lists MessagePort.\n\t\tconst port = registry as unknown as Parameters<typeof receiveMessageOnPort>[0];\n\t\tfor (let message = receiveMessageOnPort(port); message !== undefined; message = receiveMessageOnPort(port))\n\t\t\tregisterWorkerDirectory(message.message);\n\t}\n\tfor (const path of isMainThread ? usedProcessDirectories : openDirectories) {\n\t\ttry {\n\t\t\trmSync(path, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Nothing can report it while the thread ends; the next sweep removes what is left once the process is gone.\n\t\t}\n\t}\n\topenDirectories.clear();\n\tif (isMainThread) return;\n\tfor (const path of usedProcessDirectories) {\n\t\ttry {\n\t\t\trmdirSync(path);\n\t\t} catch {\n\t\t\t// Another thread's stores are still in it.\n\t\t}\n\t}\n}\n\n/** A store's directory is gone; once this thread has none, its process directory goes too, unless a thread uses it. */\nasync function closed(path: string): Promise<void> {\n\topenDirectories.delete(path);\n\tif (openDirectories.size > 0) return;\n\tfor (const directory of usedProcessDirectories) await rmdir(directory).catch(() => undefined);\n}\n\n/** Writes `data` at `position` of the file at `path`, creating the file when `position` is 0. */\nasync function writeAt(path: string, data: Uint8Array, position: number): Promise<void> {\n\tconst handle = await open(path, position === 0 ? \"w\" : \"r+\", SESSION_TEMP_FILE_MODE);\n\tlet failure: unknown;\n\ttry {\n\t\tfor (let written = 0; written < data.byteLength; ) {\n\t\t\tconst { bytesWritten } = await handle.write(data, written, data.byteLength - written, position + written);\n\t\t\twritten += bytesWritten;\n\t\t}\n\t} catch (error) {\n\t\tfailure = error;\n\t}\n\ttry {\n\t\tawait handle.close();\n\t} catch (closeFailure) {\n\t\tif (failure === undefined) throw closeFailure;\n\t\tif (failure instanceof Error) Object.defineProperty(failure, \"cleanupCause\", { value: closeFailure });\n\t}\n\tif (failure !== undefined) throw failure;\n}\n\n/**\n * Writes the file at `path` whole, a copy of `previous` followed by `data`, into a file of its own that is renamed to\n * `path` once complete: a write cut short, by a failure or by the process being killed, never leaves part of a file\n * under that name.\n */\nasync function writeWhole(\n\tpath: string,\n\tdata: Uint8Array,\n\tprevious: { readonly path: string; readonly bytes: number } | undefined,\n): Promise<void> {\n\tconst staging = `${path}.partial`;\n\ttry {\n\t\t// FICLONE requests reflinks where supported; Node falls back to a plain copy otherwise.\n\t\tif (previous !== undefined) await copyFile(previous.path, staging, constants.COPYFILE_FICLONE);\n\t\tawait writeAt(staging, data, previous?.bytes ?? 0);\n\t\tawait rename(staging, path);\n\t} catch (error) {\n\t\tawait rm(staging, { force: true }).catch(() => undefined);\n\t\tthrow error;\n\t}\n}\n\nfunction historyDirectory(path: string): SessionHistoryDirectory {\n\tconst fileAt = (file: number) => join(path, String(file));\n\treturn {\n\t\tpath,\n\t\tasync write(file, data, previous) {\n\t\t\tconst before = previous === undefined ? undefined : { path: fileAt(previous.file), bytes: previous.bytes };\n\t\t\ttry {\n\t\t\t\tawait writeWhole(fileAt(file), data, before);\n\t\t\t} catch (error) {\n\t\t\t\tif (getErrnoCode(error) !== \"ENOENT\") throw error;\n\t\t\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\t\tawait writeWhole(fileAt(file), data, before);\n\t\t\t}\n\t\t},\n\t\tread: (file) => readFile(fileAt(file)),\n\t\tasync removeFile(file) {\n\t\t\tawait rm(fileAt(file), { force: true });\n\t\t},\n\t\tasync remove() {\n\t\t\tawait rm(path, { recursive: true, force: true });\n\t\t\tawait closed(path);\n\t\t},\n\t};\n}\n\n/**\n * Released sessions' history in `<agentDir>/released-history/<host-identity>/<pid>-<start>-<nonce>/`: host identity includes\n * hostname, platform, boot, and Linux PID namespace. Store directories/files are owner-only (0700/0600) on POSIX;\n * Windows inherits the agent directory's ACL. The last handle closing removes its store directory. Main-thread exit\n * removes registered worker directories too, even after terminate(); worker-only SDK imports cannot install main\n * cleanup. Normal worker exit removes its stores. A matching namespace/boot's next startup sweeps killed owners;\n * uncertain identities and owners are always kept.\n */\nexport function releasedHistoryFiles(agentDir: string): SessionHistoryFiles {\n\tsweepReleasedHistoryOnce(agentDir);\n\treturn {\n\t\tasync createDirectory() {\n\t\t\tconst parent = await processDirectory(agentDir);\n\t\t\tif (parent instanceof SessionSpillError) return parent;\n\t\t\tconst path = join(parent, randomBytes(6).toString(\"hex\"));\n\t\t\ttry {\n\t\t\t\t// Recursive: the process directory goes when this thread's last store closes, and comes back with the next.\n\t\t\t\tawait mkdir(path, { recursive: true, mode: SESSION_TEMP_DIR_MODE });\n\t\t\t} catch (cause) {\n\t\t\t\treturn new SessionSpillError(\n\t\t\t\t\t\"spill-dir-refused\",\n\t\t\t\t\t{ directory: path, errno: getErrnoCode(cause) },\n\t\t\t\t\t{ cause },\n\t\t\t\t);\n\t\t\t}\n\t\t\topenDirectories.add(path);\n\t\t\treturn historyDirectory(path);\n\t\t},\n\t\treport(degradation) {\n\t\t\tprocess.emitWarning(degradation);\n\t\t},\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAiIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAiBnD,YAAY,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA6NnD,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBA00B/D"}
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAkIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAiBnD,YAAY,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AA6NnD,wBAAsB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,WAAW,iBA40B/D"}
package/dist/main.js CHANGED
@@ -21,6 +21,7 @@ import { INTERACTIVE_MODEL_REFRESH_TIMEOUT_MS } from "./core/model-refresh-timeo
21
21
  import { resolveModelScope, resolveModelScopeWithDiagnostics } from "./core/model-resolver.js";
22
22
  import { ModelRuntime } from "./core/model-runtime.js";
23
23
  import { flushRawStdout, restoreStdout, takeOverStdout, writeRawStdout } from "./core/output-guard.js";
24
+ import { registerHostStoragePackages } from "./core/package-manager-storage-adapters.js";
24
25
  import { formatBorrowedExtensionSourceTrustPrompt, resolveProjectTrusted } from "./core/project-trust.js";
25
26
  import { resumeFailureMessage } from "./core/resume/failure.js";
26
27
  import { findMissingSessionCwdIssue, MissingSessionCwdError } from "./core/session-cwd.js";
@@ -423,6 +424,8 @@ export async function main(argv, options) {
423
424
  startupStoredProjectTrust ??
424
425
  (!startupHasTrustInputs || startupDefaultProjectTrust === "always");
425
426
  const resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions), resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);
427
+ // Storage opens before the extensions load, and may select an adapter by the name of a package passed here.
428
+ registerHostStoragePackages(resolvedExtensionPaths, cwd);
426
429
  const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates), resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);
427
430
  const beginStartupInputCapture = (sessionCwd, sessionSelectionComplete = false, deprecationWarningCount = 0) => startEarlyInputCapture({
428
431
  enabled: computeStartupInputCaptureEnabled({