@carrieros/cli 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -13
- package/dist/commands/chat.js +3 -3
- package/dist/commands/context.js +40 -0
- package/dist/commands/doctor.js +27 -12
- package/dist/commands/logout.js +1 -0
- package/dist/commands/permissions.js +77 -0
- package/dist/commands/scope.js +9 -6
- package/dist/commands/sessions.js +5 -0
- package/dist/commands/settings.js +8 -1
- package/dist/commands/update.js +79 -9
- package/dist/commands/usage.js +5 -5
- package/dist/commands/whoami.js +12 -9
- package/dist/ide/editor-context.js +115 -12
- package/dist/ide/ide-session.js +274 -13
- package/dist/ide/tool-host.js +2 -2
- package/dist/main.js +0 -0
- package/dist/services/api.js +178 -12
- package/dist/services/auth-origin.js +20 -0
- package/dist/services/chat-stream.js +26 -3
- package/dist/services/checkpoints.js +176 -14
- package/dist/services/client-tools.js +113 -21
- 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 +85 -12
- package/dist/services/command-policy.js +34 -4
- package/dist/services/config.js +67 -5
- package/dist/services/container-runner.js +254 -0
- package/dist/services/container-supervisor.js +38 -0
- package/dist/services/context.js +45 -17
- package/dist/services/device-auth.js +30 -5
- package/dist/services/execution-platform.js +30 -0
- package/dist/services/file-resolver.js +1 -1
- package/dist/services/folder-key.js +22 -0
- package/dist/services/git-tools.js +181 -0
- package/dist/services/helper-bin.js +56 -35
- package/dist/services/instruction-resolver.js +54 -0
- package/dist/services/job-helper.js +31 -10
- package/dist/services/local-files.js +148 -26
- package/dist/services/local-tools.js +540 -35
- package/dist/services/login-flow.js +43 -12
- package/dist/services/mutation-coordinator.js +186 -20
- package/dist/services/mutation-groups.js +309 -0
- package/dist/services/mutation-recovery.js +159 -0
- package/dist/services/mutations.js +264 -78
- package/dist/services/packaged-update.js +403 -0
- package/dist/services/packaged.js +15 -0
- package/dist/services/permission-mode.js +60 -0
- package/dist/services/process-runner.js +7 -1
- package/dist/services/project-context.js +4 -4
- package/dist/services/result-reconciliation.js +49 -0
- package/dist/services/secure-store.js +21 -1
- package/dist/services/session-resolver.js +5 -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 +37 -12
- package/dist/services/workspace-registry.js +4 -3
- package/dist/services/workspace.js +8 -1
- package/dist/shell/shell-chat.js +299 -32
- package/dist/shell/shell-commands.js +46 -4
- package/dist/shell/shell-prompt.js +21 -11
- package/dist/shell/shell-renderer.js +1 -1
- package/dist/shell/shell.js +69 -7
- package/dist/shell/task-context-view.js +40 -0
- package/dist/ui/agent-cards.js +111 -0
- package/dist/ui/agent-presentation.js +131 -0
- package/dist/ui/approval.js +46 -16
- package/dist/ui/banner.js +31 -87
- package/dist/ui/change-review.js +293 -46
- package/dist/ui/chat-renderer.js +6 -6
- package/dist/ui/colors.js +9 -9
- package/dist/ui/command-details.js +11 -0
- package/dist/ui/command-palette.js +27 -10
- package/dist/ui/command-registry.js +9 -2
- package/dist/ui/command-review.js +77 -28
- package/dist/ui/composer-layout.js +26 -20
- package/dist/ui/conversation.js +77 -25
- package/dist/ui/live.js +1 -1
- package/dist/ui/screen.js +19 -11
- package/dist/ui/select.js +6 -0
- package/dist/ui/task-context-card.js +99 -0
- package/dist/ui/trust.js +7 -12
- package/dist/ui/ui.js +23 -0
- package/package.json +8 -5
|
@@ -1,8 +1,13 @@
|
|
|
1
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";
|
|
2
5
|
import { workspaceRoot } from "./local-files.js";
|
|
3
6
|
import { MUTATION_TOOL_NAMES } from "./mutations.js";
|
|
4
7
|
import { inScreen } from "../ui/screen-prompt.js";
|
|
5
8
|
import { isTrusted } from "../ui/trust.js";
|
|
9
|
+
import { executionAdapter, executionPlatform } from "./execution-platform.js";
|
|
10
|
+
import { containerRuntime } from "./container-runner.js";
|
|
6
11
|
/**
|
|
7
12
|
* The CLI end of a delegated tool call: receive → execute locally → answer.
|
|
8
13
|
*
|
|
@@ -58,13 +63,12 @@ export const COMMANDS_OPT_IN_ENV = "COS_ENABLE_LOCAL_COMMANDS";
|
|
|
58
63
|
* Should this turn offer run_command?
|
|
59
64
|
*
|
|
60
65
|
* Everything file changes require — the interactive screen and a trusted
|
|
61
|
-
* folder — plus
|
|
62
|
-
* plus an explicit opt-in.
|
|
63
|
-
* permissions
|
|
64
|
-
* so nothing offers them by default until that is resolved.
|
|
66
|
+
* folder — plus a configured platform containment adapter,
|
|
67
|
+
* plus an explicit opt-in. The Windows path still runs project code with the
|
|
68
|
+
* user's permissions; isolation does not make commands enabled by default.
|
|
65
69
|
*/
|
|
66
|
-
export function declaredCommandTools(ctx) {
|
|
67
|
-
const state = localCommandsState(ctx);
|
|
70
|
+
export function declaredCommandTools(ctx, approverPresent = inScreen()) {
|
|
71
|
+
const state = localCommandsState(ctx, approverPresent);
|
|
68
72
|
return state.enabled && !state.blockedBy ? ["run_command"] : undefined;
|
|
69
73
|
}
|
|
70
74
|
/**
|
|
@@ -73,21 +77,28 @@ export function declaredCommandTools(ctx) {
|
|
|
73
77
|
* ON means the user chose it: the persisted `/settings commands on`, or the
|
|
74
78
|
* original `COS_ENABLE_LOCAL_COMMANDS=1` opt-in, which keeps working so nobody
|
|
75
79
|
* who relied on it has to migrate. Even when ON, the tool is only offered in
|
|
76
|
-
* the interactive shell,
|
|
77
|
-
* repository
|
|
80
|
+
* the interactive shell, with the platform's containment prerequisite, in a
|
|
81
|
+
* trusted repository. Runtime health is checked again before execution.
|
|
78
82
|
*/
|
|
79
|
-
export function localCommandsState(ctx) {
|
|
83
|
+
export function localCommandsState(ctx, approverPresent = inScreen()) {
|
|
80
84
|
const fromEnv = process.env[COMMANDS_OPT_IN_ENV] === "1";
|
|
81
85
|
const fromSetting = ctx.config.get("localCommandsEnabled") === true;
|
|
82
86
|
const enabled = fromEnv || fromSetting;
|
|
83
87
|
const source = fromSetting ? "setting" : fromEnv ? "env" : null;
|
|
84
88
|
let blockedBy = null;
|
|
85
89
|
if (enabled) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
90
|
+
try {
|
|
91
|
+
if (executionAdapter(executionPlatform()) === "isolated-container")
|
|
92
|
+
containerRuntime();
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
blockedBy = error.message;
|
|
96
|
+
}
|
|
97
|
+
// Someone must be present to approve each command: the interactive shell
|
|
98
|
+
// by default; the IDE passes whether a live panel can show the approval.
|
|
99
|
+
if (!blockedBy && !approverPresent)
|
|
89
100
|
blockedBy = "only in the interactive shell";
|
|
90
|
-
else {
|
|
101
|
+
else if (!blockedBy) {
|
|
91
102
|
try {
|
|
92
103
|
if (!isTrusted(ctx.config, workspaceRoot()))
|
|
93
104
|
blockedBy = "the active repository is not trusted";
|
|
@@ -104,18 +115,35 @@ export function toolActivityLabel(call) {
|
|
|
104
115
|
const a = (call.arguments ?? {});
|
|
105
116
|
const s = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
|
|
106
117
|
switch (call.name) {
|
|
107
|
-
case "read_file":
|
|
108
|
-
|
|
118
|
+
case "read_file": {
|
|
119
|
+
const from = typeof a.start_line === "number" ? a.start_line : undefined;
|
|
120
|
+
const to = typeof a.end_line === "number" ? a.end_line : undefined;
|
|
121
|
+
return `Reading ${s(a.path) ?? "a file"}${from || to ? ` lines ${from ?? 1}–${to ?? "…"}` : ""}`;
|
|
122
|
+
}
|
|
109
123
|
case "search_files":
|
|
110
|
-
return `Searching ${s(a.glob) ?? "the project"} for "${s(a.query) ?? ""}"
|
|
124
|
+
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);
|
|
125
|
+
case "find_files":
|
|
126
|
+
return `Finding ${s(a.pattern) ?? "files"}`;
|
|
111
127
|
case "list_files":
|
|
112
128
|
return s(a.glob) ? `Finding ${s(a.glob)}` : `Listing ${s(a.path) ?? "project files"}`;
|
|
113
129
|
case "resolve_local_file":
|
|
114
130
|
return `Resolving ${s(a.reference) ?? "a file"}`;
|
|
131
|
+
case "code_outline":
|
|
132
|
+
return `Outlining ${s(a.path) ?? "a file"}`;
|
|
133
|
+
case "find_symbol":
|
|
134
|
+
return `Finding the definition of ${s(a.name) ?? "a symbol"}`.slice(0, 120);
|
|
135
|
+
case "find_references":
|
|
136
|
+
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);
|
|
115
137
|
case "git_status":
|
|
116
138
|
return `Checking git status${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
|
|
117
139
|
case "git_diff":
|
|
118
140
|
return `Reviewing changes${s(a.repository) ? ` in ${s(a.repository)}` : ""}`;
|
|
141
|
+
case "git_log":
|
|
142
|
+
return `Reading history${s(a.path) ? ` of ${s(a.path)}` : ""}`;
|
|
143
|
+
case "git_blame":
|
|
144
|
+
return `Reading blame for ${s(a.path) ?? "a file"}`;
|
|
145
|
+
case "git_show":
|
|
146
|
+
return `Reading commit ${s(a.revision) ?? ""}`.trim();
|
|
119
147
|
case "create_file":
|
|
120
148
|
return `Proposing to create ${s(a.path) ?? "a file"}`;
|
|
121
149
|
case "write_file":
|
|
@@ -133,6 +161,19 @@ export function toolActivityLabel(call) {
|
|
|
133
161
|
return "Inspecting the project";
|
|
134
162
|
}
|
|
135
163
|
}
|
|
164
|
+
function recordDeliveredRead(cache, call, payload) {
|
|
165
|
+
const r = payload.result;
|
|
166
|
+
if (!payload.ok || !r || r.truncated !== false || r.range === true || typeof r.content !== "string" || typeof r.sha256 !== "string")
|
|
167
|
+
return;
|
|
168
|
+
try {
|
|
169
|
+
const selector = call.arguments?.repository;
|
|
170
|
+
const repo = selector ? resolveRepository(selector) : activeRepository();
|
|
171
|
+
cache.record(repo.id, String(r.path), r.sha256, call.tool_call_id);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
/* an unresolvable repository is simply not cached */
|
|
175
|
+
}
|
|
176
|
+
}
|
|
136
177
|
/** The codes the server documents for client tool failures. */
|
|
137
178
|
function publicCode(code) {
|
|
138
179
|
switch (code) {
|
|
@@ -162,6 +203,16 @@ function fitResult(result) {
|
|
|
162
203
|
}
|
|
163
204
|
return { ...result, content: "", truncated: true };
|
|
164
205
|
}
|
|
206
|
+
const commandText = (args) => {
|
|
207
|
+
const a = (args ?? {});
|
|
208
|
+
const program = typeof a.program === "string" ? a.program : "";
|
|
209
|
+
const rest = Array.isArray(a.args) ? a.args.filter((x) => typeof x === "string") : [];
|
|
210
|
+
return program ? [program, ...rest].join(" ").slice(0, 300) : undefined;
|
|
211
|
+
};
|
|
212
|
+
const pathOf = (args) => {
|
|
213
|
+
const p = args?.path;
|
|
214
|
+
return typeof p === "string" ? p.slice(0, 300) : undefined;
|
|
215
|
+
};
|
|
165
216
|
/**
|
|
166
217
|
* Post a result, retrying once on a transport failure: the server holds the
|
|
167
218
|
* call for its timeout, so a blip should not cost the turn. A 4xx is an
|
|
@@ -175,10 +226,13 @@ export async function submitWithRetry(client, payload) {
|
|
|
175
226
|
}
|
|
176
227
|
catch (err) {
|
|
177
228
|
const status = err.status ?? 0;
|
|
178
|
-
if (status >= 400 && status < 500)
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
229
|
+
if (terminalToolRejection(err) || (status >= 400 && status < 500 && status !== 408 && status !== 429) || attempt === 1) {
|
|
230
|
+
const failure = err instanceof ToolDeliveryError ? err : new ToolDeliveryError(terminalToolRejection(err)
|
|
231
|
+
? "The server rejected the tool result. The tool was not rerun; the conversation may not reflect its outcome."
|
|
232
|
+
: undefined);
|
|
233
|
+
errorLine(failure.message);
|
|
234
|
+
throw failure;
|
|
235
|
+
}
|
|
182
236
|
await new Promise((r) => setTimeout(r, 400));
|
|
183
237
|
}
|
|
184
238
|
}
|
|
@@ -193,6 +247,30 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
|
193
247
|
return; // nothing to correlate an answer with
|
|
194
248
|
const label = toolActivityLabel(call);
|
|
195
249
|
const started = Date.now();
|
|
250
|
+
if (call.name === "coding_workflow") {
|
|
251
|
+
let payload;
|
|
252
|
+
try {
|
|
253
|
+
if (!ui.workflow || declaredClientTools(ctx) === undefined)
|
|
254
|
+
throw new Error("Coding workflow is not enabled in this trusted interactive session.");
|
|
255
|
+
payload = { tool_call_id: id, ok: true, result: await ui.workflow.control(call) };
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
payload = { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } };
|
|
259
|
+
const action = call.arguments?.action;
|
|
260
|
+
ui.onRefused?.({ proposal: action === "plan" ? "plan" : "workflow", ...(typeof action === "string" ? { target: action } : {}),
|
|
261
|
+
code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
await submitWithRetry(client, payload);
|
|
265
|
+
if (payload.ok)
|
|
266
|
+
ui.workflow?.confirmControl(id);
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
ui.workflow?.interrupt();
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
196
274
|
// A proposed command goes to the command coordinator — never anywhere else,
|
|
197
275
|
// and never at all unless this turn offered commands.
|
|
198
276
|
if (call.name === "run_command" || call.kind === "command") {
|
|
@@ -203,8 +281,17 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
|
203
281
|
error: { code: "COMMAND_NOT_ENABLED", message: "Local commands are not enabled in this session. Nothing ran." },
|
|
204
282
|
duration_ms: 0
|
|
205
283
|
});
|
|
284
|
+
ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "COMMAND_NOT_ENABLED", reason: "Local commands are not enabled in this session. Nothing ran." });
|
|
206
285
|
}
|
|
207
286
|
else {
|
|
287
|
+
try {
|
|
288
|
+
ui.workflow?.beforeCommand(call);
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
await submitWithRetry(client, { tool_call_id: id, ok: false, error: { code: "CODING_WORKFLOW_BLOCKED", message: error.message } });
|
|
292
|
+
ui.onRefused?.({ proposal: "command", target: commandText(call.arguments), code: "CODING_WORKFLOW_BLOCKED", reason: error.message });
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
208
295
|
await ui.commands.handle(call);
|
|
209
296
|
}
|
|
210
297
|
return;
|
|
@@ -219,6 +306,7 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
|
219
306
|
error: { code: "MUTATION_NOT_ENABLED", message: "File changes are not enabled in this session. Nothing was changed." },
|
|
220
307
|
duration_ms: 0
|
|
221
308
|
});
|
|
309
|
+
ui.onRefused?.({ proposal: "change", target: pathOf(call.arguments), code: "MUTATION_NOT_ENABLED", reason: "File changes are not enabled in this session. Nothing was changed." });
|
|
222
310
|
}
|
|
223
311
|
else {
|
|
224
312
|
await ui.mutations.handle(call);
|
|
@@ -245,7 +333,7 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
|
245
333
|
else {
|
|
246
334
|
// The executor re-validates everything — name, arguments, containment,
|
|
247
335
|
// ignore rules, size — regardless of what the server already checked.
|
|
248
|
-
const res = executeLocalTool({ id, name: call.name, arguments: call.arguments });
|
|
336
|
+
const res = executeLocalTool({ id, name: call.name, arguments: call.arguments }, { readCache: ui.readCache });
|
|
249
337
|
payload = res.ok
|
|
250
338
|
? { tool_call_id: id, ok: true, result: fitResult(res.result) }
|
|
251
339
|
: {
|
|
@@ -256,5 +344,9 @@ export async function handleClientToolCall(ctx, client, call, ui = {}) {
|
|
|
256
344
|
}
|
|
257
345
|
payload.duration_ms = Date.now() - started;
|
|
258
346
|
await submitWithRetry(client, payload);
|
|
347
|
+
// Only bytes that were actually posted, untrimmed, count as delivered.
|
|
348
|
+
if (ui.readCache && call.name === "read_file")
|
|
349
|
+
recordDeliveredRead(ui.readCache, call, payload);
|
|
350
|
+
ui.workflow?.observeRead(call, payload);
|
|
259
351
|
ui.onDone?.(label, payload.ok, call.name, payload.ok ? payload.result : payload.error?.message);
|
|
260
352
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The function / class a line belongs to — deterministic, no parser, no index.
|
|
3
|
+
*
|
|
4
|
+
* Used to label search matches ("line 58, in Cart.subtotal") so an agent can go
|
|
5
|
+
* from a matching line to the symbol to its callers (by searching the name)
|
|
6
|
+
* without reading whole files first. Heuristic by design: it recognises common
|
|
7
|
+
* declaration shapes in JS/TS, Python, Go, Rust, Java/C#/Kotlin and Ruby, and
|
|
8
|
+
* uses indentation to find the enclosing one. When unsure it returns nothing
|
|
9
|
+
* rather than a guess.
|
|
10
|
+
*/
|
|
11
|
+
/** How far above a line to look for its declaration. */
|
|
12
|
+
const MAX_SCAN = 400;
|
|
13
|
+
const KEYWORDS = new Set(["if", "for", "while", "switch", "catch", "return", "function", "else", "do", "try", "with", "new", "typeof", "await"]);
|
|
14
|
+
/** Declaration patterns; the first capture group that is a name wins. */
|
|
15
|
+
const PATTERNS = [
|
|
16
|
+
// class / interface / struct / enum / trait / impl / module (any language)
|
|
17
|
+
{ re: /^\s*(?:export\s+)?(?:default\s+)?(?:public\s+|private\s+|protected\s+|internal\s+)?(?:abstract\s+|final\s+|sealed\s+|static\s+|data\s+|pub(?:\([^)]*\))?\s+)*(?:class|interface|struct|enum|trait|impl|module|object)\s+(?:<[^>]*>\s*)?([A-Za-z_$][\w$]*)/, container: true },
|
|
18
|
+
// JS/TS function declarations
|
|
19
|
+
{ re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/ },
|
|
20
|
+
// JS/TS const x = (...) => / function
|
|
21
|
+
{ re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/ },
|
|
22
|
+
// Python / Ruby
|
|
23
|
+
{ re: /^\s*(?:async\s+)?def\s+(?:self\.)?([A-Za-z_]\w*[!?]?)/ },
|
|
24
|
+
// Go (functions and methods)
|
|
25
|
+
{ re: /^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/ },
|
|
26
|
+
// Rust
|
|
27
|
+
{ re: /^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)/ },
|
|
28
|
+
// Class members: JS/TS methods, Java/C#/Kotlin methods — `name(args) {` with optional modifiers/return type
|
|
29
|
+
{ re: /^\s*(?:(?:public|private|protected|internal|static|async|override|virtual|final|readonly|get|set|fun)\s+)*(?:[\w<>\[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\([^;]*\)\s*(?::\s*[^{=;]+)?(?:throws\s+[\w., ]+)?\s*\{\s*$/ }
|
|
30
|
+
];
|
|
31
|
+
const indentOf = (line) => {
|
|
32
|
+
const m = /^[ \t]*/.exec(line);
|
|
33
|
+
return m ? m[0].replace(/\t/g, " ").length : 0;
|
|
34
|
+
};
|
|
35
|
+
export function declaration(line) {
|
|
36
|
+
for (const { re, container } of PATTERNS) {
|
|
37
|
+
const m = re.exec(line);
|
|
38
|
+
const name = m?.[1];
|
|
39
|
+
if (name && !KEYWORDS.has(name))
|
|
40
|
+
return { name, container: !!container };
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The innermost declaration enclosing `lines[index]` (0-based), with its
|
|
46
|
+
* containing class/struct when there is one: "Cart.subtotal", "subtotal",
|
|
47
|
+
* "Cart". The line itself counts when it is the declaration.
|
|
48
|
+
*/
|
|
49
|
+
export function enclosingSymbol(lines, index) {
|
|
50
|
+
if (index < 0 || index >= lines.length)
|
|
51
|
+
return undefined;
|
|
52
|
+
const own = declaration(lines[index]);
|
|
53
|
+
let inner = own ? { ...own, indent: indentOf(lines[index]) } : undefined;
|
|
54
|
+
let limit = inner ? inner.indent : indentOf(lines[index]);
|
|
55
|
+
// A top-level line that is not itself a declaration belongs to no symbol: the
|
|
56
|
+
// declarations above it are its siblings, not its parents.
|
|
57
|
+
if (!inner && limit === 0)
|
|
58
|
+
return undefined;
|
|
59
|
+
let outer;
|
|
60
|
+
for (let i = index - 1, scanned = 0; i >= 0 && scanned < MAX_SCAN; i -= 1, scanned += 1) {
|
|
61
|
+
const line = lines[i];
|
|
62
|
+
if (!line.trim())
|
|
63
|
+
continue;
|
|
64
|
+
const indent = indentOf(line);
|
|
65
|
+
if (indent >= limit)
|
|
66
|
+
continue;
|
|
67
|
+
const d = declaration(line);
|
|
68
|
+
if (!d) {
|
|
69
|
+
// A shallower non-declaration line (e.g. the closing brace of an earlier
|
|
70
|
+
// block at top level) means the enclosing scope is above it; keep looking,
|
|
71
|
+
// but only for something still shallower.
|
|
72
|
+
if (indent < limit)
|
|
73
|
+
limit = indent;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!inner) {
|
|
77
|
+
inner = { ...d, indent };
|
|
78
|
+
limit = indent;
|
|
79
|
+
if (indent === 0)
|
|
80
|
+
break;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (d.container && !inner.container) {
|
|
84
|
+
outer = d.name;
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
limit = indent;
|
|
88
|
+
if (indent === 0)
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
if (!inner)
|
|
92
|
+
return undefined;
|
|
93
|
+
return outer ? `${outer}.${inner.name}` : inner.name;
|
|
94
|
+
}
|