@draht/coding-agent 2026.10.23 → 2026.10.31-1
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 +21 -0
- package/README.md +10 -0
- package/dist/bundle/chunks/{anthropic-messages-VEMVBETR.js → anthropic-messages-CZYDBUW7.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-EXUP6SLM.js → azure-openai-responses-UKM4K3L6.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +21 -21
- package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
- package/dist/bundle/chunks/{chunk-FXLM6UQV.js → chunk-2TZWVGCR.js} +1 -1
- package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-6WESOD4H.js} +1 -1
- package/dist/bundle/chunks/{chunk-RGI7SF5G.js → chunk-7ATV4EYW.js} +1 -1
- package/dist/bundle/chunks/{chunk-CHRFWNPF.js → chunk-AS6DCLAM.js} +105 -101
- package/dist/bundle/chunks/{chunk-57PET6SW.js → chunk-BL72B6LV.js} +1 -1
- package/dist/bundle/chunks/{chunk-CI37W6HM.js → chunk-C2XCXA6V.js} +1 -1
- package/dist/bundle/chunks/chunk-CLKG6K6Z.js +7 -0
- package/dist/bundle/chunks/{chunk-QG2WW2SA.js → chunk-CPFKZX4B.js} +1 -1
- package/dist/bundle/chunks/{chunk-AACPRSR2.js → chunk-E4VZJRJ2.js} +1 -1
- package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
- package/dist/bundle/chunks/{chunk-ITP6IDBA.js → chunk-GQXRTK54.js} +2 -2
- package/dist/bundle/chunks/{chunk-JRHPLIE5.js → chunk-H5BLLINF.js} +1 -1
- package/dist/bundle/chunks/{chunk-XB4F3WGD.js → chunk-IGO52ZOY.js} +10 -10
- package/dist/bundle/chunks/chunk-IT4RIOZD.js +2 -0
- package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
- package/dist/bundle/chunks/{chunk-DHZBWXZK.js → chunk-N3FZGIII.js} +1 -1
- package/dist/bundle/chunks/chunk-OCUU7HYF.js +2 -0
- package/dist/bundle/chunks/{chunk-DLVZ3EK7.js → chunk-PMDUR6B5.js} +8 -8
- package/dist/bundle/chunks/{chunk-2RI4GIFP.js → chunk-UCJ7FLSO.js} +3 -3
- package/dist/bundle/chunks/{chunk-KINQOWAP.js → chunk-WFHH5SX6.js} +1 -1
- package/dist/bundle/chunks/{chunk-CMKX4CSI.js → chunk-WYWBXNDO.js} +1 -1
- package/dist/bundle/chunks/{cli-LGOE6EXL.js → cli-HTUB6WOG.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-47PK45EQ.js → cloudflare-workers-ai-system-one-V37VPUK4.js} +1 -1
- package/dist/bundle/chunks/{execute-ZVQ7ITER.js → execute-UUPNZJJG.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-PBPH45HB.js → google-generative-ai-A2277FHU.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-ZPCFQNU6.js → google-vertex-2KSVQZQN.js} +1 -1
- package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
- package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
- package/dist/bundle/chunks/{llama-cpp-classify-MWIQKGBR.js → llama-cpp-classify-Y3DUSEM2.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7ODWQ37T.js → mistral-conversations-R2NJADHS.js} +1 -1
- package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
- package/dist/bundle/chunks/{node-BZAVEWJ3.js → node-DXZFQBEO.js} +1 -1
- package/dist/bundle/chunks/{node-C2JGH2OB.js → node-LBZLUIBE.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-7Y2SP2GS.js → openai-codex-responses-KJZDJELP.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-QNWYJ4H4.js → openai-completions-RTWADJBP.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-4PKBAPR3.js → openai-decisions-JRN6M2KB.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-73WU3TQM.js → openai-responses-B7ASLN2Z.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-IMWDSQ5F.js → openrouter-images-2XTVCXIC.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-AMNZ7HKZ.js → pi-messages-7TX4RC24.js} +1 -1
- package/dist/bundle/chunks/{runtime-MZVF4MP6.js → runtime-IB3XQ7E3.js} +1 -1
- package/dist/bundle/chunks/{runtime-7BIFTREJ.js → runtime-LB35PK4J.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-QF6DRH5C.js → settings-manager-YNY5F4RU.js} +1 -1
- package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
- package/dist/bundle/chunks/{typesafe-system-one-AXQRIVVX.js → typesafe-system-one-7BNMQFXE.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-OFCQ5AEG.js +2 -0
- 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.map +1 -1
- package/dist/core/agent-session.js +1 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/builtins/budget-guidance.d.ts +2 -0
- package/dist/core/builtins/budget-guidance.d.ts.map +1 -0
- package/dist/core/builtins/budget-guidance.js +2 -0
- package/dist/core/builtins/budget-guidance.js.map +1 -0
- package/dist/core/builtins/budgets.d.ts +3 -0
- package/dist/core/builtins/budgets.d.ts.map +1 -0
- package/dist/core/builtins/budgets.js +272 -0
- package/dist/core/builtins/budgets.js.map +1 -0
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/subagent.d.ts +3 -1
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +6 -3
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +32 -3
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +2 -2
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +3 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts +37 -8
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +158 -17
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +3 -0
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +29 -7
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -0
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +1 -1
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/hooks/checks/budget-command.md +22 -0
- package/dist/hooks/checks/budgets-cl100k.json.gz +0 -0
- package/dist/hooks/checks/budgets-runtime.LICENSE +95 -0
- package/dist/hooks/checks/budgets-runtime.cjs +3382 -0
- package/docs/budgets.md +122 -0
- package/docs/docs.json +4 -0
- package/docs/environment-variables.md +1 -1
- package/docs/extensions.md +3 -1
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +13 -1
- package/docs/slash-commands.md +1 -0
- package/eval/drahtbank/runtime-checks.d.mts +1 -1
- package/eval/drahtbank/runtime-checks.mjs +38 -4
- package/hooks/checks/budget-command.md +22 -0
- package/hooks/checks/budgets-cl100k.json.gz +0 -0
- package/hooks/checks/budgets-runtime.LICENSE +95 -0
- package/hooks/checks/budgets-runtime.cjs +3382 -0
- package/package.json +9 -9
- package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
- package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
- package/dist/bundle/chunks/chunk-LK54N67E.js +0 -7
- package/dist/bundle/chunks/chunk-SYRVFGYE.js +0 -2
- package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
- package/dist/bundle/chunks/chunk-YSIQCH4Z.js +0 -2
- package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
- package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
- package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
- package/dist/bundle/chunks/virtual-modules-Z4F3ZUX3.js +0 -2
- /package/dist/bundle/chunks/{chunk-UQSONZLL.js → chunk-DN7SM3LX.js} +0 -0
- /package/dist/bundle/chunks/{chunk-2MJ6J5N2.js → chunk-FOYIPAAD.js} +0 -0
- /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-MOOADNVS.js} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare const BUDGET_GUIDANCE = "Budgets are ceilings, not targets: write the smallest clear solution. Prefer clear names, cohesive functions, and focused modules. Keep documentation concise: explain contracts, setup, and non-obvious decisions; avoid restating code or writing progress diaries. Do not minify code or make arbitrary file splits just to fit a budget. Change .draht/budgets.json only when the user asks; edits apply only after the user starts a new budget task.";
|
|
2
|
+
//# sourceMappingURL=budget-guidance.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget-guidance.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/budget-guidance.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,+bACia,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export const BUDGET_GUIDANCE = "Budgets are ceilings, not targets: write the smallest clear solution. Prefer clear names, cohesive functions, and focused modules. Keep documentation concise: explain contracts, setup, and non-obvious decisions; avoid restating code or writing progress diaries. Do not minify code or make arbitrary file splits just to fit a budget. Change .draht/budgets.json only when the user asks; edits apply only after the user starts a new budget task.";
|
|
2
|
+
//# sourceMappingURL=budget-guidance.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budget-guidance.js","sourceRoot":"","sources":["../../../src/core/builtins/budget-guidance.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAC3B,4bAA4b,CAAC","sourcesContent":["export const BUDGET_GUIDANCE =\n\t\"Budgets are ceilings, not targets: write the smallest clear solution. Prefer clear names, cohesive functions, and focused modules. Keep documentation concise: explain contracts, setup, and non-obvious decisions; avoid restating code or writing progress diaries. Do not minify code or make arbitrary file splits just to fit a budget. Change .draht/budgets.json only when the user asks; edits apply only after the user starts a new budget task.\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budgets.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAOA,OAAO,EAEN,KAAK,YAAY,EAGjB,MAAM,wBAAwB,CAAC;AA0KhC,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,QA2GtD"}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { getPackageDir, isBunBinary } from "../../config.js";
|
|
5
|
+
import { spawnProcess, waitForChildProcess } from "../../utils/child-process.js";
|
|
6
|
+
import { stripFrontmatter } from "../../utils/frontmatter.js";
|
|
7
|
+
import { splitBom } from "../../utils/text.js";
|
|
8
|
+
import { isToolCallEventType, } from "../extensions/types.js";
|
|
9
|
+
import { applyEditsToNormalizedContent, detectLineEnding, normalizeToLF, restoreLineEndings, } from "../tools/edit-diff.js";
|
|
10
|
+
import { resolveToCwd } from "../tools/path-utils.js";
|
|
11
|
+
import { BUDGET_GUIDANCE } from "./budget-guidance.js";
|
|
12
|
+
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls"]);
|
|
13
|
+
const MAX_REPAIR_ATTEMPTS = 3;
|
|
14
|
+
const CONTEXT_TYPE = "budget-context";
|
|
15
|
+
const RUNTIME_TIMEOUT_MS = 60_000;
|
|
16
|
+
const MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
17
|
+
function runtimePath() {
|
|
18
|
+
return join(getPackageDir(), "hooks", "checks", "budgets-runtime.cjs");
|
|
19
|
+
}
|
|
20
|
+
function parseResult(value) {
|
|
21
|
+
if (typeof value !== "object" ||
|
|
22
|
+
value === null ||
|
|
23
|
+
!("status" in value) ||
|
|
24
|
+
!("summary" in value) ||
|
|
25
|
+
(value.status !== "passed" &&
|
|
26
|
+
value.status !== "failed" &&
|
|
27
|
+
value.status !== "disabled" &&
|
|
28
|
+
value.status !== "error") ||
|
|
29
|
+
typeof value.summary !== "string") {
|
|
30
|
+
throw new Error("Invalid budget policy result");
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
status: value.status,
|
|
34
|
+
summary: value.summary,
|
|
35
|
+
...("taskId" in value && typeof value.taskId === "string" ? { taskId: value.taskId } : {}),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function failure(error) {
|
|
39
|
+
return {
|
|
40
|
+
status: "error",
|
|
41
|
+
summary: `Budget check failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Runs the packaged runtime in a child process, so snapshotting a large repository never blocks the session. */
|
|
45
|
+
async function callBudget(method, request, signal) {
|
|
46
|
+
let output = "";
|
|
47
|
+
let errors = "";
|
|
48
|
+
let termination;
|
|
49
|
+
try {
|
|
50
|
+
// A compiled binary runs a script as plain Bun when BUN_BE_BUN is set, so budgets need no separate Node.
|
|
51
|
+
const child = spawnProcess(process.execPath, [runtimePath(), "call"], {
|
|
52
|
+
cwd: request.cwd,
|
|
53
|
+
env: isBunBinary ? { ...process.env, BUN_BE_BUN: "1" } : process.env,
|
|
54
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
55
|
+
});
|
|
56
|
+
const terminate = (reason) => {
|
|
57
|
+
termination ??= reason;
|
|
58
|
+
child.kill("SIGKILL");
|
|
59
|
+
};
|
|
60
|
+
const onAbort = () => terminate("Budget check was cancelled");
|
|
61
|
+
const timeout = setTimeout(() => terminate("Budget check exceeded its 60-second limit"), RUNTIME_TIMEOUT_MS);
|
|
62
|
+
child.stdout?.on("data", (chunk) => {
|
|
63
|
+
output += chunk.toString();
|
|
64
|
+
if (Buffer.byteLength(output) > MAX_OUTPUT_BYTES)
|
|
65
|
+
terminate("Budget check output exceeded 1 MiB");
|
|
66
|
+
});
|
|
67
|
+
child.stderr?.on("data", (chunk) => {
|
|
68
|
+
errors = `${errors}${chunk.toString()}`.slice(-4000);
|
|
69
|
+
});
|
|
70
|
+
if (signal?.aborted)
|
|
71
|
+
onAbort();
|
|
72
|
+
else
|
|
73
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
74
|
+
child.stdin?.end(JSON.stringify({ method, request }));
|
|
75
|
+
try {
|
|
76
|
+
const code = await waitForChildProcess(child);
|
|
77
|
+
if (termination)
|
|
78
|
+
return failure(termination);
|
|
79
|
+
if (code !== 0)
|
|
80
|
+
return failure(`budget runtime exited ${code ?? "without an exit status"}. ${errors}`.trim());
|
|
81
|
+
return parseResult(JSON.parse(output));
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
clearTimeout(timeout);
|
|
85
|
+
signal?.removeEventListener("abort", onAbort);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
return failure(error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function loadRuntime() {
|
|
93
|
+
const runtime = createRequire(import.meta.url)(runtimePath());
|
|
94
|
+
if (typeof runtime !== "object" ||
|
|
95
|
+
runtime === null ||
|
|
96
|
+
!("beginTask" in runtime) ||
|
|
97
|
+
!("budgetConfigured" in runtime)) {
|
|
98
|
+
throw new Error("Missing budget policy");
|
|
99
|
+
}
|
|
100
|
+
const { beginTask, budgetConfigured } = runtime;
|
|
101
|
+
if (typeof beginTask !== "function" || typeof budgetConfigured !== "function")
|
|
102
|
+
throw new Error("Invalid budget policy");
|
|
103
|
+
return {
|
|
104
|
+
/** Starts a new task in this process: the runtime's command-line interface refuses to, so agents cannot. */
|
|
105
|
+
startNewTask: (cwd) => parseResult(beginTask({ cwd, newTask: true })),
|
|
106
|
+
/** A file-system check that lets repositories without budgets skip the runtime process entirely. */
|
|
107
|
+
configured: (cwd) => budgetConfigured(cwd) === true,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Reads a regular file; the nonblocking open keeps a named pipe from stalling the session's thread. */
|
|
111
|
+
function readRegularFile(path) {
|
|
112
|
+
const descriptor = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
|
|
113
|
+
try {
|
|
114
|
+
return fstatSync(descriptor).isFile() ? readFileSync(descriptor, "utf8") : undefined;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
closeSync(descriptor);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Edits the tool itself would reject, of files that are not regular files, or that run on another filesystem are
|
|
122
|
+
* left to the tool and the audit after it.
|
|
123
|
+
*/
|
|
124
|
+
function previewEdit(event, cwd) {
|
|
125
|
+
if (isToolCallEventType("write", event)) {
|
|
126
|
+
return [{ path: resolveToCwd(event.input.path, cwd), content: event.input.content }];
|
|
127
|
+
}
|
|
128
|
+
if (!isToolCallEventType("edit", event))
|
|
129
|
+
return undefined;
|
|
130
|
+
try {
|
|
131
|
+
const path = resolveToCwd(event.input.path, cwd);
|
|
132
|
+
const original = readRegularFile(path);
|
|
133
|
+
if (original === undefined)
|
|
134
|
+
return undefined;
|
|
135
|
+
const { bom, text } = splitBom(original);
|
|
136
|
+
const { newContent } = applyEditsToNormalizedContent(normalizeToLF(text), event.input.edits, event.input.path);
|
|
137
|
+
return [{ path, content: bom + restoreLineEndings(newContent, detectLineEnding(text)) }];
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** True when budget guidance reached the context after the last compaction. */
|
|
144
|
+
function hasBudgetContext(entries) {
|
|
145
|
+
const compaction = entries.findLastIndex((entry) => entry.type === "compaction");
|
|
146
|
+
return entries
|
|
147
|
+
.slice(compaction + 1)
|
|
148
|
+
.some((entry) => entry.type === "custom_message" && entry.customType === CONTEXT_TYPE);
|
|
149
|
+
}
|
|
150
|
+
function configurationPrompt(request) {
|
|
151
|
+
const packageDir = getPackageDir();
|
|
152
|
+
const body = stripFrontmatter(readFileSync(join(packageDir, "hooks", "checks", "budget-command.md"), "utf8"));
|
|
153
|
+
const runtime = runtimePath().replace(/["\\$`]/g, (character) => `\\${character}`);
|
|
154
|
+
return body.replaceAll("<BUDGET_RUNTIME>", () => runtime).replaceAll("$ARGUMENTS", () => request);
|
|
155
|
+
}
|
|
156
|
+
export default function budgetsBuiltin(pi) {
|
|
157
|
+
let runtime;
|
|
158
|
+
const local = () => {
|
|
159
|
+
runtime ??= loadRuntime();
|
|
160
|
+
return runtime;
|
|
161
|
+
};
|
|
162
|
+
// Budgets are opt-in, so a run checks nothing until its start finds a configured repository.
|
|
163
|
+
let active = false;
|
|
164
|
+
let repairAttempts = 0;
|
|
165
|
+
const preflighted = new Set();
|
|
166
|
+
pi.on("before_agent_start", async (_event, ctx) => {
|
|
167
|
+
repairAttempts = 0;
|
|
168
|
+
try {
|
|
169
|
+
active = local().configured(ctx.cwd);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// The runtime process reports why the packaged policy cannot load.
|
|
173
|
+
active = true;
|
|
174
|
+
}
|
|
175
|
+
if (!active)
|
|
176
|
+
return;
|
|
177
|
+
const result = await callBudget("beginTask", { cwd: ctx.cwd }, ctx.signal);
|
|
178
|
+
active = result.status !== "disabled";
|
|
179
|
+
if (!active)
|
|
180
|
+
return;
|
|
181
|
+
const informed = hasBudgetContext(ctx.sessionManager.getBranch());
|
|
182
|
+
if (informed && result.status === "passed")
|
|
183
|
+
return;
|
|
184
|
+
const guided = informed || result.status === "error" ? result.summary : `${result.summary}\n${BUDGET_GUIDANCE}`;
|
|
185
|
+
return { message: { customType: CONTEXT_TYPE, content: guided, display: false, details: result } };
|
|
186
|
+
});
|
|
187
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
188
|
+
if (!active)
|
|
189
|
+
return;
|
|
190
|
+
const proposed = previewEdit(event, ctx.cwd);
|
|
191
|
+
if (!proposed)
|
|
192
|
+
return;
|
|
193
|
+
const result = await callBudget("checkBudget", { cwd: ctx.cwd, proposed }, ctx.signal);
|
|
194
|
+
if (result.status === "failed")
|
|
195
|
+
return { block: true, reason: result.summary };
|
|
196
|
+
if (result.status === "passed")
|
|
197
|
+
preflighted.add(event.toolCallId);
|
|
198
|
+
});
|
|
199
|
+
pi.on("tool_result", async (event, ctx) => {
|
|
200
|
+
if (!active || READ_ONLY_TOOLS.has(event.toolName))
|
|
201
|
+
return;
|
|
202
|
+
// A write or edit whose preflight passed wrote exactly the content that was checked.
|
|
203
|
+
if (preflighted.delete(event.toolCallId))
|
|
204
|
+
return;
|
|
205
|
+
const result = await callBudget("auditBudget", { cwd: ctx.cwd }, ctx.signal);
|
|
206
|
+
if (result.status !== "failed")
|
|
207
|
+
return;
|
|
208
|
+
return { content: [...event.content, { type: "text", text: result.summary }] };
|
|
209
|
+
});
|
|
210
|
+
pi.on("agent_before_settle", async (event, ctx) => {
|
|
211
|
+
if (!active || event.outcome !== "completed")
|
|
212
|
+
return;
|
|
213
|
+
const result = await callBudget("auditBudget", { cwd: ctx.cwd }, ctx.signal);
|
|
214
|
+
if (result.status === "passed" || result.status === "disabled")
|
|
215
|
+
return;
|
|
216
|
+
const continueRun = result.status === "failed" && repairAttempts < MAX_REPAIR_ATTEMPTS && !ctx.signal?.aborted;
|
|
217
|
+
let content;
|
|
218
|
+
if (continueRun) {
|
|
219
|
+
repairAttempts++;
|
|
220
|
+
content = `Budget exceeded (repair ${repairAttempts}/${MAX_REPAIR_ATTEMPTS}). Reduce the reported excess while keeping code readable and documentation concise.\n${result.summary}`;
|
|
221
|
+
}
|
|
222
|
+
else if (result.status === "failed") {
|
|
223
|
+
content = `Budget verification failed. Automatic repair stopped; this work is not within budget.\n${result.summary}`;
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
content = `Budget verification could not run, so this work is not checked against the budget. Fix .draht/budgets.json or start a new task with /budget new.\n${result.summary}`;
|
|
227
|
+
}
|
|
228
|
+
if (!continueRun) {
|
|
229
|
+
ctx.ui.notify(content, "error");
|
|
230
|
+
ctx.abort();
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
entries: [
|
|
234
|
+
...event.entries,
|
|
235
|
+
{ type: "custom_message", customType: "budgets", content, display: true, details: result },
|
|
236
|
+
],
|
|
237
|
+
continue: event.continue || continueRun,
|
|
238
|
+
};
|
|
239
|
+
});
|
|
240
|
+
pi.registerCommand("budget", {
|
|
241
|
+
description: "Configure file budgets, show status, or start a new shared task with /budget new",
|
|
242
|
+
handler: async (args, ctx) => {
|
|
243
|
+
const request = args.trim() || "configure";
|
|
244
|
+
const action = /^configure(?:\s|$)/.test(request) ? "configure" : request;
|
|
245
|
+
if (action !== "configure" && action !== "status" && action !== "new") {
|
|
246
|
+
ctx.ui.notify("Usage: /budget [configure|status|new]", "error");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (action !== "status" && !ctx.isIdle()) {
|
|
250
|
+
ctx.ui.notify("Wait for the active run to finish before configuring budgets or starting a new task.", "error");
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (action === "configure") {
|
|
254
|
+
pi.sendUserMessage(configurationPrompt(request), { expandPromptTemplates: false });
|
|
255
|
+
await ctx.waitForIdle();
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
let result;
|
|
259
|
+
try {
|
|
260
|
+
result =
|
|
261
|
+
action === "new"
|
|
262
|
+
? local().startNewTask(ctx.cwd)
|
|
263
|
+
: await callBudget("auditBudget", { cwd: ctx.cwd }, ctx.signal);
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
result = failure(error);
|
|
267
|
+
}
|
|
268
|
+
pi.sendMessage({ customType: "budget-status", content: result.summary, display: true, details: result });
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
//# sourceMappingURL=budgets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"budgets.js","sourceRoot":"","sources":["../../../src/core/builtins/budgets.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAGN,mBAAmB,GAEnB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACN,6BAA6B,EAC7B,gBAAgB,EAChB,aAAa,EACb,kBAAkB,GAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,C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,EAAE,CAAC,MAAM,CAAC,uCAAuC,EAAE,OAAO,CAAC,CAAC;gBAChE,OAAO;YACR,CAAC;YACD,IAAI,MAAM,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC;gBAC1C,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,sFAAsF,EACtF,OAAO,CACP,CAAC;gBACF,OAAO;YACR,CAAC;YACD,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;gBAC5B,EAAE,CAAC,eAAe,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,EAAE,qBAAqB,EAAE,KAAK,EAAE,CAAC,CAAC;gBACnF,MAAM,GAAG,CAAC,WAAW,EAAE,CAAC;gBACxB,OAAO;YACR,CAAC;YACD,IAAI,MAAoB,CAAC;YACzB,IAAI,CAAC;gBACJ,MAAM;oBACL,MAAM,KAAK,KAAK;wBACf,CAAC,CAAC,KAAK,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC;wBAC/B,CAAC,CAAC,MAAM,UAAU,CAAC,aAAa,EAAE,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACnE,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;YACzB,CAAC;YACD,EAAE,CAAC,WAAW,CAAC,EAAE,UAAU,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;QAC1G,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { closeSync, constants, fstatSync, openSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { getPackageDir, isBunBinary } from \"../../config.ts\";\nimport { spawnProcess, waitForChildProcess } from \"../../utils/child-process.ts\";\nimport { stripFrontmatter } from \"../../utils/frontmatter.ts\";\nimport { splitBom } from \"../../utils/text.ts\";\nimport {\n\ttype BoundaryResult,\n\ttype ExtensionAPI,\n\tisToolCallEventType,\n\ttype ToolCallEvent,\n} from \"../extensions/types.ts\";\nimport type { SessionEntry } from \"../session-manager.ts\";\nimport {\n\tapplyEditsToNormalizedContent,\n\tdetectLineEnding,\n\tnormalizeToLF,\n\trestoreLineEndings,\n} from \"../tools/edit-diff.ts\";\nimport { resolveToCwd } from \"../tools/path-utils.ts\";\nimport { BUDGET_GUIDANCE } from \"./budget-guidance.ts\";\n\ninterface BudgetResult {\n\tstatus: \"passed\" | \"failed\" | \"disabled\" | \"error\";\n\tsummary: string;\n\ttaskId?: string;\n}\n\ntype ProposedFiles = Array<{ path: string; content: string | null }>;\n\nconst READ_ONLY_TOOLS = new Set([\"read\", \"grep\", \"find\", \"ls\"]);\nconst MAX_REPAIR_ATTEMPTS = 3;\nconst CONTEXT_TYPE = \"budget-context\";\nconst RUNTIME_TIMEOUT_MS = 60_000;\nconst MAX_OUTPUT_BYTES = 1024 * 1024;\n\nfunction runtimePath(): string {\n\treturn join(getPackageDir(), \"hooks\", \"checks\", \"budgets-runtime.cjs\");\n}\n\nfunction parseResult(value: unknown): BudgetResult {\n\tif (\n\t\ttypeof value !== \"object\" ||\n\t\tvalue === null ||\n\t\t!(\"status\" in value) ||\n\t\t!(\"summary\" in value) ||\n\t\t(value.status !== \"passed\" &&\n\t\t\tvalue.status !== \"failed\" &&\n\t\t\tvalue.status !== \"disabled\" &&\n\t\t\tvalue.status !== \"error\") ||\n\t\ttypeof value.summary !== \"string\"\n\t) {\n\t\tthrow new Error(\"Invalid budget policy result\");\n\t}\n\treturn {\n\t\tstatus: value.status,\n\t\tsummary: value.summary,\n\t\t...(\"taskId\" in value && typeof value.taskId === \"string\" ? { taskId: value.taskId } : {}),\n\t};\n}\n\nfunction failure(error: unknown): BudgetResult {\n\treturn {\n\t\tstatus: \"error\",\n\t\tsummary: `Budget check failed: ${error instanceof Error ? error.message : String(error)}`,\n\t};\n}\n\n/** Runs the packaged runtime in a child process, so snapshotting a large repository never blocks the session. */\nasync function callBudget(\n\tmethod: \"beginTask\" | \"checkBudget\" | \"auditBudget\",\n\trequest: { cwd: string; proposed?: ProposedFiles },\n\tsignal?: AbortSignal,\n): Promise<BudgetResult> {\n\tlet output = \"\";\n\tlet errors = \"\";\n\tlet termination: string | undefined;\n\ttry {\n\t\t// A compiled binary runs a script as plain Bun when BUN_BE_BUN is set, so budgets need no separate Node.\n\t\tconst child = spawnProcess(process.execPath, [runtimePath(), \"call\"], {\n\t\t\tcwd: request.cwd,\n\t\t\tenv: isBunBinary ? { ...process.env, BUN_BE_BUN: \"1\" } : process.env,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tconst terminate = (reason: string) => {\n\t\t\ttermination ??= reason;\n\t\t\tchild.kill(\"SIGKILL\");\n\t\t};\n\t\tconst onAbort = () => terminate(\"Budget check was cancelled\");\n\t\tconst timeout = setTimeout(() => terminate(\"Budget check exceeded its 60-second limit\"), RUNTIME_TIMEOUT_MS);\n\t\tchild.stdout?.on(\"data\", (chunk: Buffer) => {\n\t\t\toutput += chunk.toString();\n\t\t\tif (Buffer.byteLength(output) > MAX_OUTPUT_BYTES) terminate(\"Budget check output exceeded 1 MiB\");\n\t\t});\n\t\tchild.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\terrors = `${errors}${chunk.toString()}`.slice(-4000);\n\t\t});\n\t\tif (signal?.aborted) onAbort();\n\t\telse signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\tchild.stdin?.end(JSON.stringify({ method, request }));\n\t\ttry {\n\t\t\tconst code = await waitForChildProcess(child);\n\t\t\tif (termination) return failure(termination);\n\t\t\tif (code !== 0) return failure(`budget runtime exited ${code ?? \"without an exit status\"}. ${errors}`.trim());\n\t\t\treturn parseResult(JSON.parse(output));\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t} catch (error) {\n\t\treturn failure(error);\n\t}\n}\n\nfunction loadRuntime() {\n\tconst runtime: unknown = createRequire(import.meta.url)(runtimePath());\n\tif (\n\t\ttypeof runtime !== \"object\" ||\n\t\truntime === null ||\n\t\t!(\"beginTask\" in runtime) ||\n\t\t!(\"budgetConfigured\" in runtime)\n\t) {\n\t\tthrow new Error(\"Missing budget policy\");\n\t}\n\tconst { beginTask, budgetConfigured } = runtime;\n\tif (typeof beginTask !== \"function\" || typeof budgetConfigured !== \"function\")\n\t\tthrow new Error(\"Invalid budget policy\");\n\treturn {\n\t\t/** Starts a new task in this process: the runtime's command-line interface refuses to, so agents cannot. */\n\t\tstartNewTask: (cwd: string) => parseResult(beginTask({ cwd, newTask: true })),\n\t\t/** A file-system check that lets repositories without budgets skip the runtime process entirely. */\n\t\tconfigured: (cwd: string) => budgetConfigured(cwd) === true,\n\t};\n}\n\n/** Reads a regular file; the nonblocking open keeps a named pipe from stalling the session's thread. */\nfunction readRegularFile(path: string): string | undefined {\n\tconst descriptor = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n\ttry {\n\t\treturn fstatSync(descriptor).isFile() ? readFileSync(descriptor, \"utf8\") : undefined;\n\t} finally {\n\t\tcloseSync(descriptor);\n\t}\n}\n\n/**\n * Edits the tool itself would reject, of files that are not regular files, or that run on another filesystem are\n * left to the tool and the audit after it.\n */\nfunction previewEdit(event: ToolCallEvent, cwd: string): ProposedFiles | undefined {\n\tif (isToolCallEventType(\"write\", event)) {\n\t\treturn [{ path: resolveToCwd(event.input.path, cwd), content: event.input.content }];\n\t}\n\tif (!isToolCallEventType(\"edit\", event)) return undefined;\n\ttry {\n\t\tconst path = resolveToCwd(event.input.path, cwd);\n\t\tconst original = readRegularFile(path);\n\t\tif (original === undefined) return undefined;\n\t\tconst { bom, text } = splitBom(original);\n\t\tconst { newContent } = applyEditsToNormalizedContent(normalizeToLF(text), event.input.edits, event.input.path);\n\t\treturn [{ path, content: bom + restoreLineEndings(newContent, detectLineEnding(text)) }];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** True when budget guidance reached the context after the last compaction. */\nfunction hasBudgetContext(entries: readonly SessionEntry[]): boolean {\n\tconst compaction = entries.findLastIndex((entry) => entry.type === \"compaction\");\n\treturn entries\n\t\t.slice(compaction + 1)\n\t\t.some((entry) => entry.type === \"custom_message\" && entry.customType === CONTEXT_TYPE);\n}\n\nfunction configurationPrompt(request: string): string {\n\tconst packageDir = getPackageDir();\n\tconst body = stripFrontmatter(readFileSync(join(packageDir, \"hooks\", \"checks\", \"budget-command.md\"), \"utf8\"));\n\tconst runtime = runtimePath().replace(/[\"\\\\$`]/g, (character) => `\\\\${character}`);\n\treturn body.replaceAll(\"<BUDGET_RUNTIME>\", () => runtime).replaceAll(\"$ARGUMENTS\", () => request);\n}\n\nexport default function budgetsBuiltin(pi: ExtensionAPI) {\n\tlet runtime: ReturnType<typeof loadRuntime> | undefined;\n\tconst local = () => {\n\t\truntime ??= loadRuntime();\n\t\treturn runtime;\n\t};\n\t// Budgets are opt-in, so a run checks nothing until its start finds a configured repository.\n\tlet active = false;\n\tlet repairAttempts = 0;\n\tconst preflighted = new Set<string>();\n\n\tpi.on(\"before_agent_start\", async (_event, ctx) => {\n\t\trepairAttempts = 0;\n\t\ttry {\n\t\t\tactive = local().configured(ctx.cwd);\n\t\t} catch {\n\t\t\t// The runtime process reports why the packaged policy cannot load.\n\t\t\tactive = true;\n\t\t}\n\t\tif (!active) return;\n\t\tconst result = await callBudget(\"beginTask\", { cwd: ctx.cwd }, ctx.signal);\n\t\tactive = result.status !== \"disabled\";\n\t\tif (!active) return;\n\t\tconst informed = hasBudgetContext(ctx.sessionManager.getBranch());\n\t\tif (informed && result.status === \"passed\") return;\n\t\tconst guided = informed || result.status === \"error\" ? result.summary : `${result.summary}\\n${BUDGET_GUIDANCE}`;\n\t\treturn { message: { customType: CONTEXT_TYPE, content: guided, display: false, details: result } };\n\t});\n\n\tpi.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!active) return;\n\t\tconst proposed = previewEdit(event, ctx.cwd);\n\t\tif (!proposed) return;\n\t\tconst result = await callBudget(\"checkBudget\", { cwd: ctx.cwd, proposed }, ctx.signal);\n\t\tif (result.status === \"failed\") return { block: true, reason: result.summary };\n\t\tif (result.status === \"passed\") preflighted.add(event.toolCallId);\n\t});\n\n\tpi.on(\"tool_result\", async (event, ctx) => {\n\t\tif (!active || READ_ONLY_TOOLS.has(event.toolName)) return;\n\t\t// A write or edit whose preflight passed wrote exactly the content that was checked.\n\t\tif (preflighted.delete(event.toolCallId)) return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status !== \"failed\") return;\n\t\treturn { content: [...event.content, { type: \"text\", text: result.summary }] };\n\t});\n\n\tpi.on(\"agent_before_settle\", async (event, ctx): Promise<BoundaryResult | undefined> => {\n\t\tif (!active || event.outcome !== \"completed\") return;\n\t\tconst result = await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\tif (result.status === \"passed\" || result.status === \"disabled\") return;\n\t\tconst continueRun = result.status === \"failed\" && repairAttempts < MAX_REPAIR_ATTEMPTS && !ctx.signal?.aborted;\n\t\tlet content: string;\n\t\tif (continueRun) {\n\t\t\trepairAttempts++;\n\t\t\tcontent = `Budget exceeded (repair ${repairAttempts}/${MAX_REPAIR_ATTEMPTS}). Reduce the reported excess while keeping code readable and documentation concise.\\n${result.summary}`;\n\t\t} else if (result.status === \"failed\") {\n\t\t\tcontent = `Budget verification failed. Automatic repair stopped; this work is not within budget.\\n${result.summary}`;\n\t\t} else {\n\t\t\tcontent = `Budget verification could not run, so this work is not checked against the budget. Fix .draht/budgets.json or start a new task with /budget new.\\n${result.summary}`;\n\t\t}\n\t\tif (!continueRun) {\n\t\t\tctx.ui.notify(content, \"error\");\n\t\t\tctx.abort();\n\t\t}\n\t\treturn {\n\t\t\tentries: [\n\t\t\t\t...event.entries,\n\t\t\t\t{ type: \"custom_message\", customType: \"budgets\", content, display: true, details: result },\n\t\t\t],\n\t\t\tcontinue: event.continue || continueRun,\n\t\t};\n\t});\n\n\tpi.registerCommand(\"budget\", {\n\t\tdescription: \"Configure file budgets, show status, or start a new shared task with /budget new\",\n\t\thandler: async (args, ctx) => {\n\t\t\tconst request = args.trim() || \"configure\";\n\t\t\tconst action = /^configure(?:\\s|$)/.test(request) ? \"configure\" : request;\n\t\t\tif (action !== \"configure\" && action !== \"status\" && action !== \"new\") {\n\t\t\t\tctx.ui.notify(\"Usage: /budget [configure|status|new]\", \"error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action !== \"status\" && !ctx.isIdle()) {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Wait for the active run to finish before configuring budgets or starting a new task.\",\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (action === \"configure\") {\n\t\t\t\tpi.sendUserMessage(configurationPrompt(request), { expandPromptTemplates: false });\n\t\t\t\tawait ctx.waitForIdle();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet result: BudgetResult;\n\t\t\ttry {\n\t\t\t\tresult =\n\t\t\t\t\taction === \"new\"\n\t\t\t\t\t\t? local().startNewTask(ctx.cwd)\n\t\t\t\t\t\t: await callBudget(\"auditBudget\", { cwd: ctx.cwd }, ctx.signal);\n\t\t\t} catch (error) {\n\t\t\t\tresult = failure(error);\n\t\t\t}\n\t\t\tpi.sendMessage({ customType: \"budget-status\", content: result.summary, display: true, details: result });\n\t\t},\n\t});\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAS9D;;;;;;;GAOG;AACH,eAAO,MAAM,uBAAuB,EAAE,eAAe,EAQpD,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import budgetsBuiltin from "./budgets.js";
|
|
1
2
|
import checkpointsBuiltin from "./checkpoints.js";
|
|
2
3
|
import completionChecksBuiltin from "./completion-checks.js";
|
|
3
4
|
import duetBuiltin from "./duet.js";
|
|
@@ -19,5 +20,6 @@ export const CORE_BUILTIN_EXTENSIONS = [
|
|
|
19
20
|
{ name: "checkpoints", factory: checkpointsBuiltin },
|
|
20
21
|
{ name: "polyphase", factory: polyphaseBuiltin },
|
|
21
22
|
{ name: "completion-checks", factory: completionChecksBuiltin },
|
|
23
|
+
{ name: "budgets", factory: budgetsBuiltin },
|
|
22
24
|
];
|
|
23
25
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/builtins/index.ts"],"names":[],"mappings":"AACA,OAAO,kBAAkB,MAAM,kBAAkB,CAAC;AAClD,OAAO,uBAAuB,MAAM,wBAAwB,CAAC;AAC7D,OAAO,WAAW,MAAM,WAAW,CAAC;AACpC,OAAO,gBAAgB,MAAM,iBAAiB,CAAC;AAC/C,OAAO,gBAAgB,MAAM,gBAAgB,CAAC;AAC9C,OAAO,eAAe,MAAM,eAAe,CAAC;AAE5C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAsB;IACzD,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,EAAE;IACjD,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE;IACjD,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE;IACtC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,EAAE;IACpD,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE;IAChD,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,uBAAuB,EAAE;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/builtins/index.ts"],"names":[],"mappings":"AACA,OAAO,cAAc,MAAM,cAAc,CAAC;AAC1C,OAAO,kBAAkB,MAAM,kBAAkB,CAAC;AAClD,OAAO,uBAAuB,MAAM,wBAAwB,CAAC;AAC7D,OAAO,WAAW,MAAM,WAAW,CAAC;AACpC,OAAO,gBAAgB,MAAM,iBAAiB,CAAC;AAC/C,OAAO,gBAAgB,MAAM,gBAAgB,CAAC;AAC9C,OAAO,eAAe,MAAM,eAAe,CAAC;AAE5C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAsB;IACzD,EAAE,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,EAAE;IACjD,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE;IACjD,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE;IACtC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,EAAE;IACpD,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE;IAChD,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,uBAAuB,EAAE;IAC/D,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,cAAc,EAAE;CAC5C,CAAC","sourcesContent":["import type { InlineExtension } from \"../extensions/types.ts\";\nimport budgetsBuiltin from \"./budgets.ts\";\nimport checkpointsBuiltin from \"./checkpoints.ts\";\nimport completionChecksBuiltin from \"./completion-checks.ts\";\nimport duetBuiltin from \"./duet.ts\";\nimport gitSafetyBuiltin from \"./git-safety.ts\";\nimport polyphaseBuiltin from \"./polyphase.ts\";\nimport subagentBuiltin from \"./subagent.ts\";\n\n/**\n * Extensions that ship as part of the coding-agent core.\n *\n * Unlike project/global extensions (opt-in via settings `packages` or\n * `.draht/extensions/`), these are always loaded by `createAgentSessionServices`\n * regardless of settings, `--no-extensions`, or project trust — the same way\n * the core bash/read/write/edit tools are always available.\n */\nexport const CORE_BUILTIN_EXTENSIONS: InlineExtension[] = [\n\t{ name: \"git-safety\", factory: gitSafetyBuiltin },\n\t{ name: \"multi-agent\", factory: subagentBuiltin },\n\t{ name: \"duet\", factory: duetBuiltin },\n\t{ name: \"checkpoints\", factory: checkpointsBuiltin },\n\t{ name: \"polyphase\", factory: polyphaseBuiltin },\n\t{ name: \"completion-checks\", factory: completionChecksBuiltin },\n\t{ name: \"budgets\", factory: budgetsBuiltin },\n];\n"]}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* chain — { chain: [{ agent, task }] } (sequential, {previous} placeholder)
|
|
11
11
|
*/
|
|
12
12
|
import type { ExtensionAPI, ExtensionContext, ToolCallEvent, ToolCallEventResult } from "../extensions/types.js";
|
|
13
|
-
import { type AgentFSMTransitionEvent, MailboxSystem, PermissionGate, type PermissionMode, type PermissionRule, TaskBoard, WorktreeIsolator } from "../multi-agent/index.ts";
|
|
13
|
+
import { type AgentFSMTransitionEvent, type GatedTool, MailboxSystem, PermissionGate, type PermissionMode, type PermissionRule, TaskBoard, WorktreeIsolator } from "../multi-agent/index.ts";
|
|
14
14
|
import { type ApprovalDescription } from "../polyphase/approval.ts";
|
|
15
15
|
import { type AgentLimiter } from "../polyphase/limiter.ts";
|
|
16
16
|
import { type ParentPermissionBridge } from "../polyphase/permission-bridge.ts";
|
|
@@ -133,6 +133,8 @@ export declare function createRunMailbox(prefix: string): RunMailbox;
|
|
|
133
133
|
export declare function loadPermissionRules(projectDir: string, projectTrusted: boolean, globalDir?: string): PermissionRule[];
|
|
134
134
|
/** Hook points `createPermissionGateToolCallHandler` offers to its caller (§10.5). */
|
|
135
135
|
export interface PermissionGateHandlerOptions {
|
|
136
|
+
/** The called tool as the session registered it, whose read-only hint can spare an ask. */
|
|
137
|
+
getTool?: (toolName: string) => GatedTool | undefined;
|
|
136
138
|
/** Called only for `approve` decisions. Must be cheap and must not throw. */
|
|
137
139
|
describe?: (event: ToolCallEvent, ctx: ExtensionContext) => ApprovalDescription | undefined;
|
|
138
140
|
/** Called right before `ctx.ui.confirm` (so an open inspector can close first). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,OAAO,KAAK,EACX,YAAY,EACZ,gBAAgB,EAEhB,aAAa,EACb,mBAAmB,EACnB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEN,KAAK,uBAAuB,
|
|
1
|
+
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/builtins/subagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAUH,OAAO,KAAK,EACX,YAAY,EACZ,gBAAgB,EAEhB,aAAa,EACb,mBAAmB,EACnB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEN,KAAK,uBAAuB,EAE5B,KAAK,SAAS,EAId,aAAa,EAEb,cAAc,EACd,KAAK,cAAc,EACnB,KAAK,cAAc,EAGnB,SAAS,EACT,gBAAgB,EAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,KAAK,mBAAmB,EAA+B,MAAM,0BAA0B,CAAC;AAIjG,OAAO,EAAE,KAAK,YAAY,EAA0C,MAAM,yBAAyB,CAAC;AAEpG,OAAO,EAEN,KAAK,sBAAsB,EAE3B,MAAM,mCAAmC,CAAC;AAG3C,OAAO,EAGN,KAAK,gBAAgB,EAErB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,KAAK,EACX,WAAW,EACX,eAAe,EACf,WAAW,EACX,oBAAoB,EAIpB,UAAU,EACV,SAAS,EACT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AAC,CAAC,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;CACxD;AAED;;;;;;;GAOG;AACH,wBAAgB,mCAAmC,CAClD,IAAI,EAAE,cAAc,EACpB,OAAO,CAAC,EAAE,4BAA4B,GACpC,CAAC,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAyC3F;AAwED,MAAM,WAAW,2BAA2B;IAC3C,+DAA+D;IAC/D,UAAU,EAAE,MAAM,CAAC;IACnB,8FAA8F;IAC9F,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CAClC;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CACzC,GAAG,EAAE,gBAAgB,EACrB,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,2BAA2B,GAClC,oBAAoB,CA8CtB;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,gBAAgB,EACrB,OAAO,EAAE,gBAAgB,EACzB,UAAU,EAAE,MAAM,GAChB,IAAI,CAAC,eAAe,EAAE,KAAK,GAAG,iBAAiB,CAAC,CAKlD;AAmGD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAS1E;AAED,sGAAsG;AACtG,wBAAgB,uBAAuB,CAAC,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,WAAW,CAAA;CAAO,GAAG,CAAC,EAAE,EAAE,YAAY,KAAK,IAAI,CAqqB1G;6BArqBqF,YAAY,KAAK,IAAI"}
|
|
@@ -62,9 +62,10 @@ export function permissionEnv(session) {
|
|
|
62
62
|
/**
|
|
63
63
|
* Where `app.permissions.cycle` switches to. It alternates `auto` and `ask` and never enters
|
|
64
64
|
* `yolo`, so no single key press drops every approval; that takes `/yolo`. From `yolo` it goes back
|
|
65
|
-
* to `auto`.
|
|
65
|
+
* to `auto`, and from `supervised`, which only `/permissions` enters, to `ask`.
|
|
66
66
|
*/
|
|
67
67
|
const NEXT_PERMISSION_MODE = {
|
|
68
|
+
supervised: "ask",
|
|
68
69
|
auto: "ask",
|
|
69
70
|
ask: "auto",
|
|
70
71
|
yolo: "auto",
|
|
@@ -586,7 +587,7 @@ export function loadPermissionRules(projectDir, projectTrusted, globalDir) {
|
|
|
586
587
|
export function createPermissionGateToolCallHandler(gate, options) {
|
|
587
588
|
return async (event, ctx) => {
|
|
588
589
|
const input = event.input;
|
|
589
|
-
const decision = gate.evaluate(event.toolName, input);
|
|
590
|
+
const decision = gate.evaluate(event.toolName, input, options?.getTool?.(event.toolName));
|
|
590
591
|
if (decision.action === "deny") {
|
|
591
592
|
return { block: true, reason: decision.reason };
|
|
592
593
|
}
|
|
@@ -1258,7 +1259,8 @@ export function createSubagentExtension(options = {}) {
|
|
|
1258
1259
|
updatePermissionStatus(ctx);
|
|
1259
1260
|
}
|
|
1260
1261
|
const MODE_DESCRIPTIONS = {
|
|
1261
|
-
|
|
1262
|
+
supervised: "like ask, and every file change requires approval",
|
|
1263
|
+
ask: "rules as authored; unmatched bash commands, and read-only tools that may reach the web, require approval",
|
|
1262
1264
|
auto: "auto-approve bash unless the command looks dangerous, and start workflows and duet batches without asking (deny rules still block)",
|
|
1263
1265
|
yolo: "no approval prompts this session (deny rules still block)",
|
|
1264
1266
|
};
|
|
@@ -1268,6 +1270,7 @@ export function createSubagentExtension(options = {}) {
|
|
|
1268
1270
|
cwd: ctx.cwd,
|
|
1269
1271
|
mode: permissionMode,
|
|
1270
1272
|
}), {
|
|
1273
|
+
getTool: (name) => pi.getAllTools().find((tool) => tool.name === name),
|
|
1271
1274
|
describe: (e, c) => {
|
|
1272
1275
|
if (e.toolName !== WORKFLOW_TOOL_NAME)
|
|
1273
1276
|
return undefined;
|