@fabric-harness/sdk 5.2.0 → 6.0.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 (105) hide show
  1. package/README.md +24 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +7 -0
  4. package/dist/agent.js.map +1 -1
  5. package/dist/conversation-projection.d.ts +1 -1
  6. package/dist/conversation-projection.d.ts.map +1 -1
  7. package/dist/conversation-projection.js +61 -5
  8. package/dist/conversation-projection.js.map +1 -1
  9. package/dist/conversation-stream-contract.d.ts.map +1 -1
  10. package/dist/conversation-stream-contract.js +86 -0
  11. package/dist/conversation-stream-contract.js.map +1 -1
  12. package/dist/conversation-stream.d.ts +32 -1
  13. package/dist/conversation-stream.d.ts.map +1 -1
  14. package/dist/conversation-stream.js +81 -1
  15. package/dist/conversation-stream.js.map +1 -1
  16. package/dist/conversation-ui.d.ts +8 -0
  17. package/dist/conversation-ui.d.ts.map +1 -1
  18. package/dist/conversation-ui.js +82 -5
  19. package/dist/conversation-ui.js.map +1 -1
  20. package/dist/dispatch.d.ts +15 -1
  21. package/dist/dispatch.d.ts.map +1 -1
  22. package/dist/dispatch.js +14 -0
  23. package/dist/dispatch.js.map +1 -1
  24. package/dist/dynamic-agent.d.ts +186 -0
  25. package/dist/dynamic-agent.d.ts.map +1 -0
  26. package/dist/dynamic-agent.js +1068 -0
  27. package/dist/dynamic-agent.js.map +1 -0
  28. package/dist/error.d.ts +3 -1
  29. package/dist/error.d.ts.map +1 -1
  30. package/dist/error.js +25 -0
  31. package/dist/error.js.map +1 -1
  32. package/dist/events.d.ts +30 -0
  33. package/dist/events.d.ts.map +1 -1
  34. package/dist/events.js.map +1 -1
  35. package/dist/history.d.ts.map +1 -1
  36. package/dist/history.js +57 -5
  37. package/dist/history.js.map +1 -1
  38. package/dist/in-memory-submission-store.d.ts +5 -0
  39. package/dist/in-memory-submission-store.d.ts.map +1 -1
  40. package/dist/in-memory-submission-store.js +70 -2
  41. package/dist/in-memory-submission-store.js.map +1 -1
  42. package/dist/index.d.ts +11 -9
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -4
  45. package/dist/index.js.map +1 -1
  46. package/dist/loop.d.ts +12 -0
  47. package/dist/loop.d.ts.map +1 -1
  48. package/dist/loop.js +67 -2
  49. package/dist/loop.js.map +1 -1
  50. package/dist/model.d.ts +6 -0
  51. package/dist/model.d.ts.map +1 -1
  52. package/dist/model.js +22 -2
  53. package/dist/model.js.map +1 -1
  54. package/dist/operational-metrics.d.ts.map +1 -1
  55. package/dist/operational-metrics.js +4 -2
  56. package/dist/operational-metrics.js.map +1 -1
  57. package/dist/persistent-agent.d.ts +45 -3
  58. package/dist/persistent-agent.d.ts.map +1 -1
  59. package/dist/persistent-agent.js +163 -3
  60. package/dist/persistent-agent.js.map +1 -1
  61. package/dist/pi-loop-runtime.d.ts +9 -2
  62. package/dist/pi-loop-runtime.d.ts.map +1 -1
  63. package/dist/pi-loop-runtime.js +109 -39
  64. package/dist/pi-loop-runtime.js.map +1 -1
  65. package/dist/sandbox.d.ts +15 -0
  66. package/dist/sandbox.d.ts.map +1 -1
  67. package/dist/sandbox.js +45 -0
  68. package/dist/sandbox.js.map +1 -1
  69. package/dist/session.d.ts +12 -4
  70. package/dist/session.d.ts.map +1 -1
  71. package/dist/session.js +798 -71
  72. package/dist/session.js.map +1 -1
  73. package/dist/store.d.ts.map +1 -1
  74. package/dist/store.js +6 -0
  75. package/dist/store.js.map +1 -1
  76. package/dist/strict.d.ts +11 -9
  77. package/dist/strict.d.ts.map +1 -1
  78. package/dist/strict.js +5 -4
  79. package/dist/strict.js.map +1 -1
  80. package/dist/submission-runner.d.ts +9 -2
  81. package/dist/submission-runner.d.ts.map +1 -1
  82. package/dist/submission-runner.js +130 -10
  83. package/dist/submission-runner.js.map +1 -1
  84. package/dist/submission-state.d.ts +1 -1
  85. package/dist/submission-state.d.ts.map +1 -1
  86. package/dist/submission-state.js +13 -6
  87. package/dist/submission-state.js.map +1 -1
  88. package/dist/submission-store-contract.d.ts.map +1 -1
  89. package/dist/submission-store-contract.js +63 -0
  90. package/dist/submission-store-contract.js.map +1 -1
  91. package/dist/submission-store.d.ts +30 -2
  92. package/dist/submission-store.d.ts.map +1 -1
  93. package/dist/submission-store.js +8 -0
  94. package/dist/submission-store.js.map +1 -1
  95. package/dist/submission-telemetry.d.ts +19 -1
  96. package/dist/submission-telemetry.d.ts.map +1 -1
  97. package/dist/submission-telemetry.js.map +1 -1
  98. package/dist/tools.d.ts +70 -1
  99. package/dist/tools.d.ts.map +1 -1
  100. package/dist/tools.js +119 -2
  101. package/dist/tools.js.map +1 -1
  102. package/dist/types.d.ts +67 -4
  103. package/dist/types.d.ts.map +1 -1
  104. package/dist/types.js.map +1 -1
  105. package/package.json +3 -3
@@ -0,0 +1,1068 @@
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
+ let currentFrame;
9
+ const dynamicToolResultSymbol = Symbol.for('fabric-harness.dynamic-tool-result');
10
+ export function unwrapDynamicToolResult(value) {
11
+ if (typeof value === 'object' &&
12
+ value !== null &&
13
+ value[dynamicToolResultSymbol] === true) {
14
+ const result = value;
15
+ return { output: result.output, stateWrites: result.stateWrites };
16
+ }
17
+ return { output: value, stateWrites: [] };
18
+ }
19
+ function requireFrame(hook) {
20
+ if (!currentFrame) {
21
+ throw new Error(`[fabric-harness] ${hook}() was called outside createAgent(). Hooks must run synchronously in the persistent-agent initializer or a custom hook it calls.`);
22
+ }
23
+ currentFrame.usedHooks = true;
24
+ return currentFrame;
25
+ }
26
+ function rejectSubagent(frame, hook) {
27
+ if (frame.kind === 'subagent') {
28
+ throw new Error(`[fabric-harness] ${hook}() is not available while rendering a subagent.`);
29
+ }
30
+ }
31
+ export function isDynamicAgentRendering() {
32
+ return currentFrame !== undefined;
33
+ }
34
+ export async function renderDynamicAgent(render, props, options = {}, staticConfig = {}) {
35
+ 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;
52
+ const base = {
53
+ ...staticConfig,
54
+ ...(isPersistentConfig(result) ? result : {}),
55
+ };
56
+ const returnedInstruction = typeof result === 'string' ? result : undefined;
57
+ const instructions = [base.instructions, returnedInstruction, ...frame.instructions]
58
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
59
+ .join('\n\n');
60
+ await persistRenderStructure(frame, state);
61
+ const connections = await connectDeclaredMcp(frame.mcpConnections, state);
62
+ const mcpTools = connections.flatMap((connection) => connection.tools);
63
+ const hookTools = frame.tools.map((tool) => wrapDynamicTool(tool, state));
64
+ const roles = frame.subagents.map(resolveSubagent);
65
+ const tools = [...(base.tools ?? []), ...hookTools, ...mcpTools];
66
+ assertUniqueNames(tools.map((tool) => tool.name), 'tool');
67
+ const skills = [...(base.skills ?? []), ...frame.skills];
68
+ assertUniqueNames(skills.map((skill) => skill.name), 'skill');
69
+ const subagents = [...(base.subagents ?? []), ...roles];
70
+ assertUniqueNames(subagents.map((role) => role.name), 'subagent');
71
+ const runtime = createDynamicRuntime(frame, state, connections, (input = {}) => renderDynamicAgent(render, props, {
72
+ ...options,
73
+ ...(input.delivery !== undefined ? { delivery: input.delivery } : {}),
74
+ }, staticConfig));
75
+ return {
76
+ ...base,
77
+ ...(frame.model !== undefined ? { model: frame.model } : {}),
78
+ ...(frame.thinkingLevel !== undefined ? { thinkingLevel: frame.thinkingLevel } : {}),
79
+ ...(frame.compaction !== undefined
80
+ ? { compaction: frame.compaction === false ? { enabled: false } : frame.compaction }
81
+ : {}),
82
+ ...(frame.sandbox !== undefined ? { sandbox: frame.sandbox } : {}),
83
+ ...(frame.cwd !== undefined ? { cwd: frame.cwd } : {}),
84
+ ...(instructions ? { instructions } : {}),
85
+ ...(tools.length > 0 ? { tools } : {}),
86
+ ...(skills.length > 0 ? { skills } : {}),
87
+ ...(subagents.length > 0 ? { subagents } : {}),
88
+ dynamic: runtime,
89
+ };
90
+ }
91
+ 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.');
95
+ }
96
+ frame.instructions.push(text);
97
+ }
98
+ export function useModel(model, options = {}) {
99
+ const frame = requireFrame('useModel');
100
+ rejectSubagent(frame, 'useModel');
101
+ 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.');
105
+ }
106
+ frame.model = model;
107
+ if (options.thinkingLevel !== undefined)
108
+ frame.thinkingLevel = options.thinkingLevel;
109
+ if (options.compaction !== undefined)
110
+ frame.compaction = options.compaction;
111
+ }
112
+ export function useSandbox(sandbox, options = {}) {
113
+ const frame = requireFrame('useSandbox');
114
+ rejectSubagent(frame, 'useSandbox');
115
+ if (frame.sandbox !== undefined)
116
+ throw new Error('[fabric-harness] useSandbox() may be called once per render.');
117
+ if (!sandbox)
118
+ throw new Error('[fabric-harness] useSandbox() requires a sandbox backend, factory, or environment.');
119
+ if (options.cwd !== undefined && options.cwd.trim().length === 0) {
120
+ throw new Error('[fabric-harness] useSandbox() options.cwd must be non-empty.');
121
+ }
122
+ frame.sandbox = sandbox;
123
+ if (options.cwd !== undefined)
124
+ frame.cwd = options.cwd;
125
+ }
126
+ 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.');
130
+ }
131
+ if (frame.skills.some((candidate) => candidate.name === skill.name)) {
132
+ throw new Error(`[fabric-harness] Duplicate skill name in one render: ${skill.name}`);
133
+ }
134
+ frame.skills.push(skill);
135
+ }
136
+ export function useTool(tool) {
137
+ const frame = requireFrame('useTool');
138
+ const normalized = defineTool(tool);
139
+ if (frame.tools.some((candidate) => candidate.name === normalized.name)) {
140
+ throw new Error(`[fabric-harness] Duplicate tool name in one render: ${normalized.name}`);
141
+ }
142
+ frame.tools.push(normalized);
143
+ }
144
+ export function usePersistentState(name, defaultValue, options = {}) {
145
+ const frame = requireFrame('usePersistentState');
146
+ rejectSubagent(frame, 'usePersistentState');
147
+ if (!name.trim())
148
+ throw new Error('[fabric-harness] usePersistentState() requires a non-empty name.');
149
+ if (frame.stateNames.has(name))
150
+ throw new Error(`[fabric-harness] Duplicate persistent state name: ${name}`);
151
+ frame.stateNames.add(name);
152
+ const persisted = frame.state.snapshot.get(name);
153
+ const initial = (persisted === undefined ? defaultValue : persisted);
154
+ const value = options.schema ? options.schema.parse(initial, `$state.${name}`) : initial;
155
+ const setter = (next) => {
156
+ if (isDynamicAgentRendering()) {
157
+ throw new Error(`[fabric-harness] Persistent state "${name}" cannot be written during render.`);
158
+ }
159
+ const collector = frame.state.active;
160
+ if (!collector) {
161
+ throw new Error(`[fabric-harness] Persistent state "${name}" can only be written by a tracked tool or lifecycle callback.`);
162
+ }
163
+ const prior = collector.overlay.has(name)
164
+ ? collector.overlay.get(name)
165
+ : frame.state.snapshot.get(name) ?? normalizeJson(defaultValue, `State "${name}" default`);
166
+ const candidate = typeof next === 'function' ? next(prior) : next;
167
+ const parsed = options.schema ? options.schema.parse(candidate, `$state.${name}`) : candidate;
168
+ const normalized = normalizeJson(parsed, `State "${name}"`);
169
+ if (jsonEqual(prior, normalized))
170
+ return;
171
+ collector.overlay.set(name, normalized);
172
+ collector.writes.push({ name, value: normalized });
173
+ };
174
+ return [value, setter];
175
+ }
176
+ export function useDelivery() {
177
+ const frame = requireFrame('useDelivery');
178
+ if (!frame.state.options.delivery) {
179
+ throw new Error('[fabric-harness] useDelivery() requires a delivered message in the runtime render context.');
180
+ }
181
+ return frame.state.options.delivery;
182
+ }
183
+ export function useInitialData() {
184
+ const frame = requireFrame('useInitialData');
185
+ return frame.kind === 'subagent' ? undefined : frame.state.options.initialData;
186
+ }
187
+ export function useDispatchMessage() {
188
+ const frame = requireFrame('useDispatchMessage');
189
+ rejectSubagent(frame, 'useDispatchMessage');
190
+ const { agentName, storeSessionId } = frame.state.options;
191
+ const persistentIdentity = storeSessionId ? parsePersistentTarget(storeSessionId) : undefined;
192
+ const instanceId = persistentIdentity?.instanceId;
193
+ return async (message) => {
194
+ if (isDynamicAgentRendering())
195
+ throw new Error('[fabric-harness] Dispatch is not allowed during render.');
196
+ if (!agentName || !instanceId || !storeSessionId) {
197
+ throw new Error('[fabric-harness] Self-dispatch requires an addressable persistent-agent runtime.');
198
+ }
199
+ const submission = currentSubmissionContext();
200
+ const request = {
201
+ agent: agentName,
202
+ id: instanceId,
203
+ session: submission?.session ?? persistentIdentity.session,
204
+ message: normalizeDeliveredMessage(message),
205
+ ...(submission?.tenantId ?? frame.state.options.tenantId
206
+ ? { tenantId: submission?.tenantId ?? frame.state.options.tenantId }
207
+ : {}),
208
+ ...(submission?.actor ?? frame.state.options.actor
209
+ ? { actor: submission?.actor ?? frame.state.options.actor }
210
+ : {}),
211
+ };
212
+ if (frame.state.options.dispatchQueue) {
213
+ return enqueueDispatch(frame.state.options.dispatchQueue, request, {
214
+ ...(request.tenantId ? { tenantId: request.tenantId } : {}),
215
+ ...(request.actor ? { actor: request.actor } : {}),
216
+ });
217
+ }
218
+ return dispatch(request);
219
+ };
220
+ }
221
+ export function useDataWriter(name, options = {}) {
222
+ const frame = requireFrame('useDataWriter');
223
+ rejectSubagent(frame, 'useDataWriter');
224
+ if (!name.trim())
225
+ throw new Error('[fabric-harness] useDataWriter() requires a non-empty name.');
226
+ if (frame.dataNames.has(name))
227
+ throw new Error(`[fabric-harness] Duplicate message data name: ${name}`);
228
+ frame.dataNames.add(name);
229
+ return (data) => {
230
+ if (isDynamicAgentRendering())
231
+ throw new Error(`[fabric-harness] Message data "${name}" cannot be written during render.`);
232
+ const collector = frame.state.active;
233
+ if (!collector)
234
+ throw new Error(`[fabric-harness] Message data "${name}" requires an active response callback.`);
235
+ const parsed = options.schema ? options.schema.parse(data, `$data.${name}`) : data;
236
+ const value = normalizeJson(parsed, `Message data "${name}"`);
237
+ enqueueCollectorEntry(collector, () => appendDynamicEntry(frame.state, 'message_data', { name, value }, collector.correlation));
238
+ };
239
+ }
240
+ 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.');
245
+ frame.responseStarts.push(run);
246
+ }
247
+ 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.');
252
+ frame.responseFinishes.push(run);
253
+ }
254
+ 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.');
259
+ frame.agentStarts.push(run);
260
+ }
261
+ 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.');
266
+ frame.agentFinishes.push(run);
267
+ }
268
+ export function defineMcpConnection(definition) {
269
+ assertMcpConnection(definition);
270
+ return Object.freeze({
271
+ ...definition,
272
+ ...(definition.tools ? { tools: Object.freeze([...definition.tools]) } : {}),
273
+ });
274
+ }
275
+ export function useMcpConnection(definition) {
276
+ const frame = requireFrame('useMcpConnection');
277
+ rejectSubagent(frame, 'useMcpConnection');
278
+ assertMcpConnection(definition);
279
+ if (frame.mcpConnections.some((candidate) => candidate.name === definition.name)) {
280
+ throw new Error(`[fabric-harness] Duplicate MCP connection name: ${definition.name}`);
281
+ }
282
+ frame.mcpConnections.push(definition);
283
+ }
284
+ export function defineSubagent(definition) {
285
+ assertSubagent(definition);
286
+ return Object.freeze({ ...definition });
287
+ }
288
+ export const GeneralSubagent = defineSubagent({
289
+ name: 'fabric-general',
290
+ description: 'General-purpose delegate for independent research and file exploration.',
291
+ agent: () => undefined,
292
+ });
293
+ export function useSubagent(definition) {
294
+ const frame = requireFrame('useSubagent');
295
+ assertSubagent(definition);
296
+ if (frame.subagents.some((candidate) => candidate.name === definition.name)) {
297
+ throw new Error(`[fabric-harness] Duplicate subagent name: ${definition.name}`);
298
+ }
299
+ frame.subagents.push(definition);
300
+ }
301
+ function createFrame(kind, state) {
302
+ return {
303
+ kind,
304
+ instructions: [],
305
+ tools: [],
306
+ skills: [],
307
+ subagents: [],
308
+ mcpConnections: [],
309
+ stateNames: new Set(),
310
+ dataNames: new Set(),
311
+ responseStarts: [],
312
+ responseFinishes: [],
313
+ agentStarts: [],
314
+ agentFinishes: [],
315
+ state,
316
+ usedHooks: false,
317
+ };
318
+ }
319
+ function wrapDynamicTool(tool, state) {
320
+ if (!tool.execute)
321
+ return tool;
322
+ return {
323
+ ...tool,
324
+ async execute(input, context) {
325
+ const correlation = context?.__fabricSubmission;
326
+ return enqueueEffect(state, async (collector) => {
327
+ const output = await tool.execute?.(input, context);
328
+ await Promise.all(collector.pending);
329
+ return {
330
+ [dynamicToolResultSymbol]: true,
331
+ output,
332
+ stateWrites: collector.writes,
333
+ };
334
+ }, correlation);
335
+ },
336
+ };
337
+ }
338
+ async function enqueueEffect(state, run, correlation) {
339
+ let resolve;
340
+ let reject;
341
+ const result = new Promise((res, rej) => {
342
+ resolve = res;
343
+ reject = rej;
344
+ });
345
+ const prior = state.queue;
346
+ state.queue = prior.then(async () => {
347
+ const collector = {
348
+ writes: [],
349
+ overlay: new Map(),
350
+ pending: [],
351
+ ...(correlation ? { correlation } : {}),
352
+ };
353
+ state.active = collector;
354
+ try {
355
+ resolve(await run(collector));
356
+ }
357
+ catch (error) {
358
+ reject(error);
359
+ }
360
+ finally {
361
+ state.active = undefined;
362
+ }
363
+ });
364
+ await state.queue;
365
+ return result;
366
+ }
367
+ function createDynamicRuntime(frame, state, connections, refresh) {
368
+ let metadata = {};
369
+ let closed = false;
370
+ let lifecycleSignal = new AbortController().signal;
371
+ let lifecycleSandbox = new EmptySandboxEnv();
372
+ const emptyResponse = { toolCalls: [] };
373
+ const baseContext = (response) => ({
374
+ ...(state.options.delivery ? { delivery: state.options.delivery } : {}),
375
+ metadata,
376
+ response,
377
+ });
378
+ return {
379
+ dataNames: [...frame.dataNames],
380
+ resourceFingerprint: resourceFingerprint(frame),
381
+ executionDescriptor() {
382
+ const { agentName, storeSessionId, delivery, tenantId, actor } = state.options;
383
+ const instanceId = storeSessionId?.split(':')[2];
384
+ 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.');
386
+ }
387
+ const submission = currentSubmissionContext();
388
+ return {
389
+ version: 1,
390
+ agentName,
391
+ instanceId,
392
+ resourceFingerprint: resourceFingerprint(frame),
393
+ ...(delivery ? { delivery } : {}),
394
+ ...(submission?.tenantId ?? tenantId ? { tenantId: submission?.tenantId ?? tenantId } : {}),
395
+ ...(submission?.actor ?? actor ? { actor: submission?.actor ?? actor } : {}),
396
+ ...(submission?.submissionId ? { submissionId: submission.submissionId } : {}),
397
+ ...(submission?.attemptId ? { attemptId: submission.attemptId } : {}),
398
+ };
399
+ },
400
+ refresh,
401
+ async runResponseStart(response = emptyResponse, correlation = undefined) {
402
+ 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;
407
+ },
408
+ async runAgentStart(input) {
409
+ lifecycleSignal = input.signal ?? lifecycleSignal;
410
+ lifecycleSandbox = input.sandbox ?? lifecycleSandbox;
411
+ if (frame.agentStarts.length === 0)
412
+ return [];
413
+ const prior = await readLifecycleEntry(state, 'start', undefined, input.submissionId);
414
+ if (prior?.data?.messages && Array.isArray(prior.data.messages)) {
415
+ return prior.data.messages.map(assertLifecycleSignal);
416
+ }
417
+ const appendedByHook = [];
418
+ const correlation = {
419
+ ...(input.submissionId ? { submissionId: input.submissionId } : {}),
420
+ ...(input.attemptId ? { attemptId: input.attemptId } : {}),
421
+ };
422
+ await enqueueEffect(state, async (collector) => {
423
+ const outcomes = await Promise.allSettled(frame.agentStarts.map(async (run, index) => {
424
+ let open = true;
425
+ const appended = [];
426
+ appendedByHook[index] = appended;
427
+ try {
428
+ await run({
429
+ ...baseContext(emptyResponse),
430
+ signal: lifecycleSignal,
431
+ sandbox: lifecycleSandbox,
432
+ harness: { sandbox: lifecycleSandbox },
433
+ log: createLifecycleLogger(state, 'start', index),
434
+ append(message) {
435
+ if (!open)
436
+ throw new Error('[fabric-harness] Agent-start append is closed.');
437
+ appended.push(assertLifecycleSignal(message));
438
+ },
439
+ });
440
+ }
441
+ finally {
442
+ open = false;
443
+ }
444
+ }));
445
+ const failures = outcomes.flatMap((outcome) => outcome.status === 'rejected' ? [outcome.reason] : []);
446
+ if (failures.length === 1)
447
+ throw failures[0];
448
+ if (failures.length > 1) {
449
+ throw new AggregateError(failures, '[fabric-harness] Multiple useAgentStart callbacks failed.');
450
+ }
451
+ await Promise.all(collector.pending);
452
+ const appended = appendedByHook.flat();
453
+ await commitLifecycle(state, collector.writes, 'start', {
454
+ messages: appended,
455
+ }, {
456
+ ...(input.submissionId ? { submissionId: input.submissionId } : {}),
457
+ ...(input.attemptId ? { attemptId: input.attemptId } : {}),
458
+ }, appended);
459
+ }, correlation);
460
+ return appendedByHook.flat();
461
+ },
462
+ 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.');
469
+ }
470
+ return normalized;
471
+ });
472
+ }
473
+ const appended = [];
474
+ if (frame.agentFinishes.length === 0)
475
+ 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
+ });
492
+ }
493
+ finally {
494
+ open = false;
495
+ }
496
+ }
497
+ await Promise.all(collector.pending);
498
+ await commitLifecycle(state, collector.writes, 'finish', {
499
+ ...(response.responseId ? { responseId: response.responseId } : {}),
500
+ messages: appended,
501
+ }, correlation);
502
+ }, 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
+ },
512
+ acknowledgeStateWrites(writes) {
513
+ for (const write of writes)
514
+ state.snapshot.set(write.name, write.value);
515
+ },
516
+ async close() {
517
+ if (closed)
518
+ return;
519
+ closed = true;
520
+ await Promise.all(connections.map((connection) => connection.close()));
521
+ },
522
+ };
523
+ }
524
+ async function runMetadataCallbacks(callbacks, context, initial = {}) {
525
+ let metadata = { ...initial, ...context.metadata };
526
+ for (const callback of callbacks) {
527
+ const output = callback({ ...context, metadata });
528
+ if (output instanceof Promise) {
529
+ throw new Error('[fabric-harness] Response metadata callbacks must be synchronous.');
530
+ }
531
+ if (output)
532
+ metadata = deepMerge(metadata, output);
533
+ }
534
+ return metadata;
535
+ }
536
+ async function commitLifecycle(state, writes, phase, extra = {}, correlationOverride = {}, messages = []) {
537
+ const { store, storeSessionId, actor, tenantId } = state.options;
538
+ if (!store || !storeSessionId || !store.appendEntries) {
539
+ throw new Error('[fabric-harness] Dynamic lifecycle state requires atomic SessionStore.appendEntries().');
540
+ }
541
+ const current = await store.load(storeSessionId);
542
+ const timestamp = new Date().toISOString();
543
+ const submission = currentSubmissionContext();
544
+ const correlationSubmissionId = correlationOverride.submissionId ?? submission?.submissionId;
545
+ const correlationAttemptId = correlationOverride.attemptId ?? submission?.attemptId;
546
+ const correlation = {
547
+ ...(correlationSubmissionId ? { submissionId: correlationSubmissionId } : {}),
548
+ ...(correlationAttemptId ? { attemptId: correlationAttemptId } : {}),
549
+ };
550
+ const common = {
551
+ timestamp,
552
+ ...(actor ? { actor } : {}),
553
+ ...(tenantId ? { tenantId } : {}),
554
+ };
555
+ let parentId = current?.leafId;
556
+ const entries = writes.map((write) => {
557
+ const entry = {
558
+ id: `${storeSessionId}:lifecycle-state:${crypto.randomUUID()}`,
559
+ type: 'agent_state',
560
+ ...common,
561
+ ...(parentId ? { parentId } : {}),
562
+ data: { name: write.name, value: write.value, source: `agent_${phase}`, ...correlation },
563
+ };
564
+ parentId = entry.id;
565
+ return entry;
566
+ });
567
+ for (const message of messages) {
568
+ const entry = {
569
+ id: `${storeSessionId}:lifecycle-signal:${crypto.randomUUID()}`,
570
+ type: 'signal',
571
+ ...common,
572
+ ...(parentId ? { parentId } : {}),
573
+ data: { ...deliveredSignalToEntryData(message), ...correlation },
574
+ };
575
+ parentId = entry.id;
576
+ entries.push(entry);
577
+ }
578
+ entries.push({
579
+ id: `${storeSessionId}:lifecycle:${correlationSubmissionId ?? crypto.randomUUID()}:${phase}`,
580
+ type: 'agent_lifecycle',
581
+ ...common,
582
+ ...(parentId ? { parentId } : {}),
583
+ data: { phase, ...extra, ...correlation },
584
+ });
585
+ const committed = await store.appendEntries(storeSessionId, entries, {
586
+ expectedLeafId: current?.leafId,
587
+ });
588
+ if (!committed) {
589
+ throw new Error('[fabric-harness] Dynamic lifecycle changed concurrently; retry the interaction.');
590
+ }
591
+ for (const write of writes)
592
+ state.snapshot.set(write.name, write.value);
593
+ }
594
+ async function readLifecycleEntry(state, phase, responseId, submissionIdOverride) {
595
+ const submissionId = submissionIdOverride ?? currentSubmissionContext()?.submissionId;
596
+ if (!submissionId || !state.options.store || !state.options.storeSessionId)
597
+ return undefined;
598
+ const path = SessionHistory.fromData(await state.options.store.load(state.options.storeSessionId)).getActivePath();
599
+ return [...path].reverse().find((entry) => entry.type === 'agent_lifecycle' &&
600
+ entry.data?.phase === phase &&
601
+ entry.data?.submissionId === submissionId &&
602
+ (phase !== 'finish' || entry.data?.responseId === responseId));
603
+ }
604
+ async function appendDynamicEntry(state, type, data, correlationOverride) {
605
+ const { store, storeSessionId, actor, tenantId } = state.options;
606
+ if (!store || !storeSessionId || !store.appendEntry) {
607
+ throw new Error(`[fabric-harness] ${type} requires a durable SessionStore.appendEntry() runtime.`);
608
+ }
609
+ const current = await store.load(storeSessionId);
610
+ const submission = currentSubmissionContext();
611
+ const correlation = correlationOverride ?? submission;
612
+ await store.appendEntry(storeSessionId, {
613
+ id: `${storeSessionId}-${type}-${Date.now()}-${crypto.randomUUID()}`,
614
+ type,
615
+ timestamp: new Date().toISOString(),
616
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
617
+ ...(actor ? { actor } : {}),
618
+ ...(tenantId ? { tenantId } : {}),
619
+ data: correlation
620
+ ? {
621
+ ...data,
622
+ ...(correlation.submissionId ? { submissionId: correlation.submissionId } : {}),
623
+ ...(correlation.attemptId ? { attemptId: correlation.attemptId } : {}),
624
+ }
625
+ : data,
626
+ });
627
+ }
628
+ function assertLifecycleSignal(message) {
629
+ const normalized = normalizeDeliveredMessage(message);
630
+ if (normalized.kind !== 'signal') {
631
+ throw new Error('[fabric-harness] Lifecycle append requires a signal message.');
632
+ }
633
+ return normalized;
634
+ }
635
+ function createLifecycleLogger(state, phase, hookIndex) {
636
+ const write = (level, message, data) => {
637
+ const collector = state.active;
638
+ if (!collector) {
639
+ throw new Error('[fabric-harness] Lifecycle logging requires an active callback.');
640
+ }
641
+ enqueueCollectorEntry(collector, () => appendDynamicEntry(state, 'metric', {
642
+ kind: 'agent_lifecycle_progress',
643
+ phase,
644
+ hookIndex,
645
+ level,
646
+ message,
647
+ ...(data ? { data } : {}),
648
+ }, collector.correlation));
649
+ };
650
+ 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),
654
+ };
655
+ }
656
+ function enqueueCollectorEntry(collector, append) {
657
+ const prior = collector.pending.at(-1);
658
+ const pending = prior ? prior.then(append) : append();
659
+ collector.pending.push(pending);
660
+ }
661
+ async function persistRenderStructure(frame, state) {
662
+ const { store, storeSessionId, actor, tenantId } = state.options;
663
+ if (!store || !storeSessionId)
664
+ return;
665
+ if (!store.appendEntry) {
666
+ throw new Error('[fabric-harness] Dynamic agent structure requires SessionStore.appendEntry().');
667
+ }
668
+ const next = renderStructure(frame);
669
+ let current = await store.load(storeSessionId);
670
+ let path = SessionHistory.fromData(current).getActivePath();
671
+ let priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
672
+ if (!priorEntry && !frame.usedHooks)
673
+ return;
674
+ if (!current) {
675
+ const now = new Date().toISOString();
676
+ await store.save({
677
+ id: storeSessionId,
678
+ createdAt: now,
679
+ updatedAt: now,
680
+ entries: [],
681
+ events: [],
682
+ ...(tenantId ? { tenantId } : {}),
683
+ });
684
+ current = await store.load(storeSessionId);
685
+ path = SessionHistory.fromData(current).getActivePath();
686
+ priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
687
+ }
688
+ const prior = priorEntry?.data?.structure;
689
+ if (prior) {
690
+ const dataDelta = setDelta(prior.dataNames, next.dataNames);
691
+ if (dataDelta) {
692
+ throw new Error(`[fabric-harness] The agent's render changed message-data identity: ${dataDelta}. Declare useDataWriter() names unconditionally on every render.`);
693
+ }
694
+ if (jsonEqual(prior, next))
695
+ return;
696
+ }
697
+ const timestamp = new Date().toISOString();
698
+ const submission = currentSubmissionContext();
699
+ const correlation = submission
700
+ ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
701
+ : {};
702
+ const structureEntry = {
703
+ id: `${storeSessionId}:render:${crypto.randomUUID()}`,
704
+ type: 'agent_render_structure',
705
+ timestamp,
706
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
707
+ ...(actor ? { actor } : {}),
708
+ ...(tenantId ? { tenantId } : {}),
709
+ data: { structure: next, ...correlation },
710
+ };
711
+ const entries = [structureEntry];
712
+ if (prior) {
713
+ entries.push({
714
+ id: `${storeSessionId}:resources:${crypto.randomUUID()}`,
715
+ type: 'signal',
716
+ timestamp,
717
+ parentId: structureEntry.id,
718
+ ...(actor ? { actor } : {}),
719
+ ...(tenantId ? { tenantId } : {}),
720
+ data: {
721
+ signalType: 'resources.changed',
722
+ content: describeStructureChange(prior, next),
723
+ ...correlation,
724
+ },
725
+ });
726
+ }
727
+ if (store.appendEntries) {
728
+ const committed = await store.appendEntries(storeSessionId, entries, {
729
+ expectedLeafId: current?.leafId,
730
+ });
731
+ if (!committed) {
732
+ throw new Error('[fabric-harness] Agent resources changed concurrently; retry the interaction.');
733
+ }
734
+ return;
735
+ }
736
+ for (const entry of entries)
737
+ await store.appendEntry(storeSessionId, entry);
738
+ }
739
+ function renderStructure(frame) {
740
+ return {
741
+ dataNames: [...frame.dataNames].sort(),
742
+ 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 ?? '']),
745
+ subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
746
+ mcp: frame.mcpConnections.map((connection) => [
747
+ connection.name,
748
+ connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
749
+ ]),
750
+ },
751
+ sandbox: frame.sandbox !== undefined,
752
+ };
753
+ }
754
+ function describeStructureChange(previous, next) {
755
+ const changes = [];
756
+ for (const kind of ['tools', 'skills', 'subagents', 'mcp']) {
757
+ const before = new Map(previous.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
758
+ const after = new Map(next.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
759
+ const added = [...after.keys()].filter((name) => !before.has(name));
760
+ const removed = [...before.keys()].filter((name) => !after.has(name));
761
+ const updated = [...after.keys()].filter((name) => before.has(name) && before.get(name) !== after.get(name));
762
+ if (added.length)
763
+ changes.push(`added ${kind}: ${added.join(', ')}`);
764
+ if (removed.length)
765
+ changes.push(`removed ${kind}: ${removed.join(', ')}`);
766
+ if (updated.length)
767
+ changes.push(`updated ${kind}: ${updated.join(', ')}`);
768
+ }
769
+ if (previous.sandbox !== next.sandbox) {
770
+ changes.push(next.sandbox ? 'sandbox environment attached' : 'sandbox environment removed');
771
+ }
772
+ return `Your available capabilities changed since the previous response: ${changes.join('; ')}.`;
773
+ }
774
+ function setDelta(previous, next) {
775
+ const before = new Set(previous);
776
+ const after = new Set(next);
777
+ const added = [...after].filter((name) => !before.has(name));
778
+ const removed = [...before].filter((name) => !after.has(name));
779
+ if (!added.length && !removed.length)
780
+ return undefined;
781
+ return [
782
+ ...(added.length ? [`added ${added.join(', ')}`] : []),
783
+ ...(removed.length ? [`removed ${removed.join(', ')}`] : []),
784
+ ].join('; ');
785
+ }
786
+ async function loadStateSnapshot(store, storeSessionId) {
787
+ if (!store || !storeSessionId)
788
+ return new Map();
789
+ const data = await store.load(storeSessionId);
790
+ const active = SessionHistory.fromData(data).getActivePath();
791
+ const snapshot = new Map();
792
+ for (const entry of active) {
793
+ if (entry.type !== 'agent_state')
794
+ continue;
795
+ const name = typeof entry.data?.name === 'string' ? entry.data.name : undefined;
796
+ if (name && entry.data && 'value' in entry.data)
797
+ snapshot.set(name, entry.data.value);
798
+ }
799
+ return snapshot;
800
+ }
801
+ async function resolveInitialData(options) {
802
+ const storeSessionId = options.instanceStoreSessionId ?? options.storeSessionId;
803
+ const { store } = options;
804
+ if (!store || !storeSessionId)
805
+ return options;
806
+ for (let attempt = 0; attempt < 8; attempt += 1) {
807
+ const current = await store.load(storeSessionId);
808
+ if (current &&
809
+ (current.tenantId !== undefined || options.tenantId !== undefined) &&
810
+ 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'}.`);
813
+ }
814
+ const recorded = SessionHistory.fromData(current)
815
+ .getActivePath()
816
+ .find((entry) => entry.type === 'agent_initial_data');
817
+ if (recorded?.data && 'value' in recorded.data) {
818
+ return { ...options, initialData: recorded.data.value };
819
+ }
820
+ if (options.initialData === undefined)
821
+ return options;
822
+ const parsed = options.initialDataSchema
823
+ ? options.initialDataSchema.parse(options.initialData, '$initialData')
824
+ : options.initialData;
825
+ const value = normalizeJson(parsed, 'Agent initial data');
826
+ if (!current) {
827
+ const now = new Date().toISOString();
828
+ await store.save({
829
+ id: storeSessionId,
830
+ createdAt: now,
831
+ updatedAt: now,
832
+ entries: [],
833
+ events: [],
834
+ ...(options.tenantId ? { tenantId: options.tenantId } : {}),
835
+ });
836
+ continue;
837
+ }
838
+ if (!store.appendEntries) {
839
+ throw new Error('[fabric-harness] Immutable initial data requires SessionStore.appendEntries() for first-contact concurrency.');
840
+ }
841
+ const entry = {
842
+ id: `${storeSessionId}:initial-data`,
843
+ type: 'agent_initial_data',
844
+ timestamp: new Date().toISOString(),
845
+ ...(current.leafId ? { parentId: current.leafId } : {}),
846
+ ...(options.tenantId ? { tenantId: options.tenantId } : {}),
847
+ ...(options.actor ? { actor: options.actor } : {}),
848
+ data: { value },
849
+ };
850
+ const committed = await store.appendEntries(storeSessionId, [entry], {
851
+ expectedLeafId: current.leafId,
852
+ });
853
+ if (committed)
854
+ return { ...options, initialData: value };
855
+ }
856
+ throw new Error('[fabric-harness] Could not establish immutable initial data after concurrent admission retries.');
857
+ }
858
+ async function connectDeclaredMcp(definitions, state) {
859
+ return (await Promise.all(definitions.map(async (definition) => {
860
+ try {
861
+ if (definition.connect) {
862
+ const connection = await definition.connect();
863
+ if (!definition.tools)
864
+ return connection;
865
+ const allowed = new Set(definition.tools);
866
+ const remoteNames = connection.tools.map((tool) => {
867
+ const remote = tool.metadata?.mcp?.tool;
868
+ return typeof remote === 'string' ? remote : tool.name;
869
+ });
870
+ const missing = definition.tools.filter((name) => !remoteNames.includes(name));
871
+ if (missing.length > 0) {
872
+ await connection.close();
873
+ throw new Error(`MCP connection "${definition.name}" did not advertise configured tool(s): ${missing.join(', ')}.`);
874
+ }
875
+ return {
876
+ ...connection,
877
+ tools: connection.tools.filter((_tool, index) => allowed.has(remoteNames[index] ?? '')),
878
+ };
879
+ }
880
+ const { name, auth, resolveSecret, tools, optional: _optional, connect: _connect, url, ...rest } = definition;
881
+ if (!url)
882
+ throw new Error(`MCP connection "${name}" requires a URL or connect() factory.`);
883
+ const fetchWithAuth = auth
884
+ ? async (input, init = {}) => {
885
+ const resolveToken = async () => {
886
+ if (typeof auth === 'function')
887
+ return auth();
888
+ if (!resolveSecret) {
889
+ throw new Error(`MCP connection "${name}" requires resolveSecret for auth secret "${auth.name}".`);
890
+ }
891
+ return resolveSecret(auth);
892
+ };
893
+ const send = async () => {
894
+ const token = await resolveToken();
895
+ if (!token)
896
+ throw new Error(`MCP connection "${name}" auth secret was unavailable.`);
897
+ const headers = new Headers(init.headers);
898
+ headers.set('authorization', `Bearer ${token}`);
899
+ return (rest.fetch ?? fetch)(input, { ...init, headers });
900
+ };
901
+ const response = await send();
902
+ return response.status === 401 ? send() : response;
903
+ }
904
+ : rest.fetch;
905
+ return await connectMcpServer(name, {
906
+ ...rest,
907
+ url,
908
+ ...(tools ? { allowTools: tools } : {}),
909
+ ...(fetchWithAuth ? { fetch: fetchWithAuth } : {}),
910
+ });
911
+ }
912
+ catch (error) {
913
+ if (definition.optional) {
914
+ await appendDynamicEntry(state, 'agent_lifecycle', {
915
+ phase: 'mcp_connection_failed',
916
+ connection: definition.name,
917
+ optional: true,
918
+ error: 'The optional MCP connection was unavailable and its tools were omitted.',
919
+ });
920
+ return undefined;
921
+ }
922
+ throw error;
923
+ }
924
+ }))).filter((value) => value !== undefined);
925
+ }
926
+ function resolveSubagent(definition) {
927
+ const state = { snapshot: new Map(), options: {}, active: undefined, queue: Promise.resolve() };
928
+ const frame = createFrame('subagent', state);
929
+ if (currentFrame)
930
+ throw new Error('[fabric-harness] Re-entrant subagent render is not supported.');
931
+ currentFrame = frame;
932
+ let instruction;
933
+ try {
934
+ instruction = definition.agent();
935
+ }
936
+ finally {
937
+ currentFrame = undefined;
938
+ }
939
+ const content = [instruction, ...frame.instructions].filter(Boolean).join('\n\n');
940
+ const subagents = frame.subagents.map(resolveSubagent);
941
+ return {
942
+ name: definition.name,
943
+ description: definition.description,
944
+ content,
945
+ ...(definition.model ? { model: definition.model } : {}),
946
+ ...(definition.thinkingLevel ? { thinkingLevel: definition.thinkingLevel } : {}),
947
+ ...(frame.tools.length > 0 ? { tools: frame.tools } : {}),
948
+ ...(frame.skills.length > 0 ? { skills: frame.skills } : {}),
949
+ ...(subagents.length > 0 ? { subagents } : {}),
950
+ metadata: {
951
+ dynamicSubagent: true,
952
+ ...(frame.tools.length > 0 ? { tools: frame.tools.map((tool) => tool.name) } : {}),
953
+ ...(frame.skills.length > 0 ? { skills: frame.skills.map((skill) => skill.name) } : {}),
954
+ },
955
+ };
956
+ }
957
+ function resourceFingerprint(frame) {
958
+ return JSON.stringify({
959
+ model: frame.model,
960
+ sandbox: frame.sandbox !== undefined,
961
+ tools: frame.tools.map((tool) => [tool.name, tool.description, tool.inputSchema]),
962
+ skills: frame.skills.map((skill) => [skill.name, skill.description]),
963
+ subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
964
+ mcp: frame.mcpConnections.map((connection) => [
965
+ connection.name,
966
+ connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
967
+ ]),
968
+ });
969
+ }
970
+ function isPersistentConfig(value) {
971
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
972
+ }
973
+ function assertUniqueNames(names, kind) {
974
+ const seen = new Set();
975
+ for (const name of names) {
976
+ if (seen.has(name))
977
+ throw new Error(`[fabric-harness] Duplicate ${kind} name: ${name}`);
978
+ seen.add(name);
979
+ }
980
+ }
981
+ 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.');
984
+ }
985
+ if (!definition.connect && !(definition.url instanceof URL) && (typeof definition.url !== 'string' || !URL.canParse(definition.url))) {
986
+ throw new Error(`[fabric-harness] MCP connection "${definition.name}" requires an absolute URL or connect() factory.`);
987
+ }
988
+ if (typeof definition.auth === 'string') {
989
+ throw new Error(`[fabric-harness] MCP connection "${definition.name}" must use an auth resolver or SecretRef, not a raw secret.`);
990
+ }
991
+ if (definition.url) {
992
+ const parsed = new URL(definition.url);
993
+ const credentialParameter = [...parsed.searchParams.keys()].find((key) => /(token|secret|password|signature|api[-_]?key|auth)/i.test(key));
994
+ if (parsed.username || parsed.password || credentialParameter) {
995
+ throw new Error(`[fabric-harness] MCP connection "${definition.name}" must not put credentials in its URL; use auth instead.`);
996
+ }
997
+ }
998
+ }
999
+ function sanitizeMcpUrl(value) {
1000
+ const url = new URL(value);
1001
+ url.username = '';
1002
+ url.password = '';
1003
+ url.search = '';
1004
+ url.hash = '';
1005
+ return url.toString();
1006
+ }
1007
+ function assertSubagent(definition) {
1008
+ if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
1009
+ throw new Error('[fabric-harness] Subagent requires a non-empty name.');
1010
+ }
1011
+ if (!definition.description?.trim())
1012
+ throw new Error(`[fabric-harness] Subagent "${definition.name}" requires a description.`);
1013
+ if (typeof definition.agent !== 'function')
1014
+ throw new Error(`[fabric-harness] Subagent "${definition.name}" requires an agent function.`);
1015
+ }
1016
+ function parsePersistentTarget(storeSessionId) {
1017
+ const parts = storeSessionId.split(':');
1018
+ return parts.length === 4 && parts[0] === 'agent' && parts[2] && parts[3]
1019
+ ? { instanceId: parts[2], session: parts[3] }
1020
+ : undefined;
1021
+ }
1022
+ function normalizeJson(value, label) {
1023
+ if (value === undefined)
1024
+ throw new Error(`[fabric-harness] ${label} cannot be undefined.`);
1025
+ let encoded;
1026
+ try {
1027
+ encoded = JSON.stringify(value);
1028
+ }
1029
+ catch (error) {
1030
+ throw new Error(`${label} is not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`);
1031
+ }
1032
+ if (encoded === undefined)
1033
+ throw new Error(`[fabric-harness] ${label} is not JSON-serializable.`);
1034
+ return JSON.parse(encoded);
1035
+ }
1036
+ function jsonEqual(left, right) {
1037
+ return JSON.stringify(left) === JSON.stringify(right);
1038
+ }
1039
+ function deepMerge(left, right) {
1040
+ const output = { ...left };
1041
+ for (const [key, value] of Object.entries(right)) {
1042
+ const prior = output[key];
1043
+ output[key] =
1044
+ isJsonObject(prior) && isJsonObject(value) ? deepMerge(prior, value) : value;
1045
+ }
1046
+ return output;
1047
+ }
1048
+ function isJsonObject(value) {
1049
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1050
+ }
1051
+ /** Build an atomic agent-state entry batch for a successful tool outcome. */
1052
+ export function dynamicStateEntriesForTool(input, writes) {
1053
+ let parentId = input.parentId;
1054
+ return writes.map((write, index) => {
1055
+ const entry = {
1056
+ id: `agent-state:${encodeURIComponent(input.toolCallId)}:${index}`,
1057
+ type: 'agent_state',
1058
+ timestamp: input.timestamp,
1059
+ ...(parentId ? { parentId } : {}),
1060
+ ...(input.actor ? { actor: input.actor } : {}),
1061
+ ...(input.tenantId ? { tenantId: input.tenantId } : {}),
1062
+ data: { name: write.name, value: write.value, toolCallId: input.toolCallId },
1063
+ };
1064
+ parentId = entry.id;
1065
+ return entry;
1066
+ });
1067
+ }
1068
+ //# sourceMappingURL=dynamic-agent.js.map