@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,356 @@
|
|
|
1
|
+
import { LOCAL_TOOL_NAMES, executeLocalTool } from "./local-tools.js";
|
|
2
|
+
import { activeRepository, resolveRepository } from "./workspace-registry.js";
|
|
3
|
+
import { ToolDeliveryError, terminalToolRejection } from "./tool-result-outbox.js";
|
|
4
|
+
import { errorLine } from "./output.js";
|
|
5
|
+
import { workspaceRoot } from "./local-files.js";
|
|
6
|
+
import { MUTATION_TOOL_NAMES } from "./mutations.js";
|
|
7
|
+
import { inScreen } from "../ui/screen-prompt.js";
|
|
8
|
+
import { isTrusted } from "../ui/trust.js";
|
|
9
|
+
import { executionAdapter, executionPlatform } from "./execution-platform.js";
|
|
10
|
+
import { containerRuntime } from "./container-runner.js";
|
|
11
|
+
/**
|
|
12
|
+
* The CLI end of a delegated tool call: receive → execute locally → answer.
|
|
13
|
+
*
|
|
14
|
+
* There is no loop here and there must never be one. The server's agent loop
|
|
15
|
+
* decides what it needs; this runs exactly the call it was sent, through the
|
|
16
|
+
* same executor and the same containment checks as everything else local, and
|
|
17
|
+
* posts the outcome back. If this code ever starts deciding what to read next,
|
|
18
|
+
* it has become a second agent.
|
|
19
|
+
*/
|
|
20
|
+
/** Largest serialized result we will post — under the server's per-tool cap. */
|
|
21
|
+
const MAX_POST_BYTES = 380 * 1024;
|
|
22
|
+
/**
|
|
23
|
+
* Should this turn offer local tools at all?
|
|
24
|
+
*
|
|
25
|
+
* Only in a trusted workspace. Trust is the existing "may Carrier OS read this
|
|
26
|
+
* folder" consent, scoped to the workspace ROOT because that is what the tools
|
|
27
|
+
* reach. Asked for at startup in the shell; never prompted for mid-turn, where a
|
|
28
|
+
* dialog would fight the stream for the terminal. Non-interactive runs follow
|
|
29
|
+
* trust.ts's existing rule: there is nobody to ask, so the check does not apply.
|
|
30
|
+
*/
|
|
31
|
+
export function declaredClientTools(ctx) {
|
|
32
|
+
try {
|
|
33
|
+
const trusted = !process.stdin.isTTY || isTrusted(ctx.config, workspaceRoot());
|
|
34
|
+
return trusted ? [...LOCAL_TOOL_NAMES] : undefined;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined; // no usable workspace — plain chat, no local tools
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Should this turn offer file-changing tools?
|
|
42
|
+
*
|
|
43
|
+
* Folder trust is necessary but NOT sufficient: trust means "may read", and it
|
|
44
|
+
* is never taken as consent to write. What makes a change possible is a person
|
|
45
|
+
* approving that specific change, so these are offered only where one can be
|
|
46
|
+
* asked — the interactive shell's screen. Piped, scripted and `cos chat` runs
|
|
47
|
+
* never get them, and there is no flag to change that.
|
|
48
|
+
*/
|
|
49
|
+
export function declaredMutationTools(ctx) {
|
|
50
|
+
if (!inScreen())
|
|
51
|
+
return undefined;
|
|
52
|
+
try {
|
|
53
|
+
return isTrusted(ctx.config, workspaceRoot()) ? [...MUTATION_TOOL_NAMES] : undefined;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const isMutationName = (name) => MUTATION_TOOL_NAMES.includes(name);
|
|
60
|
+
/** Opt-in switch for local commands while their release blockers are open. */
|
|
61
|
+
export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
|
|
62
|
+
/**
|
|
63
|
+
* Should this turn offer run_command?
|
|
64
|
+
*
|
|
65
|
+
* Everything file changes require — the interactive screen and a trusted
|
|
66
|
+
* folder — plus a configured platform containment adapter,
|
|
67
|
+
* plus an explicit opt-in. In Auto mode that opt-in is the mode selection
|
|
68
|
+
* itself; an explicit `/settings commands off` remains a hard stop. The Windows
|
|
69
|
+
* path still runs project code with the user's permissions.
|
|
70
|
+
*/
|
|
71
|
+
export function declaredCommandTools(ctx, approverPresent = inScreen(), autoMode = false) {
|
|
72
|
+
const state = localCommandsState(ctx, approverPresent, autoMode);
|
|
73
|
+
return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Whether local commands are on, why, and what (if anything) stops them.
|
|
77
|
+
*
|
|
78
|
+
* ON means the user chose it: Auto mode, `/settings commands on`, or the
|
|
79
|
+
* original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in. An explicit persisted OFF is
|
|
80
|
+
* a hard stop. Even when ON, the tool is only offered in an interactive
|
|
81
|
+
* session, with platform containment and a trusted repository. Runtime health
|
|
82
|
+
* is checked again before execution.
|
|
83
|
+
*/
|
|
84
|
+
export function localCommandsState(ctx, approverPresent = inScreen(), autoMode = false) {
|
|
85
|
+
const fromEnv = process.env[COMMANDS_OPT_IN_ENV] === "1";
|
|
86
|
+
const localSetting = ctx.config.get("localCommandsEnabled");
|
|
87
|
+
const fromSetting = localSetting === true;
|
|
88
|
+
// Choosing Auto is itself an explicit command-execution opt-in. A persisted
|
|
89
|
+
// OFF is a deliberate kill switch and wins over Auto.
|
|
90
|
+
const enabled = localSetting !== false && (fromEnv || fromSetting || autoMode);
|
|
91
|
+
const source = !enabled ? null : fromSetting ? "setting" : fromEnv ? "env" : autoMode ? "auto" : null;
|
|
92
|
+
let blockedBy = null;
|
|
93
|
+
if (enabled) {
|
|
94
|
+
try {
|
|
95
|
+
if (executionAdapter(executionPlatform()) === "isolated-container")
|
|
96
|
+
containerRuntime();
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
blockedBy = error.message;
|
|
100
|
+
}
|
|
101
|
+
// Someone must be present to approve each command: the interactive shell
|
|
102
|
+
// by default; the IDE passes whether a live panel can show the approval.
|
|
103
|
+
if (!blockedBy && !approverPresent)
|
|
104
|
+
blockedBy = "only in the interactive shell";
|
|
105
|
+
else if (!blockedBy) {
|
|
106
|
+
try {
|
|
107
|
+
if (!isTrusted(ctx.config, workspaceRoot()))
|
|
108
|
+
blockedBy = "the active repository is not trusted";
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
blockedBy = "the active repository could not be checked";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { enabled, source, blockedBy };
|
|
116
|
+
}
|
|
117
|
+
/** A short, user-facing description of what is about to happen. */
|
|
118
|
+
export function toolActivityLabel(call) {
|
|
119
|
+
const a = (call.arguments ?? {});
|
|
120
|
+
const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
121
|
+
switch (call.name) {
|
|
122
|
+
case "read_file": {
|
|
123
|
+
const from = typeof a.start_line === "number" ? a.start_line : undefined;
|
|
124
|
+
const to = typeof a.end_line === "number" ? a.end_line : undefined;
|
|
125
|
+
return `Reading ${s(a.path) ?? "a file"}${from || to ? ` lines ${from ?? 1}–${to ?? "…"}` : ""}`;
|
|
126
|
+
}
|
|
127
|
+
case "search_files":
|
|
128
|
+
return `Searching ${s(a.path) ?? s(a.glob) ?? (s(a.type) ? `${s(a.type)} files` : "the project")} for ${a.regex === true ? "/" + (s(a.query) ?? "") + "/" : `"${s(a.query) ?? ""}"`}`.slice(0, 120);
|
|
129
|
+
case "find_files":
|
|
130
|
+
return `Finding ${s(a.pattern) ?? "files"}`;
|
|
131
|
+
case "list_files":
|
|
132
|
+
return s(a.glob) ? `Finding ${s(a.glob)}` : `Listing ${s(a.path) ?? "project files"}`;
|
|
133
|
+
case "resolve_local_file":
|
|
134
|
+
return `Resolving ${s(a.reference) ?? "a file"}`;
|
|
135
|
+
case "code_outline":
|
|
136
|
+
return `Outlining ${s(a.path) ?? "a file"}`;
|
|
137
|
+
case "find_symbol":
|
|
138
|
+
return `Finding the definition of ${s(a.name) ?? "a symbol"}`.slice(0, 120);
|
|
139
|
+
case "find_references":
|
|
140
|
+
return (s(a.name)?.startsWith("/") ? `Finding the route and callers of ${s(a.name)}` : `Finding usages of ${s(a.name) ?? "a symbol"}`).slice(0, 120);
|
|
141
|
+
case "git_status":
|
|
142
|
+
return `Checking git status${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
|
|
143
|
+
case "git_diff":
|
|
144
|
+
return `Reviewing changes${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
|
|
145
|
+
case "git_log":
|
|
146
|
+
return `Reading history${s(a.path) ? ` of ${s(a.path)}` : ""}`;
|
|
147
|
+
case "git_blame":
|
|
148
|
+
return `Reading blame for ${s(a.path) ?? "a file"}`;
|
|
149
|
+
case "git_show":
|
|
150
|
+
return `Reading commit ${s(a.revision) ?? ""}`.trim();
|
|
151
|
+
case "create_file":
|
|
152
|
+
return `Proposing to create ${s(a.path) ?? "a file"}`;
|
|
153
|
+
case "write_file":
|
|
154
|
+
case "edit_file":
|
|
155
|
+
return `Proposing a change to ${s(a.path) ?? "a file"}`;
|
|
156
|
+
case "delete_file":
|
|
157
|
+
return `Proposing to delete ${s(a.path) ?? "a file"}`;
|
|
158
|
+
case "revert_change":
|
|
159
|
+
return "Proposing to undo a change";
|
|
160
|
+
case "run_command": {
|
|
161
|
+
const list = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string").join(" ") : "";
|
|
162
|
+
return `Proposing to run ${s(a.program) ?? "a command"}${list ? " " + list : ""}`.slice(0, 120);
|
|
163
|
+
}
|
|
164
|
+
default:
|
|
165
|
+
return "Inspecting the project";
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function recordDeliveredRead(cache, call, payload) {
|
|
169
|
+
const r = payload.result;
|
|
170
|
+
if (!payload.ok || !r || r.truncated !== false || r.range === true || typeof r.content !== "string" || typeof r.sha256 !== "string")
|
|
171
|
+
return;
|
|
172
|
+
try {
|
|
173
|
+
const selector = call.arguments?.repository;
|
|
174
|
+
const repo = selector ? resolveRepository(selector) : activeRepository();
|
|
175
|
+
cache.record(repo.id, String(r.path), r.sha256, call.tool_call_id);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
/* an unresolvable repository is simply not cached */
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** The codes the server documents for client tool failures. */
|
|
182
|
+
function publicCode(code) {
|
|
183
|
+
switch (code) {
|
|
184
|
+
case "NOT_FOUND":
|
|
185
|
+
return "FILE_NOT_FOUND";
|
|
186
|
+
case "UNKNOWN_TOOL":
|
|
187
|
+
return "UNKNOWN_CLIENT_TOOL";
|
|
188
|
+
case "INVALID_ARGUMENTS":
|
|
189
|
+
return "INVALID_TOOL_ARGUMENTS";
|
|
190
|
+
default:
|
|
191
|
+
return code;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** Keep a read result under the post cap by trimming content, and say so. */
|
|
195
|
+
function fitResult(result) {
|
|
196
|
+
let size = Buffer.byteLength(JSON.stringify(result), "utf8");
|
|
197
|
+
if (size <= MAX_POST_BYTES || typeof result.content !== "string")
|
|
198
|
+
return result;
|
|
199
|
+
let content = result.content;
|
|
200
|
+
while (size > MAX_POST_BYTES && content.length > 0) {
|
|
201
|
+
content = content.slice(0, Math.floor(content.length * 0.75));
|
|
202
|
+
const trimmed = { ...result, content, truncated: true };
|
|
203
|
+
delete trimmed.line_count;
|
|
204
|
+
size = Buffer.byteLength(JSON.stringify(trimmed), "utf8");
|
|
205
|
+
if (size <= MAX_POST_BYTES)
|
|
206
|
+
return trimmed;
|
|
207
|
+
}
|
|
208
|
+
return { ...result, content: "", truncated: true };
|
|
209
|
+
}
|
|
210
|
+
const commandText = (args) => {
|
|
211
|
+
const a = (args ?? {});
|
|
212
|
+
const program = typeof a.program === "string" ? a.program : "";
|
|
213
|
+
const rest = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string") : [];
|
|
214
|
+
return program ? [program, ...rest].join(" ").slice(0, 300) : undefined;
|
|
215
|
+
};
|
|
216
|
+
const pathOf = (args) => {
|
|
217
|
+
const p = args?.path;
|
|
218
|
+
return typeof p === "string" ? p.slice(0, 300) : undefined;
|
|
219
|
+
};
|
|
220
|
+
/**
|
|
221
|
+
* Post a result, retrying once on a transport failure: the server holds the
|
|
222
|
+
* call for its timeout, so a blip should not cost the turn. A 4xx is an
|
|
223
|
+
* answer, not a blip.
|
|
224
|
+
*/
|
|
225
|
+
export async function submitWithRetry(client, payload) {
|
|
226
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
227
|
+
try {
|
|
228
|
+
await client.submitToolResult(payload);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
const status = err.status ?? 0;
|
|
233
|
+
if (terminalToolRejection(err) || (status >= 400 && status < 500 && status !== 408 && status !== 429) || attempt === 1) {
|
|
234
|
+
const failure = err instanceof ToolDeliveryError ? err : new ToolDeliveryError(terminalToolRejection(err)
|
|
235
|
+
? "The server rejected the tool result. The tool was not rerun; the conversation may not reflect its outcome."
|
|
236
|
+
: undefined);
|
|
237
|
+
errorLine(failure.message);
|
|
238
|
+
throw failure;
|
|
239
|
+
}
|
|
240
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Handle one `client_tool_call`. Never throws: every outcome, including a
|
|
246
|
+
* malformed request, becomes a result the server can hand back to the model.
|
|
247
|
+
*/
|
|
248
|
+
export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
249
|
+
const id = typeof call?.tool_call_id === "string" ? call.tool_call_id : "";
|
|
250
|
+
if (!id)
|
|
251
|
+
return; // nothing to correlate an answer with
|
|
252
|
+
const label = toolActivityLabel(call);
|
|
253
|
+
const started = Date.now();
|
|
254
|
+
if (call.name === "coding_workflow") {
|
|
255
|
+
let payload;
|
|
256
|
+
try {
|
|
257
|
+
if (!ui.workflow || declaredClientTools(ctx) === undefined)
|
|
258
|
+
throw new Error("Coding workflow is not enabled in this trusted interactive session.");
|
|
259
|
+
payload = { tool_call_id: id, ok: true, result: await ui.workflow.control(call) };
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
payload = { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } };
|
|
263
|
+
const action = call.arguments?.action;
|
|
264
|
+
ui.onRefused?.({ proposal: action === "plan" ? "plan" : "workflow", ...(typeof action === "string" ? { target: action } : {}),
|
|
265
|
+
code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
await submitWithRetry(client, payload);
|
|
269
|
+
if (payload.ok)
|
|
270
|
+
ui.workflow?.confirmControl(id);
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
ui.workflow?.interrupt();
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
// A proposed command goes to the command coordinator — never anywhere else,
|
|
279
|
+
// and never at all unless this turn offered commands.
|
|
280
|
+
if (call.name === "run_command" || call.kind === "command") {
|
|
281
|
+
if (!ui.commands || call.name !== "run_command") {
|
|
282
|
+
await submitWithRetry(client, {
|
|
283
|
+
tool_call_id: id,
|
|
284
|
+
ok: false,
|
|
285
|
+
error: { code: "COMMAND_NOT_ENABLED", message: "Local commands are not enabled in this session. Nothing ran." },
|
|
286
|
+
duration_ms: 0
|
|
287
|
+
});
|
|
288
|
+
ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "COMMAND_NOT_ENABLED", reason: "Local commands are not enabled in this session. Nothing ran." });
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
try {
|
|
292
|
+
ui.workflow?.beforeCommand(call);
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
await submitWithRetry(client, { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } });
|
|
296
|
+
ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
await ui.commands.handle(call);
|
|
300
|
+
}
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
// A proposed change goes to the reviewer — never to the read executor, and
|
|
304
|
+
// never anywhere at all unless this turn offered changes in the first place.
|
|
305
|
+
if (isMutationName(call.name) || call.kind === "mutation") {
|
|
306
|
+
if (!ui.mutations || !isMutationName(call.name)) {
|
|
307
|
+
await submitWithRetry(client, {
|
|
308
|
+
tool_call_id: id,
|
|
309
|
+
ok: false,
|
|
310
|
+
error: { code: "MUTATION_NOT_ENABLED", message: "File changes are not enabled in this session. Nothing was changed." },
|
|
311
|
+
duration_ms: 0
|
|
312
|
+
});
|
|
313
|
+
ui.onRefused?.({ proposal: "change", target: pathOf(call.arguments), code: "MUTATION_NOT_ENABLED", reason: "File changes are not enabled in this session. Nothing was changed." });
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
await ui.mutations.handle(call);
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
ui.onStart?.(label, call.name);
|
|
321
|
+
let payload;
|
|
322
|
+
const trusted = declaredClientTools(ctx) !== undefined;
|
|
323
|
+
if (!trusted) {
|
|
324
|
+
payload = {
|
|
325
|
+
tool_call_id: id,
|
|
326
|
+
ok: false,
|
|
327
|
+
error: { code: "TOOL_NOT_TRUSTED", message: "This folder has not been trusted for Carrier OS to read." }
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
else if (!call.arguments || typeof call.arguments !== "object" || Array.isArray(call.arguments)) {
|
|
331
|
+
payload = {
|
|
332
|
+
tool_call_id: id,
|
|
333
|
+
ok: false,
|
|
334
|
+
error: { code: "INVALID_TOOL_ARGUMENTS", message: "Tool arguments must be an object." }
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
// The executor re-validates everything — name, arguments, containment,
|
|
339
|
+
// ignore rules, size — regardless of what the server already checked.
|
|
340
|
+
const res = executeLocalTool({ id, name: call.name, arguments: call.arguments }, { readCache: ui.readCache });
|
|
341
|
+
payload = res.ok
|
|
342
|
+
? { tool_call_id: id, ok: true, result: fitResult(res.result) }
|
|
343
|
+
: {
|
|
344
|
+
tool_call_id: id,
|
|
345
|
+
ok: false,
|
|
346
|
+
error: { code: publicCode(res.error?.code ?? "TOOL_FAILED"), message: res.error?.message ?? "Tool failed." }
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
payload.duration_ms = Date.now() - started;
|
|
350
|
+
await submitWithRetry(client, payload);
|
|
351
|
+
// Only bytes that were actually posted, untrimmed, count as delivered.
|
|
352
|
+
if (ui.readCache && call.name === "read_file")
|
|
353
|
+
recordDeliveredRead(ui.readCache, call, payload);
|
|
354
|
+
ui.workflow?.observeRead(call, payload);
|
|
355
|
+
ui.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
|
|
356
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { declaration } from "./code-symbols.js";
|
|
3
|
+
export const OUTLINE_LIMITS = Object.freeze({ symbols: 200, imports: 100, routes: 50, requests: 50, symbolLines: 3000 });
|
|
4
|
+
const LANGUAGES = {
|
|
5
|
+
".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
|
|
6
|
+
".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
|
|
7
|
+
".py": "python", ".go": "go", ".rs": "rust", ".java": "java", ".kt": "kotlin", ".cs": "csharp", ".rb": "ruby", ".php": "php"
|
|
8
|
+
};
|
|
9
|
+
export const languageOf = (rel) => LANGUAGES[path.extname(rel).toLowerCase()] ?? "text";
|
|
10
|
+
const indent = (line) => (/^[ \t]*/.exec(line)?.[0] ?? "").replace(/\t/g, " ").length;
|
|
11
|
+
/** The last line of the block a declaration opens: braces for C-like languages, indentation for Python. */
|
|
12
|
+
function blockEnd(lines, start, language) {
|
|
13
|
+
if (language === "python" || language === "ruby") {
|
|
14
|
+
const base = indent(lines[start]);
|
|
15
|
+
let end = start;
|
|
16
|
+
for (let i = start + 1; i < lines.length && i - start < OUTLINE_LIMITS.symbolLines; i++) {
|
|
17
|
+
if (!lines[i].trim())
|
|
18
|
+
continue;
|
|
19
|
+
if (indent(lines[i]) <= base && !/^\s*[)\]}]/.test(lines[i]))
|
|
20
|
+
break;
|
|
21
|
+
end = i;
|
|
22
|
+
}
|
|
23
|
+
return end + 1;
|
|
24
|
+
}
|
|
25
|
+
let depth = 0, opened = false;
|
|
26
|
+
for (let i = start; i < lines.length && i - start < OUTLINE_LIMITS.symbolLines; i++) {
|
|
27
|
+
// Strings and comments are not stripped: a heuristic, bounded and labelled.
|
|
28
|
+
const line = lines[i].replace(/(["'`])(?:\\.|(?!\1).)*\1/g, "\"\"").replace(/\/\/.*$/, "");
|
|
29
|
+
for (const ch of line) {
|
|
30
|
+
if (ch === "{") {
|
|
31
|
+
depth++;
|
|
32
|
+
opened = true;
|
|
33
|
+
}
|
|
34
|
+
else if (ch === "}")
|
|
35
|
+
depth--;
|
|
36
|
+
}
|
|
37
|
+
if (opened && depth <= 0)
|
|
38
|
+
return i + 1;
|
|
39
|
+
// A one-line declaration with no block (`const x = () => y;`, `type A = B;`).
|
|
40
|
+
if (!opened && i === start && /;\s*$/.test(line))
|
|
41
|
+
return i + 1;
|
|
42
|
+
if (!opened && i - start > 3)
|
|
43
|
+
return start + 1;
|
|
44
|
+
}
|
|
45
|
+
return Math.min(lines.length, start + 1);
|
|
46
|
+
}
|
|
47
|
+
function kindOf(line, name, container, rel, insideClass) {
|
|
48
|
+
if (/\binterface\s/.test(line))
|
|
49
|
+
return "interface";
|
|
50
|
+
if (/^\s*(?:export\s+)?type\s+[A-Za-z_$]/.test(line))
|
|
51
|
+
return "type";
|
|
52
|
+
if (container)
|
|
53
|
+
return "class";
|
|
54
|
+
if (insideClass)
|
|
55
|
+
return "method";
|
|
56
|
+
const jsx = /\.(jsx|tsx)$/i.test(rel);
|
|
57
|
+
if (jsx && /^[A-Z]/.test(name))
|
|
58
|
+
return "component";
|
|
59
|
+
if (/^\s*(?:export\s+)?(?:const|let|var)\s/.test(line) && !/=>|function\b/.test(line))
|
|
60
|
+
return "constant";
|
|
61
|
+
return "function";
|
|
62
|
+
}
|
|
63
|
+
const ROUTE = /\b(app|router|server|api|route|routes|r)\s*\.\s*(get|post|put|patch|delete|all|options|head)\s*\(\s*(['"`])([^'"`]+)\3\s*,\s*([\s\S]*)$/i;
|
|
64
|
+
const PY_ROUTE = /^\s*@\s*[\w.]+\.(route|get|post|put|patch|delete)\(\s*(['"])([^'"]+)\2([^)]*)\)/i;
|
|
65
|
+
const FETCH = /\bfetch\s*\(\s*(['"`])([^'"`]+)\1(?:\s*,\s*\{[^}]*method\s*:\s*(['"`])(\w+)\3)?/i;
|
|
66
|
+
const CLIENT = /\b(axios|http|api|client|request|\$http|ky|superagent)\s*\.\s*(get|post|put|patch|delete)\s*\(\s*(['"`])([^'"`]+)\3/i;
|
|
67
|
+
/** Symbols, imports, routes and requests in one file's text. */
|
|
68
|
+
export function outline(text, rel) {
|
|
69
|
+
const language = languageOf(rel);
|
|
70
|
+
const lines = text.split(/\r\n|\r|\n/);
|
|
71
|
+
const symbols = [], imports = [], routes = [], requests = [];
|
|
72
|
+
const exportedNames = new Set();
|
|
73
|
+
let truncated = false;
|
|
74
|
+
const classes = [];
|
|
75
|
+
for (let i = 0; i < lines.length; i++) {
|
|
76
|
+
const line = lines[i];
|
|
77
|
+
// Imports and re-exports.
|
|
78
|
+
let m;
|
|
79
|
+
if ((m = /^\s*import\s+(?:type\s+)?(?:([\w$*{}\s,]+?)\s+from\s+)?(['"])([^'"]+)\2/.exec(line)) || (m = /^\s*export\s+(?:\*|\{[^}]*\})\s+from\s+(['"])([^'"]+)\1/.exec(line))) {
|
|
80
|
+
const isExport = /^\s*export/.test(line);
|
|
81
|
+
const specifier = isExport ? m[2] : m[3];
|
|
82
|
+
const names = isExport ? [] : (m[1] ?? "").replace(/[{}]/g, " ").split(/[\s,]+/).filter((n) => n && n !== "as" && n !== "*" && !/^type$/.test(n));
|
|
83
|
+
if (imports.length < OUTLINE_LIMITS.imports)
|
|
84
|
+
imports.push({ specifier, names, line: i + 1 });
|
|
85
|
+
else
|
|
86
|
+
truncated = true;
|
|
87
|
+
}
|
|
88
|
+
else if ((m = /\b(?:const|let|var)\s+([\w${}\s,:]+?)\s*=\s*require\(\s*(['"])([^'"]+)\2\s*\)/.exec(line))) {
|
|
89
|
+
if (imports.length < OUTLINE_LIMITS.imports)
|
|
90
|
+
imports.push({ specifier: m[3], names: m[1].replace(/[{}]/g, " ").split(/[\s,:]+/).filter(Boolean), line: i + 1 });
|
|
91
|
+
}
|
|
92
|
+
else if (language === "python" && (m = /^\s*from\s+([\w.]+)\s+import\s+(.+)$/.exec(line))) {
|
|
93
|
+
imports.push({ specifier: m[1], names: m[2].split(",").map((n) => n.trim().split(/\s+as\s+/)[0]).filter(Boolean), line: i + 1 });
|
|
94
|
+
}
|
|
95
|
+
else if (language === "python" && (m = /^\s*import\s+([\w.]+)/.exec(line))) {
|
|
96
|
+
imports.push({ specifier: m[1], names: [], line: i + 1 });
|
|
97
|
+
}
|
|
98
|
+
// module.exports = { a, b } / exports.a = …
|
|
99
|
+
if ((m = /\bmodule\.exports\s*=\s*\{([^}]*)\}/.exec(line)))
|
|
100
|
+
for (const n of m[1].split(",")) {
|
|
101
|
+
const id = n.trim().split(/\s*:\s*/)[0];
|
|
102
|
+
if (id)
|
|
103
|
+
exportedNames.add(id);
|
|
104
|
+
}
|
|
105
|
+
if ((m = /\b(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*=/.exec(line)))
|
|
106
|
+
exportedNames.add(m[1]);
|
|
107
|
+
if ((m = /^\s*export\s*\{([^}]*)\}\s*;?\s*$/.exec(line)))
|
|
108
|
+
for (const n of m[1].split(",")) {
|
|
109
|
+
const id = n.trim().split(/\s+as\s+/)[0];
|
|
110
|
+
if (id)
|
|
111
|
+
exportedNames.add(id);
|
|
112
|
+
}
|
|
113
|
+
// Routes and client requests.
|
|
114
|
+
if ((m = ROUTE.exec(line))) {
|
|
115
|
+
const handlers = m[5].replace(/\)\s*;?\s*$/, "").split(",").map((s) => s.trim()).filter((s) => /^[A-Za-z_$][\w$.]*$/.test(s));
|
|
116
|
+
if (routes.length < OUTLINE_LIMITS.routes)
|
|
117
|
+
routes.push({ method: m[2].toUpperCase(), path: m[4], handler: handlers.at(-1) ?? null, line: i + 1 });
|
|
118
|
+
}
|
|
119
|
+
else if ((m = PY_ROUTE.exec(line))) {
|
|
120
|
+
const method = m[1].toLowerCase() === "route" ? (/methods\s*=\s*\[\s*['"](\w+)/.exec(m[4])?.[1] ?? "GET") : m[1];
|
|
121
|
+
const next = lines.slice(i + 1, i + 4).map((l) => /^\s*(?:async\s+)?def\s+(\w+)/.exec(l)?.[1]).find(Boolean) ?? null;
|
|
122
|
+
if (routes.length < OUTLINE_LIMITS.routes)
|
|
123
|
+
routes.push({ method: method.toUpperCase(), path: m[3], handler: next, line: i + 1 });
|
|
124
|
+
}
|
|
125
|
+
if ((m = FETCH.exec(line))) {
|
|
126
|
+
if (requests.length < OUTLINE_LIMITS.requests)
|
|
127
|
+
requests.push({ method: m[4]?.toUpperCase() ?? null, url: m[2], line: i + 1 });
|
|
128
|
+
}
|
|
129
|
+
else if ((m = CLIENT.exec(line))) {
|
|
130
|
+
if (requests.length < OUTLINE_LIMITS.requests)
|
|
131
|
+
requests.push({ method: m[2].toUpperCase(), url: m[4], line: i + 1 });
|
|
132
|
+
}
|
|
133
|
+
// Declarations.
|
|
134
|
+
while (classes.length && i + 1 > classes[classes.length - 1].end)
|
|
135
|
+
classes.pop();
|
|
136
|
+
// A factory's returned object (`return { add() {…}, subtotal() {…} }`): its
|
|
137
|
+
// methods are real declarations — `createCart().subtotal` — and must be
|
|
138
|
+
// listed, or a plan naming them is refused as "not declared".
|
|
139
|
+
if (language !== "python" && language !== "go" && /^\s*return\s*\{\s*$/.test(line)) {
|
|
140
|
+
const owner = [...symbols].reverse().find((s) => s.kind === "function" && s.start_line <= i + 1 && s.end_line >= i + 1);
|
|
141
|
+
const end = blockEnd(lines, i, language);
|
|
142
|
+
if (end > i + 1)
|
|
143
|
+
classes.push({ name: owner?.name ?? "object", end });
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const typeAlias = /^\s*(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*=/.exec(line);
|
|
147
|
+
let d = typeAlias ? { name: typeAlias[1], container: false } : declaration(line);
|
|
148
|
+
// A top-level value — `export const sessionStore = new SessionStore()`, or an
|
|
149
|
+
// object-literal service whose methods are then `authService.login`.
|
|
150
|
+
const value = !d && classes.length === 0 && indent(line) === 0 ? /^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(.*)$/.exec(line) : null;
|
|
151
|
+
if (value) {
|
|
152
|
+
const end = blockEnd(lines, i, language);
|
|
153
|
+
const isObject = /^\{/.test(value[2].trim()) && end > i + 1;
|
|
154
|
+
if (symbols.length >= OUTLINE_LIMITS.symbols) {
|
|
155
|
+
truncated = true;
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
symbols.push({ name: value[1], kind: "constant", start_line: i + 1, end_line: Math.max(i + 1, end), exported: /^export\b/.test(line) });
|
|
159
|
+
if (isObject)
|
|
160
|
+
classes.push({ name: value[1], end });
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (!d)
|
|
164
|
+
continue;
|
|
165
|
+
const insideClass = classes.length > 0 && !d.container;
|
|
166
|
+
// A method-shaped line at top level is a call, not a declaration (`foo(x) {` is rare outside classes in JS).
|
|
167
|
+
if (!insideClass && !d.container && /^\s*[A-Za-z_$][\w$]*\s*\(/.test(line) && !/^\s*(?:async\s+)?def\s|^\s*func\s|^\s*fn\s/.test(line) && language !== "go")
|
|
168
|
+
continue;
|
|
169
|
+
const end = blockEnd(lines, i, language);
|
|
170
|
+
const kind = kindOf(line, d.name, d.container, rel, insideClass);
|
|
171
|
+
const exported = /^\s*export\b/.test(line) || (language === "go" && /^[A-Z]/.test(d.name)) || (language === "python" && !d.name.startsWith("_") && indent(line) === 0);
|
|
172
|
+
if (symbols.length >= OUTLINE_LIMITS.symbols) {
|
|
173
|
+
truncated = true;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
symbols.push({ name: d.name, kind, start_line: i + 1, end_line: Math.max(i + 1, end), exported, ...(insideClass ? { container: classes[classes.length - 1].name } : {}) });
|
|
177
|
+
if (d.container)
|
|
178
|
+
classes.push({ name: d.name, end });
|
|
179
|
+
}
|
|
180
|
+
for (const s of symbols)
|
|
181
|
+
if (!s.container && exportedNames.has(s.name))
|
|
182
|
+
s.exported = true;
|
|
183
|
+
return { language, symbols, imports, routes, requests, truncated };
|
|
184
|
+
}
|
|
185
|
+
const EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".py"];
|
|
186
|
+
/**
|
|
187
|
+
* The repository file a RELATIVE import refers to, or null (packages and
|
|
188
|
+
* unresolved paths are never guessed). `exists` is the caller's own check.
|
|
189
|
+
*/
|
|
190
|
+
export function resolveImport(specifier, fromRel, exists) {
|
|
191
|
+
if (!specifier.startsWith("."))
|
|
192
|
+
return null;
|
|
193
|
+
const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromRel.split(path.sep).join("/")), specifier));
|
|
194
|
+
if (base.startsWith(".."))
|
|
195
|
+
return null;
|
|
196
|
+
const stem = base.replace(/\.(js|mjs|cjs|jsx)$/, "");
|
|
197
|
+
const candidates = [base, ...EXTENSIONS.map((e) => stem + e), ...EXTENSIONS.map((e) => `${base}/index${e}`)];
|
|
198
|
+
return candidates.find((c) => exists(c)) ?? null;
|
|
199
|
+
}
|
|
200
|
+
/** How a line uses `name`: a call, an import, JSX, a definition, or another reference. */
|
|
201
|
+
export function referenceKind(line, name) {
|
|
202
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
203
|
+
const d = declaration(line);
|
|
204
|
+
if (d?.name === name || new RegExp(`^\\s*(?:export\\s+)?type\\s+${esc}\\b`).test(line))
|
|
205
|
+
return "definition";
|
|
206
|
+
if (/^\s*(?:import\b|export\s+\{[^}]*\}\s+from|from\s+[\w.]+\s+import)|\brequire\(/.test(line))
|
|
207
|
+
return "import";
|
|
208
|
+
if (new RegExp(`<${esc}[\\s/>]`).test(line))
|
|
209
|
+
return "jsx";
|
|
210
|
+
if (new RegExp(`\\b${esc}\\s*(?:<[^>]*>)?\\s*\\(`).test(line))
|
|
211
|
+
return "call";
|
|
212
|
+
return "reference";
|
|
213
|
+
}
|
|
214
|
+
/** Does a line define an HTTP route for `url`, or request it? */
|
|
215
|
+
export function urlUse(line, url) {
|
|
216
|
+
const r = ROUTE.exec(line) ?? null;
|
|
217
|
+
if (r && r[4] === url)
|
|
218
|
+
return "route";
|
|
219
|
+
const p = PY_ROUTE.exec(line);
|
|
220
|
+
if (p && p[3] === url)
|
|
221
|
+
return "route";
|
|
222
|
+
const f = FETCH.exec(line) ?? CLIENT.exec(line);
|
|
223
|
+
if (f && (f[2] === url || f[4] === url || (f[2] ?? f[4] ?? "").endsWith(url)))
|
|
224
|
+
return "request";
|
|
225
|
+
return "other";
|
|
226
|
+
}
|
|
227
|
+
/** A relevance score for a file in a search for `term`: definitions and names first, tests last. */
|
|
228
|
+
export function relevance(rel, term, hits) {
|
|
229
|
+
const t = term.toLowerCase().replace(/[^a-z0-9_$]+/g, "");
|
|
230
|
+
const p = rel.toLowerCase(), base = path.posix.basename(p).replace(/\.[^.]+$/, "");
|
|
231
|
+
let score = Math.min(hits.count, 10);
|
|
232
|
+
if (hits.definition)
|
|
233
|
+
score += 20;
|
|
234
|
+
if (t && base === t)
|
|
235
|
+
score += 12;
|
|
236
|
+
else if (t && base.includes(t))
|
|
237
|
+
score += 8;
|
|
238
|
+
else if (t && p.includes(t))
|
|
239
|
+
score += 4;
|
|
240
|
+
if (/(^|\/)(test|tests|__tests__|spec)(\/|$)|\.(test|spec)\.[a-z]+$/.test(p))
|
|
241
|
+
score -= 6;
|
|
242
|
+
return score;
|
|
243
|
+
}
|