@carrieros/cli 0.3.0 → 0.4.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.
Files changed (86) hide show
  1. package/README.md +34 -13
  2. package/dist/commands/chat.js +3 -3
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +27 -12
  5. package/dist/commands/logout.js +1 -0
  6. package/dist/commands/permissions.js +77 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +8 -1
  10. package/dist/commands/update.js +79 -9
  11. package/dist/commands/usage.js +5 -5
  12. package/dist/commands/whoami.js +12 -9
  13. package/dist/ide/editor-context.js +115 -12
  14. package/dist/ide/ide-session.js +274 -13
  15. package/dist/ide/tool-host.js +2 -2
  16. package/dist/main.js +0 -0
  17. package/dist/services/api.js +178 -12
  18. package/dist/services/auth-origin.js +20 -0
  19. package/dist/services/chat-stream.js +26 -3
  20. package/dist/services/checkpoints.js +176 -14
  21. package/dist/services/client-tools.js +113 -21
  22. package/dist/services/code-intel.js +243 -0
  23. package/dist/services/code-symbols.js +94 -0
  24. package/dist/services/coding-workflow.js +554 -0
  25. package/dist/services/command-coordinator.js +85 -12
  26. package/dist/services/command-policy.js +34 -4
  27. package/dist/services/config.js +67 -5
  28. package/dist/services/container-runner.js +254 -0
  29. package/dist/services/container-supervisor.js +38 -0
  30. package/dist/services/context.js +45 -17
  31. package/dist/services/device-auth.js +30 -5
  32. package/dist/services/execution-platform.js +30 -0
  33. package/dist/services/file-resolver.js +1 -1
  34. package/dist/services/folder-key.js +22 -0
  35. package/dist/services/git-tools.js +181 -0
  36. package/dist/services/helper-bin.js +56 -35
  37. package/dist/services/instruction-resolver.js +54 -0
  38. package/dist/services/job-helper.js +31 -10
  39. package/dist/services/local-files.js +148 -26
  40. package/dist/services/local-tools.js +540 -35
  41. package/dist/services/login-flow.js +43 -12
  42. package/dist/services/mutation-coordinator.js +186 -20
  43. package/dist/services/mutation-groups.js +309 -0
  44. package/dist/services/mutation-recovery.js +159 -0
  45. package/dist/services/mutations.js +264 -78
  46. package/dist/services/packaged-update.js +403 -0
  47. package/dist/services/packaged.js +15 -0
  48. package/dist/services/permission-mode.js +60 -0
  49. package/dist/services/process-runner.js +7 -1
  50. package/dist/services/project-context.js +4 -4
  51. package/dist/services/result-reconciliation.js +49 -0
  52. package/dist/services/secure-store.js +21 -1
  53. package/dist/services/session-resolver.js +5 -0
  54. package/dist/services/supported-runtime.js +59 -0
  55. package/dist/services/task-context.js +212 -0
  56. package/dist/services/task-snapshot.js +38 -0
  57. package/dist/services/tool-result-outbox.js +195 -0
  58. package/dist/services/update.js +37 -12
  59. package/dist/services/workspace-registry.js +4 -3
  60. package/dist/services/workspace.js +8 -1
  61. package/dist/shell/shell-chat.js +299 -32
  62. package/dist/shell/shell-commands.js +46 -4
  63. package/dist/shell/shell-prompt.js +21 -11
  64. package/dist/shell/shell-renderer.js +1 -1
  65. package/dist/shell/shell.js +69 -7
  66. package/dist/shell/task-context-view.js +40 -0
  67. package/dist/ui/agent-cards.js +111 -0
  68. package/dist/ui/agent-presentation.js +131 -0
  69. package/dist/ui/approval.js +46 -16
  70. package/dist/ui/banner.js +31 -87
  71. package/dist/ui/change-review.js +293 -46
  72. package/dist/ui/chat-renderer.js +6 -6
  73. package/dist/ui/colors.js +9 -9
  74. package/dist/ui/command-details.js +11 -0
  75. package/dist/ui/command-palette.js +27 -10
  76. package/dist/ui/command-registry.js +9 -2
  77. package/dist/ui/command-review.js +77 -28
  78. package/dist/ui/composer-layout.js +26 -20
  79. package/dist/ui/conversation.js +77 -25
  80. package/dist/ui/live.js +1 -1
  81. package/dist/ui/screen.js +19 -11
  82. package/dist/ui/select.js +6 -0
  83. package/dist/ui/task-context-card.js +99 -0
  84. package/dist/ui/trust.js +7 -12
  85. package/dist/ui/ui.js +23 -0
  86. package/package.json +8 -5
@@ -2,25 +2,26 @@ import { ApiError } from "../services/api.js";
2
2
  import { heading, kv, line, warn } from "../services/output.js";
3
3
  import { withSpinner } from "../services/spinner.js";
4
4
  /**
5
- * `cos whoami` — show the identity behind the stored key. Re-verifies
5
+ * `cos whoami` — show the signed-in account. Re-verifies
6
6
  * against the API for freshness, falling back to the cached scope if offline.
7
7
  */
8
8
  export function registerWhoami(program, ctx) {
9
9
  program
10
10
  .command("whoami")
11
- .description("Show the workspace, project and account for the current key")
12
- .action(async () => {
11
+ .description("Show your signed-in account")
12
+ .option("--details", "include advanced API workspace, project and environment details")
13
+ .action(async (options) => {
13
14
  const client = ctx.requireAuth();
14
15
  try {
15
16
  const scope = await withSpinner("Checking…", () => client.verify());
16
17
  ctx.config.set("scope", scope);
17
- render(scope, false);
18
+ render(scope, false, options.details);
18
19
  }
19
20
  catch (err) {
20
21
  const cached = ctx.config.get("scope");
21
22
  if (cached) {
22
23
  warn(`Could not reach the API (${err instanceof ApiError ? err.code : "error"}); showing cached details.`);
23
- render(cached, true);
24
+ render(cached, true, options.details);
24
25
  }
25
26
  else {
26
27
  throw err;
@@ -28,11 +29,13 @@ export function registerWhoami(program, ctx) {
28
29
  }
29
30
  });
30
31
  }
31
- function render(scope, cached) {
32
+ function render(scope, cached, details = false) {
32
33
  heading(cached ? "Account (cached)" : "Account");
33
- kv("Workspace", `${scope.workspace.name} (${scope.workspace.slug})`);
34
- kv("Project", scope.project.name);
35
- kv("Environment", scope.project.environment);
34
+ if (details) {
35
+ kv("API workspace", `${scope.workspace?.name ?? "Not required"} (${scope.workspace?.slug ?? "user session"})`);
36
+ kv("API project", scope.project?.name ?? "Not required");
37
+ kv("Project environment", scope.project?.environment ?? "Not applicable");
38
+ }
36
39
  // apiKey is null for a device-flow (browser) session.
37
40
  kv("Signed in via", scope.apiKey ? `API key · ${scope.apiKey.name}` : "Browser session");
38
41
  if (scope.user)
@@ -1,4 +1,7 @@
1
1
  import path from "node:path";
2
+ import { looksBinary } from "../services/local-files.js";
3
+ import { executeLocalTool } from "../services/local-tools.js";
4
+ import { repositoryForPath } from "../services/workspace-registry.js";
2
5
  /** Bounds — editor context is a hint, never a payload. */
3
6
  const MAX_SELECTION_BYTES = 32 * 1024;
4
7
  const MAX_OPEN_FILES = 100;
@@ -32,31 +35,58 @@ export function executeIdeContextTool(name, args, state, resolve) {
32
35
  repository: at.repository,
33
36
  path: at.path,
34
37
  language: a.languageId ?? null,
35
- cursor: a.cursorLine ? { line: a.cursorLine, column: a.cursorColumn ?? 1 } : null
38
+ cursor: a.cursorLine ? { line: a.cursorLine, column: a.cursorColumn ?? 1 } : null,
39
+ visible_range: a.visibleRange ? { start_line: a.visibleRange.startLine, end_line: a.visibleRange.endLine } : null,
40
+ // Unsaved edits mean read_file (disk) and the editor differ.
41
+ dirty: a.dirty === true,
42
+ version: Number.isInteger(a.version) ? a.version : null
36
43
  });
37
44
  }
38
45
  case "get_selection": {
39
46
  const a = state.activeFile;
40
47
  if (!a?.selection || !a.selection.text)
41
48
  return ok({ selected: false });
42
- const at = locate(a.absPath, resolve);
43
- if (!at)
44
- return ok({ selected: false, reason: "The selection is in a file outside the workspace." });
45
- const text = clampBytes(a.selection.text, MAX_SELECTION_BYTES);
49
+ // Editor metadata/resolvers cannot grant content access. Use the actual
50
+ // registry and the SAME read_file executor as CLI reads: trust, canonical
51
+ // containment, ignore/sensitive rules, binary detection and bounded I/O.
52
+ // Its file content is discarded; only the approved editor selection leaves
53
+ // this process (including unsaved edits to an existing allowed file).
54
+ const repo = repositoryForPath(a.absPath);
55
+ if (!repo)
56
+ return selectionDenied("OUTSIDE_WORKSPACE");
57
+ const checked = executeLocalTool({
58
+ id: "ide-selection-check",
59
+ name: "read_file",
60
+ arguments: { repository: repo.name, path: a.absPath }
61
+ });
62
+ if (!checked.ok)
63
+ return selectionDenied(checked.error?.code ?? "SELECTION_DENIED");
64
+ const checkedFile = checked.result;
65
+ // A small selection must not circumvent the underlying file's read cap.
66
+ if (checkedFile.truncated)
67
+ return selectionDenied("FILE_TOO_LARGE");
68
+ if (Buffer.byteLength(a.selection.text, "utf8") > MAX_SELECTION_BYTES) {
69
+ return selectionDenied("SELECTION_TOO_LARGE");
70
+ }
71
+ if (looksBinary(Buffer.from(a.selection.text, "utf8")))
72
+ return selectionDenied("BINARY_FILE");
46
73
  return ok({
47
74
  selected: true,
48
- repository: at.repository,
49
- path: at.path,
75
+ repository: repo.name,
76
+ path: checkedFile.path,
50
77
  language: a.languageId ?? null,
51
78
  start_line: a.selection.startLine,
52
79
  end_line: a.selection.endLine,
53
- text: text.text,
54
- truncated: text.truncated
80
+ ...(a.selection.startColumn ? { start_column: a.selection.startColumn, end_column: a.selection.endColumn ?? null } : {}),
81
+ version: Number.isInteger(a.version) ? a.version : null,
82
+ text: a.selection.text,
83
+ truncated: false
55
84
  });
56
85
  }
57
86
  case "get_open_files": {
58
87
  const seen = new Set();
59
88
  const files = [];
89
+ const meta = new Map((state.openDocuments ?? []).map((d) => [path.resolve(d.absPath), d]));
60
90
  let outside = 0;
61
91
  for (const abs of (state.openFiles ?? []).slice(0, MAX_OPEN_FILES * 2)) {
62
92
  const at = locate(abs, resolve);
@@ -68,8 +98,10 @@ export function executeIdeContextTool(name, args, state, resolve) {
68
98
  if (seen.has(key))
69
99
  continue;
70
100
  seen.add(key);
71
- if (files.length < MAX_OPEN_FILES)
72
- files.push(at);
101
+ const d = meta.get(path.resolve(abs));
102
+ if (files.length < MAX_OPEN_FILES) {
103
+ files.push({ ...at, ...(d ? { language: d.languageId, dirty: d.dirty === true, active: d.active === true, ...(Number.isInteger(d.version) ? { version: d.version } : {}) } : {}) });
104
+ }
73
105
  }
74
106
  return ok({ files, outside_workspace: outside, truncated: files.length >= MAX_OPEN_FILES });
75
107
  }
@@ -99,9 +131,11 @@ export function executeIdeContextTool(name, args, state, resolve) {
99
131
  const entry = (state.diagnostics ?? []).find((d) => path.resolve(d.absPath) === path.resolve(absPath));
100
132
  const items = (entry?.items ?? []).slice(0, MAX_DIAGNOSTICS).map((d) => ({
101
133
  line: d.line,
134
+ column: d.column ?? null,
102
135
  severity: d.severity,
103
136
  message: clampBytes(d.message, 2000).text,
104
- source: d.source ?? null
137
+ source: d.source ?? null,
138
+ code: d.code ?? null
105
139
  }));
106
140
  return ok({
107
141
  repository: at.repository,
@@ -153,15 +187,84 @@ export function ideContextHint(state, resolve) {
153
187
  `Repository: ${at.repository}`,
154
188
  `File: ${at.path}`
155
189
  ];
190
+ if (a.languageId)
191
+ lines.push(`Language: ${a.languageId}`);
192
+ if (a.cursorLine)
193
+ lines.push(`Cursor: line ${a.cursorLine}, column ${a.cursorColumn ?? 1}`);
194
+ if (a.visibleRange)
195
+ lines.push(`Visible lines: ${a.visibleRange.startLine}-${a.visibleRange.endLine}`);
196
+ if (a.dirty)
197
+ lines.push(`Unsaved edits in the editor${Number.isInteger(a.version) ? ` (version ${a.version})` : ""}: the file on disk differs; read_file returns the saved bytes.`);
156
198
  const sel = a.selection;
157
199
  if (sel && sel.text && Number.isFinite(sel.startLine) && Number.isFinite(sel.endLine)) {
158
200
  lines.push(`Selection: lines ${sel.startLine}-${sel.endLine}`);
159
201
  }
202
+ // Other open tabs: identity only. The agent reads any of them with read_file.
203
+ const others = [];
204
+ const seen = new Set([`${at.repository}:${at.path}`]);
205
+ const meta = new Map((state.openDocuments ?? []).map((d) => [path.resolve(d.absPath), d]));
206
+ for (const abs of state.openFiles ?? []) {
207
+ const o = locate(abs, resolve);
208
+ if (!o || seen.has(`${o.repository}:${o.path}`))
209
+ continue;
210
+ seen.add(`${o.repository}:${o.path}`);
211
+ others.push(`${o.repository === at.repository ? o.path : `${o.repository}:${o.path}`}${meta.get(path.resolve(abs))?.dirty ? " (unsaved edits)" : ""}`);
212
+ }
213
+ if (others.length)
214
+ lines.push(`Other open files: ${others.slice(0, MAX_HINT_OPEN_FILES).join(", ")}${others.length > MAX_HINT_OPEN_FILES ? ` (+${others.length - MAX_HINT_OPEN_FILES} more)` : ""}`);
160
215
  return lines.join("\n");
161
216
  }
217
+ const MAX_HINT_OPEN_FILES = 10;
218
+ const MAX_ATTACHMENTS = 20;
219
+ const MAX_ATTACHED_DIAGNOSTICS = 30;
220
+ /** The attached context as one bounded, clearly labelled block, or null when none. */
221
+ export function attachmentsHint(attachments) {
222
+ if (!attachments.length)
223
+ return null;
224
+ const where = (a) => `${a.repository}:${a.path}`;
225
+ const out = ["[ATTACHED CONTEXT] (chosen by the user in the editor; read files with read_file before relying on them)"];
226
+ for (const a of attachments.slice(0, MAX_ATTACHMENTS)) {
227
+ switch (a.kind) {
228
+ case "file":
229
+ out.push(`- File: ${where(a)}`);
230
+ break;
231
+ case "folder":
232
+ out.push(`- Folder: ${where(a)}/`);
233
+ break;
234
+ case "open_files":
235
+ out.push(`- Open files: ${a.files.map((f) => `${where(f)}${f.dirty ? " (unsaved edits)" : ""}`).join(", ") || "none"}`);
236
+ break;
237
+ case "diagnostics": {
238
+ out.push(`- Diagnostics for ${where(a)}: ${a.items.length ? "" : "none reported"}`);
239
+ for (const d of a.items.slice(0, MAX_ATTACHED_DIAGNOSTICS)) {
240
+ out.push(` - line ${d.line}${d.column ? `:${d.column}` : ""} ${d.severity}${d.source ? ` [${d.source}${d.code ? ` ${d.code}` : ""}]` : ""}: ${d.message.split("\n")[0].slice(0, 300)}`);
241
+ }
242
+ if (a.truncated || a.items.length > MAX_ATTACHED_DIAGNOSTICS)
243
+ out.push(" - … more not shown");
244
+ break;
245
+ }
246
+ case "selection": {
247
+ const cols = a.startColumn ? ` (columns ${a.startColumn}-${a.endColumn ?? "?"})` : "";
248
+ out.push(`- Selection: ${where(a)} lines ${a.startLine}-${a.endLine}${cols}`);
249
+ if (a.stale)
250
+ out.push(" The file changed since this was selected; read the lines again with read_file.");
251
+ else if (a.text)
252
+ out.push(` Selected text (editor buffer${a.language ? `, ${a.language}` : ""}):`, " ```", ...a.text.split("\n").map((l) => ` ${l}`), " ```");
253
+ break;
254
+ }
255
+ }
256
+ }
257
+ if (attachments.length > MAX_ATTACHMENTS)
258
+ out.push(`- … ${attachments.length - MAX_ATTACHMENTS} more attachments not included`);
259
+ return out.join("\n");
260
+ }
162
261
  function ok(result) {
163
262
  return { ok: true, result };
164
263
  }
264
+ /** Do not echo editor text or absolute paths in a denial sent to the backend. */
265
+ function selectionDenied(code) {
266
+ return { ok: false, error: { code, message: "Selection content is unavailable under the local file-access policy." } };
267
+ }
165
268
  function clampBytes(text, max) {
166
269
  if (Buffer.byteLength(text, "utf8") <= max)
167
270
  return { text, truncated: false };
@@ -1,4 +1,16 @@
1
- import { submitWithRetry } from "../services/client-tools.js";
1
+ import { permissionPolicy, rememberPermissionMode } from "../services/permission-mode.js";
2
+ import { declaredCommandTools, submitWithRetry } from "../services/client-tools.js";
3
+ import { CodingWorkflow } from "../services/coding-workflow.js";
4
+ import { createCommandCoordinator } from "../services/command-coordinator.js";
5
+ import { displayCommand } from "../services/command-policy.js";
6
+ import { containerRuntime, verifyContainerRuntime } from "../services/container-runner.js";
7
+ import { executionContract } from "../services/execution-platform.js";
8
+ import { ensureJobHelper } from "../services/job-helper.js";
9
+ import { TurnReadCache } from "../services/local-tools.js";
10
+ import { workspaceRoot } from "../services/local-files.js";
11
+ import { TaskFileLedger, repositoryContext, repositoryState } from "../services/task-context.js";
12
+ import { analysisExplanation } from "../ui/agent-presentation.js";
13
+ import { parseTestReport, summariseOutput } from "../ui/command-review.js";
2
14
  import { createMutationCoordinator } from "../services/mutation-coordinator.js";
3
15
  import { handleIdeToolCall, ideDeclaredMutationTools, ideDeclaredReadTools } from "./tool-host.js";
4
16
  /**
@@ -17,17 +29,171 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
17
29
  const signal = controller.signal;
18
30
  // File-changing tools, gated exactly as the CLI gates them — trust plus a
19
31
  // present approver (here, a live panel). Reads are gated on trust alone.
20
- const mutationTools = ideDeclaredMutationTools(ctx, ports.approverPresent);
32
+ // The session's permission mode, fixed for this turn: switching modes while it
33
+ // runs (or while a review is open) never changes what this turn may do.
34
+ const permission = permissionPolicy(ports.permissionMode ?? "manual");
35
+ const mutationTools = permission.changeTools ? ideDeclaredMutationTools(ctx, ports.approverPresent) : undefined;
36
+ // Commands (tests): the CLI's own gate — opt-in, contained runtime, trusted
37
+ // repository — with "approver present" meaning this panel can show the review.
38
+ const commandTools = mutationTools && permission.commands && ports.commandsAllowed && ports.reviewCommand ? declaredCommandTools(ctx, ports.approverPresent) : undefined;
39
+ const emit = (event) => {
40
+ try {
41
+ ports.onWorkflowEvent?.(event);
42
+ }
43
+ catch { /* presentation must never break a turn */ }
44
+ };
45
+ // Coding mode: the SAME CodingWorkflow the CLI uses gates plan → reads →
46
+ // approved change → approved test → analysis → correction → retest. Only
47
+ // when commands are available, because a plan must name its verification.
48
+ const readCache = new TurnReadCache();
49
+ const outcome = {};
50
+ let workflow;
51
+ if (commandTools) {
52
+ workflow = new CodingWorkflow(async () => {
53
+ const contract = executionContract();
54
+ if (contract.capability === "UNSUPPORTED")
55
+ throw new Error(contract.prerequisite);
56
+ if (contract.capability === "ISOLATED_RUNTIME_REQUIRED")
57
+ await verifyContainerRuntime(containerRuntime());
58
+ else
59
+ ensureJobHelper();
60
+ return contract;
61
+ }, (lines) => {
62
+ const snap = workflow.snapshot();
63
+ if (lines[0]?.startsWith("Plan:")) {
64
+ const plan = snap.plan;
65
+ if (!plan)
66
+ return;
67
+ const corrective = Number(snap.corrections) > 0;
68
+ if (!outcome.task && !corrective)
69
+ outcome.task = plan.summary;
70
+ emit({
71
+ kind: "plan", corrective, task: plan.summary, files: plan.files.map((f) => f.path),
72
+ // The workflow's own per-file reasons, shown as the plan's steps.
73
+ steps: plan.files.map((f) => ({ path: f.path, reason: typeof f.reason === "string" ? f.reason : "" })),
74
+ validation: plan.tests.map((t) => displayCommand(String(t.program ?? ""), Array.isArray(t.args) ? t.args.map(String) : [])),
75
+ ...(corrective && outcome.rootCause ? { rootCause: outcome.rootCause } : plan.expected ? { expected: plan.expected } : {}),
76
+ ...(plan.risks ? { risks: plan.risks } : {}),
77
+ // The investigation the workflow verified: symptom → path → cause → change location.
78
+ ...(plan.investigation ? { investigation: {
79
+ symptom: plan.investigation.symptom, rootCause: plan.investigation.root_cause,
80
+ changeLocation: `${plan.investigation.change_location.path}${plan.investigation.change_location.symbol ? ` · ${plan.investigation.change_location.symbol}` : ""}`,
81
+ path: plan.investigation.execution_path.map((s) => (s.symbol ? `${s.path} · ${s.symbol}` : s.path)),
82
+ evidence: plan.investigation.evidence.map((e) => `${e.path}${e.lines ? `:${e.lines}` : ""} — ${e.note}`),
83
+ ruledOut: plan.investigation.ruled_out.map((r) => `${r.path} — ${r.reason}`)
84
+ } } : {})
85
+ });
86
+ }
87
+ else if (lines[0]?.startsWith("Failure analysis")) {
88
+ const a = analysisExplanation(lines);
89
+ outcome.rootCause = a.explanation;
90
+ emit({ kind: "analysis", classification: a.classification, explanation: a.explanation });
91
+ }
92
+ emit({ kind: "state", state: String(snap.state), corrections: Number(snap.corrections) || 0 });
93
+ }, { signal, recoveryScope: () => client.mutationRecoveryScope(), onReadsInvalidated: () => readCache.invalidate() });
94
+ }
21
95
  const mutations = mutationTools
22
96
  ? createMutationCoordinator({
23
- submit: (payload) => submitWithRetry(client, payload),
97
+ signal,
98
+ recoveryScope: () => client.mutationRecoveryScope(),
99
+ ...(workflow
100
+ ? { approvalContext: () => workflow.approvalContext(), validatePlans: (plans) => workflow.beforeMutation(plans) }
101
+ : {}),
102
+ approveEditsByPolicy: () => permission.approveEditsByPolicy,
103
+ // The workflow records the outcome before the server can see it, so an
104
+ // immediate reply (the next tool call) finds the change already recorded.
105
+ record: (payload) => workflow?.mutationResult(payload),
106
+ submit: async (payload) => {
107
+ await submitWithRetry(client, payload);
108
+ },
24
109
  ui: {
25
- review: (plans) => ports.reviewMutations(plans),
26
- note: (lines) => ports.onMutationNote?.(lines),
110
+ review: async (plans) => {
111
+ const decision = await ports.reviewMutations(plans, { corrective: Number(workflow?.snapshot().corrections ?? 0) > 0 }, signal);
112
+ workflow?.approval(decision);
113
+ return decision;
114
+ },
115
+ approvedByPolicy: (plans) => {
116
+ workflow?.approval("approve");
117
+ emit({ kind: "edits_accepted", mode: ports.permissionMode ?? "accept_edits", files: plans.map((p) => ({ path: p.rel, additions: p.diff.added, deletions: p.diff.removed })) });
118
+ },
119
+ note: (lines) => {
120
+ ports.onMutationNote?.(lines);
121
+ const applied = lines.map((l) => APPLIED.exec(l.trim())).filter((m) => !!m)
122
+ .map((m) => ({ rel: m[2], added: Number(m[3]), removed: Number(m[4]), operationId: m[5] }));
123
+ if (applied.length)
124
+ emit({ kind: "changes_applied", changes: applied });
125
+ },
126
+ noLongerValid: (rels) => emit({ kind: "change_invalidated", files: rels }),
127
+ rejected: (plans) => emit({ kind: "change_rejected", files: plans.map((p) => p.rel) }),
128
+ applyFailed: (f) => emit({ kind: "apply_failed", ...f }),
129
+ refused: (r) => emit({ kind: "proposal_refused", proposal: "change", ...(r.files.length ? { target: r.files.join(", ") } : {}), code: r.code, reason: r.message }),
27
130
  cancelTurn: abort
28
131
  }
29
132
  })
30
133
  : undefined;
134
+ let commands;
135
+ if (commandTools && workflow) {
136
+ // One review at a time: a change review and a command review never overlap.
137
+ let lane = Promise.resolve();
138
+ const auth = ctx.config.get("auth");
139
+ commands = createCommandCoordinator({
140
+ root: workspaceRoot(),
141
+ signal,
142
+ withTerminal: (fn) => { const run = lane.then(fn, fn); lane = run.catch(() => undefined); return run; },
143
+ recoveryScope: () => client.mutationRecoveryScope(),
144
+ approvalContext: () => workflow.approvalContext(),
145
+ cliSecrets: [auth?.accessToken, auth?.refreshToken, ctx.config.get("secretKey")].filter((v) => typeof v === "string"),
146
+ submit: async (payload) => {
147
+ await submitWithRetry(client, payload);
148
+ const wasAnalyzing = workflow.state === "ANALYZING_FAILURE";
149
+ workflow.commandResult(payload);
150
+ if (!wasAnalyzing && workflow.state === "ANALYZING_FAILURE") {
151
+ emit({ kind: "validation_failed", counts: outcome.counts, failure: outcome.failure });
152
+ }
153
+ emit({ kind: "state", state: String(workflow.snapshot().state), corrections: Number(workflow.snapshot().corrections) || 0 });
154
+ },
155
+ ui: {
156
+ // Cancelled turns show no review and take no decision — not even one
157
+ // queued before Cancel and reached after it.
158
+ review: async (decision, reason, repository, operationId) => {
159
+ if (signal.aborted)
160
+ return "cancel";
161
+ // Auto: a contained R0/R1 command is approved by the session's policy, and says so.
162
+ if (permission.approveCommandByPolicy(decision.tier)) {
163
+ emit({ kind: "command_auto_approved", command: displayCommand(decision.program, decision.effectiveArgs), tier: decision.tier });
164
+ return "approve";
165
+ }
166
+ const answer = await ports.reviewCommand(commandView(decision, reason, repository, operationId), signal);
167
+ return signal.aborted ? "cancel" : answer;
168
+ },
169
+ started: (decision) => emit({ kind: "command_started", command: displayCommand(decision.program, decision.effectiveArgs) }),
170
+ output: () => { },
171
+ finished: ({ decision, result, errorCode, message }) => {
172
+ const command = decision ? displayCommand(decision.program, decision.args) : "command";
173
+ if (!result) {
174
+ const declined = errorCode === "COMMAND_REJECTED" || errorCode === "APPROVAL_TIMEOUT" || errorCode === "COMMAND_CANCELLED";
175
+ // Refused before any review (policy, repository, runtime): a refusal, not a failed run.
176
+ if (!declined)
177
+ emit({ kind: "proposal_refused", proposal: "command", target: command, code: errorCode ?? "COMMAND_REFUSED", reason: message ?? "The command was refused. Nothing ran." });
178
+ else
179
+ emit({ kind: "command_result", command, status: "declined", exitCode: null, tests: [], message: message ?? errorCode });
180
+ return;
181
+ }
182
+ const counts = summariseOutput(result.output) || undefined;
183
+ const report = parseTestReport(result.output);
184
+ outcome.counts = counts;
185
+ outcome.failure = report.failure;
186
+ const status = result.timed_out ? "timed_out" : result.cancelled ? "cancelled" : result.exit_code === 0 ? "passed" : "failed";
187
+ emit({ kind: "command_result", command, status, exitCode: result.exit_code, counts, tests: report.tests.slice(0, 30), durationMs: result.duration_ms });
188
+ },
189
+ cancelTurn: abort
190
+ }
191
+ });
192
+ }
193
+ // Task Context: what earlier coding work in this conversation touched, and
194
+ // whether it is still the same repository and the same bytes. Context only.
195
+ const taskFiles = workflow ? new TaskFileLedger() : undefined;
196
+ const ownerScope = workflow ? client.mutationRecoveryScope() : undefined;
31
197
  const sessionId = ctx.config.get("sessionId");
32
198
  const compose = ports.composeMessage ?? ((m) => m);
33
199
  // What the model has said so far. It narrates as it works; commit each span at
@@ -40,16 +206,42 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
40
206
  if (text.trim())
41
207
  ports.onAssistantText(text);
42
208
  };
209
+ const repoContext = workflow ? repositoryContext(ownerScope, sessionId) : null;
210
+ const repoState = workflow && sessionId && repoContext?.same_repository !== false ? repositoryState(ownerScope, sessionId) : [];
211
+ if (workflow && sessionId && typeof client.taskContext === "function") {
212
+ const previous = await client.taskContext(sessionId).catch(() => null);
213
+ if (previous?.current) {
214
+ const t = previous.current;
215
+ emit({
216
+ kind: "task_context", title: t.title, repository: t.repository ?? repoContext?.name ?? null, branch: repoContext?.branch ?? null,
217
+ sameRepository: repoContext?.same_repository ?? null,
218
+ relevantFiles: t.references ? t.references.items.length + t.references.omitted : t.investigation.files.length + t.investigation.files_omitted,
219
+ previousChanges: t.changes.applied + previous.earlier_tasks.reduce((n, e) => n + e.files_changed.length, 0),
220
+ changedOnDisk: repoState.filter((e) => e.status !== "unchanged").length
221
+ });
222
+ }
223
+ }
43
224
  try {
225
+ const readTools = ideDeclaredReadTools(ctx);
44
226
  const result = await client.chatStream({
45
227
  mode: ctx.mode,
228
+ // The model picked in the panel (shared with the CLI's /model); unset
229
+ // lets the mode choose, exactly as the CLI's chat turns do.
230
+ model: ctx.config.get("model") || undefined,
46
231
  message: compose(message),
47
232
  session_id: sessionId,
48
233
  chat_type: ctx.chatType,
49
- // Reads + editor context, and — only when an approver is present —
50
- // the file-changing tools. Commands are not offered on this surface.
51
- client_tools: ideDeclaredReadTools(ctx),
52
- client_mutation_tools: mutationTools
234
+ // Fast Mode and High Power, shared with the CLI's /fast and /hipwr.
235
+ speed: ctx.fast ? "fast" : undefined,
236
+ high_power: ctx.highPower ? true : undefined,
237
+ // Reads + editor context; the file-changing tools only when an
238
+ // approver is present; in coding mode also the workflow gate and the
239
+ // command tool (each command still needs its own approval).
240
+ client_tools: workflow && readTools ? [...readTools, "coding_workflow"] : readTools,
241
+ client_mutation_tools: mutationTools,
242
+ ...(commandTools ? { client_command_tools: commandTools } : {}),
243
+ ...(repoState.length ? { repository_state: repoState } : {}),
244
+ ...(repoContext ? { repository_context: repoContext } : {})
53
245
  }, {
54
246
  onDelta: (delta) => {
55
247
  if (signal.aborted)
@@ -58,37 +250,106 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
58
250
  ports.onDelta?.(streamed.slice(shown));
59
251
  },
60
252
  onClientToolCall: (call) => {
253
+ // A call that reaches us after Cancel belongs to a stopped turn: it is
254
+ // not run, reviewed or shown. (The stream is closed; nothing awaits it.)
255
+ if (signal.aborted)
256
+ return;
61
257
  // Whatever the model said before asking for this tool belongs above it.
62
258
  say();
63
259
  return handleIdeToolCall(ctx, client, call, {
64
260
  editorState: ports.editorState,
65
261
  resolveRepoForPath: ports.resolveRepoForPath,
66
262
  toolUi: {
67
- onStart: (label, tool) => ports.onToolStart?.(label, tool),
68
- onDone: (label, ok, tool, detail) => ports.onToolEnd?.(label, ok, tool, detail),
69
- mutations
263
+ onStart: (label, tool) => { if (!signal.aborted)
264
+ ports.onToolStart?.(label, tool); },
265
+ onDone: (label, ok, tool, detail) => {
266
+ if (ok)
267
+ taskFiles?.touch(call.name, call.arguments);
268
+ if (!signal.aborted)
269
+ ports.onToolEnd?.(label, ok, tool, detail);
270
+ },
271
+ onRefused: (r) => { if (!signal.aborted)
272
+ emit({ kind: "proposal_refused", ...r }); },
273
+ mutations,
274
+ ...(workflow ? { workflow, readCache, commands } : {})
70
275
  }
71
276
  });
72
277
  }
73
278
  }, signal);
74
279
  // The final message — anything the model did not already narrate.
75
280
  say(result.response);
281
+ if (workflow) {
282
+ workflow.interrupt();
283
+ emitOutcome(workflow, outcome, mutations, emit);
284
+ }
76
285
  if (result.session_id && result.session_id !== sessionId) {
77
286
  ctx.config.set("sessionId", result.session_id);
287
+ rememberPermissionMode(ctx.config);
78
288
  }
79
289
  return { response: result.response, sessionId: result.session_id ?? sessionId, applied: mutations?.applied ?? [] };
80
290
  }
81
291
  catch (err) {
292
+ if (workflow) {
293
+ workflow.interrupt();
294
+ emitOutcome(workflow, outcome, mutations, emit);
295
+ }
82
296
  const e = err;
83
297
  return {
84
298
  response: streamed,
85
299
  sessionId,
86
300
  applied: mutations?.applied ?? [],
87
- error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed." }
301
+ error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed.", ...(e.reason ? { reason: e.reason } : {}) }
88
302
  };
89
303
  }
90
304
  finally {
91
305
  if (externalSignal)
92
306
  externalSignal.removeEventListener("abort", abort);
307
+ // Hash what this turn read or changed, as it is on disk now, for the next
308
+ // turn's freshness report — also after a failed or cancelled turn.
309
+ taskFiles?.touchApplied(mutations?.applied ?? []);
310
+ taskFiles?.commit(ownerScope, ctx.config.get("sessionId"));
311
+ // However the turn ended, nothing it left open — a change review or a
312
+ // command dialog — may still be approved and apply or run afterwards.
313
+ controller.abort();
93
314
  }
94
315
  }
316
+ /** The coordinator's own "✓ Edited <rel> (+a −r) · Applied · <op>" confirmation. */
317
+ const APPLIED = /^✓\s+(\S+)\s+(.+?)\s+\(\+(\d+)\s+−(\d+)\)\s+·\s+Applied\s+·\s+(\S+)$/;
318
+ function commandView(decision, reason, repository, operationId) {
319
+ const contract = executionContract();
320
+ const backend = contract.backend;
321
+ return {
322
+ command: displayCommand(decision.program, decision.args),
323
+ directory: decision.cwdAbsolute,
324
+ runtime: backend ? `${backend}${backend === "docker-engine-v1" ? " · isolated Linux runtime" : backend === "windows-job" ? " · native Windows" : ""}` : "unavailable",
325
+ network: backend === "docker-engine-v1" ? "Disabled" : backend === "windows-job" ? "Not restricted by executor" : "Unavailable",
326
+ risk: decision.tier,
327
+ ...(decision.script ? { script: decision.script.text } : {}),
328
+ reason,
329
+ ...(repository ? { repository } : {}),
330
+ ...(operationId ? { operationId } : {})
331
+ };
332
+ }
333
+ /** The final, verified-or-not summary, from the workflow snapshot and the coordinator's records. */
334
+ function emitOutcome(workflow, outcome, mutations, emit) {
335
+ const snap = workflow.snapshot();
336
+ if (!snap.plan)
337
+ return;
338
+ const validation = (snap.validation ?? []).map((v) => ({
339
+ command: displayCommand(String(v.program ?? ""), Array.isArray(v.args) ? v.args.map(String) : []),
340
+ status: String(v.status ?? "PENDING")
341
+ }));
342
+ const applied = mutations?.applied ?? [];
343
+ const files = Array.isArray(snap.files) && snap.files.length ? snap.files.map(String) : [...new Set(applied.map((a) => a.rel))];
344
+ emit({
345
+ kind: "outcome",
346
+ state: String(snap.state),
347
+ ...(outcome.task ? { task: outcome.task } : { task: snap.plan.summary }),
348
+ files,
349
+ corrections: Number(snap.corrections) || 0,
350
+ operationIds: applied.map((a) => a.operationId),
351
+ validation,
352
+ ...(outcome.counts ? { counts: outcome.counts } : {}),
353
+ verified: String(snap.state) === "COMPLETED" && validation.length > 0 && validation.every((v) => v.status === "PASSED")
354
+ });
355
+ }
@@ -1,4 +1,4 @@
1
- import { declaredClientTools, handleClientToolCall } from "../services/client-tools.js";
1
+ import { declaredClientTools, handleClientToolCall, submitWithRetry } from "../services/client-tools.js";
2
2
  import { workspaceRoot } from "../services/local-files.js";
3
3
  import { MUTATION_TOOL_NAMES } from "../services/mutations.js";
4
4
  import { repositoryForPath } from "../services/workspace-registry.js";
@@ -34,7 +34,7 @@ export async function handleIdeToolCall(ctx, client, call, deps) {
34
34
  payload = { tool_call_id: id, ok: false, error: { code: "IDE_TOOL_FAILED", message: err.message ?? "Failed." } };
35
35
  }
36
36
  payload.duration_ms = Date.now() - started;
37
- await client.submitToolResult(payload).catch(() => undefined);
37
+ await submitWithRetry(client, payload);
38
38
  deps.toolUi.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
39
39
  return;
40
40
  }
package/dist/main.js CHANGED
File without changes