@namzu/sdk 42.0.0 → 42.0.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.
Files changed (72) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/manager/resident/outbox.d.ts +8 -8
  3. package/dist/manager/resident/store.d.ts +4 -4
  4. package/dist/runtime/query/cancelled-before-start.d.ts +34 -0
  5. package/dist/runtime/query/cancelled-before-start.d.ts.map +1 -0
  6. package/dist/runtime/query/cancelled-before-start.js +152 -0
  7. package/dist/runtime/query/cancelled-before-start.js.map +1 -0
  8. package/dist/runtime/query/checkpoint.d.ts +21 -0
  9. package/dist/runtime/query/checkpoint.d.ts.map +1 -1
  10. package/dist/runtime/query/checkpoint.js +23 -0
  11. package/dist/runtime/query/checkpoint.js.map +1 -1
  12. package/dist/runtime/query/executor/tool-call-admission.d.ts +57 -0
  13. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -0
  14. package/dist/runtime/query/executor/tool-call-admission.js +373 -0
  15. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -0
  16. package/dist/runtime/query/executor.d.ts +70 -35
  17. package/dist/runtime/query/executor.d.ts.map +1 -1
  18. package/dist/runtime/query/executor.js +46 -380
  19. package/dist/runtime/query/executor.js.map +1 -1
  20. package/dist/runtime/query/finalize-run.d.ts +55 -0
  21. package/dist/runtime/query/finalize-run.d.ts.map +1 -0
  22. package/dist/runtime/query/finalize-run.js +113 -0
  23. package/dist/runtime/query/finalize-run.js.map +1 -0
  24. package/dist/runtime/query/index.d.ts +4 -9
  25. package/dist/runtime/query/index.d.ts.map +1 -1
  26. package/dist/runtime/query/index.js +238 -893
  27. package/dist/runtime/query/index.js.map +1 -1
  28. package/dist/runtime/query/iteration/index.d.ts +6 -161
  29. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  30. package/dist/runtime/query/iteration/index.js +23 -523
  31. package/dist/runtime/query/iteration/index.js.map +1 -1
  32. package/dist/runtime/query/iteration/outstanding-work.d.ts +158 -0
  33. package/dist/runtime/query/iteration/outstanding-work.d.ts.map +1 -0
  34. package/dist/runtime/query/iteration/outstanding-work.js +365 -0
  35. package/dist/runtime/query/iteration/outstanding-work.js.map +1 -0
  36. package/dist/runtime/query/iteration/phases/plan.d.ts.map +1 -1
  37. package/dist/runtime/query/iteration/phases/plan.js +13 -2
  38. package/dist/runtime/query/iteration/phases/plan.js.map +1 -1
  39. package/dist/runtime/query/iteration/step-shaping.d.ts +41 -0
  40. package/dist/runtime/query/iteration/step-shaping.d.ts.map +1 -0
  41. package/dist/runtime/query/iteration/step-shaping.js +184 -0
  42. package/dist/runtime/query/iteration/step-shaping.js.map +1 -0
  43. package/dist/runtime/query/prepare-run.d.ts +94 -0
  44. package/dist/runtime/query/prepare-run.d.ts.map +1 -0
  45. package/dist/runtime/query/prepare-run.js +589 -0
  46. package/dist/runtime/query/prepare-run.js.map +1 -0
  47. package/dist/runtime/query/release-run.d.ts +56 -0
  48. package/dist/runtime/query/release-run.d.ts.map +1 -0
  49. package/dist/runtime/query/release-run.js +101 -0
  50. package/dist/runtime/query/release-run.js.map +1 -0
  51. package/dist/runtime/query/resume-pending.d.ts +112 -1
  52. package/dist/runtime/query/resume-pending.d.ts.map +1 -1
  53. package/dist/runtime/query/resume-pending.js +133 -0
  54. package/dist/runtime/query/resume-pending.js.map +1 -1
  55. package/dist/store/evidence/compaction-archive.d.ts +2 -2
  56. package/dist/types/run/config.d.ts +12 -5
  57. package/dist/types/run/config.d.ts.map +1 -1
  58. package/package.json +1 -1
  59. package/src/runtime/query/cancelled-before-start.ts +189 -0
  60. package/src/runtime/query/checkpoint.ts +22 -0
  61. package/src/runtime/query/executor/tool-call-admission.ts +473 -0
  62. package/src/runtime/query/executor.ts +63 -442
  63. package/src/runtime/query/finalize-run.ts +192 -0
  64. package/src/runtime/query/index.ts +270 -1011
  65. package/src/runtime/query/iteration/index.ts +40 -586
  66. package/src/runtime/query/iteration/outstanding-work.ts +386 -0
  67. package/src/runtime/query/iteration/phases/plan.ts +18 -2
  68. package/src/runtime/query/iteration/step-shaping.ts +271 -0
  69. package/src/runtime/query/prepare-run.ts +718 -0
  70. package/src/runtime/query/release-run.ts +168 -0
  71. package/src/runtime/query/resume-pending.ts +158 -0
  72. package/src/types/run/config.ts +12 -5
@@ -0,0 +1,589 @@
1
+ import { drainQueuedMessages } from '../../agents/handle.js';
2
+ import { repairToolMessageHistory, toolHistoryRepairChanged, } from '../../compaction/dangling.js';
3
+ import { resolveModelPricing } from '../../pricing/index.js';
4
+ import { isCallerAbortError } from '../../provider/errors.js';
5
+ import { withProviderFallback, } from '../../provider/fallback.js';
6
+ import { resolveStreamIdleTimeoutMs, withStreamIdleTimeout } from '../../provider/idle-timeout.js';
7
+ import { withProviderRetry } from '../../provider/retry.js';
8
+ import { withTokenBudget } from '../../provider/token-budget.js';
9
+ import { resolveAttachments } from '../../store/attachment/index.js';
10
+ import { NAMZU } from '../../telemetry/attributes.js';
11
+ import { NamzuError } from '../../types/errors/index.js';
12
+ import { autoApproveHandler } from '../../types/hitl/index.js';
13
+ import { cancelCauseOf } from '../../types/run/cancel-cause.js';
14
+ import { toErrorMessage } from '../../utils/error.js';
15
+ import { generateCheckpointId, generateRunId } from '../../utils/id.js';
16
+ import { errorAttributes } from '../../utils/log/exception.js';
17
+ import { AUTO_APPROVE_POLICY_NAME, createRunApprovalPolicy } from './approval-policy.js';
18
+ import { RunContextFactory } from './context.js';
19
+ import { EventTranslator } from './events.js';
20
+ import { isCompactionMessage } from './iteration/phases/compaction.js';
21
+ import { isWorkingMemoryMessage } from './iteration/phases/working-memory.js';
22
+ import { awaitProjectInstructionCallback, collapseProjectInstructionSnapshots, replaceProjectInstructionSnapshot, } from './project-instructions.js';
23
+ import { resolveMaxRequestRichContentBytes } from './request-rich-content.js';
24
+ import { resolveSandboxTeardownTimeoutMs } from './sandbox-lifecycle.js';
25
+ import { resolveQueryBudget } from './token-budget.js';
26
+ import { assertMaxToolCalls } from './tool-call-budget.js';
27
+ export const selectedResumeStates = new WeakMap();
28
+ /**
29
+ * Refuse to price a run whose tokens two differently-priced members may produce.
30
+ *
31
+ * `RunPersistence` holds ONE {@link ModelPricing} table and applies it to every
32
+ * accumulation regardless of which model produced the tokens. Across a swap that
33
+ * makes `costInfo.totalCost` wrong by an unbounded margin, and silently — the
34
+ * number keeps the shape of an answer. `CostInfo` cannot express the truth
35
+ * either: it carries `inputCostPer1M` / `outputCostPer1M`, and there is no
36
+ * honest value for those once a total spans two rate cards.
37
+ *
38
+ * So the total is refused rather than blended. Naming what that costs is part
39
+ * of the refusal, because the caller loses `costLimitUsd` with it: the guard
40
+ * enforces that limit from this same accumulated total, and a limit enforced
41
+ * with the wrong rate card stops a run early or late by the same unbounded
42
+ * margin. A budget that is quietly wrong is worse than a budget that is
43
+ * declined.
44
+ *
45
+ * Reachable, not decorative: a host that passes `pricing` and declares a chain
46
+ * hits it on the first call. It costs `@namzu/cli` nothing, which passes no
47
+ * pricing at all — its `/cost` already reports that the provider gave no price.
48
+ *
49
+ * The way out is per-member pricing, which needs a `CostInfo` that can sum over
50
+ * heterogeneous rates. That is a public-type change and it is not this one.
51
+ */
52
+ function assertCostIsAttributable(chain, pricing) {
53
+ if (pricing === undefined || chain.length < 2)
54
+ return;
55
+ throw new NamzuError({
56
+ code: 'invalid_config',
57
+ message: `A provider chain of ${chain.length} members was declared together with a single pricing table. ` +
58
+ 'One table cannot price two members, so the run would report a total that is wrong by an unbounded ' +
59
+ 'margin — and `runConfig.costLimitUsd` would be enforced against that same wrong total. ' +
60
+ 'Either drop `pricing` (usage is still reported per model in the run) or declare one member.',
61
+ details: { chainLength: chain.length },
62
+ });
63
+ }
64
+ /**
65
+ * Refuse a budget that cannot be measured.
66
+ *
67
+ * `runConfig.costLimitUsd` is enforced against `costInfo.totalCost`, and that
68
+ * total only moves for tokens something has a rate for. A model no rate card
69
+ * covers therefore produced a limit that could never trip — a host that set a
70
+ * cost cap had no cost cap, and nothing said so. That was every run before the
71
+ * price catalogue existed, which is how it went unnoticed.
72
+ *
73
+ * Refusing at the front is the cheap half of the answer: it costs the caller
74
+ * nothing, fires before any spend, and names both ways out. The other half is
75
+ * the `cost_unmeasurable` stop, for the models this cannot see — a step naming
76
+ * its own, or a chain member declaring one.
77
+ *
78
+ * This is the same shape `advisory/budget.ts` already applies to
79
+ * `AdvisoryBudget.maxCostPerRun`, one layer down, and for the same reason. The
80
+ * run path simply never had it.
81
+ */
82
+ function assertBudgetIsMeasurable(params) {
83
+ const limit = params.runConfig.costLimitUsd;
84
+ if (limit === undefined || limit <= 0)
85
+ return;
86
+ // A host-supplied table prices whatever it is pointed at, so a caller who
87
+ // brought one has answered the question themselves.
88
+ if (params.pricing !== undefined)
89
+ return;
90
+ const model = params.runConfig.model;
91
+ if (resolveModelPricing(params.provider.id, model) !== undefined)
92
+ return;
93
+ throw new NamzuError({
94
+ code: 'invalid_config',
95
+ message: `runConfig.costLimitUsd is set to ${limit}, but no rate is known for model "${model}" on ` +
96
+ `provider "${params.provider.id}". The limit is enforced against the run's accumulated ` +
97
+ 'cost, and tokens with no rate never reach that total — so the budget would read as ' +
98
+ 'satisfied for the whole run and stop nothing. Either pass `pricing` to declare the rate ' +
99
+ 'yourself, add the model to packages/sdk/src/pricing/rates.source.json, or drop ' +
100
+ '`costLimitUsd` and bound the run with `tokenBudget`, which is measurable here.',
101
+ details: { model, providerId: params.provider.id, costLimitUsd: limit },
102
+ });
103
+ }
104
+ /**
105
+ * Ask the driver what this model's window is, and never let the answer
106
+ * cost the run.
107
+ *
108
+ * Three outcomes collapse to two here on purpose. No member and a resolved
109
+ * `undefined` both mean "no answer" — the distinction matters to a driver
110
+ * author, not to a caller about to fall through to the table. A rejection
111
+ * is the third, and it is logged rather than propagated: a run that would
112
+ * have worked on the table must not fail because a listing endpoint was
113
+ * down.
114
+ */
115
+ export async function resolveProviderContextWindow(provider, model, signal, timeoutMs, log) {
116
+ if (!provider.resolveContextWindow || !model)
117
+ return undefined;
118
+ if (signal?.aborted)
119
+ return undefined;
120
+ // The resolver is an optional optimisation that runs before RunContext
121
+ // owns its child controller. Give it a private deadline signal and fuse
122
+ // caller cancellation into that transport in the safe direction: neither
123
+ // outcome aborts the caller's controller. Passing a signal is necessary
124
+ // but not sufficient, because a third-party driver can accept it and still
125
+ // leave its promise pending; the race below makes fallback independent of
126
+ // driver cooperation. Promise.race keeps the losing provider promise
127
+ // observed, so a later rejection cannot become unhandled.
128
+ const deadline = new AbortController();
129
+ const resolverSignal = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
130
+ const interrupted = Symbol('provider-context-window-interrupted');
131
+ let onAbort;
132
+ const interruption = new Promise((resolve) => {
133
+ onAbort = () => resolve(interrupted);
134
+ resolverSignal.addEventListener('abort', onAbort, { once: true });
135
+ });
136
+ // Direct QueryParams callers can supply a large run deadline. The clamp
137
+ // avoids Node's >2^31-1 one-millisecond timer coercion during metadata lookup.
138
+ // Metadata discovery remains optional and bounded even without a run deadline.
139
+ const deadlineMs = timeoutMs === 0 ? 5_000 : Math.min(Math.max(0, timeoutMs), 2_147_483_647);
140
+ const timer = setTimeout(() => {
141
+ deadline.abort(new Error(`Provider context-window lookup exceeded ${deadlineMs}ms`));
142
+ }, deadlineMs);
143
+ try {
144
+ const resolution = provider.resolveContextWindow(model, resolverSignal);
145
+ const reported = await Promise.race([resolution, interruption]);
146
+ if (reported === interrupted) {
147
+ if (deadline.signal.aborted) {
148
+ log.debug('Provider context-window lookup timed out; using the table', {
149
+ 'namzu.model.id': model,
150
+ 'namzu.runtime.timeout_ms': deadlineMs,
151
+ });
152
+ }
153
+ return undefined;
154
+ }
155
+ return typeof reported === 'number' && reported > 0 ? reported : undefined;
156
+ }
157
+ catch (err) {
158
+ log.debug('Provider could not report a context window; using the table', {
159
+ 'namzu.model.id': model,
160
+ 'namzu.error.message': toErrorMessage(err),
161
+ });
162
+ return undefined;
163
+ }
164
+ finally {
165
+ clearTimeout(timer);
166
+ if (onAbort)
167
+ resolverSignal.removeEventListener('abort', onAbort);
168
+ }
169
+ }
170
+ /**
171
+ * Project historical system messages exactly as a new run will persist them.
172
+ *
173
+ * Arbitrary historical prompt floors are rebuilt for this run and therefore
174
+ * never reach its provider-bound conversation. Repair must happen AFTER that
175
+ * removal: treating a soon-to-be-dropped system message as a tool-result
176
+ * boundary can replace an exact real result with an invented unknown outcome.
177
+ * The two state-bearing system forms survive; fresh inherited compaction is
178
+ * pinned until this run can prove it reconstructed equivalent state.
179
+ */
180
+ export function projectStateBearingHistory(messages, options) {
181
+ const projected = [];
182
+ for (const message of messages) {
183
+ if (message.role !== 'system') {
184
+ projected.push(message);
185
+ continue;
186
+ }
187
+ if (isCompactionMessage(message.content)) {
188
+ projected.push(options.pinCompaction ? { ...message, retain: true } : message);
189
+ }
190
+ else if (isWorkingMemoryMessage(message.content)) {
191
+ projected.push(message);
192
+ }
193
+ }
194
+ return collapseProjectInstructionSnapshots(projected);
195
+ }
196
+ export async function prepareRun(params) {
197
+ assertMaxToolCalls(params.maxToolCalls);
198
+ // Required types do not protect JavaScript callers. Reject missing scope
199
+ // before opening a budget or persisting a run without its owning identity.
200
+ const missingFields = ['sessionId', 'topicId', 'projectId', 'tenantId'].filter((field) => !params[field]);
201
+ if (missingFields.length > 0) {
202
+ throw new NamzuError({
203
+ code: 'invalid_config',
204
+ message: `query requires sessionId, topicId, projectId, and tenantId; missing: ${missingFields.join(', ')}.`,
205
+ details: { missingFields },
206
+ });
207
+ }
208
+ const selectedResumeState = selectedResumeStates.get(params);
209
+ selectedResumeStates.delete(params);
210
+ // Resolved at the DOOR, before a run id exists or a logger is built.
211
+ // A caller who set both spellings of a renamed field has a config bug,
212
+ // and refusing it here costs them nothing; refusing it at the read site
213
+ // deep in the loop turns the same bug into a mid-run failure, after a
214
+ // provider call has been paid for and a partial transcript written.
215
+ const promptCache = params.promptCache;
216
+ const taskScheduler = params.taskScheduler;
217
+ const streamIdleTimeoutMs = resolveStreamIdleTimeoutMs(params.runConfig.streamIdleTimeoutMs);
218
+ const maxRequestRichContentBytes = resolveMaxRequestRichContentBytes(params.runConfig.maxRequestRichContentBytes);
219
+ const sandboxTeardownTimeoutMs = resolveSandboxTeardownTimeoutMs(params.sandboxTeardownTimeoutMs);
220
+ // Persist the EFFECTIVE value, not only an override. A run replayed after a
221
+ // later release must be able to explain which liveness policy settled it;
222
+ // an absent field whose meaning follows the currently-installed default
223
+ // would rewrite that evidence at read time.
224
+ const runConfig = {
225
+ ...params.runConfig,
226
+ streamIdleTimeoutMs,
227
+ maxRequestRichContentBytes,
228
+ };
229
+ // The run's one correlated logger, built before anything below needs
230
+ // one — the migration check, the retry/fallback wrappers and `ctx`
231
+ // itself all read this SAME object, so a retry warning and the run
232
+ // record it retried for carry the identical `namzu.run.id` instead of
233
+ // three separate `getRootLogger()` reads that happened to agree by
234
+ // accident. `runId` is resolved here, once, rather than left to
235
+ // `build`'s own `config.runId ?? generateRunId()` fallback —
236
+ // generating it twice would silently hand the log and the run two
237
+ // different ids.
238
+ const runId = params.runId ?? generateRunId();
239
+ const budget = await resolveQueryBudget(params, runId, selectedResumeState);
240
+ const log = RunContextFactory.buildLogger({
241
+ agentName: params.agentName,
242
+ runConfig,
243
+ runId,
244
+ parentRunId: params.parentRunId,
245
+ sessionId: params.sessionId,
246
+ topicId: params.topicId,
247
+ projectId: params.projectId,
248
+ tenantId: params.tenantId,
249
+ });
250
+ // Every model call in the run — the loop's turns, the forced-final
251
+ // summary, advisory and compaction side calls — goes through this one
252
+ // wrapped provider, so the retry policy cannot be bypassed by a code
253
+ // path that happens to hold the raw driver.
254
+ // The logger is passed on purpose: `withProviderRetry` guards every one
255
+ // of its warns behind `options.log`, and this is its only production
256
+ // call site — so without it the "failed, retrying" and "failed, giving
257
+ // up" lines were dead code and a backoff left no trace anywhere.
258
+ //
259
+ // With a chain declared, the same sentence holds two levels out. The idle
260
+ // watchdog is applied to each raw member, retry wraps that, and fallback
261
+ // wraps the members: `fallback(retry(idle(m0)), retry(idle(m1)), …)`. The
262
+ // idle layer cannot sit outside retry, because its timer would then count a
263
+ // legitimate backoff as provider silence. This order is not a
264
+ // preference. Assembled the other way round — which is what a host gets if
265
+ // it wraps its own chain and hands the result in, because this function
266
+ // would then wrap THAT in retry — an exhausted chain gets restarted from
267
+ // the head by the outer loop and a throttle on the last member is counted
268
+ // by two budgets. Building it here is what makes the order unspellable
269
+ // wrong.
270
+ const chain = [
271
+ { provider: params.provider },
272
+ ...(params.fallbackProviders ?? []),
273
+ ];
274
+ assertCostIsAttributable(chain, params.pricing);
275
+ assertBudgetIsMeasurable(params);
276
+ const withRecovery = (provider) => {
277
+ const withIdleBound = withStreamIdleTimeout(provider, {
278
+ idleTimeoutMs: streamIdleTimeoutMs,
279
+ log,
280
+ });
281
+ const metered = withTokenBudget(withIdleBound, budget);
282
+ return params.retry === false
283
+ ? metered
284
+ : withProviderRetry(metered, {
285
+ config: params.retry,
286
+ log,
287
+ canRetry: () => budget.remaining > 0,
288
+ });
289
+ };
290
+ // Who is serving right now, for the run RECORD rather than for the request.
291
+ //
292
+ // It starts at the head and moves only when the chain does, which is the
293
+ // whole of the truth because the cursor never rewinds. The run cannot read
294
+ // this off `resilientProvider`: that wrapper reports the head's `id` on
295
+ // purpose, so asking it produces the declaration back — the defect this
296
+ // record exists to fix.
297
+ const serving = {
298
+ current: { index: 0, providerId: params.provider.id },
299
+ };
300
+ const resilientProvider = withProviderFallback(chain.map((member) => ({
301
+ ...member,
302
+ provider: withRecovery(member.provider),
303
+ })), {
304
+ log,
305
+ canFallback: () => budget.remaining > 0,
306
+ onSwap: (to) => {
307
+ serving.current = to;
308
+ // `ctx` is declared below and is initialized before anything can
309
+ // call the provider: this fires from inside a `chatStream`, and
310
+ // the first one is issued by the loop that `ctx` is built for.
311
+ ctx.runMgr.setServingProvider(to.providerId);
312
+ },
313
+ });
314
+ // Asked ONCE, here, before the loop exists. Both readers are synchronous
315
+ // and hot, so this can never move inside the iteration — and a driver
316
+ // that rejects, or one that hangs until the run is cancelled, must not
317
+ // take down a run the table could have served perfectly well. That is
318
+ // why the failure path is a swallow with a log rather than a throw: the
319
+ // window is an optimisation over a working default, not a prerequisite.
320
+ const providerContextWindow = await resolveProviderContextWindow(resilientProvider, runConfig.model, params.signal, runConfig.timeoutMs, log);
321
+ const modelContextWindows = new Map();
322
+ if (runConfig.model)
323
+ modelContextWindows.set(runConfig.model, providerContextWindow);
324
+ // The mode this conversation was left in, when the run config names none.
325
+ // Read once, before the loop exists, for the same reason the context
326
+ // window is: the executor's resolver is synchronous and hot.
327
+ //
328
+ // A store that throws is not a run failure — the run falls back to the
329
+ // config's answer, which is exactly what it did before this existed.
330
+ const topicState = params.topicStateStore
331
+ ? await params.topicStateStore
332
+ .getState(params.topicId, params.tenantId)
333
+ .catch((err) => {
334
+ log.debug('Could not read the topic state; using the run config', {
335
+ 'namzu.topic.id': params.topicId,
336
+ 'namzu.error.message': toErrorMessage(err),
337
+ });
338
+ return null;
339
+ })
340
+ : null;
341
+ // Whatever a host left for "the next run", taken and cleared in one
342
+ // compare-and-set write. Prepended to the messages this run starts from,
343
+ // so it is in the FIRST request rather than arriving a turn late.
344
+ //
345
+ // Cleared as it is read: a queue read and cleared separately re-delivers
346
+ // on a crash between the two, and "start with this" arriving twice is a
347
+ // different instruction from the one that was left.
348
+ const queuedForThisRun = params.topicStateStore
349
+ ? await drainQueuedMessages(params.topicStateStore, params.topicId, params.tenantId).catch((err) => {
350
+ log.debug('Could not drain the topic queue; starting without it', {
351
+ 'namzu.topic.id': params.topicId,
352
+ 'namzu.error.message': toErrorMessage(err),
353
+ });
354
+ return [];
355
+ })
356
+ : [];
357
+ // One effective list, used everywhere the run is seeded from. Three
358
+ // branches below push from it, and computing it at each would be three
359
+ // places to forget the queue.
360
+ //
361
+ // Stored attachments are resolved HERE, once, before the messages reach
362
+ // the run record. Resolving later — at the provider boundary — would put
363
+ // refs in the durable transcript and in every checkpoint, and a run
364
+ // resumed against a store that had since forgotten a ref would fail
365
+ // replaying its own history rather than at the moment somebody asked for
366
+ // the bytes. Every failure refuses: a message that silently lost its
367
+ // image is a model answering about a picture it never saw.
368
+ const seeded = queuedForThisRun.length > 0 ? [...queuedForThisRun, ...params.messages] : params.messages;
369
+ let resolvedInitialMessages;
370
+ let attachmentResolutionCancelled = false;
371
+ try {
372
+ resolvedInitialMessages = [
373
+ ...(await resolveAttachments(seeded, params.attachmentStore, {
374
+ signal: params.signal,
375
+ timeoutMs: params.attachmentResolveTimeoutMs,
376
+ })),
377
+ ];
378
+ params.signal?.throwIfAborted();
379
+ }
380
+ catch (error) {
381
+ // Attachment materialization precedes RunContext construction so stored
382
+ // bytes never enter a live run's checkpoints. Cancellation still belongs
383
+ // to that run: preserve the exact input refs, build the context below, and
384
+ // let its normal terminal path classify/persist a cancelled Run. Every
385
+ // other store failure remains a pre-run refusal.
386
+ if (!params.signal?.aborted || error !== params.signal.reason)
387
+ throw error;
388
+ resolvedInitialMessages = [...seeded];
389
+ attachmentResolutionCancelled = true;
390
+ }
391
+ if (!attachmentResolutionCancelled && params.projectInstructionContext?.prepareInitialSnapshot) {
392
+ const preparationSignal = params.signal ?? new AbortController().signal;
393
+ let snapshot;
394
+ try {
395
+ const prepared = await awaitProjectInstructionCallback(preparationSignal, () => params.projectInstructionContext?.prepareInitialSnapshot?.({
396
+ messages: [...resolvedInitialMessages],
397
+ signal: preparationSignal,
398
+ }));
399
+ // The callback promise can settle, remove its listener, and queue this
400
+ // continuation immediately before a queued abort. Publication is a
401
+ // separate authority boundary, so fence it too.
402
+ preparationSignal.throwIfAborted();
403
+ snapshot = prepared;
404
+ }
405
+ catch (error) {
406
+ // This callback runs before RunContext owns its child controller. A
407
+ // caller cancellation here still belongs to the run: publish no late
408
+ // snapshot and let the context below settle the normal cancelled Run.
409
+ // Compare the exact reason: a callback failure that won first must not
410
+ // be erased merely because cancellation arrived before this catch ran.
411
+ if (!preparationSignal.aborted || error !== preparationSignal.reason)
412
+ throw error;
413
+ }
414
+ if (snapshot !== undefined) {
415
+ resolvedInitialMessages = replaceProjectInstructionSnapshot(resolvedInitialMessages, snapshot, 'before-latest-user');
416
+ }
417
+ }
418
+ const pendingHistoryRepairs = [];
419
+ const projectedInitialMessages = collapseProjectInstructionSnapshots(params.resumeFromCheckpoint || params.continuationMode
420
+ ? resolvedInitialMessages
421
+ : projectStateBearingHistory(resolvedInitialMessages, {
422
+ pinCompaction: true,
423
+ }));
424
+ const initialRepair = params.resumeFromCheckpoint
425
+ ? { messages: projectedInitialMessages, report: undefined }
426
+ : repairToolMessageHistory(projectedInitialMessages);
427
+ const initialMessages = initialRepair.messages;
428
+ if (initialRepair.report && toolHistoryRepairChanged(initialRepair.report)) {
429
+ pendingHistoryRepairs.push({
430
+ source: 'fresh-history',
431
+ report: initialRepair.report,
432
+ });
433
+ log.warn('Repaired provider-invalid tool history before starting the run', {
434
+ [NAMZU.RUN_ID]: runId,
435
+ 'namzu.history.source': 'fresh-history',
436
+ 'namzu.history.duplicate_tool_results_removed': initialRepair.report.duplicateToolResultsRemoved,
437
+ 'namzu.history.orphaned_tool_results_removed': initialRepair.report.orphanedToolResultsRemoved,
438
+ 'namzu.history.synthetic_tool_results_inserted': initialRepair.report.syntheticToolResultsInserted,
439
+ });
440
+ }
441
+ const ctx = RunContextFactory.build({
442
+ budget,
443
+ ...(topicState ? { topicPermissionMode: topicState.permissionMode } : {}),
444
+ ...(params.permissionModeRef ? { permissionModeRef: params.permissionModeRef } : {}),
445
+ agentId: params.agentId,
446
+ agentName: params.agentName,
447
+ runConfig,
448
+ provider: resilientProvider,
449
+ workingDirectory: params.workingDirectory,
450
+ pricing: params.pricing,
451
+ enableActivityTracking: params.enableActivityTracking,
452
+ messages: initialMessages,
453
+ signal: params.signal,
454
+ sessionId: params.sessionId,
455
+ topicId: params.topicId,
456
+ projectId: params.projectId,
457
+ tenantId: params.tenantId,
458
+ pathBuilder: params.pathBuilder,
459
+ checkpointStore: params.checkpointStore,
460
+ runStore: params.runStore,
461
+ runId,
462
+ parentRunId: params.parentRunId,
463
+ depth: params.depth,
464
+ log,
465
+ });
466
+ // Built here because the plan-approval closure below captures it, and
467
+ // its `emit` resolves `eventTranslator` at CALL time — the translator is
468
+ // a `const` some lines further down.
469
+ //
470
+ // The HANDOUT is therefore deliberately NOT here. A host given the box
471
+ // at this point can call `set` synchronously, `emit` reaches
472
+ // `eventTranslator` inside its temporal dead zone, and the run dies
473
+ // before it starts. That is not hypothetical: it is what the first
474
+ // version of this did, and the test that hands out the box and
475
+ // immediately swaps the policy is the one that found it.
476
+ const approvalPolicy = createRunApprovalPolicy({
477
+ runId: ctx.runId,
478
+ initial: {
479
+ // By identity against the default, not by presence. `resumeHandler`
480
+ // is REQUIRED on `QueryParams` — `drainQuery` substitutes
481
+ // `autoApproveHandler` before calling here — so "is it set" is
482
+ // always yes and would name every run `host`, including the ones
483
+ // approving everything unattended. Identity is what actually
484
+ // separates the two.
485
+ name: params.approvalPolicyName ??
486
+ (params.resumeHandler === autoApproveHandler ? AUTO_APPROVE_POLICY_NAME : 'host'),
487
+ handler: params.resumeHandler,
488
+ },
489
+ emit: (event) => eventTranslator.emitEvent(event),
490
+ });
491
+ const planApprovalIds = new Map();
492
+ ctx.planManager.setApprovalHandler(async (request) => {
493
+ let checkpointId = planApprovalIds.get(request.planId);
494
+ if (!checkpointId) {
495
+ checkpointId = generateCheckpointId();
496
+ planApprovalIds.set(request.planId, checkpointId);
497
+ }
498
+ // `.current.handler`, never a captured `params.resumeHandler`. That
499
+ // capture is what made changing the policy mean ending the run.
500
+ const decision = await approvalPolicy.current.handler({
501
+ type: 'plan_approval',
502
+ runId: ctx.runId,
503
+ checkpointId,
504
+ plan: {
505
+ planId: request.planId,
506
+ title: request.title,
507
+ steps: request.steps.map((s, i) => ({
508
+ id: s.id,
509
+ description: s.description,
510
+ toolName: s.toolName,
511
+ agentId: s.agentId,
512
+ dependsOn: s.dependsOn,
513
+ order: s.order ?? i + 1,
514
+ })),
515
+ summary: request.summary,
516
+ },
517
+ });
518
+ if (decision.action === 'approve_plan') {
519
+ // Optional approve-with-edits channel: the host may attach
520
+ // feedback to an approval. `PlanApprovalResponse.feedback`
521
+ // already exists on the type; threading it through lets the
522
+ // coordinator's approve_plan tool surface the user's edits in
523
+ // the same tool_result that unblocks the park. Bare approvals
524
+ // stay byte-identical (`{ approved: true }`).
525
+ return decision.feedback
526
+ ? { approved: true, feedback: decision.feedback }
527
+ : { approved: true };
528
+ }
529
+ if (decision.action === 'reject_plan') {
530
+ return { approved: false, feedback: decision.feedback };
531
+ }
532
+ return { approved: false, feedback: `Action: ${decision.action}` };
533
+ });
534
+ const eventTranslator = new EventTranslator(ctx.runMgr, undefined, ctx.log);
535
+ eventTranslator.wireActivityStore(ctx.activityStore, ctx.runId);
536
+ eventTranslator.wirePlanManager(ctx.planManager, ctx.runId);
537
+ eventTranslator.setGeneration(params.claimFence);
538
+ let interruptHooksStarted = false;
539
+ const executeUserInterruptHooks = async (terminalError) => {
540
+ if (interruptHooksStarted ||
541
+ !params.pluginManager ||
542
+ !isCallerAbortError(terminalError, ctx.abortController.signal) ||
543
+ params.parentRunId !== undefined ||
544
+ (params.depth ?? 0) !== 0 ||
545
+ cancelCauseOf(ctx.abortController.signal.reason) !== 'user') {
546
+ return;
547
+ }
548
+ interruptHooksStarted = true;
549
+ try {
550
+ // Deliberately omit the already-aborted run signal. The lifecycle
551
+ // manager still supplies each handler its own deadline signal, while
552
+ // `run_interrupt`'s observational fan-out prevents one result from
553
+ // suppressing the cleanup hooks that follow it.
554
+ await params.pluginManager.executeHooks('run_interrupt', { runId: ctx.runId, cancelCause: 'user' }, eventTranslator.emitEvent);
555
+ }
556
+ catch (error) {
557
+ // Cancellation is the terminal authority. A hook event sink or an
558
+ // unexpected manager failure is reported, but cannot turn Stop into a
559
+ // failed run or prevent the durable cancellation verdict.
560
+ ctx.log.error('Run interrupt hooks did not settle cleanly', {
561
+ [NAMZU.RUN_ID]: ctx.runId,
562
+ ...errorAttributes(error),
563
+ });
564
+ }
565
+ };
566
+ return {
567
+ runConfig,
568
+ budget,
569
+ log,
570
+ ctx,
571
+ resilientProvider,
572
+ serving,
573
+ providerContextWindow,
574
+ modelContextWindows,
575
+ approvalPolicy,
576
+ eventTranslator,
577
+ executeUserInterruptHooks,
578
+ pendingHistoryRepairs,
579
+ initialMessages,
580
+ queuedForThisRun,
581
+ selectedResumeState,
582
+ attachmentResolutionCancelled,
583
+ streamIdleTimeoutMs,
584
+ sandboxTeardownTimeoutMs,
585
+ promptCache,
586
+ taskScheduler,
587
+ };
588
+ }
589
+ //# sourceMappingURL=prepare-run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare-run.js","sourceRoot":"","sources":["../../../src/runtime/query/prepare-run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAA;AAC5D,OAAO,EAEN,wBAAwB,EACxB,wBAAwB,GACxB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAA;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAC7D,OAAO,EAGN,oBAAoB,GACpB,MAAM,4BAA4B,CAAA;AACnC,OAAO,EAAE,0BAA0B,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAA;AAClG,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAA;AAEhE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAA;AACpE,OAAO,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAA;AAGrD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAA;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAK9D,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAA;AAI/D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,oBAAoB,EAAE,a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