@fabric-harness/sdk 5.1.0 → 5.3.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 (43) hide show
  1. package/README.md +24 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +3 -0
  4. package/dist/agent.js.map +1 -1
  5. package/dist/conversation-ui.d.ts.map +1 -1
  6. package/dist/conversation-ui.js +68 -3
  7. package/dist/conversation-ui.js.map +1 -1
  8. package/dist/dispatch.d.ts +15 -3
  9. package/dist/dispatch.d.ts.map +1 -1
  10. package/dist/dispatch.js +35 -17
  11. package/dist/dispatch.js.map +1 -1
  12. package/dist/dynamic-agent.d.ts +132 -0
  13. package/dist/dynamic-agent.d.ts.map +1 -0
  14. package/dist/dynamic-agent.js +773 -0
  15. package/dist/dynamic-agent.js.map +1 -0
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/persistent-agent.d.ts +7 -2
  21. package/dist/persistent-agent.d.ts.map +1 -1
  22. package/dist/persistent-agent.js +13 -2
  23. package/dist/persistent-agent.js.map +1 -1
  24. package/dist/session.d.ts +8 -3
  25. package/dist/session.d.ts.map +1 -1
  26. package/dist/session.js +321 -54
  27. package/dist/session.js.map +1 -1
  28. package/dist/strict.d.ts +3 -1
  29. package/dist/strict.d.ts.map +1 -1
  30. package/dist/strict.js +1 -0
  31. package/dist/strict.js.map +1 -1
  32. package/dist/submission-store.d.ts +4 -1
  33. package/dist/submission-store.d.ts.map +1 -1
  34. package/dist/submission-store.js +2 -0
  35. package/dist/submission-store.js.map +1 -1
  36. package/dist/tools.d.ts +58 -0
  37. package/dist/tools.d.ts.map +1 -1
  38. package/dist/tools.js +36 -0
  39. package/dist/tools.js.map +1 -1
  40. package/dist/types.d.ts +5 -1
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/types.js.map +1 -1
  43. package/package.json +1 -1
@@ -0,0 +1,773 @@
1
+ import { dispatch } from './dispatch.js';
2
+ import { normalizeDeliveredMessage } from './delivered-message.js';
3
+ import { SessionHistory } from './history.js';
4
+ import { connectMcpServer } from './mcp.js';
5
+ import { defineTool } from './tools.js';
6
+ import { currentSubmissionContext } from './submission-context.js';
7
+ let currentFrame;
8
+ const dynamicToolResultSymbol = Symbol.for('fabric-harness.dynamic-tool-result');
9
+ export function unwrapDynamicToolResult(value) {
10
+ if (typeof value === 'object' &&
11
+ value !== null &&
12
+ value[dynamicToolResultSymbol] === true) {
13
+ const result = value;
14
+ return { output: result.output, stateWrites: result.stateWrites };
15
+ }
16
+ return { output: value, stateWrites: [] };
17
+ }
18
+ function requireFrame(hook) {
19
+ if (!currentFrame) {
20
+ 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.`);
21
+ }
22
+ currentFrame.usedHooks = true;
23
+ return currentFrame;
24
+ }
25
+ function rejectSubagent(frame, hook) {
26
+ if (frame.kind === 'subagent') {
27
+ throw new Error(`[fabric-harness] ${hook}() is not available while rendering a subagent.`);
28
+ }
29
+ }
30
+ export function isDynamicAgentRendering() {
31
+ return currentFrame !== undefined;
32
+ }
33
+ export async function renderDynamicAgent(render, props, options = {}) {
34
+ const resolvedOptions = await resolveInitialData(options);
35
+ const snapshot = await loadStateSnapshot(resolvedOptions.store, resolvedOptions.storeSessionId);
36
+ const state = { snapshot, options: resolvedOptions, active: undefined, queue: Promise.resolve() };
37
+ const frame = createFrame('agent', state);
38
+ if (currentFrame)
39
+ throw new Error('[fabric-harness] Re-entrant dynamic-agent render is not supported.');
40
+ currentFrame = frame;
41
+ let rendered;
42
+ try {
43
+ rendered = render(props);
44
+ }
45
+ finally {
46
+ currentFrame = undefined;
47
+ }
48
+ // Hooks are deliberately synchronous. An async legacy initializer remains
49
+ // supported, but hook calls made after its first await fail outside-render.
50
+ const result = await rendered;
51
+ const base = isPersistentConfig(result) ? result : {};
52
+ const returnedInstruction = typeof result === 'string' ? result : undefined;
53
+ const instructions = [base.instructions, returnedInstruction, ...frame.instructions]
54
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
55
+ .join('\n\n');
56
+ await persistRenderStructure(frame, state);
57
+ const connections = await connectDeclaredMcp(frame.mcpConnections);
58
+ const mcpTools = connections.flatMap((connection) => connection.tools);
59
+ const hookTools = frame.tools.map((tool) => wrapDynamicTool(tool, state));
60
+ const roles = frame.subagents.map(resolveSubagent);
61
+ const tools = [...(base.tools ?? []), ...hookTools, ...mcpTools];
62
+ assertUniqueNames(tools.map((tool) => tool.name), 'tool');
63
+ const skills = [...(base.skills ?? []), ...frame.skills];
64
+ assertUniqueNames(skills.map((skill) => skill.name), 'skill');
65
+ const subagents = [...(base.subagents ?? []), ...roles];
66
+ assertUniqueNames(subagents.map((role) => role.name), 'subagent');
67
+ const runtime = createDynamicRuntime(frame, state, connections);
68
+ return {
69
+ ...base,
70
+ ...(frame.model !== undefined ? { model: frame.model } : {}),
71
+ ...(frame.thinkingLevel !== undefined ? { thinkingLevel: frame.thinkingLevel } : {}),
72
+ ...(frame.compaction !== undefined
73
+ ? { compaction: frame.compaction === false ? { enabled: false } : frame.compaction }
74
+ : {}),
75
+ ...(frame.sandbox !== undefined ? { sandbox: frame.sandbox } : {}),
76
+ ...(frame.cwd !== undefined ? { cwd: frame.cwd } : {}),
77
+ ...(instructions ? { instructions } : {}),
78
+ ...(tools.length > 0 ? { tools } : {}),
79
+ ...(skills.length > 0 ? { skills } : {}),
80
+ ...(subagents.length > 0 ? { subagents } : {}),
81
+ dynamic: runtime,
82
+ };
83
+ }
84
+ export function useInstruction(text) {
85
+ const frame = requireFrame('useInstruction');
86
+ if (typeof text !== 'string' || text.trim().length === 0) {
87
+ throw new Error('[fabric-harness] useInstruction() requires a non-empty string.');
88
+ }
89
+ frame.instructions.push(text);
90
+ }
91
+ export function useModel(model, options = {}) {
92
+ const frame = requireFrame('useModel');
93
+ rejectSubagent(frame, 'useModel');
94
+ if (frame.model !== undefined)
95
+ throw new Error('[fabric-harness] useModel() may be called once per render.');
96
+ if (typeof model === 'string' && model.trim().length === 0) {
97
+ throw new Error('[fabric-harness] useModel() requires a non-empty model specifier.');
98
+ }
99
+ frame.model = model;
100
+ if (options.thinkingLevel !== undefined)
101
+ frame.thinkingLevel = options.thinkingLevel;
102
+ if (options.compaction !== undefined)
103
+ frame.compaction = options.compaction;
104
+ }
105
+ export function useSandbox(sandbox, options = {}) {
106
+ const frame = requireFrame('useSandbox');
107
+ rejectSubagent(frame, 'useSandbox');
108
+ if (frame.sandbox !== undefined)
109
+ throw new Error('[fabric-harness] useSandbox() may be called once per render.');
110
+ if (!sandbox)
111
+ throw new Error('[fabric-harness] useSandbox() requires a sandbox backend, factory, or environment.');
112
+ if (options.cwd !== undefined && options.cwd.trim().length === 0) {
113
+ throw new Error('[fabric-harness] useSandbox() options.cwd must be non-empty.');
114
+ }
115
+ frame.sandbox = sandbox;
116
+ if (options.cwd !== undefined)
117
+ frame.cwd = options.cwd;
118
+ }
119
+ export function useSkill(skill) {
120
+ const frame = requireFrame('useSkill');
121
+ if (!skill || typeof skill !== 'object' || !skill.name?.trim()) {
122
+ throw new Error('[fabric-harness] useSkill() requires a named skill.');
123
+ }
124
+ if (frame.skills.some((candidate) => candidate.name === skill.name)) {
125
+ throw new Error(`[fabric-harness] Duplicate skill name in one render: ${skill.name}`);
126
+ }
127
+ frame.skills.push(skill);
128
+ }
129
+ export function useTool(tool) {
130
+ const frame = requireFrame('useTool');
131
+ const normalized = defineTool(tool);
132
+ if (frame.tools.some((candidate) => candidate.name === normalized.name)) {
133
+ throw new Error(`[fabric-harness] Duplicate tool name in one render: ${normalized.name}`);
134
+ }
135
+ frame.tools.push(normalized);
136
+ }
137
+ export function usePersistentState(name, defaultValue, options = {}) {
138
+ const frame = requireFrame('usePersistentState');
139
+ rejectSubagent(frame, 'usePersistentState');
140
+ if (!name.trim())
141
+ throw new Error('[fabric-harness] usePersistentState() requires a non-empty name.');
142
+ if (frame.stateNames.has(name))
143
+ throw new Error(`[fabric-harness] Duplicate persistent state name: ${name}`);
144
+ frame.stateNames.add(name);
145
+ const persisted = frame.state.snapshot.get(name);
146
+ const initial = (persisted === undefined ? defaultValue : persisted);
147
+ const value = options.schema ? options.schema.parse(initial, `$state.${name}`) : initial;
148
+ const setter = (next) => {
149
+ if (isDynamicAgentRendering()) {
150
+ throw new Error(`[fabric-harness] Persistent state "${name}" cannot be written during render.`);
151
+ }
152
+ const collector = frame.state.active;
153
+ if (!collector) {
154
+ throw new Error(`[fabric-harness] Persistent state "${name}" can only be written by a tracked tool or lifecycle callback.`);
155
+ }
156
+ const prior = collector.overlay.has(name)
157
+ ? collector.overlay.get(name)
158
+ : frame.state.snapshot.get(name) ?? normalizeJson(defaultValue, `State "${name}" default`);
159
+ const candidate = typeof next === 'function' ? next(prior) : next;
160
+ const parsed = options.schema ? options.schema.parse(candidate, `$state.${name}`) : candidate;
161
+ const normalized = normalizeJson(parsed, `State "${name}"`);
162
+ if (jsonEqual(prior, normalized))
163
+ return;
164
+ collector.overlay.set(name, normalized);
165
+ collector.writes.push({ name, value: normalized });
166
+ };
167
+ return [value, setter];
168
+ }
169
+ export function useDelivery() {
170
+ const frame = requireFrame('useDelivery');
171
+ if (!frame.state.options.delivery) {
172
+ throw new Error('[fabric-harness] useDelivery() requires a delivered message in the runtime render context.');
173
+ }
174
+ return frame.state.options.delivery;
175
+ }
176
+ export function useInitialData() {
177
+ const frame = requireFrame('useInitialData');
178
+ return frame.kind === 'subagent' ? undefined : frame.state.options.initialData;
179
+ }
180
+ export function useDispatchMessage() {
181
+ const frame = requireFrame('useDispatchMessage');
182
+ rejectSubagent(frame, 'useDispatchMessage');
183
+ const { agentName, storeSessionId } = frame.state.options;
184
+ const instanceId = frame.state.options.storeSessionId
185
+ ? parseInstanceId(frame.state.options.storeSessionId)
186
+ : undefined;
187
+ return async (message) => {
188
+ if (isDynamicAgentRendering())
189
+ throw new Error('[fabric-harness] Dispatch is not allowed during render.');
190
+ if (!agentName || !instanceId || !storeSessionId) {
191
+ throw new Error('[fabric-harness] Self-dispatch requires an addressable persistent-agent runtime.');
192
+ }
193
+ return dispatch({ agent: agentName, id: instanceId, message: normalizeDeliveredMessage(message) });
194
+ };
195
+ }
196
+ export function useDataWriter(name, options = {}) {
197
+ const frame = requireFrame('useDataWriter');
198
+ rejectSubagent(frame, 'useDataWriter');
199
+ if (!name.trim())
200
+ throw new Error('[fabric-harness] useDataWriter() requires a non-empty name.');
201
+ if (frame.dataNames.has(name))
202
+ throw new Error(`[fabric-harness] Duplicate message data name: ${name}`);
203
+ frame.dataNames.add(name);
204
+ return (data) => {
205
+ if (isDynamicAgentRendering())
206
+ throw new Error(`[fabric-harness] Message data "${name}" cannot be written during render.`);
207
+ const collector = frame.state.active;
208
+ if (!collector)
209
+ throw new Error(`[fabric-harness] Message data "${name}" requires an active response callback.`);
210
+ const parsed = options.schema ? options.schema.parse(data, `$data.${name}`) : data;
211
+ const value = normalizeJson(parsed, `Message data "${name}"`);
212
+ collector.pending.push(appendDynamicEntry(frame.state, 'message_data', { name, value }));
213
+ };
214
+ }
215
+ export function useResponseStart(run) {
216
+ const frame = requireFrame('useResponseStart');
217
+ rejectSubagent(frame, 'useResponseStart');
218
+ if (typeof run !== 'function')
219
+ throw new Error('[fabric-harness] useResponseStart() requires a callback.');
220
+ frame.responseStarts.push(run);
221
+ }
222
+ export function useResponseFinish(run) {
223
+ const frame = requireFrame('useResponseFinish');
224
+ rejectSubagent(frame, 'useResponseFinish');
225
+ if (typeof run !== 'function')
226
+ throw new Error('[fabric-harness] useResponseFinish() requires a callback.');
227
+ frame.responseFinishes.push(run);
228
+ }
229
+ export function useAgentStart(run) {
230
+ const frame = requireFrame('useAgentStart');
231
+ rejectSubagent(frame, 'useAgentStart');
232
+ if (typeof run !== 'function')
233
+ throw new Error('[fabric-harness] useAgentStart() requires a callback.');
234
+ frame.agentStarts.push(run);
235
+ }
236
+ export function useAgentFinish(run) {
237
+ const frame = requireFrame('useAgentFinish');
238
+ rejectSubagent(frame, 'useAgentFinish');
239
+ if (typeof run !== 'function')
240
+ throw new Error('[fabric-harness] useAgentFinish() requires a callback.');
241
+ frame.agentFinishes.push(run);
242
+ }
243
+ export function defineMcpConnection(definition) {
244
+ assertMcpConnection(definition);
245
+ return Object.freeze({
246
+ ...definition,
247
+ ...(definition.tools ? { tools: Object.freeze([...definition.tools]) } : {}),
248
+ });
249
+ }
250
+ export function useMcpConnection(definition) {
251
+ const frame = requireFrame('useMcpConnection');
252
+ rejectSubagent(frame, 'useMcpConnection');
253
+ assertMcpConnection(definition);
254
+ if (frame.mcpConnections.some((candidate) => candidate.name === definition.name)) {
255
+ throw new Error(`[fabric-harness] Duplicate MCP connection name: ${definition.name}`);
256
+ }
257
+ frame.mcpConnections.push(definition);
258
+ }
259
+ export function defineSubagent(definition) {
260
+ assertSubagent(definition);
261
+ return Object.freeze({ ...definition });
262
+ }
263
+ export const GeneralSubagent = defineSubagent({
264
+ name: 'fabric-general',
265
+ description: 'General-purpose delegate for independent research and file exploration.',
266
+ agent: () => undefined,
267
+ });
268
+ export function useSubagent(definition) {
269
+ const frame = requireFrame('useSubagent');
270
+ assertSubagent(definition);
271
+ if (frame.subagents.some((candidate) => candidate.name === definition.name)) {
272
+ throw new Error(`[fabric-harness] Duplicate subagent name: ${definition.name}`);
273
+ }
274
+ frame.subagents.push(definition);
275
+ }
276
+ function createFrame(kind, state) {
277
+ return {
278
+ kind,
279
+ instructions: [],
280
+ tools: [],
281
+ skills: [],
282
+ subagents: [],
283
+ mcpConnections: [],
284
+ stateNames: new Set(),
285
+ dataNames: new Set(),
286
+ responseStarts: [],
287
+ responseFinishes: [],
288
+ agentStarts: [],
289
+ agentFinishes: [],
290
+ state,
291
+ usedHooks: false,
292
+ };
293
+ }
294
+ function wrapDynamicTool(tool, state) {
295
+ if (!tool.execute)
296
+ return tool;
297
+ return {
298
+ ...tool,
299
+ async execute(input, context) {
300
+ return enqueueEffect(state, async (collector) => {
301
+ const output = await tool.execute?.(input, context);
302
+ await Promise.all(collector.pending);
303
+ return {
304
+ [dynamicToolResultSymbol]: true,
305
+ output,
306
+ stateWrites: collector.writes,
307
+ };
308
+ });
309
+ },
310
+ };
311
+ }
312
+ async function enqueueEffect(state, run) {
313
+ let resolve;
314
+ let reject;
315
+ const result = new Promise((res, rej) => {
316
+ resolve = res;
317
+ reject = rej;
318
+ });
319
+ const prior = state.queue;
320
+ state.queue = prior.then(async () => {
321
+ const collector = { writes: [], overlay: new Map(), pending: [] };
322
+ state.active = collector;
323
+ try {
324
+ resolve(await run(collector));
325
+ }
326
+ catch (error) {
327
+ reject(error);
328
+ }
329
+ finally {
330
+ state.active = undefined;
331
+ }
332
+ });
333
+ await state.queue;
334
+ return result;
335
+ }
336
+ function createDynamicRuntime(frame, state, connections) {
337
+ let metadata = {};
338
+ let closed = false;
339
+ const emptyResponse = { toolCalls: [] };
340
+ const baseContext = (response) => ({
341
+ ...(state.options.delivery ? { delivery: state.options.delivery } : {}),
342
+ metadata,
343
+ response,
344
+ });
345
+ return {
346
+ dataNames: [...frame.dataNames],
347
+ resourceFingerprint: resourceFingerprint(frame),
348
+ async runResponseStart(response = emptyResponse) {
349
+ if (frame.responseStarts.length === 0)
350
+ return metadata;
351
+ metadata = await runMetadataCallbacks(frame.responseStarts, baseContext(response));
352
+ await appendDynamicEntry(state, 'response_metadata', { phase: 'start', metadata });
353
+ return metadata;
354
+ },
355
+ async runAgentStart(input) {
356
+ if (frame.agentStarts.length === 0)
357
+ return;
358
+ await Promise.all(frame.agentStarts.map((run) => enqueueEffect(state, async (collector) => {
359
+ await run({ ...baseContext(emptyResponse), ...input });
360
+ await commitStateWrites(state, collector.writes, 'agent_start');
361
+ await Promise.all(collector.pending);
362
+ })));
363
+ await appendDynamicEntry(state, 'agent_lifecycle', { phase: 'start' });
364
+ },
365
+ async runAgentFinish(response) {
366
+ const appended = [];
367
+ if (frame.agentFinishes.length === 0)
368
+ return appended;
369
+ for (const run of frame.agentFinishes) {
370
+ await enqueueEffect(state, async (collector) => {
371
+ let open = true;
372
+ await run({
373
+ ...baseContext(response),
374
+ append(message) {
375
+ if (!open)
376
+ throw new Error('[fabric-harness] Agent-finish append is closed.');
377
+ appended.push(message);
378
+ },
379
+ });
380
+ open = false;
381
+ await commitStateWrites(state, collector.writes, 'agent_finish');
382
+ await Promise.all(collector.pending);
383
+ });
384
+ }
385
+ return appended;
386
+ },
387
+ async runResponseFinish(response) {
388
+ if (frame.responseFinishes.length === 0)
389
+ return metadata;
390
+ metadata = await runMetadataCallbacks(frame.responseFinishes, baseContext(response), metadata);
391
+ await appendDynamicEntry(state, 'response_metadata', { phase: 'finish', metadata });
392
+ return metadata;
393
+ },
394
+ async close() {
395
+ if (closed)
396
+ return;
397
+ closed = true;
398
+ await Promise.all(connections.map((connection) => connection.close()));
399
+ },
400
+ };
401
+ }
402
+ async function runMetadataCallbacks(callbacks, context, initial = {}) {
403
+ let metadata = { ...initial, ...context.metadata };
404
+ for (const callback of callbacks) {
405
+ const output = callback({ ...context, metadata });
406
+ if (output instanceof Promise) {
407
+ throw new Error('[fabric-harness] Response metadata callbacks must be synchronous.');
408
+ }
409
+ if (output)
410
+ metadata = deepMerge(metadata, output);
411
+ }
412
+ return metadata;
413
+ }
414
+ async function commitStateWrites(state, writes, source) {
415
+ for (const write of writes) {
416
+ await appendDynamicEntry(state, 'agent_state', {
417
+ name: write.name,
418
+ value: write.value,
419
+ source,
420
+ });
421
+ }
422
+ }
423
+ async function appendDynamicEntry(state, type, data) {
424
+ const { store, storeSessionId, actor, tenantId } = state.options;
425
+ if (!store || !storeSessionId || !store.appendEntry) {
426
+ throw new Error(`[fabric-harness] ${type} requires a durable SessionStore.appendEntry() runtime.`);
427
+ }
428
+ const current = await store.load(storeSessionId);
429
+ const submission = currentSubmissionContext();
430
+ await store.appendEntry(storeSessionId, {
431
+ id: `${storeSessionId}-${type}-${Date.now()}-${crypto.randomUUID()}`,
432
+ type,
433
+ timestamp: new Date().toISOString(),
434
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
435
+ ...(actor ? { actor } : {}),
436
+ ...(tenantId ? { tenantId } : {}),
437
+ data: submission
438
+ ? { ...data, submissionId: submission.submissionId, attemptId: submission.attemptId }
439
+ : data,
440
+ });
441
+ }
442
+ async function persistRenderStructure(frame, state) {
443
+ const { store, storeSessionId, actor, tenantId } = state.options;
444
+ if (!store || !storeSessionId)
445
+ return;
446
+ if (!store.appendEntry) {
447
+ throw new Error('[fabric-harness] Dynamic agent structure requires SessionStore.appendEntry().');
448
+ }
449
+ const next = renderStructure(frame);
450
+ let current = await store.load(storeSessionId);
451
+ let path = SessionHistory.fromData(current).getActivePath();
452
+ let priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
453
+ if (!priorEntry && !frame.usedHooks)
454
+ return;
455
+ if (!current) {
456
+ const now = new Date().toISOString();
457
+ await store.save({
458
+ id: storeSessionId,
459
+ createdAt: now,
460
+ updatedAt: now,
461
+ entries: [],
462
+ events: [],
463
+ ...(tenantId ? { tenantId } : {}),
464
+ });
465
+ current = await store.load(storeSessionId);
466
+ path = SessionHistory.fromData(current).getActivePath();
467
+ priorEntry = [...path].reverse().find((entry) => entry.type === 'agent_render_structure');
468
+ }
469
+ const prior = priorEntry?.data?.structure;
470
+ if (prior) {
471
+ const dataDelta = setDelta(prior.dataNames, next.dataNames);
472
+ if (dataDelta) {
473
+ throw new Error(`[fabric-harness] The agent's render changed message-data identity: ${dataDelta}. Declare useDataWriter() names unconditionally on every render.`);
474
+ }
475
+ if (jsonEqual(prior, next))
476
+ return;
477
+ }
478
+ const timestamp = new Date().toISOString();
479
+ const submission = currentSubmissionContext();
480
+ const correlation = submission
481
+ ? { submissionId: submission.submissionId, attemptId: submission.attemptId }
482
+ : {};
483
+ const structureEntry = {
484
+ id: `${storeSessionId}:render:${crypto.randomUUID()}`,
485
+ type: 'agent_render_structure',
486
+ timestamp,
487
+ ...(current?.leafId ? { parentId: current.leafId } : {}),
488
+ ...(actor ? { actor } : {}),
489
+ ...(tenantId ? { tenantId } : {}),
490
+ data: { structure: next, ...correlation },
491
+ };
492
+ const entries = [structureEntry];
493
+ if (prior) {
494
+ entries.push({
495
+ id: `${storeSessionId}:resources:${crypto.randomUUID()}`,
496
+ type: 'signal',
497
+ timestamp,
498
+ parentId: structureEntry.id,
499
+ ...(actor ? { actor } : {}),
500
+ ...(tenantId ? { tenantId } : {}),
501
+ data: {
502
+ signalType: 'resources.changed',
503
+ content: describeStructureChange(prior, next),
504
+ ...correlation,
505
+ },
506
+ });
507
+ }
508
+ if (store.appendEntries) {
509
+ const committed = await store.appendEntries(storeSessionId, entries, {
510
+ expectedLeafId: current?.leafId,
511
+ });
512
+ if (!committed) {
513
+ throw new Error('[fabric-harness] Agent resources changed concurrently; retry the interaction.');
514
+ }
515
+ return;
516
+ }
517
+ for (const entry of entries)
518
+ await store.appendEntry(storeSessionId, entry);
519
+ }
520
+ function renderStructure(frame) {
521
+ return {
522
+ dataNames: [...frame.dataNames].sort(),
523
+ resources: {
524
+ tools: frame.tools.map((tool) => [tool.name, tool.description ?? '', JSON.stringify(tool.inputSchema ?? null)]),
525
+ skills: frame.skills.map((skill) => [skill.name, skill.description ?? '']),
526
+ subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
527
+ mcp: frame.mcpConnections.map((connection) => [connection.name, connection.url ? String(connection.url) : 'custom']),
528
+ },
529
+ sandbox: frame.sandbox !== undefined,
530
+ };
531
+ }
532
+ function describeStructureChange(previous, next) {
533
+ const changes = [];
534
+ for (const kind of ['tools', 'skills', 'subagents', 'mcp']) {
535
+ const before = new Map(previous.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
536
+ const after = new Map(next.resources[kind].map((item) => [item[0], JSON.stringify(item)]));
537
+ const added = [...after.keys()].filter((name) => !before.has(name));
538
+ const removed = [...before.keys()].filter((name) => !after.has(name));
539
+ const updated = [...after.keys()].filter((name) => before.has(name) && before.get(name) !== after.get(name));
540
+ if (added.length)
541
+ changes.push(`added ${kind}: ${added.join(', ')}`);
542
+ if (removed.length)
543
+ changes.push(`removed ${kind}: ${removed.join(', ')}`);
544
+ if (updated.length)
545
+ changes.push(`updated ${kind}: ${updated.join(', ')}`);
546
+ }
547
+ if (previous.sandbox !== next.sandbox) {
548
+ changes.push(next.sandbox ? 'sandbox environment attached' : 'sandbox environment removed');
549
+ }
550
+ return `Your available capabilities changed since the previous response: ${changes.join('; ')}.`;
551
+ }
552
+ function setDelta(previous, next) {
553
+ const before = new Set(previous);
554
+ const after = new Set(next);
555
+ const added = [...after].filter((name) => !before.has(name));
556
+ const removed = [...before].filter((name) => !after.has(name));
557
+ if (!added.length && !removed.length)
558
+ return undefined;
559
+ return [
560
+ ...(added.length ? [`added ${added.join(', ')}`] : []),
561
+ ...(removed.length ? [`removed ${removed.join(', ')}`] : []),
562
+ ].join('; ');
563
+ }
564
+ async function loadStateSnapshot(store, storeSessionId) {
565
+ if (!store || !storeSessionId)
566
+ return new Map();
567
+ const data = await store.load(storeSessionId);
568
+ const active = SessionHistory.fromData(data).getActivePath();
569
+ const snapshot = new Map();
570
+ for (const entry of active) {
571
+ if (entry.type !== 'agent_state')
572
+ continue;
573
+ const name = typeof entry.data?.name === 'string' ? entry.data.name : undefined;
574
+ if (name && entry.data && 'value' in entry.data)
575
+ snapshot.set(name, entry.data.value);
576
+ }
577
+ return snapshot;
578
+ }
579
+ async function resolveInitialData(options) {
580
+ const { store, storeSessionId } = options;
581
+ if (!store || !storeSessionId)
582
+ return options;
583
+ const current = await store.load(storeSessionId);
584
+ const recorded = SessionHistory.fromData(current)
585
+ .getActivePath()
586
+ .find((entry) => entry.type === 'agent_initial_data');
587
+ if (recorded?.data && 'value' in recorded.data) {
588
+ return { ...options, initialData: recorded.data.value };
589
+ }
590
+ if (options.initialData === undefined)
591
+ return options;
592
+ const value = normalizeJson(options.initialData, 'Agent initial data');
593
+ if (!current) {
594
+ const now = new Date().toISOString();
595
+ await store.save({
596
+ id: storeSessionId,
597
+ createdAt: now,
598
+ updatedAt: now,
599
+ entries: [],
600
+ events: [],
601
+ ...(options.tenantId ? { tenantId: options.tenantId } : {}),
602
+ });
603
+ }
604
+ const latest = await store.load(storeSessionId);
605
+ await store.appendEntry?.(storeSessionId, {
606
+ id: `${storeSessionId}:initial-data`,
607
+ type: 'agent_initial_data',
608
+ timestamp: new Date().toISOString(),
609
+ ...(latest?.leafId ? { parentId: latest.leafId } : {}),
610
+ ...(options.tenantId ? { tenantId: options.tenantId } : {}),
611
+ ...(options.actor ? { actor: options.actor } : {}),
612
+ data: { value },
613
+ });
614
+ return { ...options, initialData: value };
615
+ }
616
+ async function connectDeclaredMcp(definitions) {
617
+ return (await Promise.all(definitions.map(async (definition) => {
618
+ try {
619
+ if (definition.connect) {
620
+ const connection = await definition.connect();
621
+ if (!definition.tools)
622
+ return connection;
623
+ const allowed = new Set(definition.tools);
624
+ return {
625
+ ...connection,
626
+ tools: connection.tools.filter((tool) => {
627
+ const remote = tool.metadata?.mcp?.tool;
628
+ return allowed.has(typeof remote === 'string' ? remote : tool.name);
629
+ }),
630
+ };
631
+ }
632
+ const { name, auth, tools, optional: _optional, connect: _connect, url, ...rest } = definition;
633
+ if (!url)
634
+ throw new Error(`MCP connection "${name}" requires a URL or connect() factory.`);
635
+ const fetchWithAuth = auth
636
+ ? async (input, init = {}) => {
637
+ const token = typeof auth === 'function' ? await auth() : auth;
638
+ const headers = new Headers(init.headers);
639
+ if (token)
640
+ headers.set('authorization', `Bearer ${token}`);
641
+ return (rest.fetch ?? fetch)(input, { ...init, headers });
642
+ }
643
+ : rest.fetch;
644
+ return await connectMcpServer(name, {
645
+ ...rest,
646
+ url,
647
+ ...(tools ? { allowTools: tools } : {}),
648
+ ...(fetchWithAuth ? { fetch: fetchWithAuth } : {}),
649
+ });
650
+ }
651
+ catch (error) {
652
+ if (definition.optional)
653
+ return undefined;
654
+ throw error;
655
+ }
656
+ }))).filter((value) => value !== undefined);
657
+ }
658
+ function resolveSubagent(definition) {
659
+ const state = { snapshot: new Map(), options: {}, active: undefined, queue: Promise.resolve() };
660
+ const frame = createFrame('subagent', state);
661
+ if (currentFrame)
662
+ throw new Error('[fabric-harness] Re-entrant subagent render is not supported.');
663
+ currentFrame = frame;
664
+ let instruction;
665
+ try {
666
+ instruction = definition.agent();
667
+ }
668
+ finally {
669
+ currentFrame = undefined;
670
+ }
671
+ const content = [instruction, ...frame.instructions].filter(Boolean).join('\n\n');
672
+ return {
673
+ name: definition.name,
674
+ description: definition.description,
675
+ content,
676
+ ...(definition.model ? { model: definition.model } : {}),
677
+ metadata: {
678
+ dynamicSubagent: true,
679
+ ...(definition.thinkingLevel ? { thinkingLevel: definition.thinkingLevel } : {}),
680
+ ...(frame.tools.length > 0 ? { tools: frame.tools.map((tool) => tool.name) } : {}),
681
+ ...(frame.skills.length > 0 ? { skills: frame.skills.map((skill) => skill.name) } : {}),
682
+ },
683
+ };
684
+ }
685
+ function resourceFingerprint(frame) {
686
+ return JSON.stringify({
687
+ model: frame.model,
688
+ sandbox: frame.sandbox !== undefined,
689
+ tools: frame.tools.map((tool) => [tool.name, tool.description, tool.inputSchema]),
690
+ skills: frame.skills.map((skill) => [skill.name, skill.description]),
691
+ subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
692
+ mcp: frame.mcpConnections.map((connection) => [connection.name, connection.url ? String(connection.url) : 'custom']),
693
+ });
694
+ }
695
+ function isPersistentConfig(value) {
696
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
697
+ }
698
+ function assertUniqueNames(names, kind) {
699
+ const seen = new Set();
700
+ for (const name of names) {
701
+ if (seen.has(name))
702
+ throw new Error(`[fabric-harness] Duplicate ${kind} name: ${name}`);
703
+ seen.add(name);
704
+ }
705
+ }
706
+ function assertMcpConnection(definition) {
707
+ if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
708
+ throw new Error('[fabric-harness] MCP connection requires a non-empty name.');
709
+ }
710
+ if (!definition.connect && !(definition.url instanceof URL) && (typeof definition.url !== 'string' || !URL.canParse(definition.url))) {
711
+ throw new Error(`[fabric-harness] MCP connection "${definition.name}" requires an absolute URL or connect() factory.`);
712
+ }
713
+ }
714
+ function assertSubagent(definition) {
715
+ if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
716
+ throw new Error('[fabric-harness] Subagent requires a non-empty name.');
717
+ }
718
+ if (!definition.description?.trim())
719
+ throw new Error(`[fabric-harness] Subagent "${definition.name}" requires a description.`);
720
+ if (typeof definition.agent !== 'function')
721
+ throw new Error(`[fabric-harness] Subagent "${definition.name}" requires an agent function.`);
722
+ }
723
+ function parseInstanceId(storeSessionId) {
724
+ const parts = storeSessionId.split(':');
725
+ return parts.length === 4 && parts[0] === 'agent' ? parts[2] : undefined;
726
+ }
727
+ function normalizeJson(value, label) {
728
+ if (value === undefined)
729
+ throw new Error(`[fabric-harness] ${label} cannot be undefined.`);
730
+ let encoded;
731
+ try {
732
+ encoded = JSON.stringify(value);
733
+ }
734
+ catch (error) {
735
+ throw new Error(`${label} is not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`);
736
+ }
737
+ if (encoded === undefined)
738
+ throw new Error(`[fabric-harness] ${label} is not JSON-serializable.`);
739
+ return JSON.parse(encoded);
740
+ }
741
+ function jsonEqual(left, right) {
742
+ return JSON.stringify(left) === JSON.stringify(right);
743
+ }
744
+ function deepMerge(left, right) {
745
+ const output = { ...left };
746
+ for (const [key, value] of Object.entries(right)) {
747
+ const prior = output[key];
748
+ output[key] =
749
+ isJsonObject(prior) && isJsonObject(value) ? deepMerge(prior, value) : value;
750
+ }
751
+ return output;
752
+ }
753
+ function isJsonObject(value) {
754
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
755
+ }
756
+ /** Build an atomic agent-state entry batch for a successful tool outcome. */
757
+ export function dynamicStateEntriesForTool(input, writes) {
758
+ let parentId = input.parentId;
759
+ return writes.map((write, index) => {
760
+ const entry = {
761
+ id: `agent-state:${encodeURIComponent(input.toolCallId)}:${index}`,
762
+ type: 'agent_state',
763
+ timestamp: input.timestamp,
764
+ ...(parentId ? { parentId } : {}),
765
+ ...(input.actor ? { actor: input.actor } : {}),
766
+ ...(input.tenantId ? { tenantId: input.tenantId } : {}),
767
+ data: { name: write.name, value: write.value, toolCallId: input.toolCallId },
768
+ };
769
+ parentId = entry.id;
770
+ return entry;
771
+ });
772
+ }
773
+ //# sourceMappingURL=dynamic-agent.js.map