@fabric-harness/sdk 5.3.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.
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +4 -0
- package/dist/agent.js.map +1 -1
- package/dist/conversation-projection.d.ts +1 -1
- package/dist/conversation-projection.d.ts.map +1 -1
- package/dist/conversation-projection.js +61 -5
- package/dist/conversation-projection.js.map +1 -1
- package/dist/conversation-stream-contract.d.ts.map +1 -1
- package/dist/conversation-stream-contract.js +86 -0
- package/dist/conversation-stream-contract.js.map +1 -1
- package/dist/conversation-stream.d.ts +32 -1
- package/dist/conversation-stream.d.ts.map +1 -1
- package/dist/conversation-stream.js +81 -1
- package/dist/conversation-stream.js.map +1 -1
- package/dist/conversation-ui.d.ts +8 -0
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +20 -8
- package/dist/conversation-ui.js.map +1 -1
- package/dist/dispatch.d.ts +11 -0
- package/dist/dispatch.d.ts.map +1 -1
- package/dist/dispatch.js +4 -0
- package/dist/dispatch.js.map +1 -1
- package/dist/dynamic-agent.d.ts +66 -12
- package/dist/dynamic-agent.d.ts.map +1 -1
- package/dist/dynamic-agent.js +392 -97
- package/dist/dynamic-agent.js.map +1 -1
- package/dist/error.d.ts +3 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/error.js +25 -0
- package/dist/error.js.map +1 -1
- package/dist/events.d.ts +30 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -5
- package/dist/history.js.map +1 -1
- package/dist/in-memory-submission-store.d.ts +5 -0
- package/dist/in-memory-submission-store.d.ts.map +1 -1
- package/dist/in-memory-submission-store.js +70 -2
- package/dist/in-memory-submission-store.js.map +1 -1
- package/dist/index.d.ts +9 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +12 -0
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +67 -2
- package/dist/loop.js.map +1 -1
- package/dist/model.d.ts +6 -0
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +22 -2
- package/dist/model.js.map +1 -1
- package/dist/operational-metrics.d.ts.map +1 -1
- package/dist/operational-metrics.js +4 -2
- package/dist/operational-metrics.js.map +1 -1
- package/dist/persistent-agent.d.ts +39 -2
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +153 -4
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-loop-runtime.d.ts +9 -2
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +109 -39
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/sandbox.d.ts +15 -0
- package/dist/sandbox.d.ts.map +1 -1
- package/dist/sandbox.js +45 -0
- package/dist/sandbox.js.map +1 -1
- package/dist/session.d.ts +4 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +530 -67
- package/dist/session.js.map +1 -1
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +6 -0
- package/dist/store.js.map +1 -1
- package/dist/strict.d.ts +9 -9
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +4 -4
- package/dist/strict.js.map +1 -1
- package/dist/submission-runner.d.ts +9 -2
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +130 -10
- package/dist/submission-runner.js.map +1 -1
- package/dist/submission-state.d.ts +1 -1
- package/dist/submission-state.d.ts.map +1 -1
- package/dist/submission-state.js +13 -6
- package/dist/submission-state.js.map +1 -1
- package/dist/submission-store-contract.d.ts.map +1 -1
- package/dist/submission-store-contract.js +63 -0
- package/dist/submission-store-contract.js.map +1 -1
- package/dist/submission-store.d.ts +26 -1
- package/dist/submission-store.d.ts.map +1 -1
- package/dist/submission-store.js +6 -0
- package/dist/submission-store.js.map +1 -1
- package/dist/submission-telemetry.d.ts +19 -1
- package/dist/submission-telemetry.d.ts.map +1 -1
- package/dist/submission-telemetry.js.map +1 -1
- package/dist/tools.d.ts +14 -3
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +93 -12
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +63 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
package/dist/dynamic-agent.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { dispatch } from './dispatch.js';
|
|
2
|
-
import { normalizeDeliveredMessage } from './delivered-message.js';
|
|
1
|
+
import { dispatch, enqueueDispatch } from './dispatch.js';
|
|
2
|
+
import { deliveredSignalToEntryData, normalizeDeliveredMessage } from './delivered-message.js';
|
|
3
3
|
import { SessionHistory } from './history.js';
|
|
4
4
|
import { connectMcpServer } from './mcp.js';
|
|
5
|
+
import { EmptySandboxEnv } from './sandbox.js';
|
|
5
6
|
import { defineTool } from './tools.js';
|
|
6
7
|
import { currentSubmissionContext } from './submission-context.js';
|
|
7
8
|
let currentFrame;
|
|
@@ -30,7 +31,7 @@ function rejectSubagent(frame, hook) {
|
|
|
30
31
|
export function isDynamicAgentRendering() {
|
|
31
32
|
return currentFrame !== undefined;
|
|
32
33
|
}
|
|
33
|
-
export async function renderDynamicAgent(render, props, options = {}) {
|
|
34
|
+
export async function renderDynamicAgent(render, props, options = {}, staticConfig = {}) {
|
|
34
35
|
const resolvedOptions = await resolveInitialData(options);
|
|
35
36
|
const snapshot = await loadStateSnapshot(resolvedOptions.store, resolvedOptions.storeSessionId);
|
|
36
37
|
const state = { snapshot, options: resolvedOptions, active: undefined, queue: Promise.resolve() };
|
|
@@ -48,13 +49,16 @@ export async function renderDynamicAgent(render, props, options = {}) {
|
|
|
48
49
|
// Hooks are deliberately synchronous. An async legacy initializer remains
|
|
49
50
|
// supported, but hook calls made after its first await fail outside-render.
|
|
50
51
|
const result = await rendered;
|
|
51
|
-
const base =
|
|
52
|
+
const base = {
|
|
53
|
+
...staticConfig,
|
|
54
|
+
...(isPersistentConfig(result) ? result : {}),
|
|
55
|
+
};
|
|
52
56
|
const returnedInstruction = typeof result === 'string' ? result : undefined;
|
|
53
57
|
const instructions = [base.instructions, returnedInstruction, ...frame.instructions]
|
|
54
58
|
.filter((value) => typeof value === 'string' && value.trim().length > 0)
|
|
55
59
|
.join('\n\n');
|
|
56
60
|
await persistRenderStructure(frame, state);
|
|
57
|
-
const connections = await connectDeclaredMcp(frame.mcpConnections);
|
|
61
|
+
const connections = await connectDeclaredMcp(frame.mcpConnections, state);
|
|
58
62
|
const mcpTools = connections.flatMap((connection) => connection.tools);
|
|
59
63
|
const hookTools = frame.tools.map((tool) => wrapDynamicTool(tool, state));
|
|
60
64
|
const roles = frame.subagents.map(resolveSubagent);
|
|
@@ -64,7 +68,10 @@ export async function renderDynamicAgent(render, props, options = {}) {
|
|
|
64
68
|
assertUniqueNames(skills.map((skill) => skill.name), 'skill');
|
|
65
69
|
const subagents = [...(base.subagents ?? []), ...roles];
|
|
66
70
|
assertUniqueNames(subagents.map((role) => role.name), 'subagent');
|
|
67
|
-
const runtime = createDynamicRuntime(frame, state, connections)
|
|
71
|
+
const runtime = createDynamicRuntime(frame, state, connections, (input = {}) => renderDynamicAgent(render, props, {
|
|
72
|
+
...options,
|
|
73
|
+
...(input.delivery !== undefined ? { delivery: input.delivery } : {}),
|
|
74
|
+
}, staticConfig));
|
|
68
75
|
return {
|
|
69
76
|
...base,
|
|
70
77
|
...(frame.model !== undefined ? { model: frame.model } : {}),
|
|
@@ -181,16 +188,34 @@ export function useDispatchMessage() {
|
|
|
181
188
|
const frame = requireFrame('useDispatchMessage');
|
|
182
189
|
rejectSubagent(frame, 'useDispatchMessage');
|
|
183
190
|
const { agentName, storeSessionId } = frame.state.options;
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
: undefined;
|
|
191
|
+
const persistentIdentity = storeSessionId ? parsePersistentTarget(storeSessionId) : undefined;
|
|
192
|
+
const instanceId = persistentIdentity?.instanceId;
|
|
187
193
|
return async (message) => {
|
|
188
194
|
if (isDynamicAgentRendering())
|
|
189
195
|
throw new Error('[fabric-harness] Dispatch is not allowed during render.');
|
|
190
196
|
if (!agentName || !instanceId || !storeSessionId) {
|
|
191
197
|
throw new Error('[fabric-harness] Self-dispatch requires an addressable persistent-agent runtime.');
|
|
192
198
|
}
|
|
193
|
-
|
|
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);
|
|
194
219
|
};
|
|
195
220
|
}
|
|
196
221
|
export function useDataWriter(name, options = {}) {
|
|
@@ -209,7 +234,7 @@ export function useDataWriter(name, options = {}) {
|
|
|
209
234
|
throw new Error(`[fabric-harness] Message data "${name}" requires an active response callback.`);
|
|
210
235
|
const parsed = options.schema ? options.schema.parse(data, `$data.${name}`) : data;
|
|
211
236
|
const value = normalizeJson(parsed, `Message data "${name}"`);
|
|
212
|
-
collector
|
|
237
|
+
enqueueCollectorEntry(collector, () => appendDynamicEntry(frame.state, 'message_data', { name, value }, collector.correlation));
|
|
213
238
|
};
|
|
214
239
|
}
|
|
215
240
|
export function useResponseStart(run) {
|
|
@@ -297,6 +322,7 @@ function wrapDynamicTool(tool, state) {
|
|
|
297
322
|
return {
|
|
298
323
|
...tool,
|
|
299
324
|
async execute(input, context) {
|
|
325
|
+
const correlation = context?.__fabricSubmission;
|
|
300
326
|
return enqueueEffect(state, async (collector) => {
|
|
301
327
|
const output = await tool.execute?.(input, context);
|
|
302
328
|
await Promise.all(collector.pending);
|
|
@@ -305,11 +331,11 @@ function wrapDynamicTool(tool, state) {
|
|
|
305
331
|
output,
|
|
306
332
|
stateWrites: collector.writes,
|
|
307
333
|
};
|
|
308
|
-
});
|
|
334
|
+
}, correlation);
|
|
309
335
|
},
|
|
310
336
|
};
|
|
311
337
|
}
|
|
312
|
-
async function enqueueEffect(state, run) {
|
|
338
|
+
async function enqueueEffect(state, run, correlation) {
|
|
313
339
|
let resolve;
|
|
314
340
|
let reject;
|
|
315
341
|
const result = new Promise((res, rej) => {
|
|
@@ -318,7 +344,12 @@ async function enqueueEffect(state, run) {
|
|
|
318
344
|
});
|
|
319
345
|
const prior = state.queue;
|
|
320
346
|
state.queue = prior.then(async () => {
|
|
321
|
-
const collector = {
|
|
347
|
+
const collector = {
|
|
348
|
+
writes: [],
|
|
349
|
+
overlay: new Map(),
|
|
350
|
+
pending: [],
|
|
351
|
+
...(correlation ? { correlation } : {}),
|
|
352
|
+
};
|
|
322
353
|
state.active = collector;
|
|
323
354
|
try {
|
|
324
355
|
resolve(await run(collector));
|
|
@@ -333,9 +364,11 @@ async function enqueueEffect(state, run) {
|
|
|
333
364
|
await state.queue;
|
|
334
365
|
return result;
|
|
335
366
|
}
|
|
336
|
-
function createDynamicRuntime(frame, state, connections) {
|
|
367
|
+
function createDynamicRuntime(frame, state, connections, refresh) {
|
|
337
368
|
let metadata = {};
|
|
338
369
|
let closed = false;
|
|
370
|
+
let lifecycleSignal = new AbortController().signal;
|
|
371
|
+
let lifecycleSandbox = new EmptySandboxEnv();
|
|
339
372
|
const emptyResponse = { toolCalls: [] };
|
|
340
373
|
const baseContext = (response) => ({
|
|
341
374
|
...(state.options.delivery ? { delivery: state.options.delivery } : {}),
|
|
@@ -345,52 +378,141 @@ function createDynamicRuntime(frame, state, connections) {
|
|
|
345
378
|
return {
|
|
346
379
|
dataNames: [...frame.dataNames],
|
|
347
380
|
resourceFingerprint: resourceFingerprint(frame),
|
|
348
|
-
|
|
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) {
|
|
349
402
|
if (frame.responseStarts.length === 0)
|
|
350
403
|
return metadata;
|
|
351
404
|
metadata = await runMetadataCallbacks(frame.responseStarts, baseContext(response));
|
|
352
|
-
await appendDynamicEntry(state, 'response_metadata', { phase: 'start', metadata });
|
|
405
|
+
await appendDynamicEntry(state, 'response_metadata', { phase: 'start', metadata }, correlation);
|
|
353
406
|
return metadata;
|
|
354
407
|
},
|
|
355
408
|
async runAgentStart(input) {
|
|
409
|
+
lifecycleSignal = input.signal ?? lifecycleSignal;
|
|
410
|
+
lifecycleSandbox = input.sandbox ?? lifecycleSandbox;
|
|
356
411
|
if (frame.agentStarts.length === 0)
|
|
357
|
-
return;
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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
|
+
}
|
|
361
451
|
await Promise.all(collector.pending);
|
|
362
|
-
|
|
363
|
-
|
|
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();
|
|
364
461
|
},
|
|
365
|
-
async runAgentFinish(response) {
|
|
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
|
+
}
|
|
366
473
|
const appended = [];
|
|
367
474
|
if (frame.agentFinishes.length === 0)
|
|
368
475
|
return appended;
|
|
369
|
-
|
|
370
|
-
|
|
476
|
+
await enqueueEffect(state, async (collector) => {
|
|
477
|
+
for (const [index, run] of frame.agentFinishes.entries()) {
|
|
371
478
|
let open = true;
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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);
|
|
385
503
|
return appended;
|
|
386
504
|
},
|
|
387
|
-
async runResponseFinish(response) {
|
|
505
|
+
async runResponseFinish(response, correlation) {
|
|
388
506
|
if (frame.responseFinishes.length === 0)
|
|
389
507
|
return metadata;
|
|
390
508
|
metadata = await runMetadataCallbacks(frame.responseFinishes, baseContext(response), metadata);
|
|
391
|
-
await appendDynamicEntry(state, 'response_metadata', { phase: 'finish', metadata });
|
|
509
|
+
await appendDynamicEntry(state, 'response_metadata', { phase: 'finish', metadata }, correlation);
|
|
392
510
|
return metadata;
|
|
393
511
|
},
|
|
512
|
+
acknowledgeStateWrites(writes) {
|
|
513
|
+
for (const write of writes)
|
|
514
|
+
state.snapshot.set(write.name, write.value);
|
|
515
|
+
},
|
|
394
516
|
async close() {
|
|
395
517
|
if (closed)
|
|
396
518
|
return;
|
|
@@ -411,22 +533,82 @@ async function runMetadataCallbacks(callbacks, context, initial = {}) {
|
|
|
411
533
|
}
|
|
412
534
|
return metadata;
|
|
413
535
|
}
|
|
414
|
-
async function
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
value: write.value,
|
|
419
|
-
source,
|
|
420
|
-
});
|
|
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().');
|
|
421
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));
|
|
422
603
|
}
|
|
423
|
-
async function appendDynamicEntry(state, type, data) {
|
|
604
|
+
async function appendDynamicEntry(state, type, data, correlationOverride) {
|
|
424
605
|
const { store, storeSessionId, actor, tenantId } = state.options;
|
|
425
606
|
if (!store || !storeSessionId || !store.appendEntry) {
|
|
426
607
|
throw new Error(`[fabric-harness] ${type} requires a durable SessionStore.appendEntry() runtime.`);
|
|
427
608
|
}
|
|
428
609
|
const current = await store.load(storeSessionId);
|
|
429
610
|
const submission = currentSubmissionContext();
|
|
611
|
+
const correlation = correlationOverride ?? submission;
|
|
430
612
|
await store.appendEntry(storeSessionId, {
|
|
431
613
|
id: `${storeSessionId}-${type}-${Date.now()}-${crypto.randomUUID()}`,
|
|
432
614
|
type,
|
|
@@ -434,11 +616,48 @@ async function appendDynamicEntry(state, type, data) {
|
|
|
434
616
|
...(current?.leafId ? { parentId: current.leafId } : {}),
|
|
435
617
|
...(actor ? { actor } : {}),
|
|
436
618
|
...(tenantId ? { tenantId } : {}),
|
|
437
|
-
data:
|
|
438
|
-
? {
|
|
619
|
+
data: correlation
|
|
620
|
+
? {
|
|
621
|
+
...data,
|
|
622
|
+
...(correlation.submissionId ? { submissionId: correlation.submissionId } : {}),
|
|
623
|
+
...(correlation.attemptId ? { attemptId: correlation.attemptId } : {}),
|
|
624
|
+
}
|
|
439
625
|
: data,
|
|
440
626
|
});
|
|
441
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
|
+
}
|
|
442
661
|
async function persistRenderStructure(frame, state) {
|
|
443
662
|
const { store, storeSessionId, actor, tenantId } = state.options;
|
|
444
663
|
if (!store || !storeSessionId)
|
|
@@ -524,7 +743,10 @@ function renderStructure(frame) {
|
|
|
524
743
|
tools: frame.tools.map((tool) => [tool.name, tool.description ?? '', JSON.stringify(tool.inputSchema ?? null)]),
|
|
525
744
|
skills: frame.skills.map((skill) => [skill.name, skill.description ?? '']),
|
|
526
745
|
subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
|
|
527
|
-
mcp: frame.mcpConnections.map((connection) => [
|
|
746
|
+
mcp: frame.mcpConnections.map((connection) => [
|
|
747
|
+
connection.name,
|
|
748
|
+
connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
|
|
749
|
+
]),
|
|
528
750
|
},
|
|
529
751
|
sandbox: frame.sandbox !== undefined,
|
|
530
752
|
};
|
|
@@ -577,43 +799,63 @@ async function loadStateSnapshot(store, storeSessionId) {
|
|
|
577
799
|
return snapshot;
|
|
578
800
|
}
|
|
579
801
|
async function resolveInitialData(options) {
|
|
580
|
-
const
|
|
802
|
+
const storeSessionId = options.instanceStoreSessionId ?? options.storeSessionId;
|
|
803
|
+
const { store } = options;
|
|
581
804
|
if (!store || !storeSessionId)
|
|
582
805
|
return options;
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
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 } : {}),
|
|
601
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,
|
|
602
852
|
});
|
|
853
|
+
if (committed)
|
|
854
|
+
return { ...options, initialData: value };
|
|
603
855
|
}
|
|
604
|
-
|
|
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 };
|
|
856
|
+
throw new Error('[fabric-harness] Could not establish immutable initial data after concurrent admission retries.');
|
|
615
857
|
}
|
|
616
|
-
async function connectDeclaredMcp(definitions) {
|
|
858
|
+
async function connectDeclaredMcp(definitions, state) {
|
|
617
859
|
return (await Promise.all(definitions.map(async (definition) => {
|
|
618
860
|
try {
|
|
619
861
|
if (definition.connect) {
|
|
@@ -621,24 +863,43 @@ async function connectDeclaredMcp(definitions) {
|
|
|
621
863
|
if (!definition.tools)
|
|
622
864
|
return connection;
|
|
623
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
|
+
}
|
|
624
875
|
return {
|
|
625
876
|
...connection,
|
|
626
|
-
tools: connection.tools.filter((
|
|
627
|
-
const remote = tool.metadata?.mcp?.tool;
|
|
628
|
-
return allowed.has(typeof remote === 'string' ? remote : tool.name);
|
|
629
|
-
}),
|
|
877
|
+
tools: connection.tools.filter((_tool, index) => allowed.has(remoteNames[index] ?? '')),
|
|
630
878
|
};
|
|
631
879
|
}
|
|
632
|
-
const { name, auth, tools, optional: _optional, connect: _connect, url, ...rest } = definition;
|
|
880
|
+
const { name, auth, resolveSecret, tools, optional: _optional, connect: _connect, url, ...rest } = definition;
|
|
633
881
|
if (!url)
|
|
634
882
|
throw new Error(`MCP connection "${name}" requires a URL or connect() factory.`);
|
|
635
883
|
const fetchWithAuth = auth
|
|
636
884
|
? async (input, init = {}) => {
|
|
637
|
-
const
|
|
638
|
-
|
|
639
|
-
|
|
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);
|
|
640
898
|
headers.set('authorization', `Bearer ${token}`);
|
|
641
|
-
|
|
899
|
+
return (rest.fetch ?? fetch)(input, { ...init, headers });
|
|
900
|
+
};
|
|
901
|
+
const response = await send();
|
|
902
|
+
return response.status === 401 ? send() : response;
|
|
642
903
|
}
|
|
643
904
|
: rest.fetch;
|
|
644
905
|
return await connectMcpServer(name, {
|
|
@@ -649,8 +910,15 @@ async function connectDeclaredMcp(definitions) {
|
|
|
649
910
|
});
|
|
650
911
|
}
|
|
651
912
|
catch (error) {
|
|
652
|
-
if (definition.optional)
|
|
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
|
+
});
|
|
653
920
|
return undefined;
|
|
921
|
+
}
|
|
654
922
|
throw error;
|
|
655
923
|
}
|
|
656
924
|
}))).filter((value) => value !== undefined);
|
|
@@ -669,14 +937,18 @@ function resolveSubagent(definition) {
|
|
|
669
937
|
currentFrame = undefined;
|
|
670
938
|
}
|
|
671
939
|
const content = [instruction, ...frame.instructions].filter(Boolean).join('\n\n');
|
|
940
|
+
const subagents = frame.subagents.map(resolveSubagent);
|
|
672
941
|
return {
|
|
673
942
|
name: definition.name,
|
|
674
943
|
description: definition.description,
|
|
675
944
|
content,
|
|
676
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 } : {}),
|
|
677
950
|
metadata: {
|
|
678
951
|
dynamicSubagent: true,
|
|
679
|
-
...(definition.thinkingLevel ? { thinkingLevel: definition.thinkingLevel } : {}),
|
|
680
952
|
...(frame.tools.length > 0 ? { tools: frame.tools.map((tool) => tool.name) } : {}),
|
|
681
953
|
...(frame.skills.length > 0 ? { skills: frame.skills.map((skill) => skill.name) } : {}),
|
|
682
954
|
},
|
|
@@ -689,7 +961,10 @@ function resourceFingerprint(frame) {
|
|
|
689
961
|
tools: frame.tools.map((tool) => [tool.name, tool.description, tool.inputSchema]),
|
|
690
962
|
skills: frame.skills.map((skill) => [skill.name, skill.description]),
|
|
691
963
|
subagents: frame.subagents.map((subagent) => [subagent.name, subagent.description]),
|
|
692
|
-
mcp: frame.mcpConnections.map((connection) => [
|
|
964
|
+
mcp: frame.mcpConnections.map((connection) => [
|
|
965
|
+
connection.name,
|
|
966
|
+
connection.url ? sanitizeMcpUrl(connection.url) : 'custom',
|
|
967
|
+
]),
|
|
693
968
|
});
|
|
694
969
|
}
|
|
695
970
|
function isPersistentConfig(value) {
|
|
@@ -710,6 +985,24 @@ function assertMcpConnection(definition) {
|
|
|
710
985
|
if (!definition.connect && !(definition.url instanceof URL) && (typeof definition.url !== 'string' || !URL.canParse(definition.url))) {
|
|
711
986
|
throw new Error(`[fabric-harness] MCP connection "${definition.name}" requires an absolute URL or connect() factory.`);
|
|
712
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();
|
|
713
1006
|
}
|
|
714
1007
|
function assertSubagent(definition) {
|
|
715
1008
|
if (!definition || typeof definition !== 'object' || !definition.name?.trim()) {
|
|
@@ -720,9 +1013,11 @@ function assertSubagent(definition) {
|
|
|
720
1013
|
if (typeof definition.agent !== 'function')
|
|
721
1014
|
throw new Error(`[fabric-harness] Subagent "${definition.name}" requires an agent function.`);
|
|
722
1015
|
}
|
|
723
|
-
function
|
|
1016
|
+
function parsePersistentTarget(storeSessionId) {
|
|
724
1017
|
const parts = storeSessionId.split(':');
|
|
725
|
-
return parts.length === 4 && parts[0] === 'agent'
|
|
1018
|
+
return parts.length === 4 && parts[0] === 'agent' && parts[2] && parts[3]
|
|
1019
|
+
? { instanceId: parts[2], session: parts[3] }
|
|
1020
|
+
: undefined;
|
|
726
1021
|
}
|
|
727
1022
|
function normalizeJson(value, label) {
|
|
728
1023
|
if (value === undefined)
|