@fabric-harness/sdk 6.10.1 → 6.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/session.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import path from "node:path";
3
4
  import { abandonToolOnAbort } from "./abort.js";
@@ -30,6 +31,7 @@ import { assertProposalToolConfiguration, classifyTools, createProposalCallTrack
30
31
  import { createActivateSkillTool, createBuiltinTools, createCommandTools, hasScopedCommandRenderer, renderScopedCommand, shellQuote, unwrapHookToolRunResult, } from "./tools.js";
31
32
  import { MAX_TASK_DEPTH } from "./types.js";
32
33
  let nextTaskId = 0;
34
+ const promptEventScope = new AsyncLocalStorage();
33
35
  const CROCKFORD_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
34
36
  const AFFINITY_KEY_REGEX = /^aff_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
35
37
  function isResolvedDynamicModelProvider(value) {
@@ -256,6 +258,33 @@ export class StubFabricSession {
256
258
  });
257
259
  }
258
260
  async prompt(text, promptOptions = {}) {
261
+ return promptEventScope.run({ session: this, id: randomUUID() }, () => this.runPrompt(text, promptOptions));
262
+ }
263
+ async runPrompt(text, promptOptions) {
264
+ const metadata = promptOptions.metadata === undefined ? {} : { metadata: promptOptions.metadata };
265
+ const promptData = { text, ...metadata };
266
+ let promptOpen = false;
267
+ const startPrompt = async (role) => {
268
+ promptOpen = true;
269
+ await this.emit("prompt_start", { ...promptData, ...(role ? { role } : {}) });
270
+ };
271
+ const endPrompt = async (result, data) => {
272
+ promptOpen = false;
273
+ await this.emit("prompt_end", {
274
+ ...data,
275
+ ...promptData,
276
+ result: result,
277
+ });
278
+ };
279
+ const failPrompt = async (error) => {
280
+ if (!promptOpen)
281
+ return;
282
+ // Preserve the original prompt failure if an event subscriber also fails.
283
+ await this.emit("prompt_error", {
284
+ ...metadata,
285
+ error: isAbortError(error) ? "Prompt cancelled." : "Prompt failed.",
286
+ }).catch(() => undefined);
287
+ };
259
288
  const ambientSignal = promptOptions.signal === undefined ? currentSubmissionContext()?.signal : undefined;
260
289
  const options = ambientSignal
261
290
  ? { ...promptOptions, signal: ambientSignal }
@@ -303,22 +332,33 @@ export class StubFabricSession {
303
332
  this.refuseProposalToolsOnDurableRuntime(options.tools);
304
333
  // Delegate to the durable runtime; the runtime is responsible for
305
334
  // recording entries / events on its own side. We still emit a single
306
- // local prompt_start/end pair so local subscribers see activity.
307
- await this.emit("prompt_start", { text });
335
+ // local prompt lifecycle so local subscribers see activity.
308
336
  try {
309
- // Checked again here: a prompt_start subscriber ran since the first check.
310
- this.refuseProposalToolsOnDurableRuntime(options.tools);
311
- const forwardedPolicy = this.durablePolicy(options.policy);
312
- const result = await durable.prompt({
313
- text,
314
- options: this.durablePromptOptions(options, forwardedPolicy),
315
- ...(this.options.dynamic ? { dynamic: this.options.dynamic.executionDescriptor() } : {}),
316
- });
317
- await this.emit("prompt_end", { text });
318
- return result;
337
+ await startPrompt();
338
+ try {
339
+ // Checked again here: a prompt_start subscriber ran since the first check.
340
+ this.refuseProposalToolsOnDurableRuntime(options.tools);
341
+ const forwardedPolicy = this.durablePolicy(options.policy);
342
+ const result = await durable.prompt({
343
+ text,
344
+ options: this.durablePromptOptions(options, forwardedPolicy),
345
+ ...(this.options.dynamic
346
+ ? { dynamic: this.options.dynamic.executionDescriptor() }
347
+ : {}),
348
+ });
349
+ await endPrompt(result);
350
+ return result;
351
+ }
352
+ catch (error) {
353
+ await this.emit("error", {
354
+ error: error instanceof Error ? error.message : String(error),
355
+ ...(isAbortError(error) ? { cancelled: true } : {}),
356
+ });
357
+ throw error;
358
+ }
319
359
  }
320
360
  catch (error) {
321
- await this.emit("error", { error: error instanceof Error ? error.message : String(error) });
361
+ await failPrompt(error);
322
362
  throw error;
323
363
  }
324
364
  }
@@ -459,7 +499,7 @@ export class StubFabricSession {
459
499
  // narration was appended between them during worker initialization.
460
500
  const responseStartLeafId = firstRecoveredCall?.parentId ?? responseStartData.leafId;
461
501
  await this.repairDanglingToolCalls(tools, sandbox, options.signal, options.policy);
462
- await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
502
+ await startPrompt(role?.name);
463
503
  // Submission-correlated prompts are idempotent by submission id: a
464
504
  // recovered attempt whose input entry already landed (crash after the
465
505
  // canonical write) resumes from history instead of double-applying.
@@ -550,174 +590,186 @@ export class StubFabricSession {
550
590
  if (options.signal?.aborted)
551
591
  throw promptAbortError(options.signal);
552
592
  await this.recordEntry("result", { result: results });
553
- await this.emit("prompt_end", { text, result: results });
554
593
  const value = await validateResult(results, options.result, options.resultExtraction);
555
594
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, undefined, submissionCorrelation);
556
595
  if (finalized.continued) {
557
596
  throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
558
597
  }
598
+ await endPrompt(finalized.value);
559
599
  return finalized.value;
560
600
  }
561
601
  // Use tool-based result extraction when a validator is provided and the caller
562
602
  // has not explicitly opted into delimiter-based extraction.
563
603
  const useResultTools = options.result !== undefined && options.resultExtraction === undefined;
564
604
  const runtime = options.loopRuntime ?? this.options.loopRuntime ?? defaultLoopRuntime;
565
- const runRuntime = () => runtime.runPrompt({
566
- sessionId: this.id,
567
- ...(streamRecovery ? { streamRecovery: "replace" } : {}),
568
- ...(sessionData.affinityKey !== undefined
569
- ? { affinityKey: sessionData.affinityKey }
570
- : {}),
571
- text,
572
- ...(options.submission?.message !== undefined
573
- ? { delivery: options.submission.message }
574
- : {}),
575
- messages,
576
- tools,
577
- sandbox,
578
- ...(typeof (options.model ?? this.options.model ?? this.agent.model) === "string"
579
- ? { model: (options.model ?? this.options.model ?? this.agent.model) }
580
- : {}),
581
- ...((options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel) !==
582
- undefined
583
- ? {
584
- thinkingLevel: options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel,
585
- }
586
- : {}),
587
- ...((options.modelProvider ?? this.options.modelProvider) !== undefined
588
- ? { modelProvider: options.modelProvider ?? this.options.modelProvider }
589
- : {}),
590
- ...(options.maxIterations !== undefined ? { maxIterations: options.maxIterations } : {}),
591
- ...(options.modelTimeoutMs !== undefined
592
- ? { modelTimeoutMs: options.modelTimeoutMs }
593
- : {}),
594
- ...(options.modelRetries !== undefined ? { modelRetries: options.modelRetries } : {}),
595
- ...(options.modelRetryDelayMs !== undefined
596
- ? { modelRetryDelayMs: options.modelRetryDelayMs }
597
- : {}),
598
- ...((options.stopReasonGuard ?? this.options.stopReasonGuard) !== undefined
599
- ? { stopReasonGuard: options.stopReasonGuard ?? this.options.stopReasonGuard }
600
- : {}),
601
- ...(options.signal !== undefined ? { signal: options.signal } : {}),
602
- ...(options.policy !== undefined ? { policy: options.policy } : {}),
603
- ...((options.approvalTimeoutMs ?? this.options.approvalTimeoutMs) !== undefined
604
- ? { approvalTimeoutMs: options.approvalTimeoutMs ?? this.options.approvalTimeoutMs }
605
- : {}),
606
- ...(this.costBudget.enabled()
607
- ? {
608
- costBudget: this.costBudget,
609
- requestCostLimitApproval: (ctx) => this.requestCostLimitApproval(ctx, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval),
610
- }
611
- : {}),
612
- ...(useResultTools ? { resultValidator: options.result } : {}),
613
- agentId: this.agent.id,
614
- ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
615
- ...(options.submission?.takeJoinedInputs
616
- ? {
617
- takeSteeringMessages: async () => {
618
- const inputs = await options.submission?.takeJoinedInputs?.();
619
- if (!inputs?.length)
620
- return [];
621
- const messages = [];
622
- for (const input of inputs) {
623
- if (input.message && renderDeliveredMessage(input.message) !== input.text) {
624
- throw new FabricError({
625
- code: "INVALID_CONFIG",
626
- message: "A joined durable submission message does not match its rendered prompt text. " +
627
- "Refusing to persist and execute contradictory inputs.",
628
- publicMessage: "A joined durable submission input is inconsistent.",
629
- });
630
- }
631
- const current = await this.history();
632
- const exists = (current.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
633
- entry.data?.submissionId === input.submissionId);
634
- if (!exists) {
635
- if (input.message?.kind === "signal") {
636
- await this.recordEntry("signal", {
637
- ...deliveredSignalToEntryData(input.message),
638
- submissionId: input.submissionId,
605
+ let runtimeEndData;
606
+ const runRuntime = () => {
607
+ runtimeEndData = undefined;
608
+ return runtime.runPrompt({
609
+ sessionId: this.id,
610
+ ...(streamRecovery ? { streamRecovery: "replace" } : {}),
611
+ ...(sessionData.affinityKey !== undefined
612
+ ? { affinityKey: sessionData.affinityKey }
613
+ : {}),
614
+ text,
615
+ ...(options.submission?.message !== undefined
616
+ ? { delivery: options.submission.message }
617
+ : {}),
618
+ messages,
619
+ tools,
620
+ sandbox,
621
+ ...(typeof (options.model ?? this.options.model ?? this.agent.model) === "string"
622
+ ? { model: (options.model ?? this.options.model ?? this.agent.model) }
623
+ : {}),
624
+ ...((options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel) !==
625
+ undefined
626
+ ? {
627
+ thinkingLevel: options.thinkingLevel ?? this.options.thinkingLevel ?? this.agent.thinkingLevel,
628
+ }
629
+ : {}),
630
+ ...((options.modelProvider ?? this.options.modelProvider) !== undefined
631
+ ? { modelProvider: options.modelProvider ?? this.options.modelProvider }
632
+ : {}),
633
+ ...(options.maxIterations !== undefined ? { maxIterations: options.maxIterations } : {}),
634
+ ...(options.modelTimeoutMs !== undefined
635
+ ? { modelTimeoutMs: options.modelTimeoutMs }
636
+ : {}),
637
+ ...(options.modelRetries !== undefined ? { modelRetries: options.modelRetries } : {}),
638
+ ...(options.modelRetryDelayMs !== undefined
639
+ ? { modelRetryDelayMs: options.modelRetryDelayMs }
640
+ : {}),
641
+ ...((options.stopReasonGuard ?? this.options.stopReasonGuard) !== undefined
642
+ ? { stopReasonGuard: options.stopReasonGuard ?? this.options.stopReasonGuard }
643
+ : {}),
644
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
645
+ ...(options.policy !== undefined ? { policy: options.policy } : {}),
646
+ ...((options.approvalTimeoutMs ?? this.options.approvalTimeoutMs) !== undefined
647
+ ? { approvalTimeoutMs: options.approvalTimeoutMs ?? this.options.approvalTimeoutMs }
648
+ : {}),
649
+ ...(this.costBudget.enabled()
650
+ ? {
651
+ costBudget: this.costBudget,
652
+ requestCostLimitApproval: (ctx) => this.requestCostLimitApproval(ctx, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval),
653
+ }
654
+ : {}),
655
+ ...(useResultTools ? { resultValidator: options.result } : {}),
656
+ agentId: this.agent.id,
657
+ ...(this.options.tenantId !== undefined ? { tenantId: this.options.tenantId } : {}),
658
+ ...(options.submission?.takeJoinedInputs
659
+ ? {
660
+ takeSteeringMessages: async () => {
661
+ const inputs = await options.submission?.takeJoinedInputs?.();
662
+ if (!inputs?.length)
663
+ return [];
664
+ const messages = [];
665
+ for (const input of inputs) {
666
+ if (input.message && renderDeliveredMessage(input.message) !== input.text) {
667
+ throw new FabricError({
668
+ code: "INVALID_CONFIG",
669
+ message: "A joined durable submission message does not match its rendered prompt text. " +
670
+ "Refusing to persist and execute contradictory inputs.",
671
+ publicMessage: "A joined durable submission input is inconsistent.",
639
672
  });
640
- messages.push({ role: "user", content: input.text });
641
673
  }
642
- else {
643
- const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
644
- await this.recordEntry("user_prompt", {
645
- text: input.text,
646
- submissionId: input.submissionId,
647
- ...(joinedAttachments.records.length > 0
648
- ? { attachments: joinedAttachments.records }
649
- : {}),
650
- });
651
- const [joinedMessage] = await hydrateModelMessageAttachments([
652
- {
653
- role: "user",
654
- content: input.text,
674
+ const current = await this.history();
675
+ const exists = (current.entries ?? []).some((entry) => (entry.type === "user_prompt" || entry.type === "signal") &&
676
+ entry.data?.submissionId === input.submissionId);
677
+ if (!exists) {
678
+ if (input.message?.kind === "signal") {
679
+ await this.recordEntry("signal", {
680
+ ...deliveredSignalToEntryData(input.message),
681
+ submissionId: input.submissionId,
682
+ });
683
+ messages.push({ role: "user", content: input.text });
684
+ }
685
+ else {
686
+ const joinedAttachments = await this.prepareInputAttachments([], input.message, input.submissionId);
687
+ await this.recordEntry("user_prompt", {
688
+ text: input.text,
689
+ submissionId: input.submissionId,
655
690
  ...(joinedAttachments.records.length > 0
656
- ? {
657
- attachments: recordsToModelAttachments(joinedAttachments.records),
658
- }
691
+ ? { attachments: joinedAttachments.records }
659
692
  : {}),
660
- },
661
- ], {
662
- store: this.attachmentStore(),
663
- scope: this.id,
664
- inflight: joinedAttachments.inflight,
665
- // Charged against the running request's allowance,
666
- // not a fresh 50 MiB per joined input.
667
- budget: hydrationBudget,
693
+ });
694
+ const [joinedMessage] = await hydrateModelMessageAttachments([
695
+ {
696
+ role: "user",
697
+ content: input.text,
698
+ ...(joinedAttachments.records.length > 0
699
+ ? {
700
+ attachments: recordsToModelAttachments(joinedAttachments.records),
701
+ }
702
+ : {}),
703
+ },
704
+ ], {
705
+ store: this.attachmentStore(),
706
+ scope: this.id,
707
+ inflight: joinedAttachments.inflight,
708
+ // Charged against the running request's allowance,
709
+ // not a fresh 50 MiB per joined input.
710
+ budget: hydrationBudget,
711
+ });
712
+ if (joinedMessage)
713
+ messages.push(joinedMessage);
714
+ }
715
+ }
716
+ if (input.message && dynamic) {
717
+ await refreshDynamic({
718
+ delivery: input.message,
668
719
  });
669
- if (joinedMessage)
670
- messages.push(joinedMessage);
720
+ const lifecycleSignals = await dynamic?.runAgentStart({
721
+ ...(options.signal ? { signal: options.signal } : {}),
722
+ sandbox,
723
+ submissionId: input.submissionId,
724
+ });
725
+ for (const signal of lifecycleSignals ?? []) {
726
+ messages.push({ role: "user", content: renderDeliveredMessage(signal) });
727
+ }
728
+ joinedRenderReady = true;
671
729
  }
730
+ await input.onInputApplied();
672
731
  }
673
- if (input.message && dynamic) {
674
- await refreshDynamic({
675
- delivery: input.message,
676
- });
677
- const lifecycleSignals = await dynamic?.runAgentStart({
678
- ...(options.signal ? { signal: options.signal } : {}),
679
- sandbox,
680
- submissionId: input.submissionId,
681
- });
682
- for (const signal of lifecycleSignals ?? []) {
683
- messages.push({ role: "user", content: renderDeliveredMessage(signal) });
684
- }
685
- joinedRenderReady = true;
732
+ return messages;
733
+ },
734
+ }
735
+ : {}),
736
+ ...(dynamic
737
+ ? {
738
+ refreshTurn: async () => {
739
+ if (joinedRenderReady) {
740
+ joinedRenderReady = false;
741
+ return currentTurnConfiguration();
686
742
  }
687
- await input.onInputApplied();
688
- }
689
- return messages;
690
- },
691
- }
692
- : {}),
693
- ...(dynamic
694
- ? {
695
- refreshTurn: async () => {
696
- if (joinedRenderReady) {
697
- joinedRenderReady = false;
698
- return currentTurnConfiguration();
699
- }
700
- return refreshDynamic();
701
- },
702
- }
703
- : {}),
704
- executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
705
- // The prompt's policy wins (call over session over agent). A loop may pass none for
706
- // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
707
- options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
708
- recordToolAdditions: async (toolCallId, names) => {
709
- if (names.length === 0)
710
- return;
711
- await this.recordEntry("signal", {
712
- signalType: "resources.tool_additions",
713
- content: "Conditional tools became available after this tool result.",
714
- toolCallId,
715
- names,
716
- });
717
- },
718
- recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
719
- emit: (type, data) => streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data),
720
- });
743
+ return refreshDynamic();
744
+ },
745
+ }
746
+ : {}),
747
+ executeToolCalls: (calls, policy, approvalTimeoutMs, attribution) => this.executeToolCalls(calls, tools, sandbox,
748
+ // The prompt's policy wins (call over session over agent). A loop may pass none for
749
+ // model-issued calls, and a dynamic agent's turn refresh passes its rendered agent policy.
750
+ options.policy ?? policy, approvalTimeoutMs, options.onApproval, attribution, options.signal, undefined, streamRecovery ? (data) => streamRecovery.record("tool_call", data) : undefined),
751
+ recordToolAdditions: async (toolCallId, names) => {
752
+ if (names.length === 0)
753
+ return;
754
+ await this.recordEntry("signal", {
755
+ signalType: "resources.tool_additions",
756
+ content: "Conditional tools became available after this tool result.",
757
+ toolCallId,
758
+ names,
759
+ });
760
+ },
761
+ recordEntry: (type, data) => streamRecovery ? streamRecovery.record(type, data) : this.recordEntry(type, data),
762
+ // A runtime can finish more than once during validation retries or
763
+ // finish-hook continuations. The session emits the terminal event.
764
+ emit: async (type, data) => {
765
+ if (type === "prompt_end") {
766
+ runtimeEndData = data;
767
+ return;
768
+ }
769
+ await (streamRecovery ? streamRecovery.emit(type, data) : this.emit(type, data));
770
+ },
771
+ });
772
+ };
721
773
  let result;
722
774
  try {
723
775
  result = await runRuntime();
@@ -800,6 +852,10 @@ export class StubFabricSession {
800
852
  }
801
853
  const finalized = await this.finalizeDynamicResult(value, responseStartLeafId, result.usage, submissionCorrelation);
802
854
  if (!finalized.continued) {
855
+ await endPrompt(finalized.value, {
856
+ ...runtimeEndData,
857
+ ...(result.terminatedByTool ? { terminatedByTool: true } : {}),
858
+ });
803
859
  if (result.terminatedByTool)
804
860
  await this.compactAfterTermination(role, options);
805
861
  return finalized.value;
@@ -814,6 +870,10 @@ export class StubFabricSession {
814
870
  result = await runRuntime();
815
871
  }
816
872
  }
873
+ catch (error) {
874
+ await failPrompt(error);
875
+ throw error;
876
+ }
817
877
  finally {
818
878
  if (promptSubscriber)
819
879
  this.eventSubscribers.delete(promptSubscriber);
@@ -3246,6 +3306,7 @@ export class StubFabricSession {
3246
3306
  await this.ensureData();
3247
3307
  const submission = currentSubmissionContext();
3248
3308
  const agentName = this.agent.name ?? submission?.agent;
3309
+ const prompt = promptEventScope.getStore();
3249
3310
  const event = {
3250
3311
  id: `${this.id}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
3251
3312
  type,
@@ -3255,7 +3316,11 @@ export class StubFabricSession {
3255
3316
  ...(agentName ? { agentName } : {}),
3256
3317
  ...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
3257
3318
  ...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
3258
- ...(data ? { data } : {}),
3319
+ ...(prompt?.session === this
3320
+ ? { data: { ...data, promptRunId: prompt.id } }
3321
+ : data
3322
+ ? { data }
3323
+ : {}),
3259
3324
  };
3260
3325
  await this.store.appendEvent?.(this.id, event);
3261
3326
  await this.options.onEvent?.(event);