@carrieros/cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +89 -15
  2. package/dist/commands/chat.js +6 -6
  3. package/dist/commands/context.js +40 -0
  4. package/dist/commands/doctor.js +34 -14
  5. package/dist/commands/logout.js +2 -0
  6. package/dist/commands/permissions.js +78 -0
  7. package/dist/commands/scope.js +9 -6
  8. package/dist/commands/sessions.js +5 -0
  9. package/dist/commands/settings.js +83 -10
  10. package/dist/commands/update.js +177 -51
  11. package/dist/commands/usage.js +10 -8
  12. package/dist/commands/version.js +1 -3
  13. package/dist/commands/whoami.js +12 -9
  14. package/dist/ide/editor-context.js +115 -12
  15. package/dist/ide/ide-session.js +288 -18
  16. package/dist/ide/tool-host.js +6 -6
  17. package/dist/main.js +10 -1
  18. package/dist/services/api.js +183 -15
  19. package/dist/services/auth-origin.js +20 -0
  20. package/dist/services/auto-update.js +221 -0
  21. package/dist/services/chat-stream.js +26 -3
  22. package/dist/services/checkpoints.js +176 -14
  23. package/dist/services/client-tools.js +123 -27
  24. package/dist/services/code-intel.js +243 -0
  25. package/dist/services/code-symbols.js +94 -0
  26. package/dist/services/coding-workflow.js +554 -0
  27. package/dist/services/command-coordinator.js +85 -12
  28. package/dist/services/command-policy.js +34 -4
  29. package/dist/services/config.js +96 -11
  30. package/dist/services/container-runner.js +254 -0
  31. package/dist/services/container-supervisor.js +38 -0
  32. package/dist/services/context.js +98 -25
  33. package/dist/services/device-auth.js +33 -6
  34. package/dist/services/execution-platform.js +30 -0
  35. package/dist/services/file-resolver.js +1 -1
  36. package/dist/services/folder-key.js +22 -0
  37. package/dist/services/git-tools.js +181 -0
  38. package/dist/services/helper-bin.js +56 -35
  39. package/dist/services/instruction-resolver.js +54 -0
  40. package/dist/services/job-helper.js +31 -10
  41. package/dist/services/local-files.js +148 -26
  42. package/dist/services/local-tools.js +540 -35
  43. package/dist/services/login-flow.js +44 -13
  44. package/dist/services/meta.js +27 -0
  45. package/dist/services/mutation-coordinator.js +186 -20
  46. package/dist/services/mutation-groups.js +309 -0
  47. package/dist/services/mutation-recovery.js +159 -0
  48. package/dist/services/mutations.js +264 -78
  49. package/dist/services/packaged-update.js +403 -0
  50. package/dist/services/packaged.js +15 -0
  51. package/dist/services/permission-mode.js +78 -0
  52. package/dist/services/process-runner.js +7 -1
  53. package/dist/services/project-context.js +4 -4
  54. package/dist/services/result-reconciliation.js +49 -0
  55. package/dist/services/secure-store.js +21 -1
  56. package/dist/services/session-resolver.js +7 -0
  57. package/dist/services/supported-runtime.js +59 -0
  58. package/dist/services/task-context.js +212 -0
  59. package/dist/services/task-snapshot.js +38 -0
  60. package/dist/services/tool-result-outbox.js +195 -0
  61. package/dist/services/update.js +457 -13
  62. package/dist/services/workspace-registry.js +4 -3
  63. package/dist/services/workspace.js +8 -1
  64. package/dist/shell/shell-chat.js +320 -34
  65. package/dist/shell/shell-commands.js +47 -5
  66. package/dist/shell/shell-prompt.js +21 -11
  67. package/dist/shell/shell-renderer.js +1 -1
  68. package/dist/shell/shell.js +107 -20
  69. package/dist/shell/task-context-view.js +40 -0
  70. package/dist/ui/agent-cards.js +111 -0
  71. package/dist/ui/agent-presentation.js +131 -0
  72. package/dist/ui/approval.js +46 -16
  73. package/dist/ui/banner.js +31 -87
  74. package/dist/ui/change-review.js +293 -46
  75. package/dist/ui/chat-renderer.js +6 -6
  76. package/dist/ui/colors.js +9 -9
  77. package/dist/ui/command-details.js +11 -0
  78. package/dist/ui/command-palette.js +27 -10
  79. package/dist/ui/command-registry.js +11 -4
  80. package/dist/ui/command-review.js +77 -28
  81. package/dist/ui/composer-layout.js +26 -20
  82. package/dist/ui/conversation.js +77 -25
  83. package/dist/ui/live.js +1 -1
  84. package/dist/ui/screen.js +19 -11
  85. package/dist/ui/select.js +6 -0
  86. package/dist/ui/task-context-card.js +99 -0
  87. package/dist/ui/trust.js +7 -12
  88. package/dist/ui/ui.js +23 -0
  89. package/package.json +9 -5
@@ -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,18 +29,177 @@ 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 have their own gate, separate from file changes: CLI opt-in or
37
+ // Auto mode, contained runtime, trusted repository, and live panel decision UI.
38
+ const commandTools = permission.commands && ports.commandsAllowed && ports.reviewCommand
39
+ ? declaredCommandTools(ctx, ports.commandsAllowed && !!ports.reviewCommand, ports.permissionMode === "auto")
40
+ : undefined;
41
+ const emit = (event) => {
42
+ try {
43
+ ports.onWorkflowEvent?.(event);
44
+ }
45
+ catch { /* presentation must never break a turn */ }
46
+ };
47
+ // Coding mode: the SAME CodingWorkflow the CLI uses gates plan → reads →
48
+ // approved change → approved test → analysis → correction → retest. Only
49
+ // when commands are available, because a plan must name its verification.
50
+ const readCache = new TurnReadCache();
51
+ const outcome = {};
52
+ let workflow;
53
+ if (commandTools) {
54
+ workflow = new CodingWorkflow(async () => {
55
+ const contract = executionContract();
56
+ if (contract.capability === "UNSUPPORTED")
57
+ throw new Error(contract.prerequisite);
58
+ if (contract.capability === "ISOLATED_RUNTIME_REQUIRED")
59
+ await verifyContainerRuntime(containerRuntime());
60
+ else
61
+ ensureJobHelper();
62
+ return contract;
63
+ }, (lines) => {
64
+ const snap = workflow.snapshot();
65
+ if (lines[0]?.startsWith("Plan:")) {
66
+ const plan = snap.plan;
67
+ if (!plan)
68
+ return;
69
+ const corrective = Number(snap.corrections) > 0;
70
+ if (!outcome.task && !corrective)
71
+ outcome.task = plan.summary;
72
+ emit({
73
+ kind: "plan", corrective, task: plan.summary, files: plan.files.map((f) => f.path),
74
+ // The workflow's own per-file reasons, shown as the plan's steps.
75
+ steps: plan.files.map((f) => ({ path: f.path, reason: typeof f.reason === "string" ? f.reason : "" })),
76
+ validation: plan.tests.map((t) => displayCommand(String(t.program ?? ""), Array.isArray(t.args) ? t.args.map(String) : [])),
77
+ ...(corrective && outcome.rootCause ? { rootCause: outcome.rootCause } : plan.expected ? { expected: plan.expected } : {}),
78
+ ...(plan.risks ? { risks: plan.risks } : {}),
79
+ // The investigation the workflow verified: symptom → path → cause → change location.
80
+ ...(plan.investigation ? { investigation: {
81
+ symptom: plan.investigation.symptom, rootCause: plan.investigation.root_cause,
82
+ changeLocation: `${plan.investigation.change_location.path}${plan.investigation.change_location.symbol ? ` · ${plan.investigation.change_location.symbol}` : ""}`,
83
+ path: plan.investigation.execution_path.map((s) => (s.symbol ? `${s.path} · ${s.symbol}` : s.path)),
84
+ evidence: plan.investigation.evidence.map((e) => `${e.path}${e.lines ? `:${e.lines}` : ""} — ${e.note}`),
85
+ ruledOut: plan.investigation.ruled_out.map((r) => `${r.path} — ${r.reason}`)
86
+ } } : {})
87
+ });
88
+ }
89
+ else if (lines[0]?.startsWith("Failure analysis")) {
90
+ const a = analysisExplanation(lines);
91
+ outcome.rootCause = a.explanation;
92
+ emit({ kind: "analysis", classification: a.classification, explanation: a.explanation });
93
+ }
94
+ emit({ kind: "state", state: String(snap.state), corrections: Number(snap.corrections) || 0 });
95
+ }, { signal, recoveryScope: () => client.mutationRecoveryScope(), onReadsInvalidated: () => readCache.invalidate() });
96
+ }
21
97
  const mutations = mutationTools
22
98
  ? createMutationCoordinator({
23
- submit: (payload) => submitWithRetry(client, payload),
99
+ signal,
100
+ recoveryScope: () => client.mutationRecoveryScope(),
101
+ ...(workflow
102
+ ? { approvalContext: () => workflow.approvalContext(), validatePlans: (plans) => workflow.beforeMutation(plans) }
103
+ : {}),
104
+ approveEditsByPolicy: () => permission.approveEditsByPolicy,
105
+ // The workflow records the outcome before the server can see it, so an
106
+ // immediate reply (the next tool call) finds the change already recorded.
107
+ record: (payload) => workflow?.mutationResult(payload),
108
+ submit: async (payload) => {
109
+ await submitWithRetry(client, payload);
110
+ },
24
111
  ui: {
25
- review: (plans) => ports.reviewMutations(plans),
26
- note: (lines) => ports.onMutationNote?.(lines),
112
+ review: async (plans) => {
113
+ const decision = await ports.reviewMutations(plans, { corrective: Number(workflow?.snapshot().corrections ?? 0) > 0 }, signal);
114
+ workflow?.approval(decision);
115
+ return decision;
116
+ },
117
+ approvedByPolicy: (plans) => {
118
+ workflow?.approval("approve");
119
+ emit({ kind: "edits_accepted", mode: ports.permissionMode ?? "accept_edits", files: plans.map((p) => ({ path: p.rel, additions: p.diff.added, deletions: p.diff.removed })) });
120
+ },
121
+ note: (lines) => {
122
+ ports.onMutationNote?.(lines);
123
+ const applied = lines.map((l) => APPLIED.exec(l.trim())).filter((m) => !!m)
124
+ .map((m) => ({ rel: m[2], added: Number(m[3]), removed: Number(m[4]), operationId: m[5] }));
125
+ if (applied.length)
126
+ emit({ kind: "changes_applied", changes: applied });
127
+ },
128
+ noLongerValid: (rels) => emit({ kind: "change_invalidated", files: rels }),
129
+ rejected: (plans) => emit({ kind: "change_rejected", files: plans.map((p) => p.rel) }),
130
+ applyFailed: (f) => emit({ kind: "apply_failed", ...f }),
131
+ refused: (r) => emit({ kind: "proposal_refused", proposal: "change", ...(r.files.length ? { target: r.files.join(", ") } : {}), code: r.code, reason: r.message }),
27
132
  cancelTurn: abort
28
133
  }
29
134
  })
30
135
  : undefined;
31
- const sessionId = ctx.config.get("sessionId");
136
+ let commands;
137
+ if (commandTools && workflow) {
138
+ // One review at a time: a change review and a command review never overlap.
139
+ let lane = Promise.resolve();
140
+ const auth = ctx.config.get("auth");
141
+ commands = createCommandCoordinator({
142
+ root: workspaceRoot(),
143
+ signal,
144
+ withTerminal: (fn) => { const run = lane.then(fn, fn); lane = run.catch(() => undefined); return run; },
145
+ recoveryScope: () => client.mutationRecoveryScope(),
146
+ approvalContext: () => workflow.approvalContext(),
147
+ cliSecrets: [auth?.accessToken, auth?.refreshToken, ctx.config.get("secretKey")].filter((v) => typeof v === "string"),
148
+ submit: async (payload) => {
149
+ await submitWithRetry(client, payload);
150
+ const wasAnalyzing = workflow.state === "ANALYZING_FAILURE";
151
+ workflow.commandResult(payload);
152
+ if (!wasAnalyzing && workflow.state === "ANALYZING_FAILURE") {
153
+ emit({ kind: "validation_failed", counts: outcome.counts, failure: outcome.failure });
154
+ }
155
+ emit({ kind: "state", state: String(workflow.snapshot().state), corrections: Number(workflow.snapshot().corrections) || 0 });
156
+ },
157
+ ui: {
158
+ // Cancelled turns show no review and take no decision — not even one
159
+ // queued before Cancel and reached after it.
160
+ review: async (decision, reason, repository, operationId) => {
161
+ if (signal.aborted)
162
+ return "cancel";
163
+ // Auto: locally admitted commands are approved by session policy, and say so.
164
+ if (permission.approveCommandByPolicy(decision.tier)) {
165
+ emit({ kind: "command_auto_approved", command: displayCommand(decision.program, decision.effectiveArgs), tier: decision.tier });
166
+ return "approve";
167
+ }
168
+ const answer = await ports.reviewCommand(commandView(decision, reason, repository, operationId), signal);
169
+ return signal.aborted ? "cancel" : answer;
170
+ },
171
+ started: (decision) => emit({ kind: "command_started", command: displayCommand(decision.program, decision.effectiveArgs) }),
172
+ output: () => { },
173
+ finished: ({ decision, result, errorCode, message }) => {
174
+ const command = decision ? displayCommand(decision.program, decision.args) : "command";
175
+ if (!result) {
176
+ const declined = errorCode === "COMMAND_REJECTED" || errorCode === "APPROVAL_TIMEOUT" || errorCode === "COMMAND_CANCELLED";
177
+ // Refused before any review (policy, repository, runtime): a refusal, not a failed run.
178
+ if (!declined)
179
+ emit({ kind: "proposal_refused", proposal: "command", target: command, code: errorCode ?? "COMMAND_REFUSED", reason: message ?? "The command was refused. Nothing ran." });
180
+ else
181
+ emit({ kind: "command_result", command, status: "declined", exitCode: null, tests: [], message: message ?? errorCode });
182
+ return;
183
+ }
184
+ const counts = summariseOutput(result.output) || undefined;
185
+ const report = parseTestReport(result.output);
186
+ outcome.counts = counts;
187
+ outcome.failure = report.failure;
188
+ const status = result.timed_out ? "timed_out" : result.cancelled ? "cancelled" : result.exit_code === 0 ? "passed" : "failed";
189
+ emit({ kind: "command_result", command, status, exitCode: result.exit_code, counts, tests: report.tests.slice(0, 30), durationMs: result.duration_ms });
190
+ },
191
+ cancelTurn: abort
192
+ }
193
+ });
194
+ }
195
+ // Task Context: what earlier coding work in this conversation touched, and
196
+ // whether it is still the same repository and the same bytes. Context only.
197
+ const taskFiles = workflow ? new TaskFileLedger() : undefined;
198
+ const ownerScope = workflow ? client.mutationRecoveryScope() : undefined;
199
+ const hasSessionOverride = Object.prototype.hasOwnProperty.call(ports, "sessionId");
200
+ const sessionId = hasSessionOverride ? ports.sessionId : ctx.config.get("sessionId");
201
+ const chatType = ports.chatType ?? ctx.chatType;
202
+ let resultSessionId = sessionId;
32
203
  const compose = ports.composeMessage ?? ((m) => m);
33
204
  // What the model has said so far. It narrates as it works; commit each span at
34
205
  // a tool boundary so a progress line lands above the activity it describes.
@@ -40,16 +211,45 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
40
211
  if (text.trim())
41
212
  ports.onAssistantText(text);
42
213
  };
214
+ const repoContext = workflow ? repositoryContext(ownerScope, sessionId) : null;
215
+ const repoState = workflow && sessionId && repoContext?.same_repository !== false ? repositoryState(ownerScope, sessionId) : [];
216
+ if (workflow && sessionId && typeof client.taskContext === "function") {
217
+ const previous = await client.taskContext(sessionId).catch(() => null);
218
+ if (previous?.current) {
219
+ const t = previous.current;
220
+ emit({
221
+ kind: "task_context", title: t.title, repository: t.repository ?? repoContext?.name ?? null, branch: repoContext?.branch ?? null,
222
+ sameRepository: repoContext?.same_repository ?? null,
223
+ relevantFiles: t.references ? t.references.items.length + t.references.omitted : t.investigation.files.length + t.investigation.files_omitted,
224
+ previousChanges: t.changes.applied + previous.earlier_tasks.reduce((n, e) => n + e.files_changed.length, 0),
225
+ changedOnDisk: repoState.filter((e) => e.status !== "unchanged").length
226
+ });
227
+ }
228
+ }
43
229
  try {
230
+ const readTools = ideDeclaredReadTools(ctx);
44
231
  const result = await client.chatStream({
45
232
  mode: ctx.mode,
233
+ // The model picked in the panel (shared with the CLI's /model); unset
234
+ // lets the mode choose, exactly as the CLI's chat turns do.
235
+ model: ctx.config.get("model") || undefined,
46
236
  message: compose(message),
47
237
  session_id: sessionId,
48
- 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
238
+ chat_type: chatType,
239
+ file_ids: ports.fileIds?.length ? ports.fileIds : undefined,
240
+ ...(ports.webSearch === true ? { web_search: true } : {}),
241
+ // Fast Mode and High Power, shared with the CLI's /fast and /hipwr.
242
+ speed: ctx.fast ? "fast" : undefined,
243
+ high_power: ctx.highPower ? true : undefined,
244
+ // Reads + editor context; the file-changing tools only when an
245
+ // approver is present; in coding mode also the workflow gate and the
246
+ // command tool (Manual/Accept Edits review each command; Auto follows
247
+ // command policy without an individual prompt).
248
+ client_tools: workflow && readTools ? [...readTools, "coding_workflow"] : readTools,
249
+ client_mutation_tools: mutationTools,
250
+ ...(commandTools ? { client_command_tools: commandTools } : {}),
251
+ ...(repoState.length ? { repository_state: repoState } : {}),
252
+ ...(repoContext ? { repository_context: repoContext } : {})
53
253
  }, {
54
254
  onDelta: (delta) => {
55
255
  if (signal.aborted)
@@ -58,37 +258,107 @@ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
58
258
  ports.onDelta?.(streamed.slice(shown));
59
259
  },
60
260
  onClientToolCall: (call) => {
261
+ // A call that reaches us after Cancel belongs to a stopped turn: it is
262
+ // not run, reviewed or shown. (The stream is closed; nothing awaits it.)
263
+ if (signal.aborted)
264
+ return;
61
265
  // Whatever the model said before asking for this tool belongs above it.
62
266
  say();
63
267
  return handleIdeToolCall(ctx, client, call, {
64
268
  editorState: ports.editorState,
65
269
  resolveRepoForPath: ports.resolveRepoForPath,
66
270
  toolUi: {
67
- onStart: (label, tool) => ports.onToolStart?.(label, tool),
68
- onDone: (label, ok, tool, detail) => ports.onToolEnd?.(label, ok, tool, detail),
69
- mutations
271
+ onStart: (label, tool) => { if (!signal.aborted)
272
+ ports.onToolStart?.(label, tool); },
273
+ onDone: (label, ok, tool, detail) => {
274
+ if (ok)
275
+ taskFiles?.touch(call.name, call.arguments);
276
+ if (!signal.aborted)
277
+ ports.onToolEnd?.(label, ok, tool, detail);
278
+ },
279
+ onRefused: (r) => { if (!signal.aborted)
280
+ emit({ kind: "proposal_refused", ...r }); },
281
+ mutations,
282
+ ...(workflow ? { workflow, readCache, commands } : {})
70
283
  }
71
284
  });
72
285
  }
73
286
  }, signal);
74
287
  // The final message — anything the model did not already narrate.
75
288
  say(result.response);
76
- if (result.session_id && result.session_id !== sessionId) {
289
+ if (workflow) {
290
+ workflow.interrupt();
291
+ emitOutcome(workflow, outcome, mutations, emit);
292
+ }
293
+ resultSessionId = result.session_id ?? sessionId;
294
+ if (!hasSessionOverride && result.session_id && result.session_id !== sessionId) {
77
295
  ctx.config.set("sessionId", result.session_id);
296
+ rememberPermissionMode(ctx.config);
78
297
  }
79
- return { response: result.response, sessionId: result.session_id ?? sessionId, applied: mutations?.applied ?? [] };
298
+ return { response: result.response, sessionId: resultSessionId, applied: mutations?.applied ?? [] };
80
299
  }
81
300
  catch (err) {
301
+ if (workflow) {
302
+ workflow.interrupt();
303
+ emitOutcome(workflow, outcome, mutations, emit);
304
+ }
82
305
  const e = err;
83
306
  return {
84
307
  response: streamed,
85
- sessionId,
308
+ sessionId: resultSessionId,
86
309
  applied: mutations?.applied ?? [],
87
- error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed." }
310
+ error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed.", ...(e.reason ? { reason: e.reason } : {}) }
88
311
  };
89
312
  }
90
313
  finally {
91
314
  if (externalSignal)
92
315
  externalSignal.removeEventListener("abort", abort);
316
+ // Hash what this turn read or changed, as it is on disk now, for the next
317
+ // turn's freshness report — also after a failed or cancelled turn.
318
+ taskFiles?.touchApplied(mutations?.applied ?? []);
319
+ taskFiles?.commit(ownerScope, resultSessionId);
320
+ // However the turn ended, nothing it left open — a change review or a
321
+ // command dialog — may still be approved and apply or run afterwards.
322
+ controller.abort();
93
323
  }
94
324
  }
325
+ /** The coordinator's own "✓ Edited <rel> (+a −r) · Applied · <op>" confirmation. */
326
+ const APPLIED = /^✓\s+(\S+)\s+(.+?)\s+\(\+(\d+)\s+−(\d+)\)\s+·\s+Applied\s+·\s+(\S+)$/;
327
+ function commandView(decision, reason, repository, operationId) {
328
+ const contract = executionContract();
329
+ const backend = contract.backend;
330
+ return {
331
+ command: displayCommand(decision.program, decision.args),
332
+ directory: decision.cwdAbsolute,
333
+ runtime: backend ? `${backend}${backend === "docker-engine-v1" ? " · isolated Linux runtime" : backend === "windows-job" ? " · native Windows" : ""}` : "unavailable",
334
+ network: backend === "docker-engine-v1" ? "Disabled" : backend === "windows-job" ? "Not restricted by executor" : "Unavailable",
335
+ risk: decision.tier,
336
+ ...(decision.script ? { script: decision.script.text } : {}),
337
+ reason,
338
+ ...(repository ? { repository } : {}),
339
+ ...(operationId ? { operationId } : {})
340
+ };
341
+ }
342
+ /** The final, verified-or-not summary, from the workflow snapshot and the coordinator's records. */
343
+ function emitOutcome(workflow, outcome, mutations, emit) {
344
+ const snap = workflow.snapshot();
345
+ if (!snap.plan)
346
+ return;
347
+ const validation = (snap.validation ?? []).map((v) => ({
348
+ command: displayCommand(String(v.program ?? ""), Array.isArray(v.args) ? v.args.map(String) : []),
349
+ status: String(v.status ?? "PENDING")
350
+ }));
351
+ const applied = mutations?.applied ?? [];
352
+ const files = Array.isArray(snap.files) && snap.files.length ? snap.files.map(String) : [...new Set(applied.map((a) => a.rel))];
353
+ emit({
354
+ kind: "outcome",
355
+ state: String(snap.state),
356
+ ...(outcome.task ? { task: outcome.task } : { task: snap.plan.summary }),
357
+ files,
358
+ corrections: Number(snap.corrections) || 0,
359
+ operationIds: applied.map((a) => a.operationId),
360
+ validation,
361
+ ...(outcome.counts ? { counts: outcome.counts } : {}),
362
+ verified: String(snap.state) === "COMPLETED" && validation.length > 0 && validation.every((v) => v.status === "PASSED")
363
+ });
364
+ }
@@ -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
  }
@@ -92,10 +92,10 @@ export function ideDeclaredReadTools(ctx) {
92
92
  * present, no mutation tools are declared, exactly as a piped CLI run offers
93
93
  * none.
94
94
  *
95
- * Commands are deliberately NOT offered on the IDE surface in V1: the CLI's
96
- * `run_command` depends on Windows Job Object containment wired to the terminal
97
- * lifecycle and an explicit opt-in, and porting that containment to the IDE is a
98
- * separate security review. Until then the IDE stays read + change only.
95
+ * Commands are offered only when the extension has a live command decision UI,
96
+ * the CLI opt-in or Auto mode enables them, the repository is trusted, and the
97
+ * shared executor reports the required containment adapter. The CLI's existing
98
+ * coordinator performs the actual policy and approval decision.
99
99
  */
100
100
  export function ideDeclaredMutationTools(ctx, approverPresent) {
101
101
  if (!approverPresent)
package/dist/main.js CHANGED
@@ -31,17 +31,26 @@ import { registerVersion } from "./commands/version.js";
31
31
  import { registerWhoami } from "./commands/whoami.js";
32
32
  import { ApiError } from "./services/api.js";
33
33
  import { ConfigStore } from "./services/config.js";
34
+ import { setClientIdentity, setClientReleaseChannel } from "./services/meta.js";
35
+ import { isPackaged } from "./services/packaged.js";
36
+ import { updateSettings } from "./services/auto-update.js";
34
37
  import { AuthRequiredError, CommandContext } from "./services/context.js";
35
38
  import { cliVersion } from "./services/meta.js";
36
39
  import { errorLine } from "./services/output.js";
37
40
  import { runShell } from "./shell/shell.js";
38
41
  import { loadAccent } from "./ui/theme.js";
39
42
  async function main() {
40
- const ctx = new CommandContext(new ConfigStore());
43
+ const stagingProfile = process.env.CARRIEROS_CLI_PROFILE === "staging";
44
+ const ctx = new CommandContext(new ConfigStore(stagingProfile
45
+ ? { fixedApiUrl: "https://api.carrieros.site/v1" }
46
+ : {}));
41
47
  // Trust is per repository, so the registry has to be able to read it.
42
48
  attachConfig(ctx.config);
43
49
  // Restore the saved accent color before anything renders.
44
50
  loadAccent(ctx.config.get("theme")?.accent);
51
+ // Identify this client on every API request (version + release channel).
52
+ setClientIdentity(isPackaged() ? "cli-exe" : "cli");
53
+ setClientReleaseChannel(updateSettings(ctx.config).channel);
45
54
  const program = new Command();
46
55
  program
47
56
  .name("cos")