@diffra-ai/cli 0.1.3 → 0.2.0
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/CHANGELOG.md +22 -1
- package/dist/bundle/chunks/{anthropic-messages-5EMOURYI.js → anthropic-messages-T6QSBW2I.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-N67KWG2X.js → azure-openai-responses-QHACUEEL.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-CES65UJH.js → chunk-2CWIL3U7.js} +1 -1
- package/dist/bundle/chunks/{chunk-PISJX26Y.js → chunk-3OQXW6CV.js} +1 -1
- package/dist/bundle/chunks/{chunk-NEFH2K3C.js → chunk-ACRSTWI3.js} +1 -1
- package/dist/bundle/chunks/{chunk-QYYUGS66.js → chunk-EMYFX4WY.js} +1 -1
- package/dist/bundle/chunks/{chunk-RTPG7C5I.js → chunk-GU5QXRH2.js} +344 -315
- package/dist/bundle/chunks/{chunk-BF423NQ7.js → chunk-HGCDVLYI.js} +1 -1
- package/dist/bundle/chunks/{chunk-SI7T4LPD.js → chunk-J3RI6JJL.js} +2 -2
- package/dist/bundle/chunks/{chunk-VOKUVFV4.js → chunk-JZ2OAQAK.js} +1 -1
- package/dist/bundle/chunks/{chunk-HFTZ6OJJ.js → chunk-TXISM6X7.js} +4 -4
- package/dist/bundle/chunks/{chunk-3UNTEQ65.js → chunk-UVU7AFFV.js} +1 -1
- package/dist/bundle/chunks/chunk-YTFC5DOS.js +2 -0
- package/dist/bundle/chunks/{chunk-RLMZZV4Q.js → chunk-ZTDZEFOK.js} +1 -1
- package/dist/bundle/chunks/{cli-55VO5MAJ.js → cli-B74BATSM.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-HB5U67WC.js → cloudflare-workers-ai-system-one-IRTLSYMY.js} +1 -1
- package/dist/bundle/chunks/{execute-OEFRHFHI.js → execute-YR7Q5B3S.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-XRHE7R52.js → google-generative-ai-J4JVZXHV.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-75CQOPKC.js → google-vertex-A36RXRWN.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-LKIRB7ZR.js → llama-cpp-classify-WD5MJBC7.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-KLGIHK73.js → mistral-conversations-YIKS5LKW.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-7L5VV67U.js → openai-codex-responses-UBNJIYCO.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-RBF6UXDW.js → openai-completions-WBIL7MLK.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-W3PJQIOF.js → openai-decisions-6T6CQTOT.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-W5ZMLOTR.js → openai-responses-W2CLKVKJ.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-4FW6VFV4.js → openrouter-images-ZP4QC3RD.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-RT7FVQ4G.js → pi-messages-VHFVA66D.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-DSJ7OYVL.js → typesafe-system-one-GORHCFHB.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-M75O3ECA.js → virtual-modules-XMXHVMFN.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts +68 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +173 -9
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/background-commands.d.ts +71 -0
- package/dist/core/background-commands.d.ts.map +1 -0
- package/dist/core/background-commands.js +158 -0
- package/dist/core/background-commands.js.map +1 -0
- package/dist/core/decisions.d.ts +144 -0
- package/dist/core/decisions.d.ts.map +1 -0
- package/dist/core/decisions.js +74 -0
- package/dist/core/decisions.js.map +1 -0
- package/dist/core/explain-tool-call.d.ts +20 -0
- package/dist/core/explain-tool-call.d.ts.map +1 -0
- package/dist/core/explain-tool-call.js +39 -0
- package/dist/core/explain-tool-call.js.map +1 -0
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +11 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +15 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +29 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/tools/background-tasks.d.ts +35 -0
- package/dist/core/tools/background-tasks.d.ts.map +1 -0
- package/dist/core/tools/background-tasks.js +110 -0
- package/dist/core/tools/background-tasks.js.map +1 -0
- package/dist/core/tools/bash.d.ts +11 -3
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +67 -17
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +8 -0
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +22 -0
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +1 -0
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +1 -1
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/powershell.d.ts +1 -1
- package/dist/core/tools/powershell.d.ts.map +1 -1
- package/dist/core/tools/powershell.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +2 -1
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/tools/write.d.ts +1 -0
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts +6 -0
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +15 -8
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/turn-files.d.ts +99 -0
- package/dist/core/turn-files.d.ts.map +1 -0
- package/dist/core/turn-files.js +270 -0
- package/dist/core/turn-files.js.map +1 -0
- package/dist/extensions/agents/agent-tool.d.ts +0 -1
- package/dist/extensions/agents/agent-tool.d.ts.map +1 -1
- package/dist/extensions/agents/agent-tool.js +2 -1
- package/dist/extensions/agents/agent-tool.js.map +1 -1
- package/dist/extensions/agents/index.d.ts +4 -3
- package/dist/extensions/agents/index.d.ts.map +1 -1
- package/dist/extensions/agents/index.js +33 -32
- package/dist/extensions/agents/index.js.map +1 -1
- package/dist/extensions/approval/exit-plan-mode.d.ts +5 -1
- package/dist/extensions/approval/exit-plan-mode.d.ts.map +1 -1
- package/dist/extensions/approval/exit-plan-mode.js +131 -19
- package/dist/extensions/approval/exit-plan-mode.js.map +1 -1
- package/dist/extensions/approval/index.d.ts.map +1 -1
- package/dist/extensions/approval/index.js +46 -23
- package/dist/extensions/approval/index.js.map +1 -1
- package/dist/extensions/approval/policy.d.ts +5 -12
- package/dist/extensions/approval/policy.d.ts.map +1 -1
- package/dist/extensions/approval/policy.js +26 -4
- package/dist/extensions/approval/policy.js.map +1 -1
- package/dist/extensions/hooks/index.d.ts.map +1 -1
- package/dist/extensions/hooks/index.js +12 -1
- package/dist/extensions/hooks/index.js.map +1 -1
- package/dist/extensions/index.d.ts.map +1 -1
- package/dist/extensions/index.js +3 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/questions/index.d.ts +41 -0
- package/dist/extensions/questions/index.d.ts.map +1 -0
- package/dist/extensions/questions/index.js +132 -0
- package/dist/extensions/questions/index.js.map +1 -0
- package/dist/index.d.ts +11 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/docs/approval-modes.md +7 -3
- package/docs/cli.md +12 -1
- package/docs/codemode.md +1 -1
- package/docs/extensions.md +36 -1
- package/docs/json.md +19 -0
- package/docs/sdk.md +64 -0
- package/docs/session-format.md +2 -0
- package/docs/settings.md +1 -1
- package/docs/slash-commands.md +1 -1
- package/docs/subagents.md +2 -2
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-VWWMBH3G.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { dirname, join } from "node:path";
|
|
3
|
+
import { dirname, join, relative } from "node:path";
|
|
4
4
|
import lockfile from "proper-lockfile";
|
|
5
5
|
import { CONFIG_DIR_NAME } from "../config.js";
|
|
6
6
|
import { canonicalizePath, pathsEqual, resolvePath } from "../utils/paths.js";
|
|
@@ -155,21 +155,28 @@ function withTrustFileLock(path, fn) {
|
|
|
155
155
|
* trusted user resource and is ignored here, even when cwd is $HOME.
|
|
156
156
|
*/
|
|
157
157
|
export function hasTrustRequiringProjectResources(cwd) {
|
|
158
|
+
return findTrustRequiringProjectResources(cwd).length > 0;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The project-local resources that make cwd need project trust, as paths relative to cwd with forward
|
|
162
|
+
* slashes: the trust-requiring entries under cwd/.diffra, then the nearest .agents/skills in cwd or one of
|
|
163
|
+
* its ancestors (see `hasTrustRequiringProjectResources`). Hosts show them when they ask for trust.
|
|
164
|
+
*/
|
|
165
|
+
export function findTrustRequiringProjectResources(cwd) {
|
|
158
166
|
const homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));
|
|
159
167
|
const userAgentsSkillsDir = join(homeDir, ".agents", "skills");
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
return true;
|
|
164
|
-
}
|
|
168
|
+
const root = canonicalizePath(resolvePath(cwd));
|
|
169
|
+
const found = TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.filter((entry) => existsSync(join(root, CONFIG_DIR_NAME, entry))).map((entry) => `${CONFIG_DIR_NAME}/${entry}`);
|
|
170
|
+
let currentDir = root;
|
|
165
171
|
while (true) {
|
|
166
172
|
const agentsSkillsDir = join(currentDir, ".agents", "skills");
|
|
167
173
|
if (!pathsEqual(agentsSkillsDir, userAgentsSkillsDir) && existsSync(agentsSkillsDir)) {
|
|
168
|
-
|
|
174
|
+
found.push(relative(root, agentsSkillsDir).replaceAll("\\", "/"));
|
|
175
|
+
return found;
|
|
169
176
|
}
|
|
170
177
|
const parentDir = dirname(currentDir);
|
|
171
178
|
if (parentDir === currentDir) {
|
|
172
|
-
return
|
|
179
|
+
return found;
|
|
173
180
|
}
|
|
174
181
|
currentDir = parentDir;
|
|
175
182
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAuB5C,MAAM,wCAAwC,GAAG;IAChD,eAAe;IACf,UAAU;IACV,YAAY;IACZ,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW;IACX,kBAAkB;CACT,CAAC;AAEX,SAAS,YAAY,CAAC,GAAW;IAChC,OAAO,gBAAgB,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC;AAED,uGAAuG;AACvG,SA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I,SAAS,EAAE,CAAC;gBAC5C,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC/B,KAAK,MAAM,WAAW,IAAI,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;oBACxD,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC;gBAC1B,CAAC;gBACD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { canonicalizePath, pathsEqual, resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\n/** Trust file keys naming `path`. Usually one; several on Windows when saved with different casing. */\nfunction findTrustFileKeys(data: TrustFile, path: string): string[] {\n\treturn Object.keys(data).filter((key) => pathsEqual(key, path));\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tfor (const key of findTrustFileKeys(data, currentDir)) {\n\t\t\tconst value = data[key];\n\t\t\tif (value === true || value === false) {\n\t\t\t\treturn { path: key, decision: value };\n\t\t\t}\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.diffra, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\tconst homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));\n\tconst userAgentsSkillsDir = join(homeDir, \".agents\", \"skills\");\n\tlet currentDir = canonicalizePath(resolvePath(cwd));\n\n\tconst configDir = join(currentDir, CONFIG_DIR_NAME);\n\tif (TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some((entry) => existsSync(join(configDir, entry)))) {\n\t\treturn true;\n\t}\n\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (!pathsEqual(agentsSkillsDir, userAgentsSkillsDir) && existsSync(agentsSkillsDir)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tfor (const existingKey of findTrustFileKeys(data, key)) {\n\t\t\t\t\tdelete data[existingKey];\n\t\t\t\t}\n\t\t\t\tif (decision !== null) {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"trust-manager.js","sourceRoot":"","sources":["../../src/core/trust-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAuB5C,MAAM,wCAAwC,GAAG;IAChD,eAAe;IACf,UAAU;IACV,YAAY;IACZ,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,WAAW;IACX,kBAAkB;CACT,CAAC;AAEX,SAAS,YA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,EAAE,GAAG,CAAC,CAAC;QACzC,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,QAA8B;QAC9C,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;IACzC,CAAC;IAED,OAAO,CAAC,SAA+B;QACtC,iBAAiB,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,EAAE;YACtC,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAC3C,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,SAAS,EAAE,CAAC;gBAC5C,MAAM,GAAG,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;gBAC/B,KAAK,MAAM,WAAW,IAAI,iBAAiB,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;oBACxD,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC;gBAC1B,CAAC;gBACD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, relative } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { CONFIG_DIR_NAME } from \"../config.ts\";\nimport { canonicalizePath, pathsEqual, resolvePath } from \"../utils/paths.ts\";\nimport { stripBom } from \"../utils/text.ts\";\n\nexport type ProjectTrustDecision = boolean | null;\n\nexport interface ProjectTrustStoreEntry {\n\tpath: string;\n\tdecision: boolean;\n}\n\nexport interface ProjectTrustUpdate {\n\tpath: string;\n\tdecision: ProjectTrustDecision;\n}\n\nexport interface ProjectTrustOption {\n\tlabel: string;\n\ttrusted: boolean;\n\tupdates: ProjectTrustUpdate[];\n\tsavedPath?: string;\n}\n\ntype TrustFile = Record<string, boolean | null | undefined>;\n\nconst TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES = [\n\t\"settings.json\",\n\t\"mcp.json\",\n\t\"extensions\",\n\t\"skills\",\n\t\"prompts\",\n\t\"themes\",\n\t\"SYSTEM.md\",\n\t\"APPEND_SYSTEM.md\",\n] as const;\n\nfunction normalizeCwd(cwd: string): string {\n\treturn canonicalizePath(resolvePath(cwd));\n}\n\n/** Trust file keys naming `path`. Usually one; several on Windows when saved with different casing. */\nfunction findTrustFileKeys(data: TrustFile, path: string): string[] {\n\treturn Object.keys(data).filter((key) => pathsEqual(key, path));\n}\n\nfunction findNearestTrustEntry(data: TrustFile, cwd: string): ProjectTrustStoreEntry | null {\n\tlet currentDir = normalizeCwd(cwd);\n\twhile (true) {\n\t\tfor (const key of findTrustFileKeys(data, currentDir)) {\n\t\t\tconst value = data[key];\n\t\t\tif (value === true || value === false) {\n\t\t\t\treturn { path: key, decision: value };\n\t\t\t}\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn null;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport function getProjectTrustParentPath(cwd: string): string | undefined {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst parentDir = dirname(trustPath);\n\treturn parentDir === trustPath ? undefined : parentDir;\n}\n\nexport function getProjectTrustOptions(cwd: string, options?: { includeSessionOnly?: boolean }): ProjectTrustOption[] {\n\tconst trustPath = normalizeCwd(cwd);\n\tconst trustOptions: ProjectTrustOption[] = [\n\t\t{ label: \"Trust\", trusted: true, updates: [{ path: trustPath, decision: true }], savedPath: trustPath },\n\t];\n\tconst parentPath = getProjectTrustParentPath(cwd);\n\tif (parentPath !== undefined) {\n\t\ttrustOptions.push({\n\t\t\tlabel: `Trust parent folder (${parentPath})`,\n\t\t\ttrusted: true,\n\t\t\tupdates: [\n\t\t\t\t{ path: parentPath, decision: true },\n\t\t\t\t{ path: trustPath, decision: null },\n\t\t\t],\n\t\t\tsavedPath: parentPath,\n\t\t});\n\t}\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Trust (this session only)\", trusted: true, updates: [] });\n\t}\n\ttrustOptions.push({\n\t\tlabel: \"Do not trust\",\n\t\ttrusted: false,\n\t\tupdates: [{ path: trustPath, decision: false }],\n\t\tsavedPath: trustPath,\n\t});\n\tif (options?.includeSessionOnly) {\n\t\ttrustOptions.push({ label: \"Do not trust (this session only)\", trusted: false, updates: [] });\n\t}\n\treturn trustOptions;\n}\n\nfunction readTrustFile(path: string): TrustFile {\n\tif (!existsSync(path)) {\n\t\treturn {};\n\t}\n\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(stripBom(readFileSync(path, \"utf-8\")));\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(`Failed to read trust store ${path}: ${message}`);\n\t}\n\n\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n\t\tthrow new Error(`Invalid trust store ${path}: expected an object`);\n\t}\n\n\tconst data: TrustFile = {};\n\tfor (const [key, value] of Object.entries(parsed)) {\n\t\tif (value !== true && value !== false && value !== null) {\n\t\t\tthrow new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);\n\t\t}\n\t\tdata[key] = value;\n\t}\n\treturn data;\n}\n\nfunction writeTrustFile(path: string, data: TrustFile): void {\n\tconst sorted: TrustFile = {};\n\tfor (const key of Object.keys(data).sort()) {\n\t\tconst value = data[key];\n\t\tif (value === true || value === false || value === null) {\n\t\t\tsorted[key] = value;\n\t\t}\n\t}\n\tmkdirSync(dirname(path), { recursive: true });\n\twriteFileSync(path, `${JSON.stringify(sorted, null, 2)}\\n`, \"utf-8\");\n}\n\nfunction acquireTrustLockSync(path: string): () => void {\n\tconst trustDir = dirname(path);\n\tmkdirSync(trustDir, { recursive: true });\n\tconst maxAttempts = 10;\n\tconst delayMs = 20;\n\tlet lastError: unknown;\n\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt++) {\n\t\ttry {\n\t\t\treturn lockfile.lockSync(trustDir, { realpath: false, lockfilePath: `${path}.lock` });\n\t\t} catch (error) {\n\t\t\tconst code =\n\t\t\t\ttypeof error === \"object\" && error !== null && \"code\" in error\n\t\t\t\t\t? String((error as { code?: unknown }).code)\n\t\t\t\t\t: undefined;\n\t\t\tif (code !== \"ELOCKED\" || attempt === maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tlastError = error;\n\t\t\tconst start = Date.now();\n\t\t\twhile (Date.now() - start < delayMs) {\n\t\t\t\t// Sleep synchronously to avoid changing trust store callers to async.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (lastError instanceof Error) {\n\t\tthrow lastError;\n\t}\n\tthrow new Error(\"Failed to acquire trust store lock\");\n}\n\nfunction withTrustFileLock<T>(path: string, fn: () => T): T {\n\tconst release = acquireTrustLockSync(path);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\trelease();\n\t}\n}\n\n/**\n * Returns true when cwd has project-local resources that must be gated by\n * project trust: trust-requiring entries under cwd/.diffra, or .agents/skills in\n * cwd or one of its ancestors. Returns false when no such project resources\n * exist. The user/global ~/.agents/skills directory is always treated as a\n * trusted user resource and is ignored here, even when cwd is $HOME.\n */\nexport function hasTrustRequiringProjectResources(cwd: string): boolean {\n\treturn findTrustRequiringProjectResources(cwd).length > 0;\n}\n\n/**\n * The project-local resources that make cwd need project trust, as paths relative to cwd with forward\n * slashes: the trust-requiring entries under cwd/.diffra, then the nearest .agents/skills in cwd or one of\n * its ancestors (see `hasTrustRequiringProjectResources`). Hosts show them when they ask for trust.\n */\nexport function findTrustRequiringProjectResources(cwd: string): string[] {\n\tconst homeDir = canonicalizePath(resolvePath(process.env.HOME || homedir()));\n\tconst userAgentsSkillsDir = join(homeDir, \".agents\", \"skills\");\n\tconst root = canonicalizePath(resolvePath(cwd));\n\tconst found = TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.filter((entry) =>\n\t\texistsSync(join(root, CONFIG_DIR_NAME, entry)),\n\t).map((entry) => `${CONFIG_DIR_NAME}/${entry}`);\n\n\tlet currentDir = root;\n\twhile (true) {\n\t\tconst agentsSkillsDir = join(currentDir, \".agents\", \"skills\");\n\t\tif (!pathsEqual(agentsSkillsDir, userAgentsSkillsDir) && existsSync(agentsSkillsDir)) {\n\t\t\tfound.push(relative(root, agentsSkillsDir).replaceAll(\"\\\\\", \"/\"));\n\t\t\treturn found;\n\t\t}\n\n\t\tconst parentDir = dirname(currentDir);\n\t\tif (parentDir === currentDir) {\n\t\t\treturn found;\n\t\t}\n\t\tcurrentDir = parentDir;\n\t}\n}\n\nexport class ProjectTrustStore {\n\tprivate trustPath: string;\n\n\tconstructor(agentDir: string) {\n\t\tthis.trustPath = join(resolvePath(agentDir), \"trust.json\");\n\t}\n\n\tget(cwd: string): ProjectTrustDecision {\n\t\treturn this.getEntry(cwd)?.decision ?? null;\n\t}\n\n\tgetEntry(cwd: string): ProjectTrustStoreEntry | null {\n\t\treturn withTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\treturn findNearestTrustEntry(data, cwd);\n\t\t});\n\t}\n\n\tset(cwd: string, decision: ProjectTrustDecision): void {\n\t\tthis.setMany([{ path: cwd, decision }]);\n\t}\n\n\tsetMany(decisions: ProjectTrustUpdate[]): void {\n\t\twithTrustFileLock(this.trustPath, () => {\n\t\t\tconst data = readTrustFile(this.trustPath);\n\t\t\tfor (const { path, decision } of decisions) {\n\t\t\t\tconst key = normalizeCwd(path);\n\t\t\t\tfor (const existingKey of findTrustFileKeys(data, key)) {\n\t\t\t\t\tdelete data[existingKey];\n\t\t\t\t}\n\t\t\t\tif (decision !== null) {\n\t\t\t\t\tdata[key] = decision;\n\t\t\t\t}\n\t\t\t}\n\t\t\twriteTrustFile(this.trustPath, data);\n\t\t});\n\t}\n}\n"]}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-turn file snapshots. A turn is one agent run, from the message that starts it until the session
|
|
3
|
+
* settles. While it runs, the built-in edit and write tools report each file before their first write to
|
|
4
|
+
* it; when it ends, the files that differ from that state are recorded on the session branch, with
|
|
5
|
+
* content-addressed snapshots of their content before and after, so the turn can be undone. Shell commands
|
|
6
|
+
* are not tracked: a file only a command changed is not recorded, though the end state of a recorded file
|
|
7
|
+
* includes what commands did to it during the turn.
|
|
8
|
+
*/
|
|
9
|
+
import type { SessionEntry, SessionManager } from "./session-manager.ts";
|
|
10
|
+
/** A file one turn changed. */
|
|
11
|
+
export type TurnFileChange = {
|
|
12
|
+
/** Absolute path. */
|
|
13
|
+
path: string;
|
|
14
|
+
kind: "added" | "modified" | "deleted";
|
|
15
|
+
/** Lines added and removed; both 0 when either side is binary or too large to snapshot. */
|
|
16
|
+
additions: number;
|
|
17
|
+
deletions: number;
|
|
18
|
+
/** False when either side was too large to snapshot. */
|
|
19
|
+
undoable: boolean;
|
|
20
|
+
};
|
|
21
|
+
/** The files one turn changed. */
|
|
22
|
+
export type TurnFileChanges = {
|
|
23
|
+
/** Session entry id of the message that started the turn. */
|
|
24
|
+
turnId: string;
|
|
25
|
+
files: TurnFileChange[];
|
|
26
|
+
/** Whether the turn was undone on the current branch. */
|
|
27
|
+
undone: boolean;
|
|
28
|
+
};
|
|
29
|
+
/** Outcome of undoing a turn. A refusal changes no file; its `paths` are the files that caused it. */
|
|
30
|
+
export type UndoTurnResult = {
|
|
31
|
+
kind: "undone";
|
|
32
|
+
paths: string[];
|
|
33
|
+
} | {
|
|
34
|
+
kind: "refused";
|
|
35
|
+
reason: "running" | "not-found" | "already-undone" | "later-turn" | "changed-on-disk" | "not-undoable";
|
|
36
|
+
paths: string[];
|
|
37
|
+
};
|
|
38
|
+
/** Custom entry type of the record of the files a turn changed. */
|
|
39
|
+
export declare const TURN_FILES_ENTRY = "diffra.turn-files";
|
|
40
|
+
/** Custom entry type that marks a turn's file changes undone on the branch. */
|
|
41
|
+
export declare const TURN_FILES_UNDO_ENTRY = "diffra.turn-files-undo";
|
|
42
|
+
/** Larger files are recorded without a snapshot, so the turn that changed one cannot be undone. */
|
|
43
|
+
export declare const TURN_FILE_SNAPSHOT_MAX_BYTES: number;
|
|
44
|
+
/** A file's state in a record: missing, a snapshot named by the SHA-256 of its bytes, or too large to snapshot. */
|
|
45
|
+
type RecordedFileState = {
|
|
46
|
+
kind: "missing";
|
|
47
|
+
} | {
|
|
48
|
+
kind: "snapshot";
|
|
49
|
+
sha256: string;
|
|
50
|
+
} | {
|
|
51
|
+
kind: "too-large";
|
|
52
|
+
size: number;
|
|
53
|
+
};
|
|
54
|
+
/** A changed file in a record. */
|
|
55
|
+
type RecordedFileChange = {
|
|
56
|
+
path: string;
|
|
57
|
+
before: RecordedFileState;
|
|
58
|
+
after: RecordedFileState;
|
|
59
|
+
additions: number;
|
|
60
|
+
deletions: number;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Data of a `diffra.turn-files` entry. Snapshots are files in `snapshotDir`, an absolute path so that forks
|
|
64
|
+
* of the session find them, or are held in memory for in-memory sessions, which have no `snapshotDir`.
|
|
65
|
+
*/
|
|
66
|
+
export type TurnFilesData = {
|
|
67
|
+
turnId: string;
|
|
68
|
+
snapshotDir?: string;
|
|
69
|
+
files: RecordedFileChange[];
|
|
70
|
+
};
|
|
71
|
+
/** The files the built-in edit and write tools write during one turn, with their state before the first write. */
|
|
72
|
+
export declare class TurnFileRecorder {
|
|
73
|
+
private readonly _before;
|
|
74
|
+
/**
|
|
75
|
+
* Snapshot `path` before the turn first writes it. Tools call this in the file's mutation queue, so calls
|
|
76
|
+
* for one path do not overlap.
|
|
77
|
+
*/
|
|
78
|
+
beforeWrite(path: string): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Store snapshots of the files that differ from their state before the turn and return the turn's record,
|
|
81
|
+
* sorted by path, or undefined when no file differs.
|
|
82
|
+
*/
|
|
83
|
+
record(turnId: string, sessionManager: SessionManager): Promise<TurnFilesData | undefined>;
|
|
84
|
+
}
|
|
85
|
+
/** `operations` with each write first reported to the recorder of the running turn, when a turn runs. */
|
|
86
|
+
export declare function recordTurnFileWrites<T extends {
|
|
87
|
+
writeFile: (absolutePath: string, content: string) => Promise<void>;
|
|
88
|
+
}>(operations: T, getRecorder: () => TurnFileRecorder | undefined): T;
|
|
89
|
+
/** The files each turn on `branch` changed, oldest first. */
|
|
90
|
+
export declare function readTurnFileChanges(branch: readonly SessionEntry[]): TurnFileChanges[];
|
|
91
|
+
/**
|
|
92
|
+
* Restore the files the turn `turnId` on the branch changed to their state before it, deleting files it
|
|
93
|
+
* added. Refuses, changing nothing, when the turn is not on the branch or already undone, when one of its
|
|
94
|
+
* files cannot be undone, when a later turn that was not undone changed one of its files, or when a file on
|
|
95
|
+
* disk differs from the turn's end state. The caller records the undo on the branch.
|
|
96
|
+
*/
|
|
97
|
+
export declare function undoTurnFiles(turnId: string, sessionManager: SessionManager): Promise<UndoTurnResult>;
|
|
98
|
+
export {};
|
|
99
|
+
//# sourceMappingURL=turn-files.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turn-files.d.ts","sourceRoot":"","sources":["../../src/core/turn-files.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGzE,+BAA+B;AAC/B,MAAM,MAAM,cAAc,GAAG;IAC5B,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,OAAO,GAAG,UAAU,GAAG,SAAS,CAAC;IACvC,2FAA2F;IAC3F,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,wDAAwD;IACxD,QAAQ,EAAE,OAAO,CA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B,EAAE,CAAA;CAAE,CAAC;AAQlG,kHAAkH;AAClH,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgC;IAExD;;;OAGG;IACG,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG7C;IAED;;;OAGG;IACG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAa/F;CACD;AAED,yGAAyG;AACzG,wBAAgB,oBAAoB,CAAC,CAAC,SAAS;IAAE,SAAS,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,EACrH,UAAU,EAAE,CAAC,EACb,WAAW,EAAE,MAAM,gBAAgB,GAAG,SAAS,GAC7C,CAAC,CAQH;AAED,6DAA6D;AAC7D,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,GAAG,eAAe,EAAE,CAYtF;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAmB3G"}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-turn file snapshots. A turn is one agent run, from the message that starts it until the session
|
|
3
|
+
* settles. While it runs, the built-in edit and write tools report each file before their first write to
|
|
4
|
+
* it; when it ends, the files that differ from that state are recorded on the session branch, with
|
|
5
|
+
* content-addressed snapshots of their content before and after, so the turn can be undone. Shell commands
|
|
6
|
+
* are not tracked: a file only a command changed is not recorded, though the end state of a recorded file
|
|
7
|
+
* includes what commands did to it during the turn.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { countChangedLines } from "./tools/edit-diff.js";
|
|
13
|
+
/** Custom entry type of the record of the files a turn changed. */
|
|
14
|
+
export const TURN_FILES_ENTRY = "diffra.turn-files";
|
|
15
|
+
/** Custom entry type that marks a turn's file changes undone on the branch. */
|
|
16
|
+
export const TURN_FILES_UNDO_ENTRY = "diffra.turn-files-undo";
|
|
17
|
+
/** Larger files are recorded without a snapshot, so the turn that changed one cannot be undone. */
|
|
18
|
+
export const TURN_FILE_SNAPSHOT_MAX_BYTES = 1024 * 1024;
|
|
19
|
+
/** The files the built-in edit and write tools write during one turn, with their state before the first write. */
|
|
20
|
+
export class TurnFileRecorder {
|
|
21
|
+
_before = new Map();
|
|
22
|
+
/**
|
|
23
|
+
* Snapshot `path` before the turn first writes it. Tools call this in the file's mutation queue, so calls
|
|
24
|
+
* for one path do not overlap.
|
|
25
|
+
*/
|
|
26
|
+
async beforeWrite(path) {
|
|
27
|
+
if (this._before.has(path))
|
|
28
|
+
return;
|
|
29
|
+
this._before.set(path, await readFileState(path));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Store snapshots of the files that differ from their state before the turn and return the turn's record,
|
|
33
|
+
* sorted by path, or undefined when no file differs.
|
|
34
|
+
*/
|
|
35
|
+
async record(turnId, sessionManager) {
|
|
36
|
+
const snapshotDir = getSnapshotDir(sessionManager);
|
|
37
|
+
const store = (state) => storeFileState(state, snapshotDir, sessionManager);
|
|
38
|
+
const files = [];
|
|
39
|
+
// Parallel tool calls write in any order, so the order of first writes is not stable.
|
|
40
|
+
const written = [...this._before].sort(([left], [right]) => left.localeCompare(right));
|
|
41
|
+
for (const [path, before] of written) {
|
|
42
|
+
const after = await readFileState(path);
|
|
43
|
+
if (sameFileState(before, after))
|
|
44
|
+
continue;
|
|
45
|
+
files.push({ path, before: await store(before), after: await store(after), ...countFileLines(before, after) });
|
|
46
|
+
}
|
|
47
|
+
if (files.length === 0)
|
|
48
|
+
return undefined;
|
|
49
|
+
return snapshotDir === undefined ? { turnId, files } : { turnId, snapshotDir, files };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** `operations` with each write first reported to the recorder of the running turn, when a turn runs. */
|
|
53
|
+
export function recordTurnFileWrites(operations, getRecorder) {
|
|
54
|
+
return {
|
|
55
|
+
...operations,
|
|
56
|
+
writeFile: async (absolutePath, content) => {
|
|
57
|
+
await getRecorder()?.beforeWrite(absolutePath);
|
|
58
|
+
await operations.writeFile(absolutePath, content);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** The files each turn on `branch` changed, oldest first. */
|
|
63
|
+
export function readTurnFileChanges(branch) {
|
|
64
|
+
return readTurnRecords(branch).map(({ data, undone }) => ({
|
|
65
|
+
turnId: data.turnId,
|
|
66
|
+
files: data.files.map((file) => ({
|
|
67
|
+
path: file.path,
|
|
68
|
+
kind: file.before.kind === "missing" ? "added" : file.after.kind === "missing" ? "deleted" : "modified",
|
|
69
|
+
additions: file.additions,
|
|
70
|
+
deletions: file.deletions,
|
|
71
|
+
undoable: isUndoable(file),
|
|
72
|
+
})),
|
|
73
|
+
undone,
|
|
74
|
+
}));
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Restore the files the turn `turnId` on the branch changed to their state before it, deleting files it
|
|
78
|
+
* added. Refuses, changing nothing, when the turn is not on the branch or already undone, when one of its
|
|
79
|
+
* files cannot be undone, when a later turn that was not undone changed one of its files, or when a file on
|
|
80
|
+
* disk differs from the turn's end state. The caller records the undo on the branch.
|
|
81
|
+
*/
|
|
82
|
+
export async function undoTurnFiles(turnId, sessionManager) {
|
|
83
|
+
const records = readTurnRecords(sessionManager.getBranch());
|
|
84
|
+
const index = records.findIndex((record) => record.data.turnId === turnId);
|
|
85
|
+
if (index === -1)
|
|
86
|
+
return { kind: "refused", reason: "not-found", paths: [] };
|
|
87
|
+
const { data, undone } = records[index];
|
|
88
|
+
if (undone)
|
|
89
|
+
return { kind: "refused", reason: "already-undone", paths: [] };
|
|
90
|
+
const notUndoable = data.files.filter((file) => !isUndoable(file)).map((file) => file.path);
|
|
91
|
+
if (notUndoable.length > 0)
|
|
92
|
+
return { kind: "refused", reason: "not-undoable", paths: notUndoable };
|
|
93
|
+
const laterPaths = new Set(records.slice(index + 1).flatMap((record) => (record.undone ? [] : record.data.files.map((file) => file.path))));
|
|
94
|
+
const conflicts = data.files.filter((file) => laterPaths.has(file.path)).map((file) => file.path);
|
|
95
|
+
if (conflicts.length > 0)
|
|
96
|
+
return { kind: "refused", reason: "later-turn", paths: conflicts };
|
|
97
|
+
const changed = [];
|
|
98
|
+
for (const file of data.files) {
|
|
99
|
+
if (!matchesRecordedState(await readFileState(file.path), file.after))
|
|
100
|
+
changed.push(file.path);
|
|
101
|
+
}
|
|
102
|
+
if (changed.length > 0)
|
|
103
|
+
return { kind: "refused", reason: "changed-on-disk", paths: changed };
|
|
104
|
+
return await restoreFiles(data, sessionManager);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Write back the state of the record's files before the turn. Every snapshot loads before a file changes,
|
|
108
|
+
* so a lost snapshot refuses the undo instead of leaving it half done.
|
|
109
|
+
*/
|
|
110
|
+
async function restoreFiles(data, sessionManager) {
|
|
111
|
+
const restores = [];
|
|
112
|
+
const lost = [];
|
|
113
|
+
for (const { path, before } of data.files) {
|
|
114
|
+
if (before.kind !== "snapshot") {
|
|
115
|
+
restores.push({ kind: "delete", path });
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const bytes = await loadSnapshot(before.sha256, data.snapshotDir, sessionManager);
|
|
119
|
+
if (bytes)
|
|
120
|
+
restores.push({ kind: "write", path, bytes });
|
|
121
|
+
else
|
|
122
|
+
lost.push(path);
|
|
123
|
+
}
|
|
124
|
+
if (lost.length > 0)
|
|
125
|
+
return { kind: "refused", reason: "not-undoable", paths: lost };
|
|
126
|
+
for (const restore of restores) {
|
|
127
|
+
if (restore.kind === "delete") {
|
|
128
|
+
await rm(restore.path, { force: true });
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
await mkdir(dirname(restore.path), { recursive: true });
|
|
132
|
+
await writeFile(restore.path, restore.bytes);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { kind: "undone", paths: data.files.map((file) => file.path) };
|
|
136
|
+
}
|
|
137
|
+
/** The records on `branch`, oldest first, with whether each was undone on it. */
|
|
138
|
+
function readTurnRecords(branch) {
|
|
139
|
+
const records = [];
|
|
140
|
+
const undone = new Set();
|
|
141
|
+
for (const entry of branch) {
|
|
142
|
+
if (entry.type !== "custom")
|
|
143
|
+
continue;
|
|
144
|
+
if (entry.customType === TURN_FILES_ENTRY)
|
|
145
|
+
records.push(entry.data);
|
|
146
|
+
else if (entry.customType === TURN_FILES_UNDO_ENTRY)
|
|
147
|
+
undone.add(entry.data.turnId);
|
|
148
|
+
}
|
|
149
|
+
return records.map((data) => ({ data, undone: undone.has(data.turnId) }));
|
|
150
|
+
}
|
|
151
|
+
function isUndoable(file) {
|
|
152
|
+
return file.before.kind !== "too-large" && file.after.kind !== "too-large";
|
|
153
|
+
}
|
|
154
|
+
async function readFileState(path) {
|
|
155
|
+
let size;
|
|
156
|
+
try {
|
|
157
|
+
size = (await stat(path)).size;
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (isMissingPathError(error))
|
|
161
|
+
return { kind: "missing" };
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
if (size > TURN_FILE_SNAPSHOT_MAX_BYTES)
|
|
165
|
+
return { kind: "too-large", size };
|
|
166
|
+
return { kind: "content", bytes: await readFile(path) };
|
|
167
|
+
}
|
|
168
|
+
function isMissingPathError(error) {
|
|
169
|
+
const code = error.code;
|
|
170
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
171
|
+
}
|
|
172
|
+
/** Whether two states are known to be equal. Files too large to snapshot never are. */
|
|
173
|
+
function sameFileState(a, b) {
|
|
174
|
+
if (a.kind === "missing" || b.kind === "missing")
|
|
175
|
+
return a.kind === b.kind;
|
|
176
|
+
return a.kind === "content" && b.kind === "content" && a.bytes.equals(b.bytes);
|
|
177
|
+
}
|
|
178
|
+
function matchesRecordedState(state, recorded) {
|
|
179
|
+
switch (recorded.kind) {
|
|
180
|
+
case "missing":
|
|
181
|
+
return state.kind === "missing";
|
|
182
|
+
case "snapshot":
|
|
183
|
+
return state.kind === "content" && hashBytes(state.bytes) === recorded.sha256;
|
|
184
|
+
case "too-large":
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Lines added and removed between two states; both 0 when either side is binary or too large. */
|
|
189
|
+
function countFileLines(before, after) {
|
|
190
|
+
const oldText = textOf(before);
|
|
191
|
+
const newText = textOf(after);
|
|
192
|
+
if (oldText === undefined || newText === undefined)
|
|
193
|
+
return { additions: 0, deletions: 0 };
|
|
194
|
+
return countChangedLines(oldText, newText);
|
|
195
|
+
}
|
|
196
|
+
/** The text of a state: empty when missing, undefined when too large or binary (holding a NUL byte). */
|
|
197
|
+
function textOf(state) {
|
|
198
|
+
switch (state.kind) {
|
|
199
|
+
case "missing":
|
|
200
|
+
return "";
|
|
201
|
+
case "too-large":
|
|
202
|
+
return undefined;
|
|
203
|
+
case "content":
|
|
204
|
+
return state.bytes.includes(0) ? undefined : state.bytes.toString("utf-8");
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** The folder next to the session file that holds its snapshots, or undefined for an in-memory session. */
|
|
208
|
+
function getSnapshotDir(sessionManager) {
|
|
209
|
+
const sessionFile = sessionManager.isPersisted() ? sessionManager.getSessionFile() : undefined;
|
|
210
|
+
return sessionFile === undefined ? undefined : `${sessionFile.replace(/\.jsonl$/, "")}.snapshots`;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Snapshots of in-memory sessions, by the session manager that owns them. A fork of an in-memory session
|
|
214
|
+
* keeps its manager, so it finds the snapshots of the turns it copied.
|
|
215
|
+
*/
|
|
216
|
+
const memorySnapshots = new WeakMap();
|
|
217
|
+
/** Keep the content of `state` as a snapshot and return its recorded form. */
|
|
218
|
+
async function storeFileState(state, snapshotDir, sessionManager) {
|
|
219
|
+
if (state.kind !== "content")
|
|
220
|
+
return state;
|
|
221
|
+
const sha256 = hashBytes(state.bytes);
|
|
222
|
+
if (snapshotDir === undefined) {
|
|
223
|
+
let snapshots = memorySnapshots.get(sessionManager);
|
|
224
|
+
if (!snapshots) {
|
|
225
|
+
snapshots = new Map();
|
|
226
|
+
memorySnapshots.set(sessionManager, snapshots);
|
|
227
|
+
}
|
|
228
|
+
snapshots.set(sha256, state.bytes);
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
await writeSnapshotFile(join(snapshotDir, sha256), state.bytes);
|
|
232
|
+
}
|
|
233
|
+
return { kind: "snapshot", sha256 };
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Write a snapshot file unless it exists. Writing a temporary file and renaming it keeps a crash from
|
|
237
|
+
* leaving a partial snapshot under the hash.
|
|
238
|
+
*/
|
|
239
|
+
async function writeSnapshotFile(path, bytes) {
|
|
240
|
+
try {
|
|
241
|
+
await stat(path);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
if (!isMissingPathError(error))
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
await mkdir(dirname(path), { recursive: true });
|
|
249
|
+
const temporaryPath = `${path}.tmp`;
|
|
250
|
+
await writeFile(temporaryPath, bytes);
|
|
251
|
+
await rename(temporaryPath, path);
|
|
252
|
+
}
|
|
253
|
+
/** The bytes of a snapshot, or undefined when it is lost or a snapshot file no longer matches its hash. */
|
|
254
|
+
async function loadSnapshot(sha256, snapshotDir, sessionManager) {
|
|
255
|
+
if (snapshotDir === undefined)
|
|
256
|
+
return memorySnapshots.get(sessionManager)?.get(sha256);
|
|
257
|
+
try {
|
|
258
|
+
const bytes = await readFile(join(snapshotDir, sha256));
|
|
259
|
+
return hashBytes(bytes) === sha256 ? bytes : undefined;
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
if (isMissingPathError(error))
|
|
263
|
+
return undefined;
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
function hashBytes(bytes) {
|
|
268
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=turn-files.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turn-files.js","sourceRoot":"","sources":["../../src/core/turn-files.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAgCzD,mEAAmE;AACnE,MAAM,CAAC,MAAM,gBAAgB,GAAG,mBAAmB,CAAC;AAEpD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,qBAAqB,GAAG,wBAAwB,CAAC;AAE9D,mGAAmG;AACnG,MAAM,CAAC,MAAM,4BAA4B,GAAG,IAAI,GAAG,IAAI,CAAC;AA+BxD,kHAAkH;AAClH,MAAM,OAAO,gBAAgB;IACX,OAAO,GAAG,IAAI,GAAG,EAAqB,CAAC;IAExD;;;OAGG;IACH,KAAK,CAAC,WAAW,CAAC,IAAY;QAC7B,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,OAAO;QACnC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;OAGG;IACH,KAAK,CA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C;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;IAC7C,CAAC;IACD,MAAM,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,GAAG,IAAI,MAAM,CAAC;IACpC,MAAM,SAAS,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IACtC,MAAM,MAAM,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,2GAA2G;AAC3G,KAAK,UAAU,YAAY,CAC1B,MAAc,EACd,WAA+B,EAC/B,cAA8B;IAE9B,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,eAAe,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACvF,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC;QACxD,OAAO,SAAS,CAAC,KAAK,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACxD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,kBAAkB,CAAC,KAAK,CAAC;YAAE,OAAO,SAAS,CAAC;QAChD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC/B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACzD,CAAC","sourcesContent":["/**\n * Per-turn file snapshots. A turn is one agent run, from the message that starts it until the session\n * settles. While it runs, the built-in edit and write tools report each file before their first write to\n * it; when it ends, the files that differ from that state are recorded on the session branch, with\n * content-addressed snapshots of their content before and after, so the turn can be undone. Shell commands\n * are not tracked: a file only a command changed is not recorded, though the end state of a recorded file\n * includes what commands did to it during the turn.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { SessionEntry, SessionManager } from \"./session-manager.ts\";\nimport { countChangedLines } from \"./tools/edit-diff.ts\";\n\n/** A file one turn changed. */\nexport type TurnFileChange = {\n\t/** Absolute path. */\n\tpath: string;\n\tkind: \"added\" | \"modified\" | \"deleted\";\n\t/** Lines added and removed; both 0 when either side is binary or too large to snapshot. */\n\tadditions: number;\n\tdeletions: number;\n\t/** False when either side was too large to snapshot. */\n\tundoable: boolean;\n};\n\n/** The files one turn changed. */\nexport type TurnFileChanges = {\n\t/** Session entry id of the message that started the turn. */\n\tturnId: string;\n\tfiles: TurnFileChange[];\n\t/** Whether the turn was undone on the current branch. */\n\tundone: boolean;\n};\n\n/** Outcome of undoing a turn. A refusal changes no file; its `paths` are the files that caused it. */\nexport type UndoTurnResult =\n\t| { kind: \"undone\"; paths: string[] }\n\t| {\n\t\t\tkind: \"refused\";\n\t\t\treason: \"running\" | \"not-found\" | \"already-undone\" | \"later-turn\" | \"changed-on-disk\" | \"not-undoable\";\n\t\t\tpaths: string[];\n\t };\n\n/** Custom entry type of the record of the files a turn changed. */\nexport const TURN_FILES_ENTRY = \"diffra.turn-files\";\n\n/** Custom entry type that marks a turn's file changes undone on the branch. */\nexport const TURN_FILES_UNDO_ENTRY = \"diffra.turn-files-undo\";\n\n/** Larger files are recorded without a snapshot, so the turn that changed one cannot be undone. */\nexport const TURN_FILE_SNAPSHOT_MAX_BYTES = 1024 * 1024;\n\n// The recorded shapes are stored in session files: changing them needs a migration.\n\n/** A file's state in a record: missing, a snapshot named by the SHA-256 of its bytes, or too large to snapshot. */\ntype RecordedFileState =\n\t| { kind: \"missing\" }\n\t| { kind: \"snapshot\"; sha256: string }\n\t| { kind: \"too-large\"; size: number };\n\n/** A changed file in a record. */\ntype RecordedFileChange = {\n\tpath: string;\n\tbefore: RecordedFileState;\n\tafter: RecordedFileState;\n\tadditions: number;\n\tdeletions: number;\n};\n\n/**\n * Data of a `diffra.turn-files` entry. Snapshots are files in `snapshotDir`, an absolute path so that forks\n * of the session find them, or are held in memory for in-memory sessions, which have no `snapshotDir`.\n */\nexport type TurnFilesData = { turnId: string; snapshotDir?: string; files: RecordedFileChange[] };\n\n/** Data of a `diffra.turn-files-undo` entry. */\ntype TurnFilesUndoData = { turnId: string };\n\n/** A file's state on disk: missing, its bytes, or its size when it is too large to snapshot. */\ntype FileState = { kind: \"missing\" } | { kind: \"content\"; bytes: Buffer } | { kind: \"too-large\"; size: number };\n\n/** The files the built-in edit and write tools write during one turn, with their state before the first write. */\nexport class TurnFileRecorder {\n\tprivate readonly _before = new Map<string, FileState>();\n\n\t/**\n\t * Snapshot `path` before the turn first writes it. Tools call this in the file's mutation queue, so calls\n\t * for one path do not overlap.\n\t */\n\tasync beforeWrite(path: string): Promise<void> {\n\t\tif (this._before.has(path)) return;\n\t\tthis._before.set(path, await readFileState(path));\n\t}\n\n\t/**\n\t * Store snapshots of the files that differ from their state before the turn and return the turn's record,\n\t * sorted by path, or undefined when no file differs.\n\t */\n\tasync record(turnId: string, sessionManager: SessionManager): Promise<TurnFilesData | undefined> {\n\t\tconst snapshotDir = getSnapshotDir(sessionManager);\n\t\tconst store = (state: FileState) => storeFileState(state, snapshotDir, sessionManager);\n\t\tconst files: RecordedFileChange[] = [];\n\t\t// Parallel tool calls write in any order, so the order of first writes is not stable.\n\t\tconst written = [...this._before].sort(([left], [right]) => left.localeCompare(right));\n\t\tfor (const [path, before] of written) {\n\t\t\tconst after = await readFileState(path);\n\t\t\tif (sameFileState(before, after)) continue;\n\t\t\tfiles.push({ path, before: await store(before), after: await store(after), ...countFileLines(before, after) });\n\t\t}\n\t\tif (files.length === 0) return undefined;\n\t\treturn snapshotDir === undefined ? { turnId, files } : { turnId, snapshotDir, files };\n\t}\n}\n\n/** `operations` with each write first reported to the recorder of the running turn, when a turn runs. */\nexport function recordTurnFileWrites<T extends { writeFile: (absolutePath: string, content: string) => Promise<void> }>(\n\toperations: T,\n\tgetRecorder: () => TurnFileRecorder | undefined,\n): T {\n\treturn {\n\t\t...operations,\n\t\twriteFile: async (absolutePath: string, content: string) => {\n\t\t\tawait getRecorder()?.beforeWrite(absolutePath);\n\t\t\tawait operations.writeFile(absolutePath, content);\n\t\t},\n\t};\n}\n\n/** The files each turn on `branch` changed, oldest first. */\nexport function readTurnFileChanges(branch: readonly SessionEntry[]): TurnFileChanges[] {\n\treturn readTurnRecords(branch).map(({ data, undone }) => ({\n\t\tturnId: data.turnId,\n\t\tfiles: data.files.map((file) => ({\n\t\t\tpath: file.path,\n\t\t\tkind: file.before.kind === \"missing\" ? \"added\" : file.after.kind === \"missing\" ? \"deleted\" : \"modified\",\n\t\t\tadditions: file.additions,\n\t\t\tdeletions: file.deletions,\n\t\t\tundoable: isUndoable(file),\n\t\t})),\n\t\tundone,\n\t}));\n}\n\n/**\n * Restore the files the turn `turnId` on the branch changed to their state before it, deleting files it\n * added. Refuses, changing nothing, when the turn is not on the branch or already undone, when one of its\n * files cannot be undone, when a later turn that was not undone changed one of its files, or when a file on\n * disk differs from the turn's end state. The caller records the undo on the branch.\n */\nexport async function undoTurnFiles(turnId: string, sessionManager: SessionManager): Promise<UndoTurnResult> {\n\tconst records = readTurnRecords(sessionManager.getBranch());\n\tconst index = records.findIndex((record) => record.data.turnId === turnId);\n\tif (index === -1) return { kind: \"refused\", reason: \"not-found\", paths: [] };\n\tconst { data, undone } = records[index];\n\tif (undone) return { kind: \"refused\", reason: \"already-undone\", paths: [] };\n\tconst notUndoable = data.files.filter((file) => !isUndoable(file)).map((file) => file.path);\n\tif (notUndoable.length > 0) return { kind: \"refused\", reason: \"not-undoable\", paths: notUndoable };\n\tconst laterPaths = new Set(\n\t\trecords.slice(index + 1).flatMap((record) => (record.undone ? [] : record.data.files.map((file) => file.path))),\n\t);\n\tconst conflicts = data.files.filter((file) => laterPaths.has(file.path)).map((file) => file.path);\n\tif (conflicts.length > 0) return { kind: \"refused\", reason: \"later-turn\", paths: conflicts };\n\tconst changed: string[] = [];\n\tfor (const file of data.files) {\n\t\tif (!matchesRecordedState(await readFileState(file.path), file.after)) changed.push(file.path);\n\t}\n\tif (changed.length > 0) return { kind: \"refused\", reason: \"changed-on-disk\", paths: changed };\n\treturn await restoreFiles(data, sessionManager);\n}\n\n/** A file to restore: delete it, or write its content from before the turn. */\ntype Restore = { kind: \"delete\"; path: string } | { kind: \"write\"; path: string; bytes: Buffer };\n\n/**\n * Write back the state of the record's files before the turn. Every snapshot loads before a file changes,\n * so a lost snapshot refuses the undo instead of leaving it half done.\n */\nasync function restoreFiles(data: TurnFilesData, sessionManager: SessionManager): Promise<UndoTurnResult> {\n\tconst restores: Restore[] = [];\n\tconst lost: string[] = [];\n\tfor (const { path, before } of data.files) {\n\t\tif (before.kind !== \"snapshot\") {\n\t\t\trestores.push({ kind: \"delete\", path });\n\t\t\tcontinue;\n\t\t}\n\t\tconst bytes = await loadSnapshot(before.sha256, data.snapshotDir, sessionManager);\n\t\tif (bytes) restores.push({ kind: \"write\", path, bytes });\n\t\telse lost.push(path);\n\t}\n\tif (lost.length > 0) return { kind: \"refused\", reason: \"not-undoable\", paths: lost };\n\tfor (const restore of restores) {\n\t\tif (restore.kind === \"delete\") {\n\t\t\tawait rm(restore.path, { force: true });\n\t\t} else {\n\t\t\tawait mkdir(dirname(restore.path), { recursive: true });\n\t\t\tawait writeFile(restore.path, restore.bytes);\n\t\t}\n\t}\n\treturn { kind: \"undone\", paths: data.files.map((file) => file.path) };\n}\n\n/** The records on `branch`, oldest first, with whether each was undone on it. */\nfunction readTurnRecords(branch: readonly SessionEntry[]): Array<{ data: TurnFilesData; undone: boolean }> {\n\tconst records: TurnFilesData[] = [];\n\tconst undone = new Set<string>();\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom\") continue;\n\t\tif (entry.customType === TURN_FILES_ENTRY) records.push(entry.data as TurnFilesData);\n\t\telse if (entry.customType === TURN_FILES_UNDO_ENTRY) undone.add((entry.data as TurnFilesUndoData).turnId);\n\t}\n\treturn records.map((data) => ({ data, undone: undone.has(data.turnId) }));\n}\n\nfunction isUndoable(file: RecordedFileChange): boolean {\n\treturn file.before.kind !== \"too-large\" && file.after.kind !== \"too-large\";\n}\n\nasync function readFileState(path: string): Promise<FileState> {\n\tlet size: number;\n\ttry {\n\t\tsize = (await stat(path)).size;\n\t} catch (error) {\n\t\tif (isMissingPathError(error)) return { kind: \"missing\" };\n\t\tthrow error;\n\t}\n\tif (size > TURN_FILE_SNAPSHOT_MAX_BYTES) return { kind: \"too-large\", size };\n\treturn { kind: \"content\", bytes: await readFile(path) };\n}\n\nfunction isMissingPathError(error: unknown): boolean {\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\n/** Whether two states are known to be equal. Files too large to snapshot never are. */\nfunction sameFileState(a: FileState, b: FileState): boolean {\n\tif (a.kind === \"missing\" || b.kind === \"missing\") return a.kind === b.kind;\n\treturn a.kind === \"content\" && b.kind === \"content\" && a.bytes.equals(b.bytes);\n}\n\nfunction matchesRecordedState(state: FileState, recorded: RecordedFileState): boolean {\n\tswitch (recorded.kind) {\n\t\tcase \"missing\":\n\t\t\treturn state.kind === \"missing\";\n\t\tcase \"snapshot\":\n\t\t\treturn state.kind === \"content\" && hashBytes(state.bytes) === recorded.sha256;\n\t\tcase \"too-large\":\n\t\t\treturn false;\n\t}\n}\n\n/** Lines added and removed between two states; both 0 when either side is binary or too large. */\nfunction countFileLines(before: FileState, after: FileState): { additions: number; deletions: number } {\n\tconst oldText = textOf(before);\n\tconst newText = textOf(after);\n\tif (oldText === undefined || newText === undefined) return { additions: 0, deletions: 0 };\n\treturn countChangedLines(oldText, newText);\n}\n\n/** The text of a state: empty when missing, undefined when too large or binary (holding a NUL byte). */\nfunction textOf(state: FileState): string | undefined {\n\tswitch (state.kind) {\n\t\tcase \"missing\":\n\t\t\treturn \"\";\n\t\tcase \"too-large\":\n\t\t\treturn undefined;\n\t\tcase \"content\":\n\t\t\treturn state.bytes.includes(0) ? undefined : state.bytes.toString(\"utf-8\");\n\t}\n}\n\n/** The folder next to the session file that holds its snapshots, or undefined for an in-memory session. */\nfunction getSnapshotDir(sessionManager: SessionManager): string | undefined {\n\tconst sessionFile = sessionManager.isPersisted() ? sessionManager.getSessionFile() : undefined;\n\treturn sessionFile === undefined ? undefined : `${sessionFile.replace(/\\.jsonl$/, \"\")}.snapshots`;\n}\n\n/**\n * Snapshots of in-memory sessions, by the session manager that owns them. A fork of an in-memory session\n * keeps its manager, so it finds the snapshots of the turns it copied.\n */\nconst memorySnapshots = new WeakMap<SessionManager, Map<string, Buffer>>();\n\n/** Keep the content of `state` as a snapshot and return its recorded form. */\nasync function storeFileState(\n\tstate: FileState,\n\tsnapshotDir: string | undefined,\n\tsessionManager: SessionManager,\n): Promise<RecordedFileState> {\n\tif (state.kind !== \"content\") return state;\n\tconst sha256 = hashBytes(state.bytes);\n\tif (snapshotDir === undefined) {\n\t\tlet snapshots = memorySnapshots.get(sessionManager);\n\t\tif (!snapshots) {\n\t\t\tsnapshots = new Map();\n\t\t\tmemorySnapshots.set(sessionManager, snapshots);\n\t\t}\n\t\tsnapshots.set(sha256, state.bytes);\n\t} else {\n\t\tawait writeSnapshotFile(join(snapshotDir, sha256), state.bytes);\n\t}\n\treturn { kind: \"snapshot\", sha256 };\n}\n\n/**\n * Write a snapshot file unless it exists. Writing a temporary file and renaming it keeps a crash from\n * leaving a partial snapshot under the hash.\n */\nasync function writeSnapshotFile(path: string, bytes: Buffer): Promise<void> {\n\ttry {\n\t\tawait stat(path);\n\t\treturn;\n\t} catch (error) {\n\t\tif (!isMissingPathError(error)) throw error;\n\t}\n\tawait mkdir(dirname(path), { recursive: true });\n\tconst temporaryPath = `${path}.tmp`;\n\tawait writeFile(temporaryPath, bytes);\n\tawait rename(temporaryPath, path);\n}\n\n/** The bytes of a snapshot, or undefined when it is lost or a snapshot file no longer matches its hash. */\nasync function loadSnapshot(\n\tsha256: string,\n\tsnapshotDir: string | undefined,\n\tsessionManager: SessionManager,\n): Promise<Buffer | undefined> {\n\tif (snapshotDir === undefined) return memorySnapshots.get(sessionManager)?.get(sha256);\n\ttry {\n\t\tconst bytes = await readFile(join(snapshotDir, sha256));\n\t\treturn hashBytes(bytes) === sha256 ? bytes : undefined;\n\t} catch (error) {\n\t\tif (isMissingPathError(error)) return undefined;\n\t\tthrow error;\n\t}\n}\n\nfunction hashBytes(bytes: Buffer): string {\n\treturn createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n"]}
|
|
@@ -14,7 +14,6 @@ import type { SubagentScope } from "./call-scopes.ts";
|
|
|
14
14
|
import { type AgentDefinition } from "./definitions.ts";
|
|
15
15
|
import { type SubagentProgress } from "./runner.ts";
|
|
16
16
|
export declare const AGENT_TOOL_NAME = "agent";
|
|
17
|
-
export declare const TASK_STOP_TOOL_NAME = "task_stop";
|
|
18
17
|
declare const agentSchema: Type.TObject<{
|
|
19
18
|
description: Type.TString;
|
|
20
19
|
prompt: Type.TString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/agents/agent-tool.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAGvD,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAG3F,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/agents/agent-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E,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACzF,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IACxE,UAAU,EAAE,gBAAgB,CAAC;IAC7B,8DAA8D;IAC9D,MAAM,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,CAAC;CACrC;AAED,gEAAgE;AAChE,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,aAAa,GAAG,cAAc,CAAC,OAAO,WAAW,EAAE,gBAAgB,CAAC,CAmInH;AAaD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAChC,MAAM,EAAE,YAAY,EACpB,UAAU,EAAE,eAAe,EAC3B,cAAc,EAAE,OAAO,GACrB,YAAY,CAMd;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,oBAAoB,EAAE,UAAU,EAAE,eAAe,EAAE,YAAY,EAAE,OAAO,GAAG,SAAS,EAAE,CAmBrH"}
|
|
@@ -8,16 +8,17 @@ import { Text } from "@diffra-ai/tui";
|
|
|
8
8
|
import { Type } from "typebox";
|
|
9
9
|
import { resolveFastModel } from "../../core/fast-model.js";
|
|
10
10
|
import { findExactModelReferenceMatch } from "../../core/model-resolver.js";
|
|
11
|
+
import { TASK_STOP_TOOL_NAME } from "../../core/tools/background-tasks.js";
|
|
11
12
|
import { incompleteResult, settle } from "./background.js";
|
|
12
13
|
import { DEFAULT_AGENT_TYPE } from "./builtin-agents.js";
|
|
13
14
|
import { findAgent } from "./definitions.js";
|
|
14
15
|
import { runSubagent } from "./runner.js";
|
|
15
16
|
export const AGENT_TOOL_NAME = "agent";
|
|
16
|
-
export const TASK_STOP_TOOL_NAME = "task_stop";
|
|
17
17
|
/** Tools a subagent never gets: they belong to the parent's conversation with the user. */
|
|
18
18
|
const EXCLUDED_FROM_SUBAGENTS = new Set([
|
|
19
19
|
"todo_write",
|
|
20
20
|
"exit_plan_mode",
|
|
21
|
+
"ask_user_question",
|
|
21
22
|
"get_goal",
|
|
22
23
|
"update_goal",
|
|
23
24
|
"enter_worktree",
|