@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,216 @@
1
+ import { ApiError, GoogleGenAI } from "@google/genai";
2
+ import { NexoError } from "../../../telemetry/src/index.js";
3
+ /** OpenAI's API root, used when `models.embedding.provider` is `openai` and no `baseUrl` is set. */
4
+ export const OPENAI_BASE_URL = "https://api.openai.com/v1";
5
+ /** The embedding provider served by the Vertex AI API with Google credentials (a service account or ADC) instead of a `baseUrl`. */
6
+ export const VERTEX_PROVIDER = "google-vertex";
7
+ /** Most Vertex embedding requests in flight at once; each request carries one text. */
8
+ const VERTEX_CONCURRENCY = 8;
9
+ /** Longest wait for one embeddings request. */
10
+ export const EMBED_TIMEOUT_MS = 30_000;
11
+ /** The configured embedding endpoint, or null without `models.embedding`. */
12
+ export function embeddingEndpoint(config) {
13
+ const e = config.models.embedding;
14
+ if (!e)
15
+ return null;
16
+ const baseUrl = e.provider === VERTEX_PROVIDER ? "" : (e.baseUrl ?? OPENAI_BASE_URL).replace(/\/+$/, "");
17
+ return { provider: e.provider, id: e.id, model: `${e.provider}/${e.id}`, baseUrl, ...(e.dimensions ? { dimensions: e.dimensions } : {}) };
18
+ }
19
+ /** The reflector and curator model: `models.reflector`, where `{ ref }` (and an absent value, which means `{ ref: "s1" }`) names a role. */
20
+ export function reflectorModelSpec(config) {
21
+ const r = config.models.reflector;
22
+ if (!r || ("ref" in r && r.ref === "s1"))
23
+ return config.models.s1;
24
+ if ("ref" in r)
25
+ return config.models.s2;
26
+ return r;
27
+ }
28
+ function providerError(endpoint, status, detail) {
29
+ const context = { provider: endpoint.provider, model: endpoint.model, status };
30
+ if (status === 401 || status === 403) {
31
+ return new NexoError({ code: "PROVIDER_AUTH", message: `The embeddings endpoint refused the key (HTTP ${status})`, hint: `Check the key with \`nexo settings set-key ${endpoint.provider}\``, context });
32
+ }
33
+ if (status === 429)
34
+ return new NexoError({ code: "PROVIDER_RATE_LIMIT", message: "The embeddings endpoint is rate limiting (HTTP 429)", retryable: true, context });
35
+ if (status >= 500)
36
+ return new NexoError({ code: "PROVIDER_UNAVAILABLE", message: `The embeddings endpoint failed (HTTP ${status})`, retryable: true, context });
37
+ return new NexoError({ code: "PROVIDER_UNAVAILABLE", message: `The embeddings endpoint rejected the request (HTTP ${status}): ${detail.slice(0, 300)}`, context });
38
+ }
39
+ function isEmbedding(value) {
40
+ return Array.isArray(value) && value.length > 0 && value.every((x) => typeof x === "number" && Number.isFinite(x));
41
+ }
42
+ function tokensOrEstimate(vectors, tokens, texts) {
43
+ if (Number.isFinite(tokens) && tokens > 0)
44
+ return { vectors, tokens };
45
+ const chars = texts.reduce((sum, t) => sum + t.length, 0);
46
+ return { vectors, tokens: Math.ceil(chars / 4), tokensEstimated: true };
47
+ }
48
+ /** Vertex clients by project, location and key, so the Google auth client and its access token are reused across calls. */
49
+ const vertexClients = new Map();
50
+ function vertexClient(project, location, apiKey) {
51
+ const key = `${project}\0${location}\0${apiKey ?? ""}`;
52
+ let client = vertexClients.get(key);
53
+ if (!client) {
54
+ client = new GoogleGenAI({ vertexai: true, project, location, ...(apiKey ? { apiKey } : {}) });
55
+ vertexClients.set(key, client);
56
+ }
57
+ return client;
58
+ }
59
+ /** A failure from the Vertex client, mapped like an HTTP failure; missing Google credentials are PROVIDER_AUTH. */
60
+ function vertexError(endpoint, error) {
61
+ if (error instanceof NexoError)
62
+ return error;
63
+ if (error instanceof ApiError)
64
+ return providerError(endpoint, error.status, error.message);
65
+ const message = error instanceof Error ? error.message : String(error);
66
+ if (/default credentials|GOOGLE_APPLICATION_CREDENTIALS|invalid_grant|unauthorized_client/i.test(message)) {
67
+ return new NexoError({
68
+ code: "PROVIDER_AUTH",
69
+ message: "No usable Google credentials for Vertex AI embeddings",
70
+ hint: "Set GOOGLE_APPLICATION_CREDENTIALS to a service account JSON file, or run `gcloud auth application-default login`",
71
+ context: { provider: endpoint.provider, model: endpoint.model },
72
+ });
73
+ }
74
+ return new NexoError({ code: "PROVIDER_UNAVAILABLE", message: `Vertex AI embeddings failed: ${message.slice(0, 300)}`, retryable: true, context: { model: endpoint.model }, cause: error });
75
+ }
76
+ /**
77
+ * Embeds `texts` through the Vertex AI API, one request per text (Vertex embedding models take one input per request).
78
+ * Authenticates with `apiKey` when set, else Google Application Default Credentials (`GOOGLE_APPLICATION_CREDENTIALS`
79
+ * or gcloud); the project and location come from `GOOGLE_CLOUD_PROJECT` (or `GCLOUD_PROJECT`) and `GOOGLE_CLOUD_LOCATION`.
80
+ */
81
+ async function embedVertex(endpoint, texts, options) {
82
+ const env = options.env ?? process.env;
83
+ const project = env.GOOGLE_CLOUD_PROJECT || env.GCLOUD_PROJECT;
84
+ const location = env.GOOGLE_CLOUD_LOCATION;
85
+ if (!project || !location) {
86
+ const missing = !project ? "GOOGLE_CLOUD_PROJECT" : "GOOGLE_CLOUD_LOCATION";
87
+ throw new NexoError({
88
+ code: "PROVIDER_AUTH",
89
+ message: `Vertex AI embeddings need ${missing}`,
90
+ hint: `Set ${missing} (and GOOGLE_APPLICATION_CREDENTIALS for a service account) in the environment nexo runs in`,
91
+ context: { provider: endpoint.provider },
92
+ });
93
+ }
94
+ const client = options.vertexClient ?? vertexClient(project, location, options.apiKey);
95
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? EMBED_TIMEOUT_MS);
96
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
97
+ const aborted = new Promise((_, reject) => {
98
+ const fail = () => reject(signal.reason);
99
+ if (signal.aborted)
100
+ fail();
101
+ else
102
+ signal.addEventListener("abort", fail, { once: true });
103
+ });
104
+ aborted.catch(() => { });
105
+ const embedOne = async (text) => {
106
+ const config = { abortSignal: signal, ...(endpoint.dimensions ? { outputDimensionality: endpoint.dimensions } : {}) };
107
+ let response;
108
+ try {
109
+ response = await Promise.race([client.models.embedContent({ model: endpoint.id, contents: text, config }), aborted]);
110
+ }
111
+ catch (error) {
112
+ if (options.signal?.aborted)
113
+ throw error;
114
+ if (timeout.aborted)
115
+ throw new NexoError({ code: "PROVIDER_TIMEOUT", message: "The embeddings request timed out", retryable: true, context: { model: endpoint.model } });
116
+ throw vertexError(endpoint, error);
117
+ }
118
+ const embedding = response.embeddings?.length === 1 ? response.embeddings[0] : undefined;
119
+ if (!isEmbedding(embedding?.values)) {
120
+ throw new NexoError({ code: "PROVIDER_UNAVAILABLE", message: "The embeddings reply has a malformed vector", context: { model: endpoint.model } });
121
+ }
122
+ return { vector: embedding.values, tokens: Number(embedding.statistics?.tokenCount ?? 0) };
123
+ };
124
+ const results = [];
125
+ for (let start = 0; start < texts.length; start += VERTEX_CONCURRENCY) {
126
+ results.push(...(await Promise.all(texts.slice(start, start + VERTEX_CONCURRENCY).map(embedOne))));
127
+ }
128
+ const reported = results.every((r) => Number.isFinite(r.tokens) && r.tokens > 0);
129
+ return tokensOrEstimate(results.map((r) => r.vector), reported ? results.reduce((n, r) => n + r.tokens, 0) : 0, texts);
130
+ }
131
+ /**
132
+ * Embeds `texts` with one `POST {baseUrl}/embeddings` request (OpenAI wire format), or through the Vertex AI API for
133
+ * provider `google-vertex`. Throws PROVIDER_AUTH (no key or Google credentials, 401, 403), PROVIDER_RATE_LIMIT (429),
134
+ * PROVIDER_UNAVAILABLE (5xx, network error, malformed reply) or PROVIDER_TIMEOUT. The key is sent only in the
135
+ * Authorization header and never appears in an error.
136
+ */
137
+ export async function embedTexts(endpoint, texts, options) {
138
+ if (texts.length === 0)
139
+ return { vectors: [], tokens: 0 };
140
+ if (endpoint.provider === VERTEX_PROVIDER)
141
+ return embedVertex(endpoint, texts, options);
142
+ if (!options.apiKey) {
143
+ throw new NexoError({
144
+ code: "PROVIDER_AUTH",
145
+ message: `No API key for the embedding provider "${endpoint.provider}"`,
146
+ hint: `Set it with \`nexo settings set-key ${endpoint.provider}\` or its environment variable`,
147
+ context: { provider: endpoint.provider },
148
+ });
149
+ }
150
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
151
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? EMBED_TIMEOUT_MS);
152
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
153
+ let response;
154
+ try {
155
+ response = await doFetch(`${endpoint.baseUrl}/embeddings`, {
156
+ method: "POST",
157
+ headers: { "content-type": "application/json", authorization: `Bearer ${options.apiKey}` },
158
+ body: JSON.stringify({ model: endpoint.id, input: texts, ...(endpoint.dimensions ? { dimensions: endpoint.dimensions } : {}) }),
159
+ signal,
160
+ });
161
+ }
162
+ catch (cause) {
163
+ if (options.signal?.aborted)
164
+ throw cause;
165
+ if (timeout.aborted)
166
+ throw new NexoError({ code: "PROVIDER_TIMEOUT", message: "The embeddings request timed out", retryable: true, context: { model: endpoint.model } });
167
+ throw new NexoError({ code: "PROVIDER_UNAVAILABLE", message: `The embeddings endpoint is unreachable: ${cause.message}`, retryable: true, context: { model: endpoint.model }, cause });
168
+ }
169
+ const body = await response.text();
170
+ if (!response.ok)
171
+ throw providerError(endpoint, response.status, body);
172
+ let parsed;
173
+ try {
174
+ parsed = JSON.parse(body);
175
+ }
176
+ catch {
177
+ throw new NexoError({ code: "PROVIDER_UNAVAILABLE", message: "The embeddings reply is not JSON", context: { model: endpoint.model } });
178
+ }
179
+ const data = Array.isArray(parsed.data) ? parsed.data : [];
180
+ const slots = new Array(texts.length).fill(undefined);
181
+ for (const [position, item] of data.entries()) {
182
+ const index = typeof item.index === "number" ? item.index : position;
183
+ const embedding = item.embedding;
184
+ if (!isEmbedding(embedding) ||
185
+ !Number.isInteger(index) ||
186
+ index < 0 ||
187
+ index >= texts.length ||
188
+ slots[index] !== undefined) {
189
+ throw new NexoError({ code: "PROVIDER_UNAVAILABLE", message: "The embeddings reply has a malformed vector", context: { model: endpoint.model, index } });
190
+ }
191
+ slots[index] = embedding;
192
+ }
193
+ const vectors = [];
194
+ for (const v of slots)
195
+ if (v !== undefined)
196
+ vectors.push(v);
197
+ if (data.length !== texts.length || vectors.length !== texts.length) {
198
+ throw new NexoError({ code: "PROVIDER_UNAVAILABLE", message: `The embeddings reply has ${data.length} vectors for ${texts.length} texts`, context: { model: endpoint.model } });
199
+ }
200
+ return tokensOrEstimate(vectors, Number(parsed.usage?.prompt_tokens ?? parsed.usage?.total_tokens ?? 0), texts);
201
+ }
202
+ /**
203
+ * USD of an embeddings call from `pricingOverrides["<provider>/<id>"].input` (USD per million tokens). Without a price
204
+ * the cost is unknown (spec §10: never counted as $0); only a call with no tokens (empty input) costs a known 0.
205
+ */
206
+ export function embeddingCost(config, endpoint, tokens) {
207
+ const rate = config.pricingOverrides[endpoint.model]?.input;
208
+ if (rate === undefined)
209
+ return { costUsd: 0, costUnknown: tokens > 0 };
210
+ return { costUsd: (tokens * rate) / 1_000_000, costUnknown: false };
211
+ }
212
+ /** Upper-bound USD of embedding `chars` characters (ceil(chars / 4) tokens); 0 without a price. */
213
+ export function estimateEmbeddingUsd(config, endpoint, chars) {
214
+ const rate = config.pricingOverrides[endpoint.model]?.input;
215
+ return rate === undefined ? 0 : (Math.ceil(chars / 4) * rate) / 1_000_000;
216
+ }
@@ -0,0 +1,196 @@
1
+ import { curateWikiKnowledge } from "./wiki.js";
2
+ import { existsSync } from "node:fs";
3
+ import { applyCuratorDelta, CURATOR_SYSTEM, CuratorDeltaSchema, curatorPrompt, REFLECTOR_SYSTEM, ReflectionSchema, reflectorPrompt, relevanceScores, } from "../../../memory/src/index.js";
4
+ import { renderTrajectory } from "../../../scorers/src/index.js";
5
+ import { completeLearnJob, ftsScores, getRun, isSkillName, latestFeedback, listPlaybookItems, listScores, listSpans, liveMemories, memoriesWithoutEmbedding, putEmbedding, readRunJson, RunDir, transaction, } from "../../../store/src/index.js";
6
+ import { NexoError, toErrorPayload } from "../../../telemetry/src/index.js";
7
+ import { Recorder } from "../engine/recorder.js";
8
+ import { summarizeSpans } from "../scoring/runner.js";
9
+ import { embedCharged, ensureLearnBudget, estimateLearnCallUsd, learnBudget, ledgerCharge, structuredLearnCall } from "./caller.js";
10
+ import { embeddingEndpoint } from "./embedder.js";
11
+ /** Memories without a vector that one job embeds before reflecting (user-added and older memories catch up this way). */
12
+ export const EMBED_BACKFILL_PER_JOB = 32;
13
+ /** Related memories shown to the curator. */
14
+ const CURATOR_MEMORIES = 30;
15
+ /**
16
+ * Thrown when the worker no longer holds the job (it was reclaimed or released) at the moment the job would be marked
17
+ * succeeded; nothing of the job's result is written.
18
+ */
19
+ export class LearnClaimLostError extends NexoError {
20
+ constructor(jobId, workerId) {
21
+ super({ code: "WRITE_CONFLICT", message: `Learn job ${jobId} is no longer held by worker ${workerId}`, context: { jobId, workerId } });
22
+ }
23
+ }
24
+ /** Skills a run used: its `--skill` and every skill it loaded successfully with load_skill. */
25
+ export function skillsUsed(skill, spans) {
26
+ const names = new Set();
27
+ if (skill)
28
+ names.add(skill);
29
+ for (const s of spans) {
30
+ const name = s.attrs.args?.name;
31
+ if (s.kind === "skill_load" && s.status === "ok" && isSkillName(name))
32
+ names.add(name);
33
+ }
34
+ return [...names].sort();
35
+ }
36
+ /**
37
+ * Runs one reflect job (spec §8.1): reads the run, its latest scores and verdict, asks the reflector for lessons, asks
38
+ * the curator for deltas and applies them through the guarded store. Every model call is a span on the learned run under
39
+ * one `learn` span, and the applied delta is a `memory_write` span. The job is marked succeeded for `options.workerId`
40
+ * in the same transaction that applies the delta, so the delta is applied exactly when the job succeeds; a worker that
41
+ * lost the claim gets LearnClaimLostError and writes nothing. Throws on any failure (the worker records it on the job);
42
+ * the run itself is never changed.
43
+ */
44
+ export async function runLearnJob(env, job, options) {
45
+ const { db, config, redact, logger } = env.deps;
46
+ const run = getRun(db, job.runId);
47
+ if (!run)
48
+ throw new NexoError({ code: "NOT_FOUND", message: `Run ${job.runId} does not exist`, context: { runId: job.runId } });
49
+ if (run.status === "running")
50
+ throw new NexoError({ code: "CONFLICT", message: `Run ${run.id} is still running`, retryable: true, context: { runId: run.id } });
51
+ if (!existsSync(run.dirPath))
52
+ throw new NexoError({ code: "NOT_FOUND", message: `The directory of run ${run.id} is gone`, context: { runId: run.id, dir: run.dirPath } });
53
+ const budget = learnBudget(db, config, env.now());
54
+ const recorder = new Recorder({ db, runDir: new RunDir(run.dirPath, run.id, redact), runId: run.id, now: env.now, redact });
55
+ const learnSpan = recorder.start({ kind: "learn", name: "reflect", parentSpanId: null, attrs: { jobId: job.id, trigger: job.trigger, attempt: job.attempts } });
56
+ let costUsd = 0;
57
+ let costUnknown = false;
58
+ const toLedgers = ledgerCharge(db, env.now);
59
+ const markSucceeded = () => {
60
+ if (!completeLearnJob(db, job.id, options.workerId, env.now().toISOString()))
61
+ throw new LearnClaimLostError(job.id, options.workerId);
62
+ };
63
+ const deps = {
64
+ env,
65
+ recorder,
66
+ parentSpanId: learnSpan,
67
+ budget,
68
+ signal: options.signal,
69
+ ...(options.fetch ? { fetch: options.fetch } : {}),
70
+ charge: (usd, unknown) => {
71
+ toLedgers(usd);
72
+ costUsd += usd;
73
+ costUnknown ||= unknown;
74
+ },
75
+ };
76
+ try {
77
+ const spans = listSpans(db, run.id);
78
+ const skills = skillsUsed(run.skill, spans);
79
+ const playbooks = skills.map((name) => ({ name, items: listPlaybookItems(db, name).map((i) => ({ key: i.key, source: i.source, content: i.content })) }));
80
+ const scores = listScores(db, run.id);
81
+ const lastRound = Math.max(-1, ...scores.map((s) => s.round));
82
+ let output = "";
83
+ try {
84
+ output = readRunJson(run.dirPath).output ?? "";
85
+ }
86
+ catch {
87
+ output = "";
88
+ }
89
+ const feedback = latestFeedback(db, run.id);
90
+ const reflectorUser = reflectorPrompt({
91
+ instruction: run.instruction,
92
+ status: run.status,
93
+ output,
94
+ trajectory: renderTrajectory(summarizeSpans(spans), 6000),
95
+ scores: scores
96
+ .filter((s) => s.round === lastRound)
97
+ .map((s) => ({ name: s.scorerName, status: s.status, value: s.value, passed: s.passed, rationale: s.rationale })),
98
+ verdict: feedback ? { verdict: feedback.verdict, comment: feedback.comment } : null,
99
+ skills: playbooks,
100
+ });
101
+ // Before anything is spent: the reflector call and a curator call at least its system prompt long must fit the budget.
102
+ ensureLearnBudget(config, budget, estimateLearnCallUsd(env, REFLECTOR_SYSTEM.length + reflectorUser.length) + estimateLearnCallUsd(env, CURATOR_SYSTEM.length));
103
+ const endpoint = embeddingEndpoint(config);
104
+ if (endpoint) {
105
+ const missing = memoriesWithoutEmbedding(db, endpoint.model, EMBED_BACKFILL_PER_JOB);
106
+ try {
107
+ const vectors = await embedCharged(deps, endpoint, missing.map((m) => m.content), "backfill");
108
+ missing.forEach((m, i) => {
109
+ const v = vectors[i];
110
+ if (v)
111
+ putEmbedding(db, m.id, endpoint.model, v, env.now().toISOString());
112
+ });
113
+ }
114
+ catch (error) {
115
+ if (options.signal.aborted)
116
+ throw error;
117
+ logger.warn("embedding backfill failed; continuing without it", { run_id: run.id, error });
118
+ }
119
+ }
120
+ const reflection = await structuredLearnCall(deps, ReflectionSchema, { system: REFLECTOR_SYSTEM, user: reflectorUser, tier: "reflector" });
121
+ if (reflection.lessons.length === 0 && reflection.playbookTags.length === 0) {
122
+ markSucceeded();
123
+ return { lessons: 0, curation: null, costUsd, costUnknown };
124
+ }
125
+ const scopes = ["user", "global", ...skills.map((s) => `skill:${s}`)];
126
+ const candidates = liveMemories(db, scopes);
127
+ const relevance = relevanceScores(candidates, ftsScores(db, reflection.lessons.map((l) => l.content).join("\n"), scopes), null);
128
+ const related = [...candidates]
129
+ .sort((a, b) => (relevance.get(b.id) ?? 0) - (relevance.get(a.id) ?? 0) || b.createdAt.localeCompare(a.createdAt))
130
+ .slice(0, CURATOR_MEMORIES);
131
+ const delta = reflection.lessons.length === 0
132
+ ? { memory: [], playbook: [] }
133
+ : await structuredLearnCall(deps, CuratorDeltaSchema, {
134
+ system: CURATOR_SYSTEM,
135
+ user: curatorPrompt({ lessons: reflection.lessons, memories: related, skills: playbooks }),
136
+ tier: "curator",
137
+ });
138
+ const vectors = new Map();
139
+ const texts = [...new Set(delta.memory.flatMap((op) => (op.op === "noop" ? [] : [op.content])))];
140
+ if (endpoint && texts.length > 0) {
141
+ try {
142
+ const embedded = await embedCharged(deps, endpoint, texts, "memory");
143
+ texts.forEach((t, i) => {
144
+ const v = embedded[i];
145
+ if (v)
146
+ vectors.set(t, v);
147
+ });
148
+ }
149
+ catch (error) {
150
+ if (options.signal.aborted)
151
+ throw error;
152
+ logger.warn("embedding new memories failed; dedup falls back to word overlap", { run_id: run.id, error });
153
+ }
154
+ }
155
+ if (options.signal.aborted)
156
+ throw new NexoError({ code: "INTERNAL", message: "The learn job was aborted before applying its delta", retryable: true });
157
+ const writeSpan = recorder.start({ kind: "memory_write", name: "curate", parentSpanId: learnSpan, attrs: { delta: redact(delta) } });
158
+ let curation;
159
+ try {
160
+ curation = transaction(db, () => {
161
+ markSucceeded();
162
+ return applyCuratorDelta(db, {
163
+ runId: run.id,
164
+ delta,
165
+ tags: reflection.playbookTags,
166
+ skills,
167
+ maxPlaybookItems: config.learning.maxPlaybookItems,
168
+ vectors,
169
+ embeddingModel: endpoint?.model ?? null,
170
+ redact,
171
+ nowIso: env.now().toISOString(),
172
+ });
173
+ });
174
+ }
175
+ catch (error) {
176
+ recorder.finish(writeSpan, { status: "error", attrs: { error: redact(toErrorPayload(error)) } });
177
+ throw error;
178
+ }
179
+ recorder.finish(writeSpan, { status: "ok", attrs: { result: curation } });
180
+ try {
181
+ await curateWikiKnowledge(deps, run, output, spans);
182
+ }
183
+ catch (err) {
184
+ logger.warn("wiki curation pass failed; continuing without it", { run_id: run.id, error: err });
185
+ }
186
+ return { lessons: reflection.lessons.length, curation, costUsd, costUnknown };
187
+ }
188
+ catch (error) {
189
+ recorder.finish(learnSpan, { status: "error", costUsd: 0, attrs: { error: redact(toErrorPayload(error)), totalCostUsd: costUsd } });
190
+ throw error;
191
+ }
192
+ finally {
193
+ if (recorder.get(learnSpan)?.status === "running")
194
+ recorder.finish(learnSpan, { status: "ok", costUsd: 0, attrs: { totalCostUsd: costUsd } });
195
+ }
196
+ }
@@ -0,0 +1,116 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { dataBlock } from "../../../scorers/src/index.js";
4
+ import { resolveConfined } from "../../../tools/src/index.js";
5
+ import { Type } from "typebox";
6
+ import { structuredLearnCall } from "./caller.js";
7
+ export const WikiPageProposalSchema = Type.Object({
8
+ wikiName: Type.String({ minLength: 1, maxLength: 64, pattern: "^[a-z0-9]+(-[a-z0-9]+)*$" }),
9
+ path: Type.String({ minLength: 1, maxLength: 128 }),
10
+ summary: Type.String({ minLength: 1, maxLength: 300 }),
11
+ content: Type.String({ minLength: 1, maxLength: 8000 }),
12
+ }, { additionalProperties: false });
13
+ export const WikiCurationSchema = Type.Object({
14
+ pages: Type.Array(WikiPageProposalSchema, { maxItems: 4 }),
15
+ }, { additionalProperties: false });
16
+ export const WIKI_CURATOR_SYSTEM = `You are a knowledge curator for an AI agent's persistent markdown wikis.
17
+ Review the finished task and its output. Determine if the task produced substantive, durable subject knowledge (research results, domain concepts, entity profiles, method syntheses, technical facts) that should be recorded into a markdown wiki for future reference.
18
+
19
+ Do NOT create wiki pages for:
20
+ - Routine code modifications, git operations or minor debugging
21
+ - One-off conversational chit-chat or simple user preference statements (which belong to memories)
22
+ - Ephemeral task artifacts
23
+
24
+ If durable subject knowledge is present:
25
+ - Select an appropriate wiki topic name in lowercase-with-hyphens (e.g. "ai", "finance", "distributed-systems").
26
+ - Propose pages using appropriate subfolders: "concepts/<slug>.md", "entities/<slug>.md", "sources/<slug>.md", or "analyses/<slug>.md".
27
+ - Provide a concise summary and clear markdown content (with [[wikilinks]] where relevant).
28
+ If no substantive subject knowledge is worth saving, reply with {"pages": []}.`;
29
+ export function wikiCuratorPrompt(input) {
30
+ const wikisList = input.existingWikis.length > 0 ? input.existingWikis.join(", ") : "(no existing wikis)";
31
+ return [
32
+ `# Existing wikis\n${wikisList}`,
33
+ `# User instruction\n${dataBlock("instruction", input.instruction)}`,
34
+ `# Final output\n${dataBlock("output", input.output || "(empty)")}`,
35
+ ].join("\n\n");
36
+ }
37
+ /**
38
+ * Curates durable subject knowledge into persistent markdown wikis after a run.
39
+ */
40
+ export async function curateWikiKnowledge(deps, run, output, spans) {
41
+ const wikisDir = deps.env.deps.paths?.wikis;
42
+ if (!wikisDir)
43
+ return { pagesCreated: 0, wikisTouched: [] };
44
+ if (!existsSync(wikisDir))
45
+ mkdirSync(wikisDir, { recursive: true });
46
+ // Skip if the run itself explicitly loaded the wiki skill (it managed its own wiki edits)
47
+ const usedWikiSkill = spans.some((s) => s.kind === "skill_load" && s.status === "ok" && s.attrs.args?.name === "wiki");
48
+ if (usedWikiSkill)
49
+ return { pagesCreated: 0, wikisTouched: [] };
50
+ // Only evaluate runs that have non-trivial instruction/output
51
+ if (!output || output.trim().length < 50)
52
+ return { pagesCreated: 0, wikisTouched: [] };
53
+ let existingWikis = [];
54
+ try {
55
+ existingWikis = readdirSync(wikisDir).filter((f) => {
56
+ if (f.startsWith("."))
57
+ return false;
58
+ try {
59
+ return statSync(join(wikisDir, f)).isDirectory();
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ });
65
+ }
66
+ catch {
67
+ existingWikis = [];
68
+ }
69
+ const prompt = wikiCuratorPrompt({
70
+ instruction: run.instruction,
71
+ output,
72
+ existingWikis,
73
+ });
74
+ const curation = await structuredLearnCall(deps, WikiCurationSchema, {
75
+ system: WIKI_CURATOR_SYSTEM,
76
+ user: prompt,
77
+ tier: "curator",
78
+ });
79
+ if (curation.pages.length === 0)
80
+ return { pagesCreated: 0, wikisTouched: [] };
81
+ let pagesCreated = 0;
82
+ const wikisTouched = new Set();
83
+ const today = deps.env.now().toISOString().slice(0, 10);
84
+ for (const p of curation.pages) {
85
+ try {
86
+ const wikiDir = resolveConfined(wikisDir, p.wikiName);
87
+ if (!existsSync(wikiDir)) {
88
+ mkdirSync(wikiDir, { recursive: true });
89
+ mkdirSync(join(wikiDir, "concepts"), { recursive: true });
90
+ mkdirSync(join(wikiDir, "entities"), { recursive: true });
91
+ mkdirSync(join(wikiDir, "sources"), { recursive: true });
92
+ mkdirSync(join(wikiDir, "analyses"), { recursive: true });
93
+ mkdirSync(join(wikiDir, "raw"), { recursive: true });
94
+ writeFileSync(join(wikiDir, "AGENTS.md"), `# ${p.wikiName} wiki\n\nKnowledge base for ${p.wikiName}.\n`);
95
+ writeFileSync(join(wikiDir, "index.md"), `# ${p.wikiName} index\n\n## Concepts\n\n## Entities\n\n## Sources\n\n## Analyses\n`);
96
+ writeFileSync(join(wikiDir, "log.md"), `# Log\n\n## [${today}] create | Initialized wiki\n`);
97
+ writeFileSync(join(wikiDir, "overview.md"), `---\nsummary: Overview of ${p.wikiName}\nupdated: ${today}\nsources: []\n---\n\n# ${p.wikiName}\n`);
98
+ }
99
+ const targetFile = resolveConfined(wikiDir, p.path.endsWith(".md") ? p.path : `${p.path}.md`);
100
+ mkdirSync(dirname(targetFile), { recursive: true });
101
+ const frontmatter = `---\nsummary: ${p.summary.replace(/\n/g, " ")}\nupdated: ${today}\nsources: [run:${run.id}]\n---\n\n`;
102
+ writeFileSync(targetFile, frontmatter + p.content.trim() + "\n");
103
+ pagesCreated++;
104
+ wikisTouched.add(p.wikiName);
105
+ const logFile = join(wikiDir, "log.md");
106
+ if (existsSync(logFile)) {
107
+ const logLine = `\n## [${today}] ingest | Auto-curated ${p.path} from run ${run.id}\n`;
108
+ writeFileSync(logFile, readFileSync(logFile, "utf8") + logLine);
109
+ }
110
+ }
111
+ catch (err) {
112
+ deps.env.deps.logger.warn("failed to write curated wiki page", { wiki: p.wikiName, path: p.path, error: err });
113
+ }
114
+ }
115
+ return { pagesCreated, wikisTouched: [...wikisTouched] };
116
+ }
@@ -0,0 +1,141 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { hostname } from "node:os";
3
+ import { claimLearnJob, failLearnJob, reclaimStaleLearnJobs, releaseLearnJob } from "../../../store/src/index.js";
4
+ import { NexoError, toErrorPayload } from "../../../telemetry/src/index.js";
5
+ import { LearnClaimLostError, runLearnJob } from "./job.js";
6
+ /** Part of `learning.staleMinutes` a job may run before it is aborted, so it ends before other workers reclaim it. */
7
+ const JOB_DEADLINE_SHARE = 0.8;
8
+ /**
9
+ * Runs learn jobs one at a time in this process (spec §8.1: in the background, never blocking or failing a run). Jobs
10
+ * are taken with the store's atomic claim, so several processes can drain one database; a job that is still running
11
+ * after 0.8 × `learning.staleMinutes` is aborted and fails. With `learning.enabled: false` a drain does nothing.
12
+ */
13
+ export class LearnWorker {
14
+ workerId;
15
+ env;
16
+ options;
17
+ background = null;
18
+ again = false;
19
+ stopController = new AbortController();
20
+ /** The job this worker is running, if any. */
21
+ current = null;
22
+ /** The id of the job `stop` put back to pending. */
23
+ releasedOnStop = null;
24
+ constructor(env, options = {}) {
25
+ this.env = env;
26
+ this.options = options;
27
+ this.workerId = options.workerId ?? `${hostname()}:${process.pid}:${randomBytes(4).toString("hex")}`;
28
+ }
29
+ /** Runs pending jobs until none is left, `maxJobs` ran, the deadline passed or the signal aborted. */
30
+ async drain(options = {}) {
31
+ const result = { succeeded: 0, failed: 0, released: 0 };
32
+ const { config, db, logger, redact } = this.env.deps;
33
+ if (!config.learning.enabled || this.stopController.signal.aborted)
34
+ return result;
35
+ const signals = [this.stopController.signal];
36
+ if (options.signal)
37
+ signals.push(options.signal);
38
+ if (options.deadlineMs !== undefined)
39
+ signals.push(AbortSignal.timeout(Math.max(0, options.deadlineMs)));
40
+ const signal = AbortSignal.any(signals);
41
+ const now = this.env.now();
42
+ const stale = reclaimStaleLearnJobs(db, new Date(now.getTime() - config.learning.staleMinutes * 60_000).toISOString(), now.toISOString());
43
+ if (stale.pending.length + stale.failed.length > 0)
44
+ logger.warn("reclaimed learn jobs left running by a stopped process", { pending: stale.pending, failed: stale.failed });
45
+ const max = options.maxJobs ?? Number.POSITIVE_INFINITY;
46
+ while (result.succeeded + result.failed < max && !signal.aborted) {
47
+ const job = claimLearnJob(db, this.workerId, this.env.now().toISOString());
48
+ if (!job)
49
+ break;
50
+ this.options.onEvent?.({ type: "job_start", job });
51
+ this.current = job;
52
+ const deadlineMs = config.learning.staleMinutes * 60_000 * JOB_DEADLINE_SHARE;
53
+ const deadline = AbortSignal.timeout(deadlineMs);
54
+ const jobSignal = AbortSignal.any([signal, deadline]);
55
+ try {
56
+ const outcome = await runLearnJob(this.env, job, { workerId: this.workerId, signal: jobSignal, ...(this.options.fetch ? { fetch: this.options.fetch } : {}) });
57
+ result.succeeded++;
58
+ logger.info("learn job succeeded", { job_id: job.id, run_id: job.runId, lessons: outcome.lessons, cost_usd: outcome.costUsd });
59
+ this.options.onEvent?.({ type: "job_end", job, ok: true, outcome });
60
+ }
61
+ catch (error) {
62
+ if (error instanceof LearnClaimLostError) {
63
+ logger.warn("learn job lost its claim; another worker owns it, nothing was written", { job_id: job.id, run_id: job.runId });
64
+ continue;
65
+ }
66
+ if (signal.aborted) {
67
+ if (releaseLearnJob(db, job.id, this.workerId, this.env.now().toISOString()) || this.releasedOnStop === job.id)
68
+ result.released++;
69
+ else
70
+ logger.warn("learn job lost its claim while stopping", { job_id: job.id, run_id: job.runId });
71
+ break;
72
+ }
73
+ const cause = deadline.aborted
74
+ ? new NexoError({
75
+ code: "PROVIDER_TIMEOUT",
76
+ message: `The learn job ran past its deadline of ${Math.round(deadlineMs / 1000)} s (0.8 × learning.staleMinutes)`,
77
+ retryable: true,
78
+ hint: "Raise learning.staleMinutes, or retry with `nexo learn --retry`",
79
+ })
80
+ : error;
81
+ const payload = redact(toErrorPayload(cause));
82
+ if (!failLearnJob(db, job.id, this.workerId, payload, this.env.now().toISOString())) {
83
+ logger.warn("learn job lost its claim; another worker owns it", { job_id: job.id, run_id: job.runId, error: payload });
84
+ continue;
85
+ }
86
+ result.failed++;
87
+ logger.warn("learn job failed", { job_id: job.id, run_id: job.runId, error: payload });
88
+ this.options.onEvent?.({ type: "job_end", job, ok: false, error: { code: payload.code, message: payload.message } });
89
+ }
90
+ finally {
91
+ this.current = null;
92
+ }
93
+ }
94
+ return result;
95
+ }
96
+ /** Starts a background drain, or asks the running one to look again when it finishes. Never throws; failures are logged. */
97
+ kick() {
98
+ if (this.stopController.signal.aborted)
99
+ return;
100
+ if (this.background) {
101
+ this.again = true;
102
+ return;
103
+ }
104
+ const loop = async () => {
105
+ const total = { succeeded: 0, failed: 0, released: 0 };
106
+ do {
107
+ this.again = false;
108
+ const r = await this.drain();
109
+ total.succeeded += r.succeeded;
110
+ total.failed += r.failed;
111
+ total.released += r.released;
112
+ } while (this.again && !this.stopController.signal.aborted);
113
+ return total;
114
+ };
115
+ this.background = loop()
116
+ .catch((error) => {
117
+ this.env.deps.logger.error("learn worker failed", { error });
118
+ return { succeeded: 0, failed: 0, released: 0 };
119
+ })
120
+ .finally(() => {
121
+ this.background = null;
122
+ });
123
+ }
124
+ /** Resolves when the background drain started by `kick` has finished (immediately when none runs). */
125
+ async idle() {
126
+ while (this.background)
127
+ await this.background;
128
+ }
129
+ /**
130
+ * Stops the worker: the running job is aborted and put back to pending (attempt not counted) before this returns its
131
+ * promise, so the release is written even when the process exits right after. The promise resolves once the aborted
132
+ * job has unwound.
133
+ */
134
+ async stop() {
135
+ this.stopController.abort();
136
+ const job = this.current;
137
+ if (job && releaseLearnJob(this.env.deps.db, job.id, this.workerId, this.env.now().toISOString()))
138
+ this.releasedOnStop = job.id;
139
+ await this.idle();
140
+ }
141
+ }