@hexdecimal16/nexo 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ import { approverModel, createSettings, nexoModels } from "../../core/src/index.js";
2
+ import { createModelRegistry } from "../../router/src/index.js";
3
+ /** nex's model for `nexo ui`: the s1 role (the small, cheap model), with the same keys and settings as `nexo run`. Null when it cannot be set up. */
4
+ export function companionModel(options, paths) {
5
+ try {
6
+ const models = options.models ?? nexoModels();
7
+ const settings = createSettings({ paths, cwd: options.cwd, env: options.env, models });
8
+ // The approver (auto-classifier) tier: small and fast, and it falls back to s1 when models.approver is unset.
9
+ const small = approverModel(settings.loadConfig().config);
10
+ const model = createModelRegistry(models).get(small.provider, small.id);
11
+ return {
12
+ async complete({ system, user, signal }) {
13
+ const msg = await models.completeSimple(model, { systemPrompt: system, messages: [{ role: "user", content: user, timestamp: Date.now() }] }, { apiKey: settings.resolveApiKey(model.provider), maxTokens: 700, signal });
14
+ if (msg.stopReason === "error" || msg.stopReason === "aborted")
15
+ throw new Error(msg.errorMessage ?? "The companion model failed");
16
+ return msg.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
17
+ },
18
+ };
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
package/cli/src/ui.js CHANGED
@@ -4,6 +4,7 @@ import { ensureNexoDirs, isPidAlive, openDb, recoverCrashedOptimRuns, recoverCra
4
4
  import { createRedactor, NexoError } from "../../telemetry/src/index.js";
5
5
  import { nonInteractivePrompter } from "../../tools/src/index.js";
6
6
  import { startWebServer } from "../../web/src/index.js";
7
+ import { companionModel } from "./companion.js";
7
8
  import { openLogger } from "./runtime.js";
8
9
  /** How often `nexo ui` looks for pending learn jobs (new runs and verdicts from the UI or other processes). */
9
10
  export const UI_LEARN_POLL_MS = 5000;
@@ -85,6 +86,7 @@ export async function runUi(options) {
85
86
  learning: { enabled: config?.learning.enabled ?? false },
86
87
  optimize: { minJudgeKappa: config?.optimize.minJudgeKappa ?? 0.6 },
87
88
  wikisDir: paths.wikis,
89
+ companion: config ? companionModel(options, paths) : null,
88
90
  });
89
91
  }
90
92
  catch (error) {
@@ -418,6 +418,7 @@ export async function executeRun(env, input) {
418
418
  deps.onEvent?.({
419
419
  type: "run_start",
420
420
  runId,
421
+ ...(parent?.taskId ? { taskId: parent.taskId } : {}),
421
422
  parentRunId: parent?.runId ?? null,
422
423
  instruction: deps.redact(request.instruction),
423
424
  depth,
@@ -1101,7 +1102,7 @@ export async function executeRun(env, input) {
1101
1102
  if (!parent && !optimRunId && config.learning.enabled && status !== "aborted") {
1102
1103
  attempt("enqueueing the learn job", () => enqueueLearnJob(db, { runId, trigger: "run_end" }, now().toISOString()));
1103
1104
  }
1104
- attempt("run_end event", () => deps.onEvent?.({ type: "run_end", runId, depth, status, costUsd: totalCost }));
1105
+ attempt("run_end event", () => deps.onEvent?.({ type: "run_end", runId, depth, status, costUsd: totalCost, ...(error ? { error: { code: error.code, message: deps.redact(error.message) } } : {}) }));
1105
1106
  logger.info("run finished", { status, cost_usd: totalCost, approval_cost_usd: approvalCost });
1106
1107
  const messages = agent ? newMessages(agent.state.messages, seededCount) : [];
1107
1108
  return {
@@ -1,3 +1,4 @@
1
+ import { toErrorPayload } from "../../../telemetry/src/index.js";
1
2
  import { Type } from "typebox";
2
3
  import { EffortSchema } from "../config/schema.js";
3
4
  import { RunBudget } from "../cost/budget.js";
@@ -47,20 +48,21 @@ async function runSpawn(ctx, toolCallId, tasks, signal) {
47
48
  }
48
49
  const subSpan = recorder.start({ kind: "subagent", name: task.id, parentSpanId: spawnSpanId, queuedMs: input.queuedMs, attrs: { task, budgetUsd: input.budgetUsd } });
49
50
  const startedAt = env.now().toISOString();
50
- const result = await executeRun(env, {
51
+ const runChild = (childBudgetUsd) => executeRun(env, {
51
52
  request: {
52
53
  instruction: withDependencyOutputs(task.instruction, input.dependencyOutputs),
53
54
  skill: task.skill,
54
55
  model: task.model,
55
56
  effort: task.effort,
56
57
  },
57
- budget: new RunBudget(input.budgetUsd),
58
+ budget: new RunBudget(childBudgetUsd),
58
59
  signal,
59
60
  parent: {
60
61
  runId: ctx.runId,
61
62
  rootRunId: ctx.rootRunId,
62
63
  runDir: ctx.runDir,
63
64
  spanId: subSpan,
65
+ taskId: task.id,
64
66
  depth: ctx.depth + 1,
65
67
  leases: ctx.leases,
66
68
  sharedWorkspace: ctx.sharedWorkspace,
@@ -72,6 +74,30 @@ async function runSpawn(ctx, toolCallId, tasks, signal) {
72
74
  approvals: ctx.approvals,
73
75
  },
74
76
  });
77
+ let result;
78
+ let priorCostUsd = 0;
79
+ try {
80
+ result = await runChild(input.budgetUsd);
81
+ // A retryable provider failure (e.g. a stalled CLI) gets one more attempt with whatever is left of the
82
+ // task's reservation; the first attempt's spend still counts.
83
+ const remainingUsd = input.budgetUsd - result.costUsd;
84
+ if (result.status === "failed" && result.error?.retryable && !signal?.aborted && remainingUsd > 1e-9) {
85
+ ctx.addChildCost(result.costUsd, result.costUnknown, result.approvalCostUsd);
86
+ priorCostUsd = result.costUsd;
87
+ env.deps.logger.warn("retrying subagent after retryable failure", { run_id: ctx.runId, task_id: task.id, error: result.error });
88
+ result = await runChild(remainingUsd);
89
+ }
90
+ }
91
+ catch (caught) {
92
+ // Always close the span, otherwise it stays 'running' forever.
93
+ try {
94
+ recorder.finish(subSpan, { status: "error", attrs: { error: toErrorPayload(caught) } });
95
+ }
96
+ catch (finishError) {
97
+ env.deps.logger.error("finishing subagent span failed", { run_id: ctx.runId, task_id: task.id, error: finishError });
98
+ }
99
+ throw caught;
100
+ }
75
101
  ctx.addChildCost(result.costUsd, result.costUnknown, result.approvalCostUsd);
76
102
  try {
77
103
  recorder.finish(subSpan, {
@@ -87,7 +113,7 @@ async function runSpawn(ctx, toolCallId, tasks, signal) {
87
113
  trajectoryId: result.trajectoryId,
88
114
  status: result.status,
89
115
  output: result.output,
90
- costUsd: result.costUsd,
116
+ costUsd: priorCostUsd + result.costUsd,
91
117
  startedAt,
92
118
  endedAt: env.now().toISOString(),
93
119
  ...(result.error ? { error: result.error } : {}),
@@ -1,10 +1,9 @@
1
- import { spawn } from "node:child_process";
2
1
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
2
  import { tmpdir } from "node:os";
4
3
  import { join } from "node:path";
5
- import { createInterface } from "node:readline";
6
4
  import { calculateCost, createAssistantMessageEventStream, createProvider, getCurrentSystemPrompt, getCurrentTools, } from "@earendil-works/pi-ai";
7
5
  import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
6
+ import { spawnGroup } from "./process-runner.js";
8
7
  /** Provider id: models are referenced as `claude-p/<model>`, e.g. `claude-p/opus` or `claude-p/claude-sonnet-5-5`. */
9
8
  export const CLAUDE_P_PROVIDER = "claude-p";
10
9
  const CLAUDE_P_API = "claude-p";
@@ -15,22 +14,7 @@ const ALIASES = ["opus", "sonnet", "haiku", "fable"];
15
14
  /** `claude --effort` values; pi's `minimal` maps to `low`. */
16
15
  const EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
17
16
  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
- };
17
+ return (request) => spawnGroup(command, request);
34
18
  }
35
19
  /** The Claude models from pi-ai's Anthropic catalog, re-homed under `claude-p`, plus the CLI's family aliases. */
36
20
  function claudePModels() {