march-cli 0.1.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/bin/march.mjs +13 -0
- package/package.json +36 -0
- package/src/agent/command-exec-tool.mjs +91 -0
- package/src/agent/context-stats-tool.mjs +57 -0
- package/src/agent/editing/diff-apply.mjs +28 -0
- package/src/agent/editing/diff-format.mjs +57 -0
- package/src/agent/file-edit-tool.mjs +276 -0
- package/src/agent/find-tool.mjs +112 -0
- package/src/agent/model-payload-dumper.mjs +201 -0
- package/src/agent/pi-session/pi-session-sidecar-failure.mjs +10 -0
- package/src/agent/provider/payload-messages.mjs +138 -0
- package/src/agent/read-file-tool.mjs +112 -0
- package/src/agent/runner/fast-model.mjs +36 -0
- package/src/agent/runner/runner-cleanup.mjs +12 -0
- package/src/agent/runner/runner-init.mjs +15 -0
- package/src/agent/runner/runner-session-state.mjs +40 -0
- package/src/agent/runner.mjs +266 -0
- package/src/agent/runtime/runner-runtime-host.mjs +73 -0
- package/src/agent/runtime/runtime-factory.mjs +42 -0
- package/src/agent/runtime/runtime-host.mjs +34 -0
- package/src/agent/session/session-auto-name.mjs +41 -0
- package/src/agent/session/session-binding.mjs +12 -0
- package/src/agent/session/session-options.mjs +46 -0
- package/src/agent/tool-names.mjs +1 -0
- package/src/agent/tool-result.mjs +3 -0
- package/src/agent/tools.mjs +54 -0
- package/src/agent/turn/turn-events.mjs +64 -0
- package/src/agent/turn/turn-runner.mjs +103 -0
- package/src/auth/login-command.mjs +90 -0
- package/src/auth/storage.mjs +33 -0
- package/src/cli/args.mjs +71 -0
- package/src/cli/commands/copy-command.mjs +73 -0
- package/src/cli/commands/export-command.mjs +206 -0
- package/src/cli/commands/extensions-command.mjs +53 -0
- package/src/cli/commands/help-command.mjs +7 -0
- package/src/cli/commands/model-command.mjs +110 -0
- package/src/cli/commands/paste-image-command.mjs +43 -0
- package/src/cli/commands/provider-command.mjs +55 -0
- package/src/cli/commands/status-command.mjs +157 -0
- package/src/cli/commands/thinking-command.mjs +80 -0
- package/src/cli/fallback-ui.mjs +156 -0
- package/src/cli/input/attachment-tokens.mjs +20 -0
- package/src/cli/input/autocomplete.mjs +106 -0
- package/src/cli/input/external-editor.mjs +39 -0
- package/src/cli/input/history-store.mjs +35 -0
- package/src/cli/input/image-clipboard.mjs +55 -0
- package/src/cli/input/keybinding-dispatch.mjs +76 -0
- package/src/cli/input/keybindings.mjs +96 -0
- package/src/cli/input/mode-state.mjs +43 -0
- package/src/cli/input/prompt-templates.mjs +84 -0
- package/src/cli/input/select-with-keyboard.mjs +67 -0
- package/src/cli/permissions.mjs +103 -0
- package/src/cli/repl-commands.mjs +86 -0
- package/src/cli/repl-loop.mjs +157 -0
- package/src/cli/selector-list.mjs +21 -0
- package/src/cli/session/pi-session-switch-command.mjs +41 -0
- package/src/cli/session/session-command.mjs +23 -0
- package/src/cli/session/session-list-command.mjs +68 -0
- package/src/cli/session/session-name-command.mjs +26 -0
- package/src/cli/session/session-source-command.mjs +89 -0
- package/src/cli/session/session-switch-command.mjs +1 -0
- package/src/cli/shell/shell-command.mjs +55 -0
- package/src/cli/shell/shell-drawer-controls.mjs +33 -0
- package/src/cli/shell/shell-drawer.mjs +192 -0
- package/src/cli/shell/shell-split-layout.mjs +70 -0
- package/src/cli/slash-commands.mjs +176 -0
- package/src/cli/startup/startup-banner.mjs +17 -0
- package/src/cli/startup/startup-session.mjs +51 -0
- package/src/cli/status-line-updater.mjs +74 -0
- package/src/cli/tool-output.mjs +9 -0
- package/src/cli/tui/editor/external-editor-runner.mjs +24 -0
- package/src/cli/tui/input/mouse-selection-controller.mjs +89 -0
- package/src/cli/tui/input/mouse-tracking.mjs +20 -0
- package/src/cli/tui/layout/main-pane-layout.mjs +38 -0
- package/src/cli/tui/layout/safe-render-boundary.mjs +46 -0
- package/src/cli/tui/markdown-renderer.mjs +279 -0
- package/src/cli/tui/output/scroll-state.mjs +79 -0
- package/src/cli/tui/output/tool-card-renderer.mjs +59 -0
- package/src/cli/tui/output-buffer.mjs +297 -0
- package/src/cli/tui/permission-request-ui.mjs +18 -0
- package/src/cli/tui/recall-rendering.mjs +25 -0
- package/src/cli/tui/select/editor-select-list.mjs +111 -0
- package/src/cli/tui/selection-screen.mjs +212 -0
- package/src/cli/tui/status/retry-status.mjs +72 -0
- package/src/cli/tui/status/spinner-status.mjs +42 -0
- package/src/cli/tui/status/status-bar.mjs +88 -0
- package/src/cli/tui/syntax/highlighting.mjs +277 -0
- package/src/cli/tui/syntax/languages.mjs +91 -0
- package/src/cli/tui/syntax/tree-sitter/bash.highlights.scm +261 -0
- package/src/cli/tui/syntax/tree-sitter/c.highlights.scm +341 -0
- package/src/cli/tui/syntax/tree-sitter/cpp.highlights.scm +268 -0
- package/src/cli/tui/syntax/tree-sitter/csharp.highlights.scm +577 -0
- package/src/cli/tui/syntax/tree-sitter/css.highlights.scm +109 -0
- package/src/cli/tui/syntax/tree-sitter/diff.highlights.scm +49 -0
- package/src/cli/tui/syntax/tree-sitter/go.highlights.scm +254 -0
- package/src/cli/tui/syntax/tree-sitter/html.highlights.scm +13 -0
- package/src/cli/tui/syntax/tree-sitter/java.highlights.scm +330 -0
- package/src/cli/tui/syntax/tree-sitter/json.highlights.scm +38 -0
- package/src/cli/tui/syntax/tree-sitter/php.highlights.scm +203 -0
- package/src/cli/tui/syntax/tree-sitter/python.highlights.scm +137 -0
- package/src/cli/tui/syntax/tree-sitter/ruby.highlights.scm +309 -0
- package/src/cli/tui/syntax/tree-sitter/rust.highlights.scm +531 -0
- package/src/cli/tui/syntax/tree-sitter/toml.highlights.scm +39 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-bash.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-c-sharp.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-c.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-cpp.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-css.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-diff.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-go.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-html.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-java.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-json.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-php.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-python.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-ruby.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-rust.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-toml.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-tsx.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-typescript.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tree-sitter-yaml.wasm +0 -0
- package/src/cli/tui/syntax/tree-sitter/tsx.highlights.scm +35 -0
- package/src/cli/tui/syntax/tree-sitter/typescript.highlights.scm +35 -0
- package/src/cli/tui/syntax/tree-sitter/yaml.highlights.scm +99 -0
- package/src/cli/tui/tool-rendering.mjs +194 -0
- package/src/cli/tui/tui-diff-rendering.mjs +157 -0
- package/src/cli/tui/tui-handlers.mjs +110 -0
- package/src/cli/tui/tui-input-controller.mjs +61 -0
- package/src/cli/tui/ui-theme.mjs +148 -0
- package/src/cli/ui.mjs +299 -0
- package/src/config/config-json.mjs +73 -0
- package/src/config/dotenv.mjs +20 -0
- package/src/config/features.mjs +75 -0
- package/src/config/loader.mjs +109 -0
- package/src/config/settings-command.mjs +97 -0
- package/src/context/diagnostics.mjs +70 -0
- package/src/context/engine.mjs +148 -0
- package/src/context/injections.mjs +26 -0
- package/src/context/project-context.mjs +20 -0
- package/src/context/session-status.mjs +15 -0
- package/src/context/shell-layers.mjs +23 -0
- package/src/context/system-core/base.md +60 -0
- package/src/context/system-core/prompts/deepseek-v4-pro.md +3 -0
- package/src/context/system-core/prompts/default.md +3 -0
- package/src/context/system-core.mjs +35 -0
- package/src/debug/model-context-dumper.mjs +52 -0
- package/src/extensions/discovery.mjs +40 -0
- package/src/extensions/lifecycle-adapter.mjs +210 -0
- package/src/extensions/lifecycle-manifest.mjs +69 -0
- package/src/image-gen/index.mjs +7 -0
- package/src/image-gen/provider.mjs +231 -0
- package/src/image-gen/tool.mjs +84 -0
- package/src/lsp/client.mjs +204 -0
- package/src/lsp/diagnostic-store.mjs +39 -0
- package/src/lsp/servers.mjs +212 -0
- package/src/lsp/service.mjs +65 -0
- package/src/main.mjs +294 -0
- package/src/mcp/client.mjs +195 -0
- package/src/mcp/config.mjs +130 -0
- package/src/mcp/index.mjs +48 -0
- package/src/mcp/tools.mjs +98 -0
- package/src/memory/database.mjs +219 -0
- package/src/memory/glossary.mjs +124 -0
- package/src/memory/graph/graph-cascades.mjs +109 -0
- package/src/memory/graph/graph-diagnostics.mjs +73 -0
- package/src/memory/graph/graph-path-removal.mjs +50 -0
- package/src/memory/graph/graph-path-utils.mjs +17 -0
- package/src/memory/graph/graph-primitives.mjs +103 -0
- package/src/memory/graph/graph-read.mjs +159 -0
- package/src/memory/graph.mjs +282 -0
- package/src/memory/markdown/markdown-delete.mjs +23 -0
- package/src/memory/markdown/markdown-format.mjs +128 -0
- package/src/memory/markdown/markdown-recall.mjs +28 -0
- package/src/memory/markdown/ripgrep.mjs +16 -0
- package/src/memory/markdown/sqlite-index.mjs +87 -0
- package/src/memory/markdown-store.mjs +286 -0
- package/src/memory/markdown-tools.mjs +103 -0
- package/src/memory/search.mjs +142 -0
- package/src/memory/snapshot.mjs +86 -0
- package/src/memory/system-views.mjs +120 -0
- package/src/memory/tools.mjs +282 -0
- package/src/notification/desktop-notifier.mjs +85 -0
- package/src/platform/open-file.mjs +28 -0
- package/src/provider/config-command.mjs +129 -0
- package/src/provider/presets.mjs +72 -0
- package/src/session/attachment-display.mjs +16 -0
- package/src/session/attachment-references.mjs +65 -0
- package/src/session/attachments.mjs +140 -0
- package/src/session/persist.mjs +1 -0
- package/src/session/pi-manager.mjs +34 -0
- package/src/session/session-utils.mjs +16 -0
- package/src/session/sidecar-sync.mjs +19 -0
- package/src/session/sidecar.mjs +68 -0
- package/src/session/transcript.mjs +83 -0
- package/src/session/tree.mjs +42 -0
- package/src/shell/cli-runtime.mjs +11 -0
- package/src/shell/hints.mjs +12 -0
- package/src/shell/node-pty-adapter.mjs +81 -0
- package/src/shell/runtime-state.mjs +126 -0
- package/src/shell/runtime.mjs +244 -0
- package/src/shell/screen-buffer.mjs +136 -0
- package/src/shell/tool-read.mjs +74 -0
- package/src/shell/tools.mjs +299 -0
- package/src/supergrok/actions/image-generate.mjs +60 -0
- package/src/supergrok/actions/search.mjs +78 -0
- package/src/supergrok/auth.mjs +36 -0
- package/src/supergrok/constants.mjs +18 -0
- package/src/supergrok/oauth-provider.mjs +278 -0
- package/src/supergrok/provider.mjs +36 -0
- package/src/supergrok/response.mjs +76 -0
- package/src/supergrok/tool.mjs +61 -0
- package/src/text/ansi.mjs +3 -0
- package/src/web/config-command.mjs +43 -0
- package/src/web/fetch.mjs +78 -0
- package/src/web/presets.mjs +16 -0
- package/src/web/search.mjs +83 -0
- package/src/web/tools.mjs +107 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { stripAnsi } from "../text/ansi.mjs";
|
|
2
|
+
|
|
3
|
+
export { appendProviderUserMessage, replaceProviderContextMessages, replaceProviderSystemPrompt } from "./provider/payload-messages.mjs";
|
|
4
|
+
|
|
5
|
+
const MODEL_PAYLOAD_DUMPER_INSTALLED = Symbol("march.modelPayloadDumperInstalled");
|
|
6
|
+
|
|
7
|
+
export function installModelPayloadDumper(session, modelContextDumper, getKind = () => "model", onModelPayload = null, transformPayload = null) {
|
|
8
|
+
if ((!modelContextDumper?.enabled && typeof onModelPayload !== "function" && typeof transformPayload !== "function") || !session?.agent) return;
|
|
9
|
+
const agent = session.agent;
|
|
10
|
+
if (agent[MODEL_PAYLOAD_DUMPER_INSTALLED]) return;
|
|
11
|
+
const originalOnPayload = agent.onPayload;
|
|
12
|
+
agent.onPayload = async (payload, model) => {
|
|
13
|
+
const replacement = originalOnPayload ? await originalOnPayload(payload, model) : undefined;
|
|
14
|
+
const originalEffectivePayload = replacement === undefined ? payload : replacement;
|
|
15
|
+
const kind = getKind();
|
|
16
|
+
const effectivePayload = typeof transformPayload === "function"
|
|
17
|
+
? transformPayload(originalEffectivePayload, { kind, model })
|
|
18
|
+
: originalEffectivePayload;
|
|
19
|
+
onModelPayload?.({
|
|
20
|
+
payload: effectivePayload,
|
|
21
|
+
model,
|
|
22
|
+
kind,
|
|
23
|
+
estimatedTokens: estimateProviderPayloadTokens(effectivePayload),
|
|
24
|
+
});
|
|
25
|
+
if (!modelContextDumper?.enabled) {
|
|
26
|
+
return effectivePayload !== originalEffectivePayload ? effectivePayload : replacement;
|
|
27
|
+
}
|
|
28
|
+
const metadata = {
|
|
29
|
+
provider: model?.provider,
|
|
30
|
+
model: model?.id,
|
|
31
|
+
payload: "provider_request",
|
|
32
|
+
};
|
|
33
|
+
const requestPath = modelContextDumper.dump({
|
|
34
|
+
kind,
|
|
35
|
+
prompt: formatHumanPayload(effectivePayload),
|
|
36
|
+
metadata,
|
|
37
|
+
});
|
|
38
|
+
modelContextDumper.dumpSidecar?.({
|
|
39
|
+
sourcePath: requestPath,
|
|
40
|
+
suffix: "payload",
|
|
41
|
+
value: effectivePayload,
|
|
42
|
+
});
|
|
43
|
+
const tools = extractPayloadTools(effectivePayload);
|
|
44
|
+
if (tools) {
|
|
45
|
+
modelContextDumper.dumpSidecar?.({
|
|
46
|
+
sourcePath: requestPath,
|
|
47
|
+
suffix: "tools",
|
|
48
|
+
value: {
|
|
49
|
+
metadata: { ...metadata, payload: "provider_tools" },
|
|
50
|
+
tools,
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
if (effectivePayload !== originalEffectivePayload) return effectivePayload;
|
|
55
|
+
return replacement;
|
|
56
|
+
};
|
|
57
|
+
agent[MODEL_PAYLOAD_DUMPER_INSTALLED] = true;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function estimateProviderPayloadTokens(payload) {
|
|
61
|
+
const request = normalizePayload(payload);
|
|
62
|
+
let chars = 0;
|
|
63
|
+
for (const key of ["system", "systemPrompt", "instructions"]) {
|
|
64
|
+
chars += textChars(request[key]);
|
|
65
|
+
}
|
|
66
|
+
for (const key of ["messages", "input"]) {
|
|
67
|
+
if (Array.isArray(request[key])) chars += textChars(request[key]);
|
|
68
|
+
}
|
|
69
|
+
const tools = extractPayloadTools(payload);
|
|
70
|
+
if (tools?.length) chars += JSON.stringify(tools).length;
|
|
71
|
+
if (chars === 0) chars = JSON.stringify(request).length;
|
|
72
|
+
return Math.ceil(chars / 4);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function formatHumanPayload(payload) {
|
|
76
|
+
const request = normalizePayload(payload);
|
|
77
|
+
const lines = ["# Messages", ""];
|
|
78
|
+
const messages = getHumanMessages(request);
|
|
79
|
+
const toolCalls = collectToolCalls(messages);
|
|
80
|
+
if (messages.length === 0) {
|
|
81
|
+
lines.push("(no messages found)", "");
|
|
82
|
+
} else {
|
|
83
|
+
for (const message of messages) {
|
|
84
|
+
lines.push(formatMessageHeading(message, toolCalls), "", formatMessageContent(message.content));
|
|
85
|
+
if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
|
|
86
|
+
lines.push("", ...message.tool_calls.map(formatToolCallLine));
|
|
87
|
+
}
|
|
88
|
+
lines.push("");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const tools = extractPayloadTools(payload);
|
|
93
|
+
if (tools?.length) {
|
|
94
|
+
lines.push("# Tools", "");
|
|
95
|
+
for (const tool of tools) lines.push(`- ${formatToolSummary(tool)}`);
|
|
96
|
+
lines.push("");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
lines.push("# Raw Payload", "", "See the sibling `*-payload.json` file for the exact provider request.");
|
|
100
|
+
if (tools?.length) lines.push("See the sibling `*-tools.json` file for the complete tool schema.");
|
|
101
|
+
return lines.join("\n");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function getHumanMessages(request) {
|
|
105
|
+
if (Array.isArray(request.messages)) return request.messages;
|
|
106
|
+
if (!Array.isArray(request.input)) return [];
|
|
107
|
+
const messages = [];
|
|
108
|
+
if (typeof request.instructions === "string" && request.instructions) {
|
|
109
|
+
messages.push({ role: "system", content: request.instructions });
|
|
110
|
+
}
|
|
111
|
+
for (const item of request.input) {
|
|
112
|
+
if (!item || typeof item !== "object") continue;
|
|
113
|
+
if (item.role) {
|
|
114
|
+
messages.push(item);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
messages.push({ role: item.type ?? "input", content: item });
|
|
118
|
+
}
|
|
119
|
+
return messages;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function collectToolCalls(messages) {
|
|
123
|
+
const calls = new Map();
|
|
124
|
+
for (const message of messages) {
|
|
125
|
+
if (!Array.isArray(message?.tool_calls)) continue;
|
|
126
|
+
for (const call of message.tool_calls) {
|
|
127
|
+
if (call?.id) calls.set(call.id, call);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return calls;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function formatMessageHeading(message, toolCalls) {
|
|
134
|
+
if (message?.role !== "tool") return `## ${message?.role ?? "message"}`;
|
|
135
|
+
const call = toolCalls.get(message.tool_call_id);
|
|
136
|
+
const name = call?.function?.name ?? message.name;
|
|
137
|
+
return name ? `## tool ${name}` : "## tool";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function formatToolCallLine(call) {
|
|
141
|
+
const name = call?.function?.name ?? call?.name ?? "unnamed_tool";
|
|
142
|
+
const args = call?.function?.arguments ?? call?.arguments ?? "";
|
|
143
|
+
return `tool_call ${name}(${stripAnsi(String(args ?? ""))})`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function normalizePayload(payload) {
|
|
147
|
+
if (!payload || typeof payload !== "object") return { messages: [{ role: "payload", content: String(payload ?? "") }] };
|
|
148
|
+
if (Array.isArray(payload.messages)) return payload;
|
|
149
|
+
if (payload.body && typeof payload.body === "object") return payload.body;
|
|
150
|
+
if (typeof payload.body === "string") {
|
|
151
|
+
try {
|
|
152
|
+
return JSON.parse(payload.body);
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
return payload;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function formatMessageContent(content) {
|
|
159
|
+
if (typeof content === "string") return stripAnsi(content);
|
|
160
|
+
if (Array.isArray(content)) return content.map(formatContentPart).join("\n");
|
|
161
|
+
return stripAnsi(JSON.stringify(content, null, 2));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function formatContentPart(part) {
|
|
165
|
+
if (typeof part === "string") return stripAnsi(part);
|
|
166
|
+
if (!part || typeof part !== "object") return String(part ?? "");
|
|
167
|
+
if (typeof part.text === "string") return stripAnsi(part.text);
|
|
168
|
+
if (part.type) return stripAnsi(`[${part.type}] ${JSON.stringify(part)}`);
|
|
169
|
+
return stripAnsi(JSON.stringify(part));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function formatToolSummary(tool) {
|
|
173
|
+
const name = tool?.function?.name ?? tool?.name ?? "unnamed_tool";
|
|
174
|
+
const description = tool?.function?.description ?? tool?.description ?? "";
|
|
175
|
+
return description ? `${name}: ${description}` : name;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function extractPayloadTools(payload) {
|
|
179
|
+
if (!payload || typeof payload !== "object") return null;
|
|
180
|
+
if (Array.isArray(payload.tools)) return payload.tools;
|
|
181
|
+
if (payload.body && typeof payload.body === "object" && Array.isArray(payload.body.tools)) return payload.body.tools;
|
|
182
|
+
if (typeof payload.body === "string") {
|
|
183
|
+
try {
|
|
184
|
+
const body = JSON.parse(payload.body);
|
|
185
|
+
if (Array.isArray(body.tools)) return body.tools;
|
|
186
|
+
} catch {}
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function textChars(value) {
|
|
192
|
+
if (value == null) return 0;
|
|
193
|
+
if (typeof value === "string") return value.length;
|
|
194
|
+
if (Array.isArray(value)) return value.reduce((sum, item) => sum + textChars(item), 0);
|
|
195
|
+
if (typeof value !== "object") return String(value).length;
|
|
196
|
+
if (typeof value.text === "string") return value.text.length;
|
|
197
|
+
if (typeof value.content === "string") return value.content.length;
|
|
198
|
+
if (Array.isArray(value.content)) return textChars(value.content);
|
|
199
|
+
if (value.type === "image" || value.type === "image_url") return 0;
|
|
200
|
+
return JSON.stringify(value).length;
|
|
201
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export async function createSidecarWriteFailure({ runtimeHost, sourceSessionFile, action, cause }) {
|
|
2
|
+
const causeMessage = cause?.message ?? String(cause);
|
|
3
|
+
const baseMessage = `failed to write pi session sidecar after ${action}: ${causeMessage}`;
|
|
4
|
+
try {
|
|
5
|
+
await runtimeHost.switchSession(sourceSessionFile);
|
|
6
|
+
return new Error(`${baseMessage}; rolled back to source session`);
|
|
7
|
+
} catch (rollbackErr) {
|
|
8
|
+
return new Error(`${baseMessage}; rollback failed: ${rollbackErr.message}`);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export function replaceProviderSystemPrompt(payload, systemPrompt) {
|
|
2
|
+
if (!payload || typeof payload !== "object" || !systemPrompt) return payload;
|
|
3
|
+
if (payload.body && typeof payload.body === "object") {
|
|
4
|
+
const body = replaceProviderSystemPrompt(payload.body, systemPrompt);
|
|
5
|
+
return body === payload.body ? payload : { ...payload, body };
|
|
6
|
+
}
|
|
7
|
+
if (typeof payload.body === "string") {
|
|
8
|
+
try {
|
|
9
|
+
const body = JSON.parse(payload.body);
|
|
10
|
+
const replaced = replaceProviderSystemPrompt(body, systemPrompt);
|
|
11
|
+
return replaced === body ? payload : { ...payload, body: JSON.stringify(replaced) };
|
|
12
|
+
} catch {
|
|
13
|
+
return payload;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (!Array.isArray(payload.messages)) return payload;
|
|
17
|
+
return {
|
|
18
|
+
...payload,
|
|
19
|
+
messages: [
|
|
20
|
+
{ role: "system", content: systemPrompt },
|
|
21
|
+
...payload.messages.filter((message) => message?.role !== "system"),
|
|
22
|
+
],
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function replaceProviderContextMessages(payload, providerContext) {
|
|
27
|
+
if (!payload || typeof payload !== "object" || !providerContext?.system) return payload;
|
|
28
|
+
if (payload.body && typeof payload.body === "object") {
|
|
29
|
+
const body = replaceProviderContextMessages(payload.body, providerContext);
|
|
30
|
+
return body === payload.body ? payload : { ...payload, body };
|
|
31
|
+
}
|
|
32
|
+
if (typeof payload.body === "string") {
|
|
33
|
+
try {
|
|
34
|
+
const body = JSON.parse(payload.body);
|
|
35
|
+
const replaced = replaceProviderContextMessages(body, providerContext);
|
|
36
|
+
return replaced === body ? payload : { ...payload, body: JSON.stringify(replaced) };
|
|
37
|
+
} catch {
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(payload.messages)) return replaceChatMessagesPayload(payload, providerContext);
|
|
42
|
+
if (Array.isArray(payload.input) && typeof payload.instructions === "string") return replaceResponsesPayload(payload, providerContext);
|
|
43
|
+
return payload;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function appendProviderUserMessage(payload, content) {
|
|
47
|
+
if (!payload || typeof payload !== "object" || !content) return payload;
|
|
48
|
+
if (payload.body && typeof payload.body === "object") {
|
|
49
|
+
const body = appendProviderUserMessage(payload.body, content);
|
|
50
|
+
return body === payload.body ? payload : { ...payload, body };
|
|
51
|
+
}
|
|
52
|
+
if (typeof payload.body === "string") {
|
|
53
|
+
try {
|
|
54
|
+
const body = JSON.parse(payload.body);
|
|
55
|
+
const appended = appendProviderUserMessage(body, content);
|
|
56
|
+
return appended === body ? payload : { ...payload, body: JSON.stringify(appended) };
|
|
57
|
+
} catch {
|
|
58
|
+
return payload;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (Array.isArray(payload.messages)) {
|
|
62
|
+
return {
|
|
63
|
+
...payload,
|
|
64
|
+
messages: [...payload.messages, { role: "user", content }],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (Array.isArray(payload.input) && typeof payload.instructions === "string") {
|
|
68
|
+
return {
|
|
69
|
+
...payload,
|
|
70
|
+
input: [...payload.input, { role: "user", content: [{ type: "input_text", text: content }] }],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return payload;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function replaceChatMessagesPayload(payload, providerContext) {
|
|
77
|
+
const originalUser = payload.messages.findLast?.((message) => message?.role === "user")
|
|
78
|
+
?? [...payload.messages].reverse().find((message) => message?.role === "user");
|
|
79
|
+
const userMessages = (providerContext.userMessages ?? []).filter((message) => message?.content);
|
|
80
|
+
const contextMessages = userMessages.map((message, index) => ({
|
|
81
|
+
role: "user",
|
|
82
|
+
content: index === userMessages.length - 1 ? contentWithOriginalNonTextParts(message.content, originalUser) : message.content,
|
|
83
|
+
}));
|
|
84
|
+
return {
|
|
85
|
+
...payload,
|
|
86
|
+
messages: [
|
|
87
|
+
{ role: "system", content: providerContext.system },
|
|
88
|
+
...contextMessages,
|
|
89
|
+
...payload.messages.filter((message) => message?.role !== "system" && message?.role !== "user"),
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function replaceResponsesPayload(payload, providerContext) {
|
|
95
|
+
const userMessages = (providerContext.userMessages ?? []).filter((message) => message?.content);
|
|
96
|
+
const originalUser = payload.input.findLast?.((item) => item?.role === "user")
|
|
97
|
+
?? [...payload.input].reverse().find((item) => item?.role === "user");
|
|
98
|
+
return {
|
|
99
|
+
...payload,
|
|
100
|
+
instructions: providerContext.system,
|
|
101
|
+
input: [
|
|
102
|
+
...userMessages.map((message, index) => ({
|
|
103
|
+
role: "user",
|
|
104
|
+
content: index === userMessages.length - 1
|
|
105
|
+
? responsesContentWithOriginalNonTextParts(message.content, originalUser)
|
|
106
|
+
: [{ type: "input_text", text: message.content }],
|
|
107
|
+
})),
|
|
108
|
+
...payload.input.filter((item) => item?.role !== "user"),
|
|
109
|
+
],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function responsesContentWithOriginalNonTextParts(text, originalUser) {
|
|
114
|
+
return [{ type: "input_text", text }, ...responsesNonTextContentParts(originalUser?.content)];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function responsesNonTextContentParts(content) {
|
|
118
|
+
if (!Array.isArray(content)) return [];
|
|
119
|
+
return content.filter((part) => {
|
|
120
|
+
if (!part || typeof part !== "object") return false;
|
|
121
|
+
if (part.type === "input_text" || part.type === "text" || typeof part.text === "string") return false;
|
|
122
|
+
return true;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function contentWithOriginalNonTextParts(text, originalUser) {
|
|
127
|
+
const extraParts = nonTextContentParts(originalUser?.content);
|
|
128
|
+
return extraParts.length ? [{ type: "text", text }, ...extraParts] : text;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function nonTextContentParts(content) {
|
|
132
|
+
if (!Array.isArray(content)) return [];
|
|
133
|
+
return content.filter((part) => {
|
|
134
|
+
if (!part || typeof part !== "object") return false;
|
|
135
|
+
if (part.type === "text" || typeof part.text === "string") return false;
|
|
136
|
+
return true;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { Type } from "typebox";
|
|
5
|
+
import { toolText } from "./tool-result.mjs";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_LIMIT = 30;
|
|
8
|
+
const DEFAULT_DIRECTORY_LIMIT = 200;
|
|
9
|
+
const MAX_LIMIT = 2000;
|
|
10
|
+
|
|
11
|
+
export function createReadFileTool({ engine }) {
|
|
12
|
+
return defineTool({
|
|
13
|
+
name: "read",
|
|
14
|
+
label: "Read File",
|
|
15
|
+
description: "Read a file slice with 1-based line numbers. Use offset and limit to read specific line ranges.",
|
|
16
|
+
parameters: Type.Object({
|
|
17
|
+
path: Type.String({ description: "Absolute or relative path to read" }),
|
|
18
|
+
offset: Type.Optional(Type.Number({ description: "1-based line number to start reading from; default 1" })),
|
|
19
|
+
limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read; default 30, max 2000" })),
|
|
20
|
+
}),
|
|
21
|
+
execute: async (_toolCallId, params) => readFileSlice({ engine, ...params }),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function readFileSlice({ engine, path, offset = 1, limit = DEFAULT_LIMIT }) {
|
|
26
|
+
const absPath = engine.resolvePath(path);
|
|
27
|
+
let stat;
|
|
28
|
+
try {
|
|
29
|
+
stat = statSync(absPath);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
return toolText(`Error reading ${absPath}: ${err.message}`, { error: true, path: absPath });
|
|
32
|
+
}
|
|
33
|
+
if (stat.isDirectory()) return readDirectoryListing({ path: absPath, offset, limit });
|
|
34
|
+
|
|
35
|
+
let content;
|
|
36
|
+
try {
|
|
37
|
+
content = readFileSync(absPath, "utf8");
|
|
38
|
+
} catch (err) {
|
|
39
|
+
if (err?.code === "EISDIR") {
|
|
40
|
+
return toolText(`Error reading ${absPath}: this is a directory. Use ls(path) or find(pattern, path) to inspect it.`, { error: true, path: absPath, isDirectory: true });
|
|
41
|
+
}
|
|
42
|
+
return toolText(`Error reading ${absPath}: ${err.message}`, { error: true, path: absPath });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const lines = content.split("\n");
|
|
46
|
+
const start = clampLine(offset, lines.length);
|
|
47
|
+
const count = clampLimit(limit);
|
|
48
|
+
const selected = lines.slice(start - 1, start - 1 + count);
|
|
49
|
+
const end = start + selected.length - 1;
|
|
50
|
+
const body = selected.map((line, index) => `${start + index} | ${line}`).join("\n");
|
|
51
|
+
const header = `--- ${absPath} (lines ${start}-${end} of ${lines.length}) ---`;
|
|
52
|
+
const remaining = lines.length - end;
|
|
53
|
+
const footer = remaining > 0 ? `\n\n[${remaining} more lines in file. Use offset=${end + 1} to continue.]` : "";
|
|
54
|
+
return toolText(`${header}\n${body || "(empty)"}${footer}`, {
|
|
55
|
+
path: absPath,
|
|
56
|
+
offset: start,
|
|
57
|
+
limit: count,
|
|
58
|
+
totalLines: lines.length,
|
|
59
|
+
endLine: end,
|
|
60
|
+
truncated: remaining > 0,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readDirectoryListing({ path, offset = 1, limit }) {
|
|
65
|
+
let entries;
|
|
66
|
+
try {
|
|
67
|
+
entries = readdirSync(path, { withFileTypes: true })
|
|
68
|
+
.map((entry) => ({
|
|
69
|
+
name: entry.name,
|
|
70
|
+
label: entry.isDirectory() ? `${entry.name}/` : entry.name,
|
|
71
|
+
isDirectory: entry.isDirectory(),
|
|
72
|
+
}))
|
|
73
|
+
.sort((a, b) => Number(b.isDirectory) - Number(a.isDirectory) || a.name.localeCompare(b.name));
|
|
74
|
+
} catch (err) {
|
|
75
|
+
return toolText(`Error reading ${path}: ${err.message}`, { error: true, path });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const start = entries.length === 0 ? 0 : clampLine(offset, entries.length);
|
|
79
|
+
const count = clampLimit(limit ?? DEFAULT_DIRECTORY_LIMIT);
|
|
80
|
+
const selected = start === 0 ? [] : entries.slice(start - 1, start - 1 + count);
|
|
81
|
+
const end = start + selected.length - 1;
|
|
82
|
+
const remaining = start === 0 ? 0 : entries.length - end;
|
|
83
|
+
const range = entries.length === 0 ? "0 entries" : `entries ${start}-${end} of ${entries.length}`;
|
|
84
|
+
const header = `--- ${path} (directory, ${range}) ---`;
|
|
85
|
+
const footer = remaining > 0 ? `\n\n[${remaining} more entries in directory. Use offset=${end + 1} to continue, or find(pattern, path) to search recursively.]` : "";
|
|
86
|
+
return toolText(`${header}\n${selected.map((entry) => entry.label).join("\n") || "(empty directory)"}${footer}`, {
|
|
87
|
+
path,
|
|
88
|
+
isDirectory: true,
|
|
89
|
+
entryCount: entries.length,
|
|
90
|
+
offset: start,
|
|
91
|
+
limit: count,
|
|
92
|
+
endEntry: end,
|
|
93
|
+
truncated: remaining > 0,
|
|
94
|
+
entries: selected.map((entry) => ({
|
|
95
|
+
name: entry.name,
|
|
96
|
+
path: resolve(path, entry.name),
|
|
97
|
+
isDirectory: entry.isDirectory,
|
|
98
|
+
})),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function clampLine(value, lineCount) {
|
|
103
|
+
const parsed = Math.trunc(Number(value));
|
|
104
|
+
if (!Number.isFinite(parsed) || parsed < 1) return 1;
|
|
105
|
+
return Math.min(parsed, Math.max(1, lineCount));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function clampLimit(value) {
|
|
109
|
+
const parsed = Math.trunc(Number(value));
|
|
110
|
+
if (!Number.isFinite(parsed) || parsed < 1) return DEFAULT_LIMIT;
|
|
111
|
+
return Math.min(parsed, MAX_LIMIT);
|
|
112
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const FAST_PROVIDERS = new Set(["openai", "openai-codex"]);
|
|
2
|
+
const FAST_ID_SUFFIX = "__fast";
|
|
3
|
+
|
|
4
|
+
export function isFastProvider(provider) {
|
|
5
|
+
return FAST_PROVIDERS.has(provider);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function createFastModelEntry(baseModel) {
|
|
9
|
+
return {
|
|
10
|
+
model: {
|
|
11
|
+
...baseModel,
|
|
12
|
+
id: baseModel.id + FAST_ID_SUFFIX,
|
|
13
|
+
name: baseModel.name + " Fast",
|
|
14
|
+
__isFast: true,
|
|
15
|
+
__baseId: baseModel.id,
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function appendFastVariants(scopedModels) {
|
|
21
|
+
const result = [];
|
|
22
|
+
for (const entry of scopedModels) {
|
|
23
|
+
result.push(entry);
|
|
24
|
+
if (isFastProvider(entry.model.provider)) {
|
|
25
|
+
result.push(createFastModelEntry(entry.model));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function fromFastEntryModel(model) {
|
|
32
|
+
if (model.__isFast) {
|
|
33
|
+
return { baseId: model.__baseId, isFast: true };
|
|
34
|
+
}
|
|
35
|
+
return { baseId: model.id, isFast: false };
|
|
36
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export async function runRunnerCleanup(cleanups) {
|
|
2
|
+
const errors = [];
|
|
3
|
+
for (const cleanup of cleanups) {
|
|
4
|
+
try {
|
|
5
|
+
await cleanup();
|
|
6
|
+
} catch (err) {
|
|
7
|
+
errors.push(err);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
if (errors.length === 1) throw errors[0];
|
|
11
|
+
if (errors.length > 1) throw new AggregateError(errors, "Runner cleanup failed");
|
|
12
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
export function createDefaultSessionManager(cwd) {
|
|
4
|
+
return SessionManager.inMemory(cwd);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function resolveRunnerSessionManager(cwd, sessionManager = null) {
|
|
8
|
+
return sessionManager ?? createDefaultSessionManager(cwd);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function resolveInitialModel({ modelRegistry, provider, modelId }) {
|
|
12
|
+
const available = modelRegistry.getAvailable?.() ?? [];
|
|
13
|
+
if (provider && modelId) return available.find((model) => model.provider === provider && model.id === modelId) ?? null;
|
|
14
|
+
return available[0] ?? null;
|
|
15
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export function getRunnerSessionStats(activeSession, runtimeHost) {
|
|
2
|
+
const stats = activeSession.getSessionStats();
|
|
3
|
+
const manager = activeSession.sessionManager;
|
|
4
|
+
return {
|
|
5
|
+
...stats,
|
|
6
|
+
runtimeHost: Boolean(runtimeHost),
|
|
7
|
+
piSessionSwitching: Boolean(runtimeHost),
|
|
8
|
+
persisted: manager?.isPersisted?.() ?? Boolean(activeSession.sessionFile),
|
|
9
|
+
sessionFile: manager?.getSessionFile?.() ?? activeSession.sessionFile,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function syncEngineSessionState(engine, session) {
|
|
14
|
+
bindToolDefs(engine, session);
|
|
15
|
+
engine.setRuntimeState({
|
|
16
|
+
modelId: session.model?.id,
|
|
17
|
+
provider: session.model?.provider,
|
|
18
|
+
thinkingLevel: session.thinkingLevel,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function bindToolDefs(engine, session) {
|
|
23
|
+
engine.setToolDefs(session.getActiveToolNames().map((name) => {
|
|
24
|
+
const tool = session.getToolDefinition(name);
|
|
25
|
+
return {
|
|
26
|
+
name,
|
|
27
|
+
description: tool?.description ?? "",
|
|
28
|
+
parameters: tool?.parameters ? describeParams(tool.parameters) : null,
|
|
29
|
+
};
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function describeParams(schema) {
|
|
34
|
+
if (!schema || !schema.properties) return {};
|
|
35
|
+
const out = {};
|
|
36
|
+
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
37
|
+
out[key] = prop.description ?? key;
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|