@hexdecimal16/nexo 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +75 -2
  3. package/cli/src/bin.js +12 -0
  4. package/cli/src/common.js +77 -0
  5. package/cli/src/doctor.js +27 -0
  6. package/cli/src/eval-cases.js +65 -0
  7. package/cli/src/eval.js +67 -0
  8. package/cli/src/init.js +186 -0
  9. package/cli/src/interactive.js +171 -0
  10. package/cli/src/learn.js +178 -0
  11. package/cli/src/main.js +261 -0
  12. package/cli/src/optimize.js +289 -0
  13. package/cli/src/prompter.js +47 -0
  14. package/cli/src/review.js +120 -0
  15. package/cli/src/runtime.js +2 -0
  16. package/cli/src/sessions.js +34 -0
  17. package/cli/src/settings.js +169 -0
  18. package/cli/src/ui.js +112 -0
  19. package/core/src/approval/classifier.js +152 -0
  20. package/core/src/config/load.js +283 -0
  21. package/core/src/config/schema.js +186 -0
  22. package/core/src/cost/admission.js +90 -0
  23. package/core/src/cost/budget.js +67 -0
  24. package/core/src/cost/pricing.js +53 -0
  25. package/core/src/engine/charged-completion.js +79 -0
  26. package/core/src/engine/errors.js +77 -0
  27. package/core/src/engine/mcp.js +11 -0
  28. package/core/src/engine/messages.js +86 -0
  29. package/core/src/engine/prompts.js +32 -0
  30. package/core/src/engine/provider-gate.js +33 -0
  31. package/core/src/engine/recorder.js +61 -0
  32. package/core/src/engine/run.js +1115 -0
  33. package/core/src/engine/semaphore.js +45 -0
  34. package/core/src/engine/spawn-tool.js +119 -0
  35. package/core/src/engine/task-graph.js +153 -0
  36. package/core/src/index.js +32 -0
  37. package/core/src/learn/caller.js +171 -0
  38. package/core/src/learn/context.js +112 -0
  39. package/core/src/learn/embedder.js +216 -0
  40. package/core/src/learn/job.js +196 -0
  41. package/core/src/learn/wiki.js +116 -0
  42. package/core/src/learn/worker.js +141 -0
  43. package/core/src/optimize/adapter.js +250 -0
  44. package/core/src/optimize/climb.js +338 -0
  45. package/core/src/optimize/mine.js +95 -0
  46. package/core/src/optimize/optimize.js +377 -0
  47. package/core/src/optimize/optimizer-run.js +67 -0
  48. package/core/src/optimize/reflect.js +100 -0
  49. package/core/src/optimize/scratchpad-wiki.js +69 -0
  50. package/core/src/providers/claude-p.js +363 -0
  51. package/core/src/providers/kiro-p.js +408 -0
  52. package/core/src/providers/models.js +10 -0
  53. package/core/src/scoring/calibration.js +31 -0
  54. package/core/src/scoring/continuation.js +24 -0
  55. package/core/src/scoring/runner.js +322 -0
  56. package/core/src/scoring/sources.js +88 -0
  57. package/core/src/session/lock.js +88 -0
  58. package/core/src/session/session.js +647 -0
  59. package/core/src/session/shell.js +26 -0
  60. package/core/src/session/transcript.js +86 -0
  61. package/core/src/settings/config-edit.js +472 -0
  62. package/core/src/settings/credentials.js +120 -0
  63. package/core/src/settings/doctor.js +103 -0
  64. package/core/src/settings/settings.js +265 -0
  65. package/mcp/src/hub.js +184 -0
  66. package/mcp/src/index.js +1 -0
  67. package/memory/src/curate.js +121 -0
  68. package/memory/src/index.js +4 -0
  69. package/memory/src/prompts.js +143 -0
  70. package/memory/src/retrieval.js +91 -0
  71. package/memory/src/similarity.js +47 -0
  72. package/optimize/src/engine.js +206 -0
  73. package/optimize/src/index.js +8 -0
  74. package/optimize/src/merge.js +73 -0
  75. package/optimize/src/novelty.js +37 -0
  76. package/optimize/src/pareto.js +83 -0
  77. package/optimize/src/proposer.js +148 -0
  78. package/optimize/src/report.js +107 -0
  79. package/optimize/src/rng.js +34 -0
  80. package/optimize/src/target.js +34 -0
  81. package/package.json +47 -4
  82. package/router/src/effort.js +5 -0
  83. package/router/src/escalation.js +171 -0
  84. package/router/src/index.js +4 -0
  85. package/router/src/registry.js +21 -0
  86. package/router/src/resolve.js +117 -0
  87. package/scorers/src/deterministic.js +194 -0
  88. package/scorers/src/family.js +48 -0
  89. package/scorers/src/index.js +6 -0
  90. package/scorers/src/judge.js +284 -0
  91. package/scorers/src/regex-worker.js +3 -0
  92. package/scorers/src/spec.js +147 -0
  93. package/scorers/src/trajectory.js +22 -0
  94. package/scorers/src/types.js +1 -0
  95. package/sdk/src/index.js +3 -0
  96. package/sdk/src/nexo.js +94 -0
  97. package/sdk/src/runtime.js +39 -0
  98. package/skills/bundled/browser/SKILL.md +57 -0
  99. package/skills/bundled/wiki/SKILL.md +73 -0
  100. package/skills/src/frontmatter.js +25 -0
  101. package/skills/src/index.js +3 -0
  102. package/skills/src/load-skill-tool.js +41 -0
  103. package/skills/src/loader.js +95 -0
  104. package/store/src/artifacts.js +124 -0
  105. package/store/src/budget-ledger.js +18 -0
  106. package/store/src/cost-report.js +46 -0
  107. package/store/src/cursor.js +35 -0
  108. package/store/src/db.js +83 -0
  109. package/store/src/errors.js +9 -0
  110. package/store/src/eval-cases.js +255 -0
  111. package/store/src/feedback.js +154 -0
  112. package/store/src/goldens.js +61 -0
  113. package/store/src/ids.js +6 -0
  114. package/store/src/index.js +25 -0
  115. package/store/src/judge-calibration.js +182 -0
  116. package/store/src/learn-jobs.js +145 -0
  117. package/store/src/memories.js +261 -0
  118. package/store/src/migrations/001_init.sql +81 -0
  119. package/store/src/migrations/002_feedback.sql +9 -0
  120. package/store/src/migrations/003_sessions.sql +19 -0
  121. package/store/src/migrations/004_scoring.sql +22 -0
  122. package/store/src/migrations/005_judge_calibration.sql +27 -0
  123. package/store/src/migrations/006_learning.sql +77 -0
  124. package/store/src/migrations/007_optimize.sql +55 -0
  125. package/store/src/migrations/008_mined_cases_and_climb.sql +46 -0
  126. package/store/src/mine.js +51 -0
  127. package/store/src/optim.js +291 -0
  128. package/store/src/paths.js +22 -0
  129. package/store/src/playbooks.js +199 -0
  130. package/store/src/reindex.js +143 -0
  131. package/store/src/run-dir.js +151 -0
  132. package/store/src/runs.js +310 -0
  133. package/store/src/scores.js +92 -0
  134. package/store/src/sessions.js +304 -0
  135. package/store/src/span-tree.js +98 -0
  136. package/store/src/spans.js +84 -0
  137. package/store/src/sql.js +13 -0
  138. package/store/src/workspace-copy.js +80 -0
  139. package/telemetry/src/errors.js +32 -0
  140. package/telemetry/src/index.js +3 -0
  141. package/telemetry/src/logger.js +39 -0
  142. package/telemetry/src/redact.js +106 -0
  143. package/tools/src/builtin.js +269 -0
  144. package/tools/src/change-tracker.js +57 -0
  145. package/tools/src/confine.js +101 -0
  146. package/tools/src/index.js +7 -0
  147. package/tools/src/leases.js +57 -0
  148. package/tools/src/policy.js +162 -0
  149. package/tools/src/read-only.js +338 -0
  150. package/tools/src/session-rules.js +140 -0
  151. package/tui/src/app.js +948 -0
  152. package/tui/src/approvals.js +96 -0
  153. package/tui/src/commands.js +38 -0
  154. package/tui/src/components.js +248 -0
  155. package/tui/src/index.js +5 -0
  156. package/tui/src/picker.js +78 -0
  157. package/tui/src/session-picker.js +100 -0
  158. package/tui/src/settings-screen.js +346 -0
  159. package/tui/src/text.js +70 -0
  160. package/tui/src/theme.js +44 -0
  161. package/web/public/cost.html +25 -0
  162. package/web/public/fonts/GeistMono-400.woff2 +0 -0
  163. package/web/public/fonts/GeistMono-600.woff2 +0 -0
  164. package/web/public/fonts/InstrumentSans-400.woff2 +0 -0
  165. package/web/public/fonts/InstrumentSans-600.woff2 +0 -0
  166. package/web/public/index.html +39 -0
  167. package/web/public/judge.html +21 -0
  168. package/web/public/learning.html +46 -0
  169. package/web/public/lib/api-types.ts +616 -0
  170. package/web/public/lib/common-view.ts +47 -0
  171. package/web/public/lib/cost-view.ts +35 -0
  172. package/web/public/lib/files-view.ts +90 -0
  173. package/web/public/lib/format.ts +35 -0
  174. package/web/public/lib/html.ts +51 -0
  175. package/web/public/lib/judge-view.ts +62 -0
  176. package/web/public/lib/learning-view.ts +102 -0
  177. package/web/public/lib/optim-view.ts +148 -0
  178. package/web/public/lib/pager.ts +56 -0
  179. package/web/public/lib/poller.ts +79 -0
  180. package/web/public/lib/run-view.ts +61 -0
  181. package/web/public/lib/runs-view.ts +87 -0
  182. package/web/public/lib/score-view.ts +94 -0
  183. package/web/public/lib/sessions-view.ts +28 -0
  184. package/web/public/lib/span-view.ts +90 -0
  185. package/web/public/lib/theme.ts +60 -0
  186. package/web/public/lib/timeline.ts +97 -0
  187. package/web/public/lib/wikis-view.ts +257 -0
  188. package/web/public/optim.html +30 -0
  189. package/web/public/pages/api.ts +60 -0
  190. package/web/public/pages/cost.ts +36 -0
  191. package/web/public/pages/judge.ts +15 -0
  192. package/web/public/pages/learning.ts +92 -0
  193. package/web/public/pages/optim.ts +68 -0
  194. package/web/public/pages/paging.ts +18 -0
  195. package/web/public/pages/run.ts +221 -0
  196. package/web/public/pages/runs.ts +91 -0
  197. package/web/public/pages/sessions.ts +25 -0
  198. package/web/public/pages/wikis.ts +103 -0
  199. package/web/public/run.html +36 -0
  200. package/web/public/sessions.html +28 -0
  201. package/web/public/style.css +288 -0
  202. package/web/public/wikis.html +25 -0
  203. package/web/src/api.js +682 -0
  204. package/web/src/http-errors.js +60 -0
  205. package/web/src/index.js +5 -0
  206. package/web/src/server.js +292 -0
  207. package/web/src/static.js +86 -0
  208. package/web/src/strip.js +22 -0
@@ -0,0 +1,69 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { emptyScratchpad, SCRATCHPAD_ENTRIES, scratchpadEntry } from "../../../optimize/src/index.js";
4
+ import { resolveConfined } from "../../../tools/src/index.js";
5
+ /** The wiki that holds what optimizations learned: one page per target, readable and editable in the Wikis UI. */
6
+ export const SCRATCHPAD_WIKI = "optimization";
7
+ /** The page of `targetKey` inside the wiki, e.g. `analyses/optim-skill-web-research.md`. */
8
+ export function scratchpadPagePath(targetKey) {
9
+ const slug = targetKey.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "target";
10
+ return `analyses/optim-${slug}.md`;
11
+ }
12
+ /** The bullet lines under "Validated patterns" and "Anti-patterns" of a page, newest last, each clipped, at most SCRATCHPAD_ENTRIES per list. */
13
+ export function parseScratchpad(markdown) {
14
+ const pad = emptyScratchpad();
15
+ let list = null;
16
+ for (const line of markdown.split(/\r?\n/)) {
17
+ if (/^##\s+validated patterns/i.test(line))
18
+ list = pad.patterns;
19
+ else if (/^##\s+anti-patterns/i.test(line))
20
+ list = pad.antiPatterns;
21
+ else if (/^#/.test(line))
22
+ list = null;
23
+ else if (list && /^-\s+\S/.test(line))
24
+ list.push(scratchpadEntry(line.replace(/^-\s+/, "")));
25
+ }
26
+ return { patterns: pad.patterns.slice(-SCRATCHPAD_ENTRIES), antiPatterns: pad.antiPatterns.slice(-SCRATCHPAD_ENTRIES) };
27
+ }
28
+ /** The saved scratchpad of a target, or undefined when there is no page, it has no entries or it cannot be read. */
29
+ export function readScratchpad(wikisDir, targetKey) {
30
+ try {
31
+ const file = resolveConfined(resolveConfined(wikisDir, SCRATCHPAD_WIKI), scratchpadPagePath(targetKey));
32
+ if (!existsSync(file))
33
+ return undefined;
34
+ const pad = parseScratchpad(readFileSync(file, "utf8"));
35
+ return pad.patterns.length + pad.antiPatterns.length > 0 ? pad : undefined;
36
+ }
37
+ catch {
38
+ return undefined;
39
+ }
40
+ }
41
+ /** Writes the target's scratchpad page (creating the wiki on first use) and logs it; returns the page file. */
42
+ export function writeScratchpad(wikisDir, targetKey, pad, info) {
43
+ const wikiDir = resolveConfined(wikisDir, SCRATCHPAD_WIKI);
44
+ const { today } = info;
45
+ if (!existsSync(wikiDir)) {
46
+ for (const d of ["concepts", "entities", "sources", "analyses", "raw"])
47
+ mkdirSync(join(wikiDir, d), { recursive: true });
48
+ writeFileSync(join(wikiDir, "AGENTS.md"), "# optimization wiki\n\nWhat nexo optimizations learned about each target. Pages under analyses/ are read back into the next optimization of the same target.\n");
49
+ writeFileSync(join(wikiDir, "index.md"), "# optimization index\n\n## Concepts\n\n## Entities\n\n## Sources\n\n## Analyses\n");
50
+ writeFileSync(join(wikiDir, "log.md"), `# Log\n\n## [${today}] create | Initialized wiki\n`);
51
+ writeFileSync(join(wikiDir, "overview.md"), `---\nsummary: Overview of optimization\nupdated: ${today}\nsources: []\n---\n\n# optimization\n`);
52
+ }
53
+ const page = scratchpadPagePath(targetKey);
54
+ const file = resolveConfined(wikiDir, page);
55
+ mkdirSync(dirname(file), { recursive: true });
56
+ const bullets = (items) => (items.length > 0 ? items.map((i) => `- ${info.redact(i)}`).join("\n") : "(none yet)");
57
+ const body = [
58
+ `---\nsummary: Lessons from optimizing ${targetKey}, read back into its next optimization\nupdated: ${today}\nsources: [optim:${info.optimRunId}]\n---`,
59
+ `# Optimization scratchpad: ${targetKey}`,
60
+ `Written by optimization ${info.optimRunId} (base v${info.baseVersion}, ${today}). Edit or delete lines freely: the next optimization of this target reads them as hints, at most ${SCRATCHPAD_ENTRIES} per list.`,
61
+ `## Validated patterns\n${bullets(pad.patterns)}`,
62
+ `## Anti-patterns\n${bullets(pad.antiPatterns)}`,
63
+ ].join("\n\n");
64
+ writeFileSync(file, `${body}\n`);
65
+ const log = join(wikiDir, "log.md");
66
+ if (existsSync(log))
67
+ writeFileSync(log, `${readFileSync(log, "utf8")}\n## [${today}] ingest | Optimization ${info.optimRunId} updated ${page}\n`);
68
+ return file;
69
+ }
@@ -0,0 +1,363 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createInterface } from "node:readline";
6
+ import { calculateCost, createAssistantMessageEventStream, createProvider, getCurrentSystemPrompt, getCurrentTools, } from "@earendil-works/pi-ai";
7
+ import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
8
+ /** Provider id: models are referenced as `claude-p/<model>`, e.g. `claude-p/opus` or `claude-p/claude-sonnet-5-5`. */
9
+ export const CLAUDE_P_PROVIDER = "claude-p";
10
+ const CLAUDE_P_API = "claude-p";
11
+ /** Environment variable naming the Claude Code executable; `claude` on the PATH otherwise. */
12
+ export const CLAUDE_P_COMMAND_ENV = "NEXO_CLAUDE_P_COMMAND";
13
+ /** Aliases the Claude Code CLI resolves to the newest model of the family. */
14
+ const ALIASES = ["opus", "sonnet", "haiku", "fable"];
15
+ /** `claude --effort` values; pi's `minimal` maps to `low`. */
16
+ const EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
17
+ function spawnRunner(command) {
18
+ return ({ args, stdin, cwd, signal }) => {
19
+ const child = spawn(command, args, { cwd, stdio: ["pipe", "pipe", "pipe"], ...(signal ? { signal } : {}) });
20
+ let stderr = "";
21
+ child.stderr.setEncoding("utf8");
22
+ child.stderr.on("data", (chunk) => {
23
+ if (stderr.length < 16_384)
24
+ stderr += chunk;
25
+ });
26
+ const exit = new Promise((resolve) => {
27
+ child.on("error", (error) => resolve({ code: null, stderr: stderr || error.message }));
28
+ child.on("close", (code) => resolve({ code, stderr }));
29
+ });
30
+ child.stdin.on("error", () => { });
31
+ child.stdin.end(stdin);
32
+ return { lines: createInterface({ input: child.stdout, crlfDelay: Infinity }), exit };
33
+ };
34
+ }
35
+ /** The Claude models from pi-ai's Anthropic catalog, re-homed under `claude-p`, plus the CLI's family aliases. */
36
+ function claudePModels() {
37
+ const anthropic = getBuiltinModels("anthropic").filter((m) => !/-\d{8}$/.test(m.id));
38
+ const rehome = (m, id, name) => ({
39
+ ...m,
40
+ id,
41
+ name,
42
+ api: CLAUDE_P_API,
43
+ provider: CLAUDE_P_PROVIDER,
44
+ baseUrl: "",
45
+ input: ["text"],
46
+ });
47
+ const out = anthropic.map((m) => rehome(m, m.id, `${m.name} (claude -p)`));
48
+ for (const alias of ALIASES) {
49
+ const newest = anthropic
50
+ .filter((m) => m.id.startsWith(`claude-${alias}-`))
51
+ .sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }))
52
+ .at(-1);
53
+ if (newest)
54
+ out.push(rehome(newest, alias, `Claude ${alias} (claude -p, newest)`));
55
+ }
56
+ return out;
57
+ }
58
+ function contentText(content) {
59
+ if (typeof content === "string")
60
+ return content;
61
+ return content.map((b) => (b.type === "text" ? (b.text ?? "") : "[image omitted]")).join("\n");
62
+ }
63
+ function attr(value) {
64
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
65
+ }
66
+ /** Renders the conversation for stdin. A lone user message goes as-is; anything longer becomes a tagged transcript. */
67
+ export function renderTranscript(messages) {
68
+ const turns = messages.filter((m) => m.role !== "system");
69
+ const only = turns[0];
70
+ if (turns.length === 1 && only?.role === "user")
71
+ return contentText(only.content);
72
+ const parts = [];
73
+ for (const m of turns) {
74
+ if (m.role === "user")
75
+ parts.push(`<user>\n${contentText(m.content)}\n</user>`);
76
+ else if (m.role === "assistant") {
77
+ const body = m.content
78
+ .map((b) => {
79
+ if (b.type === "text")
80
+ return b.text;
81
+ if (b.type === "toolCall")
82
+ return `<tool_call id="${attr(b.id)}" name="${attr(b.name)}">${JSON.stringify(b.arguments)}</tool_call>`;
83
+ return "";
84
+ })
85
+ .filter((s) => s.length > 0)
86
+ .join("\n");
87
+ parts.push(`<assistant>\n${body}\n</assistant>`);
88
+ }
89
+ else if (m.role === "toolResult") {
90
+ parts.push(`<tool_result id="${attr(m.toolCallId)}" name="${attr(m.toolName)}"${m.isError ? ' is_error="true"' : ""}>\n${contentText(m.content)}\n</tool_result>`);
91
+ }
92
+ }
93
+ return `${parts.join("\n\n")}\n\nWrite the assistant's next turn, continuing from the last entry above.`;
94
+ }
95
+ function plainSchema(tool) {
96
+ return JSON.parse(JSON.stringify(tool.parameters));
97
+ }
98
+ /**
99
+ * System-prompt section describing the tools and the reply format the JSON schema enforces. The definitions are
100
+ * written as data, not tool declarations: Claude otherwise invokes them natively and burns a turn on the failure.
101
+ */
102
+ export function toolsSection(tools) {
103
+ const defs = tools.map((t) => JSON.stringify({ name: t.name, description: t.description, parameters: plainSchema(t) })).join("\n");
104
+ return [
105
+ "# Actions",
106
+ "",
107
+ "Your only tool is StructuredOutput, and every reply must be one StructuredOutput call with `text` (what you say to the user, may be empty) and `tool_calls` (actions for the caller to run now, each `{ name, arguments }` with arguments matching the action's parameters).",
108
+ "The actions below are not tools you can invoke: never call them directly, only list them in `tool_calls`. The caller runs them and sends the results back in the next turn as <tool_result> entries. When you are finished, leave `tool_calls` empty and put the final answer in `text`.",
109
+ "",
110
+ "Available actions, one JSON definition per line:",
111
+ defs,
112
+ ].join("\n");
113
+ }
114
+ /** Reply schema for `--json-schema`: each tool call is constrained to one tool's name and parameters. */
115
+ export function replySchema(tools) {
116
+ return {
117
+ type: "object",
118
+ properties: {
119
+ text: { type: "string" },
120
+ tool_calls: {
121
+ type: "array",
122
+ items: {
123
+ anyOf: tools.map((t) => ({
124
+ type: "object",
125
+ properties: { name: { const: t.name }, arguments: plainSchema(t) },
126
+ required: ["name", "arguments"],
127
+ })),
128
+ },
129
+ },
130
+ },
131
+ required: ["text", "tool_calls"],
132
+ };
133
+ }
134
+ function effortFlag(reasoning) {
135
+ if (!reasoning)
136
+ return undefined;
137
+ const effort = reasoning === "minimal" ? "low" : reasoning;
138
+ return EFFORTS.has(effort) ? effort : undefined;
139
+ }
140
+ function toUsage(model, result) {
141
+ const u = result?.usage ?? {};
142
+ const usage = {
143
+ input: u.input_tokens ?? 0,
144
+ output: u.output_tokens ?? 0,
145
+ cacheRead: u.cache_read_input_tokens ?? 0,
146
+ cacheWrite: u.cache_creation_input_tokens ?? 0,
147
+ totalTokens: 0,
148
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
149
+ };
150
+ usage.totalTokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
151
+ usage.cost = calculateCost(model, usage);
152
+ // The CLI's own figure (what the request costs at list price) wins over the catalog estimate.
153
+ if (typeof result?.total_cost_usd === "number" && result.total_cost_usd > 0)
154
+ usage.cost.total = result.total_cost_usd;
155
+ return usage;
156
+ }
157
+ function resultError(result, exit) {
158
+ if (result && !result.is_error && result.subtype === "success")
159
+ return undefined;
160
+ const status = result?.api_error_status ? ` (${result.api_error_status})` : "";
161
+ const detail = (result?.result && result.result.trim()) ||
162
+ (Array.isArray(result?.errors) && result.errors.length > 0 ? JSON.stringify(result.errors) : "") ||
163
+ exit.stderr.trim() ||
164
+ (result ? (result.subtype ?? "error") : `exited with code ${exit.code ?? "null"} without a result`);
165
+ return `claude -p failed${status}: ${detail}`;
166
+ }
167
+ let callSeq = 0;
168
+ function toolCallId() {
169
+ callSeq = (callSeq + 1) % 1_000_000;
170
+ return `claude_p_${Date.now().toString(36)}_${callSeq}`;
171
+ }
172
+ function parseStructured(value) {
173
+ const obj = (typeof value === "object" && value !== null ? value : {});
174
+ const text = typeof obj.text === "string" ? obj.text : "";
175
+ const calls = [];
176
+ if (Array.isArray(obj.tool_calls)) {
177
+ for (const c of obj.tool_calls) {
178
+ if (typeof c?.name !== "string")
179
+ continue;
180
+ const args = typeof c.arguments === "object" && c.arguments !== null && !Array.isArray(c.arguments) ? c.arguments : {};
181
+ calls.push({ type: "toolCall", id: toolCallId(), name: c.name, arguments: args });
182
+ }
183
+ }
184
+ return { text, calls };
185
+ }
186
+ function streamClaudeP(run, model, context, options) {
187
+ const stream = createAssistantMessageEventStream();
188
+ const partial = {
189
+ role: "assistant",
190
+ content: [],
191
+ api: model.api,
192
+ provider: model.provider,
193
+ model: model.id,
194
+ usage: toUsage(model, undefined),
195
+ stopReason: "pending",
196
+ timestamp: Date.now(),
197
+ };
198
+ const snapshot = () => ({ ...partial, content: [...partial.content] });
199
+ const fail = (reason, message, usage) => {
200
+ const error = { ...snapshot(), stopReason: reason, errorMessage: message, ...(usage ? { usage } : {}) };
201
+ stream.push({ type: "error", reason, error });
202
+ stream.end(error);
203
+ };
204
+ queueMicrotask(async () => {
205
+ const signal = options?.signal;
206
+ if (signal?.aborted)
207
+ return fail("aborted", "Request was aborted");
208
+ const tools = getCurrentTools(context.messages);
209
+ const useTools = tools.length > 0 && options?.toolChoice !== "none";
210
+ const systemPrompt = [getCurrentSystemPrompt(context.messages), useTools ? toolsSection(tools) : ""].filter((s) => s.length > 0).join("\n\n");
211
+ let dir;
212
+ try {
213
+ dir = await mkdtemp(join(tmpdir(), "nexo-claude-p-"));
214
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model.id, "--tools", "", "--no-session-persistence", "--setting-sources", "", "--strict-mcp-config", "--disable-slash-commands"];
215
+ if (!useTools)
216
+ args.push("--include-partial-messages");
217
+ if (systemPrompt) {
218
+ const file = join(dir, "system-prompt.md");
219
+ await writeFile(file, systemPrompt, "utf8");
220
+ args.push("--system-prompt-file", file);
221
+ }
222
+ const effort = effortFlag(options?.reasoning);
223
+ if (effort)
224
+ args.push("--effort", effort);
225
+ if (useTools)
226
+ args.push("--json-schema", JSON.stringify(replySchema(tools)));
227
+ const proc = run({ args, stdin: renderTranscript(context.messages), cwd: dir, ...(signal ? { signal } : {}) });
228
+ stream.push({ type: "start", partial: snapshot() });
229
+ let result;
230
+ /** Open streamed block per API content index, for the current API message. */
231
+ const open = new Map();
232
+ for await (const line of proc.lines) {
233
+ if (!line.trim())
234
+ continue;
235
+ let event;
236
+ try {
237
+ event = JSON.parse(line);
238
+ }
239
+ catch {
240
+ continue;
241
+ }
242
+ if (event.type === "result") {
243
+ result = event;
244
+ continue;
245
+ }
246
+ if (useTools || event.type !== "stream_event" || event.parent_tool_use_id || !event.event)
247
+ continue;
248
+ const e = event.event;
249
+ if (e.type === "message_start")
250
+ open.clear();
251
+ else if (e.type === "content_block_start" && e.index !== undefined) {
252
+ const kind = e.content_block?.type;
253
+ if (kind !== "text" && kind !== "thinking")
254
+ continue;
255
+ const contentIndex = partial.content.length;
256
+ partial.content.push(kind === "text" ? { type: "text", text: "" } : { type: "thinking", thinking: "" });
257
+ open.set(e.index, contentIndex);
258
+ stream.push({ type: kind === "text" ? "text_start" : "thinking_start", contentIndex, partial: snapshot() });
259
+ }
260
+ else if (e.type === "content_block_delta" && e.index !== undefined) {
261
+ const contentIndex = open.get(e.index);
262
+ const block = contentIndex === undefined ? undefined : partial.content[contentIndex];
263
+ if (contentIndex === undefined || !block)
264
+ continue;
265
+ if (block.type === "text" && e.delta?.type === "text_delta" && e.delta.text) {
266
+ block.text += e.delta.text;
267
+ stream.push({ type: "text_delta", contentIndex, delta: e.delta.text, partial: snapshot() });
268
+ }
269
+ else if (block.type === "thinking" && e.delta?.type === "thinking_delta" && e.delta.thinking) {
270
+ block.thinking += e.delta.thinking;
271
+ stream.push({ type: "thinking_delta", contentIndex, delta: e.delta.thinking, partial: snapshot() });
272
+ }
273
+ }
274
+ else if (e.type === "content_block_stop" && e.index !== undefined) {
275
+ const contentIndex = open.get(e.index);
276
+ const block = contentIndex === undefined ? undefined : partial.content[contentIndex];
277
+ if (contentIndex === undefined || !block)
278
+ continue;
279
+ open.delete(e.index);
280
+ if (block.type === "text")
281
+ stream.push({ type: "text_end", contentIndex, content: block.text, partial: snapshot() });
282
+ else if (block.type === "thinking")
283
+ stream.push({ type: "thinking_end", contentIndex, content: block.thinking, partial: snapshot() });
284
+ }
285
+ }
286
+ const exit = await proc.exit;
287
+ if (signal?.aborted)
288
+ return fail("aborted", "Request was aborted");
289
+ const usage = toUsage(model, result);
290
+ const error = resultError(result, exit);
291
+ if (error)
292
+ return fail("error", error, usage);
293
+ // Drop thinking the CLI did not display (signature only) so it is not replayed as empty blocks.
294
+ partial.content = partial.content.filter((b) => b.type !== "thinking" || b.thinking.length > 0);
295
+ let stopReason = result?.stop_reason === "max_tokens" ? "length" : "stop";
296
+ if (useTools) {
297
+ const { text, calls } = parseStructured(result?.structured_output);
298
+ if (text) {
299
+ const contentIndex = partial.content.length;
300
+ partial.content.push({ type: "text", text: "" });
301
+ stream.push({ type: "text_start", contentIndex, partial: snapshot() });
302
+ partial.content[contentIndex].text = text;
303
+ stream.push({ type: "text_delta", contentIndex, delta: text, partial: snapshot() });
304
+ stream.push({ type: "text_end", contentIndex, content: text, partial: snapshot() });
305
+ }
306
+ for (const call of calls) {
307
+ const contentIndex = partial.content.length;
308
+ partial.content.push({ ...call, arguments: {} });
309
+ stream.push({ type: "toolcall_start", contentIndex, partial: snapshot() });
310
+ partial.content[contentIndex] = call;
311
+ stream.push({ type: "toolcall_delta", contentIndex, delta: JSON.stringify(call.arguments), partial: snapshot() });
312
+ stream.push({ type: "toolcall_end", contentIndex, toolCall: call, partial: snapshot() });
313
+ }
314
+ stopReason = calls.length > 0 ? "toolUse" : "stop";
315
+ }
316
+ else if (!partial.content.some((b) => b.type === "text") && result?.result) {
317
+ const contentIndex = partial.content.length;
318
+ partial.content.push({ type: "text", text: result.result });
319
+ stream.push({ type: "text_start", contentIndex, partial: snapshot() });
320
+ stream.push({ type: "text_delta", contentIndex, delta: result.result, partial: snapshot() });
321
+ stream.push({ type: "text_end", contentIndex, content: result.result, partial: snapshot() });
322
+ }
323
+ const message = { ...snapshot(), usage, stopReason };
324
+ stream.push({ type: "done", reason: stopReason, message });
325
+ stream.end(message);
326
+ }
327
+ catch (error) {
328
+ if (signal?.aborted)
329
+ return fail("aborted", "Request was aborted");
330
+ fail("error", `claude -p failed: ${error instanceof Error ? error.message : String(error)}`);
331
+ }
332
+ finally {
333
+ if (dir)
334
+ await rm(dir, { recursive: true, force: true }).catch(() => { });
335
+ }
336
+ });
337
+ return stream;
338
+ }
339
+ /**
340
+ * Runs Claude through the local Claude Code CLI (`claude -p`), authenticated by whatever login the CLI has (a Claude
341
+ * subscription or its own API key), so no nexo key is needed. Claude's built-in tools are disabled; when the request
342
+ * carries nexo tools, the reply is constrained by `--json-schema` to `{ text, tool_calls }` and returned as real tool
343
+ * calls, so those turns arrive whole rather than streamed.
344
+ */
345
+ export function claudePProvider(options = {}) {
346
+ const run = options.run ?? spawnRunner(options.command ?? process.env[CLAUDE_P_COMMAND_ENV] ?? "claude");
347
+ const api = {
348
+ stream: (model, context, opts) => streamClaudeP(run, model, context, opts),
349
+ streamSimple: (model, context, opts) => streamClaudeP(run, model, context, opts),
350
+ };
351
+ return createProvider({
352
+ id: CLAUDE_P_PROVIDER,
353
+ name: "Claude Code (claude -p)",
354
+ auth: {
355
+ apiKey: {
356
+ name: "Claude Code CLI login",
357
+ resolve: async () => ({ auth: {}, source: "claude CLI login" }),
358
+ },
359
+ },
360
+ models: claudePModels(),
361
+ api,
362
+ });
363
+ }