@fabric-harness/sdk 5.2.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 +4 -1
  9. package/dist/dispatch.d.ts.map +1 -1
  10. package/dist/dispatch.js +10 -0
  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 +309 -45
  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
package/dist/session.js CHANGED
@@ -2,6 +2,7 @@ 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
- return validateResult(results, options.result, options.resultExtraction);
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
- // If the loop produced a validated result via finish/give_up tools, return it directly.
263
- if (result.validatedResult !== undefined) {
264
- return result.validatedResult;
265
- }
266
- const resultRetries = options.resultRetries ?? (options.result ? 1 : 0);
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
- catch (error) {
272
- if (attempt >= resultRetries)
273
- throw error;
274
- const message = error instanceof Error ? error.message : String(error);
275
- await this.recordEntry("result_retry", {
276
- error: message,
277
- retryAttempt: attempt + 1,
278
- maxRetries: resultRetries,
279
- });
280
- await this.emit("result_retry", {
281
- error: message,
282
- retryAttempt: attempt + 1,
283
- maxRetries: resultRetries,
284
- });
285
- messages.push({
286
- role: "user",
287
- content: buildResultRetryPrompt(error, options.resultExtraction),
288
- });
289
- result = await runRuntime();
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 = {}) {
@@ -1171,6 +1205,7 @@ export class StubFabricSession {
1171
1205
  tool: call.tool,
1172
1206
  input: call.input,
1173
1207
  ...(tool?.metadata?.effect ? { effect: tool.metadata.effect } : {}),
1208
+ ...(tool?.durable ? { durable: true } : {}),
1174
1209
  toolCallId,
1175
1210
  ...(attribution ? { attribution: attribution } : {}),
1176
1211
  });
@@ -1202,17 +1237,22 @@ export class StubFabricSession {
1202
1237
  toolCallId,
1203
1238
  ...(signal ? { signal } : {}),
1204
1239
  ...(approvalGrant ? { approval: approvalGrant } : {}),
1240
+ ...(tool.durable ? { step: this.createToolStep(toolCallId) } : {}),
1241
+ log: this.createToolProgressLogger(call.tool, toolCallId),
1242
+ harness: { sandbox },
1205
1243
  }));
1206
- const output = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
1244
+ const rawOutput = await approvedSandboxCalls.reduceRight((next, approvedCall) => () => runWithSandboxPolicyApproval(sandbox, approvedCall, next), execute)();
1245
+ const dynamicOutput = unwrapDynamicToolResult(rawOutput);
1246
+ const output = dynamicOutput.output;
1207
1247
  const durationMs = Date.now() - startedAt;
1208
1248
  results.push({ tool: call.tool, input, output, ...(call.id ? { id: call.id } : {}) });
1209
- await this.recordEntry("tool_result", {
1249
+ await this.recordToolResult({
1210
1250
  tool: call.tool,
1211
1251
  output: output,
1212
1252
  durationMs,
1213
1253
  toolCallId,
1214
1254
  ...(attribution ? { attribution: attribution } : {}),
1215
- });
1255
+ }, dynamicOutput.stateWrites);
1216
1256
  await this.emit("tool_end", {
1217
1257
  tool: call.tool,
1218
1258
  durationMs,
@@ -1558,17 +1598,63 @@ export class StubFabricSession {
1558
1598
  *
1559
1599
  * A crash/abort between recording a `tool_call` and its outcome leaves an
1560
1600
  * assistant tool_use with no tool_result, which providers reject on the
1561
- * next turn. For each trailing dangling call this appends a synthetic
1562
- * `tool_result` marked interrupted (never re-executes the tool — the real
1563
- * outcome is unknown), settles trailing unfinished `task_start`s, and
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
1564
1605
  * appends one advisory `signal` entry so the model knows the previous turn
1565
1606
  * was cut short. Idempotent: a repaired window has no dangling calls.
1566
1607
  */
1567
- async repairDanglingToolCalls() {
1608
+ async repairDanglingToolCalls(tools, sandbox, signal) {
1568
1609
  for (let attempt = 0; attempt < 8; attempt += 1) {
1569
- const data = await this.history();
1570
- const path = SessionHistory.fromData(data).getActivePath();
1571
- const dangling = findTrailingDanglingToolCalls(path);
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);
1572
1658
  const unfinishedTasks = findTrailingUnfinishedTasks(path);
1573
1659
  if (dangling.length === 0 && unfinishedTasks.length === 0)
1574
1660
  return;
@@ -1669,6 +1755,167 @@ export class StubFabricSession {
1669
1755
  await this.store.appendEntry?.(this.id, entry);
1670
1756
  return entry;
1671
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
+ }
1672
1919
  async emit(type, data) {
1673
1920
  await this.ensureData();
1674
1921
  const event = {
@@ -1905,6 +2152,23 @@ function isAbortError(error) {
1905
2152
  return (error instanceof Error &&
1906
2153
  (error.name === "AbortError" || /aborted|cancelled|canceled/i.test(error.message)));
1907
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
+ }
1908
2172
  function wrapWithPolicy(env, policy, bypass) {
1909
2173
  if (bypass === true)
1910
2174
  return env;