@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.
- package/README.md +24 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +3 -0
- package/dist/agent.js.map +1 -1
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +68 -3
- package/dist/conversation-ui.js.map +1 -1
- package/dist/dispatch.d.ts +15 -3
- package/dist/dispatch.d.ts.map +1 -1
- package/dist/dispatch.js +35 -17
- package/dist/dispatch.js.map +1 -1
- package/dist/dynamic-agent.d.ts +132 -0
- package/dist/dynamic-agent.d.ts.map +1 -0
- package/dist/dynamic-agent.js +773 -0
- package/dist/dynamic-agent.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/persistent-agent.d.ts +7 -2
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +13 -2
- package/dist/persistent-agent.js.map +1 -1
- package/dist/session.d.ts +8 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +321 -54
- package/dist/session.js.map +1 -1
- package/dist/strict.d.ts +3 -1
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +1 -0
- package/dist/strict.js.map +1 -1
- package/dist/submission-store.d.ts +4 -1
- package/dist/submission-store.d.ts.map +1 -1
- package/dist/submission-store.js +2 -0
- package/dist/submission-store.js.map +1 -1
- package/dist/tools.d.ts +58 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +36 -0
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/dist/session.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { CostBudgetTracker } from "./cost-budget.js";
|
|
3
3
|
import { inMemorySessionMemory } from "./session-memory.js";
|
|
4
4
|
import { FabricError } from "./error.js";
|
|
5
|
+
import { dynamicStateEntriesForTool, unwrapDynamicToolResult, } from "./dynamic-agent.js";
|
|
5
6
|
import { approvalGrantFromState, approvalInputDigest, createApprovalGrant } from "./approval.js";
|
|
6
7
|
import { SessionHistory, buildModelMessagesFromHistory, findTrailingDanglingToolCalls, findTrailingUnfinishedTasks, } from "./history.js";
|
|
7
8
|
import { getLogger } from "./logger.js";
|
|
@@ -151,10 +152,11 @@ export class StubFabricSession {
|
|
|
151
152
|
if (promptSubscriber)
|
|
152
153
|
this.eventSubscribers.add(promptSubscriber);
|
|
153
154
|
try {
|
|
154
|
-
await this.repairDanglingToolCalls();
|
|
155
|
-
await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
|
|
156
155
|
const sandbox = createScopedSandboxEnv(await this.sandbox, options.cwd);
|
|
157
156
|
const tools = this.resolveTools(sandbox, options.tools, options.commands);
|
|
157
|
+
await this.repairDanglingToolCalls(tools, sandbox, options.signal);
|
|
158
|
+
const responseStartLeafId = (await this.history()).leafId;
|
|
159
|
+
await this.emit("prompt_start", { text, ...(role ? { role: role.name } : {}) });
|
|
158
160
|
// Submission-correlated prompts are idempotent by submission id: a
|
|
159
161
|
// recovered attempt whose input entry already landed (crash after the
|
|
160
162
|
// canonical write) resumes from history instead of double-applying.
|
|
@@ -177,6 +179,21 @@ export class StubFabricSession {
|
|
|
177
179
|
// marker CAS hangs off this callback; its failure aborts the turn
|
|
178
180
|
// (the attempt lost ownership).
|
|
179
181
|
await options.submission?.onInputApplied?.();
|
|
182
|
+
if (this.options.dynamic) {
|
|
183
|
+
const submissionId = options.submission?.submissionId;
|
|
184
|
+
const dynamicPath = SessionHistory.fromData(await this.history()).getActivePath();
|
|
185
|
+
const belongsToSubmission = (entry) => submissionId === undefined || entry.data?.submissionId === submissionId;
|
|
186
|
+
const responseStarted = dynamicPath.some((entry) => entry.type === "response_metadata" && entry.data?.phase === "start" && belongsToSubmission(entry));
|
|
187
|
+
const agentStarted = dynamicPath.some((entry) => entry.type === "agent_lifecycle" && entry.data?.phase === "start" && belongsToSubmission(entry));
|
|
188
|
+
if (!inputAlreadyApplied || !responseStarted)
|
|
189
|
+
await this.options.dynamic.runResponseStart();
|
|
190
|
+
if (!inputAlreadyApplied || !agentStarted) {
|
|
191
|
+
await this.options.dynamic.runAgentStart({
|
|
192
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
193
|
+
sandbox,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
180
197
|
const sessionData = await this.history();
|
|
181
198
|
let messages = buildModelMessagesFromHistory(sessionData, role);
|
|
182
199
|
if (!messages.some((message) => message.role === "user" && message.content === text))
|
|
@@ -186,7 +203,12 @@ export class StubFabricSession {
|
|
|
186
203
|
const results = await this.executeToolCalls(options.toolCalls, tools, sandbox, options.policy, options.approvalTimeoutMs ?? this.options.approvalTimeoutMs, options.onApproval, undefined, options.signal);
|
|
187
204
|
await this.recordEntry("result", { result: results });
|
|
188
205
|
await this.emit("prompt_end", { text, result: results });
|
|
189
|
-
|
|
206
|
+
const value = await validateResult(results, options.result, options.resultExtraction);
|
|
207
|
+
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
|
|
208
|
+
if (finalized.continued) {
|
|
209
|
+
throw new Error("useAgentFinish().append() cannot continue a prompt that uses PromptOptions.toolCalls; run the normal model loop instead.");
|
|
210
|
+
}
|
|
211
|
+
return finalized.value;
|
|
190
212
|
}
|
|
191
213
|
// Use tool-based result extraction when a validator is provided and the caller
|
|
192
214
|
// has not explicitly opted into delimiter-based extraction.
|
|
@@ -259,45 +281,57 @@ export class StubFabricSession {
|
|
|
259
281
|
messages = buildModelMessagesFromHistory(await this.history(), role);
|
|
260
282
|
result = await runRuntime();
|
|
261
283
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
for (let attempt = 0; attempt <= resultRetries; attempt += 1) {
|
|
268
|
-
try {
|
|
269
|
-
return await validateResult(result.raw, options.result, options.resultExtraction);
|
|
284
|
+
let continuationCount = 0;
|
|
285
|
+
for (;;) {
|
|
286
|
+
let value;
|
|
287
|
+
if (result.validatedResult !== undefined) {
|
|
288
|
+
value = result.validatedResult;
|
|
270
289
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
+
else {
|
|
291
|
+
const resultRetries = options.resultRetries ?? (options.result ? 1 : 0);
|
|
292
|
+
for (let attempt = 0; attempt <= resultRetries; attempt += 1) {
|
|
293
|
+
try {
|
|
294
|
+
value = await validateResult(result.raw, options.result, options.resultExtraction);
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (attempt >= resultRetries)
|
|
299
|
+
throw error;
|
|
300
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
301
|
+
await this.recordEntry("result_retry", {
|
|
302
|
+
error: message,
|
|
303
|
+
retryAttempt: attempt + 1,
|
|
304
|
+
maxRetries: resultRetries,
|
|
305
|
+
});
|
|
306
|
+
await this.emit("result_retry", {
|
|
307
|
+
error: message,
|
|
308
|
+
retryAttempt: attempt + 1,
|
|
309
|
+
maxRetries: resultRetries,
|
|
310
|
+
});
|
|
311
|
+
messages.push({
|
|
312
|
+
role: "user",
|
|
313
|
+
content: buildResultRetryPrompt(error, options.resultExtraction),
|
|
314
|
+
});
|
|
315
|
+
result = await runRuntime();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const finalized = await this.finalizeDynamicResult(value, responseStartLeafId);
|
|
320
|
+
if (!finalized.continued)
|
|
321
|
+
return finalized.value;
|
|
322
|
+
continuationCount += 1;
|
|
323
|
+
if (continuationCount > 8) {
|
|
324
|
+
throw new Error("useAgentFinish() exceeded the maximum of 8 continuation cycles.");
|
|
290
325
|
}
|
|
326
|
+
messages = buildModelMessagesFromHistory(await this.history(), role);
|
|
327
|
+
messages = await this.autoCompactIfNeeded(messages, role, options);
|
|
328
|
+
result = await runRuntime();
|
|
291
329
|
}
|
|
292
|
-
throw new FabricError({
|
|
293
|
-
code: "RESULT_VALIDATION_FAILED",
|
|
294
|
-
message: "Typed result validation failed.",
|
|
295
|
-
retryable: true,
|
|
296
|
-
});
|
|
297
330
|
}
|
|
298
331
|
finally {
|
|
299
332
|
if (promptSubscriber)
|
|
300
333
|
this.eventSubscribers.delete(promptSubscriber);
|
|
334
|
+
await this.options.dynamic?.close();
|
|
301
335
|
}
|
|
302
336
|
}
|
|
303
337
|
async *stream(text, options = {}) {
|
|
@@ -1054,6 +1088,10 @@ export class StubFabricSession {
|
|
|
1054
1088
|
const results = [];
|
|
1055
1089
|
const policy = callPolicy ?? this.options.policy;
|
|
1056
1090
|
for (const call of calls) {
|
|
1091
|
+
// Providers are allowed to omit a call id. Mint one once at the session
|
|
1092
|
+
// boundary so approvals, lineage, history, and tool execution all refer
|
|
1093
|
+
// to the same unique logical operation.
|
|
1094
|
+
const toolCallId = call.id ?? `${this.id}:${call.tool}:${randomUUID()}`;
|
|
1057
1095
|
const approvedSandboxCalls = [];
|
|
1058
1096
|
let approvalGrant;
|
|
1059
1097
|
const tool = tools.get(call.tool);
|
|
@@ -1066,7 +1104,7 @@ export class StubFabricSession {
|
|
|
1066
1104
|
const grant = await this.requestApproval({
|
|
1067
1105
|
kind: "tool",
|
|
1068
1106
|
tool: call.tool,
|
|
1069
|
-
toolCallId
|
|
1107
|
+
toolCallId,
|
|
1070
1108
|
...(executingPrincipal ? { executingPrincipal } : {}),
|
|
1071
1109
|
input: call.input,
|
|
1072
1110
|
reason: decision.reason ?? `Approval required for tool: ${call.tool}`,
|
|
@@ -1115,7 +1153,7 @@ export class StubFabricSession {
|
|
|
1115
1153
|
const grant = await this.requestApproval({
|
|
1116
1154
|
kind: "command",
|
|
1117
1155
|
tool: call.tool,
|
|
1118
|
-
toolCallId
|
|
1156
|
+
toolCallId,
|
|
1119
1157
|
...(executingPrincipal ? { executingPrincipal } : {}),
|
|
1120
1158
|
...(command ? { command } : {}),
|
|
1121
1159
|
input: call.input,
|
|
@@ -1167,7 +1205,8 @@ export class StubFabricSession {
|
|
|
1167
1205
|
tool: call.tool,
|
|
1168
1206
|
input: call.input,
|
|
1169
1207
|
...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
|
|
1170
|
-
...(
|
|
1208
|
+
...(tool?.durable ? { durable: true } : {}),
|
|
1209
|
+
toolCallId,
|
|
1171
1210
|
...(attribution ? { attribution: attribution } : {}),
|
|
1172
1211
|
});
|
|
1173
1212
|
await this.emit("tool_start", {
|
|
@@ -1195,20 +1234,25 @@ export class StubFabricSession {
|
|
|
1195
1234
|
const startedAt = Date.now();
|
|
1196
1235
|
const execute = () => Promise.resolve(tool.execute?.(input, {
|
|
1197
1236
|
sandbox,
|
|
1198
|
-
toolCallId
|
|
1237
|
+
toolCallId,
|
|
1199
1238
|
...(signal ? { signal } : {}),
|
|
1200
1239
|
...(approvalGrant ? { approval: approvalGrant } : {}),
|
|
1240
|
+
...(tool.durable ? { step: this.createToolStep(toolCallId) } : {}),
|
|
1241
|
+
log: this.createToolProgressLogger(call.tool, toolCallId),
|
|
1242
|
+
harness: { sandbox },
|
|
1201
1243
|
}));
|
|
1202
|
-
const
|
|
1244
|
+
const rawOutput = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
|
|
1245
|
+
const dynamicOutput = unwrapDynamicToolResult(rawOutput);
|
|
1246
|
+
const output = dynamicOutput.output;
|
|
1203
1247
|
const durationMs = Date.now() - startedAt;
|
|
1204
1248
|
results.push({ tool: call.tool, input, output, ...(call.id ? { id: call.id } : {}) });
|
|
1205
|
-
await this.
|
|
1249
|
+
await this.recordToolResult({
|
|
1206
1250
|
tool: call.tool,
|
|
1207
1251
|
output: output,
|
|
1208
1252
|
durationMs,
|
|
1209
|
-
|
|
1253
|
+
toolCallId,
|
|
1210
1254
|
...(attribution ? { attribution: attribution } : {}),
|
|
1211
|
-
});
|
|
1255
|
+
}, dynamicOutput.stateWrites);
|
|
1212
1256
|
await this.emit("tool_end", {
|
|
1213
1257
|
tool: call.tool,
|
|
1214
1258
|
durationMs,
|
|
@@ -1517,12 +1561,11 @@ export class StubFabricSession {
|
|
|
1517
1561
|
if (existing) {
|
|
1518
1562
|
// Cross-tenant access guard: a session that already belongs to a
|
|
1519
1563
|
// different tenant should not be silently appended to.
|
|
1520
|
-
if (this.options.tenantId !== undefined &&
|
|
1521
|
-
existing.tenantId !== undefined &&
|
|
1564
|
+
if ((this.options.tenantId !== undefined || existing.tenantId !== undefined) &&
|
|
1522
1565
|
existing.tenantId !== this.options.tenantId) {
|
|
1523
1566
|
throw new FabricError({
|
|
1524
1567
|
code: "POLICY_DENIED",
|
|
1525
|
-
message: `Session ${this.id} belongs to tenant ${existing.tenantId}; refusing to append from tenant ${this.options.tenantId}.`,
|
|
1568
|
+
message: `Session ${this.id} belongs to tenant ${existing.tenantId ?? "unscoped"}; refusing to append from tenant ${this.options.tenantId ?? "unscoped"}.`,
|
|
1526
1569
|
retryable: false,
|
|
1527
1570
|
});
|
|
1528
1571
|
}
|
|
@@ -1555,17 +1598,63 @@ export class StubFabricSession {
|
|
|
1555
1598
|
*
|
|
1556
1599
|
* A crash/abort between recording a `tool_call` and its outcome leaves an
|
|
1557
1600
|
* assistant tool_use with no tool_result, which providers reject on the
|
|
1558
|
-
* next turn.
|
|
1559
|
-
*
|
|
1560
|
-
*
|
|
1601
|
+
* next turn. A call declared durable is re-entered with the same logical
|
|
1602
|
+
* call id, replaying completed `step.do()` checkpoints. Other calls receive
|
|
1603
|
+
* a synthetic interrupted result because their real outcome is unknown.
|
|
1604
|
+
* The repair also settles trailing unfinished `task_start`s and
|
|
1561
1605
|
* appends one advisory `signal` entry so the model knows the previous turn
|
|
1562
1606
|
* was cut short. Idempotent: a repaired window has no dangling calls.
|
|
1563
1607
|
*/
|
|
1564
|
-
async repairDanglingToolCalls() {
|
|
1608
|
+
async repairDanglingToolCalls(tools, sandbox, signal) {
|
|
1565
1609
|
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1610
|
+
let data = await this.history();
|
|
1611
|
+
let path = SessionHistory.fromData(data).getActivePath();
|
|
1612
|
+
let dangling = findTrailingDanglingToolCalls(path);
|
|
1613
|
+
for (const call of dangling) {
|
|
1614
|
+
const toolName = typeof call.data?.tool === "string" ? call.data.tool : undefined;
|
|
1615
|
+
const toolCallId = typeof call.data?.toolCallId === "string" ? call.data.toolCallId : undefined;
|
|
1616
|
+
const tool = toolName ? tools.get(toolName) : undefined;
|
|
1617
|
+
if (call.data?.durable !== true || !tool?.durable || !tool.execute || !toolCallId || !toolName) {
|
|
1618
|
+
continue;
|
|
1619
|
+
}
|
|
1620
|
+
await this.emit("tool_start", { tool: toolName, recovery: true, toolCallId });
|
|
1621
|
+
try {
|
|
1622
|
+
const rawOutput = await tool.execute(call.data?.input, {
|
|
1623
|
+
sandbox,
|
|
1624
|
+
toolCallId,
|
|
1625
|
+
...(signal ? { signal } : {}),
|
|
1626
|
+
step: this.createToolStep(toolCallId),
|
|
1627
|
+
log: this.createToolProgressLogger(toolName, toolCallId),
|
|
1628
|
+
harness: { sandbox },
|
|
1629
|
+
});
|
|
1630
|
+
const dynamicOutput = unwrapDynamicToolResult(rawOutput);
|
|
1631
|
+
await this.recordToolResult({
|
|
1632
|
+
tool: toolName,
|
|
1633
|
+
toolCallId,
|
|
1634
|
+
output: dynamicOutput.output,
|
|
1635
|
+
recovered: true,
|
|
1636
|
+
}, dynamicOutput.stateWrites);
|
|
1637
|
+
await this.emit("tool_end", { tool: toolName, recovery: true, toolCallId });
|
|
1638
|
+
}
|
|
1639
|
+
catch (error) {
|
|
1640
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1641
|
+
await this.recordEntry("error", {
|
|
1642
|
+
tool: toolName,
|
|
1643
|
+
toolCallId,
|
|
1644
|
+
error: message,
|
|
1645
|
+
recovery: true,
|
|
1646
|
+
});
|
|
1647
|
+
await this.emit("tool_end", {
|
|
1648
|
+
tool: toolName,
|
|
1649
|
+
recovery: true,
|
|
1650
|
+
toolCallId,
|
|
1651
|
+
error: message,
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
data = await this.history();
|
|
1656
|
+
path = SessionHistory.fromData(data).getActivePath();
|
|
1657
|
+
dangling = findTrailingDanglingToolCalls(path);
|
|
1569
1658
|
const unfinishedTasks = findTrailingUnfinishedTasks(path);
|
|
1570
1659
|
if (dangling.length === 0 && unfinishedTasks.length === 0)
|
|
1571
1660
|
return;
|
|
@@ -1666,6 +1755,167 @@ export class StubFabricSession {
|
|
|
1666
1755
|
await this.store.appendEntry?.(this.id, entry);
|
|
1667
1756
|
return entry;
|
|
1668
1757
|
}
|
|
1758
|
+
async finalizeDynamicResult(value, responseStartLeafId) {
|
|
1759
|
+
const dynamic = this.options.dynamic;
|
|
1760
|
+
if (!dynamic)
|
|
1761
|
+
return { value, continued: false };
|
|
1762
|
+
const history = SessionHistory.fromData(await this.history());
|
|
1763
|
+
const path = responseStartLeafId
|
|
1764
|
+
? history.getActivePathSince(responseStartLeafId)
|
|
1765
|
+
: history.getActivePath();
|
|
1766
|
+
const results = new Map();
|
|
1767
|
+
for (const entry of path) {
|
|
1768
|
+
if (entry.type !== "tool_result")
|
|
1769
|
+
continue;
|
|
1770
|
+
const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
|
|
1771
|
+
if (id)
|
|
1772
|
+
results.set(id, entry);
|
|
1773
|
+
}
|
|
1774
|
+
const response = {
|
|
1775
|
+
result: value,
|
|
1776
|
+
toolCalls: path.flatMap((entry) => {
|
|
1777
|
+
if (entry.type !== "tool_call")
|
|
1778
|
+
return [];
|
|
1779
|
+
const id = typeof entry.data?.toolCallId === "string" ? entry.data.toolCallId : undefined;
|
|
1780
|
+
const tool = typeof entry.data?.tool === "string" ? entry.data.tool : "unknown";
|
|
1781
|
+
const outcome = id ? results.get(id) : undefined;
|
|
1782
|
+
return [
|
|
1783
|
+
{
|
|
1784
|
+
tool,
|
|
1785
|
+
...(id ? { toolCallId: id } : {}),
|
|
1786
|
+
...(outcome?.data && "output" in outcome.data ? { output: outcome.data.output } : {}),
|
|
1787
|
+
...(outcome?.data?.isError === true
|
|
1788
|
+
? { error: String(outcome.data.output ?? "Tool failed") }
|
|
1789
|
+
: {}),
|
|
1790
|
+
},
|
|
1791
|
+
];
|
|
1792
|
+
}),
|
|
1793
|
+
};
|
|
1794
|
+
const appended = await dynamic.runAgentFinish(response);
|
|
1795
|
+
for (const message of appended) {
|
|
1796
|
+
if (message.kind === "signal") {
|
|
1797
|
+
await this.createSignalEntry({
|
|
1798
|
+
signalType: message.type,
|
|
1799
|
+
content: message.body,
|
|
1800
|
+
...(message.attributes ? { attributes: message.attributes } : {}),
|
|
1801
|
+
...(message.tagName ? { tagName: message.tagName } : {}),
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
else {
|
|
1805
|
+
await this.recordEntry("user_prompt", {
|
|
1806
|
+
text: message.body,
|
|
1807
|
+
purpose: "agent_finish_continuation",
|
|
1808
|
+
});
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
if (appended.length === 0)
|
|
1812
|
+
await dynamic.runResponseFinish(response);
|
|
1813
|
+
return { value, continued: appended.length > 0 };
|
|
1814
|
+
}
|
|
1815
|
+
createToolStep(toolCallId) {
|
|
1816
|
+
const used = new Set();
|
|
1817
|
+
return {
|
|
1818
|
+
do: async (name, run) => {
|
|
1819
|
+
if (!name || typeof name !== "string") {
|
|
1820
|
+
throw new Error("Durable tool step names must be non-empty strings.");
|
|
1821
|
+
}
|
|
1822
|
+
if (used.has(name)) {
|
|
1823
|
+
throw new Error(`Durable tool step name was reused in one call: ${name}`);
|
|
1824
|
+
}
|
|
1825
|
+
used.add(name);
|
|
1826
|
+
const entryId = toolStepEntryId(toolCallId, name);
|
|
1827
|
+
const existing = SessionHistory.fromData(await this.store.load(this.id))
|
|
1828
|
+
.getActivePath()
|
|
1829
|
+
.find((entry) => entry.id === entryId && entry.type === "tool_step");
|
|
1830
|
+
if (existing?.data && "value" in existing.data)
|
|
1831
|
+
return existing.data.value;
|
|
1832
|
+
const value = normalizeDurableValue(await run(), `Durable tool step "${name}"`);
|
|
1833
|
+
await this.ensureData();
|
|
1834
|
+
const current = await this.store.load(this.id);
|
|
1835
|
+
const submission = currentSubmissionContext();
|
|
1836
|
+
const entry = {
|
|
1837
|
+
id: entryId,
|
|
1838
|
+
type: "tool_step",
|
|
1839
|
+
timestamp: new Date().toISOString(),
|
|
1840
|
+
...(current?.leafId ? { parentId: current.leafId } : {}),
|
|
1841
|
+
...(this.options.actor ? { actor: this.options.actor } : {}),
|
|
1842
|
+
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
1843
|
+
data: {
|
|
1844
|
+
toolCallId,
|
|
1845
|
+
name,
|
|
1846
|
+
value,
|
|
1847
|
+
...(submission ? { submissionId: submission.submissionId, attemptId: submission.attemptId } : {}),
|
|
1848
|
+
},
|
|
1849
|
+
};
|
|
1850
|
+
await this.store.appendEntry?.(this.id, entry);
|
|
1851
|
+
return value;
|
|
1852
|
+
},
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
createToolProgressLogger(tool, toolCallId) {
|
|
1856
|
+
const write = (level, message, data) => {
|
|
1857
|
+
void this.recordEntry("metric", {
|
|
1858
|
+
kind: "tool_progress",
|
|
1859
|
+
level,
|
|
1860
|
+
tool,
|
|
1861
|
+
toolCallId,
|
|
1862
|
+
message,
|
|
1863
|
+
...(data ? { data } : {}),
|
|
1864
|
+
});
|
|
1865
|
+
void this.emit("metric", { kind: "tool_progress", level, tool, toolCallId, message });
|
|
1866
|
+
};
|
|
1867
|
+
return {
|
|
1868
|
+
info: (message, data) => write("info", message, data),
|
|
1869
|
+
warn: (message, data) => write("warn", message, data),
|
|
1870
|
+
error: (message, data) => write("error", message, data),
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
async recordToolResult(data, stateWrites) {
|
|
1874
|
+
if (stateWrites.length === 0 || !this.store.appendEntries) {
|
|
1875
|
+
for (const write of stateWrites) {
|
|
1876
|
+
await this.recordEntry("agent_state", {
|
|
1877
|
+
name: write.name,
|
|
1878
|
+
value: write.value,
|
|
1879
|
+
toolCallId: data.toolCallId,
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
await this.recordEntry("tool_result", data);
|
|
1883
|
+
return;
|
|
1884
|
+
}
|
|
1885
|
+
await this.ensureData();
|
|
1886
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
1887
|
+
const current = await this.store.load(this.id);
|
|
1888
|
+
const timestamp = new Date().toISOString();
|
|
1889
|
+
const stateEntries = dynamicStateEntriesForTool({
|
|
1890
|
+
sessionId: this.id,
|
|
1891
|
+
toolCallId: data.toolCallId,
|
|
1892
|
+
...(current?.leafId ? { parentId: current.leafId } : {}),
|
|
1893
|
+
timestamp,
|
|
1894
|
+
...(this.options.actor ? { actor: this.options.actor } : {}),
|
|
1895
|
+
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
1896
|
+
}, stateWrites);
|
|
1897
|
+
const submission = currentSubmissionContext();
|
|
1898
|
+
const parentId = stateEntries.at(-1)?.id ?? current?.leafId;
|
|
1899
|
+
const resultEntry = {
|
|
1900
|
+
id: `${this.id}-entry-${Date.now()}-${randomUUID()}`,
|
|
1901
|
+
type: "tool_result",
|
|
1902
|
+
timestamp,
|
|
1903
|
+
...(parentId ? { parentId } : {}),
|
|
1904
|
+
...(this.options.actor ? { actor: this.options.actor } : {}),
|
|
1905
|
+
...(this.options.tenantId ? { tenantId: this.options.tenantId } : {}),
|
|
1906
|
+
data: {
|
|
1907
|
+
...data,
|
|
1908
|
+
...(submission ? { submissionId: submission.submissionId, attemptId: submission.attemptId } : {}),
|
|
1909
|
+
},
|
|
1910
|
+
};
|
|
1911
|
+
const committed = await this.store.appendEntries(this.id, [...stateEntries, resultEntry], {
|
|
1912
|
+
expectedLeafId: current?.leafId,
|
|
1913
|
+
});
|
|
1914
|
+
if (committed)
|
|
1915
|
+
return;
|
|
1916
|
+
}
|
|
1917
|
+
throw new Error(`Could not atomically commit tool result and dynamic state for ${data.toolCallId}.`);
|
|
1918
|
+
}
|
|
1669
1919
|
async emit(type, data) {
|
|
1670
1920
|
await this.ensureData();
|
|
1671
1921
|
const event = {
|
|
@@ -1902,6 +2152,23 @@ function isAbortError(error) {
|
|
|
1902
2152
|
return (error instanceof Error &&
|
|
1903
2153
|
(error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));
|
|
1904
2154
|
}
|
|
2155
|
+
function toolStepEntryId(toolCallId, name) {
|
|
2156
|
+
return `tool-step:${encodeURIComponent(toolCallId)}:${encodeURIComponent(name)}`;
|
|
2157
|
+
}
|
|
2158
|
+
function normalizeDurableValue(value, label) {
|
|
2159
|
+
if (value === undefined)
|
|
2160
|
+
throw new Error(`${label} cannot be undefined.`);
|
|
2161
|
+
let encoded;
|
|
2162
|
+
try {
|
|
2163
|
+
encoded = JSON.stringify(value);
|
|
2164
|
+
}
|
|
2165
|
+
catch (error) {
|
|
2166
|
+
throw new Error(`${label} is not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`);
|
|
2167
|
+
}
|
|
2168
|
+
if (encoded === undefined)
|
|
2169
|
+
throw new Error(`${label} is not JSON-serializable.`);
|
|
2170
|
+
return JSON.parse(encoded);
|
|
2171
|
+
}
|
|
1905
2172
|
function wrapWithPolicy(env, policy, bypass) {
|
|
1906
2173
|
if (bypass === true)
|
|
1907
2174
|
return env;
|