@diffra-ai/cli 0.1.4 → 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 +16 -1
- package/dist/bundle/chunks/{anthropic-messages-YTASKTAG.js → anthropic-messages-T6QSBW2I.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-2JI3BQFX.js → azure-openai-responses-QHACUEEL.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/{chunk-CAD23HR7.js → chunk-2CWIL3U7.js} +1 -1
- package/dist/bundle/chunks/{chunk-GNFHDZLP.js → chunk-3OQXW6CV.js} +1 -1
- package/dist/bundle/chunks/{chunk-MPWP6WCT.js → chunk-ACRSTWI3.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZW3S4FQY.js → chunk-EMYFX4WY.js} +1 -1
- package/dist/bundle/chunks/{chunk-PCXT7GLW.js → chunk-GU5QXRH2.js} +114 -85
- package/dist/bundle/chunks/{chunk-7QEHJ36J.js → chunk-HGCDVLYI.js} +1 -1
- package/dist/bundle/chunks/{chunk-SI7T4LPD.js → chunk-J3RI6JJL.js} +2 -2
- package/dist/bundle/chunks/{chunk-6RKODDUE.js → chunk-JZ2OAQAK.js} +1 -1
- package/dist/bundle/chunks/{chunk-AI3Y7XHP.js → chunk-TXISM6X7.js} +4 -4
- package/dist/bundle/chunks/{chunk-IDYI4NPC.js → chunk-UVU7AFFV.js} +1 -1
- package/dist/bundle/chunks/chunk-YTFC5DOS.js +2 -0
- package/dist/bundle/chunks/{chunk-YDKIXS42.js → chunk-ZTDZEFOK.js} +1 -1
- package/dist/bundle/chunks/{cli-2W6362ZV.js → cli-B74BATSM.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-MN7VZOHO.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-QROUBJ3Y.js → google-generative-ai-J4JVZXHV.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-RHSCDEG4.js → google-vertex-A36RXRWN.js} +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-QCKHKADQ.js → llama-cpp-classify-WD5MJBC7.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-WO6QUI4U.js → mistral-conversations-YIKS5LKW.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-XFI3MXBY.js → openai-codex-responses-UBNJIYCO.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-2UHGTBTY.js → openai-completions-WBIL7MLK.js} +1 -1
- package/dist/bundle/chunks/{openai-decisions-BPJODLLR.js → openai-decisions-6T6CQTOT.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-CCD734Z2.js → openai-responses-W2CLKVKJ.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-WSQ42OX2.js → openrouter-images-ZP4QC3RD.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-I264JUT4.js → pi-messages-VHFVA66D.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-O3PSKAI2.js → typesafe-system-one-GORHCFHB.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-CMUMO27Q.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 +9 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- 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 +63 -1
- 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-RAT6HXXD.js +0 -2
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The `exit_plan_mode` tool: the model presents its plan, and the user approves it, choosing the mode
|
|
3
3
|
* to continue in, or keeps planning. Only the user's answer in the dialog approves a plan.
|
|
4
|
+
*
|
|
5
|
+
* Hosts that render plan approvals get the plan as a file in the project's `.diffra/plans/`, which the
|
|
6
|
+
* user may edit before approving, and can also run the plan as a goal and pick the model to implement it.
|
|
4
7
|
*/
|
|
8
|
+
import { existsSync } from "node:fs";
|
|
9
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
5
11
|
import { Container, Markdown, Text } from "@diffra-ai/tui";
|
|
6
12
|
import { Type } from "typebox";
|
|
13
|
+
import { CONFIG_DIR_NAME } from "../../config.js";
|
|
7
14
|
import { APPROVAL_MODE_INFO, readApprovalModeState } from "../../core/approval-mode.js";
|
|
8
15
|
import { getMarkdownTheme } from "../../modes/interactive/theme/theme.js";
|
|
9
16
|
import { EXIT_PLAN_MODE_TOOL_NAME } from "./policy.js";
|
|
@@ -26,6 +33,56 @@ Ensure your plan is complete and unambiguous:
|
|
|
26
33
|
Do NOT ask "Is this plan okay?" or "Should I proceed?" in prose; that is exactly what this tool does.`;
|
|
27
34
|
/** Create `exit_plan_mode`. `onApproved` runs before the mode changes, so the change is not reported as manual. */
|
|
28
35
|
export function createExitPlanModeToolDefinition(diffra, options) {
|
|
36
|
+
// Revisions of a plan replace its file; the next plan after an approval gets a file of its own.
|
|
37
|
+
let planFile;
|
|
38
|
+
/** Ask a host that renders plan approvals; it may also run the plan as a goal and switch the model. */
|
|
39
|
+
async function approveWithHost(request, approvePlan, signal, ctx) {
|
|
40
|
+
planFile = await savePlan(request.plan, ctx.cwd, planFile);
|
|
41
|
+
const answer = await approvePlan({
|
|
42
|
+
toolCallId: request.toolCallId,
|
|
43
|
+
plan: request.plan,
|
|
44
|
+
planFile,
|
|
45
|
+
previousMode: request.previous,
|
|
46
|
+
canRunAsGoal: diffra.getCommands().some((command) => command.name === "goal"),
|
|
47
|
+
}, { signal });
|
|
48
|
+
if (answer === undefined || signal?.aborted)
|
|
49
|
+
return notApproved(NOT_APPROVED);
|
|
50
|
+
if (answer.kind === "keep-planning") {
|
|
51
|
+
const feedback = answer.feedback?.trim();
|
|
52
|
+
return notApproved(feedback
|
|
53
|
+
? `The user wants to keep planning and said: ${feedback}\n\nRevise the plan, then call ${EXIT_PLAN_MODE_TOOL_NAME} again.`
|
|
54
|
+
: NOT_APPROVED);
|
|
55
|
+
}
|
|
56
|
+
if (diffra.getApprovalMode() !== "plan")
|
|
57
|
+
return notApproved(STALE);
|
|
58
|
+
const edited = planFile ? await readEditedPlan(planFile, request.plan) : undefined;
|
|
59
|
+
const plan = edited ?? request.plan;
|
|
60
|
+
const model = answer.model && ctx.modelRegistry.find(answer.model.provider, answer.model.id);
|
|
61
|
+
if (model)
|
|
62
|
+
await diffra.setModel(model);
|
|
63
|
+
if (answer.thinkingLevel)
|
|
64
|
+
diffra.setThinkingLevel(answer.thinkingLevel);
|
|
65
|
+
options.onApproved();
|
|
66
|
+
diffra.setApprovalMode(answer.mode);
|
|
67
|
+
const file = planFile;
|
|
68
|
+
planFile = undefined;
|
|
69
|
+
if (answer.goal) {
|
|
70
|
+
// `/goal` runs at once, even mid-run; its continuations start when this run settles.
|
|
71
|
+
diffra.sendUserMessage(`/goal set ${goalObjective(plan, file)}`, { expandPromptTemplates: true });
|
|
72
|
+
}
|
|
73
|
+
const result = approved(answer.mode, answer.goal);
|
|
74
|
+
if (edited === undefined)
|
|
75
|
+
return result;
|
|
76
|
+
return {
|
|
77
|
+
...result,
|
|
78
|
+
content: [
|
|
79
|
+
{
|
|
80
|
+
type: "text",
|
|
81
|
+
text: `${result.content[0].text}\n\nThe user edited the plan before approving it. Follow this version:\n\n${edited}`,
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
}
|
|
29
86
|
return {
|
|
30
87
|
name: EXIT_PLAN_MODE_TOOL_NAME,
|
|
31
88
|
label: "ExitPlanMode",
|
|
@@ -33,20 +90,19 @@ export function createExitPlanModeToolDefinition(diffra, options) {
|
|
|
33
90
|
parameters: exitPlanModeSchema,
|
|
34
91
|
defaultActive: false,
|
|
35
92
|
executionMode: "sequential",
|
|
36
|
-
async execute(
|
|
93
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
37
94
|
const mode = diffra.getApprovalMode();
|
|
38
95
|
if (mode !== "plan") {
|
|
39
96
|
throw new Error(`You are not in plan mode (current mode: ${mode}). The user may have manually switched modes via ${options.cycleKeyText()} or /approval-mode. Do not call ${EXIT_PLAN_MODE_TOOL_NAME} again. Continue working in the current mode.`);
|
|
40
97
|
}
|
|
41
98
|
if (params.plan.trim() === "")
|
|
42
99
|
throw new Error("The plan parameter must contain your actual plan; empty plans are rejected.");
|
|
43
|
-
const notApproved = (text) => ({
|
|
44
|
-
content: [{ type: "text", text }],
|
|
45
|
-
details: { approved: false },
|
|
46
|
-
});
|
|
47
100
|
if (!ctx.hasUI)
|
|
48
101
|
return notApproved("Plan execution was not approved: no approval surface is available. Remaining in plan mode.");
|
|
49
102
|
const previous = readApprovalModeState(ctx.sessionManager.getBranch())?.prePlanMode ?? "default";
|
|
103
|
+
if (ctx.ui.approvePlan) {
|
|
104
|
+
return approveWithHost({ toolCallId, plan: params.plan, previous }, ctx.ui.approvePlan, signal, ctx);
|
|
105
|
+
}
|
|
50
106
|
const choices = [
|
|
51
107
|
{ label: `Yes, restore the previous mode (${APPROVAL_MODE_INFO[previous].name})`, mode: previous },
|
|
52
108
|
{ label: "Yes, and auto-accept edits", mode: "auto-edit" },
|
|
@@ -56,21 +112,12 @@ export function createExitPlanModeToolDefinition(diffra, options) {
|
|
|
56
112
|
const answer = await ctx.ui.select("Would you like to proceed?", choices.map((choice) => choice.label), { signal });
|
|
57
113
|
const target = choices.find((choice) => choice.label === answer)?.mode;
|
|
58
114
|
if (target === undefined || signal?.aborted)
|
|
59
|
-
return notApproved(
|
|
60
|
-
if (diffra.getApprovalMode() !== "plan")
|
|
61
|
-
return notApproved(
|
|
62
|
-
}
|
|
115
|
+
return notApproved(NOT_APPROVED);
|
|
116
|
+
if (diffra.getApprovalMode() !== "plan")
|
|
117
|
+
return notApproved(STALE);
|
|
63
118
|
options.onApproved();
|
|
64
119
|
diffra.setApprovalMode(target);
|
|
65
|
-
return
|
|
66
|
-
content: [
|
|
67
|
-
{
|
|
68
|
-
type: "text",
|
|
69
|
-
text: "User approved. You can now start coding. Start with updating your todo list if applicable.",
|
|
70
|
-
},
|
|
71
|
-
],
|
|
72
|
-
details: { approved: true, mode: target },
|
|
73
|
-
};
|
|
120
|
+
return approved(target, false);
|
|
74
121
|
},
|
|
75
122
|
renderCall(args, theme, context) {
|
|
76
123
|
const container = context.lastComponent ?? new Container();
|
|
@@ -87,7 +134,7 @@ export function createExitPlanModeToolDefinition(diffra, options) {
|
|
|
87
134
|
text.setText(theme.fg("error", result.content.find((part) => part.type === "text")?.text ?? ""));
|
|
88
135
|
}
|
|
89
136
|
else if (details.approved) {
|
|
90
|
-
text.setText(theme.fg("success", `Plan approved, continuing in ${APPROVAL_MODE_INFO[details.mode].name} mode`));
|
|
137
|
+
text.setText(theme.fg("success", `Plan approved, continuing in ${APPROVAL_MODE_INFO[details.mode].name} mode${details.goal ? " as a goal" : ""}`));
|
|
91
138
|
}
|
|
92
139
|
else {
|
|
93
140
|
text.setText(theme.fg("warning", "Plan not approved, still in plan mode"));
|
|
@@ -96,4 +143,69 @@ export function createExitPlanModeToolDefinition(diffra, options) {
|
|
|
96
143
|
},
|
|
97
144
|
};
|
|
98
145
|
}
|
|
146
|
+
const NOT_APPROVED = "Plan execution was not approved. Remaining in plan mode.";
|
|
147
|
+
const STALE = "Plan approval is stale because the approval mode changed. No action was taken.";
|
|
148
|
+
function notApproved(text) {
|
|
149
|
+
return { content: [{ type: "text", text }], details: { approved: false } };
|
|
150
|
+
}
|
|
151
|
+
function approved(mode, goal) {
|
|
152
|
+
return {
|
|
153
|
+
content: [
|
|
154
|
+
{
|
|
155
|
+
type: "text",
|
|
156
|
+
text: "User approved. You can now start coding. Start with updating your todo list if applicable.",
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
details: { approved: true, mode, goal },
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Write the plan to `.diffra/plans/` in the project, into `existing` when it is a revision. Returns
|
|
164
|
+
* undefined when the folder cannot be written; the plan is still in the tool call.
|
|
165
|
+
*/
|
|
166
|
+
async function savePlan(plan, cwd, existing) {
|
|
167
|
+
const file = existing ?? freePlanPath(join(cwd, CONFIG_DIR_NAME, "plans"), planSlug(plan));
|
|
168
|
+
try {
|
|
169
|
+
await mkdir(dirname(file), { recursive: true });
|
|
170
|
+
await writeFile(file, plan, "utf-8");
|
|
171
|
+
return file;
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** The plan file's content when the user changed it, or undefined when it is unchanged or unreadable. */
|
|
178
|
+
async function readEditedPlan(file, plan) {
|
|
179
|
+
try {
|
|
180
|
+
const content = (await readFile(file, "utf-8")).replace(/\r\n/g, "\n");
|
|
181
|
+
return content.trim() !== plan.replace(/\r\n/g, "\n").trim() && content.trim() !== "" ? content : undefined;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const MAX_SLUG_LENGTH = 48;
|
|
188
|
+
/** A file name from the plan's first line or heading, such as `ipc-layer` for "# IPC layer". */
|
|
189
|
+
function planSlug(plan) {
|
|
190
|
+
const title = plan
|
|
191
|
+
.split("\n")
|
|
192
|
+
.map((line) => line.replace(/^#+\s*/, "").trim())
|
|
193
|
+
.find((line) => line !== "");
|
|
194
|
+
const slug = (title ?? "")
|
|
195
|
+
.toLowerCase()
|
|
196
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
197
|
+
.slice(0, MAX_SLUG_LENGTH)
|
|
198
|
+
.replace(/^-+|-+$/g, "");
|
|
199
|
+
return slug || "plan";
|
|
200
|
+
}
|
|
201
|
+
function freePlanPath(dir, slug) {
|
|
202
|
+
for (let index = 1;; index++) {
|
|
203
|
+
const file = join(dir, index === 1 ? `${slug}.md` : `${slug}-${index}.md`);
|
|
204
|
+
if (!existsSync(file))
|
|
205
|
+
return file;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function goalObjective(plan, planFile) {
|
|
209
|
+
return `Carry out the approved plan${planFile ? ` (saved in ${planFile})` : ""}: ${plan}`;
|
|
210
|
+
}
|
|
99
211
|
//# sourceMappingURL=exit-plan-mode.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exit-plan-mode.js","sourceRoot":"","sources":["../../../src/extensions/approval/exit-plan-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAqB,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAE3G,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC;IACtC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC;QACjB,WAAW,EACV,oMAAoM;KACrM,CAAC;CAC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ourcesContent":["/**\n * The `exit_plan_mode` tool: the model presents its plan, and the user approves it, choosing the mode\n * to continue in, or keeps planning. Only the user's answer in the dialog approves a plan.\n */\n\nimport { Container, Markdown, Text } from \"@diffra-ai/tui\";\nimport { Type } from \"typebox\";\nimport { APPROVAL_MODE_INFO, type ApprovalMode, readApprovalModeState } from \"../../core/approval-mode.ts\";\nimport type { ExtensionAPI, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getMarkdownTheme } from \"../../modes/interactive/theme/theme.ts\";\nimport { EXIT_PLAN_MODE_TOOL_NAME } from \"./policy.ts\";\n\nconst exitPlanModeSchema = Type.Object({\n\tplan: Type.String({\n\t\tdescription:\n\t\t\t\"The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise. Must contain your actual plan content; empty strings are rejected.\",\n\t}),\n});\n\nconst DESCRIPTION = `Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.\n\n## When to Use This Tool\nIMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase, do NOT use this tool.\n\n## Before Using This Tool\nEnsure your plan is complete and unambiguous:\n- If you have unresolved questions about requirements or approach, ask the user first\n- The plan parameter MUST contain your actual plan content; empty strings will be rejected\n- Once your plan is finalized, use THIS tool to request approval\n\nDo NOT ask \"Is this plan okay?\" or \"Should I proceed?\" in prose; that is exactly what this tool does.`;\n\n/** `details` of an `exit_plan_mode` result: whether the plan was approved, and the mode chosen. */\nexport type ExitPlanModeDetails = { approved: true; mode: ApprovalMode } | { approved: false };\n\n/** Create `exit_plan_mode`. `onApproved` runs before the mode changes, so the change is not reported as manual. */\nexport function createExitPlanModeToolDefinition(\n\tdiffra: ExtensionAPI,\n\toptions: { onApproved(): void; cycleKeyText(): string },\n): ToolDefinition<typeof exitPlanModeSchema, ExitPlanModeDetails> {\n\treturn {\n\t\tname: EXIT_PLAN_MODE_TOOL_NAME,\n\t\tlabel: \"ExitPlanMode\",\n\t\tdescription: DESCRIPTION,\n\t\tparameters: exitPlanModeSchema,\n\t\tdefaultActive: false,\n\t\texecutionMode: \"sequential\",\n\t\tasync execute(_toolCallId, params, signal, _onUpdate, ctx) {\n\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\tif (mode !== \"plan\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`You are not in plan mode (current mode: ${mode}). The user may have manually switched modes via ${options.cycleKeyText()} or /approval-mode. Do not call ${EXIT_PLAN_MODE_TOOL_NAME} again. Continue working in the current mode.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.plan.trim() === \"\")\n\t\t\t\tthrow new Error(\"The plan parameter must contain your actual plan; empty plans are rejected.\");\n\t\t\tconst notApproved = (text: string) => ({\n\t\t\t\tcontent: [{ type: \"text\" as const, text }],\n\t\t\t\tdetails: { approved: false as const },\n\t\t\t});\n\t\t\tif (!ctx.hasUI)\n\t\t\t\treturn notApproved(\n\t\t\t\t\t\"Plan execution was not approved: no approval surface is available. Remaining in plan mode.\",\n\t\t\t\t);\n\n\t\t\tconst previous = readApprovalModeState(ctx.sessionManager.getBranch())?.prePlanMode ?? \"default\";\n\t\t\tconst choices: Array<{ label: string; mode: ApprovalMode | undefined }> = [\n\t\t\t\t{ label: `Yes, restore the previous mode (${APPROVAL_MODE_INFO[previous].name})`, mode: previous },\n\t\t\t\t{ label: \"Yes, and auto-accept edits\", mode: \"auto-edit\" },\n\t\t\t\t{ label: \"Yes, and manually approve edits\", mode: \"default\" },\n\t\t\t\t{ label: \"No, keep planning\", mode: undefined },\n\t\t\t];\n\t\t\tconst answer = await ctx.ui.select(\n\t\t\t\t\"Would you like to proceed?\",\n\t\t\t\tchoices.map((choice) => choice.label),\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tconst target = choices.find((choice) => choice.label === answer)?.mode;\n\t\t\tif (target === undefined || signal?.aborted)\n\t\t\t\treturn notApproved(\"Plan execution was not approved. Remaining in plan mode.\");\n\t\t\tif (diffra.getApprovalMode() !== \"plan\") {\n\t\t\t\treturn notApproved(\"Plan approval is stale because the approval mode changed. No action was taken.\");\n\t\t\t}\n\t\t\toptions.onApproved();\n\t\t\tdiffra.setApprovalMode(target);\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"User approved. You can now start coding. Start with updating your todo list if applicable.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { approved: true, mode: target },\n\t\t\t};\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst container = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcontainer.clear();\n\t\t\tcontainer.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(EXIT_PLAN_MODE_TOOL_NAME)), 0, 0));\n\t\t\tif (args.plan) container.addChild(new Markdown(args.plan, 0, 0, getMarkdownTheme()));\n\t\t\treturn container;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst details = result.details;\n\t\t\tif (context.isError || !details) {\n\t\t\t\ttext.setText(theme.fg(\"error\", result.content.find((part) => part.type === \"text\")?.text ?? \"\"));\n\t\t\t} else if (details.approved) {\n\t\t\t\ttext.setText(\n\t\t\t\t\ttheme.fg(\"success\", `Plan approved, continuing in ${APPROVAL_MODE_INFO[details.mode].name} mode`),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttext.setText(theme.fg(\"warning\", \"Plan not approved, still in plan mode\"));\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"exit-plan-mode.js","sourceRoot":"","sources":["../../../src/extensions/approval/exit-plan-mode.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,KAAK,EAA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AAI,KAAK,GAAG,CAAC,GAAI,KAAK,EAAE,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC;QAC3E,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;IACpC,CAAC;AACF,CAAC;AAED,SAAS,aAAa,CAAC,IAAY,EAAE,QAA4B;IAChE,OAAO,8BAA8B,QAAQ,CAAC,CAAC,CAAC,cAAc,QAAQ,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC;AAC3F,CAAC","sourcesContent":["/**\n * The `exit_plan_mode` tool: the model presents its plan, and the user approves it, choosing the mode\n * to continue in, or keeps planning. Only the user's answer in the dialog approves a plan.\n *\n * Hosts that render plan approvals get the plan as a file in the project's `.diffra/plans/`, which the\n * user may edit before approving, and can also run the plan as a goal and pick the model to implement it.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { Container, Markdown, Text } from \"@diffra-ai/tui\";\nimport { Type } from \"typebox\";\nimport { CONFIG_DIR_NAME } from \"../../config.ts\";\nimport { APPROVAL_MODE_INFO, type ApprovalMode, readApprovalModeState } from \"../../core/approval-mode.ts\";\nimport type { ExtensionAPI, ExtensionContext, ToolDefinition } from \"../../core/extensions/types.ts\";\nimport { getMarkdownTheme } from \"../../modes/interactive/theme/theme.ts\";\nimport { EXIT_PLAN_MODE_TOOL_NAME } from \"./policy.ts\";\n\nconst exitPlanModeSchema = Type.Object({\n\tplan: Type.String({\n\t\tdescription:\n\t\t\t\"The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise. Must contain your actual plan content; empty strings are rejected.\",\n\t}),\n});\n\nconst DESCRIPTION = `Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode.\n\n## When to Use This Tool\nIMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase, do NOT use this tool.\n\n## Before Using This Tool\nEnsure your plan is complete and unambiguous:\n- If you have unresolved questions about requirements or approach, ask the user first\n- The plan parameter MUST contain your actual plan content; empty strings will be rejected\n- Once your plan is finalized, use THIS tool to request approval\n\nDo NOT ask \"Is this plan okay?\" or \"Should I proceed?\" in prose; that is exactly what this tool does.`;\n\n/** `details` of an `exit_plan_mode` result: whether the plan was approved, the mode chosen, and whether it runs as a goal. */\nexport type ExitPlanModeDetails = { approved: true; mode: ApprovalMode; goal: boolean } | { approved: false };\n\ntype ExitPlanModeResult = { content: Array<{ type: \"text\"; text: string }>; details: ExitPlanModeDetails };\n\n/** Create `exit_plan_mode`. `onApproved` runs before the mode changes, so the change is not reported as manual. */\nexport function createExitPlanModeToolDefinition(\n\tdiffra: ExtensionAPI,\n\toptions: { onApproved(): void; cycleKeyText(): string },\n): ToolDefinition<typeof exitPlanModeSchema, ExitPlanModeDetails> {\n\t// Revisions of a plan replace its file; the next plan after an approval gets a file of its own.\n\tlet planFile: string | undefined;\n\n\t/** Ask a host that renders plan approvals; it may also run the plan as a goal and switch the model. */\n\tasync function approveWithHost(\n\t\trequest: { toolCallId: string; plan: string; previous: ApprovalMode },\n\t\tapprovePlan: NonNullable<ExtensionContext[\"ui\"][\"approvePlan\"]>,\n\t\tsignal: AbortSignal | undefined,\n\t\tctx: ExtensionContext,\n\t): Promise<ExitPlanModeResult> {\n\t\tplanFile = await savePlan(request.plan, ctx.cwd, planFile);\n\t\tconst answer = await approvePlan(\n\t\t\t{\n\t\t\t\ttoolCallId: request.toolCallId,\n\t\t\t\tplan: request.plan,\n\t\t\t\tplanFile,\n\t\t\t\tpreviousMode: request.previous,\n\t\t\t\tcanRunAsGoal: diffra.getCommands().some((command) => command.name === \"goal\"),\n\t\t\t},\n\t\t\t{ signal },\n\t\t);\n\t\tif (answer === undefined || signal?.aborted) return notApproved(NOT_APPROVED);\n\t\tif (answer.kind === \"keep-planning\") {\n\t\t\tconst feedback = answer.feedback?.trim();\n\t\t\treturn notApproved(\n\t\t\t\tfeedback\n\t\t\t\t\t? `The user wants to keep planning and said: ${feedback}\\n\\nRevise the plan, then call ${EXIT_PLAN_MODE_TOOL_NAME} again.`\n\t\t\t\t\t: NOT_APPROVED,\n\t\t\t);\n\t\t}\n\t\tif (diffra.getApprovalMode() !== \"plan\") return notApproved(STALE);\n\t\tconst edited = planFile ? await readEditedPlan(planFile, request.plan) : undefined;\n\t\tconst plan = edited ?? request.plan;\n\t\tconst model = answer.model && ctx.modelRegistry.find(answer.model.provider, answer.model.id);\n\t\tif (model) await diffra.setModel(model);\n\t\tif (answer.thinkingLevel) diffra.setThinkingLevel(answer.thinkingLevel);\n\t\toptions.onApproved();\n\t\tdiffra.setApprovalMode(answer.mode);\n\t\tconst file = planFile;\n\t\tplanFile = undefined;\n\t\tif (answer.goal) {\n\t\t\t// `/goal` runs at once, even mid-run; its continuations start when this run settles.\n\t\t\tdiffra.sendUserMessage(`/goal set ${goalObjective(plan, file)}`, { expandPromptTemplates: true });\n\t\t}\n\t\tconst result = approved(answer.mode, answer.goal);\n\t\tif (edited === undefined) return result;\n\t\treturn {\n\t\t\t...result,\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `${result.content[0].text}\\n\\nThe user edited the plan before approving it. Follow this version:\\n\\n${edited}`,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\treturn {\n\t\tname: EXIT_PLAN_MODE_TOOL_NAME,\n\t\tlabel: \"ExitPlanMode\",\n\t\tdescription: DESCRIPTION,\n\t\tparameters: exitPlanModeSchema,\n\t\tdefaultActive: false,\n\t\texecutionMode: \"sequential\",\n\t\tasync execute(toolCallId, params, signal, _onUpdate, ctx) {\n\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\tif (mode !== \"plan\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`You are not in plan mode (current mode: ${mode}). The user may have manually switched modes via ${options.cycleKeyText()} or /approval-mode. Do not call ${EXIT_PLAN_MODE_TOOL_NAME} again. Continue working in the current mode.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.plan.trim() === \"\")\n\t\t\t\tthrow new Error(\"The plan parameter must contain your actual plan; empty plans are rejected.\");\n\t\t\tif (!ctx.hasUI)\n\t\t\t\treturn notApproved(\n\t\t\t\t\t\"Plan execution was not approved: no approval surface is available. Remaining in plan mode.\",\n\t\t\t\t);\n\n\t\t\tconst previous = readApprovalModeState(ctx.sessionManager.getBranch())?.prePlanMode ?? \"default\";\n\t\t\tif (ctx.ui.approvePlan) {\n\t\t\t\treturn approveWithHost({ toolCallId, plan: params.plan, previous }, ctx.ui.approvePlan, signal, ctx);\n\t\t\t}\n\t\t\tconst choices: Array<{ label: string; mode: ApprovalMode | undefined }> = [\n\t\t\t\t{ label: `Yes, restore the previous mode (${APPROVAL_MODE_INFO[previous].name})`, mode: previous },\n\t\t\t\t{ label: \"Yes, and auto-accept edits\", mode: \"auto-edit\" },\n\t\t\t\t{ label: \"Yes, and manually approve edits\", mode: \"default\" },\n\t\t\t\t{ label: \"No, keep planning\", mode: undefined },\n\t\t\t];\n\t\t\tconst answer = await ctx.ui.select(\n\t\t\t\t\"Would you like to proceed?\",\n\t\t\t\tchoices.map((choice) => choice.label),\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tconst target = choices.find((choice) => choice.label === answer)?.mode;\n\t\t\tif (target === undefined || signal?.aborted) return notApproved(NOT_APPROVED);\n\t\t\tif (diffra.getApprovalMode() !== \"plan\") return notApproved(STALE);\n\t\t\toptions.onApproved();\n\t\t\tdiffra.setApprovalMode(target);\n\t\t\treturn approved(target, false);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst container = (context.lastComponent as Container | undefined) ?? new Container();\n\t\t\tcontainer.clear();\n\t\t\tcontainer.addChild(new Text(theme.fg(\"toolTitle\", theme.bold(EXIT_PLAN_MODE_TOOL_NAME)), 0, 0));\n\t\t\tif (args.plan) container.addChild(new Markdown(args.plan, 0, 0, getMarkdownTheme()));\n\t\t\treturn container;\n\t\t},\n\t\trenderResult(result, _options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst details = result.details;\n\t\t\tif (context.isError || !details) {\n\t\t\t\ttext.setText(theme.fg(\"error\", result.content.find((part) => part.type === \"text\")?.text ?? \"\"));\n\t\t\t} else if (details.approved) {\n\t\t\t\ttext.setText(\n\t\t\t\t\ttheme.fg(\n\t\t\t\t\t\t\"success\",\n\t\t\t\t\t\t`Plan approved, continuing in ${APPROVAL_MODE_INFO[details.mode].name} mode${details.goal ? \" as a goal\" : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttext.setText(theme.fg(\"warning\", \"Plan not approved, still in plan mode\"));\n\t\t\t}\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nconst NOT_APPROVED = \"Plan execution was not approved. Remaining in plan mode.\";\nconst STALE = \"Plan approval is stale because the approval mode changed. No action was taken.\";\n\nfunction notApproved(text: string): ExitPlanModeResult {\n\treturn { content: [{ type: \"text\", text }], details: { approved: false } };\n}\n\nfunction approved(mode: ApprovalMode, goal: boolean): ExitPlanModeResult {\n\treturn {\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"User approved. You can now start coding. Start with updating your todo list if applicable.\",\n\t\t\t},\n\t\t],\n\t\tdetails: { approved: true, mode, goal },\n\t};\n}\n\n/**\n * Write the plan to `.diffra/plans/` in the project, into `existing` when it is a revision. Returns\n * undefined when the folder cannot be written; the plan is still in the tool call.\n */\nasync function savePlan(plan: string, cwd: string, existing: string | undefined): Promise<string | undefined> {\n\tconst file = existing ?? freePlanPath(join(cwd, CONFIG_DIR_NAME, \"plans\"), planSlug(plan));\n\ttry {\n\t\tawait mkdir(dirname(file), { recursive: true });\n\t\tawait writeFile(file, plan, \"utf-8\");\n\t\treturn file;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The plan file's content when the user changed it, or undefined when it is unchanged or unreadable. */\nasync function readEditedPlan(file: string, plan: string): Promise<string | undefined> {\n\ttry {\n\t\tconst content = (await readFile(file, \"utf-8\")).replace(/\\r\\n/g, \"\\n\");\n\t\treturn content.trim() !== plan.replace(/\\r\\n/g, \"\\n\").trim() && content.trim() !== \"\" ? content : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst MAX_SLUG_LENGTH = 48;\n\n/** A file name from the plan's first line or heading, such as `ipc-layer` for \"# IPC layer\". */\nfunction planSlug(plan: string): string {\n\tconst title = plan\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.replace(/^#+\\s*/, \"\").trim())\n\t\t.find((line) => line !== \"\");\n\tconst slug = (title ?? \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.slice(0, MAX_SLUG_LENGTH)\n\t\t.replace(/^-+|-+$/g, \"\");\n\treturn slug || \"plan\";\n}\n\nfunction freePlanPath(dir: string, slug: string): string {\n\tfor (let index = 1; ; index++) {\n\t\tconst file = join(dir, index === 1 ? `${slug}.md` : `${slug}-${index}.md`);\n\t\tif (!existsSync(file)) return file;\n\t}\n}\n\nfunction goalObjective(plan: string, planFile: string | undefined): string {\n\treturn `Carry out the approved plan${planFile ? ` (saved in ${planFile})` : \"\"}: ${plan}`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/approval/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/approval/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgBH,OAAO,KAAK,EAGX,gBAAgB,EAGhB,MAAM,gCAAgC,CAAC;AAuBxC,qCAAqC;AACrC,wBAAgB,uBAAuB,IAAI,gBAAgB,CA+R1D"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* it, and adds the `/approval-mode` and `/plan` commands and the `--approval-mode` flag.
|
|
9
9
|
*/
|
|
10
10
|
import { APPROVAL_MODE_INFO, APPROVAL_MODES, isApprovalMode, readApprovalModeState, } from "../../core/approval-mode.js";
|
|
11
|
+
import { createToolCallApproval, } from "../../core/decisions.js";
|
|
11
12
|
import { resolveFastModel } from "../../core/fast-model.js";
|
|
12
13
|
import { SETTINGS_DEFAULTS } from "../../core/settings-defaults.js";
|
|
13
14
|
import { keyText } from "../../modes/interactive/components/keybinding-hints.js";
|
|
@@ -176,18 +177,19 @@ export function createApprovalExtension() {
|
|
|
176
177
|
reason: `This ${call.toolName} call needs approval, but agents running in the background cannot ask the user, so it was denied. Run the agent in the foreground (run_in_background: false) to approve its calls.`,
|
|
177
178
|
};
|
|
178
179
|
}
|
|
179
|
-
return ask(decision, call, ctx, evaluate);
|
|
180
|
+
return ask(decision, call, event.toolCallId, ctx, evaluate);
|
|
180
181
|
});
|
|
181
182
|
/** Run the classifier; after repeated blocks or outages the user decides instead. */
|
|
182
183
|
async function classify(call, ctx) {
|
|
183
|
-
const manual = {
|
|
184
|
+
const manual = (cause, title) => ({
|
|
184
185
|
kind: "ask",
|
|
185
|
-
title
|
|
186
|
+
title,
|
|
187
|
+
cause,
|
|
186
188
|
remember: undefined,
|
|
187
|
-
};
|
|
189
|
+
});
|
|
188
190
|
if (unavailable >= MAX_UNAVAILABLE) {
|
|
189
191
|
unavailable = 0;
|
|
190
|
-
return manual;
|
|
192
|
+
return manual({ kind: "auto-unavailable" }, `Auto mode cannot approve this ${call.toolName} call on its own. Allow it?\n\n ${JSON.stringify(call.input).slice(0, 300)}`);
|
|
191
193
|
}
|
|
192
194
|
const settings = diffra.getSettings();
|
|
193
195
|
const model = resolveFastModel(settings, ctx.modelRegistry, ctx.model);
|
|
@@ -212,18 +214,18 @@ export function createApprovalExtension() {
|
|
|
212
214
|
blocks++;
|
|
213
215
|
if (blocks >= MAX_BLOCKS) {
|
|
214
216
|
blocks = 0;
|
|
215
|
-
return {
|
|
216
|
-
...manual,
|
|
217
|
-
title: `Auto mode blocked this ${MAX_BLOCKS} times in a row: ${verdict.reason}\n\nAllow this ${call.toolName} call?`,
|
|
218
|
-
};
|
|
217
|
+
return manual({ kind: "auto-blocked", reason: verdict.reason }, `Auto mode blocked this ${MAX_BLOCKS} times in a row: ${verdict.reason}\n\nAllow this ${call.toolName} call?`);
|
|
219
218
|
}
|
|
220
219
|
return {
|
|
221
220
|
kind: "block",
|
|
222
221
|
reason: `Auto mode blocked this action: ${verdict.reason}. Do not retry it through wrappers; choose a safer approach or ask the user.`,
|
|
223
222
|
};
|
|
224
223
|
}
|
|
225
|
-
/**
|
|
226
|
-
|
|
224
|
+
/**
|
|
225
|
+
* Ask the user, one dialog at a time; an earlier answer may already allow this call. Hosts that
|
|
226
|
+
* render approvals get the structured request, others a `select`.
|
|
227
|
+
*/
|
|
228
|
+
async function ask(decision, call, toolCallId, ctx, evaluate) {
|
|
227
229
|
if (!ctx.hasUI) {
|
|
228
230
|
const mode = diffra.getApprovalMode();
|
|
229
231
|
return {
|
|
@@ -240,18 +242,28 @@ export function createApprovalExtension() {
|
|
|
240
242
|
if (current.kind === "block")
|
|
241
243
|
return { block: true, reason: current.reason };
|
|
242
244
|
const prompt = current.kind === "ask" ? current : decision;
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
245
|
+
const answer = ctx.ui.approve
|
|
246
|
+
? await ctx.ui.approve(await createToolCallApproval({
|
|
247
|
+
title: prompt.title,
|
|
248
|
+
toolName: call.toolName,
|
|
249
|
+
toolCallId,
|
|
250
|
+
input: call.input,
|
|
251
|
+
cause: prompt.cause,
|
|
252
|
+
remember: prompt.remember,
|
|
253
|
+
}, diffra.getSettings(), ctx), { signal: ctx.signal })
|
|
254
|
+
: await answerWithSelect(prompt, ctx);
|
|
255
|
+
if (answer?.kind === "once")
|
|
249
256
|
return undefined;
|
|
250
|
-
if (answer
|
|
251
|
-
|
|
257
|
+
if (answer?.kind === "always") {
|
|
258
|
+
if (prompt.remember)
|
|
259
|
+
remember(prompt.remember);
|
|
252
260
|
return undefined;
|
|
253
261
|
}
|
|
254
|
-
|
|
262
|
+
const feedback = answer?.feedback?.trim();
|
|
263
|
+
return {
|
|
264
|
+
block: true,
|
|
265
|
+
reason: `The user denied this ${call.toolName} call.${feedback ? ` The user said: ${feedback}` : ""}`,
|
|
266
|
+
};
|
|
255
267
|
});
|
|
256
268
|
dialogs = turn.catch(() => undefined);
|
|
257
269
|
return turn;
|
|
@@ -263,19 +275,30 @@ export function createApprovalExtension() {
|
|
|
263
275
|
for (const root of choice.roots)
|
|
264
276
|
approvals.shellRoots.add(root);
|
|
265
277
|
else
|
|
266
|
-
|
|
278
|
+
approvals.edits = true;
|
|
267
279
|
}
|
|
268
280
|
};
|
|
269
281
|
}
|
|
270
282
|
function newApprovals() {
|
|
271
|
-
return { tools: new Set(), shellRoots: new Set() };
|
|
283
|
+
return { tools: new Set(), shellRoots: new Set(), edits: false };
|
|
284
|
+
}
|
|
285
|
+
/** Ask with `select`, for hosts that do not render approvals. */
|
|
286
|
+
async function answerWithSelect(prompt, ctx) {
|
|
287
|
+
const once = "Yes, allow once";
|
|
288
|
+
const always = prompt.remember ? rememberLabel(prompt.remember) : undefined;
|
|
289
|
+
const answer = await ctx.ui.select(prompt.title, [once, ...(always ? [always] : []), "No"], { signal: ctx.signal });
|
|
290
|
+
if (answer === undefined)
|
|
291
|
+
return undefined;
|
|
292
|
+
if (answer === once)
|
|
293
|
+
return { kind: "once" };
|
|
294
|
+
return answer === always ? { kind: "always" } : { kind: "deny" };
|
|
272
295
|
}
|
|
273
296
|
function rememberLabel(choice) {
|
|
274
297
|
if (choice.kind === "tool")
|
|
275
298
|
return `Yes, always allow ${choice.name} this session`;
|
|
276
299
|
if (choice.kind === "shell")
|
|
277
300
|
return `Yes, always allow ${choice.roots.map((root) => `\`${root}\``).join(", ")} commands this session`;
|
|
278
|
-
return "Yes, allow all edits
|
|
301
|
+
return "Yes, allow all edits this session";
|
|
279
302
|
}
|
|
280
303
|
function toPolicyCall(diffra, event) {
|
|
281
304
|
const annotations = diffra.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/approval/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EACN,kBAAkB,EAClB,cAAc,EAEd,cAAc,EACd,qBAAqB,GACrB,MAAM,6BAA6B,CAAC;AAQrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,sBAAsB,EAAsB,MAAM,0BAA0B,CAAC;AACvH,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAEN,MAAM,EACN,wBAAwB,EACxB,wBAAwB,GAIxB,MAAM,aAAa,CAAC;AAErB,MAAM,UAAU,GAAG,eAAe,CAAC;AACnC,wFAAwF;AACxF,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,yGAAyG;AACzG,MAAM,UAAU,GAAG,CAAC,CAAC;AAErB,qCAAqC;AACrC,MAAM,UAAU,uBAAuB;IACtC,OAAO,CAAC,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C,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;iBACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;iBACxB,IAAI,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,eAAe,uBAAuB,EAAE,CAAC","sourcesContent":["/**\n * Approval modes as an extension. The CLI loads it as a built-in extension; SDK users add\n * `createApprovalExtension()` to their extension factories.\n *\n * The session holds the mode (`getApprovalMode()`); this extension enforces it on every tool call,\n * asks the user in a dialog where the mode requires it and remembers \"always allow\" answers for the\n * session, runs the auto-mode classifier, keeps plan mode read-only with `exit_plan_mode` to leave\n * it, and adds the `/approval-mode` and `/plan` commands and the `--approval-mode` flag.\n */\n\nimport type { AgentMessage } from \"@diffra-ai/agent-core\";\nimport {\n\tAPPROVAL_MODE_INFO,\n\tAPPROVAL_MODES,\n\ttype ApprovalMode,\n\tisApprovalMode,\n\treadApprovalModeState,\n} from \"../../core/approval-mode.ts\";\nimport type {\n\tExtensionAPI,\n\tExtensionContext,\n\tExtensionFactory,\n\tToolCallEvent,\n\tToolCallEventResult,\n} from \"../../core/extensions/types.ts\";\nimport { resolveFastModel } from \"../../core/fast-model.ts\";\nimport { SETTINGS_DEFAULTS } from \"../../core/settings-defaults.ts\";\nimport { keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { findScope, isSubagentScopeEvent, SUBAGENT_SCOPE_CHANNEL, type SubagentScope } from \"../agents/call-scopes.ts\";\nimport { classifyAction } from \"./auto-classifier.ts\";\nimport { createExitPlanModeToolDefinition } from \"./exit-plan-mode.ts\";\nimport { manualPlanExitReminder, PLAN_MODE_REMINDER } from \"./plan-reminders.ts\";\nimport {\n\ttype ApprovalDecision,\n\tdecide,\n\tEXIT_PLAN_MODE_TOOL_NAME,\n\tPLAN_NO_APPROVAL_MESSAGE,\n\ttype PolicyCall,\n\ttype Remember,\n\ttype SessionApprovals,\n} from \"./policy.ts\";\n\nconst STATUS_KEY = \"approval-mode\";\n/** Unavailable classifier answers in a row after which calls go to the user instead. */\nconst MAX_UNAVAILABLE = 2;\n/** Classifier blocks in a row after which the next block goes to the user, so the agent is not stuck. */\nconst MAX_BLOCKS = 3;\n\n/** Create the approval extension. */\nexport function createApprovalExtension(): ExtensionFactory {\n\treturn (diffra) => {\n\t\tlet approvals = newApprovals();\n\t\tlet blocks = 0;\n\t\tlet unavailable = 0;\n\t\tlet approvedPlanExit = false;\n\t\tlet manualPlanExitPending = false;\n\t\tlet autoNoticeShown = false;\n\t\t// Dialogs run one at a time; parallel tool calls wait their turn.\n\t\tlet dialogs: Promise<unknown> = Promise.resolve();\n\t\t// Running subagents, by the id of their `agent` call; their calls follow the subagent's mode.\n\t\tconst scopes = new Map<string, SubagentScope>();\n\t\tdiffra.events.on(SUBAGENT_SCOPE_CHANNEL, (event) => {\n\t\t\tif (!isSubagentScopeEvent(event)) return;\n\t\t\tif (event.kind === \"start\")\n\t\t\t\tscopes.set(event.callId, { background: event.background, approvalMode: event.approvalMode });\n\t\t\telse scopes.delete(event.callId);\n\t\t});\n\n\t\tconst cycleKeyText = () => keyText(\"app.approvalMode.cycle\") || \"/approval-mode\";\n\t\tconst prePlanMode = (ctx: ExtensionContext) => readApprovalModeState(ctx.sessionManager.getBranch())?.prePlanMode;\n\n\t\tdiffra.registerFlag(\"approval-mode\", {\n\t\t\tdescription: \"Approval mode to start in: plan, default, auto-edit, auto, or yolo\",\n\t\t\ttype: \"string\",\n\t\t});\n\n\t\tdiffra.registerTool(\n\t\t\tcreateExitPlanModeToolDefinition(diffra, {\n\t\t\t\tonApproved: () => {\n\t\t\t\t\tapprovedPlanExit = true;\n\t\t\t\t},\n\t\t\t\tcycleKeyText,\n\t\t\t}),\n\t\t);\n\n\t\tdiffra.registerCommand(\"approval-mode\", {\n\t\t\tdescription: \"Show or change the approval mode (plan, default, auto-edit, auto, yolo)\",\n\t\t\tgetArgumentCompletions: (prefix) =>\n\t\t\t\t[...APPROVAL_MODES, \"--project\", \"--user\"]\n\t\t\t\t\t.filter((value) => value.startsWith(prefix.trim().split(/\\s+/).pop() ?? \"\"))\n\t\t\t\t\t.map((value) => ({ value, label: value })),\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst parts = args.trim().split(/\\s+/).filter(Boolean);\n\t\t\t\tconst persist = parts.includes(\"--project\") ? \"project\" : parts.includes(\"--user\") ? \"user\" : undefined;\n\t\t\t\tlet mode: string | undefined = parts.find((part) => !part.startsWith(\"--\"));\n\t\t\t\tif (mode === undefined) {\n\t\t\t\t\tconst current = diffra.getApprovalMode();\n\t\t\t\t\tif (!ctx.hasUI) {\n\t\t\t\t\t\tctx.ui.notify(`Approval mode: ${APPROVAL_MODE_INFO[current].name} (${current})`, \"info\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst labels = APPROVAL_MODES.map(\n\t\t\t\t\t\t(item) =>\n\t\t\t\t\t\t\t`${item === current ? \"● \" : \" \"}${APPROVAL_MODE_INFO[item].name} (${item}): ${APPROVAL_MODE_INFO[item].description}`,\n\t\t\t\t\t);\n\t\t\t\t\tconst answer = await ctx.ui.select(\"Approval mode\", labels);\n\t\t\t\t\tmode = APPROVAL_MODES[labels.indexOf(answer ?? \"\")];\n\t\t\t\t\tif (mode === undefined) return;\n\t\t\t\t}\n\t\t\t\tif (!isApprovalMode(mode)) {\n\t\t\t\t\tctx.ui.notify(`Unknown approval mode \"${mode}\". Use one of: ${APPROVAL_MODES.join(\", \")}.`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tdiffra.setApprovalMode(mode, { persist });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Approval mode: ${APPROVAL_MODE_INFO[mode].name}${persist ? ` (saved to ${persist} settings)` : \"\"}`,\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\tdiffra.registerCommand(\"plan\", {\n\t\t\tdescription: \"Enter plan mode, optionally with a request to plan; /plan exit restores the previous mode\",\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst text = args.trim();\n\t\t\t\tif (text === \"exit\") {\n\t\t\t\t\tif (diffra.getApprovalMode() !== \"plan\") {\n\t\t\t\t\t\tctx.ui.notify(\"Not in plan mode.\", \"info\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst mode = prePlanMode(ctx) ?? \"default\";\n\t\t\t\t\tdiffra.setApprovalMode(mode);\n\t\t\t\t\tctx.ui.notify(`Exited plan mode. Approval mode: ${APPROVAL_MODE_INFO[mode].name}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (diffra.getApprovalMode() !== \"plan\") {\n\t\t\t\t\tdiffra.setApprovalMode(\"plan\");\n\t\t\t\t\tctx.ui.notify(\"Plan mode: read-only until you approve a plan.\", \"info\");\n\t\t\t\t}\n\t\t\t\tif (text) diffra.sendUserMessage(text, ctx.isIdle() ? undefined : { deliverAs: \"followUp\" });\n\t\t\t},\n\t\t});\n\n\t\tdiffra.on(\"session_start\", (event, ctx) => {\n\t\t\tapprovals = newApprovals();\n\t\t\tblocks = 0;\n\t\t\tunavailable = 0;\n\t\t\tmanualPlanExitPending = false;\n\t\t\tconst flag = diffra.getFlag(\"approval-mode\");\n\t\t\tif (event.reason === \"startup\" && typeof flag === \"string\" && flag) {\n\t\t\t\tif (isApprovalMode(flag)) diffra.setApprovalMode(flag);\n\t\t\t\telse ctx.ui.notify(`Unknown --approval-mode \"${flag}\". Use one of: ${APPROVAL_MODES.join(\", \")}.`, \"error\");\n\t\t\t}\n\t\t\tsyncExitPlanTool(diffra);\n\t\t\tupdateStatus(ctx, diffra.getApprovalMode());\n\t\t});\n\n\t\tdiffra.on(\"approval_mode_change\", (event, ctx) => {\n\t\t\tif (event.previousMode === \"plan\" && !approvedPlanExit) manualPlanExitPending = true;\n\t\t\tif (event.mode === \"plan\") manualPlanExitPending = false;\n\t\t\tapprovedPlanExit = false;\n\t\t\tblocks = 0;\n\t\t\tunavailable = 0;\n\t\t\tsyncExitPlanTool(diffra);\n\t\t\tupdateStatus(ctx, event.mode);\n\t\t\tif (event.mode === \"auto\" && !autoNoticeShown && ctx.hasUI) {\n\t\t\t\tautoNoticeShown = true;\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Auto mode: a classifier model reviews shell commands, web access, edits outside the project, and other tools, and blocks risky ones. Read-only tools and edits inside the project run without review.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\tdiffra.on(\"context\", (event) => {\n\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\tconst reminder =\n\t\t\t\tmode === \"plan\" ? PLAN_MODE_REMINDER : manualPlanExitPending ? manualPlanExitReminder(mode) : undefined;\n\t\t\tif (!reminder) return undefined;\n\t\t\tmanualPlanExitPending = false;\n\t\t\tconst message: AgentMessage = {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: \"approval-mode-reminder\",\n\t\t\t\tcontent: reminder,\n\t\t\t\tdisplay: false,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\treturn { messages: [...event.messages, message] };\n\t\t});\n\n\t\tdiffra.on(\"tool_call\", async (event, ctx) => {\n\t\t\tconst call = toPolicyCall(diffra, event);\n\t\t\tconst scope = event.parentToolCallId ? findScope(scopes, event.toolCallId) : undefined;\n\t\t\tconst evaluate = () =>\n\t\t\t\tdecide(scope?.approvalMode ?? diffra.getApprovalMode(), call, approvals, {\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tclassifyAllShell: diffra.getSettings().permissions?.autoMode?.classifyAllShell === true,\n\t\t\t\t});\n\t\t\tlet decision = evaluate();\n\t\t\tif (decision.kind === \"classify\") decision = await classify(call, ctx);\n\t\t\tif (decision.kind === \"allow\") return undefined;\n\t\t\tif (decision.kind === \"block\") return { block: true, reason: decision.reason };\n\t\t\tif (scope?.background) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `This ${call.toolName} call needs approval, but agents running in the background cannot ask the user, so it was denied. Run the agent in the foreground (run_in_background: false) to approve its calls.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn ask(decision, call, ctx, evaluate);\n\t\t});\n\n\t\t/** Run the classifier; after repeated blocks or outages the user decides instead. */\n\t\tasync function classify(call: PolicyCall, ctx: ExtensionContext): Promise<ReviewedDecision> {\n\t\t\tconst manual: ReviewedDecision = {\n\t\t\t\tkind: \"ask\",\n\t\t\t\ttitle: `Auto mode cannot approve this ${call.toolName} call on its own. Allow it?\\n\\n ${JSON.stringify(call.input).slice(0, 300)}`,\n\t\t\t\tremember: undefined,\n\t\t\t};\n\t\t\tif (unavailable >= MAX_UNAVAILABLE) {\n\t\t\t\tunavailable = 0;\n\t\t\t\treturn manual;\n\t\t\t}\n\t\t\tconst settings = diffra.getSettings();\n\t\t\tconst model = resolveFastModel(settings, ctx.modelRegistry, ctx.model);\n\t\t\tconst timeoutMs =\n\t\t\t\tsettings.permissions?.autoMode?.classifier?.timeouts?.stage1Ms ??\n\t\t\t\tSETTINGS_DEFAULTS.autoModeClassifierTimeoutMs;\n\t\t\tconst verdict = model\n\t\t\t\t? await classifyAction(\n\t\t\t\t\t\t{ toolName: call.toolName, input: call.input, cwd: ctx.cwd, userRequest: latestUserRequest(ctx) },\n\t\t\t\t\t\tsettings.permissions?.autoMode,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tctx.modelRegistry,\n\t\t\t\t\t\t{ timeoutMs, signal: ctx.signal },\n\t\t\t\t\t)\n\t\t\t\t: { kind: \"unavailable\" as const, reason: \"no model is selected\" };\n\t\t\tif (verdict.kind === \"allow\") {\n\t\t\t\tblocks = 0;\n\t\t\t\tunavailable = 0;\n\t\t\t\treturn { kind: \"allow\" };\n\t\t\t}\n\t\t\tif (verdict.kind === \"unavailable\") {\n\t\t\t\tunavailable++;\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"block\",\n\t\t\t\t\treason: `Auto mode could not review this action (${verdict.reason}), so it was blocked. Do not retry it unchanged; continue with other work or ask the user.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tunavailable = 0;\n\t\t\tblocks++;\n\t\t\tif (blocks >= MAX_BLOCKS) {\n\t\t\t\tblocks = 0;\n\t\t\t\treturn {\n\t\t\t\t\t...manual,\n\t\t\t\t\ttitle: `Auto mode blocked this ${MAX_BLOCKS} times in a row: ${verdict.reason}\\n\\nAllow this ${call.toolName} call?`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"block\",\n\t\t\t\treason: `Auto mode blocked this action: ${verdict.reason}. Do not retry it through wrappers; choose a safer approach or ask the user.`,\n\t\t\t};\n\t\t}\n\n\t\t/** Ask the user, one dialog at a time; an earlier answer may already allow this call. */\n\t\tasync function ask(\n\t\t\tdecision: Extract<ApprovalDecision, { kind: \"ask\" }>,\n\t\t\tcall: PolicyCall,\n\t\t\tctx: ExtensionContext,\n\t\t\tevaluate: () => ApprovalDecision,\n\t\t): Promise<ToolCallEventResult | undefined> {\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason:\n\t\t\t\t\t\tmode === \"plan\"\n\t\t\t\t\t\t\t? PLAN_NO_APPROVAL_MESSAGE\n\t\t\t\t\t\t\t: `This ${call.toolName} call needs approval in ${APPROVAL_MODE_INFO[mode].name} mode, but no interactive UI is available to ask. It was not run.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst turn = dialogs.then(async () => {\n\t\t\t\tconst current = evaluate();\n\t\t\t\tif (current.kind === \"allow\") return undefined;\n\t\t\t\tif (current.kind === \"block\") return { block: true, reason: current.reason };\n\t\t\t\tconst prompt = current.kind === \"ask\" ? current : decision;\n\t\t\t\tconst once = \"Yes, allow once\";\n\t\t\t\tconst always = prompt.remember ? rememberLabel(prompt.remember) : undefined;\n\t\t\t\tconst answer = await ctx.ui.select(prompt.title, [once, ...(always ? [always] : []), \"No\"], {\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t});\n\t\t\t\tif (answer === once) return undefined;\n\t\t\t\tif (answer !== undefined && answer === always && prompt.remember) {\n\t\t\t\t\tremember(prompt.remember);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { block: true, reason: `The user denied this ${call.toolName} call.` };\n\t\t\t});\n\t\t\tdialogs = turn.catch(() => undefined);\n\t\t\treturn turn;\n\t\t}\n\n\t\tfunction remember(choice: Remember): void {\n\t\t\tif (choice.kind === \"tool\") approvals.tools.add(choice.name);\n\t\t\telse if (choice.kind === \"shell\") for (const root of choice.roots) approvals.shellRoots.add(root);\n\t\t\telse diffra.setApprovalMode(\"auto-edit\");\n\t\t}\n\t};\n}\n\n/** A decision after the classifier ran: allow, block, or ask the user. */\ntype ReviewedDecision = Exclude<ApprovalDecision, { kind: \"classify\" }>;\n\nfunction newApprovals(): SessionApprovals {\n\treturn { tools: new Set(), shellRoots: new Set() };\n}\n\nfunction rememberLabel(choice: Remember): string {\n\tif (choice.kind === \"tool\") return `Yes, always allow ${choice.name} this session`;\n\tif (choice.kind === \"shell\")\n\t\treturn `Yes, always allow ${choice.roots.map((root) => `\\`${root}\\``).join(\", \")} commands this session`;\n\treturn \"Yes, allow all edits (switch to Auto Edit)\";\n}\n\nfunction toPolicyCall(diffra: ExtensionAPI, event: ToolCallEvent): PolicyCall {\n\tconst annotations = diffra.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;\n\treturn {\n\t\ttoolName: event.toolName,\n\t\t// Validated tool arguments are always an object; the event types them per tool.\n\t\tinput: event.input as Record<string, unknown>,\n\t\treadOnlyHint: annotations?.readOnlyHint === true,\n\t\topenWorldHint: annotations?.openWorldHint === true,\n\t};\n}\n\n/** `exit_plan_mode` is declared to the model only in plan mode. */\nfunction syncExitPlanTool(diffra: ExtensionAPI): void {\n\tconst active = diffra.getActiveTools();\n\tconst declared = active.includes(EXIT_PLAN_MODE_TOOL_NAME);\n\tconst plan = diffra.getApprovalMode() === \"plan\";\n\tif (plan && !declared) diffra.setActiveTools([...active, EXIT_PLAN_MODE_TOOL_NAME]);\n\telse if (!plan && declared) diffra.setActiveTools(active.filter((name) => name !== EXIT_PLAN_MODE_TOOL_NAME));\n}\n\nconst STATUS_TEXT: Record<ApprovalMode, string | undefined> = {\n\tplan: \"⏸ plan mode\",\n\tdefault: \"⏸ ask permissions\",\n\t\"auto-edit\": \"⏵⏵ accept edits\",\n\tauto: \"⏵ auto mode\",\n\tyolo: undefined,\n};\n\nfunction updateStatus(ctx: ExtensionContext, mode: ApprovalMode): void {\n\tconst text = STATUS_TEXT[mode];\n\tctx.ui.setStatus(STATUS_KEY, text ? ctx.ui.theme.fg(mode === \"plan\" ? \"warning\" : \"accent\", text) : undefined);\n}\n\n/** The text of the latest user message on the branch, for the classifier. */\nfunction latestUserRequest(ctx: ExtensionContext): string | undefined {\n\tconst branch = ctx.sessionManager.getBranch();\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\") continue;\n\t\tconst content = entry.message.content;\n\t\treturn typeof content === \"string\"\n\t\t\t? content\n\t\t\t: content\n\t\t\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t\t\t.map((part) => part.text)\n\t\t\t\t\t.join(\"\\n\");\n\t}\n\treturn undefined;\n}\n\nexport default createApprovalExtension();\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/extensions/approval/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EACN,kBAAkB,EAClB,cAAc,E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AC,SAAS,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAChH,CAAC;AAED,6EAA6E;AAC7E,SAAS,iBAAiB,CAAC,GAAqB;IAC/C,MAAM,MAAM,GAAG,GAAG,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC;IAC9C,KAAK,IAAI,KAAK,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QACzD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC5B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QACxE,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QACtC,OAAO,OAAO,OAAO,KAAK,QAAQ;YACjC,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,OAAO;iBACN,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;iBACtC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;iBACxB,IAAI,CAAC,IAAI,CAAC,CAAC;IAChB,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,eAAe,uBAAuB,EAAE,CAAC","sourcesContent":["/**\n * Approval modes as an extension. The CLI loads it as a built-in extension; SDK users add\n * `createApprovalExtension()` to their extension factories.\n *\n * The session holds the mode (`getApprovalMode()`); this extension enforces it on every tool call,\n * asks the user in a dialog where the mode requires it and remembers \"always allow\" answers for the\n * session, runs the auto-mode classifier, keeps plan mode read-only with `exit_plan_mode` to leave\n * it, and adds the `/approval-mode` and `/plan` commands and the `--approval-mode` flag.\n */\n\nimport type { AgentMessage } from \"@diffra-ai/agent-core\";\nimport {\n\tAPPROVAL_MODE_INFO,\n\tAPPROVAL_MODES,\n\ttype ApprovalMode,\n\tisApprovalMode,\n\treadApprovalModeState,\n} from \"../../core/approval-mode.ts\";\nimport {\n\ttype ApprovalAnswer,\n\ttype ApprovalCause,\n\ttype ApprovalRemember,\n\tcreateToolCallApproval,\n} from \"../../core/decisions.ts\";\nimport type {\n\tExtensionAPI,\n\tExtensionContext,\n\tExtensionFactory,\n\tToolCallEvent,\n\tToolCallEventResult,\n} from \"../../core/extensions/types.ts\";\nimport { resolveFastModel } from \"../../core/fast-model.ts\";\nimport { SETTINGS_DEFAULTS } from \"../../core/settings-defaults.ts\";\nimport { keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { findScope, isSubagentScopeEvent, SUBAGENT_SCOPE_CHANNEL, type SubagentScope } from \"../agents/call-scopes.ts\";\nimport { classifyAction } from \"./auto-classifier.ts\";\nimport { createExitPlanModeToolDefinition } from \"./exit-plan-mode.ts\";\nimport { manualPlanExitReminder, PLAN_MODE_REMINDER } from \"./plan-reminders.ts\";\nimport {\n\ttype ApprovalDecision,\n\tdecide,\n\tEXIT_PLAN_MODE_TOOL_NAME,\n\tPLAN_NO_APPROVAL_MESSAGE,\n\ttype PolicyCall,\n\ttype SessionApprovals,\n} from \"./policy.ts\";\n\nconst STATUS_KEY = \"approval-mode\";\n/** Unavailable classifier answers in a row after which calls go to the user instead. */\nconst MAX_UNAVAILABLE = 2;\n/** Classifier blocks in a row after which the next block goes to the user, so the agent is not stuck. */\nconst MAX_BLOCKS = 3;\n\n/** Create the approval extension. */\nexport function createApprovalExtension(): ExtensionFactory {\n\treturn (diffra) => {\n\t\tlet approvals = newApprovals();\n\t\tlet blocks = 0;\n\t\tlet unavailable = 0;\n\t\tlet approvedPlanExit = false;\n\t\tlet manualPlanExitPending = false;\n\t\tlet autoNoticeShown = false;\n\t\t// Dialogs run one at a time; parallel tool calls wait their turn.\n\t\tlet dialogs: Promise<unknown> = Promise.resolve();\n\t\t// Running subagents, by the id of their `agent` call; their calls follow the subagent's mode.\n\t\tconst scopes = new Map<string, SubagentScope>();\n\t\tdiffra.events.on(SUBAGENT_SCOPE_CHANNEL, (event) => {\n\t\t\tif (!isSubagentScopeEvent(event)) return;\n\t\t\tif (event.kind === \"start\")\n\t\t\t\tscopes.set(event.callId, { background: event.background, approvalMode: event.approvalMode });\n\t\t\telse scopes.delete(event.callId);\n\t\t});\n\n\t\tconst cycleKeyText = () => keyText(\"app.approvalMode.cycle\") || \"/approval-mode\";\n\t\tconst prePlanMode = (ctx: ExtensionContext) => readApprovalModeState(ctx.sessionManager.getBranch())?.prePlanMode;\n\n\t\tdiffra.registerFlag(\"approval-mode\", {\n\t\t\tdescription: \"Approval mode to start in: plan, default, auto-edit, auto, or yolo\",\n\t\t\ttype: \"string\",\n\t\t});\n\n\t\tdiffra.registerTool(\n\t\t\tcreateExitPlanModeToolDefinition(diffra, {\n\t\t\t\tonApproved: () => {\n\t\t\t\t\tapprovedPlanExit = true;\n\t\t\t\t},\n\t\t\t\tcycleKeyText,\n\t\t\t}),\n\t\t);\n\n\t\tdiffra.registerCommand(\"approval-mode\", {\n\t\t\tdescription: \"Show or change the approval mode (plan, default, auto-edit, auto, yolo)\",\n\t\t\tgetArgumentCompletions: (prefix) =>\n\t\t\t\t[...APPROVAL_MODES, \"--project\", \"--user\"]\n\t\t\t\t\t.filter((value) => value.startsWith(prefix.trim().split(/\\s+/).pop() ?? \"\"))\n\t\t\t\t\t.map((value) => ({ value, label: value })),\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst parts = args.trim().split(/\\s+/).filter(Boolean);\n\t\t\t\tconst persist = parts.includes(\"--project\") ? \"project\" : parts.includes(\"--user\") ? \"user\" : undefined;\n\t\t\t\tlet mode: string | undefined = parts.find((part) => !part.startsWith(\"--\"));\n\t\t\t\tif (mode === undefined) {\n\t\t\t\t\tconst current = diffra.getApprovalMode();\n\t\t\t\t\tif (!ctx.hasUI) {\n\t\t\t\t\t\tctx.ui.notify(`Approval mode: ${APPROVAL_MODE_INFO[current].name} (${current})`, \"info\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst labels = APPROVAL_MODES.map(\n\t\t\t\t\t\t(item) =>\n\t\t\t\t\t\t\t`${item === current ? \"● \" : \" \"}${APPROVAL_MODE_INFO[item].name} (${item}): ${APPROVAL_MODE_INFO[item].description}`,\n\t\t\t\t\t);\n\t\t\t\t\tconst answer = await ctx.ui.select(\"Approval mode\", labels);\n\t\t\t\t\tmode = APPROVAL_MODES[labels.indexOf(answer ?? \"\")];\n\t\t\t\t\tif (mode === undefined) return;\n\t\t\t\t}\n\t\t\t\tif (!isApprovalMode(mode)) {\n\t\t\t\t\tctx.ui.notify(`Unknown approval mode \"${mode}\". Use one of: ${APPROVAL_MODES.join(\", \")}.`, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tdiffra.setApprovalMode(mode, { persist });\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.ui.notify(error instanceof Error ? error.message : String(error), \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Approval mode: ${APPROVAL_MODE_INFO[mode].name}${persist ? ` (saved to ${persist} settings)` : \"\"}`,\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\tdiffra.registerCommand(\"plan\", {\n\t\t\tdescription: \"Enter plan mode, optionally with a request to plan; /plan exit restores the previous mode\",\n\t\t\thandler: async (args, ctx) => {\n\t\t\t\tconst text = args.trim();\n\t\t\t\tif (text === \"exit\") {\n\t\t\t\t\tif (diffra.getApprovalMode() !== \"plan\") {\n\t\t\t\t\t\tctx.ui.notify(\"Not in plan mode.\", \"info\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst mode = prePlanMode(ctx) ?? \"default\";\n\t\t\t\t\tdiffra.setApprovalMode(mode);\n\t\t\t\t\tctx.ui.notify(`Exited plan mode. Approval mode: ${APPROVAL_MODE_INFO[mode].name}`, \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (diffra.getApprovalMode() !== \"plan\") {\n\t\t\t\t\tdiffra.setApprovalMode(\"plan\");\n\t\t\t\t\tctx.ui.notify(\"Plan mode: read-only until you approve a plan.\", \"info\");\n\t\t\t\t}\n\t\t\t\tif (text) diffra.sendUserMessage(text, ctx.isIdle() ? undefined : { deliverAs: \"followUp\" });\n\t\t\t},\n\t\t});\n\n\t\tdiffra.on(\"session_start\", (event, ctx) => {\n\t\t\tapprovals = newApprovals();\n\t\t\tblocks = 0;\n\t\t\tunavailable = 0;\n\t\t\tmanualPlanExitPending = false;\n\t\t\tconst flag = diffra.getFlag(\"approval-mode\");\n\t\t\tif (event.reason === \"startup\" && typeof flag === \"string\" && flag) {\n\t\t\t\tif (isApprovalMode(flag)) diffra.setApprovalMode(flag);\n\t\t\t\telse ctx.ui.notify(`Unknown --approval-mode \"${flag}\". Use one of: ${APPROVAL_MODES.join(\", \")}.`, \"error\");\n\t\t\t}\n\t\t\tsyncExitPlanTool(diffra);\n\t\t\tupdateStatus(ctx, diffra.getApprovalMode());\n\t\t});\n\n\t\tdiffra.on(\"approval_mode_change\", (event, ctx) => {\n\t\t\tif (event.previousMode === \"plan\" && !approvedPlanExit) manualPlanExitPending = true;\n\t\t\tif (event.mode === \"plan\") manualPlanExitPending = false;\n\t\t\tapprovedPlanExit = false;\n\t\t\tblocks = 0;\n\t\t\tunavailable = 0;\n\t\t\tsyncExitPlanTool(diffra);\n\t\t\tupdateStatus(ctx, event.mode);\n\t\t\tif (event.mode === \"auto\" && !autoNoticeShown && ctx.hasUI) {\n\t\t\t\tautoNoticeShown = true;\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"Auto mode: a classifier model reviews shell commands, web access, edits outside the project, and other tools, and blocks risky ones. Read-only tools and edits inside the project run without review.\",\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\n\t\tdiffra.on(\"context\", (event) => {\n\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\tconst reminder =\n\t\t\t\tmode === \"plan\" ? PLAN_MODE_REMINDER : manualPlanExitPending ? manualPlanExitReminder(mode) : undefined;\n\t\t\tif (!reminder) return undefined;\n\t\t\tmanualPlanExitPending = false;\n\t\t\tconst message: AgentMessage = {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: \"approval-mode-reminder\",\n\t\t\t\tcontent: reminder,\n\t\t\t\tdisplay: false,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\treturn { messages: [...event.messages, message] };\n\t\t});\n\n\t\tdiffra.on(\"tool_call\", async (event, ctx) => {\n\t\t\tconst call = toPolicyCall(diffra, event);\n\t\t\tconst scope = event.parentToolCallId ? findScope(scopes, event.toolCallId) : undefined;\n\t\t\tconst evaluate = () =>\n\t\t\t\tdecide(scope?.approvalMode ?? diffra.getApprovalMode(), call, approvals, {\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tclassifyAllShell: diffra.getSettings().permissions?.autoMode?.classifyAllShell === true,\n\t\t\t\t});\n\t\t\tlet decision = evaluate();\n\t\t\tif (decision.kind === \"classify\") decision = await classify(call, ctx);\n\t\t\tif (decision.kind === \"allow\") return undefined;\n\t\t\tif (decision.kind === \"block\") return { block: true, reason: decision.reason };\n\t\t\tif (scope?.background) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `This ${call.toolName} call needs approval, but agents running in the background cannot ask the user, so it was denied. Run the agent in the foreground (run_in_background: false) to approve its calls.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn ask(decision, call, event.toolCallId, ctx, evaluate);\n\t\t});\n\n\t\t/** Run the classifier; after repeated blocks or outages the user decides instead. */\n\t\tasync function classify(call: PolicyCall, ctx: ExtensionContext): Promise<ReviewedDecision> {\n\t\t\tconst manual = (cause: ApprovalCause, title: string): ReviewedDecision => ({\n\t\t\t\tkind: \"ask\",\n\t\t\t\ttitle,\n\t\t\t\tcause,\n\t\t\t\tremember: undefined,\n\t\t\t});\n\t\t\tif (unavailable >= MAX_UNAVAILABLE) {\n\t\t\t\tunavailable = 0;\n\t\t\t\treturn manual(\n\t\t\t\t\t{ kind: \"auto-unavailable\" },\n\t\t\t\t\t`Auto mode cannot approve this ${call.toolName} call on its own. Allow it?\\n\\n ${JSON.stringify(call.input).slice(0, 300)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst settings = diffra.getSettings();\n\t\t\tconst model = resolveFastModel(settings, ctx.modelRegistry, ctx.model);\n\t\t\tconst timeoutMs =\n\t\t\t\tsettings.permissions?.autoMode?.classifier?.timeouts?.stage1Ms ??\n\t\t\t\tSETTINGS_DEFAULTS.autoModeClassifierTimeoutMs;\n\t\t\tconst verdict = model\n\t\t\t\t? await classifyAction(\n\t\t\t\t\t\t{ toolName: call.toolName, input: call.input, cwd: ctx.cwd, userRequest: latestUserRequest(ctx) },\n\t\t\t\t\t\tsettings.permissions?.autoMode,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tctx.modelRegistry,\n\t\t\t\t\t\t{ timeoutMs, signal: ctx.signal },\n\t\t\t\t\t)\n\t\t\t\t: { kind: \"unavailable\" as const, reason: \"no model is selected\" };\n\t\t\tif (verdict.kind === \"allow\") {\n\t\t\t\tblocks = 0;\n\t\t\t\tunavailable = 0;\n\t\t\t\treturn { kind: \"allow\" };\n\t\t\t}\n\t\t\tif (verdict.kind === \"unavailable\") {\n\t\t\t\tunavailable++;\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"block\",\n\t\t\t\t\treason: `Auto mode could not review this action (${verdict.reason}), so it was blocked. Do not retry it unchanged; continue with other work or ask the user.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tunavailable = 0;\n\t\t\tblocks++;\n\t\t\tif (blocks >= MAX_BLOCKS) {\n\t\t\t\tblocks = 0;\n\t\t\t\treturn manual(\n\t\t\t\t\t{ kind: \"auto-blocked\", reason: verdict.reason },\n\t\t\t\t\t`Auto mode blocked this ${MAX_BLOCKS} times in a row: ${verdict.reason}\\n\\nAllow this ${call.toolName} call?`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tkind: \"block\",\n\t\t\t\treason: `Auto mode blocked this action: ${verdict.reason}. Do not retry it through wrappers; choose a safer approach or ask the user.`,\n\t\t\t};\n\t\t}\n\n\t\t/**\n\t\t * Ask the user, one dialog at a time; an earlier answer may already allow this call. Hosts that\n\t\t * render approvals get the structured request, others a `select`.\n\t\t */\n\t\tasync function ask(\n\t\t\tdecision: AskDecision,\n\t\t\tcall: PolicyCall,\n\t\t\ttoolCallId: string,\n\t\t\tctx: ExtensionContext,\n\t\t\tevaluate: () => ApprovalDecision,\n\t\t): Promise<ToolCallEventResult | undefined> {\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\tconst mode = diffra.getApprovalMode();\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason:\n\t\t\t\t\t\tmode === \"plan\"\n\t\t\t\t\t\t\t? PLAN_NO_APPROVAL_MESSAGE\n\t\t\t\t\t\t\t: `This ${call.toolName} call needs approval in ${APPROVAL_MODE_INFO[mode].name} mode, but no interactive UI is available to ask. It was not run.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst turn = dialogs.then(async () => {\n\t\t\t\tconst current = evaluate();\n\t\t\t\tif (current.kind === \"allow\") return undefined;\n\t\t\t\tif (current.kind === \"block\") return { block: true, reason: current.reason };\n\t\t\t\tconst prompt = current.kind === \"ask\" ? current : decision;\n\t\t\t\tconst answer = ctx.ui.approve\n\t\t\t\t\t? await ctx.ui.approve(\n\t\t\t\t\t\t\tawait createToolCallApproval(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttitle: prompt.title,\n\t\t\t\t\t\t\t\t\ttoolName: call.toolName,\n\t\t\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\t\t\tinput: call.input,\n\t\t\t\t\t\t\t\t\tcause: prompt.cause,\n\t\t\t\t\t\t\t\t\tremember: prompt.remember,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tdiffra.getSettings(),\n\t\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t{ signal: ctx.signal },\n\t\t\t\t\t\t)\n\t\t\t\t\t: await answerWithSelect(prompt, ctx);\n\t\t\t\tif (answer?.kind === \"once\") return undefined;\n\t\t\t\tif (answer?.kind === \"always\") {\n\t\t\t\t\tif (prompt.remember) remember(prompt.remember);\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tconst feedback = answer?.feedback?.trim();\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `The user denied this ${call.toolName} call.${feedback ? ` The user said: ${feedback}` : \"\"}`,\n\t\t\t\t};\n\t\t\t});\n\t\t\tdialogs = turn.catch(() => undefined);\n\t\t\treturn turn;\n\t\t}\n\n\t\tfunction remember(choice: ApprovalRemember): void {\n\t\t\tif (choice.kind === \"tool\") approvals.tools.add(choice.name);\n\t\t\telse if (choice.kind === \"shell\") for (const root of choice.roots) approvals.shellRoots.add(root);\n\t\t\telse approvals.edits = true;\n\t\t}\n\t};\n}\n\n/** A decision after the classifier ran: allow, block, or ask the user. */\ntype ReviewedDecision = Exclude<ApprovalDecision, { kind: \"classify\" }>;\ntype AskDecision = Extract<ApprovalDecision, { kind: \"ask\" }>;\n\nfunction newApprovals(): SessionApprovals {\n\treturn { tools: new Set(), shellRoots: new Set(), edits: false };\n}\n\n/** Ask with `select`, for hosts that do not render approvals. */\nasync function answerWithSelect(prompt: AskDecision, ctx: ExtensionContext): Promise<ApprovalAnswer | undefined> {\n\tconst once = \"Yes, allow once\";\n\tconst always = prompt.remember ? rememberLabel(prompt.remember) : undefined;\n\tconst answer = await ctx.ui.select(prompt.title, [once, ...(always ? [always] : []), \"No\"], { signal: ctx.signal });\n\tif (answer === undefined) return undefined;\n\tif (answer === once) return { kind: \"once\" };\n\treturn answer === always ? { kind: \"always\" } : { kind: \"deny\" };\n}\n\nfunction rememberLabel(choice: ApprovalRemember): string {\n\tif (choice.kind === \"tool\") return `Yes, always allow ${choice.name} this session`;\n\tif (choice.kind === \"shell\")\n\t\treturn `Yes, always allow ${choice.roots.map((root) => `\\`${root}\\``).join(\", \")} commands this session`;\n\treturn \"Yes, allow all edits this session\";\n}\n\nfunction toPolicyCall(diffra: ExtensionAPI, event: ToolCallEvent): PolicyCall {\n\tconst annotations = diffra.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;\n\treturn {\n\t\ttoolName: event.toolName,\n\t\t// Validated tool arguments are always an object; the event types them per tool.\n\t\tinput: event.input as Record<string, unknown>,\n\t\treadOnlyHint: annotations?.readOnlyHint === true,\n\t\topenWorldHint: annotations?.openWorldHint === true,\n\t};\n}\n\n/** `exit_plan_mode` is declared to the model only in plan mode. */\nfunction syncExitPlanTool(diffra: ExtensionAPI): void {\n\tconst active = diffra.getActiveTools();\n\tconst declared = active.includes(EXIT_PLAN_MODE_TOOL_NAME);\n\tconst plan = diffra.getApprovalMode() === \"plan\";\n\tif (plan && !declared) diffra.setActiveTools([...active, EXIT_PLAN_MODE_TOOL_NAME]);\n\telse if (!plan && declared) diffra.setActiveTools(active.filter((name) => name !== EXIT_PLAN_MODE_TOOL_NAME));\n}\n\nconst STATUS_TEXT: Record<ApprovalMode, string | undefined> = {\n\tplan: \"⏸ plan mode\",\n\tdefault: \"⏸ ask permissions\",\n\t\"auto-edit\": \"⏵⏵ accept edits\",\n\tauto: \"⏵ auto mode\",\n\tyolo: undefined,\n};\n\nfunction updateStatus(ctx: ExtensionContext, mode: ApprovalMode): void {\n\tconst text = STATUS_TEXT[mode];\n\tctx.ui.setStatus(STATUS_KEY, text ? ctx.ui.theme.fg(mode === \"plan\" ? \"warning\" : \"accent\", text) : undefined);\n}\n\n/** The text of the latest user message on the branch, for the classifier. */\nfunction latestUserRequest(ctx: ExtensionContext): string | undefined {\n\tconst branch = ctx.sessionManager.getBranch();\n\tfor (let index = branch.length - 1; index >= 0; index--) {\n\t\tconst entry = branch[index];\n\t\tif (entry.type !== \"message\" || entry.message.role !== \"user\") continue;\n\t\tconst content = entry.message.content;\n\t\treturn typeof content === \"string\"\n\t\t\t? content\n\t\t\t: content\n\t\t\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t\t\t.map((part) => part.text)\n\t\t\t\t\t.join(\"\\n\");\n\t}\n\treturn undefined;\n}\n\nexport default createApprovalExtension();\n"]}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* auto-mode classifier. Decisions are pure; the extension carries them out.
|
|
4
4
|
*/
|
|
5
5
|
import type { ApprovalMode } from "../../core/approval-mode.ts";
|
|
6
|
+
import type { ApprovalCause, ApprovalRemember } from "../../core/decisions.ts";
|
|
6
7
|
export declare const EXIT_PLAN_MODE_TOOL_NAME = "exit_plan_mode";
|
|
7
8
|
/** A tool call as the policy sees it. */
|
|
8
9
|
export interface PolicyCall {
|
|
@@ -13,21 +14,12 @@ export interface PolicyCall {
|
|
|
13
14
|
/** From the tool's annotations: it reaches the web or other external systems. */
|
|
14
15
|
openWorldHint: boolean;
|
|
15
16
|
}
|
|
16
|
-
/** Approvals the user granted for the rest of the session. */
|
|
17
|
+
/** Approvals the user granted for the rest of the session; `edits` allows edits without changing the mode. */
|
|
17
18
|
export interface SessionApprovals {
|
|
18
19
|
tools: Set<string>;
|
|
19
20
|
shellRoots: Set<string>;
|
|
21
|
+
edits: boolean;
|
|
20
22
|
}
|
|
21
|
-
/** What "allow always" remembers when the user picks it. */
|
|
22
|
-
export type Remember = {
|
|
23
|
-
kind: "tool";
|
|
24
|
-
name: string;
|
|
25
|
-
} | {
|
|
26
|
-
kind: "shell";
|
|
27
|
-
roots: string[];
|
|
28
|
-
} | {
|
|
29
|
-
kind: "edits";
|
|
30
|
-
};
|
|
31
23
|
export type ApprovalDecision = {
|
|
32
24
|
kind: "allow";
|
|
33
25
|
} | {
|
|
@@ -36,7 +28,8 @@ export type ApprovalDecision = {
|
|
|
36
28
|
} | {
|
|
37
29
|
kind: "ask";
|
|
38
30
|
title: string;
|
|
39
|
-
|
|
31
|
+
cause: ApprovalCause;
|
|
32
|
+
remember: ApprovalRemember | undefined;
|
|
40
33
|
} | {
|
|
41
34
|
kind: "classify";
|
|
42
35
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../../src/extensions/approval/policy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"policy.d.ts","sourceRoot":"","sources":["../../../src/extensions/approval/policy.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAG/E,eAAO,MAAM,wBAAwB,mBAAmB,CAAC;AAEzD,yCAAyC;AACzC,MAAM,WAAW,UAAU;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/B,uEAAuE;IACvE,YAAY,EAAE,OAAO,CAAC;IACtB,iFAAiF;IACjF,aAAa,EAAE,OAAO,CAAC;CACvB;AAED,8GAA8G;AAC9G,MAAM,WAAW,gBAAgB;IAChC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACnB,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACxB,KAAK,EAAE,OAAO,CAAC;CACf;AA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