omk-agent-core 0.98.2 → 0.98.3

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 (61) hide show
  1. package/CHANGELOG.md +644 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +3 -5
  4. package/dist/agent.js.map +1 -1
  5. package/dist/effects/effect-journal.d.ts +43 -0
  6. package/dist/effects/effect-journal.d.ts.map +1 -0
  7. package/dist/effects/effect-journal.js +186 -0
  8. package/dist/effects/effect-journal.js.map +1 -0
  9. package/dist/effects/effect-recovery.d.ts +70 -0
  10. package/dist/effects/effect-recovery.d.ts.map +1 -0
  11. package/dist/effects/effect-recovery.js +120 -0
  12. package/dist/effects/effect-recovery.js.map +1 -0
  13. package/dist/effects/effect-transitions.d.ts +34 -0
  14. package/dist/effects/effect-transitions.d.ts.map +1 -0
  15. package/dist/effects/effect-transitions.js +148 -0
  16. package/dist/effects/effect-transitions.js.map +1 -0
  17. package/dist/effects/effect-types.d.ts +135 -0
  18. package/dist/effects/effect-types.d.ts.map +1 -0
  19. package/dist/effects/effect-types.js +32 -0
  20. package/dist/effects/effect-types.js.map +1 -0
  21. package/dist/harness/abort-delivery.d.ts +26 -0
  22. package/dist/harness/abort-delivery.d.ts.map +1 -0
  23. package/dist/harness/abort-delivery.js +36 -0
  24. package/dist/harness/abort-delivery.js.map +1 -0
  25. package/dist/harness/agent-harness.d.ts +18 -0
  26. package/dist/harness/agent-harness.d.ts.map +1 -1
  27. package/dist/harness/agent-harness.js +37 -28
  28. package/dist/harness/agent-harness.js.map +1 -1
  29. package/dist/harness/canonical-digest.d.ts +32 -0
  30. package/dist/harness/canonical-digest.d.ts.map +1 -0
  31. package/dist/harness/canonical-digest.js +164 -0
  32. package/dist/harness/canonical-digest.js.map +1 -0
  33. package/dist/harness/deferred-commands.d.ts +53 -0
  34. package/dist/harness/deferred-commands.d.ts.map +1 -0
  35. package/dist/harness/deferred-commands.js +96 -0
  36. package/dist/harness/deferred-commands.js.map +1 -0
  37. package/dist/harness/operation-outcome.d.ts +18 -10
  38. package/dist/harness/operation-outcome.d.ts.map +1 -1
  39. package/dist/harness/operation-outcome.js +71 -35
  40. package/dist/harness/operation-outcome.js.map +1 -1
  41. package/dist/harness/operation-trace-divergence.d.ts +60 -0
  42. package/dist/harness/operation-trace-divergence.d.ts.map +1 -0
  43. package/dist/harness/operation-trace-divergence.js +199 -0
  44. package/dist/harness/operation-trace-divergence.js.map +1 -0
  45. package/dist/harness/operation-trace.d.ts +134 -0
  46. package/dist/harness/operation-trace.d.ts.map +1 -0
  47. package/dist/harness/operation-trace.js +161 -0
  48. package/dist/harness/operation-trace.js.map +1 -0
  49. package/dist/harness/subscriber-fanout.d.ts +14 -1
  50. package/dist/harness/subscriber-fanout.d.ts.map +1 -1
  51. package/dist/harness/subscriber-fanout.js +25 -6
  52. package/dist/harness/subscriber-fanout.js.map +1 -1
  53. package/dist/index.d.ts +2 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +2 -0
  56. package/dist/index.js.map +1 -1
  57. package/dist/listener-delivery.d.ts +22 -0
  58. package/dist/listener-delivery.d.ts.map +1 -0
  59. package/dist/listener-delivery.js +36 -0
  60. package/dist/listener-delivery.js.map +1 -0
  61. package/package.json +4 -3
@@ -1,13 +1,15 @@
1
1
  import { isContextOverflow, streamSimple, } from "omk-ai";
2
2
  import { runAgentLoop, runAgentLoopContinue } from "../agent-loop.js";
3
+ import { assertAbortAllowed, describeAbortDelivery } from "./abort-delivery.js";
3
4
  import { collectEntriesForBranchSummary } from "./compaction/branch-summarization.js";
4
5
  import { compact, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, prepareCompaction, shouldCompact, } from "./compaction/compaction.js";
6
+ import { DeferredCommandQueue } from "./deferred-commands.js";
5
7
  import { HarnessSessionFacade } from "./harness-session.js";
6
8
  import { convertToLlm, createFailureMessage, createUserMessage } from "./messages.js";
7
9
  import { findDuplicateNames } from "./name-validation.js";
8
10
  import { OperationLifecycleController, } from "./operation-lifecycle-controller.js";
9
11
  import { PROMPT_FAMILY_KINDS, } from "./operation-lifecycle-types.js";
10
- import { classifyAssistantOutcome, classifyAttemptFailure, classifyAttemptOutcome, classifyNavigateTreeOutcome, combineBoundaryErrors, normalizeHarnessError, resolveOperationFailure, resolveOperationOutcome, } from "./operation-outcome.js";
12
+ import { classifyAssistantOutcome, classifyAttemptFailure, classifyAttemptOutcome, classifyNavigateTreeOutcome, collectStepErrors, combineBoundaryErrors, normalizeHarnessError, resolveOperationFailure, resolveOperationOutcome, } from "./operation-outcome.js";
11
13
  import { formatPromptTemplateInvocation } from "./prompt-templates.js";
12
14
  import { uuidv7 } from "./session/uuid.js";
13
15
  import { SessionWriteCoordinator } from "./session-write-coordinator.js";
@@ -39,6 +41,7 @@ export class AgentHarness {
39
41
  nextTurnQueue = [];
40
42
  handlers = new Map();
41
43
  subscribers = new SubscriberFanout();
44
+ deferredCommands = new DeferredCommandQueue(() => this.lifecycle.getSnapshot().tag === "idle");
42
45
  constructor(options) {
43
46
  this.env = options.env;
44
47
  this.session = options.session;
@@ -223,6 +226,10 @@ export class AgentHarness {
223
226
  catch (error) {
224
227
  settleError = error;
225
228
  }
229
+ // Deferred commands registered from this operation's callbacks run now that
230
+ // the lifecycle is idle. Not awaited: this call's result must not depend on
231
+ // work a listener scheduled.
232
+ void this.deferredCommands.drain();
226
233
  const failure = resolveOperationFailure({ bodyError, flushError, settleError, fallbackCode });
227
234
  if (failure !== undefined)
228
235
  throw failure;
@@ -889,42 +896,44 @@ export class AgentHarness {
889
896
  async setStreamOptions(streamOptions) {
890
897
  this.streamOptions = cloneStreamOptions(streamOptions);
891
898
  }
899
+ /**
900
+ * Deliver the abort signal to the current operation without waiting for it to
901
+ * settle. Safe from an operation's own callbacks: nothing here awaits
902
+ * settlement, so it cannot form the cycle `abort()` has to refuse.
903
+ */
904
+ requestAbort() {
905
+ assertAbortAllowed(this.lifecycle.getSnapshot());
906
+ return describeAbortDelivery(this.lifecycle.requestAbort());
907
+ }
908
+ /**
909
+ * Queue work to run once the harness is idle and return its ref immediately.
910
+ *
911
+ * This is the callback-safe way to schedule follow-up work: awaiting
912
+ * `waitForIdle()` or `abort()` from a callback of the operation being settled
913
+ * deadlocks, because settlement awaits that callback. The ref reports the
914
+ * command's outcome and cancels it while it is still queued.
915
+ */
916
+ async runWhenIdle(command) {
917
+ return this.deferredCommands.enqueue(command);
918
+ }
892
919
  async abort() {
893
920
  // Aborting awaits the captured operation's settlement, so a listener of that
894
921
  // same operation must never reach the wait below.
895
922
  this.rejectCurrentOperationSelfWait("abort()");
896
- const snapshot = this.lifecycle.getSnapshot();
897
- if (snapshot.tag === "active" && snapshot.operation.kind === "manual_compaction") {
898
- throw new AgentHarnessError("invalid_state", "Cannot abort during compaction");
899
- }
900
- if (snapshot.tag === "active" && snapshot.operation.kind === "tree_navigation") {
901
- throw new AgentHarnessError("invalid_state", "Cannot abort during branch_summary");
902
- }
923
+ assertAbortAllowed(this.lifecycle.getSnapshot());
903
924
  // Capture the current operation before delivering any signal: an operation
904
925
  // started later by a settlement listener is never this call's target.
905
926
  const capture = this.lifecycle.requestAbort();
906
927
  const clearedSteer = this.steerQueue.splice(0);
907
928
  const clearedFollowUp = this.followUpQueue.splice(0);
908
- const errors = [];
909
- try {
910
- await this.emitQueueUpdate();
911
- }
912
- catch (error) {
913
- errors.push(toError(error));
914
- }
915
- try {
916
- if (capture.target)
917
- await capture.target.settled;
918
- }
919
- catch (error) {
920
- errors.push(toError(error));
921
- }
922
- try {
923
- await this.emitOwn({ type: "abort", clearedSteer, clearedFollowUp });
924
- }
925
- catch (error) {
926
- errors.push(toError(error));
927
- }
929
+ const errors = await collectStepErrors([
930
+ () => this.emitQueueUpdate(),
931
+ async () => {
932
+ if (capture.target)
933
+ await capture.target.settled;
934
+ },
935
+ () => this.emitOwn({ type: "abort", clearedSteer, clearedFollowUp }),
936
+ ]);
928
937
  if (errors.length > 0) {
929
938
  const cause = errors.length === 1 ? errors[0] : new AggregateError(errors, "Abort completed with errors");
930
939
  throw normalizeHarnessError(cause, "hook");
@@ -1 +1 @@
1
- {"version":3,"file":"agent-harness.js","sourceRoot":"","sources":["../../src/harness/agent-harness.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,iBAAiB,EAEjB,YAAY,GAEZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAWtE,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AACtF,OAAO,EACN,OAAO,EACP,2BAA2B,EAC3B,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,GACb,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAGN,4BAA4B,GAC5B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAKN,mBAAmB,GACnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACN,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACvB,uBAAuB,GACvB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAA2B,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAChG,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CA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E,YAAY,EAAE,eAAe,EAAE,CAAC;IAAA,CACzC;IAED,KAAK,CAAC,WAAW,GAAkB;QAClC,IAAI,CAAC,8BAA8B,CAAC,eAAe,CAAC,CAAC;QACrD,gFAAgF;QAChF,MAAM,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;IAAA,CACnC;IAED,SAAS,CACR,QAA2G,EAC9F;QACb,OAAO,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAAA,CAC5C;IAED,EAAE,CACD,IAAW,EACX,OAEmF,EACtE;QACb,IAAI,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACvC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;YACrB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACnC,CAAC;QACD,QAAQ,CAAC,GAAG,CAAC,OAA8B,CAAC,CAAC;QAC7C,OAAO,GAAG,EAAE,CAAC,QAAS,CAAC,MAAM,CAAC,OAA8B,CAAC,CAAC;IAAA,CAC9D;CACD","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype Context,\n\ttype ImageContent,\n\tisContextOverflow,\n\ttype Model,\n\tstreamSimple,\n\ttype UserMessage,\n} from \"omk-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"../agent-loop.ts\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tQueueMode,\n\tStreamFn,\n\tThinkingLevel,\n} from \"../types.ts\";\nimport { collectEntriesForBranchSummary } from \"./compaction/branch-summarization.ts\";\nimport {\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\tprepareCompaction,\n\tshouldCompact,\n} from \"./compaction/compaction.ts\";\nimport type { HarnessCompactionRunOptions } from \"./compaction/operation.ts\";\nimport { HarnessSessionFacade } from \"./harness-session.ts\";\nimport { convertToLlm, createFailureMessage, createUserMessage } from \"./messages.ts\";\nimport { findDuplicateNames } from \"./name-validation.ts\";\nimport {\n\ttype AttemptLease,\n\ttype OperationLease,\n\tOperationLifecycleController,\n} from \"./operation-lifecycle-controller.ts\";\nimport {\n\ttype HarnessAttemptOutcome,\n\ttype HarnessAttemptReason,\n\ttype HarnessOperationKind,\n\ttype HarnessOperationOutcome,\n\tPROMPT_FAMILY_KINDS,\n} from \"./operation-lifecycle-types.ts\";\nimport {\n\tclassifyAssistantOutcome,\n\tclassifyAttemptFailure,\n\tclassifyAttemptOutcome,\n\tclassifyNavigateTreeOutcome,\n\tcombineBoundaryErrors,\n\tnormalizeHarnessError,\n\tresolveOperationFailure,\n\tresolveOperationOutcome,\n} from \"./operation-outcome.ts\";\nimport { formatPromptTemplateInvocation } from \"./prompt-templates.ts\";\nimport { uuidv7 } from \"./session/uuid.ts\";\nimport { type QueuedSessionWrite, SessionWriteCoordinator } from \"./session-write-coordinator.ts\";\nimport { formatSkillInvocation } from \"./skills.ts\";\nimport { applyStreamOptionsPatch, cloneStreamOptions, mergeHeaders } from \"./stream-options.ts\";\nimport { SubscriberFanout } from \"./subscriber-fanout.ts\";\nimport { createSummarizationRetry } from \"./summarization-retry.ts\";\nimport { resolveNavigationTarget, runBranchSummary } from \"./tree-navigation.ts\";\nimport type {\n\tAbortResult,\n\tAgentHarnessEvent,\n\tAgentHarnessEventResultMap,\n\tAgentHarnessOptions,\n\tAgentHarnessOwnEvent,\n\tAgentHarnessPhase,\n\tAgentHarnessResources,\n\tAgentHarnessStreamOptions,\n\tCompactionSettings,\n\tCompactResult,\n\tExecutionEnv,\n\tHarnessSession,\n\tNavigateTreeResult,\n\tPromptTemplate,\n\tSession,\n\tSkill,\n} from \"./types.ts\";\nimport { AgentHarnessError, toError } from \"./types.ts\";\n\ntype AgentHarnessHandler = (event: any, signal?: AbortSignal) => Promise<any> | any;\n\ninterface AgentHarnessTurnState<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tmessages: AgentMessage[];\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tstreamOptions: AgentHarnessStreamOptions;\n\tsessionId: string;\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: TTool[];\n\tactiveTools: TTool[];\n}\n\nexport class AgentHarness<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\treadonly env: ExecutionEnv;\n\tprivate session: Session;\n\tprivate readonly sessionFacade: HarnessSession;\n\tprivate readonly lifecycle: OperationLifecycleController;\n\tprivate readonly sessionWrites: SessionWriteCoordinator<AgentMessage>;\n\tprivate model: Model<any>;\n\tprivate thinkingLevel: ThinkingLevel;\n\tprivate systemPrompt: AgentHarnessOptions<TSkill, TPromptTemplate, TTool>[\"systemPrompt\"];\n\tprivate streamOptions: AgentHarnessStreamOptions;\n\tprivate compactionSettings: CompactionSettings;\n\tprivate getApiKeyAndHeaders?: AgentHarnessOptions[\"getApiKeyAndHeaders\"];\n\tprivate resources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tprivate tools = new Map<string, TTool>();\n\tprivate activeToolNames: string[];\n\tprivate steerQueue: UserMessage[] = [];\n\tprivate steeringQueueMode: QueueMode;\n\tprivate followUpQueue: UserMessage[] = [];\n\tprivate followUpQueueMode: QueueMode;\n\tprivate nextTurnQueue: AgentMessage[] = [];\n\tprivate handlers = new Map<string, Set<AgentHarnessHandler>>();\n\tprivate readonly subscribers = new SubscriberFanout<AgentHarnessEvent<TSkill, TPromptTemplate>>();\n\n\tconstructor(options: AgentHarnessOptions<TSkill, TPromptTemplate, TTool>) {\n\t\tthis.env = options.env;\n\t\tthis.session = options.session;\n\t\tthis.sessionWrites = new SessionWriteCoordinator(this.session);\n\t\tthis.lifecycle = new OperationLifecycleController({\n\t\t\tcreateOperationId: () => uuidv7(),\n\t\t\tnow: () => Date.now(),\n\t\t});\n\t\tthis.sessionFacade = new HarnessSessionFacade(this.session, () => this.currentPhase(), this.sessionWrites);\n\t\tthis.resources = options.resources ?? {};\n\t\tthis.streamOptions = cloneStreamOptions(options.streamOptions);\n\t\tthis.compactionSettings = { ...DEFAULT_COMPACTION_SETTINGS, ...options.compaction };\n\t\tthis.systemPrompt = options.systemPrompt;\n\t\tthis.getApiKeyAndHeaders = options.getApiKeyAndHeaders;\n\t\tthis.validateUniqueNames(\n\t\t\t(options.tools ?? []).map((tool) => tool.name),\n\t\t\t\"Duplicate tool name(s)\",\n\t\t);\n\t\tfor (const tool of options.tools ?? []) {\n\t\t\tthis.tools.set(tool.name, tool);\n\t\t}\n\t\tthis.model = options.model;\n\t\tthis.thinkingLevel = options.thinkingLevel ?? \"off\";\n\t\tthis.activeToolNames = options.activeToolNames\n\t\t\t? [...options.activeToolNames]\n\t\t\t: (options.tools ?? []).map((tool) => tool.name);\n\t\tthis.validateUniqueNames(this.activeToolNames, \"Duplicate active tool name(s)\");\n\t\tthis.validateToolNames(this.activeToolNames);\n\t\tthis.steeringQueueMode = options.steeringMode ?? \"one-at-a-time\";\n\t\tthis.followUpQueueMode = options.followUpMode ?? \"one-at-a-time\";\n\t}\n\n\tprivate async emitOwn(event: AgentHarnessOwnEvent<TSkill, TPromptTemplate>, signal?: AbortSignal): Promise<void> {\n\t\tawait this.emitAny(event as AgentHarnessEvent<TSkill, TPromptTemplate>, signal);\n\t}\n\n\t/** Subscriber fan-out; the self-wait barrier lives in `SubscriberFanout`. */\n\tprivate async emitAny(event: AgentHarnessEvent<TSkill, TPromptTemplate>, signal?: AbortSignal): Promise<void> {\n\t\tawait this.subscribers.emit(event, this.lifecycle.getCurrentOperation()?.operationId, signal);\n\t}\n\n\t/** Fail closed when an awaited listener tries to wait on its own operation. */\n\tprivate rejectCurrentOperationSelfWait(api: string): void {\n\t\tthis.subscribers.assertNotSelfWait(api, this.lifecycle.getCurrentOperation()?.operationId);\n\t}\n\n\tprivate async emitHook<TType extends keyof AgentHarnessEventResultMap>(\n\t\tevent: Extract<AgentHarnessOwnEvent, { type: TType }>,\n\t): Promise<AgentHarnessEventResultMap[TType] | undefined> {\n\t\tconst handlers = this.handlers.get(event.type as TType);\n\t\tif (!handlers || handlers.size === 0) return undefined;\n\t\tlet lastResult: AgentHarnessEventResultMap[TType] | undefined;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler(event);\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tlastResult = result;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn lastResult;\n\t}\n\n\tprivate async emitBeforeProviderRequest(\n\t\tmodel: Model<any>,\n\t\tsessionId: string,\n\t\tstreamOptions: AgentHarnessStreamOptions,\n\t): Promise<AgentHarnessStreamOptions> {\n\t\tconst handlers = this.handlers.get(\"before_provider_request\");\n\t\tlet current = cloneStreamOptions(streamOptions);\n\t\tif (!handlers || handlers.size === 0) return current;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler({\n\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\tmodel,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tstreamOptions: cloneStreamOptions(current),\n\t\t\t\t});\n\t\t\t\tif (result?.streamOptions) {\n\t\t\t\t\tcurrent = applyStreamOptionsPatch(current, result.streamOptions);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate async emitBeforeProviderPayload(model: Model<any>, payload: unknown): Promise<unknown> {\n\t\tconst handlers = this.handlers.get(\"before_provider_payload\");\n\t\tlet current = payload;\n\t\tif (!handlers || handlers.size === 0) return current;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler({ type: \"before_provider_payload\", model, payload: current });\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tcurrent = result.payload;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate async emitQueueUpdate(): Promise<void> {\n\t\tawait this.emitOwn({\n\t\t\ttype: \"queue_update\",\n\t\t\tsteer: [...this.steerQueue],\n\t\t\tfollowUp: [...this.followUpQueue],\n\t\t\tnextTurn: [...this.nextTurnQueue],\n\t\t});\n\t}\n\n\t/**\n\t * Facade write-gate vocabulary mapped from lifecycle state. `settling` maps\n\t * to \"idle\": the queue is drained by the settlement finalizer first, and\n\t * listener writes persist after it through the coordinator tail.\n\t */\n\tprivate currentPhase(): AgentHarnessPhase {\n\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\tif (snapshot.tag !== \"active\") return \"idle\";\n\t\tswitch (snapshot.operation.kind) {\n\t\t\tcase \"manual_compaction\":\n\t\t\t\treturn \"compaction\";\n\t\t\tcase \"tree_navigation\":\n\t\t\t\treturn \"branch_summary\";\n\t\t\tdefault:\n\t\t\t\treturn \"turn\";\n\t\t}\n\t}\n\n\t/** Config writes persist immediately outside an active operation and queue during one. */\n\tprivate async persistConfigChange(write: QueuedSessionWrite<AgentMessage>): Promise<void> {\n\t\tif (this.lifecycle.getSnapshot().tag !== \"active\") {\n\t\t\tawait this.sessionWrites.persistAfterPending(write);\n\t\t} else {\n\t\t\tthis.sessionWrites.enqueue(write);\n\t\t}\n\t}\n\n\t/**\n\t * Single wrapper for every public operation: begin a lease, run the body,\n\t * then settle exactly once. The final flush and the `settled` event happen\n\t * inside the settling barrier; a finalizer failure never reports success.\n\t */\n\tprivate async runOperation<T>(\n\t\tkind: HarnessOperationKind,\n\t\tfallbackCode: AgentHarnessError[\"code\"],\n\t\tbody: (lease: OperationLease) => Promise<T>,\n\t\tclassifyResult?: (result: T) => HarnessOperationOutcome | undefined,\n\t): Promise<T> {\n\t\tconst lease = this.lifecycle.begin(kind);\n\t\tlet result: T | undefined;\n\t\tlet bodyError: unknown;\n\t\t// Everything after a successful begin() runs inside one capture region. A\n\t\t// throwing `operation_started` listener must not escape before settle(),\n\t\t// or the lifecycle would stay active and wedge the harness at \"busy\".\n\t\ttry {\n\t\t\tawait this.emitOwn({ type: \"operation_started\", operation: lease.operation });\n\t\t\tresult = await body(lease);\n\t\t} catch (error) {\n\t\t\tbodyError = error;\n\t\t}\n\t\t// The final flush precedes classification: a persistence failure after a\n\t\t// provider success must never record or report a completed operation.\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tawait this.sessionWrites.flush();\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\t\tconst outcome = resolveOperationOutcome({\n\t\t\tsignalAborted: lease.signal.aborted,\n\t\t\tresult,\n\t\t\tbodyError,\n\t\t\tflushError,\n\t\t\tclassifyResult,\n\t\t\tfallbackCode,\n\t\t});\n\t\tlet settleError: unknown;\n\t\ttry {\n\t\t\tawait this.lifecycle.settle(lease, outcome, async () => {\n\t\t\t\tawait this.emitOwn(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"settled\",\n\t\t\t\t\t\tnextTurnCount: this.nextTurnQueue.length,\n\t\t\t\t\t\toperationId: lease.operation.operationId,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\tattemptCount: this.lifecycle.getAttemptSummaries(lease).length,\n\t\t\t\t\t},\n\t\t\t\t\tlease.signal,\n\t\t\t\t);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tsettleError = error;\n\t\t}\n\t\tconst failure = resolveOperationFailure({ bodyError, flushError, settleError, fallbackCode });\n\t\tif (failure !== undefined) throw failure;\n\t\treturn result as T;\n\t}\n\n\tprivate async createTurnState(): Promise<AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>> {\n\t\tconst context = await this.session.buildContext();\n\t\tconst resources = this.getResources();\n\t\tconst sessionMetadata = await this.session.getMetadata();\n\t\tconst tools = [...this.tools.values()];\n\t\tconst activeTools = this.activeToolNames\n\t\t\t.map((name) => this.tools.get(name))\n\t\t\t.filter((tool): tool is TTool => tool !== undefined);\n\t\tlet systemPrompt = \"You are a helpful assistant.\";\n\t\tif (typeof this.systemPrompt === \"string\") {\n\t\t\tsystemPrompt = this.systemPrompt;\n\t\t} else if (this.systemPrompt) {\n\t\t\tsystemPrompt = await this.systemPrompt({\n\t\t\t\tenv: this.env,\n\t\t\t\tsession: this.session,\n\t\t\t\tmodel: this.model,\n\t\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\t\tactiveTools,\n\t\t\t\tresources,\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tmessages: context.messages,\n\t\t\tresources,\n\t\t\tstreamOptions: cloneStreamOptions(this.streamOptions),\n\t\t\tsessionId: sessionMetadata.id,\n\t\t\tsystemPrompt,\n\t\t\tmodel: this.model,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\ttools,\n\t\t\tactiveTools,\n\t\t};\n\t}\n\n\tprivate createContext(\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tsystemPrompt?: string,\n\t): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: systemPrompt ?? turnState.systemPrompt,\n\t\t\tmessages: turnState.messages.slice(),\n\t\t\ttools: turnState.activeTools.slice(),\n\t\t};\n\t}\n\n\tprivate createStreamFn(getTurnState: () => AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>): StreamFn {\n\t\treturn async (model, context, streamOptions) => {\n\t\t\tconst turnState = getTurnState();\n\t\t\tconst requestContext = await this.maybeAutoCompact(model, context, streamOptions?.signal);\n\t\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\t\tconst snapshotOptions: AgentHarnessStreamOptions = {\n\t\t\t\t...turnState.streamOptions,\n\t\t\t\theaders: mergeHeaders(turnState.streamOptions.headers, auth?.headers),\n\t\t\t};\n\t\t\tconst requestOptions = await this.emitBeforeProviderRequest(model, turnState.sessionId, snapshotOptions);\n\t\t\treturn streamSimple(model, requestContext, {\n\t\t\t\tcacheRetention: requestOptions.cacheRetention,\n\t\t\t\theaders: requestOptions.headers,\n\t\t\t\tmaxRetries: requestOptions.maxRetries,\n\t\t\t\tmaxRetryDelayMs: requestOptions.maxRetryDelayMs,\n\t\t\t\tmetadata: requestOptions.metadata,\n\t\t\t\tonPayload: async (payload) => await this.emitBeforeProviderPayload(model, payload),\n\t\t\t\tonResponse: async (response) => {\n\t\t\t\t\tconst headers = { ...(response.headers as Record<string, string>) };\n\t\t\t\t\tawait this.emitOwn(\n\t\t\t\t\t\t{ type: \"after_provider_response\", status: response.status, headers },\n\t\t\t\t\t\tstreamOptions?.signal,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\treasoning: streamOptions?.reasoning,\n\t\t\t\tsignal: streamOptions?.signal,\n\t\t\t\tsessionId: turnState.sessionId,\n\t\t\t\ttimeoutMs: requestOptions.timeoutMs,\n\t\t\t\ttransport: requestOptions.transport,\n\t\t\t\tapiKey: auth?.apiKey,\n\t\t\t});\n\t\t};\n\t}\n\n\tprivate async drainQueuedMessages(queue: AgentMessage[], mode: QueueMode): Promise<AgentMessage[]> {\n\t\tconst messages = mode === \"all\" ? queue.splice(0) : queue.splice(0, 1);\n\t\tif (messages.length === 0) return messages;\n\t\ttry {\n\t\t\tawait this.emitQueueUpdate();\n\t\t\treturn messages;\n\t\t} catch (error) {\n\t\t\tqueue.unshift(...messages);\n\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t}\n\t}\n\n\tprivate createLoopConfig(\n\t\tgetTurnState: () => AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tsetTurnState: (turnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>) => void,\n\t\tlease?: OperationLease,\n\t): AgentLoopConfig {\n\t\tconst turnState = getTurnState();\n\t\treturn {\n\t\t\tmodel: turnState.model,\n\t\t\treasoning: turnState.thinkingLevel === \"off\" ? undefined : turnState.thinkingLevel,\n\t\t\tconvertToLlm,\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst result = await this.emitHook({ type: \"context\", messages: [...messages] });\n\t\t\t\treturn result?.messages ?? messages;\n\t\t\t},\n\t\t\tbeforeToolCall: async ({ toolCall, args }) => {\n\t\t\t\tconst result = await this.emitHook({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t});\n\t\t\t\treturn result ? { block: result.block, reason: result.reason } : undefined;\n\t\t\t},\n\t\t\tafterToolCall: async ({ toolCall, args, result, isError }) => {\n\t\t\t\tconst patch = await this.emitHook({\n\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tdetails: result.details,\n\t\t\t\t\tisError,\n\t\t\t\t});\n\t\t\t\treturn patch\n\t\t\t\t\t? { content: patch.content, details: patch.details, isError: patch.isError, terminate: patch.terminate }\n\t\t\t\t\t: undefined;\n\t\t\t},\n\t\t\tprepareNextTurn: async () => {\n\t\t\t\tawait this.sessionWrites.flush();\n\t\t\t\tif (lease) {\n\t\t\t\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\t\t\t\tif (snapshot.tag === \"active\" && snapshot.stage === \"save_point\") {\n\t\t\t\t\t\tthis.lifecycle.setStage(lease, \"attempt_running\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst nextTurnState = await this.createTurnState();\n\t\t\t\tsetTurnState(nextTurnState);\n\t\t\t\treturn {\n\t\t\t\t\tcontext: this.createContext(nextTurnState),\n\t\t\t\t\tmodel: nextTurnState.model,\n\t\t\t\t\tthinkingLevel: nextTurnState.thinkingLevel,\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetSteeringMessages: async () => this.drainQueuedMessages(this.steerQueue, this.steeringQueueMode),\n\t\t\tgetFollowUpMessages: async () => this.drainQueuedMessages(this.followUpQueue, this.followUpQueueMode),\n\t\t};\n\t}\n\n\tprivate validateUniqueNames(names: string[], message: string): void {\n\t\tconst duplicates = findDuplicateNames(names);\n\t\tif (duplicates.length > 0)\n\t\t\tthrow new AgentHarnessError(\"invalid_argument\", `${message}: ${duplicates.join(\", \")}`);\n\t}\n\n\tprivate validateToolNames(toolNames: string[], tools: Map<string, TTool> = this.tools): void {\n\t\tthis.validateUniqueNames(toolNames, \"Duplicate active tool name(s)\");\n\t\tconst missing = toolNames.filter((name) => !tools.has(name));\n\t\tif (missing.length > 0) throw new AgentHarnessError(\"invalid_argument\", `Unknown tool(s): ${missing.join(\", \")}`);\n\t}\n\n\tprivate async handleAgentEvent(event: AgentEvent, signal?: AbortSignal, lease?: OperationLease): Promise<void> {\n\t\tif (event.type === \"message_end\") {\n\t\t\tawait this.session.appendMessage(event.message);\n\t\t\tawait this.emitAny(event, signal);\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"turn_end\") {\n\t\t\tlet eventError: unknown;\n\t\t\ttry {\n\t\t\t\tawait this.emitAny(event, signal);\n\t\t\t} catch (error) {\n\t\t\t\teventError = error;\n\t\t\t}\n\t\t\t// The flush runs even after a failing listener so accepted writes are\n\t\t\t// not stranded; a failing flush must then report next to that listener\n\t\t\t// error, not in place of it.\n\t\t\tconst hadPendingMutations = this.sessionWrites.hasPending();\n\t\t\tlet flushError: unknown;\n\t\t\ttry {\n\t\t\t\tawait this.sessionWrites.flush();\n\t\t\t} catch (error) {\n\t\t\t\tflushError = error;\n\t\t\t}\n\t\t\tif (lease) {\n\t\t\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\t\t\tif (snapshot.tag === \"active\" && snapshot.stage === \"attempt_running\") {\n\t\t\t\t\tthis.lifecycle.setStage(lease, \"save_point\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst failure = combineBoundaryErrors(\n\t\t\t\t[eventError, flushError],\n\t\t\t\t\"turn_end listener failed and the save-point flush failed\",\n\t\t\t\t\"hook\",\n\t\t\t);\n\t\t\tif (failure !== undefined) throw failure;\n\t\t\tawait this.emitOwn({ type: \"save_point\", hadPendingMutations });\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"agent_end\") {\n\t\t\t// agent_end is an attempt event: flush its accepted writes, but lifecycle\n\t\t\t// settlement and the settled event belong to OperationLease.settle().\n\t\t\tawait this.sessionWrites.flush();\n\t\t\tawait this.emitAny(event, signal);\n\t\t\treturn;\n\t\t}\n\t\tawait this.emitAny(event, signal);\n\t}\n\n\tprivate async emitRunFailure(\n\t\tmodel: Model<any>,\n\t\terror: unknown,\n\t\taborted: boolean,\n\t\tsignal: AbortSignal,\n\t\tcompletedMessages: readonly AgentMessage[],\n\t\tlease?: OperationLease,\n\t): Promise<AgentMessage[]> {\n\t\tconst failureMessage = createFailureMessage(model, error, aborted);\n\t\tconst messages = [...completedMessages, failureMessage];\n\t\tawait this.handleAgentEvent({ type: \"message_start\", message: failureMessage }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"message_end\", message: failureMessage }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"turn_end\", message: failureMessage, toolResults: [] }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"agent_end\", messages }, signal, lease);\n\t\treturn messages;\n\t}\n\n\tprivate async executeTurn(\n\t\tlease: OperationLease,\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\ttext: string,\n\t\toptions?: { images?: ImageContent[] },\n\t): Promise<AssistantMessage> {\n\t\tlet messages: AgentMessage[] = [createUserMessage(text, options?.images)];\n\t\tif (this.nextTurnQueue.length > 0) {\n\t\t\tconst queuedMessages = this.nextTurnQueue.splice(0);\n\t\t\ttry {\n\t\t\t\tawait this.emitQueueUpdate();\n\t\t\t} catch (error) {\n\t\t\t\tthis.nextTurnQueue.unshift(...queuedMessages);\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t\tmessages = [...queuedMessages, messages[0]!];\n\t\t}\n\t\tconst beforeResult = await this.emitHook({\n\t\t\ttype: \"before_agent_start\",\n\t\t\tprompt: text,\n\t\t\timages: options?.images,\n\t\t\tsystemPrompt: turnState.systemPrompt,\n\t\t\tresources: turnState.resources,\n\t\t});\n\t\tif (beforeResult?.messages) messages = [...messages, ...beforeResult.messages];\n\n\t\tconst result = await this.executeAgentRun(\n\t\t\tlease,\n\t\t\t\"initial\",\n\t\t\tturnState,\n\t\t\tthis.createContext(turnState, beforeResult?.systemPrompt),\n\t\t\tmessages,\n\t\t);\n\t\treturn await this.recoverContextOverflow(lease, result);\n\t}\n\n\t/**\n\t * Sole attempt boundary: begin, announce, run, classify, close, announce, flush.\n\t *\n\t * Once `beginAttempt()` succeeds the attempt is closed exactly once on every\n\t * path, so `count(attempt_started) == count(attempt_finished)` holds even when\n\t * the `attempt_started` observer throws. `attempt_finished` is emitted only\n\t * after the attempt is already closed, so a throwing observer can fail the\n\t * operation but can never reopen committed attempt state. The closing flush\n\t * is not a `finally`: a `finally` that awaits a throwing flush would replace\n\t * the body error, hiding the provider or listener failure from the audit trail.\n\t */\n\tprivate async runAttempt<T>(\n\t\tlease: OperationLease,\n\t\treason: HarnessAttemptReason,\n\t\tbody: (attempt: AttemptLease) => Promise<T>,\n\t\tclassify: (result: T) => HarnessAttemptOutcome,\n\t): Promise<T> {\n\t\tconst attemptLease = this.lifecycle.beginAttempt(lease, reason);\n\t\tlet result: T | undefined;\n\t\tlet bodyError: unknown;\n\t\ttry {\n\t\t\tawait this.emitOwn({ type: \"attempt_started\", attempt: attemptLease.attempt }, lease.signal);\n\t\t\tresult = await body(attemptLease);\n\t\t} catch (error) {\n\t\t\tbodyError = error;\n\t\t}\n\t\tconst outcome: HarnessAttemptOutcome =\n\t\t\tbodyError === undefined ? classify(result as T) : classifyAttemptFailure(bodyError);\n\t\tthis.lifecycle.finishAttempt(lease, attemptLease, outcome);\n\t\tlet observerError: unknown;\n\t\ttry {\n\t\t\tawait this.emitOwn(\n\t\t\t\t{ type: \"attempt_finished\", summary: this.lifecycle.getAttemptSummary(lease, attemptLease) },\n\t\t\t\tlease.signal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tobserverError = error;\n\t\t}\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tawait this.sessionWrites.flush();\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\t\tconst failure = combineBoundaryErrors(\n\t\t\t[bodyError, observerError, flushError],\n\t\t\t\"Attempt failed and its attempt_finished reporting or closing flush failed\",\n\t\t\t\"unknown\",\n\t\t);\n\t\tif (failure !== undefined) throw failure;\n\t\treturn result as T;\n\t}\n\n\tprivate async executeAgentRun(\n\t\tlease: OperationLease,\n\t\treason: HarnessAttemptReason,\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tcontext: AgentContext,\n\t\tinitialMessages?: AgentMessage[],\n\t): Promise<AssistantMessage> {\n\t\tlet activeTurnState = turnState;\n\t\treturn await this.runAttempt(\n\t\t\tlease,\n\t\t\treason,\n\t\t\tasync (attemptLease) => {\n\t\t\t\tconst signal = attemptLease.signal;\n\t\t\t\tconst getTurnState = () => activeTurnState;\n\t\t\t\tconst setTurnState = (nextTurnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>) => {\n\t\t\t\t\tactiveTurnState = nextTurnState;\n\t\t\t\t};\n\t\t\t\tconst completedMessages: AgentMessage[] = [];\n\t\t\t\tconst emit = async (event: AgentEvent): Promise<void> => {\n\t\t\t\t\tif (event.type === \"message_end\") completedMessages.push(event.message);\n\t\t\t\t\tawait this.handleAgentEvent(event, signal, lease);\n\t\t\t\t};\n\t\t\t\tlet newMessages: AgentMessage[];\n\t\t\t\ttry {\n\t\t\t\t\tconst loopConfig = this.createLoopConfig(getTurnState, setTurnState, lease);\n\t\t\t\t\tconst streamFn = this.createStreamFn(getTurnState);\n\t\t\t\t\tnewMessages = initialMessages\n\t\t\t\t\t\t? await runAgentLoop(initialMessages, context, loopConfig, emit, signal, streamFn)\n\t\t\t\t\t\t: await runAgentLoopContinue(context, loopConfig, emit, signal, streamFn);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnewMessages = await this.emitRunFailure(\n\t\t\t\t\t\t\tactiveTurnState.model,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\tsignal.aborted,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tcompletedMessages,\n\t\t\t\t\t\t\tlease,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (failureError) {\n\t\t\t\t\t\tconst cause = new AggregateError(\n\t\t\t\t\t\t\t[toError(error), toError(failureError)],\n\t\t\t\t\t\t\t\"Agent run failed and failure reporting failed\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthrow new AgentHarnessError(\"unknown\", cause.message, cause);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (let i = newMessages.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst message = newMessages[i]!;\n\t\t\t\t\tif (message.role === \"assistant\") return message;\n\t\t\t\t}\n\t\t\t\tthrow new AgentHarnessError(\"invalid_state\", \"AgentHarness prompt completed without an assistant message\");\n\t\t\t},\n\t\t\t(message) => classifyAttemptOutcome(message, activeTurnState.model.contextWindow),\n\t\t);\n\t}\n\n\t/**\n\t * One-shot overflow recovery inside the originating operation. The lease is\n\t * proof that this operation still owns the harness, so no run-ownership or\n\t * phase re-check is needed; a strict lifecycle makes a newer operation\n\t * starting mid-recovery impossible.\n\t */\n\tprivate async recoverContextOverflow(lease: OperationLease, message: AssistantMessage): Promise<AssistantMessage> {\n\t\tif (!this.compactionSettings.enabled || !isContextOverflow(message, this.model.contextWindow)) {\n\t\t\treturn message;\n\t\t}\n\t\tif (!this.getApiKeyAndHeaders) return message;\n\t\tconst leafId = await this.session.getLeafId();\n\t\tif (!leafId) return message;\n\t\tconst leaf = await this.session.getEntry(leafId);\n\t\tif (\n\t\t\tleaf?.type !== \"message\" ||\n\t\t\tleaf.message.role !== \"assistant\" ||\n\t\t\tleaf.message.timestamp !== message.timestamp ||\n\t\t\t!isContextOverflow(leaf.message, this.model.contextWindow)\n\t\t) {\n\t\t\treturn message;\n\t\t}\n\n\t\tawait this.session.moveTo(leaf.parentId);\n\t\tthis.lifecycle.setStage(lease, \"recovering_overflow\");\n\t\ttry {\n\t\t\tconst compacted = await this.runCompaction({ automatic: true, signal: lease.signal });\n\t\t\tif (!compacted) {\n\t\t\t\tawait this.session.moveTo(leafId);\n\t\t\t\treturn message;\n\t\t\t}\n\t\t\tconst turnState = await this.createTurnState();\n\t\t\treturn await this.executeAgentRun(\n\t\t\t\tlease,\n\t\t\t\t\"context_overflow_recovery\",\n\t\t\t\tturnState,\n\t\t\t\tthis.createContext(turnState),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tawait this.session.moveTo(leafId);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync prompt(text: string, options?: { images?: ImageContent[] }): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"prompt\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\treturn await this.executeTurn(lease, turnState, text, options);\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\tasync skill(name: string, additionalInstructions?: string): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"skill\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\tconst skill = (turnState.resources.skills ?? []).find((candidate) => candidate.name === name);\n\t\t\t\tif (!skill) throw new AgentHarnessError(\"invalid_argument\", `Unknown skill: ${name}`);\n\t\t\t\treturn await this.executeTurn(lease, turnState, formatSkillInvocation(skill, additionalInstructions));\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\tasync promptFromTemplate(name: string, args: string[] = []): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"prompt_template\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\tconst template = (turnState.resources.promptTemplates ?? []).find((candidate) => candidate.name === name);\n\t\t\t\tif (!template) throw new AgentHarnessError(\"invalid_argument\", `Unknown prompt template: ${name}`);\n\t\t\t\treturn await this.executeTurn(lease, turnState, formatPromptTemplateInvocation(template, args));\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\t/**\n\t * Steering and follow-up input is consumed only by a running agent attempt.\n\t * A structural operation (`compact`, `navigateTree`) runs none, so accepting\n\t * input there would silently inject it into an unrelated later prompt.\n\t */\n\tprivate expectQueueConsumer(action: string): void {\n\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\tif (snapshot.tag !== \"active\") throw new AgentHarnessError(\"invalid_state\", `Cannot ${action} while idle`);\n\t\tif (!PROMPT_FAMILY_KINDS.includes(snapshot.operation.kind)) {\n\t\t\tthrow new AgentHarnessError(\n\t\t\t\t\"invalid_state\",\n\t\t\t\t`Cannot ${action} during ${snapshot.operation.kind}: no agent attempt can consume it`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync steer(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.expectQueueConsumer(\"steer\");\n\t\tthis.steerQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tasync followUp(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.expectQueueConsumer(\"follow up\");\n\t\tthis.followUpQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tasync nextTurn(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.nextTurnQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tgetSession(): HarnessSession {\n\t\treturn this.sessionFacade;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<void> {\n\t\tawait this.sessionFacade.appendMessage(message);\n\t}\n\n\tprivate async runCompaction(options: HarnessCompactionRunOptions): Promise<CompactResult | undefined> {\n\t\tconst model = this.model;\n\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\tif (!auth) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"auth\", \"No auth available for compaction\");\n\t\t}\n\t\tconst branchEntries = await this.session.getBranch();\n\t\tconst preparationResult = prepareCompaction(branchEntries, this.compactionSettings);\n\t\tif (!preparationResult.ok) throw preparationResult.error;\n\t\tconst preparation = preparationResult.value;\n\t\tif (!preparation) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"compaction\", \"Nothing to compact\");\n\t\t}\n\t\tconst signal = options.signal ?? new AbortController().signal;\n\t\tconst hookResult = await this.emitHook({\n\t\t\ttype: \"session_before_compact\",\n\t\t\tpreparation,\n\t\t\tbranchEntries,\n\t\t\tcustomInstructions: options.customInstructions,\n\t\t\tsignal,\n\t\t});\n\t\tif (hookResult?.cancel) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"compaction\", \"Compaction cancelled\");\n\t\t}\n\t\tconst provided = hookResult?.compaction;\n\t\tconst compactResult = provided\n\t\t\t? { ok: true as const, value: provided }\n\t\t\t: await compact(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tmodel,\n\t\t\t\t\tauth.apiKey,\n\t\t\t\t\tauth.headers,\n\t\t\t\t\toptions.customInstructions,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthis.thinkingLevel,\n\t\t\t\t\tcreateSummarizationRetry(\"compaction\", this.streamOptions.summarizationRetry, (event) =>\n\t\t\t\t\t\tthis.emitOwn(event),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\tif (!compactResult.ok) throw compactResult.error;\n\t\tconst result = compactResult.value;\n\t\toptions.beforeCommit?.();\n\t\tconst entryId = await this.session.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tprovided !== undefined,\n\t\t);\n\t\tconst entry = await this.session.getEntry(entryId);\n\t\tif (entry?.type === \"compaction\") {\n\t\t\tawait this.emitOwn({ type: \"session_compact\", compactionEntry: entry, fromHook: provided !== undefined });\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate async maybeAutoCompact(model: Model<any>, context: Context, signal?: AbortSignal): Promise<Context> {\n\t\tconst projected = estimateContextTokens(context.messages).tokens;\n\t\tif (!shouldCompact(projected, model.contextWindow ?? 0, this.compactionSettings)) return context;\n\t\tconst result = await this.runCompaction({ automatic: true, signal });\n\t\tif (!result) return context;\n\t\tconst persisted = await this.session.buildContext();\n\t\treturn { ...context, messages: convertToLlm(persisted.messages) };\n\t}\n\n\tasync compact(customInstructions?: string): Promise<CompactResult> {\n\t\treturn this.runOperation(\"manual_compaction\", \"compaction\", async (lease) => {\n\t\t\tthis.lifecycle.setStage(lease, \"structural_running\");\n\t\t\tconst result = await this.runCompaction({\n\t\t\t\tautomatic: false,\n\t\t\t\tcustomInstructions,\n\t\t\t\tbeforeCommit: () => {\n\t\t\t\t\tthis.lifecycle.setStage(lease, \"committing\");\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!result) throw new AgentHarnessError(\"compaction\", \"Nothing to compact\");\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync navigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<NavigateTreeResult> {\n\t\treturn this.runOperation(\n\t\t\t\"tree_navigation\",\n\t\t\t\"branch_summary\",\n\t\t\tasync (lease) => {\n\t\t\t\tthis.lifecycle.setStage(lease, \"structural_running\");\n\t\t\t\tconst oldLeafId = await this.session.getLeafId();\n\t\t\t\t// No-op navigation mutates nothing, so it completes without ever\n\t\t\t\t// entering the `committing` stage.\n\t\t\t\tif (oldLeafId === targetId) return { cancelled: false };\n\t\t\t\tconst targetEntry = await this.session.getEntry(targetId);\n\t\t\t\tif (!targetEntry) throw new AgentHarnessError(\"invalid_argument\", `Entry ${targetId} not found`);\n\t\t\t\tconst { entries, commonAncestorId } = await collectEntriesForBranchSummary(\n\t\t\t\t\tthis.session,\n\t\t\t\t\toldLeafId,\n\t\t\t\t\ttargetId,\n\t\t\t\t);\n\t\t\t\tconst preparation = {\n\t\t\t\t\ttargetId,\n\t\t\t\t\toldLeafId,\n\t\t\t\t\tcommonAncestorId,\n\t\t\t\t\tentriesToSummarize: entries,\n\t\t\t\t\tuserWantsSummary: options?.summarize ?? false,\n\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\tlabel: options?.label,\n\t\t\t\t};\n\t\t\t\tconst signal = new AbortController().signal;\n\t\t\t\tconst hookResult = await this.emitHook({ type: \"session_before_tree\", preparation, signal });\n\t\t\t\tif (hookResult?.cancel) return { cancelled: true };\n\t\t\t\tlet summaryEntry: NavigateTreeResult[\"summaryEntry\"];\n\t\t\t\tlet summaryText: string | undefined = hookResult?.summary?.summary;\n\t\t\t\tlet summaryDetails: unknown = hookResult?.summary?.details;\n\t\t\t\tif (!summaryText && options?.summarize && entries.length > 0) {\n\t\t\t\t\tconst model = this.model;\n\t\t\t\t\tif (!model) throw new AgentHarnessError(\"invalid_state\", \"No model set for branch summary\");\n\t\t\t\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\t\t\t\tif (!auth) throw new AgentHarnessError(\"auth\", \"No auth available for branch summary\");\n\t\t\t\t\tconst branchSummary = await runBranchSummary({\n\t\t\t\t\t\tentries,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\tcustomInstructions: hookResult?.customInstructions ?? options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: hookResult?.replaceInstructions ?? options?.replaceInstructions,\n\t\t\t\t\t\tsummarizationRetry: this.streamOptions.summarizationRetry,\n\t\t\t\t\t\temit: (event) => this.emitOwn(event),\n\t\t\t\t\t});\n\t\t\t\t\tif (branchSummary.cancelled) return { cancelled: true };\n\t\t\t\t\tsummaryText = branchSummary.summary;\n\t\t\t\t\tsummaryDetails = branchSummary.details;\n\t\t\t\t}\n\t\t\t\tconst { newLeafId, editorText } = resolveNavigationTarget(targetEntry, targetId);\n\t\t\t\t// Single declared commit point of a tree navigation.\n\t\t\t\tthis.lifecycle.setStage(lease, \"committing\");\n\t\t\t\tconst summaryId = await this.session.moveTo(\n\t\t\t\t\tnewLeafId,\n\t\t\t\t\tsummaryText\n\t\t\t\t\t\t? { summary: summaryText, details: summaryDetails, fromHook: hookResult?.summary !== undefined }\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t\tif (summaryId) {\n\t\t\t\t\tconst entry = await this.session.getEntry(summaryId);\n\t\t\t\t\tif (entry?.type === \"branch_summary\") summaryEntry = entry;\n\t\t\t\t}\n\t\t\t\tawait this.emitOwn({\n\t\t\t\t\ttype: \"session_tree\",\n\t\t\t\t\tnewLeafId: await this.session.getLeafId(),\n\t\t\t\t\toldLeafId,\n\t\t\t\t\tsummaryEntry,\n\t\t\t\t\tfromHook: hookResult?.summary !== undefined,\n\t\t\t\t});\n\t\t\t\treturn { cancelled: false, editorText, summaryEntry };\n\t\t\t},\n\t\t\tclassifyNavigateTreeOutcome,\n\t\t);\n\t}\n\n\tgetModel(): Model<any> {\n\t\treturn this.model;\n\t}\n\n\tasync setModel(model: Model<any>): Promise<void> {\n\t\ttry {\n\t\t\tconst previousModel = this.model;\n\t\t\tconst nextProvider = model.provider;\n\t\t\tconst nextModelId = model.id;\n\t\t\tawait this.persistConfigChange({ type: \"model_change\", provider: nextProvider, modelId: nextModelId });\n\t\t\tthis.model = model;\n\t\t\tawait this.emitOwn({ type: \"model_update\", model, previousModel, source: \"set\" });\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"session\");\n\t\t}\n\t}\n\n\tgetThinkingLevel(): ThinkingLevel {\n\t\treturn this.thinkingLevel;\n\t}\n\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\ttry {\n\t\t\tconst previousLevel = this.thinkingLevel;\n\t\t\tawait this.persistConfigChange({ type: \"thinking_level_change\", thinkingLevel: level });\n\t\t\tthis.thinkingLevel = level;\n\t\t\tawait this.emitOwn({ type: \"thinking_level_update\", level, previousLevel });\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"session\");\n\t\t}\n\t}\n\n\tgetTools(): TTool[] {\n\t\treturn [...this.tools.values()];\n\t}\n\n\tasync setTools(tools: TTool[], activeToolNames?: string[]): Promise<void> {\n\t\ttry {\n\t\t\tthis.validateUniqueNames(\n\t\t\t\ttools.map((tool) => tool.name),\n\t\t\t\t\"Duplicate tool name(s)\",\n\t\t\t);\n\t\t\tconst nextTools = new Map(tools.map((tool) => [tool.name, tool]));\n\t\t\tconst nextActiveToolNames = activeToolNames ? [...activeToolNames] : this.activeToolNames;\n\t\t\tthis.validateToolNames(nextActiveToolNames, nextTools);\n\t\t\tconst previousToolNames = [...this.tools.keys()];\n\t\t\tconst previousActiveToolNames = [...this.activeToolNames];\n\t\t\tawait this.persistConfigChange({ type: \"active_tools_change\", activeToolNames: [...nextActiveToolNames] });\n\t\t\tthis.tools = nextTools;\n\t\t\tthis.activeToolNames = [...nextActiveToolNames];\n\t\t\tawait this.emitOwn({\n\t\t\t\ttype: \"tools_update\",\n\t\t\t\ttoolNames: [...this.tools.keys()],\n\t\t\t\tpreviousToolNames,\n\t\t\t\tactiveToolNames: [...this.activeToolNames],\n\t\t\t\tpreviousActiveToolNames,\n\t\t\t\tsource: \"set\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"invalid_argument\");\n\t\t}\n\t}\n\n\tgetActiveTools(): TTool[] {\n\t\treturn this.activeToolNames.map((name) => this.tools.get(name)!);\n\t}\n\n\tasync setActiveTools(toolNames: string[]): Promise<void> {\n\t\ttry {\n\t\t\tconst nextActiveToolNames = [...toolNames];\n\t\t\tthis.validateToolNames(nextActiveToolNames);\n\t\t\tconst previousToolNames = [...this.tools.keys()];\n\t\t\tconst previousActiveToolNames = [...this.activeToolNames];\n\t\t\tawait this.persistConfigChange({ type: \"active_tools_change\", activeToolNames: [...nextActiveToolNames] });\n\t\t\tthis.activeToolNames = [...nextActiveToolNames];\n\t\t\tawait this.emitOwn({\n\t\t\t\ttype: \"tools_update\",\n\t\t\t\ttoolNames: [...this.tools.keys()],\n\t\t\t\tpreviousToolNames,\n\t\t\t\tactiveToolNames: [...this.activeToolNames],\n\t\t\t\tpreviousActiveToolNames,\n\t\t\t\tsource: \"set\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"invalid_argument\");\n\t\t}\n\t}\n\n\tgetSteeringMode(): QueueMode {\n\t\treturn this.steeringQueueMode;\n\t}\n\n\tasync setSteeringMode(mode: QueueMode): Promise<void> {\n\t\tthis.steeringQueueMode = mode;\n\t}\n\n\tgetFollowUpMode(): QueueMode {\n\t\treturn this.followUpQueueMode;\n\t}\n\n\tasync setFollowUpMode(mode: QueueMode): Promise<void> {\n\t\tthis.followUpQueueMode = mode;\n\t}\n\n\tgetResources(): AgentHarnessResources<TSkill, TPromptTemplate> {\n\t\treturn {\n\t\t\tskills: this.resources.skills?.slice(),\n\t\t\tpromptTemplates: this.resources.promptTemplates?.slice(),\n\t\t};\n\t}\n\n\tasync setResources(resources: AgentHarnessResources<TSkill, TPromptTemplate>): Promise<void> {\n\t\tconst previousResources = this.getResources();\n\t\tthis.resources = {\n\t\t\tskills: resources.skills?.slice(),\n\t\t\tpromptTemplates: resources.promptTemplates?.slice(),\n\t\t};\n\t\tawait this.emitOwn({ type: \"resources_update\", resources: this.getResources(), previousResources });\n\t}\n\n\tgetStreamOptions(): AgentHarnessStreamOptions {\n\t\treturn cloneStreamOptions(this.streamOptions);\n\t}\n\n\tasync setStreamOptions(streamOptions: AgentHarnessStreamOptions): Promise<void> {\n\t\tthis.streamOptions = cloneStreamOptions(streamOptions);\n\t}\n\n\tasync abort(): Promise<AbortResult> {\n\t\t// Aborting awaits the captured operation's settlement, so a listener of that\n\t\t// same operation must never reach the wait below.\n\t\tthis.rejectCurrentOperationSelfWait(\"abort()\");\n\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\tif (snapshot.tag === \"active\" && snapshot.operation.kind === \"manual_compaction\") {\n\t\t\tthrow new AgentHarnessError(\"invalid_state\", \"Cannot abort during compaction\");\n\t\t}\n\t\tif (snapshot.tag === \"active\" && snapshot.operation.kind === \"tree_navigation\") {\n\t\t\tthrow new AgentHarnessError(\"invalid_state\", \"Cannot abort during branch_summary\");\n\t\t}\n\t\t// Capture the current operation before delivering any signal: an operation\n\t\t// started later by a settlement listener is never this call's target.\n\t\tconst capture = this.lifecycle.requestAbort();\n\t\tconst clearedSteer = this.steerQueue.splice(0);\n\t\tconst clearedFollowUp = this.followUpQueue.splice(0);\n\t\tconst errors: Error[] = [];\n\t\ttry {\n\t\t\tawait this.emitQueueUpdate();\n\t\t} catch (error) {\n\t\t\terrors.push(toError(error));\n\t\t}\n\t\ttry {\n\t\t\tif (capture.target) await capture.target.settled;\n\t\t} catch (error) {\n\t\t\terrors.push(toError(error));\n\t\t}\n\t\ttry {\n\t\t\tawait this.emitOwn({ type: \"abort\", clearedSteer, clearedFollowUp });\n\t\t} catch (error) {\n\t\t\terrors.push(toError(error));\n\t\t}\n\t\tif (errors.length > 0) {\n\t\t\tconst cause = errors.length === 1 ? errors[0]! : new AggregateError(errors, \"Abort completed with errors\");\n\t\t\tthrow normalizeHarnessError(cause, \"hook\");\n\t\t}\n\t\treturn { clearedSteer, clearedFollowUp };\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\tthis.rejectCurrentOperationSelfWait(\"waitForIdle()\");\n\t\t// Delegates to the lifecycle: resolves once no operation is active or settling.\n\t\tawait this.lifecycle.waitForIdle();\n\t}\n\n\tsubscribe(\n\t\tlistener: (event: AgentHarnessEvent<TSkill, TPromptTemplate>, signal?: AbortSignal) => Promise<void> | void,\n\t): () => void {\n\t\treturn this.subscribers.subscribe(listener);\n\t}\n\n\ton<TType extends keyof AgentHarnessEventResultMap>(\n\t\ttype: TType,\n\t\thandler: (\n\t\t\tevent: Extract<AgentHarnessOwnEvent, { type: TType }>,\n\t\t) => Promise<AgentHarnessEventResultMap[TType]> | AgentHarnessEventResultMap[TType],\n\t): () => void {\n\t\tlet handlers = this.handlers.get(type);\n\t\tif (!handlers) {\n\t\t\thandlers = new Set();\n\t\t\tthis.handlers.set(type, handlers);\n\t\t}\n\t\thandlers.add(handler as AgentHarnessHandler);\n\t\treturn () => handlers!.delete(handler as AgentHarnessHandler);\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent-harness.js","sourceRoot":"","sources":["../../src/harness/agent-harness.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,iBAAiB,EAEjB,YAAY,GAEZ,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAWtE,OAAO,EAAkC,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAChH,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AACtF,OAAO,EACN,OAAO,EACP,2BAA2B,EAC3B,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,GACb,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAmB,oBAAoB,EAA+B,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAA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QACD,QAAQ,CAAC,GAAG,CAAC,OAA8B,CAAC,CAAC;QAC7C,OAAO,GAAG,EAAE,CAAC,QAAS,CAAC,MAAM,CAAC,OAA8B,CAAC,CAAC;IAAA,CAC9D;CACD","sourcesContent":["import {\n\ttype AssistantMessage,\n\ttype Context,\n\ttype ImageContent,\n\tisContextOverflow,\n\ttype Model,\n\tstreamSimple,\n\ttype UserMessage,\n} from \"omk-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"../agent-loop.ts\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tQueueMode,\n\tStreamFn,\n\tThinkingLevel,\n} from \"../types.ts\";\nimport { type AbortSignalDeliveryResult, assertAbortAllowed, describeAbortDelivery } from \"./abort-delivery.ts\";\nimport { collectEntriesForBranchSummary } from \"./compaction/branch-summarization.ts\";\nimport {\n\tcompact,\n\tDEFAULT_COMPACTION_SETTINGS,\n\testimateContextTokens,\n\tprepareCompaction,\n\tshouldCompact,\n} from \"./compaction/compaction.ts\";\nimport type { HarnessCompactionRunOptions } from \"./compaction/operation.ts\";\nimport { type CommandRef, DeferredCommandQueue, type DeferredHarnessCommand } from \"./deferred-commands.ts\";\nimport { HarnessSessionFacade } from \"./harness-session.ts\";\nimport { convertToLlm, createFailureMessage, createUserMessage } from \"./messages.ts\";\nimport { findDuplicateNames } from \"./name-validation.ts\";\nimport {\n\ttype AttemptLease,\n\ttype OperationLease,\n\tOperationLifecycleController,\n} from \"./operation-lifecycle-controller.ts\";\nimport {\n\ttype HarnessAttemptOutcome,\n\ttype HarnessAttemptReason,\n\ttype HarnessOperationKind,\n\ttype HarnessOperationOutcome,\n\tPROMPT_FAMILY_KINDS,\n} from \"./operation-lifecycle-types.ts\";\nimport {\n\tclassifyAssistantOutcome,\n\tclassifyAttemptFailure,\n\tclassifyAttemptOutcome,\n\tclassifyNavigateTreeOutcome,\n\tcollectStepErrors,\n\tcombineBoundaryErrors,\n\tnormalizeHarnessError,\n\tresolveOperationFailure,\n\tresolveOperationOutcome,\n} from \"./operation-outcome.ts\";\nimport { formatPromptTemplateInvocation } from \"./prompt-templates.ts\";\nimport { uuidv7 } from \"./session/uuid.ts\";\nimport { type QueuedSessionWrite, SessionWriteCoordinator } from \"./session-write-coordinator.ts\";\nimport { formatSkillInvocation } from \"./skills.ts\";\nimport { applyStreamOptionsPatch, cloneStreamOptions, mergeHeaders } from \"./stream-options.ts\";\nimport { SubscriberFanout } from \"./subscriber-fanout.ts\";\nimport { createSummarizationRetry } from \"./summarization-retry.ts\";\nimport { resolveNavigationTarget, runBranchSummary } from \"./tree-navigation.ts\";\nimport type {\n\tAbortResult,\n\tAgentHarnessEvent,\n\tAgentHarnessEventResultMap,\n\tAgentHarnessOptions,\n\tAgentHarnessOwnEvent,\n\tAgentHarnessPhase,\n\tAgentHarnessResources,\n\tAgentHarnessStreamOptions,\n\tCompactionSettings,\n\tCompactResult,\n\tExecutionEnv,\n\tHarnessSession,\n\tNavigateTreeResult,\n\tPromptTemplate,\n\tSession,\n\tSkill,\n} from \"./types.ts\";\nimport { AgentHarnessError, toError } from \"./types.ts\";\n\ntype AgentHarnessHandler = (event: any, signal?: AbortSignal) => Promise<any> | any;\n\ninterface AgentHarnessTurnState<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\tmessages: AgentMessage[];\n\tresources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tstreamOptions: AgentHarnessStreamOptions;\n\tsessionId: string;\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: TTool[];\n\tactiveTools: TTool[];\n}\n\nexport class AgentHarness<\n\tTSkill extends Skill = Skill,\n\tTPromptTemplate extends PromptTemplate = PromptTemplate,\n\tTTool extends AgentTool = AgentTool,\n> {\n\treadonly env: ExecutionEnv;\n\tprivate session: Session;\n\tprivate readonly sessionFacade: HarnessSession;\n\tprivate readonly lifecycle: OperationLifecycleController;\n\tprivate readonly sessionWrites: SessionWriteCoordinator<AgentMessage>;\n\tprivate model: Model<any>;\n\tprivate thinkingLevel: ThinkingLevel;\n\tprivate systemPrompt: AgentHarnessOptions<TSkill, TPromptTemplate, TTool>[\"systemPrompt\"];\n\tprivate streamOptions: AgentHarnessStreamOptions;\n\tprivate compactionSettings: CompactionSettings;\n\tprivate getApiKeyAndHeaders?: AgentHarnessOptions[\"getApiKeyAndHeaders\"];\n\tprivate resources: AgentHarnessResources<TSkill, TPromptTemplate>;\n\tprivate tools = new Map<string, TTool>();\n\tprivate activeToolNames: string[];\n\tprivate steerQueue: UserMessage[] = [];\n\tprivate steeringQueueMode: QueueMode;\n\tprivate followUpQueue: UserMessage[] = [];\n\tprivate followUpQueueMode: QueueMode;\n\tprivate nextTurnQueue: AgentMessage[] = [];\n\tprivate handlers = new Map<string, Set<AgentHarnessHandler>>();\n\tprivate readonly subscribers = new SubscriberFanout<AgentHarnessEvent<TSkill, TPromptTemplate>>();\n\tprivate readonly deferredCommands = new DeferredCommandQueue(() => this.lifecycle.getSnapshot().tag === \"idle\");\n\n\tconstructor(options: AgentHarnessOptions<TSkill, TPromptTemplate, TTool>) {\n\t\tthis.env = options.env;\n\t\tthis.session = options.session;\n\t\tthis.sessionWrites = new SessionWriteCoordinator(this.session);\n\t\tthis.lifecycle = new OperationLifecycleController({\n\t\t\tcreateOperationId: () => uuidv7(),\n\t\t\tnow: () => Date.now(),\n\t\t});\n\t\tthis.sessionFacade = new HarnessSessionFacade(this.session, () => this.currentPhase(), this.sessionWrites);\n\t\tthis.resources = options.resources ?? {};\n\t\tthis.streamOptions = cloneStreamOptions(options.streamOptions);\n\t\tthis.compactionSettings = { ...DEFAULT_COMPACTION_SETTINGS, ...options.compaction };\n\t\tthis.systemPrompt = options.systemPrompt;\n\t\tthis.getApiKeyAndHeaders = options.getApiKeyAndHeaders;\n\t\tthis.validateUniqueNames(\n\t\t\t(options.tools ?? []).map((tool) => tool.name),\n\t\t\t\"Duplicate tool name(s)\",\n\t\t);\n\t\tfor (const tool of options.tools ?? []) {\n\t\t\tthis.tools.set(tool.name, tool);\n\t\t}\n\t\tthis.model = options.model;\n\t\tthis.thinkingLevel = options.thinkingLevel ?? \"off\";\n\t\tthis.activeToolNames = options.activeToolNames\n\t\t\t? [...options.activeToolNames]\n\t\t\t: (options.tools ?? []).map((tool) => tool.name);\n\t\tthis.validateUniqueNames(this.activeToolNames, \"Duplicate active tool name(s)\");\n\t\tthis.validateToolNames(this.activeToolNames);\n\t\tthis.steeringQueueMode = options.steeringMode ?? \"one-at-a-time\";\n\t\tthis.followUpQueueMode = options.followUpMode ?? \"one-at-a-time\";\n\t}\n\n\tprivate async emitOwn(event: AgentHarnessOwnEvent<TSkill, TPromptTemplate>, signal?: AbortSignal): Promise<void> {\n\t\tawait this.emitAny(event as AgentHarnessEvent<TSkill, TPromptTemplate>, signal);\n\t}\n\n\t/** Subscriber fan-out; the self-wait barrier lives in `SubscriberFanout`. */\n\tprivate async emitAny(event: AgentHarnessEvent<TSkill, TPromptTemplate>, signal?: AbortSignal): Promise<void> {\n\t\tawait this.subscribers.emit(event, this.lifecycle.getCurrentOperation()?.operationId, signal);\n\t}\n\n\t/** Fail closed when an awaited listener tries to wait on its own operation. */\n\tprivate rejectCurrentOperationSelfWait(api: string): void {\n\t\tthis.subscribers.assertNotSelfWait(api, this.lifecycle.getCurrentOperation()?.operationId);\n\t}\n\n\tprivate async emitHook<TType extends keyof AgentHarnessEventResultMap>(\n\t\tevent: Extract<AgentHarnessOwnEvent, { type: TType }>,\n\t): Promise<AgentHarnessEventResultMap[TType] | undefined> {\n\t\tconst handlers = this.handlers.get(event.type as TType);\n\t\tif (!handlers || handlers.size === 0) return undefined;\n\t\tlet lastResult: AgentHarnessEventResultMap[TType] | undefined;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler(event);\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tlastResult = result;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn lastResult;\n\t}\n\n\tprivate async emitBeforeProviderRequest(\n\t\tmodel: Model<any>,\n\t\tsessionId: string,\n\t\tstreamOptions: AgentHarnessStreamOptions,\n\t): Promise<AgentHarnessStreamOptions> {\n\t\tconst handlers = this.handlers.get(\"before_provider_request\");\n\t\tlet current = cloneStreamOptions(streamOptions);\n\t\tif (!handlers || handlers.size === 0) return current;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler({\n\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\tmodel,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tstreamOptions: cloneStreamOptions(current),\n\t\t\t\t});\n\t\t\t\tif (result?.streamOptions) {\n\t\t\t\t\tcurrent = applyStreamOptionsPatch(current, result.streamOptions);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate async emitBeforeProviderPayload(model: Model<any>, payload: unknown): Promise<unknown> {\n\t\tconst handlers = this.handlers.get(\"before_provider_payload\");\n\t\tlet current = payload;\n\t\tif (!handlers || handlers.size === 0) return current;\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\tconst result = await handler({ type: \"before_provider_payload\", model, payload: current });\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tcurrent = result.payload;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t}\n\t\treturn current;\n\t}\n\n\tprivate async emitQueueUpdate(): Promise<void> {\n\t\tawait this.emitOwn({\n\t\t\ttype: \"queue_update\",\n\t\t\tsteer: [...this.steerQueue],\n\t\t\tfollowUp: [...this.followUpQueue],\n\t\t\tnextTurn: [...this.nextTurnQueue],\n\t\t});\n\t}\n\n\t/**\n\t * Facade write-gate vocabulary mapped from lifecycle state. `settling` maps\n\t * to \"idle\": the queue is drained by the settlement finalizer first, and\n\t * listener writes persist after it through the coordinator tail.\n\t */\n\tprivate currentPhase(): AgentHarnessPhase {\n\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\tif (snapshot.tag !== \"active\") return \"idle\";\n\t\tswitch (snapshot.operation.kind) {\n\t\t\tcase \"manual_compaction\":\n\t\t\t\treturn \"compaction\";\n\t\t\tcase \"tree_navigation\":\n\t\t\t\treturn \"branch_summary\";\n\t\t\tdefault:\n\t\t\t\treturn \"turn\";\n\t\t}\n\t}\n\n\t/** Config writes persist immediately outside an active operation and queue during one. */\n\tprivate async persistConfigChange(write: QueuedSessionWrite<AgentMessage>): Promise<void> {\n\t\tif (this.lifecycle.getSnapshot().tag !== \"active\") {\n\t\t\tawait this.sessionWrites.persistAfterPending(write);\n\t\t} else {\n\t\t\tthis.sessionWrites.enqueue(write);\n\t\t}\n\t}\n\n\t/**\n\t * Single wrapper for every public operation: begin a lease, run the body,\n\t * then settle exactly once. The final flush and the `settled` event happen\n\t * inside the settling barrier; a finalizer failure never reports success.\n\t */\n\tprivate async runOperation<T>(\n\t\tkind: HarnessOperationKind,\n\t\tfallbackCode: AgentHarnessError[\"code\"],\n\t\tbody: (lease: OperationLease) => Promise<T>,\n\t\tclassifyResult?: (result: T) => HarnessOperationOutcome | undefined,\n\t): Promise<T> {\n\t\tconst lease = this.lifecycle.begin(kind);\n\t\tlet result: T | undefined;\n\t\tlet bodyError: unknown;\n\t\t// Everything after a successful begin() runs inside one capture region. A\n\t\t// throwing `operation_started` listener must not escape before settle(),\n\t\t// or the lifecycle would stay active and wedge the harness at \"busy\".\n\t\ttry {\n\t\t\tawait this.emitOwn({ type: \"operation_started\", operation: lease.operation });\n\t\t\tresult = await body(lease);\n\t\t} catch (error) {\n\t\t\tbodyError = error;\n\t\t}\n\t\t// The final flush precedes classification: a persistence failure after a\n\t\t// provider success must never record or report a completed operation.\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tawait this.sessionWrites.flush();\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\t\tconst outcome = resolveOperationOutcome({\n\t\t\tsignalAborted: lease.signal.aborted,\n\t\t\tresult,\n\t\t\tbodyError,\n\t\t\tflushError,\n\t\t\tclassifyResult,\n\t\t\tfallbackCode,\n\t\t});\n\t\tlet settleError: unknown;\n\t\ttry {\n\t\t\tawait this.lifecycle.settle(lease, outcome, async () => {\n\t\t\t\tawait this.emitOwn(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"settled\",\n\t\t\t\t\t\tnextTurnCount: this.nextTurnQueue.length,\n\t\t\t\t\t\toperationId: lease.operation.operationId,\n\t\t\t\t\t\toutcome,\n\t\t\t\t\t\tattemptCount: this.lifecycle.getAttemptSummaries(lease).length,\n\t\t\t\t\t},\n\t\t\t\t\tlease.signal,\n\t\t\t\t);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tsettleError = error;\n\t\t}\n\t\t// Deferred commands registered from this operation's callbacks run now that\n\t\t// the lifecycle is idle. Not awaited: this call's result must not depend on\n\t\t// work a listener scheduled.\n\t\tvoid this.deferredCommands.drain();\n\t\tconst failure = resolveOperationFailure({ bodyError, flushError, settleError, fallbackCode });\n\t\tif (failure !== undefined) throw failure;\n\t\treturn result as T;\n\t}\n\n\tprivate async createTurnState(): Promise<AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>> {\n\t\tconst context = await this.session.buildContext();\n\t\tconst resources = this.getResources();\n\t\tconst sessionMetadata = await this.session.getMetadata();\n\t\tconst tools = [...this.tools.values()];\n\t\tconst activeTools = this.activeToolNames\n\t\t\t.map((name) => this.tools.get(name))\n\t\t\t.filter((tool): tool is TTool => tool !== undefined);\n\t\tlet systemPrompt = \"You are a helpful assistant.\";\n\t\tif (typeof this.systemPrompt === \"string\") {\n\t\t\tsystemPrompt = this.systemPrompt;\n\t\t} else if (this.systemPrompt) {\n\t\t\tsystemPrompt = await this.systemPrompt({\n\t\t\t\tenv: this.env,\n\t\t\t\tsession: this.session,\n\t\t\t\tmodel: this.model,\n\t\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\t\tactiveTools,\n\t\t\t\tresources,\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tmessages: context.messages,\n\t\t\tresources,\n\t\t\tstreamOptions: cloneStreamOptions(this.streamOptions),\n\t\t\tsessionId: sessionMetadata.id,\n\t\t\tsystemPrompt,\n\t\t\tmodel: this.model,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\ttools,\n\t\t\tactiveTools,\n\t\t};\n\t}\n\n\tprivate createContext(\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tsystemPrompt?: string,\n\t): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: systemPrompt ?? turnState.systemPrompt,\n\t\t\tmessages: turnState.messages.slice(),\n\t\t\ttools: turnState.activeTools.slice(),\n\t\t};\n\t}\n\n\tprivate createStreamFn(getTurnState: () => AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>): StreamFn {\n\t\treturn async (model, context, streamOptions) => {\n\t\t\tconst turnState = getTurnState();\n\t\t\tconst requestContext = await this.maybeAutoCompact(model, context, streamOptions?.signal);\n\t\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\t\tconst snapshotOptions: AgentHarnessStreamOptions = {\n\t\t\t\t...turnState.streamOptions,\n\t\t\t\theaders: mergeHeaders(turnState.streamOptions.headers, auth?.headers),\n\t\t\t};\n\t\t\tconst requestOptions = await this.emitBeforeProviderRequest(model, turnState.sessionId, snapshotOptions);\n\t\t\treturn streamSimple(model, requestContext, {\n\t\t\t\tcacheRetention: requestOptions.cacheRetention,\n\t\t\t\theaders: requestOptions.headers,\n\t\t\t\tmaxRetries: requestOptions.maxRetries,\n\t\t\t\tmaxRetryDelayMs: requestOptions.maxRetryDelayMs,\n\t\t\t\tmetadata: requestOptions.metadata,\n\t\t\t\tonPayload: async (payload) => await this.emitBeforeProviderPayload(model, payload),\n\t\t\t\tonResponse: async (response) => {\n\t\t\t\t\tconst headers = { ...(response.headers as Record<string, string>) };\n\t\t\t\t\tawait this.emitOwn(\n\t\t\t\t\t\t{ type: \"after_provider_response\", status: response.status, headers },\n\t\t\t\t\t\tstreamOptions?.signal,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\treasoning: streamOptions?.reasoning,\n\t\t\t\tsignal: streamOptions?.signal,\n\t\t\t\tsessionId: turnState.sessionId,\n\t\t\t\ttimeoutMs: requestOptions.timeoutMs,\n\t\t\t\ttransport: requestOptions.transport,\n\t\t\t\tapiKey: auth?.apiKey,\n\t\t\t});\n\t\t};\n\t}\n\n\tprivate async drainQueuedMessages(queue: AgentMessage[], mode: QueueMode): Promise<AgentMessage[]> {\n\t\tconst messages = mode === \"all\" ? queue.splice(0) : queue.splice(0, 1);\n\t\tif (messages.length === 0) return messages;\n\t\ttry {\n\t\t\tawait this.emitQueueUpdate();\n\t\t\treturn messages;\n\t\t} catch (error) {\n\t\t\tqueue.unshift(...messages);\n\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t}\n\t}\n\n\tprivate createLoopConfig(\n\t\tgetTurnState: () => AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tsetTurnState: (turnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>) => void,\n\t\tlease?: OperationLease,\n\t): AgentLoopConfig {\n\t\tconst turnState = getTurnState();\n\t\treturn {\n\t\t\tmodel: turnState.model,\n\t\t\treasoning: turnState.thinkingLevel === \"off\" ? undefined : turnState.thinkingLevel,\n\t\t\tconvertToLlm,\n\t\t\ttransformContext: async (messages) => {\n\t\t\t\tconst result = await this.emitHook({ type: \"context\", messages: [...messages] });\n\t\t\t\treturn result?.messages ?? messages;\n\t\t\t},\n\t\t\tbeforeToolCall: async ({ toolCall, args }) => {\n\t\t\t\tconst result = await this.emitHook({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t});\n\t\t\t\treturn result ? { block: result.block, reason: result.reason } : undefined;\n\t\t\t},\n\t\t\tafterToolCall: async ({ toolCall, args, result, isError }) => {\n\t\t\t\tconst patch = await this.emitHook({\n\t\t\t\t\ttype: \"tool_result\",\n\t\t\t\t\ttoolCallId: toolCall.id,\n\t\t\t\t\ttoolName: toolCall.name,\n\t\t\t\t\tinput: args as Record<string, unknown>,\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tdetails: result.details,\n\t\t\t\t\tisError,\n\t\t\t\t});\n\t\t\t\treturn patch\n\t\t\t\t\t? { content: patch.content, details: patch.details, isError: patch.isError, terminate: patch.terminate }\n\t\t\t\t\t: undefined;\n\t\t\t},\n\t\t\tprepareNextTurn: async () => {\n\t\t\t\tawait this.sessionWrites.flush();\n\t\t\t\tif (lease) {\n\t\t\t\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\t\t\t\tif (snapshot.tag === \"active\" && snapshot.stage === \"save_point\") {\n\t\t\t\t\t\tthis.lifecycle.setStage(lease, \"attempt_running\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst nextTurnState = await this.createTurnState();\n\t\t\t\tsetTurnState(nextTurnState);\n\t\t\t\treturn {\n\t\t\t\t\tcontext: this.createContext(nextTurnState),\n\t\t\t\t\tmodel: nextTurnState.model,\n\t\t\t\t\tthinkingLevel: nextTurnState.thinkingLevel,\n\t\t\t\t};\n\t\t\t},\n\t\t\tgetSteeringMessages: async () => this.drainQueuedMessages(this.steerQueue, this.steeringQueueMode),\n\t\t\tgetFollowUpMessages: async () => this.drainQueuedMessages(this.followUpQueue, this.followUpQueueMode),\n\t\t};\n\t}\n\n\tprivate validateUniqueNames(names: string[], message: string): void {\n\t\tconst duplicates = findDuplicateNames(names);\n\t\tif (duplicates.length > 0)\n\t\t\tthrow new AgentHarnessError(\"invalid_argument\", `${message}: ${duplicates.join(\", \")}`);\n\t}\n\n\tprivate validateToolNames(toolNames: string[], tools: Map<string, TTool> = this.tools): void {\n\t\tthis.validateUniqueNames(toolNames, \"Duplicate active tool name(s)\");\n\t\tconst missing = toolNames.filter((name) => !tools.has(name));\n\t\tif (missing.length > 0) throw new AgentHarnessError(\"invalid_argument\", `Unknown tool(s): ${missing.join(\", \")}`);\n\t}\n\n\tprivate async handleAgentEvent(event: AgentEvent, signal?: AbortSignal, lease?: OperationLease): Promise<void> {\n\t\tif (event.type === \"message_end\") {\n\t\t\tawait this.session.appendMessage(event.message);\n\t\t\tawait this.emitAny(event, signal);\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"turn_end\") {\n\t\t\tlet eventError: unknown;\n\t\t\ttry {\n\t\t\t\tawait this.emitAny(event, signal);\n\t\t\t} catch (error) {\n\t\t\t\teventError = error;\n\t\t\t}\n\t\t\t// The flush runs even after a failing listener so accepted writes are\n\t\t\t// not stranded; a failing flush must then report next to that listener\n\t\t\t// error, not in place of it.\n\t\t\tconst hadPendingMutations = this.sessionWrites.hasPending();\n\t\t\tlet flushError: unknown;\n\t\t\ttry {\n\t\t\t\tawait this.sessionWrites.flush();\n\t\t\t} catch (error) {\n\t\t\t\tflushError = error;\n\t\t\t}\n\t\t\tif (lease) {\n\t\t\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\t\t\tif (snapshot.tag === \"active\" && snapshot.stage === \"attempt_running\") {\n\t\t\t\t\tthis.lifecycle.setStage(lease, \"save_point\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst failure = combineBoundaryErrors(\n\t\t\t\t[eventError, flushError],\n\t\t\t\t\"turn_end listener failed and the save-point flush failed\",\n\t\t\t\t\"hook\",\n\t\t\t);\n\t\t\tif (failure !== undefined) throw failure;\n\t\t\tawait this.emitOwn({ type: \"save_point\", hadPendingMutations });\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"agent_end\") {\n\t\t\t// agent_end is an attempt event: flush its accepted writes, but lifecycle\n\t\t\t// settlement and the settled event belong to OperationLease.settle().\n\t\t\tawait this.sessionWrites.flush();\n\t\t\tawait this.emitAny(event, signal);\n\t\t\treturn;\n\t\t}\n\t\tawait this.emitAny(event, signal);\n\t}\n\n\tprivate async emitRunFailure(\n\t\tmodel: Model<any>,\n\t\terror: unknown,\n\t\taborted: boolean,\n\t\tsignal: AbortSignal,\n\t\tcompletedMessages: readonly AgentMessage[],\n\t\tlease?: OperationLease,\n\t): Promise<AgentMessage[]> {\n\t\tconst failureMessage = createFailureMessage(model, error, aborted);\n\t\tconst messages = [...completedMessages, failureMessage];\n\t\tawait this.handleAgentEvent({ type: \"message_start\", message: failureMessage }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"message_end\", message: failureMessage }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"turn_end\", message: failureMessage, toolResults: [] }, signal, lease);\n\t\tawait this.handleAgentEvent({ type: \"agent_end\", messages }, signal, lease);\n\t\treturn messages;\n\t}\n\n\tprivate async executeTurn(\n\t\tlease: OperationLease,\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\ttext: string,\n\t\toptions?: { images?: ImageContent[] },\n\t): Promise<AssistantMessage> {\n\t\tlet messages: AgentMessage[] = [createUserMessage(text, options?.images)];\n\t\tif (this.nextTurnQueue.length > 0) {\n\t\t\tconst queuedMessages = this.nextTurnQueue.splice(0);\n\t\t\ttry {\n\t\t\t\tawait this.emitQueueUpdate();\n\t\t\t} catch (error) {\n\t\t\t\tthis.nextTurnQueue.unshift(...queuedMessages);\n\t\t\t\tthrow normalizeHarnessError(error, \"hook\");\n\t\t\t}\n\t\t\tmessages = [...queuedMessages, messages[0]!];\n\t\t}\n\t\tconst beforeResult = await this.emitHook({\n\t\t\ttype: \"before_agent_start\",\n\t\t\tprompt: text,\n\t\t\timages: options?.images,\n\t\t\tsystemPrompt: turnState.systemPrompt,\n\t\t\tresources: turnState.resources,\n\t\t});\n\t\tif (beforeResult?.messages) messages = [...messages, ...beforeResult.messages];\n\n\t\tconst result = await this.executeAgentRun(\n\t\t\tlease,\n\t\t\t\"initial\",\n\t\t\tturnState,\n\t\t\tthis.createContext(turnState, beforeResult?.systemPrompt),\n\t\t\tmessages,\n\t\t);\n\t\treturn await this.recoverContextOverflow(lease, result);\n\t}\n\n\t/**\n\t * Sole attempt boundary: begin, announce, run, classify, close, announce, flush.\n\t *\n\t * Once `beginAttempt()` succeeds the attempt is closed exactly once on every\n\t * path, so `count(attempt_started) == count(attempt_finished)` holds even when\n\t * the `attempt_started` observer throws. `attempt_finished` is emitted only\n\t * after the attempt is already closed, so a throwing observer can fail the\n\t * operation but can never reopen committed attempt state. The closing flush\n\t * is not a `finally`: a `finally` that awaits a throwing flush would replace\n\t * the body error, hiding the provider or listener failure from the audit trail.\n\t */\n\tprivate async runAttempt<T>(\n\t\tlease: OperationLease,\n\t\treason: HarnessAttemptReason,\n\t\tbody: (attempt: AttemptLease) => Promise<T>,\n\t\tclassify: (result: T) => HarnessAttemptOutcome,\n\t): Promise<T> {\n\t\tconst attemptLease = this.lifecycle.beginAttempt(lease, reason);\n\t\tlet result: T | undefined;\n\t\tlet bodyError: unknown;\n\t\ttry {\n\t\t\tawait this.emitOwn({ type: \"attempt_started\", attempt: attemptLease.attempt }, lease.signal);\n\t\t\tresult = await body(attemptLease);\n\t\t} catch (error) {\n\t\t\tbodyError = error;\n\t\t}\n\t\tconst outcome: HarnessAttemptOutcome =\n\t\t\tbodyError === undefined ? classify(result as T) : classifyAttemptFailure(bodyError);\n\t\tthis.lifecycle.finishAttempt(lease, attemptLease, outcome);\n\t\tlet observerError: unknown;\n\t\ttry {\n\t\t\tawait this.emitOwn(\n\t\t\t\t{ type: \"attempt_finished\", summary: this.lifecycle.getAttemptSummary(lease, attemptLease) },\n\t\t\t\tlease.signal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tobserverError = error;\n\t\t}\n\t\tlet flushError: unknown;\n\t\ttry {\n\t\t\tawait this.sessionWrites.flush();\n\t\t} catch (error) {\n\t\t\tflushError = error;\n\t\t}\n\t\tconst failure = combineBoundaryErrors(\n\t\t\t[bodyError, observerError, flushError],\n\t\t\t\"Attempt failed and its attempt_finished reporting or closing flush failed\",\n\t\t\t\"unknown\",\n\t\t);\n\t\tif (failure !== undefined) throw failure;\n\t\treturn result as T;\n\t}\n\n\tprivate async executeAgentRun(\n\t\tlease: OperationLease,\n\t\treason: HarnessAttemptReason,\n\t\tturnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>,\n\t\tcontext: AgentContext,\n\t\tinitialMessages?: AgentMessage[],\n\t): Promise<AssistantMessage> {\n\t\tlet activeTurnState = turnState;\n\t\treturn await this.runAttempt(\n\t\t\tlease,\n\t\t\treason,\n\t\t\tasync (attemptLease) => {\n\t\t\t\tconst signal = attemptLease.signal;\n\t\t\t\tconst getTurnState = () => activeTurnState;\n\t\t\t\tconst setTurnState = (nextTurnState: AgentHarnessTurnState<TSkill, TPromptTemplate, TTool>) => {\n\t\t\t\t\tactiveTurnState = nextTurnState;\n\t\t\t\t};\n\t\t\t\tconst completedMessages: AgentMessage[] = [];\n\t\t\t\tconst emit = async (event: AgentEvent): Promise<void> => {\n\t\t\t\t\tif (event.type === \"message_end\") completedMessages.push(event.message);\n\t\t\t\t\tawait this.handleAgentEvent(event, signal, lease);\n\t\t\t\t};\n\t\t\t\tlet newMessages: AgentMessage[];\n\t\t\t\ttry {\n\t\t\t\t\tconst loopConfig = this.createLoopConfig(getTurnState, setTurnState, lease);\n\t\t\t\t\tconst streamFn = this.createStreamFn(getTurnState);\n\t\t\t\t\tnewMessages = initialMessages\n\t\t\t\t\t\t? await runAgentLoop(initialMessages, context, loopConfig, emit, signal, streamFn)\n\t\t\t\t\t\t: await runAgentLoopContinue(context, loopConfig, emit, signal, streamFn);\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnewMessages = await this.emitRunFailure(\n\t\t\t\t\t\t\tactiveTurnState.model,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\tsignal.aborted,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tcompletedMessages,\n\t\t\t\t\t\t\tlease,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (failureError) {\n\t\t\t\t\t\tconst cause = new AggregateError(\n\t\t\t\t\t\t\t[toError(error), toError(failureError)],\n\t\t\t\t\t\t\t\"Agent run failed and failure reporting failed\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthrow new AgentHarnessError(\"unknown\", cause.message, cause);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (let i = newMessages.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst message = newMessages[i]!;\n\t\t\t\t\tif (message.role === \"assistant\") return message;\n\t\t\t\t}\n\t\t\t\tthrow new AgentHarnessError(\"invalid_state\", \"AgentHarness prompt completed without an assistant message\");\n\t\t\t},\n\t\t\t(message) => classifyAttemptOutcome(message, activeTurnState.model.contextWindow),\n\t\t);\n\t}\n\n\t/**\n\t * One-shot overflow recovery inside the originating operation. The lease is\n\t * proof that this operation still owns the harness, so no run-ownership or\n\t * phase re-check is needed; a strict lifecycle makes a newer operation\n\t * starting mid-recovery impossible.\n\t */\n\tprivate async recoverContextOverflow(lease: OperationLease, message: AssistantMessage): Promise<AssistantMessage> {\n\t\tif (!this.compactionSettings.enabled || !isContextOverflow(message, this.model.contextWindow)) {\n\t\t\treturn message;\n\t\t}\n\t\tif (!this.getApiKeyAndHeaders) return message;\n\t\tconst leafId = await this.session.getLeafId();\n\t\tif (!leafId) return message;\n\t\tconst leaf = await this.session.getEntry(leafId);\n\t\tif (\n\t\t\tleaf?.type !== \"message\" ||\n\t\t\tleaf.message.role !== \"assistant\" ||\n\t\t\tleaf.message.timestamp !== message.timestamp ||\n\t\t\t!isContextOverflow(leaf.message, this.model.contextWindow)\n\t\t) {\n\t\t\treturn message;\n\t\t}\n\n\t\tawait this.session.moveTo(leaf.parentId);\n\t\tthis.lifecycle.setStage(lease, \"recovering_overflow\");\n\t\ttry {\n\t\t\tconst compacted = await this.runCompaction({ automatic: true, signal: lease.signal });\n\t\t\tif (!compacted) {\n\t\t\t\tawait this.session.moveTo(leafId);\n\t\t\t\treturn message;\n\t\t\t}\n\t\t\tconst turnState = await this.createTurnState();\n\t\t\treturn await this.executeAgentRun(\n\t\t\t\tlease,\n\t\t\t\t\"context_overflow_recovery\",\n\t\t\t\tturnState,\n\t\t\t\tthis.createContext(turnState),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tawait this.session.moveTo(leafId);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync prompt(text: string, options?: { images?: ImageContent[] }): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"prompt\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\treturn await this.executeTurn(lease, turnState, text, options);\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\tasync skill(name: string, additionalInstructions?: string): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"skill\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\tconst skill = (turnState.resources.skills ?? []).find((candidate) => candidate.name === name);\n\t\t\t\tif (!skill) throw new AgentHarnessError(\"invalid_argument\", `Unknown skill: ${name}`);\n\t\t\t\treturn await this.executeTurn(lease, turnState, formatSkillInvocation(skill, additionalInstructions));\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\tasync promptFromTemplate(name: string, args: string[] = []): Promise<AssistantMessage> {\n\t\treturn this.runOperation(\n\t\t\t\"prompt_template\",\n\t\t\t\"unknown\",\n\t\t\tasync (lease) => {\n\t\t\t\tconst turnState = await this.createTurnState();\n\t\t\t\tconst template = (turnState.resources.promptTemplates ?? []).find((candidate) => candidate.name === name);\n\t\t\t\tif (!template) throw new AgentHarnessError(\"invalid_argument\", `Unknown prompt template: ${name}`);\n\t\t\t\treturn await this.executeTurn(lease, turnState, formatPromptTemplateInvocation(template, args));\n\t\t\t},\n\t\t\tclassifyAssistantOutcome,\n\t\t);\n\t}\n\n\t/**\n\t * Steering and follow-up input is consumed only by a running agent attempt.\n\t * A structural operation (`compact`, `navigateTree`) runs none, so accepting\n\t * input there would silently inject it into an unrelated later prompt.\n\t */\n\tprivate expectQueueConsumer(action: string): void {\n\t\tconst snapshot = this.lifecycle.getSnapshot();\n\t\tif (snapshot.tag !== \"active\") throw new AgentHarnessError(\"invalid_state\", `Cannot ${action} while idle`);\n\t\tif (!PROMPT_FAMILY_KINDS.includes(snapshot.operation.kind)) {\n\t\t\tthrow new AgentHarnessError(\n\t\t\t\t\"invalid_state\",\n\t\t\t\t`Cannot ${action} during ${snapshot.operation.kind}: no agent attempt can consume it`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync steer(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.expectQueueConsumer(\"steer\");\n\t\tthis.steerQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tasync followUp(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.expectQueueConsumer(\"follow up\");\n\t\tthis.followUpQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tasync nextTurn(text: string, options?: { images?: ImageContent[] }): Promise<void> {\n\t\tthis.nextTurnQueue.push(createUserMessage(text, options?.images));\n\t\tawait this.emitQueueUpdate();\n\t}\n\n\tgetSession(): HarnessSession {\n\t\treturn this.sessionFacade;\n\t}\n\n\tasync appendMessage(message: AgentMessage): Promise<void> {\n\t\tawait this.sessionFacade.appendMessage(message);\n\t}\n\n\tprivate async runCompaction(options: HarnessCompactionRunOptions): Promise<CompactResult | undefined> {\n\t\tconst model = this.model;\n\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\tif (!auth) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"auth\", \"No auth available for compaction\");\n\t\t}\n\t\tconst branchEntries = await this.session.getBranch();\n\t\tconst preparationResult = prepareCompaction(branchEntries, this.compactionSettings);\n\t\tif (!preparationResult.ok) throw preparationResult.error;\n\t\tconst preparation = preparationResult.value;\n\t\tif (!preparation) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"compaction\", \"Nothing to compact\");\n\t\t}\n\t\tconst signal = options.signal ?? new AbortController().signal;\n\t\tconst hookResult = await this.emitHook({\n\t\t\ttype: \"session_before_compact\",\n\t\t\tpreparation,\n\t\t\tbranchEntries,\n\t\t\tcustomInstructions: options.customInstructions,\n\t\t\tsignal,\n\t\t});\n\t\tif (hookResult?.cancel) {\n\t\t\tif (options.automatic) return undefined;\n\t\t\tthrow new AgentHarnessError(\"compaction\", \"Compaction cancelled\");\n\t\t}\n\t\tconst provided = hookResult?.compaction;\n\t\tconst compactResult = provided\n\t\t\t? { ok: true as const, value: provided }\n\t\t\t: await compact(\n\t\t\t\t\tpreparation,\n\t\t\t\t\tmodel,\n\t\t\t\t\tauth.apiKey,\n\t\t\t\t\tauth.headers,\n\t\t\t\t\toptions.customInstructions,\n\t\t\t\t\tsignal,\n\t\t\t\t\tthis.thinkingLevel,\n\t\t\t\t\tcreateSummarizationRetry(\"compaction\", this.streamOptions.summarizationRetry, (event) =>\n\t\t\t\t\t\tthis.emitOwn(event),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\tif (!compactResult.ok) throw compactResult.error;\n\t\tconst result = compactResult.value;\n\t\toptions.beforeCommit?.();\n\t\tconst entryId = await this.session.appendCompaction(\n\t\t\tresult.summary,\n\t\t\tresult.firstKeptEntryId,\n\t\t\tresult.tokensBefore,\n\t\t\tresult.details,\n\t\t\tprovided !== undefined,\n\t\t);\n\t\tconst entry = await this.session.getEntry(entryId);\n\t\tif (entry?.type === \"compaction\") {\n\t\t\tawait this.emitOwn({ type: \"session_compact\", compactionEntry: entry, fromHook: provided !== undefined });\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate async maybeAutoCompact(model: Model<any>, context: Context, signal?: AbortSignal): Promise<Context> {\n\t\tconst projected = estimateContextTokens(context.messages).tokens;\n\t\tif (!shouldCompact(projected, model.contextWindow ?? 0, this.compactionSettings)) return context;\n\t\tconst result = await this.runCompaction({ automatic: true, signal });\n\t\tif (!result) return context;\n\t\tconst persisted = await this.session.buildContext();\n\t\treturn { ...context, messages: convertToLlm(persisted.messages) };\n\t}\n\n\tasync compact(customInstructions?: string): Promise<CompactResult> {\n\t\treturn this.runOperation(\"manual_compaction\", \"compaction\", async (lease) => {\n\t\t\tthis.lifecycle.setStage(lease, \"structural_running\");\n\t\t\tconst result = await this.runCompaction({\n\t\t\t\tautomatic: false,\n\t\t\t\tcustomInstructions,\n\t\t\t\tbeforeCommit: () => {\n\t\t\t\t\tthis.lifecycle.setStage(lease, \"committing\");\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!result) throw new AgentHarnessError(\"compaction\", \"Nothing to compact\");\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync navigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<NavigateTreeResult> {\n\t\treturn this.runOperation(\n\t\t\t\"tree_navigation\",\n\t\t\t\"branch_summary\",\n\t\t\tasync (lease) => {\n\t\t\t\tthis.lifecycle.setStage(lease, \"structural_running\");\n\t\t\t\tconst oldLeafId = await this.session.getLeafId();\n\t\t\t\t// No-op navigation mutates nothing, so it completes without ever\n\t\t\t\t// entering the `committing` stage.\n\t\t\t\tif (oldLeafId === targetId) return { cancelled: false };\n\t\t\t\tconst targetEntry = await this.session.getEntry(targetId);\n\t\t\t\tif (!targetEntry) throw new AgentHarnessError(\"invalid_argument\", `Entry ${targetId} not found`);\n\t\t\t\tconst { entries, commonAncestorId } = await collectEntriesForBranchSummary(\n\t\t\t\t\tthis.session,\n\t\t\t\t\toldLeafId,\n\t\t\t\t\ttargetId,\n\t\t\t\t);\n\t\t\t\tconst preparation = {\n\t\t\t\t\ttargetId,\n\t\t\t\t\toldLeafId,\n\t\t\t\t\tcommonAncestorId,\n\t\t\t\t\tentriesToSummarize: entries,\n\t\t\t\t\tuserWantsSummary: options?.summarize ?? false,\n\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\tlabel: options?.label,\n\t\t\t\t};\n\t\t\t\tconst signal = new AbortController().signal;\n\t\t\t\tconst hookResult = await this.emitHook({ type: \"session_before_tree\", preparation, signal });\n\t\t\t\tif (hookResult?.cancel) return { cancelled: true };\n\t\t\t\tlet summaryEntry: NavigateTreeResult[\"summaryEntry\"];\n\t\t\t\tlet summaryText: string | undefined = hookResult?.summary?.summary;\n\t\t\t\tlet summaryDetails: unknown = hookResult?.summary?.details;\n\t\t\t\tif (!summaryText && options?.summarize && entries.length > 0) {\n\t\t\t\t\tconst model = this.model;\n\t\t\t\t\tif (!model) throw new AgentHarnessError(\"invalid_state\", \"No model set for branch summary\");\n\t\t\t\t\tconst auth = await this.getApiKeyAndHeaders?.(model);\n\t\t\t\t\tif (!auth) throw new AgentHarnessError(\"auth\", \"No auth available for branch summary\");\n\t\t\t\t\tconst branchSummary = await runBranchSummary({\n\t\t\t\t\t\tentries,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\t\t\theaders: auth.headers,\n\t\t\t\t\t\tcustomInstructions: hookResult?.customInstructions ?? options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: hookResult?.replaceInstructions ?? options?.replaceInstructions,\n\t\t\t\t\t\tsummarizationRetry: this.streamOptions.summarizationRetry,\n\t\t\t\t\t\temit: (event) => this.emitOwn(event),\n\t\t\t\t\t});\n\t\t\t\t\tif (branchSummary.cancelled) return { cancelled: true };\n\t\t\t\t\tsummaryText = branchSummary.summary;\n\t\t\t\t\tsummaryDetails = branchSummary.details;\n\t\t\t\t}\n\t\t\t\tconst { newLeafId, editorText } = resolveNavigationTarget(targetEntry, targetId);\n\t\t\t\t// Single declared commit point of a tree navigation.\n\t\t\t\tthis.lifecycle.setStage(lease, \"committing\");\n\t\t\t\tconst summaryId = await this.session.moveTo(\n\t\t\t\t\tnewLeafId,\n\t\t\t\t\tsummaryText\n\t\t\t\t\t\t? { summary: summaryText, details: summaryDetails, fromHook: hookResult?.summary !== undefined }\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t\tif (summaryId) {\n\t\t\t\t\tconst entry = await this.session.getEntry(summaryId);\n\t\t\t\t\tif (entry?.type === \"branch_summary\") summaryEntry = entry;\n\t\t\t\t}\n\t\t\t\tawait this.emitOwn({\n\t\t\t\t\ttype: \"session_tree\",\n\t\t\t\t\tnewLeafId: await this.session.getLeafId(),\n\t\t\t\t\toldLeafId,\n\t\t\t\t\tsummaryEntry,\n\t\t\t\t\tfromHook: hookResult?.summary !== undefined,\n\t\t\t\t});\n\t\t\t\treturn { cancelled: false, editorText, summaryEntry };\n\t\t\t},\n\t\t\tclassifyNavigateTreeOutcome,\n\t\t);\n\t}\n\n\tgetModel(): Model<any> {\n\t\treturn this.model;\n\t}\n\n\tasync setModel(model: Model<any>): Promise<void> {\n\t\ttry {\n\t\t\tconst previousModel = this.model;\n\t\t\tconst nextProvider = model.provider;\n\t\t\tconst nextModelId = model.id;\n\t\t\tawait this.persistConfigChange({ type: \"model_change\", provider: nextProvider, modelId: nextModelId });\n\t\t\tthis.model = model;\n\t\t\tawait this.emitOwn({ type: \"model_update\", model, previousModel, source: \"set\" });\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"session\");\n\t\t}\n\t}\n\n\tgetThinkingLevel(): ThinkingLevel {\n\t\treturn this.thinkingLevel;\n\t}\n\n\tasync setThinkingLevel(level: ThinkingLevel): Promise<void> {\n\t\ttry {\n\t\t\tconst previousLevel = this.thinkingLevel;\n\t\t\tawait this.persistConfigChange({ type: \"thinking_level_change\", thinkingLevel: level });\n\t\t\tthis.thinkingLevel = level;\n\t\t\tawait this.emitOwn({ type: \"thinking_level_update\", level, previousLevel });\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"session\");\n\t\t}\n\t}\n\n\tgetTools(): TTool[] {\n\t\treturn [...this.tools.values()];\n\t}\n\n\tasync setTools(tools: TTool[], activeToolNames?: string[]): Promise<void> {\n\t\ttry {\n\t\t\tthis.validateUniqueNames(\n\t\t\t\ttools.map((tool) => tool.name),\n\t\t\t\t\"Duplicate tool name(s)\",\n\t\t\t);\n\t\t\tconst nextTools = new Map(tools.map((tool) => [tool.name, tool]));\n\t\t\tconst nextActiveToolNames = activeToolNames ? [...activeToolNames] : this.activeToolNames;\n\t\t\tthis.validateToolNames(nextActiveToolNames, nextTools);\n\t\t\tconst previousToolNames = [...this.tools.keys()];\n\t\t\tconst previousActiveToolNames = [...this.activeToolNames];\n\t\t\tawait this.persistConfigChange({ type: \"active_tools_change\", activeToolNames: [...nextActiveToolNames] });\n\t\t\tthis.tools = nextTools;\n\t\t\tthis.activeToolNames = [...nextActiveToolNames];\n\t\t\tawait this.emitOwn({\n\t\t\t\ttype: \"tools_update\",\n\t\t\t\ttoolNames: [...this.tools.keys()],\n\t\t\t\tpreviousToolNames,\n\t\t\t\tactiveToolNames: [...this.activeToolNames],\n\t\t\t\tpreviousActiveToolNames,\n\t\t\t\tsource: \"set\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"invalid_argument\");\n\t\t}\n\t}\n\n\tgetActiveTools(): TTool[] {\n\t\treturn this.activeToolNames.map((name) => this.tools.get(name)!);\n\t}\n\n\tasync setActiveTools(toolNames: string[]): Promise<void> {\n\t\ttry {\n\t\t\tconst nextActiveToolNames = [...toolNames];\n\t\t\tthis.validateToolNames(nextActiveToolNames);\n\t\t\tconst previousToolNames = [...this.tools.keys()];\n\t\t\tconst previousActiveToolNames = [...this.activeToolNames];\n\t\t\tawait this.persistConfigChange({ type: \"active_tools_change\", activeToolNames: [...nextActiveToolNames] });\n\t\t\tthis.activeToolNames = [...nextActiveToolNames];\n\t\t\tawait this.emitOwn({\n\t\t\t\ttype: \"tools_update\",\n\t\t\t\ttoolNames: [...this.tools.keys()],\n\t\t\t\tpreviousToolNames,\n\t\t\t\tactiveToolNames: [...this.activeToolNames],\n\t\t\t\tpreviousActiveToolNames,\n\t\t\t\tsource: \"set\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow normalizeHarnessError(error, \"invalid_argument\");\n\t\t}\n\t}\n\n\tgetSteeringMode(): QueueMode {\n\t\treturn this.steeringQueueMode;\n\t}\n\n\tasync setSteeringMode(mode: QueueMode): Promise<void> {\n\t\tthis.steeringQueueMode = mode;\n\t}\n\n\tgetFollowUpMode(): QueueMode {\n\t\treturn this.followUpQueueMode;\n\t}\n\n\tasync setFollowUpMode(mode: QueueMode): Promise<void> {\n\t\tthis.followUpQueueMode = mode;\n\t}\n\n\tgetResources(): AgentHarnessResources<TSkill, TPromptTemplate> {\n\t\treturn {\n\t\t\tskills: this.resources.skills?.slice(),\n\t\t\tpromptTemplates: this.resources.promptTemplates?.slice(),\n\t\t};\n\t}\n\n\tasync setResources(resources: AgentHarnessResources<TSkill, TPromptTemplate>): Promise<void> {\n\t\tconst previousResources = this.getResources();\n\t\tthis.resources = {\n\t\t\tskills: resources.skills?.slice(),\n\t\t\tpromptTemplates: resources.promptTemplates?.slice(),\n\t\t};\n\t\tawait this.emitOwn({ type: \"resources_update\", resources: this.getResources(), previousResources });\n\t}\n\n\tgetStreamOptions(): AgentHarnessStreamOptions {\n\t\treturn cloneStreamOptions(this.streamOptions);\n\t}\n\n\tasync setStreamOptions(streamOptions: AgentHarnessStreamOptions): Promise<void> {\n\t\tthis.streamOptions = cloneStreamOptions(streamOptions);\n\t}\n\n\t/**\n\t * Deliver the abort signal to the current operation without waiting for it to\n\t * settle. Safe from an operation's own callbacks: nothing here awaits\n\t * settlement, so it cannot form the cycle `abort()` has to refuse.\n\t */\n\trequestAbort(): AbortSignalDeliveryResult {\n\t\tassertAbortAllowed(this.lifecycle.getSnapshot());\n\t\treturn describeAbortDelivery(this.lifecycle.requestAbort());\n\t}\n\n\t/**\n\t * Queue work to run once the harness is idle and return its ref immediately.\n\t *\n\t * This is the callback-safe way to schedule follow-up work: awaiting\n\t * `waitForIdle()` or `abort()` from a callback of the operation being settled\n\t * deadlocks, because settlement awaits that callback. The ref reports the\n\t * command's outcome and cancels it while it is still queued.\n\t */\n\tasync runWhenIdle(command: DeferredHarnessCommand): Promise<CommandRef> {\n\t\treturn this.deferredCommands.enqueue(command);\n\t}\n\n\tasync abort(): Promise<AbortResult> {\n\t\t// Aborting awaits the captured operation's settlement, so a listener of that\n\t\t// same operation must never reach the wait below.\n\t\tthis.rejectCurrentOperationSelfWait(\"abort()\");\n\t\tassertAbortAllowed(this.lifecycle.getSnapshot());\n\t\t// Capture the current operation before delivering any signal: an operation\n\t\t// started later by a settlement listener is never this call's target.\n\t\tconst capture = this.lifecycle.requestAbort();\n\t\tconst clearedSteer = this.steerQueue.splice(0);\n\t\tconst clearedFollowUp = this.followUpQueue.splice(0);\n\t\tconst errors = await collectStepErrors([\n\t\t\t() => this.emitQueueUpdate(),\n\t\t\tasync () => {\n\t\t\t\tif (capture.target) await capture.target.settled;\n\t\t\t},\n\t\t\t() => this.emitOwn({ type: \"abort\", clearedSteer, clearedFollowUp }),\n\t\t]);\n\t\tif (errors.length > 0) {\n\t\t\tconst cause = errors.length === 1 ? errors[0]! : new AggregateError(errors, \"Abort completed with errors\");\n\t\t\tthrow normalizeHarnessError(cause, \"hook\");\n\t\t}\n\t\treturn { clearedSteer, clearedFollowUp };\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\tthis.rejectCurrentOperationSelfWait(\"waitForIdle()\");\n\t\t// Delegates to the lifecycle: resolves once no operation is active or settling.\n\t\tawait this.lifecycle.waitForIdle();\n\t}\n\n\tsubscribe(\n\t\tlistener: (event: AgentHarnessEvent<TSkill, TPromptTemplate>, signal?: AbortSignal) => Promise<void> | void,\n\t): () => void {\n\t\treturn this.subscribers.subscribe(listener);\n\t}\n\n\ton<TType extends keyof AgentHarnessEventResultMap>(\n\t\ttype: TType,\n\t\thandler: (\n\t\t\tevent: Extract<AgentHarnessOwnEvent, { type: TType }>,\n\t\t) => Promise<AgentHarnessEventResultMap[TType]> | AgentHarnessEventResultMap[TType],\n\t): () => void {\n\t\tlet handlers = this.handlers.get(type);\n\t\tif (!handlers) {\n\t\t\thandlers = new Set();\n\t\t\tthis.handlers.set(type, handlers);\n\t\t}\n\t\thandlers.add(handler as AgentHarnessHandler);\n\t\treturn () => handlers!.delete(handler as AgentHarnessHandler);\n\t}\n}\n"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Browser-safe canonical serialization and SHA-256 for harness identities.
3
+ *
4
+ * Every digest the harness binds to an operation, attempt, effect, or trace
5
+ * must be reproducible from the same logical value on any host, so this module
6
+ * fixes two things and imports nothing:
7
+ *
8
+ * 1. `canonicalJson` — a JCS-style (RFC 8785) serialization: object keys sorted
9
+ * by UTF-16 code unit, no whitespace, ES number formatting, `undefined`
10
+ * properties omitted. Non-finite numbers, bigint, functions, symbols, and
11
+ * non-plain objects are rejected instead of silently coerced, because a
12
+ * digest over a lossy encoding is not a commitment to the value.
13
+ * 2. `sha256Hex` — a synchronous pure-TypeScript SHA-256, so pure reducers can
14
+ * derive identities without an async `crypto.subtle` round trip or a Node
15
+ * `node:crypto` import that the browser entry point cannot carry.
16
+ *
17
+ * `domainDigest` adds domain separation: the same parts hashed under two
18
+ * domains never collide, and a part list is length-delimited through the
19
+ * canonical encoding so `["ab","c"]` and `["a","bc"]` differ.
20
+ */
21
+ export declare function canonicalJson(value: unknown): string;
22
+ /** Lowercase hex SHA-256 of a UTF-8 string or raw bytes. Synchronous and dependency-free. */
23
+ export declare function sha256Hex(input: string | Uint8Array): string;
24
+ /** SHA-256 of the canonical JSON encoding of `value`. */
25
+ export declare function canonicalDigest(value: unknown): string;
26
+ /**
27
+ * Domain-separated digest over an ordered part list. The parts are committed
28
+ * through canonical JSON, so boundaries between parts are unambiguous and a
29
+ * different domain string always yields a different digest.
30
+ */
31
+ export declare function domainDigest(domain: string, parts: readonly string[]): string;
32
+ //# sourceMappingURL=canonical-digest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical-digest.d.ts","sourceRoot":"","sources":["../../src/harness/canonical-digest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEpD;AAqHD,6FAA6F;AAC7F,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAS5D;AAED,yDAAyD;AACzD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEtD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAG7E","sourcesContent":["/**\n * Browser-safe canonical serialization and SHA-256 for harness identities.\n *\n * Every digest the harness binds to an operation, attempt, effect, or trace\n * must be reproducible from the same logical value on any host, so this module\n * fixes two things and imports nothing:\n *\n * 1. `canonicalJson` — a JCS-style (RFC 8785) serialization: object keys sorted\n * by UTF-16 code unit, no whitespace, ES number formatting, `undefined`\n * properties omitted. Non-finite numbers, bigint, functions, symbols, and\n * non-plain objects are rejected instead of silently coerced, because a\n * digest over a lossy encoding is not a commitment to the value.\n * 2. `sha256Hex` — a synchronous pure-TypeScript SHA-256, so pure reducers can\n * derive identities without an async `crypto.subtle` round trip or a Node\n * `node:crypto` import that the browser entry point cannot carry.\n *\n * `domainDigest` adds domain separation: the same parts hashed under two\n * domains never collide, and a part list is length-delimited through the\n * canonical encoding so `[\"ab\",\"c\"]` and `[\"a\",\"bc\"]` differ.\n */\n\nexport function canonicalJson(value: unknown): string {\n\treturn serialize(value, new WeakSet<object>());\n}\n\nfunction serialize(value: unknown, ancestors: WeakSet<object>): string {\n\tif (value === null) return \"null\";\n\tswitch (typeof value) {\n\t\tcase \"string\":\n\t\t\treturn JSON.stringify(value);\n\t\tcase \"boolean\":\n\t\t\treturn value ? \"true\" : \"false\";\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(value)) throw new TypeError(\"canonicalJson: non-finite numbers are not representable\");\n\t\t\treturn JSON.stringify(value);\n\t\tcase \"object\":\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`canonicalJson: unsupported value of type ${typeof value}`);\n\t}\n\tconst object = value as object;\n\tif (ancestors.has(object)) throw new TypeError(\"canonicalJson: cyclic values are not representable\");\n\tancestors.add(object);\n\ttry {\n\t\tif (Array.isArray(object)) {\n\t\t\tconst items = object.map((item) => {\n\t\t\t\tif (item === undefined)\n\t\t\t\t\tthrow new TypeError(\"canonicalJson: undefined array elements are not representable\");\n\t\t\t\treturn serialize(item, ancestors);\n\t\t\t});\n\t\t\treturn `[${items.join(\",\")}]`;\n\t\t}\n\t\tconst prototype = Object.getPrototypeOf(object);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow new TypeError(\"canonicalJson: only plain objects are representable\");\n\t\t}\n\t\tconst record = object as Record<string, unknown>;\n\t\tconst keys = Object.keys(record)\n\t\t\t.filter((key) => record[key] !== undefined)\n\t\t\t.sort(compareCodeUnits);\n\t\tconst members = keys.map((key) => `${JSON.stringify(key)}:${serialize(record[key], ancestors)}`);\n\t\treturn `{${members.join(\",\")}}`;\n\t} finally {\n\t\tancestors.delete(object);\n\t}\n}\n\n/** RFC 8785 orders keys by UTF-16 code unit, which is what `<` gives on JS strings. */\nfunction compareCodeUnits(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nconst ROUND_CONSTANTS = new Uint32Array([\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,\n\t0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n\t0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,\n\t0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n\t0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n\t0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n\t0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,\n\t0xc67178f2,\n]);\n\nconst INITIAL_STATE = new Uint32Array([\n\t0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\nfunction rotateRight(value: number, bits: number): number {\n\treturn (value >>> bits) | (value << (32 - bits));\n}\n\n/** Pad the message per FIPS 180-4 §5.1.1: 0x80, zeros, then the 64-bit big-endian bit length. */\nfunction padMessage(bytes: Uint8Array): DataView {\n\tconst bitLength = bytes.length * 8;\n\tconst paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;\n\tconst padded = new Uint8Array(paddedLength);\n\tpadded.set(bytes);\n\tpadded[bytes.length] = 0x80;\n\tconst view = new DataView(padded.buffer);\n\tview.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false);\n\tview.setUint32(paddedLength - 4, bitLength >>> 0, false);\n\treturn view;\n}\n\nfunction compressBlock(state: Uint32Array, schedule: Uint32Array, view: DataView, offset: number): void {\n\tfor (let index = 0; index < 16; index++) schedule[index] = view.getUint32(offset + index * 4, false);\n\tfor (let index = 16; index < 64; index++) {\n\t\tconst w15 = schedule[index - 15];\n\t\tconst w2 = schedule[index - 2];\n\t\tconst sigma0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ (w15 >>> 3);\n\t\tconst sigma1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ (w2 >>> 10);\n\t\tschedule[index] = (schedule[index - 16] + sigma0 + schedule[index - 7] + sigma1) >>> 0;\n\t}\n\tlet [a, b, c, d, e, f, g, h] = state;\n\tfor (let index = 0; index < 64; index++) {\n\t\tconst bigSigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n\t\tconst choose = (e & f) ^ (~e & g);\n\t\tconst temp1 = (h + bigSigma1 + choose + ROUND_CONSTANTS[index] + schedule[index]) >>> 0;\n\t\tconst bigSigma0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n\t\tconst majority = (a & b) ^ (a & c) ^ (b & c);\n\t\tconst temp2 = (bigSigma0 + majority) >>> 0;\n\t\th = g;\n\t\tg = f;\n\t\tf = e;\n\t\te = (d + temp1) >>> 0;\n\t\td = c;\n\t\tc = b;\n\t\tb = a;\n\t\ta = (temp1 + temp2) >>> 0;\n\t}\n\tstate[0] = (state[0] + a) >>> 0;\n\tstate[1] = (state[1] + b) >>> 0;\n\tstate[2] = (state[2] + c) >>> 0;\n\tstate[3] = (state[3] + d) >>> 0;\n\tstate[4] = (state[4] + e) >>> 0;\n\tstate[5] = (state[5] + f) >>> 0;\n\tstate[6] = (state[6] + g) >>> 0;\n\tstate[7] = (state[7] + h) >>> 0;\n}\n\n/** Lowercase hex SHA-256 of a UTF-8 string or raw bytes. Synchronous and dependency-free. */\nexport function sha256Hex(input: string | Uint8Array): string {\n\tconst bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n\tconst view = padMessage(bytes);\n\tconst state = new Uint32Array(INITIAL_STATE);\n\tconst schedule = new Uint32Array(64);\n\tfor (let offset = 0; offset < view.byteLength; offset += 64) compressBlock(state, schedule, view, offset);\n\tlet hex = \"\";\n\tfor (const word of state) hex += word.toString(16).padStart(8, \"0\");\n\treturn hex;\n}\n\n/** SHA-256 of the canonical JSON encoding of `value`. */\nexport function canonicalDigest(value: unknown): string {\n\treturn sha256Hex(canonicalJson(value));\n}\n\n/**\n * Domain-separated digest over an ordered part list. The parts are committed\n * through canonical JSON, so boundaries between parts are unambiguous and a\n * different domain string always yields a different digest.\n */\nexport function domainDigest(domain: string, parts: readonly string[]): string {\n\tif (domain.length === 0) throw new TypeError(\"domainDigest: domain must be non-empty\");\n\treturn sha256Hex(canonicalJson({ domain, parts }));\n}\n"]}