@carrieros/cli-staging 0.0.0-stage → 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.
- package/README.md +6 -2
- package/dist/commands/attach.js +45 -0
- package/dist/commands/auth.js +60 -0
- package/dist/commands/btw.js +78 -0
- package/dist/commands/changes.js +167 -0
- package/dist/commands/chat.js +182 -0
- package/dist/commands/context.js +200 -0
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/files.js +94 -0
- package/dist/commands/help.js +37 -0
- package/dist/commands/history.js +112 -0
- package/dist/commands/login.js +62 -0
- package/dist/commands/logout.js +26 -0
- package/dist/commands/memory.js +162 -0
- package/dist/commands/mode-model.js +64 -0
- package/dist/commands/models.js +28 -0
- package/dist/commands/modes.js +30 -0
- package/dist/commands/permissions.js +78 -0
- package/dist/commands/project.js +106 -0
- package/dist/commands/repo.js +146 -0
- package/dist/commands/repos.js +61 -0
- package/dist/commands/review.js +92 -0
- package/dist/commands/scope.js +155 -0
- package/dist/commands/search.js +92 -0
- package/dist/commands/sessions.js +282 -0
- package/dist/commands/settings.js +160 -0
- package/dist/commands/update.js +285 -0
- package/dist/commands/upload.js +223 -0
- package/dist/commands/usage.js +229 -0
- package/dist/commands/version.js +26 -0
- package/dist/commands/whoami.js +44 -0
- package/dist/ide/editor-context.js +275 -0
- package/dist/ide/ide-session.js +364 -0
- package/dist/ide/tool-host.js +109 -0
- package/dist/main.js +132 -0
- package/dist/services/api.js +441 -0
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/auto-update.js +221 -0
- package/dist/services/chat-stream.js +168 -0
- package/dist/services/checkpoints.js +278 -0
- package/dist/services/client-tools.js +356 -0
- package/dist/services/code-intel.js +243 -0
- package/dist/services/code-symbols.js +94 -0
- package/dist/services/coding-workflow.js +554 -0
- package/dist/services/command-coordinator.js +273 -0
- package/dist/services/command-policy.js +434 -0
- package/dist/services/config.js +384 -0
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +416 -0
- package/dist/services/device-auth.js +288 -0
- package/dist/services/diff.js +196 -0
- package/dist/services/env-policy.js +108 -0
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-detect.js +104 -0
- package/dist/services/file-resolver.js +199 -0
- package/dist/services/file-upload.js +126 -0
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +429 -0
- package/dist/services/glob-match.js +164 -0
- package/dist/services/helper-bin.js +85 -0
- package/dist/services/ignore-rules.js +189 -0
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +328 -0
- package/dist/services/local-files.js +639 -0
- package/dist/services/local-tools.js +937 -0
- package/dist/services/login-flow.js +156 -0
- package/dist/services/meta.js +42 -0
- package/dist/services/mutation-coordinator.js +327 -0
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +679 -0
- package/dist/services/open-url.js +68 -0
- package/dist/services/output.js +62 -0
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +39 -0
- package/dist/services/permission-mode.js +78 -0
- package/dist/services/process-runner.js +412 -0
- package/dist/services/project-context.js +298 -0
- package/dist/services/redaction.js +201 -0
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +217 -0
- package/dist/services/session-resolver.js +115 -0
- package/dist/services/sia.js +51 -0
- package/dist/services/spinner.js +40 -0
- package/dist/services/supported-runtime.js +59 -0
- package/dist/services/task-context.js +212 -0
- package/dist/services/task-snapshot.js +38 -0
- package/dist/services/tool-result-outbox.js +195 -0
- package/dist/services/update.js +730 -0
- package/dist/services/workspace-registry.js +310 -0
- package/dist/services/workspace.js +580 -0
- package/dist/shell/shell-chat.js +1622 -0
- package/dist/shell/shell-commands.js +411 -0
- package/dist/shell/shell-prompt.js +110 -0
- package/dist/shell/shell-renderer.js +51 -0
- package/dist/shell/shell-router.js +37 -0
- package/dist/shell/shell.js +414 -0
- package/dist/shell/task-context-view.js +40 -0
- package/dist/staging.js +5 -0
- package/dist/types/index.js +6 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +111 -0
- package/dist/ui/banner.js +56 -0
- package/dist/ui/btw-overlay.js +230 -0
- package/dist/ui/change-review.js +334 -0
- package/dist/ui/chat-renderer.js +463 -0
- package/dist/ui/code-block.js +52 -0
- package/dist/ui/color-picker.js +100 -0
- package/dist/ui/colors.js +55 -0
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-filter.js +92 -0
- package/dist/ui/command-item.js +6 -0
- package/dist/ui/command-palette.js +383 -0
- package/dist/ui/command-registry.js +128 -0
- package/dist/ui/command-renderer.js +55 -0
- package/dist/ui/command-review.js +187 -0
- package/dist/ui/composer-layout.js +74 -0
- package/dist/ui/conversation.js +450 -0
- package/dist/ui/interrupt.js +35 -0
- package/dist/ui/live.js +141 -0
- package/dist/ui/logo.js +58 -0
- package/dist/ui/markdown.js +205 -0
- package/dist/ui/message.js +21 -0
- package/dist/ui/screen-prompt.js +181 -0
- package/dist/ui/screen.js +297 -0
- package/dist/ui/select.js +284 -0
- package/dist/ui/sia-qa.js +213 -0
- package/dist/ui/spinner.js +23 -0
- package/dist/ui/sticky-stream.js +64 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/text-prompt.js +74 -0
- package/dist/ui/theme.js +80 -0
- package/dist/ui/trust.js +88 -0
- package/dist/ui/ui.js +101 -0
- package/package.json +33 -4
|
@@ -0,0 +1,364 @@
|
|
|
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 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;
|
|
203
|
+
const compose = ports.composeMessage ?? ((m) => m);
|
|
204
|
+
// What the model has said so far. It narrates as it works; commit each span at
|
|
205
|
+
// a tool boundary so a progress line lands above the activity it describes.
|
|
206
|
+
let streamed = "";
|
|
207
|
+
let shown = 0;
|
|
208
|
+
const say = (upTo = streamed) => {
|
|
209
|
+
const text = upTo.slice(shown);
|
|
210
|
+
shown = upTo.length;
|
|
211
|
+
if (text.trim())
|
|
212
|
+
ports.onAssistantText(text);
|
|
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
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
const readTools = ideDeclaredReadTools(ctx);
|
|
231
|
+
const result = await client.chatStream({
|
|
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,
|
|
236
|
+
message: compose(message),
|
|
237
|
+
session_id: sessionId,
|
|
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 } : {})
|
|
253
|
+
}, {
|
|
254
|
+
onDelta: (delta) => {
|
|
255
|
+
if (signal.aborted)
|
|
256
|
+
return;
|
|
257
|
+
streamed += delta;
|
|
258
|
+
ports.onDelta?.(streamed.slice(shown));
|
|
259
|
+
},
|
|
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;
|
|
265
|
+
// Whatever the model said before asking for this tool belongs above it.
|
|
266
|
+
say();
|
|
267
|
+
return handleIdeToolCall(ctx, client, call, {
|
|
268
|
+
editorState: ports.editorState,
|
|
269
|
+
resolveRepoForPath: ports.resolveRepoForPath,
|
|
270
|
+
toolUi: {
|
|
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 } : {})
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}, signal);
|
|
287
|
+
// The final message — anything the model did not already narrate.
|
|
288
|
+
say(result.response);
|
|
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) {
|
|
295
|
+
ctx.config.set("sessionId", result.session_id);
|
|
296
|
+
rememberPermissionMode(ctx.config);
|
|
297
|
+
}
|
|
298
|
+
return { response: result.response, sessionId: resultSessionId, applied: mutations?.applied ?? [] };
|
|
299
|
+
}
|
|
300
|
+
catch (err) {
|
|
301
|
+
if (workflow) {
|
|
302
|
+
workflow.interrupt();
|
|
303
|
+
emitOutcome(workflow, outcome, mutations, emit);
|
|
304
|
+
}
|
|
305
|
+
const e = err;
|
|
306
|
+
return {
|
|
307
|
+
response: streamed,
|
|
308
|
+
sessionId: resultSessionId,
|
|
309
|
+
applied: mutations?.applied ?? [],
|
|
310
|
+
error: { code: e.code ?? "TURN_FAILED", message: e.message ?? "The turn failed.", ...(e.reason ? { reason: e.reason } : {}) }
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
finally {
|
|
314
|
+
if (externalSignal)
|
|
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();
|
|
323
|
+
}
|
|
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
|
+
}
|
|
@@ -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,132 @@
|
|
|
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 { setClientIdentity, setClientReleaseChannel } from "./services/meta.js";
|
|
35
|
+
import { isPackaged } from "./services/packaged.js";
|
|
36
|
+
import { updateSettings } from "./services/auto-update.js";
|
|
37
|
+
import { AuthRequiredError, CommandContext } from "./services/context.js";
|
|
38
|
+
import { cliVersion } from "./services/meta.js";
|
|
39
|
+
import { errorLine } from "./services/output.js";
|
|
40
|
+
import { runShell } from "./shell/shell.js";
|
|
41
|
+
import { loadAccent } from "./ui/theme.js";
|
|
42
|
+
async function main() {
|
|
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
|
+
: {}));
|
|
47
|
+
// Trust is per repository, so the registry has to be able to read it.
|
|
48
|
+
attachConfig(ctx.config);
|
|
49
|
+
// Restore the saved accent color before anything renders.
|
|
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);
|
|
54
|
+
const program = new Command();
|
|
55
|
+
program
|
|
56
|
+
.name("cos")
|
|
57
|
+
.description("Carrier OS command-line interface")
|
|
58
|
+
.version(cliVersion(), "-v, --version", "print the CLI version")
|
|
59
|
+
.configureHelp({ sortSubcommands: true })
|
|
60
|
+
.showHelpAfterError("(run `cos --help` for a list of commands)")
|
|
61
|
+
// Throw instead of calling process.exit, so the shell can re-invoke commands
|
|
62
|
+
// via program.parseAsync and survive parse errors.
|
|
63
|
+
.exitOverride();
|
|
64
|
+
// Phase A — auth & diagnostics
|
|
65
|
+
registerLogin(program, ctx);
|
|
66
|
+
registerLogout(program, ctx);
|
|
67
|
+
registerAuth(program, ctx);
|
|
68
|
+
registerWhoami(program, ctx);
|
|
69
|
+
registerScope(program, ctx);
|
|
70
|
+
registerVersion(program, ctx);
|
|
71
|
+
registerUpdate(program, ctx);
|
|
72
|
+
registerDoctor(program, ctx);
|
|
73
|
+
registerRepo(program, ctx);
|
|
74
|
+
registerRepos(program, ctx);
|
|
75
|
+
registerSettings(program, ctx);
|
|
76
|
+
registerReview(program, ctx);
|
|
77
|
+
registerSearch(program, ctx);
|
|
78
|
+
registerChanges(program, ctx);
|
|
79
|
+
// Phase B — chat, sessions, history, context
|
|
80
|
+
registerChat(program, ctx);
|
|
81
|
+
registerSessions(program, ctx);
|
|
82
|
+
registerHistory(program, ctx);
|
|
83
|
+
registerContext(program, ctx);
|
|
84
|
+
registerMemory(program, ctx);
|
|
85
|
+
registerBtw(program, ctx);
|
|
86
|
+
// Phase C — files, usage, models, modes, guide
|
|
87
|
+
registerUpload(program, ctx);
|
|
88
|
+
registerAttach(program, ctx);
|
|
89
|
+
registerFiles(program, ctx);
|
|
90
|
+
registerUsage(program, ctx);
|
|
91
|
+
registerModels(program, ctx);
|
|
92
|
+
registerModes(program, ctx);
|
|
93
|
+
registerModeModel(program, ctx);
|
|
94
|
+
registerHelp(program, ctx);
|
|
95
|
+
// Explicit `cos shell` also opens it (hidden; not a default command, so
|
|
96
|
+
// unknown commands still error instead of silently launching the shell).
|
|
97
|
+
program
|
|
98
|
+
.command("shell", { hidden: true })
|
|
99
|
+
.description("Interactive Carrier OS shell (default when run with no command)")
|
|
100
|
+
.action(async () => {
|
|
101
|
+
await runShell(ctx, program);
|
|
102
|
+
});
|
|
103
|
+
// No command at all → the interactive shell. Any provided command is parsed
|
|
104
|
+
// normally (so `cos bogus` errors rather than opening the shell).
|
|
105
|
+
if (process.argv.slice(2).length === 0) {
|
|
106
|
+
await runShell(ctx, program);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
await program.parseAsync(process.argv);
|
|
110
|
+
}
|
|
111
|
+
main().catch((err) => {
|
|
112
|
+
// @inquirer throws this when the user hits Ctrl+C at a prompt — clean exit.
|
|
113
|
+
if (err instanceof Error && err.name === "ExitPromptError") {
|
|
114
|
+
process.exit(0);
|
|
115
|
+
}
|
|
116
|
+
// Commander with exitOverride throws for --help/--version/parse errors; it has
|
|
117
|
+
// already printed whatever it needed to.
|
|
118
|
+
if (err instanceof CommanderError) {
|
|
119
|
+
process.exit(err.exitCode);
|
|
120
|
+
}
|
|
121
|
+
if (err instanceof AuthRequiredError) {
|
|
122
|
+
errorLine(err.message);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
if (err instanceof ApiError) {
|
|
126
|
+
errorLine(`${err.message} (${err.code})`);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
errorLine(err instanceof Error ? err.message : String(err));
|
|
130
|
+
}
|
|
131
|
+
process.exit(1);
|
|
132
|
+
});
|