@nylorun/harness 0.25.1-beta → 0.27.0-beta

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 (42) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/HOST_CONTRACT.md +21 -18
  3. package/README.md +12 -13
  4. package/dist/api/executors.d.ts +18 -4
  5. package/dist/api/harness.d.ts +1 -1
  6. package/dist/api/harness.js +4 -4
  7. package/dist/api/host.d.ts +4 -0
  8. package/dist/api/host.js +62 -24
  9. package/dist/api/index.d.ts +1 -1
  10. package/dist/api/run.js +9 -0
  11. package/dist/definition/agent-definition.d.ts +2 -2
  12. package/dist/definition/agent-definition.js +2 -2
  13. package/dist/definition/registry.d.ts +3 -3
  14. package/dist/definition/registry.js +12 -15
  15. package/dist/loop/compaction/index.d.ts +4 -2
  16. package/dist/loop/compaction/index.js +78 -8
  17. package/dist/loop/dispatch.js +1 -1
  18. package/dist/loop/model/project.d.ts +6 -0
  19. package/dist/loop/model/project.js +59 -18
  20. package/dist/loop/run.js +2 -2
  21. package/dist/loop/state.js +0 -1
  22. package/dist/loop/step/canonicalize.d.ts +1 -3
  23. package/dist/loop/step/canonicalize.js +0 -15
  24. package/dist/loop/step/model-configuration.d.ts +4 -13
  25. package/dist/loop/step/model-configuration.js +12 -70
  26. package/dist/loop/step/resolve.js +0 -1
  27. package/dist/loop/step/run.js +33 -12
  28. package/dist/loop/step/runtime.d.ts +2 -2
  29. package/dist/loop/step/seal.js +0 -17
  30. package/dist/loop/step/slot-assembly.d.ts +5 -5
  31. package/dist/loop/step/slot-assembly.js +5 -5
  32. package/dist/loop/step/step-context.d.ts +5 -19
  33. package/dist/loop/step/step-context.js +9 -195
  34. package/dist/loop/transcript.js +7 -1
  35. package/dist/run/durable.d.ts +2 -6
  36. package/dist/run/durable.js +30 -40
  37. package/dist/types/execution.d.ts +0 -1
  38. package/package.json +6 -6
  39. package/dist/loop/step/compose.d.ts +0 -5
  40. package/dist/loop/step/compose.js +0 -109
  41. package/dist/loop/step/context-draft.d.ts +0 -8
  42. package/dist/loop/step/context-draft.js +0 -48
@@ -1,25 +1,17 @@
1
1
  import { bindTool } from "@nylorun/core/define";
2
- import { HarnessError, isHarnessError } from "@nylorun/core/define";
3
- import { normalizeDirective, sameDirective } from "../model/normalize.js";
2
+ import { HarnessError } from "@nylorun/core/define";
4
3
  import { copyJson } from "@nylorun/core/define";
5
- import { checkedReason, slotOwner, SlotDraft } from "./slot-assembly.js";
6
- /** Per-step, middleware-owned model configuration draft. It never persists past the call. */
4
+ import { SlotDraft } from "./slot-assembly.js";
5
+ /** Per-step model configuration draft, set from the definition's parts. It never persists past the call. */
7
6
  export class ModelConfigurationDraft {
8
7
  #instructions = new SlotDraft();
9
8
  #tools = new SlotDraft();
10
- #model;
11
- #excludedOwners = new Set();
12
- #excludedTools = new Set();
13
- constructor(directive) {
14
- if (directive !== undefined)
15
- this.#model = Object.freeze({ directive: checkedDirective(directive) });
16
- }
17
- setInstructions(middlewareId, middlewareOrder, slot, items, options) {
9
+ setInstructions(partId, partOrder, slot, items, options) {
18
10
  if (!Array.isArray(items) || items.some((item) => typeof item !== "string"))
19
11
  throw new HarnessError("configuration.invalid-instructions", "Model configuration instructions must be strings");
20
12
  this.#instructions.set({
21
- middlewareId,
22
- middlewareOrder,
13
+ partId,
14
+ partOrder,
23
15
  slot,
24
16
  value: Object.freeze([...items]),
25
17
  order: options?.order,
@@ -30,14 +22,14 @@ export class ModelConfigurationDraft {
30
22
  label: "Model configuration",
31
23
  });
32
24
  }
33
- setTools(middlewareId, middlewareOrder, slot, tools, options) {
25
+ setTools(partId, partOrder, slot, tools, options) {
34
26
  if (!Array.isArray(tools))
35
27
  throw new HarnessError("configuration.invalid-tools", "Model configuration tools must be an array");
36
28
  this.#tools.set({
37
- middlewareId,
38
- middlewareOrder,
29
+ partId,
30
+ partOrder,
39
31
  slot,
40
- value: Object.freeze(tools.map((tool) => bindTool(tool, { middlewareId, slot }))),
32
+ value: Object.freeze(tools.map((tool) => bindTool(tool, { partId, slot }))),
41
33
  order: options?.order,
42
34
  reason: options?.reason,
43
35
  invalidSlot: "configuration.invalid-slot",
@@ -46,43 +38,6 @@ export class ModelConfigurationDraft {
46
38
  label: "Model configuration",
47
39
  });
48
40
  }
49
- select(middlewareId, middlewareOrder, directive, options) {
50
- const normalized = checkedDirective(directive);
51
- if (this.#model && !sameDirective(this.#model.directive, normalized))
52
- throw new HarnessError("configuration.model-selection-conflict", "A different model directive is already selected; use model.replace() to change it");
53
- this.#model = Object.freeze({
54
- directive: normalized,
55
- owner: slotOwner(middlewareId, middlewareOrder, "model"),
56
- ...(options?.reason === undefined
57
- ? {}
58
- : {
59
- reason: checkedReason(options.reason, "configuration.invalid-reason", "Model configuration"),
60
- }),
61
- });
62
- }
63
- replace(middlewareId, middlewareOrder, directive, options) {
64
- this.#model = Object.freeze({
65
- directive: checkedDirective(directive),
66
- owner: slotOwner(middlewareId, middlewareOrder, "model"),
67
- ...(options?.reason === undefined
68
- ? {}
69
- : {
70
- reason: checkedReason(options.reason, "configuration.invalid-reason", "Model configuration"),
71
- }),
72
- });
73
- }
74
- /** Hide tools from this model call: every tool a capability contributed, or tools by name. */
75
- exclude(input) {
76
- for (const id of input.capabilities ?? [])
77
- this.#excludedOwners.add(id);
78
- for (const name of input.tools ?? [])
79
- this.#excludedTools.add(name);
80
- }
81
- clear(options) {
82
- if (options?.reason !== undefined)
83
- checkedReason(options.reason, "configuration.invalid-reason", "Model configuration");
84
- this.#model = undefined;
85
- }
86
41
  snapshot() {
87
42
  const instructionSlots = this.#instructions.values();
88
43
  const toolSlots = this.#tools.values();
@@ -90,11 +45,7 @@ export class ModelConfigurationDraft {
90
45
  text,
91
46
  contributor: contributor(slot.owner, slot.reason),
92
47
  })));
93
- const sourcedTools = toolSlots
94
- .filter((slot) => !this.#excludedOwners.has(slot.owner.middlewareId))
95
- .flatMap((slot) => slot.value
96
- .filter((tool) => !this.#excludedTools.has(tool.name))
97
- .map((tool) => Object.freeze({ tool, contributor: contributor(slot.owner, slot.reason) })));
48
+ const sourcedTools = toolSlots.flatMap((slot) => slot.value.map((tool) => Object.freeze({ tool, contributor: contributor(slot.owner, slot.reason) })));
98
49
  const seen = new Set();
99
50
  const duplicate = new Set();
100
51
  for (const item of sourcedTools) {
@@ -105,30 +56,21 @@ export class ModelConfigurationDraft {
105
56
  if (duplicate.size)
106
57
  throw new HarnessError("configuration.duplicate-tool-name", `Duplicate Tool '${[...duplicate].sort().join("', '")}'`);
107
58
  const toolContracts = sourcedTools.map(({ tool, contributor: source }) => toolContract(tool, source));
108
- const model = this.#model?.directive;
109
59
  return Object.freeze({
110
60
  version: 1,
111
- ...(model === undefined ? {} : { model }),
112
61
  instructions: Object.freeze(instructions),
113
62
  tools: Object.freeze(sourcedTools.map((item) => item.tool)),
114
63
  toolContracts: Object.freeze(toolContracts),
115
64
  contributors: Object.freeze([
116
65
  ...instructionSlots.map((slot) => contributor(slot.owner, slot.reason)),
117
66
  ...toolSlots.map((slot) => contributor(slot.owner, slot.reason)),
118
- ...(this.#model?.owner ? [contributor(this.#model.owner, this.#model.reason)] : []),
119
67
  ]),
120
68
  });
121
69
  }
122
70
  }
123
- function checkedDirective(value) {
124
- const normalized = normalizeDirective(value);
125
- if (isHarnessError(normalized))
126
- throw normalized;
127
- return normalized;
128
- }
129
71
  function contributor(owner, reason) {
130
72
  return Object.freeze({
131
- middlewareId: owner.middlewareId,
73
+ partId: owner.partId,
132
74
  slot: owner.slot,
133
75
  order: owner.order,
134
76
  ...(reason === undefined ? {} : { reason }),
@@ -6,7 +6,6 @@ export function resolveModelRequest(input) {
6
6
  executionId: ctx.input.executionId,
7
7
  turnId: ctx.input.turnId,
8
8
  stepId: ctx.input.stepId,
9
- ...(ctx.selectedDirective === undefined ? {} : { model: ctx.selectedDirective }),
10
9
  configuration,
11
10
  instructions: Object.freeze([...ctx.instructions]),
12
11
  context: ctx.contextSnapshot(),
@@ -2,8 +2,6 @@ import { HostSuspension } from "../host-suspension.js";
2
2
  import { normalizeCandidate } from "../model/normalize.js";
3
3
  import { HarnessError, isHarnessError, isModelFailureOutcome } from "@nylorun/core/define";
4
4
  import { copyJson } from "@nylorun/core/define";
5
- import { runMiddleware } from "./compose.js";
6
- import { ContextDraft } from "./context-draft.js";
7
5
  import { StepContext } from "./step-context.js";
8
6
  import { projectModelCall } from "../model/project.js";
9
7
  import { resolveModelRequest } from "./resolve.js";
@@ -25,8 +23,7 @@ export async function runStep(input) {
25
23
  transcript: Object.freeze([...input.state.transcript]),
26
24
  });
27
25
  const configuration = new ModelConfigurationDraft();
28
- const runtimeContext = new ContextDraft();
29
- const context = new StepContext(stepInput, input.observe, configuration, runtimeContext);
26
+ const context = new StepContext(stepInput, configuration);
30
27
  input.observe(() => ({
31
28
  type: "step.started",
32
29
  turnId: input.turnId,
@@ -35,25 +32,26 @@ export async function runStep(input) {
35
32
  stepNumber: input.stepNumber,
36
33
  attributes: snapshotStepStart(stepInput),
37
34
  }));
38
- await runMiddleware(input.agent.middleware, context, async () => {
35
+ /** Seal the step's configuration and call the model; a failure ends the step as a tripwire. */
36
+ const invokeModel = async () => {
39
37
  input.signal.throwIfAborted();
40
38
  if (context.currentTripwire)
41
- return context.tripwire(context.currentTripwire);
39
+ return;
42
40
  try {
43
41
  const selected = configuration.snapshot();
44
42
  for (const tool of selected.tools)
45
43
  input.agent.registry.reference(tool);
46
44
  context.sealConfiguration(selected);
47
- context.sealContext(runtimeContext.snapshot());
48
45
  }
49
46
  catch (error) {
50
47
  if (error instanceof HostSuspension)
51
48
  throw error;
52
49
  const message = error instanceof Error ? error.message : String(error);
53
- return context.tripwire({
50
+ context.tripwire({
54
51
  code: isHarnessError(error) ? error.code : "configuration.invalid",
55
52
  message,
56
53
  });
54
+ return;
57
55
  }
58
56
  const request = resolveModelRequest({
59
57
  context,
@@ -110,22 +108,23 @@ export async function runStep(input) {
110
108
  ...(outcome.retryAfterMs === undefined ? {} : { retryAfterMs: outcome.retryAfterMs }),
111
109
  },
112
110
  });
113
- const minted = context.mintFromModel(normalizeCandidate(outcome));
111
+ context.mintFromModel(normalizeCandidate(outcome));
114
112
  if (!context.currentCandidate)
115
113
  throw new HarnessError("model.candidate-missing", "Model candidate missing after mint");
116
- return minted;
117
114
  }
118
115
  catch (error) {
119
116
  if (error instanceof HostSuspension)
120
117
  throw error;
121
118
  if (input.signal.aborted)
122
119
  throw input.signal.reason;
123
- return context.tripwire({
120
+ context.tripwire({
124
121
  code: isHarnessError(error) ? error.code : "model.failed",
125
122
  message: error instanceof Error ? error.message : String(error),
126
123
  });
127
124
  }
128
- }, input.observe);
125
+ };
126
+ configureParts(input.agent.parts, configuration, context);
127
+ await invokeModel();
129
128
  const output = sealStep(context, input.output);
130
129
  const candidate = output.kind === "tools" ? output.plan.candidate : context.currentCandidate;
131
130
  return Object.freeze({
@@ -146,3 +145,25 @@ function snapshotStepStart(input) {
146
145
  function snapshotConfiguration(configuration) {
147
146
  return copyJson(configuration);
148
147
  }
148
+ /**
149
+ * Offer each part's tools and instructions to the model, in part order. A part whose tools or
150
+ * text the configuration refuses ends the step with that error.
151
+ */
152
+ function configureParts(parts, configuration, context) {
153
+ parts.forEach((part, order) => {
154
+ const tools = [...(part.tools ?? []), ...(part.sessionTools ?? [])];
155
+ const instructions = [...(part.instructions ?? []), ...(part.sessionInstructions ?? [])];
156
+ try {
157
+ if (tools.length)
158
+ configuration.setTools(part.id, order, part.id, tools);
159
+ if (instructions.length)
160
+ configuration.setInstructions(part.id, order, part.id, instructions);
161
+ }
162
+ catch (cause) {
163
+ context.tripwire({
164
+ code: isHarnessError(cause) ? cause.code : "tool.invalid-schema",
165
+ message: cause instanceof Error ? cause.message : String(cause),
166
+ });
167
+ }
168
+ });
169
+ }
@@ -2,11 +2,11 @@ import type { ToolRegistry } from "../../definition/registry.js";
2
2
  import type { ModelAdapter } from "@nylorun/core/define";
3
3
  import type { InputEvent, TranscriptEntry } from "@nylorun/core/define";
4
4
  import type { ToolResult } from "@nylorun/core/define";
5
- import type { BoundMiddleware } from "@nylorun/core/define";
5
+ import type { DefinitionPart } from "@nylorun/core/define";
6
6
  import type { JsonValue } from "@nylorun/core/define";
7
7
  /** Compiled definition pieces plus the per-run model adapter for one step. */
8
8
  export interface StepRuntime {
9
- readonly middleware: readonly BoundMiddleware[];
9
+ readonly parts: readonly DefinitionPart[];
10
10
  readonly invoke: ModelAdapter;
11
11
  readonly registry: ToolRegistry;
12
12
  /** Mutable session memory bag shared with tools. */
@@ -93,22 +93,6 @@ function sealCall(context, catalog, candidate) {
93
93
  canonical,
94
94
  immediate: failed(candidate.id, candidate.name, "tool.invalid-arguments", args.message, args.details),
95
95
  };
96
- const denial = context.denialFor(candidate.id);
97
- if (denial)
98
- return {
99
- order,
100
- canonical,
101
- immediate: Object.freeze({
102
- kind: "denied",
103
- callId: candidate.id,
104
- toolName: candidate.name,
105
- reason: denial,
106
- }),
107
- };
108
- const requested = context.interactionFor(candidate.id);
109
- const interaction = requested
110
- ? Object.freeze({ ...requested, id: requested.id ?? createId("interaction") })
111
- : undefined;
112
96
  return {
113
97
  order,
114
98
  canonical,
@@ -124,7 +108,6 @@ function sealCall(context, catalog, candidate) {
124
108
  owner: tool.owner,
125
109
  execute: tool.execute,
126
110
  ...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
127
- ...(interaction ? { interaction } : {}),
128
111
  }),
129
112
  };
130
113
  }
@@ -1,7 +1,7 @@
1
1
  import { type HarnessErrorCode } from "@nylorun/core/define";
2
2
  export interface SlotOwner {
3
- readonly middlewareId: string;
4
- readonly middlewareOrder: number;
3
+ readonly partId: string;
4
+ readonly partOrder: number;
5
5
  readonly slot: string;
6
6
  readonly order: number;
7
7
  }
@@ -18,8 +18,8 @@ export interface SlotDeclaration<Value> {
18
18
  export declare class SlotDraft<Value> {
19
19
  #private;
20
20
  set(input: {
21
- readonly middlewareId: string;
22
- readonly middlewareOrder: number;
21
+ readonly partId: string;
22
+ readonly partOrder: number;
23
23
  readonly slot: string;
24
24
  readonly value: Value;
25
25
  readonly order?: number;
@@ -31,7 +31,7 @@ export declare class SlotDraft<Value> {
31
31
  }): void;
32
32
  values(): readonly SlotDeclaration<Value>[];
33
33
  }
34
- export declare function slotOwner(middlewareId: string, middlewareOrder: number, slot: string): SlotOwner;
34
+ export declare function slotOwner(partId: string, partOrder: number, slot: string): SlotOwner;
35
35
  export declare function slotKey(value: SlotOwner): string;
36
36
  export declare function checkedSlot(value: string, code: HarnessErrorCode, label: string): void;
37
37
  export declare function checkedReason(value: string, code: HarnessErrorCode, label: string): string;
@@ -8,7 +8,7 @@ export class SlotDraft {
8
8
  #slots = new Map();
9
9
  set(input) {
10
10
  checkedSlot(input.slot, input.invalidSlot, input.label);
11
- const base = slotOwner(input.middlewareId, input.middlewareOrder, input.slot);
11
+ const base = slotOwner(input.partId, input.partOrder, input.slot);
12
12
  const key = slotKey(base);
13
13
  const prior = this.#slots.get(key);
14
14
  const owner = withOrder(base, input.order, prior?.owner.order, input.invalidOrder, input.label);
@@ -24,11 +24,11 @@ export class SlotDraft {
24
24
  return Object.freeze([...this.#slots.values()].sort((left, right) => compareSlotOwners(left.owner, right.owner)));
25
25
  }
26
26
  }
27
- export function slotOwner(middlewareId, middlewareOrder, slot) {
28
- return Object.freeze({ middlewareId, middlewareOrder, slot, order: 0 });
27
+ export function slotOwner(partId, partOrder, slot) {
28
+ return Object.freeze({ partId, partOrder, slot, order: 0 });
29
29
  }
30
30
  export function slotKey(value) {
31
- return `${value.middlewareId}\u0000${value.slot}`;
31
+ return `${value.partId}\u0000${value.slot}`;
32
32
  }
33
33
  export function checkedSlot(value, code, label) {
34
34
  if (typeof value !== "string" || value.length === 0)
@@ -47,6 +47,6 @@ export function withOrder(owner, requested, previousOrder, code, label) {
47
47
  }
48
48
  export function compareSlotOwners(left, right) {
49
49
  return (left.order - right.order ||
50
- left.middlewareOrder - right.middlewareOrder ||
50
+ left.partOrder - right.partOrder ||
51
51
  left.slot.localeCompare(right.slot));
52
52
  }
@@ -1,38 +1,24 @@
1
1
  import type { BoundToolDefinition } from "@nylorun/core/define";
2
2
  import type { StepInput } from "./runtime.js";
3
3
  import type { InternalModelConfigurationSnapshot } from "./describe.js";
4
- import type { ContextSnapshot, ModelCandidate, ModelDirective } from "@nylorun/core/define";
5
- import type { StepRequest, StepResponse } from "@nylorun/core/define";
4
+ import type { ContextSnapshot, ModelCandidate } from "@nylorun/core/define";
6
5
  import type { Tripwire } from "@nylorun/core/define";
7
- import type { ObserveEmit } from "../observe.js";
8
- import type { Interaction } from "@nylorun/core/define";
9
6
  import { type CanonicalCall } from "./canonicalize.js";
10
- import { ContextDraft } from "./context-draft.js";
11
7
  import { ModelConfigurationDraft } from "./model-configuration.js";
12
- export declare function isBrandedResponse(value: unknown): value is StepResponse;
13
- /** Mutable Step state. Middleware receives leased request views and one branded response. */
8
+ /** Mutable Step state: the configuration the definition's parts set, and the model's answer. */
14
9
  export declare class StepContext {
15
10
  #private;
16
11
  readonly input: Readonly<StepInput>;
17
- constructor(input: Readonly<StepInput>, observe: ObserveEmit, configuration: ModelConfigurationDraft, context: ContextDraft);
12
+ constructor(input: Readonly<StepInput>, configuration: ModelConfigurationDraft);
18
13
  get currentTripwire(): Tripwire | undefined;
19
14
  get currentCandidate(): Readonly<ModelCandidate> | undefined;
20
- get selectedDirective(): ModelDirective | undefined;
21
15
  get instructions(): readonly string[];
22
16
  contextSnapshot(): ContextSnapshot;
23
17
  get offeredTools(): readonly BoundToolDefinition[];
24
18
  get catalogByName(): ReadonlyMap<string, BoundToolDefinition>;
25
19
  configurationSnapshot(): InternalModelConfigurationSnapshot;
26
20
  sealConfiguration(snapshot: InternalModelConfigurationSnapshot): void;
27
- sealContext(snapshot: ContextSnapshot): void;
28
- denialFor(callId: string): string | undefined;
29
- interactionFor(callId: string): Interaction | undefined;
30
21
  canonicalCalls(): readonly CanonicalCall[];
31
- mintFromModel(candidate: Readonly<ModelCandidate>): StepResponse;
32
- tripwire(error: Tripwire): StepResponse;
33
- seal(): void;
34
- requestFacade(middlewareId: string, middlewareOrder: number): {
35
- readonly value: StepRequest;
36
- revokeMutators(): void;
37
- };
22
+ mintFromModel(candidate: Readonly<ModelCandidate>): void;
23
+ tripwire(error: Tripwire): void;
38
24
  }
@@ -1,34 +1,21 @@
1
- import { HarnessError, isHarnessError } from "@nylorun/core/define";
2
- import { freezeGraph } from "@nylorun/core/define";
3
- import { callsFromCanonical, candidateFromCanonical, canonicalizeOutput, identityKey, } from "./canonicalize.js";
4
- import { normalizeCandidate } from "../model/normalize.js";
5
- import { ContextDraft } from "./context-draft.js";
1
+ import { candidateFromCanonical, canonicalizeOutput } from "./canonicalize.js";
6
2
  import { ModelConfigurationDraft } from "./model-configuration.js";
7
- const branded = new WeakSet();
8
- export function isBrandedResponse(value) {
9
- return typeof value === "object" && value !== null && branded.has(value);
10
- }
11
- /** Mutable Step state. Middleware receives leased request views and one branded response. */
3
+ /** The model-visible context of a call. Nothing adds items since step middleware was removed. */
4
+ const EMPTY_CONTEXT = Object.freeze({
5
+ items: Object.freeze([]),
6
+ contributors: Object.freeze([]),
7
+ });
8
+ /** Mutable Step state: the configuration the definition's parts set, and the model's answer. */
12
9
  export class StepContext {
13
10
  input;
14
- #observe;
15
- #context;
16
11
  #configuration;
17
- #denials = new Map();
18
- #interactions = new Map();
19
- #identities = new Map();
20
12
  #canonical = Object.freeze([]);
21
13
  #candidate;
22
14
  #tripwire;
23
- #response;
24
- #sealed = false;
25
15
  #configurationSnapshot;
26
- #contextSnapshot;
27
- constructor(input, observe, configuration, context) {
16
+ constructor(input, configuration) {
28
17
  this.input = input;
29
- this.#observe = observe;
30
18
  this.#configuration = configuration;
31
- this.#context = context;
32
19
  }
33
20
  get currentTripwire() {
34
21
  return this.#tripwire;
@@ -36,14 +23,11 @@ export class StepContext {
36
23
  get currentCandidate() {
37
24
  return this.#candidate;
38
25
  }
39
- get selectedDirective() {
40
- return this.configurationSnapshot().model;
41
- }
42
26
  get instructions() {
43
27
  return Object.freeze(this.configurationSnapshot().instructions.map((item) => item.text));
44
28
  }
45
29
  contextSnapshot() {
46
- return this.#contextSnapshot ?? this.#context.snapshot();
30
+ return EMPTY_CONTEXT;
47
31
  }
48
32
  get offeredTools() {
49
33
  return this.configurationSnapshot().tools;
@@ -57,15 +41,6 @@ export class StepContext {
57
41
  sealConfiguration(snapshot) {
58
42
  this.#configurationSnapshot = snapshot;
59
43
  }
60
- sealContext(snapshot) {
61
- this.#contextSnapshot = snapshot;
62
- }
63
- denialFor(callId) {
64
- return this.#denials.get(callId);
65
- }
66
- interactionFor(callId) {
67
- return this.#interactions.get(callId);
68
- }
69
44
  canonicalCalls() {
70
45
  return this.#canonical;
71
46
  }
@@ -73,169 +48,8 @@ export class StepContext {
73
48
  const { output, calls } = canonicalizeOutput(candidate.output);
74
49
  this.#canonical = calls;
75
50
  this.#candidate = candidateFromCanonical(candidate, output);
76
- this.#identities.clear();
77
- for (const call of calls)
78
- this.#identities.set(call.id, identityKey(call.name, call.args));
79
- return this.#ensureResponse();
80
51
  }
81
52
  tripwire(error) {
82
53
  this.#tripwire ??= Object.freeze({ ...error });
83
- return this.#ensureResponse();
84
54
  }
85
- seal() {
86
- this.#sealed = true;
87
- }
88
- requestFacade(middlewareId, middlewareOrder) {
89
- let mutatorsActive = true;
90
- const mutate = (action) => {
91
- if (!mutatorsActive || this.#sealed) {
92
- this.#observe({
93
- type: "middleware.lease-violation",
94
- turnId: this.input.turnId,
95
- stepId: this.input.stepId,
96
- middlewareId,
97
- reason: this.#sealed ? "step-sealed" : "mutators-revoked",
98
- });
99
- throw new HarnessError("middleware.request-mutators-revoked", "Middleware request mutators are no longer active", { details: { middlewareId } });
100
- }
101
- action();
102
- };
103
- const mutateConfiguration = (kind, action) => mutate(() => {
104
- try {
105
- action();
106
- }
107
- catch (cause) {
108
- const message = cause instanceof Error ? cause.message : String(cause);
109
- const code = isHarnessError(cause)
110
- ? cause.code
111
- : kind === "tools"
112
- ? "tool.invalid-schema"
113
- : kind === "model"
114
- ? "model.invalid-directive"
115
- : "configuration.invalid-instructions";
116
- this.#tripwire ??= Object.freeze({ code, message });
117
- }
118
- });
119
- const mutateContext = (action) => mutate(() => {
120
- try {
121
- action();
122
- }
123
- catch (cause) {
124
- const message = cause instanceof Error ? cause.message : String(cause);
125
- this.#tripwire ??= Object.freeze({
126
- code: isHarnessError(cause) ? cause.code : "context.invalid-item",
127
- message,
128
- });
129
- }
130
- });
131
- const request = {
132
- executionId: this.input.executionId,
133
- turnId: this.input.turnId,
134
- stepId: this.input.stepId,
135
- info: this.input.info,
136
- turnNumber: this.input.turnNumber,
137
- stepNumber: this.input.stepNumber,
138
- arrivals: this.input.arrivals,
139
- toolResults: this.input.toolResults,
140
- transcript: this.input.transcript,
141
- context: Object.freeze({
142
- set: (slot, items, options) => mutateContext(() => this.#context.set(middlewareId, middlewareOrder, slot, items, options)),
143
- }),
144
- configuration: Object.freeze({
145
- instructions: Object.freeze({
146
- set: (slot, items, options) => mutateConfiguration("instructions", () => this.#configuration.setInstructions(middlewareId, middlewareOrder, slot, items, options)),
147
- }),
148
- tools: Object.freeze({
149
- set: (slot, tools, options) => mutateConfiguration("tools", () => this.#configuration.setTools(middlewareId, middlewareOrder, slot, tools, options)),
150
- }),
151
- model: Object.freeze({
152
- select: (directive, options) => mutateConfiguration("model", () => this.#configuration.select(middlewareId, middlewareOrder, directive, options)),
153
- replace: (directive, options) => mutateConfiguration("model", () => this.#configuration.replace(middlewareId, middlewareOrder, directive, options)),
154
- clear: (options) => mutateConfiguration("model", () => this.#configuration.clear(options)),
155
- }),
156
- }),
157
- tripwire: (error) => {
158
- let minted;
159
- mutate(() => {
160
- minted = this.tripwire(error);
161
- });
162
- return minted;
163
- },
164
- };
165
- const value = Object.freeze(request);
166
- return Object.freeze({
167
- value,
168
- revokeMutators: () => {
169
- mutatorsActive = false;
170
- },
171
- });
172
- }
173
- #ensureResponse() {
174
- if (this.#response)
175
- return this.#response;
176
- const value = Object.freeze({
177
- candidate: () => this.currentCandidate,
178
- toolCalls: () => callsFromCanonical(this.#canonical),
179
- replace: (candidate) => this.#replace(candidate),
180
- deny: (callId, reason) => {
181
- if (!this.#denials.has(callId))
182
- this.#denials.set(callId, reason);
183
- },
184
- requireInteraction: (callId, interaction) => {
185
- if (!this.#interactions.has(callId))
186
- this.#interactions.set(callId, freezeGraph({ ...interaction }));
187
- },
188
- tripwire: (error) => {
189
- this.#tripwire ??= Object.freeze({ ...error });
190
- return value;
191
- },
192
- });
193
- branded.add(value);
194
- this.#response = value;
195
- return value;
196
- }
197
- #replace(candidate) {
198
- let normalized;
199
- try {
200
- normalized = normalizeCandidate(candidate);
201
- }
202
- catch (error) {
203
- this.#tripwire ??= Object.freeze({
204
- code: isHarnessError(error) ? error.code : "response.invalid-replacement",
205
- message: error instanceof Error ? error.message : String(error),
206
- });
207
- return;
208
- }
209
- const { output, calls: next } = canonicalizeOutput(normalized.output);
210
- for (const call of next) {
211
- const original = this.#identities.get(call.id);
212
- if (original === undefined) {
213
- this.#tripwire ??= Object.freeze({
214
- code: "response.invalid-replacement",
215
- message: `replace() cannot add Tool call '${call.id}'`,
216
- });
217
- return;
218
- }
219
- if (original !== identityKey(call.name, call.args)) {
220
- this.#tripwire ??= Object.freeze({
221
- code: "response.invalid-replacement",
222
- message: `replace() cannot change identity of Tool call '${call.id}'`,
223
- });
224
- return;
225
- }
226
- }
227
- const current = this.#candidate;
228
- this.#canonical = next;
229
- this.#candidate = Object.freeze({
230
- output,
231
- ...pickSidecar("finishReason", candidate, normalized, current),
232
- ...pickSidecar("usage", candidate, normalized, current),
233
- ...pickSidecar("evidence", candidate, normalized, current),
234
- });
235
- }
236
- }
237
- function pickSidecar(key, replacement, normalized, current) {
238
- const source = Object.hasOwn(replacement, key) ? normalized : current;
239
- const value = source?.[key];
240
- return value === undefined ? {} : { [key]: value };
241
55
  }