@fabric-harness/sdk 6.8.0 → 6.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/agent.d.ts +5 -4
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +37 -18
  4. package/dist/agent.js.map +1 -1
  5. package/dist/dynamic-agent.d.ts +24 -19
  6. package/dist/dynamic-agent.d.ts.map +1 -1
  7. package/dist/dynamic-agent.js +402 -239
  8. package/dist/dynamic-agent.js.map +1 -1
  9. package/dist/error.d.ts +1 -1
  10. package/dist/error.d.ts.map +1 -1
  11. package/dist/error.js.map +1 -1
  12. package/dist/events.d.ts +5 -0
  13. package/dist/events.d.ts.map +1 -1
  14. package/dist/events.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/local-process.d.ts +8 -0
  20. package/dist/local-process.d.ts.map +1 -0
  21. package/dist/local-process.js +61 -0
  22. package/dist/local-process.js.map +1 -0
  23. package/dist/loop.d.ts +5 -0
  24. package/dist/loop.d.ts.map +1 -1
  25. package/dist/loop.js +18 -3
  26. package/dist/loop.js.map +1 -1
  27. package/dist/model-id.d.ts +3 -0
  28. package/dist/model-id.d.ts.map +1 -0
  29. package/dist/model-id.js +5 -0
  30. package/dist/model-id.js.map +1 -0
  31. package/dist/model-pricing.d.ts.map +1 -1
  32. package/dist/model-pricing.js +18 -1
  33. package/dist/model-pricing.js.map +1 -1
  34. package/dist/model.d.ts.map +1 -1
  35. package/dist/model.js +39 -14
  36. package/dist/model.js.map +1 -1
  37. package/dist/observability.d.ts +3 -2
  38. package/dist/observability.d.ts.map +1 -1
  39. package/dist/observability.js +42 -17
  40. package/dist/observability.js.map +1 -1
  41. package/dist/otel-observer.d.ts +2 -2
  42. package/dist/otel-observer.d.ts.map +1 -1
  43. package/dist/otel-observer.js +109 -26
  44. package/dist/otel-observer.js.map +1 -1
  45. package/dist/otel.d.ts +4 -4
  46. package/dist/otel.d.ts.map +1 -1
  47. package/dist/otel.js +28 -24
  48. package/dist/otel.js.map +1 -1
  49. package/dist/persistent-agent.d.ts +6 -6
  50. package/dist/persistent-agent.d.ts.map +1 -1
  51. package/dist/persistent-agent.js +79 -47
  52. package/dist/persistent-agent.js.map +1 -1
  53. package/dist/pi-loop-runtime.d.ts +6 -0
  54. package/dist/pi-loop-runtime.d.ts.map +1 -1
  55. package/dist/pi-loop-runtime.js +44 -22
  56. package/dist/pi-loop-runtime.js.map +1 -1
  57. package/dist/policy.d.ts +3 -1
  58. package/dist/policy.d.ts.map +1 -1
  59. package/dist/policy.js +13 -1
  60. package/dist/policy.js.map +1 -1
  61. package/dist/sandbox.d.ts +12 -12
  62. package/dist/sandbox.d.ts.map +1 -1
  63. package/dist/sandbox.js +408 -246
  64. package/dist/sandbox.js.map +1 -1
  65. package/dist/session-stream-recovery.d.ts +21 -0
  66. package/dist/session-stream-recovery.d.ts.map +1 -0
  67. package/dist/session-stream-recovery.js +115 -0
  68. package/dist/session-stream-recovery.js.map +1 -0
  69. package/dist/session.d.ts.map +1 -1
  70. package/dist/session.js +126 -39
  71. package/dist/session.js.map +1 -1
  72. package/dist/skills.d.ts +3 -1
  73. package/dist/skills.d.ts.map +1 -1
  74. package/dist/skills.js +7 -2
  75. package/dist/skills.js.map +1 -1
  76. package/dist/strict.d.ts +1 -1
  77. package/dist/strict.d.ts.map +1 -1
  78. package/dist/strict.js +1 -1
  79. package/dist/strict.js.map +1 -1
  80. package/dist/telemetry.d.ts +1 -1
  81. package/dist/telemetry.d.ts.map +1 -1
  82. package/dist/telemetry.js +30 -26
  83. package/dist/telemetry.js.map +1 -1
  84. package/dist/tools.d.ts +4 -0
  85. package/dist/tools.d.ts.map +1 -1
  86. package/dist/tools.js +6 -3
  87. package/dist/tools.js.map +1 -1
  88. package/dist/types.d.ts +14 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/types.js.map +1 -1
  91. package/package.json +7 -23
@@ -1,14 +1,15 @@
1
- import { dispatch, enqueueDispatch } from './dispatch.js';
2
- import { deliveredSignalToEntryData, normalizeDeliveredMessage } from './delivered-message.js';
3
- import { SessionHistory } from './history.js';
4
- import { connectMcpServer } from './mcp.js';
5
- import { EmptySandboxEnv } from './sandbox.js';
6
- import { defineTool } from './tools.js';
7
- import { currentSubmissionContext } from './submission-context.js';
1
+ import { dispatch, enqueueDispatch } from "./dispatch.js";
2
+ import { deliveredSignalToEntryData, normalizeDeliveredMessage } from "./delivered-message.js";
3
+ import { SessionHistory } from "./history.js";
4
+ import { connectMcpServer } from "./mcp.js";
5
+ import { EmptySandboxEnv } from "./sandbox.js";
6
+ import { defineTool } from "./tools.js";
7
+ import { currentSubmissionContext } from "./submission-context.js";
8
+ import { approvalInputDigest } from "./approval.js";
8
9
  let currentFrame;
9
- const dynamicToolResultSymbol = Symbol.for('fabric-harness.dynamic-tool-result');
10
+ const dynamicToolResultSymbol = Symbol.for("fabric-harness.dynamic-tool-result");
10
11
  export function unwrapDynamicToolResult(value) {
11
- if (typeof value === 'object' &&
12
+ if (typeof value === "object" &&
12
13
  value !== null &&
13
14
  value[dynamicToolResultSymbol] === true) {
14
15
  const result = value;
@@ -24,7 +25,7 @@ function requireFrame(hook) {
24
25
  return currentFrame;
25
26
  }
26
27
  function rejectSubagent(frame, hook) {
27
- if (frame.kind === 'subagent') {
28
+ if (frame.kind === "subagent") {
28
29
  throw new Error(`[fabric-harness] ${hook}() is not available while rendering a subagent.`);
29
30
  }
30
31
  }
@@ -33,45 +34,30 @@ export function isDynamicAgentRendering() {
33
34
  }
34
35
  export async function renderDynamicAgent(render, props, options = {}, staticConfig = {}) {
35
36
  const resolvedOptions = await resolveInitialData(options);
36
- const snapshot = await loadStateSnapshot(resolvedOptions.store, resolvedOptions.storeSessionId);
37
- const state = { snapshot, options: resolvedOptions, active: undefined, queue: Promise.resolve() };
38
- const frame = createFrame('agent', state);
39
- if (currentFrame)
40
- throw new Error('[fabric-harness] Re-entrant dynamic-agent render is not supported.');
41
- currentFrame = frame;
42
- let rendered;
43
- try {
44
- rendered = render(props);
45
- }
46
- finally {
47
- currentFrame = undefined;
48
- }
49
- // Hooks are deliberately synchronous. An async legacy initializer remains
50
- // supported, but hook calls made after its first await fail outside-render.
51
- const result = await rendered;
37
+ const { frame, result, state } = await renderDynamicFrame(render, props, resolvedOptions);
52
38
  const base = {
53
39
  ...staticConfig,
54
40
  ...(isPersistentConfig(result) ? result : {}),
55
41
  };
56
- const returnedInstruction = typeof result === 'string' ? result : undefined;
42
+ const returnedInstruction = typeof result === "string" ? result : undefined;
57
43
  const instructions = [base.instructions, returnedInstruction, ...frame.instructions]
58
- .filter((value) => typeof value === 'string' && value.trim().length > 0)
59
- .join('\n\n');
44
+ .filter((value) => typeof value === "string" && value.trim().length > 0)
45
+ .join("\n\n");
60
46
  await persistRenderStructure(frame, state);
61
47
  const connections = await connectDeclaredMcp(frame.mcpConnections, state);
62
48
  const mcpTools = connections.flatMap((connection) => connection.tools);
63
49
  const hookTools = frame.tools.map((tool) => wrapDynamicTool(tool, state));
64
50
  const roles = frame.subagents.map(resolveSubagent);
65
51
  const tools = [...(base.tools ?? []), ...hookTools, ...mcpTools];
66
- assertUniqueNames(tools.map((tool) => tool.name), 'tool');
52
+ assertUniqueNames(tools.map((tool) => tool.name), "tool");
67
53
  const skills = [...(base.skills ?? []), ...frame.skills];
68
- assertUniqueNames(skills.map((skill) => skill.name), 'skill');
54
+ assertUniqueNames(skills.map((skill) => skill.name), "skill");
69
55
  const subagents = [...(base.subagents ?? []), ...roles];
70
- assertUniqueNames(subagents.map((role) => role.name), 'subagent');
56
+ assertUniqueNames(subagents.map((role) => role.name), "subagent");
71
57
  const runtime = createDynamicRuntime(frame, state, connections, (input = {}) => renderDynamicAgent(render, props, {
72
- ...options,
58
+ ...resolvedOptions,
73
59
  ...(input.delivery !== undefined ? { delivery: input.delivery } : {}),
74
- }, staticConfig));
60
+ }, staticConfig), async () => (await renderDynamicFrame(render, props, resolvedOptions)).frame);
75
61
  return {
76
62
  ...base,
77
63
  ...(frame.model !== undefined ? { model: frame.model } : {}),
@@ -88,20 +74,46 @@ export async function renderDynamicAgent(render, props, options = {}, staticConf
88
74
  dynamic: runtime,
89
75
  };
90
76
  }
77
+ // Finish rendering only captures hook declarations. It must not connect MCP,
78
+ // persist resource-change narration, or acquire a newly declared sandbox.
79
+ async function renderDynamicFrame(render, props, resolvedOptions) {
80
+ const snapshot = await loadStateSnapshot(resolvedOptions.store, resolvedOptions.storeSessionId);
81
+ const state = {
82
+ snapshot,
83
+ options: resolvedOptions,
84
+ active: undefined,
85
+ queue: Promise.resolve(),
86
+ };
87
+ const frame = createFrame("agent", state);
88
+ if (currentFrame)
89
+ throw new Error("[fabric-harness] Re-entrant dynamic-agent render is not supported.");
90
+ currentFrame = frame;
91
+ let rendered;
92
+ try {
93
+ rendered = render(props);
94
+ }
95
+ finally {
96
+ currentFrame = undefined;
97
+ }
98
+ // Hooks are deliberately synchronous. An async legacy initializer remains
99
+ // supported, but hook calls made after its first await fail outside-render.
100
+ const result = await rendered;
101
+ return { frame, state, result };
102
+ }
91
103
  export function useInstruction(text) {
92
- const frame = requireFrame('useInstruction');
93
- if (typeof text !== 'string' || text.trim().length === 0) {
94
- throw new Error('[fabric-harness] useInstruction() requires a non-empty string.');
104
+ const frame = requireFrame("useInstruction");
105
+ if (typeof text !== "string" || text.trim().length === 0) {
106
+ throw new Error("[fabric-harness] useInstruction() requires a non-empty string.");
95
107
  }
96
108
  frame.instructions.push(text);
97
109
  }
98
110
  export function useModel(model, options = {}) {
99
- const frame = requireFrame('useModel');
100
- rejectSubagent(frame, 'useModel');
111
+ const frame = requireFrame("useModel");
112
+ rejectSubagent(frame, "useModel");
101
113
  if (frame.model !== undefined)
102
- throw new Error('[fabric-harness] useModel() may be called once per render.');
103
- if (typeof model === 'string' && model.trim().length === 0) {
104
- throw new Error('[fabric-harness] useModel() requires a non-empty model specifier.');
114
+ throw new Error("[fabric-harness] useModel() may be called once per render.");
115
+ if (typeof model === "string" && model.trim().length === 0) {
116
+ throw new Error("[fabric-harness] useModel() requires a non-empty model specifier.");
105
117
  }
106
118
  frame.model = model;
107
119
  if (options.thinkingLevel !== undefined)
@@ -110,23 +122,23 @@ export function useModel(model, options = {}) {
110
122
  frame.compaction = options.compaction;
111
123
  }
112
124
  export function useSandbox(sandbox, options = {}) {
113
- const frame = requireFrame('useSandbox');
114
- rejectSubagent(frame, 'useSandbox');
125
+ const frame = requireFrame("useSandbox");
126
+ rejectSubagent(frame, "useSandbox");
115
127
  if (frame.sandbox !== undefined)
116
- throw new Error('[fabric-harness] useSandbox() may be called once per render.');
128
+ throw new Error("[fabric-harness] useSandbox() may be called once per render.");
117
129
  if (!sandbox)
118
- throw new Error('[fabric-harness] useSandbox() requires a sandbox backend, factory, or environment.');
130
+ throw new Error("[fabric-harness] useSandbox() requires a sandbox backend, factory, or environment.");
119
131
  if (options.cwd !== undefined && options.cwd.trim().length === 0) {
120
- throw new Error('[fabric-harness] useSandbox() options.cwd must be non-empty.');
132
+ throw new Error("[fabric-harness] useSandbox() options.cwd must be non-empty.");
121
133
  }
122
134
  frame.sandbox = sandbox;
123
135
  if (options.cwd !== undefined)
124
136
  frame.cwd = options.cwd;
125
137
  }
126
138
  export function useSkill(skill) {
127
- const frame = requireFrame('useSkill');
128
- if (!skill || typeof skill !== 'object' || !skill.name?.trim()) {
129
- throw new Error('[fabric-harness] useSkill() requires a named skill.');
139
+ const frame = requireFrame("useSkill");
140
+ if (!skill || typeof skill !== "object" || !skill.name?.trim()) {
141
+ throw new Error("[fabric-harness] useSkill() requires a named skill.");
130
142
  }
131
143
  if (frame.skills.some((candidate) => candidate.name === skill.name)) {
132
144
  throw new Error(`[fabric-harness] Duplicate skill name in one render: ${skill.name}`);
@@ -134,7 +146,7 @@ export function useSkill(skill) {
134
146
  frame.skills.push(skill);
135
147
  }
136
148
  export function useTool(tool) {
137
- const frame = requireFrame('useTool');
149
+ const frame = requireFrame("useTool");
138
150
  const normalized = defineTool(tool);
139
151
  if (frame.tools.some((candidate) => candidate.name === normalized.name)) {
140
152
  throw new Error(`[fabric-harness] Duplicate tool name in one render: ${normalized.name}`);
@@ -142,10 +154,10 @@ export function useTool(tool) {
142
154
  frame.tools.push(normalized);
143
155
  }
144
156
  export function usePersistentState(name, defaultValue, options = {}) {
145
- const frame = requireFrame('usePersistentState');
146
- rejectSubagent(frame, 'usePersistentState');
157
+ const frame = requireFrame("usePersistentState");
158
+ rejectSubagent(frame, "usePersistentState");
147
159
  if (!name.trim())
148
- throw new Error('[fabric-harness] usePersistentState() requires a non-empty name.');
160
+ throw new Error("[fabric-harness] usePersistentState() requires a non-empty name.");
149
161
  if (frame.stateNames.has(name))
150
162
  throw new Error(`[fabric-harness] Duplicate persistent state name: ${name}`);
151
163
  frame.stateNames.add(name);
@@ -162,8 +174,8 @@ export function usePersistentState(name, defaultValue, options = {}) {
162
174
  }
163
175
  const prior = collector.overlay.has(name)
164
176
  ? collector.overlay.get(name)
165
- : frame.state.snapshot.get(name) ?? normalizeJson(defaultValue, `State "${name}" default`);
166
- const candidate = typeof next === 'function' ? next(prior) : next;
177
+ : (frame.state.snapshot.get(name) ?? normalizeJson(defaultValue, `State "${name}" default`));
178
+ const candidate = typeof next === "function" ? next(prior) : next;
167
179
  const parsed = options.schema ? options.schema.parse(candidate, `$state.${name}`) : candidate;
168
180
  const normalized = normalizeJson(parsed, `State "${name}"`);
169
181
  if (jsonEqual(prior, normalized))
@@ -174,27 +186,27 @@ export function usePersistentState(name, defaultValue, options = {}) {
174
186
  return [value, setter];
175
187
  }
176
188
  export function useDelivery() {
177
- const frame = requireFrame('useDelivery');
189
+ const frame = requireFrame("useDelivery");
178
190
  if (!frame.state.options.delivery) {
179
- throw new Error('[fabric-harness] useDelivery() requires a delivered message in the runtime render context.');
191
+ throw new Error("[fabric-harness] useDelivery() requires a delivered message in the runtime render context.");
180
192
  }
181
193
  return frame.state.options.delivery;
182
194
  }
183
195
  export function useInitialData() {
184
- const frame = requireFrame('useInitialData');
185
- return frame.kind === 'subagent' ? undefined : frame.state.options.initialData;
196
+ const frame = requireFrame("useInitialData");
197
+ return frame.kind === "subagent" ? undefined : frame.state.options.initialData;
186
198
  }
187
199
  export function useDispatchMessage() {
188
- const frame = requireFrame('useDispatchMessage');
189
- rejectSubagent(frame, 'useDispatchMessage');
200
+ const frame = requireFrame("useDispatchMessage");
201
+ rejectSubagent(frame, "useDispatchMessage");
190
202
  const { agentName, storeSessionId } = frame.state.options;
191
203
  const persistentIdentity = storeSessionId ? parsePersistentTarget(storeSessionId) : undefined;
192
204
  const instanceId = persistentIdentity?.instanceId;
193
205
  return async (message) => {
194
206
  if (isDynamicAgentRendering())
195
- throw new Error('[fabric-harness] Dispatch is not allowed during render.');
207
+ throw new Error("[fabric-harness] Dispatch is not allowed during render.");
196
208
  if (!agentName || !instanceId || !storeSessionId) {
197
- throw new Error('[fabric-harness] Self-dispatch requires an addressable persistent-agent runtime.');
209
+ throw new Error("[fabric-harness] Self-dispatch requires an addressable persistent-agent runtime.");
198
210
  }
199
211
  const submission = currentSubmissionContext();
200
212
  const request = {
@@ -202,10 +214,10 @@ export function useDispatchMessage() {
202
214
  id: instanceId,
203
215
  session: submission?.session ?? persistentIdentity.session,
204
216
  message: normalizeDeliveredMessage(message),
205
- ...(submission?.tenantId ?? frame.state.options.tenantId
217
+ ...((submission?.tenantId ?? frame.state.options.tenantId)
206
218
  ? { tenantId: submission?.tenantId ?? frame.state.options.tenantId }
207
219
  : {}),
208
- ...(submission?.actor ?? frame.state.options.actor
220
+ ...((submission?.actor ?? frame.state.options.actor)
209
221
  ? { actor: submission?.actor ?? frame.state.options.actor }
210
222
  : {}),
211
223
  };
@@ -219,10 +231,10 @@ export function useDispatchMessage() {
219
231
  };
220
232
  }
221
233
  export function useDataWriter(name, options = {}) {
222
- const frame = requireFrame('useDataWriter');
223
- rejectSubagent(frame, 'useDataWriter');
234
+ const frame = requireFrame("useDataWriter");
235
+ rejectSubagent(frame, "useDataWriter");
224
236
  if (!name.trim())
225
- throw new Error('[fabric-harness] useDataWriter() requires a non-empty name.');
237
+ throw new Error("[fabric-harness] useDataWriter() requires a non-empty name.");
226
238
  if (frame.dataNames.has(name))
227
239
  throw new Error(`[fabric-harness] Duplicate message data name: ${name}`);
228
240
  frame.dataNames.add(name);
@@ -234,47 +246,49 @@ export function useDataWriter(name, options = {}) {
234
246
  throw new Error(`[fabric-harness] Message data "${name}" requires an active response callback.`);
235
247
  const parsed = options.schema ? options.schema.parse(data, `$data.${name}`) : data;
236
248
  const value = normalizeJson(parsed, `Message data "${name}"`);
237
- enqueueCollectorEntry(collector, () => appendDynamicEntry(frame.state, 'message_data', { name, value }, collector.correlation));
249
+ enqueueCollectorEntry(collector, () => appendDynamicEntry(frame.state, "message_data", { name, value }, collector.correlation));
238
250
  };
239
251
  }
240
252
  export function useResponseStart(run) {
241
- const frame = requireFrame('useResponseStart');
242
- rejectSubagent(frame, 'useResponseStart');
243
- if (typeof run !== 'function')
244
- throw new Error('[fabric-harness] useResponseStart() requires a callback.');
253
+ const frame = requireFrame("useResponseStart");
254
+ rejectSubagent(frame, "useResponseStart");
255
+ if (typeof run !== "function")
256
+ throw new Error("[fabric-harness] useResponseStart() requires a callback.");
245
257
  frame.responseStarts.push(run);
246
258
  }
247
259
  export function useResponseFinish(run) {
248
- const frame = requireFrame('useResponseFinish');
249
- rejectSubagent(frame, 'useResponseFinish');
250
- if (typeof run !== 'function')
251
- throw new Error('[fabric-harness] useResponseFinish() requires a callback.');
260
+ const frame = requireFrame("useResponseFinish");
261
+ rejectSubagent(frame, "useResponseFinish");
262
+ if (typeof run !== "function")
263
+ throw new Error("[fabric-harness] useResponseFinish() requires a callback.");
252
264
  frame.responseFinishes.push(run);
253
265
  }
254
266
  export function useAgentStart(run) {
255
- const frame = requireFrame('useAgentStart');
256
- rejectSubagent(frame, 'useAgentStart');
257
- if (typeof run !== 'function')
258
- throw new Error('[fabric-harness] useAgentStart() requires a callback.');
267
+ const frame = requireFrame("useAgentStart");
268
+ rejectSubagent(frame, "useAgentStart");
269
+ if (typeof run !== "function")
270
+ throw new Error("[fabric-harness] useAgentStart() requires a callback.");
259
271
  frame.agentStarts.push(run);
260
272
  }
261
273
  export function useAgentFinish(run) {
262
- const frame = requireFrame('useAgentFinish');
263
- rejectSubagent(frame, 'useAgentFinish');
264
- if (typeof run !== 'function')
265
- throw new Error('[fabric-harness] useAgentFinish() requires a callback.');
274
+ const frame = requireFrame("useAgentFinish");
275
+ rejectSubagent(frame, "useAgentFinish");
276
+ if (typeof run !== "function")
277
+ throw new Error("[fabric-harness] useAgentFinish() requires a callback.");
266
278
  frame.agentFinishes.push(run);
267
279
  }
268
280
  export function defineMcpConnection(definition) {
269
281
  assertMcpConnection(definition);
270
282
  return Object.freeze({
271
283
  ...definition,
272
- ...(definition.tools ? { tools: Object.freeze([...definition.tools]) } : {}),
284
+ ...(definition.tools
285
+ ? { tools: Object.freeze([...definition.tools]) }
286
+ : {}),
273
287
  });
274
288
  }
275
289
  export function useMcpConnection(definition) {
276
- const frame = requireFrame('useMcpConnection');
277
- rejectSubagent(frame, 'useMcpConnection');
290
+ const frame = requireFrame("useMcpConnection");
291
+ rejectSubagent(frame, "useMcpConnection");
278
292
  assertMcpConnection(definition);
279
293
  if (frame.mcpConnections.some((candidate) => candidate.name === definition.name)) {
280
294
  throw new Error(`[fabric-harness] Duplicate MCP connection name: ${definition.name}`);
@@ -286,12 +300,12 @@ export function defineSubagent(definition) {
286
300
  return Object.freeze({ ...definition });
287
301
  }
288
302
  export const GeneralSubagent = defineSubagent({
289
- name: 'fabric-general',
290
- description: 'General-purpose delegate for independent research and file exploration.',
303
+ name: "fabric-general",
304
+ description: "General-purpose delegate for independent research and file exploration.",
291
305
  agent: () => undefined,
292
306
  });
293
307
  export function useSubagent(definition) {
294
- const frame = requireFrame('useSubagent');
308
+ const frame = requireFrame("useSubagent");
295
309
  assertSubagent(definition);
296
310
  if (frame.subagents.some((candidate) => candidate.name === definition.name)) {
297
311
  throw new Error(`[fabric-harness] Duplicate subagent name: ${definition.name}`);
@@ -364,25 +378,38 @@ async function enqueueEffect(state, run, correlation) {
364
378
  await state.queue;
365
379
  return result;
366
380
  }
367
- function createDynamicRuntime(frame, state, connections, refresh) {
368
- let metadata = {};
381
+ const lifecycleContexts = new WeakMap();
382
+ function createDynamicRuntime(frame, state, connections, refresh, renderFinishFrame) {
383
+ const execution = {
384
+ metadata: {},
385
+ signal: new AbortController().signal,
386
+ sandbox: new EmptySandboxEnv(),
387
+ };
369
388
  let closed = false;
370
- let lifecycleSignal = new AbortController().signal;
371
- let lifecycleSandbox = new EmptySandboxEnv();
372
389
  const emptyResponse = { toolCalls: [] };
373
390
  const baseContext = (response) => ({
374
391
  ...(state.options.delivery ? { delivery: state.options.delivery } : {}),
375
- metadata,
392
+ metadata: execution.metadata,
376
393
  response,
377
394
  });
378
- return {
395
+ const captureFinishFrame = async () => {
396
+ if (!frame.usedHooks)
397
+ return frame;
398
+ const fresh = await renderFinishFrame();
399
+ const dataDelta = setDelta([...frame.dataNames], [...fresh.dataNames]);
400
+ if (dataDelta) {
401
+ throw new Error(`[fabric-harness] The agent's finish render changed message-data identity: ${dataDelta}. Declare useDataWriter() names unconditionally on every render.`);
402
+ }
403
+ return fresh;
404
+ };
405
+ const runtime = {
379
406
  dataNames: [...frame.dataNames],
380
407
  resourceFingerprint: resourceFingerprint(frame),
381
408
  executionDescriptor() {
382
409
  const { agentName, storeSessionId, delivery, tenantId, actor } = state.options;
383
- const instanceId = storeSessionId?.split(':')[2];
410
+ const instanceId = storeSessionId?.split(":")[2];
384
411
  if (!agentName || !instanceId || !storeSessionId?.startsWith(`agent:${agentName}:`)) {
385
- throw new Error('[fabric-harness] Durable dynamic-agent execution requires an addressable agent name and instance session.');
412
+ throw new Error("[fabric-harness] Durable dynamic-agent execution requires an addressable agent name and instance session.");
386
413
  }
387
414
  const submission = currentSubmissionContext();
388
415
  return {
@@ -391,26 +418,34 @@ function createDynamicRuntime(frame, state, connections, refresh) {
391
418
  instanceId,
392
419
  resourceFingerprint: resourceFingerprint(frame),
393
420
  ...(delivery ? { delivery } : {}),
394
- ...(submission?.tenantId ?? tenantId ? { tenantId: submission?.tenantId ?? tenantId } : {}),
395
- ...(submission?.actor ?? actor ? { actor: submission?.actor ?? actor } : {}),
421
+ ...((submission?.tenantId ?? tenantId)
422
+ ? { tenantId: submission?.tenantId ?? tenantId }
423
+ : {}),
424
+ ...((submission?.actor ?? actor) ? { actor: submission?.actor ?? actor } : {}),
396
425
  ...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
397
426
  ...(submission?.attemptId ? { attemptId: submission.attemptId } : {}),
398
427
  };
399
428
  },
400
- refresh,
429
+ async refresh(input) {
430
+ const config = await refresh(input);
431
+ const next = config.dynamic && lifecycleContexts.get(config.dynamic);
432
+ if (next)
433
+ Object.assign(next, execution);
434
+ return config;
435
+ },
401
436
  async runResponseStart(response = emptyResponse, correlation = undefined) {
437
+ execution.metadata = {};
402
438
  if (frame.responseStarts.length === 0)
403
- return metadata;
404
- metadata = await runMetadataCallbacks(frame.responseStarts, baseContext(response));
405
- await appendDynamicEntry(state, 'response_metadata', { phase: 'start', metadata }, correlation);
406
- return metadata;
439
+ return execution.metadata;
440
+ execution.metadata = await runMetadataCallbacks(frame.responseStarts, baseContext(response));
441
+ await appendDynamicEntry(state, "response_metadata", { phase: "start", metadata: execution.metadata }, correlation);
442
+ return execution.metadata;
407
443
  },
408
444
  async runAgentStart(input) {
409
- lifecycleSignal = input.signal ?? lifecycleSignal;
410
- lifecycleSandbox = input.sandbox ?? lifecycleSandbox;
445
+ runtime.bindLifecycleContext(input);
411
446
  if (frame.agentStarts.length === 0)
412
447
  return [];
413
- const prior = await readLifecycleEntry(state, 'start', undefined, input.submissionId);
448
+ const prior = await readLifecycleEntry(state, "start", undefined, input.submissionId);
414
449
  if (prior?.data?.messages && Array.isArray(prior.data.messages)) {
415
450
  return prior.data.messages.map(assertLifecycleSignal);
416
451
  }
@@ -427,13 +462,13 @@ function createDynamicRuntime(frame, state, connections, refresh) {
427
462
  try {
428
463
  await run({
429
464
  ...baseContext(emptyResponse),
430
- signal: lifecycleSignal,
431
- sandbox: lifecycleSandbox,
432
- harness: { sandbox: lifecycleSandbox },
433
- log: createLifecycleLogger(state, 'start', index),
465
+ signal: execution.signal,
466
+ sandbox: execution.sandbox,
467
+ harness: { sandbox: execution.sandbox },
468
+ log: createLifecycleLogger(state, "start", index),
434
469
  append(message) {
435
470
  if (!open)
436
- throw new Error('[fabric-harness] Agent-start append is closed.');
471
+ throw new Error("[fabric-harness] Agent-start append is closed.");
437
472
  appended.push(assertLifecycleSignal(message));
438
473
  },
439
474
  });
@@ -442,15 +477,15 @@ function createDynamicRuntime(frame, state, connections, refresh) {
442
477
  open = false;
443
478
  }
444
479
  }));
445
- const failures = outcomes.flatMap((outcome) => outcome.status === 'rejected' ? [outcome.reason] : []);
480
+ const failures = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
446
481
  if (failures.length === 1)
447
482
  throw failures[0];
448
483
  if (failures.length > 1) {
449
- throw new AggregateError(failures, '[fabric-harness] Multiple useAgentStart callbacks failed.');
484
+ throw new AggregateError(failures, "[fabric-harness] Multiple useAgentStart callbacks failed.");
450
485
  }
451
486
  await Promise.all(collector.pending);
452
487
  const appended = appendedByHook.flat();
453
- await commitLifecycle(state, collector.writes, 'start', {
488
+ await commitLifecycle(state, collector.writes, "start", {
454
489
  messages: appended,
455
490
  }, {
456
491
  ...(input.submissionId ? { submissionId: input.submissionId } : {}),
@@ -460,59 +495,101 @@ function createDynamicRuntime(frame, state, connections, refresh) {
460
495
  return appendedByHook.flat();
461
496
  },
462
497
  async runAgentFinish(response, correlation) {
463
- const prior = await readLifecycleEntry(state, 'finish', response.responseId, correlation?.submissionId);
464
- if (prior?.data?.messages && Array.isArray(prior.data.messages)) {
465
- return prior.data.messages.map((message) => {
466
- const normalized = normalizeDeliveredMessage(message);
467
- if (normalized.kind !== 'signal') {
468
- throw new Error('[fabric-harness] Persisted agent-finish continuation must be a signal.');
498
+ return enqueueEffect(state, async (collector) => {
499
+ const prior = await readLifecycleEntry(state, "finish", response.responseId, correlation?.submissionId);
500
+ if (prior?.data?.messages && Array.isArray(prior.data.messages)) {
501
+ return prior.data.messages.map((message) => {
502
+ const normalized = normalizeDeliveredMessage(message);
503
+ if (normalized.kind !== "signal") {
504
+ throw new Error("[fabric-harness] Persisted agent-finish continuation must be a signal.");
505
+ }
506
+ return normalized;
507
+ });
508
+ }
509
+ await restoreResponseMetadata(state, execution, correlation?.submissionId);
510
+ const fresh = await captureFinishFrame();
511
+ const appended = [];
512
+ if (fresh.agentFinishes.length === 0)
513
+ return appended;
514
+ // Serialize on the active runtime, but let freshly rendered setters
515
+ // collect writes for the current snapshot in the same atomic commit.
516
+ fresh.state.active = collector;
517
+ try {
518
+ for (const [index, run] of fresh.agentFinishes.entries()) {
519
+ let open = true;
520
+ try {
521
+ await run({
522
+ ...baseContext(response),
523
+ signal: execution.signal,
524
+ sandbox: execution.sandbox,
525
+ harness: { sandbox: execution.sandbox },
526
+ log: createLifecycleLogger(fresh.state, "finish", index),
527
+ append(message) {
528
+ if (!open)
529
+ throw new Error("[fabric-harness] Agent-finish append is closed.");
530
+ appended.push(assertLifecycleSignal(message));
531
+ },
532
+ });
533
+ }
534
+ finally {
535
+ open = false;
536
+ }
469
537
  }
470
- return normalized;
471
- });
472
- }
473
- const appended = [];
474
- if (frame.agentFinishes.length === 0)
538
+ await Promise.all(collector.pending);
539
+ await commitLifecycle(fresh.state, collector.writes, "finish", {
540
+ ...(response.responseId ? { responseId: response.responseId } : {}),
541
+ messages: appended,
542
+ }, correlation);
543
+ runtime.acknowledgeStateWrites(collector.writes);
544
+ }
545
+ finally {
546
+ fresh.state.active = undefined;
547
+ }
475
548
  return appended;
476
- await enqueueEffect(state, async (collector) => {
477
- for (const [index, run] of frame.agentFinishes.entries()) {
478
- let open = true;
479
- try {
480
- await run({
481
- ...baseContext(response),
482
- signal: lifecycleSignal,
483
- sandbox: lifecycleSandbox,
484
- harness: { sandbox: lifecycleSandbox },
485
- log: createLifecycleLogger(state, 'finish', index),
486
- append(message) {
487
- if (!open)
488
- throw new Error('[fabric-harness] Agent-finish append is closed.');
489
- appended.push(assertLifecycleSignal(message));
490
- },
491
- });
549
+ }, correlation);
550
+ },
551
+ async runResponseFinish(response, correlation) {
552
+ return enqueueEffect(state, async (collector) => {
553
+ const prior = await readResponseMetadata(state, "finish", response.responseId, correlation?.submissionId);
554
+ if (prior?.data?.metadata) {
555
+ execution.metadata = prior.data.metadata;
556
+ return execution.metadata;
557
+ }
558
+ await restoreResponseMetadata(state, execution, correlation?.submissionId);
559
+ const fresh = await captureFinishFrame();
560
+ if (fresh.responseFinishes.length === 0)
561
+ return execution.metadata;
562
+ fresh.state.active = collector;
563
+ try {
564
+ execution.metadata = await runMetadataCallbacks(fresh.responseFinishes, baseContext(response), execution.metadata);
565
+ await Promise.all(collector.pending);
566
+ const payload = {
567
+ phase: "finish",
568
+ ...(response.responseId ? { responseId: response.responseId } : {}),
569
+ metadata: execution.metadata,
570
+ };
571
+ if (collector.writes.length > 0) {
572
+ await commitResponseFinish(fresh.state, collector.writes, payload, correlation);
573
+ runtime.acknowledgeStateWrites(collector.writes);
492
574
  }
493
- finally {
494
- open = false;
575
+ else {
576
+ await appendDynamicEntry(state, "response_metadata", payload, correlation);
495
577
  }
496
578
  }
497
- await Promise.all(collector.pending);
498
- await commitLifecycle(state, collector.writes, 'finish', {
499
- ...(response.responseId ? { responseId: response.responseId } : {}),
500
- messages: appended,
501
- }, correlation);
579
+ finally {
580
+ fresh.state.active = undefined;
581
+ }
582
+ return execution.metadata;
502
583
  }, correlation);
503
- return appended;
504
- },
505
- async runResponseFinish(response, correlation) {
506
- if (frame.responseFinishes.length === 0)
507
- return metadata;
508
- metadata = await runMetadataCallbacks(frame.responseFinishes, baseContext(response), metadata);
509
- await appendDynamicEntry(state, 'response_metadata', { phase: 'finish', metadata }, correlation);
510
- return metadata;
511
584
  },
512
585
  acknowledgeStateWrites(writes) {
513
586
  for (const write of writes)
514
587
  state.snapshot.set(write.name, write.value);
515
588
  },
589
+ bindLifecycleContext(input) {
590
+ execution.signal = input.signal ?? execution.signal;
591
+ execution.sandbox = input.sandbox ?? execution.sandbox;
592
+ },
516
593
  async close() {
517
594
  if (closed)
518
595
  return;
@@ -520,13 +597,37 @@ function createDynamicRuntime(frame, state, connections, refresh) {
520
597
  await Promise.all(connections.map((connection) => connection.close()));
521
598
  },
522
599
  };
600
+ lifecycleContexts.set(runtime, execution);
601
+ return runtime;
602
+ }
603
+ async function readResponseMetadata(state, phase, responseId, submissionIdOverride) {
604
+ const submissionId = submissionIdOverride ?? currentSubmissionContext()?.submissionId;
605
+ if (!submissionId || !state.options.store || !state.options.storeSessionId)
606
+ return undefined;
607
+ return [
608
+ ...SessionHistory.fromData(await state.options.store.load(state.options.storeSessionId)).getActivePath(),
609
+ ]
610
+ .reverse()
611
+ .find((entry) => entry.type === "response_metadata" &&
612
+ entry.data?.phase === phase &&
613
+ entry.tenantId === state.options.tenantId &&
614
+ approvalInputDigest(entry.actor ?? null) ===
615
+ approvalInputDigest(state.options.actor ?? null) &&
616
+ entry.data?.submissionId === submissionId &&
617
+ (phase === "start" || entry.data?.responseId === responseId));
618
+ }
619
+ async function restoreResponseMetadata(state, execution, submissionId) {
620
+ const prior = await readResponseMetadata(state, "start", undefined, submissionId);
621
+ if (prior?.data?.metadata) {
622
+ execution.metadata = { ...prior.data.metadata, ...execution.metadata };
623
+ }
523
624
  }
524
625
  async function runMetadataCallbacks(callbacks, context, initial = {}) {
525
626
  let metadata = { ...initial, ...context.metadata };
526
627
  for (const callback of callbacks) {
527
628
  const output = callback({ ...context, metadata });
528
629
  if (output instanceof Promise) {
529
- throw new Error('[fabric-harness] Response metadata callbacks must be synchronous.');
630
+ throw new Error("[fabric-harness] Response metadata callbacks must be synchronous.");
530
631
  }
531
632
  if (output)
532
633
  metadata = deepMerge(metadata, output);
@@ -536,7 +637,7 @@ async function runMetadataCallbacks(callbacks, context, initial = {}) {
536
637
  async function commitLifecycle(state, writes, phase, extra = {}, correlationOverride = {}, messages = []) {
537
638
  const { store, storeSessionId, actor, tenantId } = state.options;
538
639
  if (!store || !storeSessionId || !store.appendEntries) {
539
- throw new Error('[fabric-harness] Dynamic lifecycle state requires atomic SessionStore.appendEntries().');
640
+ throw new Error("[fabric-harness] Dynamic lifecycle state requires atomic SessionStore.appendEntries().");
540
641
  }
541
642
  const current = await store.load(storeSessionId);
542
643
  const timestamp = new Date().toISOString();
@@ -556,7 +657,7 @@ async function commitLifecycle(state, writes, phase, extra = {}, correlationOver
556
657
  const entries = writes.map((write) => {
557
658
  const entry = {
558
659
  id: `${storeSessionId}:lifecycle-state:${crypto.randomUUID()}`,
559
- type: 'agent_state',
660
+ type: "agent_state",
560
661
  ...common,
561
662
  ...(parentId ? { parentId } : {}),
562
663
  data: { name: write.name, value: write.value, source: `agent_${phase}`, ...correlation },
@@ -567,7 +668,7 @@ async function commitLifecycle(state, writes, phase, extra = {}, correlationOver
567
668
  for (const message of messages) {
568
669
  const entry = {
569
670
  id: `${storeSessionId}:lifecycle-signal:${crypto.randomUUID()}`,
570
- type: 'signal',
671
+ type: "signal",
571
672
  ...common,
572
673
  ...(parentId ? { parentId } : {}),
573
674
  data: { ...deliveredSignalToEntryData(message), ...correlation },
@@ -576,8 +677,8 @@ async function commitLifecycle(state, writes, phase, extra = {}, correlationOver
576
677
  entries.push(entry);
577
678
  }
578
679
  entries.push({
579
- id: `${storeSessionId}:lifecycle:${correlationSubmissionId ?? crypto.randomUUID()}:${phase}`,
580
- type: 'agent_lifecycle',
680
+ id: `${storeSessionId}:lifecycle:${correlationSubmissionId ?? crypto.randomUUID()}:${phase}${phase === "finish" && typeof extra.responseId === "string" ? `:${encodeURIComponent(extra.responseId)}` : ""}`,
681
+ type: "agent_lifecycle",
581
682
  ...common,
582
683
  ...(parentId ? { parentId } : {}),
583
684
  data: { phase, ...extra, ...correlation },
@@ -586,7 +687,54 @@ async function commitLifecycle(state, writes, phase, extra = {}, correlationOver
586
687
  expectedLeafId: current?.leafId,
587
688
  });
588
689
  if (!committed) {
589
- throw new Error('[fabric-harness] Dynamic lifecycle changed concurrently; retry the interaction.');
690
+ throw new Error("[fabric-harness] Dynamic lifecycle changed concurrently; retry the interaction.");
691
+ }
692
+ for (const write of writes)
693
+ state.snapshot.set(write.name, write.value);
694
+ }
695
+ async function commitResponseFinish(state, writes, metadataPayload, correlationOverride = {}) {
696
+ const { store, storeSessionId, actor, tenantId } = state.options;
697
+ if (!store || !storeSessionId || !store.appendEntries) {
698
+ throw new Error("[fabric-harness] Dynamic lifecycle state requires atomic SessionStore.appendEntries().");
699
+ }
700
+ const current = await store.load(storeSessionId);
701
+ const timestamp = new Date().toISOString();
702
+ const submission = currentSubmissionContext();
703
+ const correlationSubmissionId = correlationOverride.submissionId ?? submission?.submissionId;
704
+ const correlationAttemptId = correlationOverride.attemptId ?? submission?.attemptId;
705
+ const correlation = {
706
+ ...(correlationSubmissionId ? { submissionId: correlationSubmissionId } : {}),
707
+ ...(correlationAttemptId ? { attemptId: correlationAttemptId } : {}),
708
+ };
709
+ const common = {
710
+ timestamp,
711
+ ...(actor ? { actor } : {}),
712
+ ...(tenantId ? { tenantId } : {}),
713
+ };
714
+ let parentId = current?.leafId;
715
+ const entries = writes.map((write) => {
716
+ const entry = {
717
+ id: `${storeSessionId}:lifecycle-state:${crypto.randomUUID()}`,
718
+ type: "agent_state",
719
+ ...common,
720
+ ...(parentId ? { parentId } : {}),
721
+ data: { name: write.name, value: write.value, source: "response_finish", ...correlation },
722
+ };
723
+ parentId = entry.id;
724
+ return entry;
725
+ });
726
+ entries.push({
727
+ id: `${storeSessionId}-response_metadata-${Date.now()}-${crypto.randomUUID()}`,
728
+ type: "response_metadata",
729
+ ...common,
730
+ ...(parentId ? { parentId } : {}),
731
+ data: { ...metadataPayload, ...correlation },
732
+ });
733
+ const committed = await store.appendEntries(storeSessionId, entries, {
734
+ expectedLeafId: current?.leafId,
735
+ });
736
+ if (!committed) {
737
+ throw new Error("[fabric-harness] Dynamic lifecycle changed concurrently; retry the interaction.");
590
738
  }
591
739
  for (const write of writes)
592
740
  state.snapshot.set(write.name, write.value);
@@ -596,10 +744,15 @@ async function readLifecycleEntry(state, phase, responseId, submissionIdOverride
596
744
  if (!submissionId || !state.options.store || !state.options.storeSessionId)
597
745
  return undefined;
598
746
  const path = SessionHistory.fromData(await state.options.store.load(state.options.storeSessionId)).getActivePath();
599
- return [...path].reverse().find((entry) => entry.type === 'agent_lifecycle' &&
747
+ return [...path]
748
+ .reverse()
749
+ .find((entry) => entry.type === "agent_lifecycle" &&
750
+ entry.tenantId === state.options.tenantId &&
751
+ approvalInputDigest(entry.actor ?? null) ===
752
+ approvalInputDigest(state.options.actor ?? null) &&
600
753
  entry.data?.phase === phase &&
601
754
  entry.data?.submissionId === submissionId &&
602
- (phase !== 'finish' || entry.data?.responseId === responseId));
755
+ (phase !== "finish" || entry.data?.responseId === responseId));
603
756
  }
604
757
  async function appendDynamicEntry(state, type, data, correlationOverride) {
605
758
  const { store, storeSessionId, actor, tenantId } = state.options;
@@ -627,8 +780,8 @@ async function appendDynamicEntry(state, type, data, correlationOverride) {
627
780
  }
628
781
  function assertLifecycleSignal(message) {
629
782
  const normalized = normalizeDeliveredMessage(message);
630
- if (normalized.kind !== 'signal') {
631
- throw new Error('[fabric-harness] Lifecycle append requires a signal message.');
783
+ if (normalized.kind !== "signal") {
784
+ throw new Error("[fabric-harness] Lifecycle append requires a signal message.");
632
785
  }
633
786
  return normalized;
634
787
  }
@@ -636,10 +789,10 @@ function createLifecycleLogger(state, phase, hookIndex) {
636
789
  const write = (level, message, data) => {
637
790
  const collector = state.active;
638
791
  if (!collector) {
639
- throw new Error('[fabric-harness] Lifecycle logging requires an active callback.');
792
+ throw new Error("[fabric-harness] Lifecycle logging requires an active callback.");
640
793
  }
641
- enqueueCollectorEntry(collector, () => appendDynamicEntry(state, 'metric', {
642
- kind: 'agent_lifecycle_progress',
794
+ enqueueCollectorEntry(collector, () => appendDynamicEntry(state, "metric", {
795
+ kind: "agent_lifecycle_progress",
643
796
  phase,
644
797
  hookIndex,
645
798
  level,
@@ -648,9 +801,9 @@ function createLifecycleLogger(state, phase, hookIndex) {
648
801
  }, collector.correlation));
649
802
  };
650
803
  return {
651
- info: (message, data) => write('info', message, data),
652
- warn: (message, data) => write('warn', message, data),
653
- error: (message, data) => write('error', message, data),
804
+ info: (message, data) => write("info", message, data),
805
+ warn: (message, data) => write("warn", message, data),
806
+ error: (message, data) => write("error", message, data),
654
807
  };
655
808
  }
656
809
  function enqueueCollectorEntry(collector, append) {
@@ -663,12 +816,12 @@ async function persistRenderStructure(frame, state) {
663
816
  if (!store || !storeSessionId)
664
817
  return;
665
818
  if (!store.appendEntry) {
666
- throw new Error('[fabric-harness] Dynamic agent structure requires SessionStore.appendEntry().');
819
+ throw new Error("[fabric-harness] Dynamic agent structure requires SessionStore.appendEntry().");
667
820
  }
668
821
  const next = renderStructure(frame);
669
822
  let current = await store.load(storeSessionId);
670
823
  let path = SessionHistory.fromData(current).getActivePath();
671
- let priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
824
+ let priorEntry = [...path].reverse().find((entry) => entry.type === "agent_render_structure");
672
825
  if (!priorEntry && !frame.usedHooks)
673
826
  return;
674
827
  if (!current) {
@@ -683,7 +836,7 @@ async function persistRenderStructure(frame, state) {
683
836
  });
684
837
  current = await store.load(storeSessionId);
685
838
  path = SessionHistory.fromData(current).getActivePath();
686
- priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
839
+ priorEntry = [...path].reverse().find((entry) => entry.type === "agent_render_structure");
687
840
  }
688
841
  const prior = priorEntry?.data?.structure;
689
842
  if (prior) {
@@ -701,7 +854,7 @@ async function persistRenderStructure(frame, state) {
701
854
  : {};
702
855
  const structureEntry = {
703
856
  id: `${storeSessionId}:render:${crypto.randomUUID()}`,
704
- type: 'agent_render_structure',
857
+ type: "agent_render_structure",
705
858
  timestamp,
706
859
  ...(current?.leafId ? { parentId: current.leafId } : {}),
707
860
  ...(actor ? { actor } : {}),
@@ -712,13 +865,13 @@ async function persistRenderStructure(frame, state) {
712
865
  if (prior) {
713
866
  entries.push({
714
867
  id: `${storeSessionId}:resources:${crypto.randomUUID()}`,
715
- type: 'signal',
868
+ type: "signal",
716
869
  timestamp,
717
870
  parentId: structureEntry.id,
718
871
  ...(actor ? { actor } : {}),
719
872
  ...(tenantId ? { tenantId } : {}),
720
873
  data: {
721
- signalType: 'resources.changed',
874
+ signalType: "resources.changed",
722
875
  content: describeStructureChange(prior, next),
723
876
  ...correlation,
724
877
  },
@@ -729,7 +882,7 @@ async function persistRenderStructure(frame, state) {
729
882
  expectedLeafId: current?.leafId,
730
883
  });
731
884
  if (!committed) {
732
- throw new Error('[fabric-harness] Agent resources changed concurrently; retry the interaction.');
885
+ throw new Error("[fabric-harness] Agent resources changed concurrently; retry the interaction.");
733
886
  }
734
887
  return;
735
888
  }
@@ -740,12 +893,16 @@ function renderStructure(frame) {
740
893
  return {
741
894
  dataNames: [...frame.dataNames].sort(),
742
895
  resources: {
743
- tools: frame.tools.map((tool) => [tool.name, tool.description ?? '', JSON.stringify(tool.inputSchema ?? null)]),
744
- skills: frame.skills.map((skill) => [skill.name, skill.description ?? '']),
896
+ tools: frame.tools.map((tool) => [
897
+ tool.name,
898
+ tool.description ?? "",
899
+ JSON.stringify(tool.inputSchema ?? null),
900
+ ]),
901
+ skills: frame.skills.map((skill) => [skill.name, skill.description ?? ""]),
745
902
  subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
746
903
  mcp: frame.mcpConnections.map((connection) => [
747
904
  connection.name,
748
- connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
905
+ connection.url ? sanitizeMcpUrl(connection.url) : "custom",
749
906
  ]),
750
907
  },
751
908
  sandbox: frame.sandbox !== undefined,
@@ -753,23 +910,23 @@ function renderStructure(frame) {
753
910
  }
754
911
  function describeStructureChange(previous, next) {
755
912
  const changes = [];
756
- for (const kind of ['tools', 'skills', 'subagents', 'mcp']) {
913
+ for (const kind of ["tools", "skills", "subagents", "mcp"]) {
757
914
  const before = new Map(previous.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
758
915
  const after = new Map(next.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
759
916
  const added = [...after.keys()].filter((name) => !before.has(name));
760
917
  const removed = [...before.keys()].filter((name) => !after.has(name));
761
918
  const updated = [...after.keys()].filter((name) => before.has(name) && before.get(name) !== after.get(name));
762
919
  if (added.length)
763
- changes.push(`added ${kind}: ${added.join(', ')}`);
920
+ changes.push(`added ${kind}: ${added.join(", ")}`);
764
921
  if (removed.length)
765
- changes.push(`removed ${kind}: ${removed.join(', ')}`);
922
+ changes.push(`removed ${kind}: ${removed.join(", ")}`);
766
923
  if (updated.length)
767
- changes.push(`updated ${kind}: ${updated.join(', ')}`);
924
+ changes.push(`updated ${kind}: ${updated.join(", ")}`);
768
925
  }
769
926
  if (previous.sandbox !== next.sandbox) {
770
- changes.push(next.sandbox ? 'sandbox environment attached' : 'sandbox environment removed');
927
+ changes.push(next.sandbox ? "sandbox environment attached" : "sandbox environment removed");
771
928
  }
772
- return `Your available capabilities changed since the previous response: ${changes.join('; ')}.`;
929
+ return `Your available capabilities changed since the previous response: ${changes.join("; ")}.`;
773
930
  }
774
931
  function setDelta(previous, next) {
775
932
  const before = new Set(previous);
@@ -779,9 +936,9 @@ function setDelta(previous, next) {
779
936
  if (!added.length && !removed.length)
780
937
  return undefined;
781
938
  return [
782
- ...(added.length ? [`added ${added.join(', ')}`] : []),
783
- ...(removed.length ? [`removed ${removed.join(', ')}`] : []),
784
- ].join('; ');
939
+ ...(added.length ? [`added ${added.join(", ")}`] : []),
940
+ ...(removed.length ? [`removed ${removed.join(", ")}`] : []),
941
+ ].join("; ");
785
942
  }
786
943
  async function loadStateSnapshot(store, storeSessionId) {
787
944
  if (!store || !storeSessionId)
@@ -790,10 +947,10 @@ async function loadStateSnapshot(store, storeSessionId) {
790
947
  const active = SessionHistory.fromData(data).getActivePath();
791
948
  const snapshot = new Map();
792
949
  for (const entry of active) {
793
- if (entry.type !== 'agent_state')
950
+ if (entry.type !== "agent_state")
794
951
  continue;
795
- const name = typeof entry.data?.name === 'string' ? entry.data.name : undefined;
796
- if (name && entry.data && 'value' in entry.data)
952
+ const name = typeof entry.data?.name === "string" ? entry.data.name : undefined;
953
+ if (name && entry.data && "value" in entry.data)
797
954
  snapshot.set(name, entry.data.value);
798
955
  }
799
956
  return snapshot;
@@ -808,21 +965,21 @@ async function resolveInitialData(options) {
808
965
  if (current &&
809
966
  (current.tenantId !== undefined || options.tenantId !== undefined) &&
810
967
  current.tenantId !== options.tenantId) {
811
- throw new Error(`[fabric-harness] Persistent instance metadata belongs to tenant ${current.tenantId ?? 'unscoped'}; ` +
812
- `refusing access from ${options.tenantId ?? 'unscoped'}.`);
968
+ throw new Error(`[fabric-harness] Persistent instance metadata belongs to tenant ${current.tenantId ?? "unscoped"}; ` +
969
+ `refusing access from ${options.tenantId ?? "unscoped"}.`);
813
970
  }
814
971
  const recorded = SessionHistory.fromData(current)
815
972
  .getActivePath()
816
- .find((entry) => entry.type === 'agent_initial_data');
817
- if (recorded?.data && 'value' in recorded.data) {
973
+ .find((entry) => entry.type === "agent_initial_data");
974
+ if (recorded?.data && "value" in recorded.data) {
818
975
  return { ...options, initialData: recorded.data.value };
819
976
  }
820
977
  if (options.initialData === undefined)
821
978
  return options;
822
979
  const parsed = options.initialDataSchema
823
- ? options.initialDataSchema.parse(options.initialData, '$initialData')
980
+ ? options.initialDataSchema.parse(options.initialData, "$initialData")
824
981
  : options.initialData;
825
- const value = normalizeJson(parsed, 'Agent initial data');
982
+ const value = normalizeJson(parsed, "Agent initial data");
826
983
  if (!current) {
827
984
  const now = new Date().toISOString();
828
985
  await store.save({
@@ -836,11 +993,11 @@ async function resolveInitialData(options) {
836
993
  continue;
837
994
  }
838
995
  if (!store.appendEntries) {
839
- throw new Error('[fabric-harness] Immutable initial data requires SessionStore.appendEntries() for first-contact concurrency.');
996
+ throw new Error("[fabric-harness] Immutable initial data requires SessionStore.appendEntries() for first-contact concurrency.");
840
997
  }
841
998
  const entry = {
842
999
  id: `${storeSessionId}:initial-data`,
843
- type: 'agent_initial_data',
1000
+ type: "agent_initial_data",
844
1001
  timestamp: new Date().toISOString(),
845
1002
  ...(current.leafId ? { parentId: current.leafId } : {}),
846
1003
  ...(options.tenantId ? { tenantId: options.tenantId } : {}),
@@ -853,7 +1010,7 @@ async function resolveInitialData(options) {
853
1010
  if (committed)
854
1011
  return { ...options, initialData: value };
855
1012
  }
856
- throw new Error('[fabric-harness] Could not establish immutable initial data after concurrent admission retries.');
1013
+ throw new Error("[fabric-harness] Could not establish immutable initial data after concurrent admission retries.");
857
1014
  }
858
1015
  async function connectDeclaredMcp(definitions, state) {
859
1016
  return (await Promise.all(definitions.map(async (definition) => {
@@ -865,16 +1022,16 @@ async function connectDeclaredMcp(definitions, state) {
865
1022
  const allowed = new Set(definition.tools);
866
1023
  const remoteNames = connection.tools.map((tool) => {
867
1024
  const remote = tool.metadata?.mcp?.tool;
868
- return typeof remote === 'string' ? remote : tool.name;
1025
+ return typeof remote === "string" ? remote : tool.name;
869
1026
  });
870
1027
  const missing = definition.tools.filter((name) => !remoteNames.includes(name));
871
1028
  if (missing.length > 0) {
872
1029
  await connection.close();
873
- throw new Error(`MCP connection "${definition.name}" did not advertise configured tool(s): ${missing.join(', ')}.`);
1030
+ throw new Error(`MCP connection "${definition.name}" did not advertise configured tool(s): ${missing.join(", ")}.`);
874
1031
  }
875
1032
  return {
876
1033
  ...connection,
877
- tools: connection.tools.filter((_tool, index) => allowed.has(remoteNames[index] ?? '')),
1034
+ tools: connection.tools.filter((_tool, index) => allowed.has(remoteNames[index] ?? "")),
878
1035
  };
879
1036
  }
880
1037
  const { name, auth, resolveSecret, tools, optional: _optional, connect: _connect, url, ...rest } = definition;
@@ -883,7 +1040,7 @@ async function connectDeclaredMcp(definitions, state) {
883
1040
  const fetchWithAuth = auth
884
1041
  ? async (input, init = {}) => {
885
1042
  const resolveToken = async () => {
886
- if (typeof auth === 'function')
1043
+ if (typeof auth === "function")
887
1044
  return auth();
888
1045
  if (!resolveSecret) {
889
1046
  throw new Error(`MCP connection "${name}" requires resolveSecret for auth secret "${auth.name}".`);
@@ -895,7 +1052,7 @@ async function connectDeclaredMcp(definitions, state) {
895
1052
  if (!token)
896
1053
  throw new Error(`MCP connection "${name}" auth secret was unavailable.`);
897
1054
  const headers = new Headers(init.headers);
898
- headers.set('authorization', `Bearer ${token}`);
1055
+ headers.set("authorization", `Bearer ${token}`);
899
1056
  return (rest.fetch ?? fetch)(input, { ...init, headers });
900
1057
  };
901
1058
  const response = await send();
@@ -911,11 +1068,11 @@ async function connectDeclaredMcp(definitions, state) {
911
1068
  }
912
1069
  catch (error) {
913
1070
  if (definition.optional) {
914
- await appendDynamicEntry(state, 'agent_lifecycle', {
915
- phase: 'mcp_connection_failed',
1071
+ await appendDynamicEntry(state, "agent_lifecycle", {
1072
+ phase: "mcp_connection_failed",
916
1073
  connection: definition.name,
917
1074
  optional: true,
918
- error: 'The optional MCP connection was unavailable and its tools were omitted.',
1075
+ error: "The optional MCP connection was unavailable and its tools were omitted.",
919
1076
  });
920
1077
  return undefined;
921
1078
  }
@@ -924,10 +1081,15 @@ async function connectDeclaredMcp(definitions, state) {
924
1081
  }))).filter((value) => value !== undefined);
925
1082
  }
926
1083
  function resolveSubagent(definition) {
927
- const state = { snapshot: new Map(), options: {}, active: undefined, queue: Promise.resolve() };
928
- const frame = createFrame('subagent', state);
1084
+ const state = {
1085
+ snapshot: new Map(),
1086
+ options: {},
1087
+ active: undefined,
1088
+ queue: Promise.resolve(),
1089
+ };
1090
+ const frame = createFrame("subagent", state);
929
1091
  if (currentFrame)
930
- throw new Error('[fabric-harness] Re-entrant subagent render is not supported.');
1092
+ throw new Error("[fabric-harness] Re-entrant subagent render is not supported.");
931
1093
  currentFrame = frame;
932
1094
  let instruction;
933
1095
  try {
@@ -936,7 +1098,7 @@ function resolveSubagent(definition) {
936
1098
  finally {
937
1099
  currentFrame = undefined;
938
1100
  }
939
- const content = [instruction, ...frame.instructions].filter(Boolean).join('\n\n');
1101
+ const content = [instruction, ...frame.instructions].filter(Boolean).join("\n\n");
940
1102
  const subagents = frame.subagents.map(resolveSubagent);
941
1103
  return {
942
1104
  name: definition.name,
@@ -963,12 +1125,12 @@ function resourceFingerprint(frame) {
963
1125
  subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
964
1126
  mcp: frame.mcpConnections.map((connection) => [
965
1127
  connection.name,
966
- connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
1128
+ connection.url ? sanitizeMcpUrl(connection.url) : "custom",
967
1129
  ]),
968
1130
  });
969
1131
  }
970
1132
  function isPersistentConfig(value) {
971
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
972
1134
  }
973
1135
  function assertUniqueNames(names, kind) {
974
1136
  const seen = new Set();
@@ -979,13 +1141,15 @@ function assertUniqueNames(names, kind) {
979
1141
  }
980
1142
  }
981
1143
  function assertMcpConnection(definition) {
982
- if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
983
- throw new Error('[fabric-harness] MCP connection requires a non-empty name.');
1144
+ if (!definition || typeof definition !== "object" || !definition.name?.trim()) {
1145
+ throw new Error("[fabric-harness] MCP connection requires a non-empty name.");
984
1146
  }
985
- if (!definition.connect && !(definition.url instanceof URL) && (typeof definition.url !== 'string' || !URL.canParse(definition.url))) {
1147
+ if (!definition.connect &&
1148
+ !(definition.url instanceof URL) &&
1149
+ (typeof definition.url !== "string" || !URL.canParse(definition.url))) {
986
1150
  throw new Error(`[fabric-harness] MCP connection "${definition.name}" requires an absolute URL or connect() factory.`);
987
1151
  }
988
- if (typeof definition.auth === 'string') {
1152
+ if (typeof definition.auth === "string") {
989
1153
  throw new Error(`[fabric-harness] MCP connection "${definition.name}" must use an auth resolver or SecretRef, not a raw secret.`);
990
1154
  }
991
1155
  if (definition.url) {
@@ -998,24 +1162,24 @@ function assertMcpConnection(definition) {
998
1162
  }
999
1163
  function sanitizeMcpUrl(value) {
1000
1164
  const url = new URL(value);
1001
- url.username = '';
1002
- url.password = '';
1003
- url.search = '';
1004
- url.hash = '';
1165
+ url.username = "";
1166
+ url.password = "";
1167
+ url.search = "";
1168
+ url.hash = "";
1005
1169
  return url.toString();
1006
1170
  }
1007
1171
  function assertSubagent(definition) {
1008
- if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
1009
- throw new Error('[fabric-harness] Subagent requires a non-empty name.');
1172
+ if (!definition || typeof definition !== "object" || !definition.name?.trim()) {
1173
+ throw new Error("[fabric-harness] Subagent requires a non-empty name.");
1010
1174
  }
1011
1175
  if (!definition.description?.trim())
1012
1176
  throw new Error(`[fabric-harness] Subagent "${definition.name}" requires a description.`);
1013
- if (typeof definition.agent !== 'function')
1177
+ if (typeof definition.agent !== "function")
1014
1178
  throw new Error(`[fabric-harness] Subagent "${definition.name}" requires an agent function.`);
1015
1179
  }
1016
1180
  function parsePersistentTarget(storeSessionId) {
1017
- const parts = storeSessionId.split(':');
1018
- return parts.length === 4 && parts[0] === 'agent' && parts[2] && parts[3]
1181
+ const parts = storeSessionId.split(":");
1182
+ return parts.length === 4 && parts[0] === "agent" && parts[2] && parts[3]
1019
1183
  ? { instanceId: parts[2], session: parts[3] }
1020
1184
  : undefined;
1021
1185
  }
@@ -1040,13 +1204,12 @@ function deepMerge(left, right) {
1040
1204
  const output = { ...left };
1041
1205
  for (const [key, value] of Object.entries(right)) {
1042
1206
  const prior = output[key];
1043
- output[key] =
1044
- isJsonObject(prior) && isJsonObject(value) ? deepMerge(prior, value) : value;
1207
+ output[key] = isJsonObject(prior) && isJsonObject(value) ? deepMerge(prior, value) : value;
1045
1208
  }
1046
1209
  return output;
1047
1210
  }
1048
1211
  function isJsonObject(value) {
1049
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1212
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1050
1213
  }
1051
1214
  /** Build an atomic agent-state entry batch for a successful tool outcome. */
1052
1215
  export function dynamicStateEntriesForTool(input, writes) {
@@ -1054,7 +1217,7 @@ export function dynamicStateEntriesForTool(input, writes) {
1054
1217
  return writes.map((write, index) => {
1055
1218
  const entry = {
1056
1219
  id: `agent-state:${encodeURIComponent(input.toolCallId)}:${index}`,
1057
- type: 'agent_state',
1220
+ type: "agent_state",
1058
1221
  timestamp: input.timestamp,
1059
1222
  ...(parentId ? { parentId } : {}),
1060
1223
  ...(input.actor ? { actor: input.actor } : {}),