@carrieros/cli-staging 0.0.0-stage → 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 (136) hide show
  1. package/README.md +6 -2
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/auth.js +60 -0
  4. package/dist/commands/btw.js +78 -0
  5. package/dist/commands/changes.js +167 -0
  6. package/dist/commands/chat.js +182 -0
  7. package/dist/commands/context.js +200 -0
  8. package/dist/commands/doctor.js +119 -0
  9. package/dist/commands/files.js +94 -0
  10. package/dist/commands/help.js +37 -0
  11. package/dist/commands/history.js +112 -0
  12. package/dist/commands/login.js +62 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/memory.js +162 -0
  15. package/dist/commands/mode-model.js +64 -0
  16. package/dist/commands/models.js +28 -0
  17. package/dist/commands/modes.js +30 -0
  18. package/dist/commands/permissions.js +77 -0
  19. package/dist/commands/project.js +106 -0
  20. package/dist/commands/repo.js +146 -0
  21. package/dist/commands/repos.js +61 -0
  22. package/dist/commands/review.js +92 -0
  23. package/dist/commands/scope.js +155 -0
  24. package/dist/commands/search.js +92 -0
  25. package/dist/commands/sessions.js +282 -0
  26. package/dist/commands/settings.js +100 -0
  27. package/dist/commands/update.js +229 -0
  28. package/dist/commands/upload.js +223 -0
  29. package/dist/commands/usage.js +227 -0
  30. package/dist/commands/version.js +26 -0
  31. package/dist/commands/whoami.js +44 -0
  32. package/dist/ide/editor-context.js +275 -0
  33. package/dist/ide/ide-session.js +360 -0
  34. package/dist/ide/tool-host.js +109 -0
  35. package/dist/main.js +126 -0
  36. package/dist/services/api.js +439 -0
  37. package/dist/services/auth-origin.js +20 -0
  38. package/dist/services/chat-stream.js +168 -0
  39. package/dist/services/checkpoints.js +278 -0
  40. package/dist/services/client-tools.js +356 -0
  41. package/dist/services/code-intel.js +243 -0
  42. package/dist/services/code-symbols.js +94 -0
  43. package/dist/services/coding-workflow.js +554 -0
  44. package/dist/services/command-coordinator.js +273 -0
  45. package/dist/services/command-policy.js +434 -0
  46. package/dist/services/config.js +383 -0
  47. package/dist/services/container-runner.js +254 -0
  48. package/dist/services/container-supervisor.js +38 -0
  49. package/dist/services/context.js +371 -0
  50. package/dist/services/device-auth.js +286 -0
  51. package/dist/services/diff.js +196 -0
  52. package/dist/services/env-policy.js +108 -0
  53. package/dist/services/execution-platform.js +30 -0
  54. package/dist/services/file-detect.js +104 -0
  55. package/dist/services/file-resolver.js +199 -0
  56. package/dist/services/file-upload.js +126 -0
  57. package/dist/services/folder-key.js +22 -0
  58. package/dist/services/git-tools.js +429 -0
  59. package/dist/services/glob-match.js +164 -0
  60. package/dist/services/helper-bin.js +85 -0
  61. package/dist/services/ignore-rules.js +189 -0
  62. package/dist/services/instruction-resolver.js +54 -0
  63. package/dist/services/job-helper.js +328 -0
  64. package/dist/services/local-files.js +639 -0
  65. package/dist/services/local-tools.js +937 -0
  66. package/dist/services/login-flow.js +156 -0
  67. package/dist/services/meta.js +15 -0
  68. package/dist/services/mutation-coordinator.js +327 -0
  69. package/dist/services/mutation-groups.js +309 -0
  70. package/dist/services/mutation-recovery.js +159 -0
  71. package/dist/services/mutations.js +679 -0
  72. package/dist/services/open-url.js +68 -0
  73. package/dist/services/output.js +62 -0
  74. package/dist/services/packaged-update.js +403 -0
  75. package/dist/services/packaged.js +39 -0
  76. package/dist/services/permission-mode.js +78 -0
  77. package/dist/services/process-runner.js +412 -0
  78. package/dist/services/project-context.js +298 -0
  79. package/dist/services/redaction.js +201 -0
  80. package/dist/services/result-reconciliation.js +49 -0
  81. package/dist/services/secure-store.js +217 -0
  82. package/dist/services/session-resolver.js +113 -0
  83. package/dist/services/sia.js +51 -0
  84. package/dist/services/spinner.js +40 -0
  85. package/dist/services/supported-runtime.js +59 -0
  86. package/dist/services/task-context.js +212 -0
  87. package/dist/services/task-snapshot.js +38 -0
  88. package/dist/services/tool-result-outbox.js +195 -0
  89. package/dist/services/update.js +311 -0
  90. package/dist/services/workspace-registry.js +310 -0
  91. package/dist/services/workspace.js +580 -0
  92. package/dist/shell/shell-chat.js +1619 -0
  93. package/dist/shell/shell-commands.js +411 -0
  94. package/dist/shell/shell-prompt.js +110 -0
  95. package/dist/shell/shell-renderer.js +51 -0
  96. package/dist/shell/shell-router.js +37 -0
  97. package/dist/shell/shell.js +389 -0
  98. package/dist/shell/task-context-view.js +40 -0
  99. package/dist/staging.js +5 -0
  100. package/dist/types/index.js +6 -0
  101. package/dist/ui/agent-cards.js +111 -0
  102. package/dist/ui/agent-presentation.js +131 -0
  103. package/dist/ui/approval.js +111 -0
  104. package/dist/ui/banner.js +56 -0
  105. package/dist/ui/btw-overlay.js +230 -0
  106. package/dist/ui/change-review.js +334 -0
  107. package/dist/ui/chat-renderer.js +463 -0
  108. package/dist/ui/code-block.js +52 -0
  109. package/dist/ui/color-picker.js +100 -0
  110. package/dist/ui/colors.js +55 -0
  111. package/dist/ui/command-details.js +11 -0
  112. package/dist/ui/command-filter.js +92 -0
  113. package/dist/ui/command-item.js +6 -0
  114. package/dist/ui/command-palette.js +383 -0
  115. package/dist/ui/command-registry.js +128 -0
  116. package/dist/ui/command-renderer.js +55 -0
  117. package/dist/ui/command-review.js +187 -0
  118. package/dist/ui/composer-layout.js +74 -0
  119. package/dist/ui/conversation.js +450 -0
  120. package/dist/ui/interrupt.js +35 -0
  121. package/dist/ui/live.js +141 -0
  122. package/dist/ui/logo.js +58 -0
  123. package/dist/ui/markdown.js +205 -0
  124. package/dist/ui/message.js +21 -0
  125. package/dist/ui/screen-prompt.js +181 -0
  126. package/dist/ui/screen.js +297 -0
  127. package/dist/ui/select.js +284 -0
  128. package/dist/ui/sia-qa.js +213 -0
  129. package/dist/ui/spinner.js +23 -0
  130. package/dist/ui/sticky-stream.js +64 -0
  131. package/dist/ui/task-context-card.js +99 -0
  132. package/dist/ui/text-prompt.js +74 -0
  133. package/dist/ui/theme.js +80 -0
  134. package/dist/ui/trust.js +88 -0
  135. package/dist/ui/ui.js +101 -0
  136. package/package.json +33 -4
@@ -0,0 +1,360 @@
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";
14
+ import { createMutationCoordinator } from "../services/mutation-coordinator.js";
15
+ import { handleIdeToolCall, ideDeclaredMutationTools, ideDeclaredReadTools } from "./tool-host.js";
16
+ /**
17
+ * Run one IDE turn. Never throws: transport and stream failures come back as
18
+ * `result.error`, so the binding renders them without a second failure path.
19
+ */
20
+ export async function runIdeTurn(ctx, client, message, ports, externalSignal) {
21
+ const controller = new AbortController();
22
+ const abort = () => controller.abort();
23
+ if (externalSignal) {
24
+ if (externalSignal.aborted)
25
+ abort();
26
+ else
27
+ externalSignal.addEventListener("abort", abort, { once: true });
28
+ }
29
+ const signal = controller.signal;
30
+ // File-changing tools, gated exactly as the CLI gates them — trust plus a
31
+ // present approver (here, a live panel). Reads are gated on trust alone.
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
+ }
97
+ const mutations = mutationTools
98
+ ? createMutationCoordinator({
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
+ },
111
+ ui: {
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 }),
132
+ cancelTurn: abort
133
+ }
134
+ })
135
+ : undefined;
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 sessionId = ctx.config.get("sessionId");
200
+ const compose = ports.composeMessage ?? ((m) => m);
201
+ // What the model has said so far. It narrates as it works; commit each span at
202
+ // a tool boundary so a progress line lands above the activity it describes.
203
+ let streamed = "";
204
+ let shown = 0;
205
+ const say = (upTo = streamed) => {
206
+ const text = upTo.slice(shown);
207
+ shown = upTo.length;
208
+ if (text.trim())
209
+ ports.onAssistantText(text);
210
+ };
211
+ const repoContext = workflow ? repositoryContext(ownerScope, sessionId) : null;
212
+ const repoState = workflow && sessionId && repoContext?.same_repository !== false ? repositoryState(ownerScope, sessionId) : [];
213
+ if (workflow && sessionId && typeof client.taskContext === "function") {
214
+ const previous = await client.taskContext(sessionId).catch(() => null);
215
+ if (previous?.current) {
216
+ const t = previous.current;
217
+ emit({
218
+ kind: "task_context", title: t.title, repository: t.repository ?? repoContext?.name ?? null, branch: repoContext?.branch ?? null,
219
+ sameRepository: repoContext?.same_repository ?? null,
220
+ relevantFiles: t.references ? t.references.items.length + t.references.omitted : t.investigation.files.length + t.investigation.files_omitted,
221
+ previousChanges: t.changes.applied + previous.earlier_tasks.reduce((n, e) => n + e.files_changed.length, 0),
222
+ changedOnDisk: repoState.filter((e) => e.status !== "unchanged").length
223
+ });
224
+ }
225
+ }
226
+ try {
227
+ const readTools = ideDeclaredReadTools(ctx);
228
+ const result = await client.chatStream({
229
+ mode: ctx.mode,
230
+ // The model picked in the panel (shared with the CLI's /model); unset
231
+ // lets the mode choose, exactly as the CLI's chat turns do.
232
+ model: ctx.config.get("model") || undefined,
233
+ message: compose(message),
234
+ session_id: sessionId,
235
+ chat_type: ctx.chatType,
236
+ file_ids: ports.fileIds?.length ? ports.fileIds : undefined,
237
+ ...(ports.webSearch === true ? { web_search: true } : {}),
238
+ // Fast Mode and High Power, shared with the CLI's /fast and /hipwr.
239
+ speed: ctx.fast ? "fast" : undefined,
240
+ high_power: ctx.highPower ? true : undefined,
241
+ // Reads + editor context; the file-changing tools only when an
242
+ // approver is present; in coding mode also the workflow gate and the
243
+ // command tool (Manual/Accept Edits review each command; Auto follows
244
+ // command policy without an individual prompt).
245
+ client_tools: workflow && readTools ? [...readTools, "coding_workflow"] : readTools,
246
+ client_mutation_tools: mutationTools,
247
+ ...(commandTools ? { client_command_tools: commandTools } : {}),
248
+ ...(repoState.length ? { repository_state: repoState } : {}),
249
+ ...(repoContext ? { repository_context: repoContext } : {})
250
+ }, {
251
+ onDelta: (delta) => {
252
+ if (signal.aborted)
253
+ return;
254
+ streamed += delta;
255
+ ports.onDelta?.(streamed.slice(shown));
256
+ },
257
+ onClientToolCall: (call) => {
258
+ // A call that reaches us after Cancel belongs to a stopped turn: it is
259
+ // not run, reviewed or shown. (The stream is closed; nothing awaits it.)
260
+ if (signal.aborted)
261
+ return;
262
+ // Whatever the model said before asking for this tool belongs above it.
263
+ say();
264
+ return handleIdeToolCall(ctx, client, call, {
265
+ editorState: ports.editorState,
266
+ resolveRepoForPath: ports.resolveRepoForPath,
267
+ toolUi: {
268
+ onStart: (label, tool) => { if (!signal.aborted)
269
+ ports.onToolStart?.(label, tool); },
270
+ onDone: (label, ok, tool, detail) => {
271
+ if (ok)
272
+ taskFiles?.touch(call.name, call.arguments);
273
+ if (!signal.aborted)
274
+ ports.onToolEnd?.(label, ok, tool, detail);
275
+ },
276
+ onRefused: (r) => { if (!signal.aborted)
277
+ emit({ kind: "proposal_refused", ...r }); },
278
+ mutations,
279
+ ...(workflow ? { workflow, readCache, commands } : {})
280
+ }
281
+ });
282
+ }
283
+ }, signal);
284
+ // The final message — anything the model did not already narrate.
285
+ say(result.response);
286
+ if (workflow) {
287
+ workflow.interrupt();
288
+ emitOutcome(workflow, outcome, mutations, emit);
289
+ }
290
+ if (result.session_id && result.session_id !== sessionId) {
291
+ ctx.config.set("sessionId", result.session_id);
292
+ rememberPermissionMode(ctx.config);
293
+ }
294
+ return { response: result.response, sessionId: result.session_id ?? sessionId, applied: mutations?.applied ?? [] };
295
+ }
296
+ catch (err) {
297
+ if (workflow) {
298
+ workflow.interrupt();
299
+ emitOutcome(workflow, outcome, mutations, emit);
300
+ }
301
+ const e = err;
302
+ return {
303
+ response: streamed,
304
+ sessionId,
305
+ applied: mutations?.applied ?? [],
306
+ error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed.", ...(e.reason ? { reason: e.reason } : {}) }
307
+ };
308
+ }
309
+ finally {
310
+ if (externalSignal)
311
+ externalSignal.removeEventListener("abort", abort);
312
+ // Hash what this turn read or changed, as it is on disk now, for the next
313
+ // turn's freshness report — also after a failed or cancelled turn.
314
+ taskFiles?.touchApplied(mutations?.applied ?? []);
315
+ taskFiles?.commit(ownerScope, ctx.config.get("sessionId"));
316
+ // However the turn ended, nothing it left open — a change review or a
317
+ // command dialog — may still be approved and apply or run afterwards.
318
+ controller.abort();
319
+ }
320
+ }
321
+ /** The coordinator's own "✓ Edited <rel> (+a −r) · Applied · <op>" confirmation. */
322
+ const APPLIED = /^✓\s+(\S+)\s+(.+?)\s+\(\+(\d+)\s+−(\d+)\)\s+·\s+Applied\s+·\s+(\S+)$/;
323
+ function commandView(decision, reason, repository, operationId) {
324
+ const contract = executionContract();
325
+ const backend = contract.backend;
326
+ return {
327
+ command: displayCommand(decision.program, decision.args),
328
+ directory: decision.cwdAbsolute,
329
+ runtime: backend ? `${backend}${backend === "docker-engine-v1" ? " · isolated Linux runtime" : backend === "windows-job" ? " · native Windows" : ""}` : "unavailable",
330
+ network: backend === "docker-engine-v1" ? "Disabled" : backend === "windows-job" ? "Not restricted by executor" : "Unavailable",
331
+ risk: decision.tier,
332
+ ...(decision.script ? { script: decision.script.text } : {}),
333
+ reason,
334
+ ...(repository ? { repository } : {}),
335
+ ...(operationId ? { operationId } : {})
336
+ };
337
+ }
338
+ /** The final, verified-or-not summary, from the workflow snapshot and the coordinator's records. */
339
+ function emitOutcome(workflow, outcome, mutations, emit) {
340
+ const snap = workflow.snapshot();
341
+ if (!snap.plan)
342
+ return;
343
+ const validation = (snap.validation ?? []).map((v) => ({
344
+ command: displayCommand(String(v.program ?? ""), Array.isArray(v.args) ? v.args.map(String) : []),
345
+ status: String(v.status ?? "PENDING")
346
+ }));
347
+ const applied = mutations?.applied ?? [];
348
+ const files = Array.isArray(snap.files) && snap.files.length ? snap.files.map(String) : [...new Set(applied.map((a) => a.rel))];
349
+ emit({
350
+ kind: "outcome",
351
+ state: String(snap.state),
352
+ ...(outcome.task ? { task: outcome.task } : { task: snap.plan.summary }),
353
+ files,
354
+ corrections: Number(snap.corrections) || 0,
355
+ operationIds: applied.map((a) => a.operationId),
356
+ validation,
357
+ ...(outcome.counts ? { counts: outcome.counts } : {}),
358
+ verified: String(snap.state) === "COMPLETED" && validation.length > 0 && validation.every((v) => v.status === "PASSED")
359
+ });
360
+ }
@@ -0,0 +1,109 @@
1
+ import { declaredClientTools, handleClientToolCall, submitWithRetry } from "../services/client-tools.js";
2
+ import { workspaceRoot } from "../services/local-files.js";
3
+ import { MUTATION_TOOL_NAMES } from "../services/mutations.js";
4
+ import { repositoryForPath } from "../services/workspace-registry.js";
5
+ import { isTrusted } from "../ui/trust.js";
6
+ import { executeIdeContextTool, isIdeContextTool } from "./editor-context.js";
7
+ const defaultResolver = (abs) => {
8
+ const repo = repositoryForPath(abs);
9
+ return repo ? { name: repo.name, root: repo.root } : null;
10
+ };
11
+ /**
12
+ * Handle one tool call from an IDE-driven turn. Never throws: every outcome,
13
+ * including a malformed editor-context call, becomes a submitted result so the
14
+ * backend turn can continue.
15
+ */
16
+ export async function handleIdeToolCall(ctx, client, call, deps) {
17
+ const id = typeof call?.tool_call_id === "string" ? call.tool_call_id : "";
18
+ if (!id)
19
+ return;
20
+ // Editor context is the only thing the IDE answers itself; everything else is
21
+ // the shared engine's job.
22
+ if (isIdeContextTool(call.name)) {
23
+ const started = Date.now();
24
+ const label = ideContextLabel(call);
25
+ deps.toolUi.onStart?.(label, call.name);
26
+ let payload;
27
+ try {
28
+ const res = executeIdeContextTool(call.name, (call.arguments ?? {}), deps.editorState(), deps.resolveRepoForPath ?? defaultResolver);
29
+ payload = res.ok
30
+ ? { tool_call_id: id, ok: true, result: (res.result ?? {}) }
31
+ : { tool_call_id: id, ok: false, error: res.error ?? { code: "IDE_TOOL_FAILED", message: "Failed." } };
32
+ }
33
+ catch (err) {
34
+ payload = { tool_call_id: id, ok: false, error: { code: "IDE_TOOL_FAILED", message: err.message ?? "Failed." } };
35
+ }
36
+ payload.duration_ms = Date.now() - started;
37
+ await submitWithRetry(client, payload);
38
+ deps.toolUi.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
39
+ return;
40
+ }
41
+ // Read / search / git / resolve / mutation / command — the shared engine,
42
+ // exactly as the CLI runs it. The host's toolUi carries its IDE coordinators.
43
+ await handleClientToolCall(ctx, client, call, deps.toolUi);
44
+ }
45
+ /** A short activity label for an editor-context call, for the chat panel. */
46
+ export function ideContextLabel(call) {
47
+ switch (call.name) {
48
+ case "get_active_file":
49
+ return "Checking the active file";
50
+ case "get_selection":
51
+ return "Reading your selection";
52
+ case "get_open_files":
53
+ return "Checking open files";
54
+ case "get_workspace_folders":
55
+ return "Checking the workspace";
56
+ case "get_diagnostics":
57
+ return "Reading diagnostics";
58
+ default:
59
+ return "Reading editor context";
60
+ }
61
+ }
62
+ /**
63
+ * The tools an IDE session declares to the backend: the CLI's read/git/resolve
64
+ * set (which the shared engine already gates on trust) plus the IDE
65
+ * editor-context tools. Mutation and command tools are declared separately by
66
+ * the host, exactly as the CLI does, so their approval UIs are wired.
67
+ */
68
+ export function ideReadTools(cliReadTools) {
69
+ if (!cliReadTools)
70
+ return undefined;
71
+ return [...cliReadTools, "get_active_file", "get_selection", "get_open_files", "get_workspace_folders", "get_diagnostics"];
72
+ }
73
+ /**
74
+ * The read/context tools an IDE turn offers, gated exactly as the CLI gates
75
+ * reads — folder trust — with the editor-context tools appended. Untrusted
76
+ * folder → no local tools at all, same as the terminal.
77
+ */
78
+ export function ideDeclaredReadTools(ctx) {
79
+ return ideReadTools(declaredClientTools(ctx));
80
+ }
81
+ /**
82
+ * The file-changing tools an IDE turn offers.
83
+ *
84
+ * The security rule is unchanged from the CLI's `declaredMutationTools`: folder
85
+ * trust is necessary but never sufficient — a change is only ever possible where
86
+ * a human can approve THAT change. The CLI proves an approver is present with
87
+ * `inScreen()` (the interactive terminal). The IDE cannot use that check —
88
+ * there is no terminal screen — so it substitutes the equivalent fact for its
89
+ * own surface: `approverPresent`, which the host sets true ONLY when a panel is
90
+ * live and will actually show the native diff + approval modal. The trust gate
91
+ * is identical; only the surface-presence proxy differs. If no approver is
92
+ * present, no mutation tools are declared, exactly as a piped CLI run offers
93
+ * none.
94
+ *
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
+ */
100
+ export function ideDeclaredMutationTools(ctx, approverPresent) {
101
+ if (!approverPresent)
102
+ return undefined;
103
+ try {
104
+ return isTrusted(ctx.config, workspaceRoot()) ? [...MUTATION_TOOL_NAMES] : undefined;
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
package/dist/main.js ADDED
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ import { Command, CommanderError } from "commander";
3
+ import { registerAttach } from "./commands/attach.js";
4
+ import { registerAuth } from "./commands/auth.js";
5
+ import { registerBtw } from "./commands/btw.js";
6
+ import { registerUpdate } from "./commands/update.js";
7
+ import { registerChat } from "./commands/chat.js";
8
+ import { registerContext } from "./commands/context.js";
9
+ import { registerDoctor } from "./commands/doctor.js";
10
+ import { registerFiles } from "./commands/files.js";
11
+ import { registerHelp } from "./commands/help.js";
12
+ import { registerHistory } from "./commands/history.js";
13
+ import { registerMemory } from "./commands/memory.js";
14
+ import { registerLogin } from "./commands/login.js";
15
+ import { registerLogout } from "./commands/logout.js";
16
+ import { registerModels } from "./commands/models.js";
17
+ import { registerModes } from "./commands/modes.js";
18
+ import { registerModeModel } from "./commands/mode-model.js";
19
+ import { registerRepo } from "./commands/repo.js";
20
+ import { registerRepos } from "./commands/repos.js";
21
+ import { registerSettings } from "./commands/settings.js";
22
+ import { registerReview } from "./commands/review.js";
23
+ import { attachConfig } from "./services/workspace-registry.js";
24
+ import { registerChanges } from "./commands/changes.js";
25
+ import { registerSearch } from "./commands/search.js";
26
+ import { registerScope } from "./commands/scope.js";
27
+ import { registerSessions } from "./commands/sessions.js";
28
+ import { registerUpload } from "./commands/upload.js";
29
+ import { registerUsage } from "./commands/usage.js";
30
+ import { registerVersion } from "./commands/version.js";
31
+ import { registerWhoami } from "./commands/whoami.js";
32
+ import { ApiError } from "./services/api.js";
33
+ import { ConfigStore } from "./services/config.js";
34
+ import { AuthRequiredError, CommandContext } from "./services/context.js";
35
+ import { cliVersion } from "./services/meta.js";
36
+ import { errorLine } from "./services/output.js";
37
+ import { runShell } from "./shell/shell.js";
38
+ import { loadAccent } from "./ui/theme.js";
39
+ async function main() {
40
+ const stagingProfile = process.env.CARRIEROS_CLI_PROFILE === "staging";
41
+ const ctx = new CommandContext(new ConfigStore(stagingProfile
42
+ ? { fixedApiUrl: "https://api.carrieros.site/v1" }
43
+ : {}));
44
+ // Trust is per repository, so the registry has to be able to read it.
45
+ attachConfig(ctx.config);
46
+ // Restore the saved accent color before anything renders.
47
+ loadAccent(ctx.config.get("theme")?.accent);
48
+ const program = new Command();
49
+ program
50
+ .name("cos")
51
+ .description("Carrier OS command-line interface")
52
+ .version(cliVersion(), "-v, --version", "print the CLI version")
53
+ .configureHelp({ sortSubcommands: true })
54
+ .showHelpAfterError("(run `cos --help` for a list of commands)")
55
+ // Throw instead of calling process.exit, so the shell can re-invoke commands
56
+ // via program.parseAsync and survive parse errors.
57
+ .exitOverride();
58
+ // Phase A — auth & diagnostics
59
+ registerLogin(program, ctx);
60
+ registerLogout(program, ctx);
61
+ registerAuth(program, ctx);
62
+ registerWhoami(program, ctx);
63
+ registerScope(program, ctx);
64
+ registerVersion(program, ctx);
65
+ registerUpdate(program, ctx);
66
+ registerDoctor(program, ctx);
67
+ registerRepo(program, ctx);
68
+ registerRepos(program, ctx);
69
+ registerSettings(program, ctx);
70
+ registerReview(program, ctx);
71
+ registerSearch(program, ctx);
72
+ registerChanges(program, ctx);
73
+ // Phase B — chat, sessions, history, context
74
+ registerChat(program, ctx);
75
+ registerSessions(program, ctx);
76
+ registerHistory(program, ctx);
77
+ registerContext(program, ctx);
78
+ registerMemory(program, ctx);
79
+ registerBtw(program, ctx);
80
+ // Phase C — files, usage, models, modes, guide
81
+ registerUpload(program, ctx);
82
+ registerAttach(program, ctx);
83
+ registerFiles(program, ctx);
84
+ registerUsage(program, ctx);
85
+ registerModels(program, ctx);
86
+ registerModes(program, ctx);
87
+ registerModeModel(program, ctx);
88
+ registerHelp(program, ctx);
89
+ // Explicit `cos shell` also opens it (hidden; not a default command, so
90
+ // unknown commands still error instead of silently launching the shell).
91
+ program
92
+ .command("shell", { hidden: true })
93
+ .description("Interactive Carrier OS shell (default when run with no command)")
94
+ .action(async () => {
95
+ await runShell(ctx, program);
96
+ });
97
+ // No command at all → the interactive shell. Any provided command is parsed
98
+ // normally (so `cos bogus` errors rather than opening the shell).
99
+ if (process.argv.slice(2).length === 0) {
100
+ await runShell(ctx, program);
101
+ return;
102
+ }
103
+ await program.parseAsync(process.argv);
104
+ }
105
+ main().catch((err) => {
106
+ // @inquirer throws this when the user hits Ctrl+C at a prompt — clean exit.
107
+ if (err instanceof Error && err.name === "ExitPromptError") {
108
+ process.exit(0);
109
+ }
110
+ // Commander with exitOverride throws for --help/--version/parse errors; it has
111
+ // already printed whatever it needed to.
112
+ if (err instanceof CommanderError) {
113
+ process.exit(err.exitCode);
114
+ }
115
+ if (err instanceof AuthRequiredError) {
116
+ errorLine(err.message);
117
+ process.exit(1);
118
+ }
119
+ if (err instanceof ApiError) {
120
+ errorLine(`${err.message} (${err.code})`);
121
+ }
122
+ else {
123
+ errorLine(err instanceof Error ? err.message : String(err));
124
+ }
125
+ process.exit(1);
126
+ });