@theokit/sdk 5.12.1 → 5.13.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 (139) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{agent-IG7BP6GN.js → agent-5DSDDH7K.js} +5 -5
  3. package/dist/{agent-IG7BP6GN.js.map → agent-5DSDDH7K.js.map} +1 -1
  4. package/dist/{agent-CVzDy_Oj.d.ts → agent-DSMuwADp.d.ts} +9 -2
  5. package/dist/{agent-BVKIUP7F.cjs → agent-WOMRT3KX.cjs} +6 -6
  6. package/dist/{agent-BVKIUP7F.cjs.map → agent-WOMRT3KX.cjs.map} +1 -1
  7. package/dist/{agent-Cn0sphpA.d.cts → agent-iW5kPpfT.d.cts} +9 -2
  8. package/dist/{chunk-XJ4C4NFX.js → chunk-2PRGRYEQ.js} +61 -47
  9. package/dist/chunk-2PRGRYEQ.js.map +1 -0
  10. package/dist/{chunk-HN4IKB6X.cjs → chunk-2XWAYCFM.cjs} +15 -13
  11. package/dist/chunk-2XWAYCFM.cjs.map +1 -0
  12. package/dist/{chunk-VVGFZQZC.js → chunk-3LMVJTNJ.js} +9 -5
  13. package/dist/chunk-3LMVJTNJ.js.map +1 -0
  14. package/dist/{chunk-IO4RI5ZJ.cjs → chunk-47EACDOC.cjs} +4 -4
  15. package/dist/{chunk-IO4RI5ZJ.cjs.map → chunk-47EACDOC.cjs.map} +1 -1
  16. package/dist/{chunk-LSWHDOCL.cjs → chunk-4UYHP6NF.cjs} +64 -48
  17. package/dist/chunk-4UYHP6NF.cjs.map +1 -0
  18. package/dist/{chunk-ZLFFDPXC.js → chunk-73IITAF7.js} +36 -14
  19. package/dist/chunk-73IITAF7.js.map +1 -0
  20. package/dist/{chunk-XRPMZ7TO.js → chunk-CYWOJA6B.js} +6 -4
  21. package/dist/chunk-CYWOJA6B.js.map +1 -0
  22. package/dist/{chunk-AQW54OWQ.js → chunk-DFBWYETS.js} +5 -3
  23. package/dist/chunk-DFBWYETS.js.map +1 -0
  24. package/dist/{chunk-YOVZMN4P.cjs → chunk-DVP3YMDA.cjs} +3 -3
  25. package/dist/{chunk-YOVZMN4P.cjs.map → chunk-DVP3YMDA.cjs.map} +1 -1
  26. package/dist/{chunk-EPANMGH7.cjs → chunk-FLDHYF5C.cjs} +11 -2
  27. package/dist/chunk-FLDHYF5C.cjs.map +1 -0
  28. package/dist/{chunk-BJ7BPLQK.js → chunk-JX4LB6XO.js} +124 -13
  29. package/dist/chunk-JX4LB6XO.js.map +1 -0
  30. package/dist/{chunk-Q6WT5535.cjs → chunk-KL7ZUMK3.cjs} +161 -50
  31. package/dist/chunk-KL7ZUMK3.cjs.map +1 -0
  32. package/dist/{chunk-FEAWEBWN.cjs → chunk-PDOXYXWX.cjs} +6 -4
  33. package/dist/chunk-PDOXYXWX.cjs.map +1 -0
  34. package/dist/{chunk-NBNRQN6T.js → chunk-QGDPMM3C.js} +11 -2
  35. package/dist/chunk-QGDPMM3C.js.map +1 -0
  36. package/dist/{chunk-ZWLFHSON.cjs → chunk-R35ZJAYT.cjs} +38 -15
  37. package/dist/chunk-R35ZJAYT.cjs.map +1 -0
  38. package/dist/{chunk-4YD2WI57.cjs → chunk-R427EOZE.cjs} +19 -15
  39. package/dist/chunk-R427EOZE.cjs.map +1 -0
  40. package/dist/{chunk-TLVI2OQK.cjs → chunk-SETHRLQS.cjs} +18 -2
  41. package/dist/chunk-SETHRLQS.cjs.map +1 -0
  42. package/dist/{chunk-BO3PV3OP.js → chunk-TDED5XES.js} +18 -3
  43. package/dist/chunk-TDED5XES.js.map +1 -0
  44. package/dist/{chunk-4GUFNDZR.js → chunk-XOYNB3YN.js} +3 -3
  45. package/dist/{chunk-4GUFNDZR.js.map → chunk-XOYNB3YN.js.map} +1 -1
  46. package/dist/{chunk-NJBJ3CUG.js → chunk-ZTP6ZACR.js} +3 -3
  47. package/dist/{chunk-NJBJ3CUG.js.map → chunk-ZTP6ZACR.js.map} +1 -1
  48. package/dist/{compact-session-3U2JYTVG.js → compact-session-5HMX6KYT.js} +3 -3
  49. package/dist/{compact-session-3U2JYTVG.js.map → compact-session-5HMX6KYT.js.map} +1 -1
  50. package/dist/{compact-session-NM56BREJ.cjs → compact-session-B7P6EU3Z.cjs} +12 -12
  51. package/dist/{compact-session-NM56BREJ.cjs.map → compact-session-B7P6EU3Z.cjs.map} +1 -1
  52. package/dist/{cron-BWDYetbq.d.cts → cron-BvxrLW5J.d.cts} +1 -1
  53. package/dist/{cron-CHn-F0fC.d.ts → cron-DdKzwJqK.d.ts} +1 -1
  54. package/dist/cron.cjs +5 -5
  55. package/dist/cron.d.cts +2 -2
  56. package/dist/cron.d.ts +2 -2
  57. package/dist/cron.js +4 -4
  58. package/dist/eval.cjs +9 -9
  59. package/dist/eval.js +4 -4
  60. package/dist/{executor-HKHT4CWS.cjs → executor-5QL5AXIZ.cjs} +18 -15
  61. package/dist/executor-5QL5AXIZ.cjs.map +1 -0
  62. package/dist/{executor-3D2UDJHW.js → executor-THUXNAFR.js} +6 -3
  63. package/dist/executor-THUXNAFR.js.map +1 -0
  64. package/dist/generate-object-A5F576IT.cjs +20 -0
  65. package/dist/{generate-object-XBWD2PU7.cjs.map → generate-object-A5F576IT.cjs.map} +1 -1
  66. package/dist/{generate-object-S7MNVF2V.js → generate-object-TBDOBBYW.js} +4 -4
  67. package/dist/{generate-object-S7MNVF2V.js.map → generate-object-TBDOBBYW.js.map} +1 -1
  68. package/dist/generate-object.d.ts +14 -1
  69. package/dist/index.cjs +43 -43
  70. package/dist/index.d.cts +30 -4
  71. package/dist/index.d.ts +30 -4
  72. package/dist/index.js +13 -13
  73. package/dist/{inject-session-THABTKJY.js → inject-session-75L3NCNL.js} +3 -3
  74. package/dist/{inject-session-THABTKJY.js.map → inject-session-75L3NCNL.js.map} +1 -1
  75. package/dist/{inject-session-JVTZNQF6.cjs → inject-session-WOH7TPDX.cjs} +4 -4
  76. package/dist/{inject-session-JVTZNQF6.cjs.map → inject-session-WOH7TPDX.cjs.map} +1 -1
  77. package/dist/internal/providers/discovery.d.ts +2 -2
  78. package/dist/internal/providers/trust-gate.d.ts +35 -0
  79. package/dist/internal/runtime/plugin-loader/manifest-entry-import.d.ts +17 -0
  80. package/dist/internal/runtime/plugin-loader/workspace-plugin-trust.d.ts +16 -0
  81. package/dist/internal/structured-output-helpers.d.ts +5 -2
  82. package/dist/sandbox/bwrap.d.cts +10 -8
  83. package/dist/sandbox/bwrap.d.ts +10 -8
  84. package/dist/sandbox/deny-read.d.cts +24 -0
  85. package/dist/sandbox/deny-read.d.ts +24 -0
  86. package/dist/sandbox/index.cjs +114 -35
  87. package/dist/sandbox/index.cjs.map +1 -1
  88. package/dist/sandbox/index.d.cts +2 -1
  89. package/dist/sandbox/index.d.ts +2 -1
  90. package/dist/sandbox/index.js +96 -21
  91. package/dist/sandbox/index.js.map +1 -1
  92. package/dist/sandbox/linux-sandbox.d.cts +16 -1
  93. package/dist/sandbox/linux-sandbox.d.ts +16 -1
  94. package/dist/sandbox/local-sandbox.d.cts +3 -1
  95. package/dist/sandbox/local-sandbox.d.ts +3 -1
  96. package/dist/sandbox/seccomp-delivery.d.cts +3 -0
  97. package/dist/sandbox/seccomp-delivery.d.ts +3 -0
  98. package/dist/sandbox/shell-escape.d.cts +14 -2
  99. package/dist/sandbox/shell-escape.d.ts +14 -2
  100. package/dist/sandbox/types.d.cts +45 -0
  101. package/dist/sandbox/types.d.ts +45 -0
  102. package/dist/stream-object-AS4YYM4B.cjs +20 -0
  103. package/dist/{stream-object-TEEK3CAX.cjs.map → stream-object-AS4YYM4B.cjs.map} +1 -1
  104. package/dist/stream-object-EKM4WGTI.js +7 -0
  105. package/dist/{stream-object-R6SMYV4R.js.map → stream-object-EKM4WGTI.js.map} +1 -1
  106. package/dist/stream-object.d.ts +14 -1
  107. package/dist/subagents-loader.d.cts +1 -1
  108. package/dist/subagents-loader.d.ts +1 -1
  109. package/dist/types/agent.d.ts +8 -1
  110. package/dist/workflow-as-tool.d.ts +39 -5
  111. package/dist/workflow-errors.d.ts +16 -0
  112. package/dist/workflow.cjs +31 -23
  113. package/dist/workflow.d.cts +54 -4
  114. package/dist/workflow.d.ts +54 -4
  115. package/dist/workflow.js +2 -2
  116. package/docs/error-codes.md +16 -13
  117. package/docs/harness-capability-map.md +50 -4
  118. package/package.json +1 -1
  119. package/dist/chunk-4YD2WI57.cjs.map +0 -1
  120. package/dist/chunk-AQW54OWQ.js.map +0 -1
  121. package/dist/chunk-BJ7BPLQK.js.map +0 -1
  122. package/dist/chunk-BO3PV3OP.js.map +0 -1
  123. package/dist/chunk-EPANMGH7.cjs.map +0 -1
  124. package/dist/chunk-FEAWEBWN.cjs.map +0 -1
  125. package/dist/chunk-HN4IKB6X.cjs.map +0 -1
  126. package/dist/chunk-LSWHDOCL.cjs.map +0 -1
  127. package/dist/chunk-NBNRQN6T.js.map +0 -1
  128. package/dist/chunk-Q6WT5535.cjs.map +0 -1
  129. package/dist/chunk-TLVI2OQK.cjs.map +0 -1
  130. package/dist/chunk-VVGFZQZC.js.map +0 -1
  131. package/dist/chunk-XJ4C4NFX.js.map +0 -1
  132. package/dist/chunk-XRPMZ7TO.js.map +0 -1
  133. package/dist/chunk-ZLFFDPXC.js.map +0 -1
  134. package/dist/chunk-ZWLFHSON.cjs.map +0 -1
  135. package/dist/executor-3D2UDJHW.js.map +0 -1
  136. package/dist/executor-HKHT4CWS.cjs.map +0 -1
  137. package/dist/generate-object-XBWD2PU7.cjs +0 -20
  138. package/dist/stream-object-R6SMYV4R.js +0 -7
  139. package/dist/stream-object-TEEK3CAX.cjs +0 -20
@@ -459,8 +459,9 @@ declare function __resetSnapshotStoresForTests(): void;
459
459
  */
460
460
 
461
461
  /**
462
- * Raised by a {@link workflowAsTool} tool when the wrapped workflow run does not
463
- * reach `status: "completed"` (a step failed, the run was cancelled/suspended).
462
+ * Raised by a {@link workflowAsTool} or {@link workflowResumeTool} tool when the
463
+ * run does not reach `status: "completed"` (a step failed, the run was cancelled,
464
+ * or it suspended without `reportSuspended`, which returns a report instead).
464
465
  * The dispatch converts it to a `tool_result(isError)`.
465
466
  *
466
467
  * @public
@@ -487,6 +488,22 @@ interface WorkflowAsToolSpec<T extends ZodType> {
487
488
  description: string;
488
489
  /** Zod schema for the workflow's input (a `Workflow` carries no top-level schema). */
489
490
  inputSchema: T;
491
+ /**
492
+ * When `true`, a run that suspends returns `{"status":"suspended","runId":…,"stepId":…}` instead of
493
+ * raising {@link WorkflowToolError}, so the model can hand the run id to a
494
+ * {@link workflowResumeTool}. The report carries ids only, never the suspended payload; `stepId` is
495
+ * `null` for a run that carries no step result. Default `false`.
496
+ */
497
+ reportSuspended?: boolean;
498
+ }
499
+ /** Spec for {@link workflowResumeTool}. */
500
+ interface WorkflowResumeToolSpec {
501
+ /** Tool name surfaced to the LLM. Same constraints as a `CustomTool.name`. */
502
+ name: string;
503
+ /** Description surfaced to the LLM — when the agent should resume a suspended run. */
504
+ description: string;
505
+ /** Report a run that suspends again instead of raising, as in {@link WorkflowAsToolSpec}. */
506
+ reportSuspended?: boolean;
490
507
  }
491
508
  /**
492
509
  * SE19 — expose a {@link Workflow} as an agent {@link CustomTool}, completing the
@@ -494,7 +511,8 @@ interface WorkflowAsToolSpec<T extends ZodType> {
494
511
  * The handler validates the model's args against `spec.inputSchema`, runs the
495
512
  * workflow, and returns its output (a string as-is, else JSON). A run that does not
496
513
  * reach `status: "completed"` raises a typed {@link WorkflowToolError} (workflow
497
- * step errors do NOT throw — they surface via `run.status === "failed"`).
514
+ * step errors do NOT throw — they surface via `run.status === "failed"`), except a
515
+ * suspended run with `spec.reportSuspended`, which returns the suspended report.
498
516
  *
499
517
  * Accepts any `{ run }`-shaped workflow (structural), so it never imports the
500
518
  * `Workflow` class directly.
@@ -504,6 +522,22 @@ interface WorkflowAsToolSpec<T extends ZodType> {
504
522
  declare function workflowAsTool<T extends ZodType, TOutput = unknown>(workflow: {
505
523
  run: (input: z.infer<T>) => Promise<WorkflowRun<TOutput>>;
506
524
  }, spec: WorkflowAsToolSpec<T>): CustomTool;
525
+ /**
526
+ * B-677 — a {@link CustomTool} that resumes a suspended run of `workflow` by its run id, with an
527
+ * optional payload validated against the suspend step's schema. It returns the run's output like
528
+ * {@link workflowAsTool}; a run that suspends again keeps the same run id and is reported or raised
529
+ * per `spec.reportSuspended`. Snapshot errors (`WorkflowSnapshotNotFoundError` for an unknown or
530
+ * already-resumed id, `WorkflowResumeWorkflowMismatchError` for a run another workflow suspended,
531
+ * `WorkflowResumeStepNotFoundError` when `workflow` lacks the suspended step) and payload validation
532
+ * errors propagate to the dispatch.
533
+ *
534
+ * `workflow` must be the committed instance from `Workflow.create().commit()`. The default snapshot
535
+ * store is in memory and process-local: a host that resumes across processes configures a persistent
536
+ * backend. This tool resumes any run id it is given; deciding who may approve a run is the host's job.
537
+ *
538
+ * @public
539
+ */
540
+ declare function workflowResumeTool(workflow: WorkflowResumeOptions["workflow"], spec: WorkflowResumeToolSpec): CustomTool;
507
541
 
508
542
  /**
509
543
  * The workflow error hierarchy — runtime classes, deliberately NOT in `types/`.
@@ -643,6 +677,22 @@ declare class WorkflowResumeStepNotFoundError extends TheokitAgentError {
643
677
  readonly name = "WorkflowResumeStepNotFoundError";
644
678
  constructor(stepId: string, workflowName: string);
645
679
  }
680
+ /**
681
+ * Thrown by `Workflow.resume()` (and so by a `workflowResumeTool` tool) when the snapshot for the run
682
+ * id was written by a workflow of another name. The snapshot is left in the store, so the workflow
683
+ * that suspended the run can still resume it.
684
+ *
685
+ * Without this check the default store, one process-global memory store, would let workflow B run
686
+ * its own tail on workflow A's accumulated input whenever both declare a step with the suspended id.
687
+ * `name` is a label, not an identity: two workflows that share a name are not told apart here.
688
+ */
689
+ declare class WorkflowResumeWorkflowMismatchError extends TheokitAgentError {
690
+ readonly runId: string;
691
+ readonly snapshotWorkflowName: string;
692
+ readonly workflowName: string;
693
+ readonly name = "WorkflowResumeWorkflowMismatchError";
694
+ constructor(runId: string, snapshotWorkflowName: string, workflowName: string);
695
+ }
646
696
  /**
647
697
  * Aggregate failure from parallel branches.
648
698
  *
@@ -908,4 +958,4 @@ declare function cloneWorkflow<TI = unknown, TO = unknown>(wf: Workflow<TI, TO>,
908
958
  id: string;
909
959
  }): Workflow<TI, TO>;
910
960
 
911
- export { type AgentStep, type BranchStep, type DowhileStep, type FnStep, type ForeachStep, type ParallelStep, type RetryPolicy, type SleepStep, type Step, type StepContext, type StepResult, type SuspendStep, Workflow, WorkflowAlreadyRunningError, type WorkflowAsToolSpec, WorkflowBuilder, WorkflowCompensateNotImplementedError, type WorkflowDescription, WorkflowDuplicateStepIdError, type WorkflowEvent, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, type WorkflowOptions, WorkflowOutputError, WorkflowParallelError, type WorkflowPersistenceOptions, type WorkflowResumeOptions, WorkflowResumeStepNotFoundError, type WorkflowRun, type WorkflowRunOptions, type WorkflowSnapshot, WorkflowSnapshotNotFoundError, WorkflowStateError, type WorkflowStepDescription, type WorkflowStream, WorkflowToolError, __resetSnapshotStoresForTests, agentStep, cloneWorkflow, fn, workflowAsTool, workflowStep };
961
+ export { type AgentStep, type BranchStep, type DowhileStep, type FnStep, type ForeachStep, type ParallelStep, type RetryPolicy, type SleepStep, type Step, type StepContext, type StepResult, type SuspendStep, Workflow, WorkflowAlreadyRunningError, type WorkflowAsToolSpec, WorkflowBuilder, WorkflowCompensateNotImplementedError, type WorkflowDescription, WorkflowDuplicateStepIdError, type WorkflowEvent, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, type WorkflowOptions, WorkflowOutputError, WorkflowParallelError, type WorkflowPersistenceOptions, type WorkflowResumeOptions, WorkflowResumeStepNotFoundError, type WorkflowResumeToolSpec, WorkflowResumeWorkflowMismatchError, type WorkflowRun, type WorkflowRunOptions, type WorkflowSnapshot, WorkflowSnapshotNotFoundError, WorkflowStateError, type WorkflowStepDescription, type WorkflowStream, WorkflowToolError, __resetSnapshotStoresForTests, agentStep, cloneWorkflow, fn, workflowAsTool, workflowResumeTool, workflowStep };
package/dist/workflow.js CHANGED
@@ -1,5 +1,5 @@
1
- export { Workflow, WorkflowBuilder, WorkflowToolError, agentStep, cloneWorkflow, fn, workflowAsTool, workflowStep } from './chunk-ZLFFDPXC.js';
2
- export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests } from './chunk-BO3PV3OP.js';
1
+ export { Workflow, WorkflowBuilder, WorkflowToolError, agentStep, cloneWorkflow, fn, workflowAsTool, workflowResumeTool, workflowStep } from './chunk-73IITAF7.js';
2
+ export { WorkflowAlreadyRunningError, WorkflowCompensateNotImplementedError, WorkflowDuplicateStepIdError, WorkflowInputError, WorkflowMaxIterationsExceededError, WorkflowNestedError, WorkflowNotSerializableError, WorkflowOutputError, WorkflowParallelError, WorkflowResumeStepNotFoundError, WorkflowResumeWorkflowMismatchError, WorkflowSnapshotNotFoundError, WorkflowStateError, __resetSnapshotStoresForTests } from './chunk-TDED5XES.js';
3
3
  import './chunk-HY66GLM6.js';
4
4
  import './chunk-7I5Z3UBJ.js';
5
5
  import './chunk-PKRPV3R7.js';
@@ -6,7 +6,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
6
6
 
7
7
  **Transport codes vs the rest.** `ErrorCode` in `errors.ts` is the small canonical union a provider failure maps onto — the codes marked *transport* below. Everything else is raised by a specific subsystem at a specific place, and a `catch` that only handles the union will meet them anyway.
8
8
 
9
- 251 distinct code(s).
9
+ 254 distinct code(s).
10
10
 
11
11
  | Code | Kind | Raised by | Sites |
12
12
  |---|---|---|---|
@@ -40,7 +40,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
40
40
  | `cloud_custom_tools_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/cloud-agent/cloud-agent.ts:154` +1 |
41
41
  | `cloud_incompatible_function_resolver` | domain | ConfigurationError | `packages/sdk/src/internal/cloud-agent/cloud-tool-parity.ts:43` +2 |
42
42
  | `cloud_incompatible_mcp_stdio_local` | domain | ConfigurationError | `packages/sdk/src/internal/cloud-agent/cloud-tool-parity.ts:74` |
43
- | `cloud_plugin_path_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:159` +1 |
43
+ | `cloud_plugin_path_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:195` +1 |
44
44
  | `cloud_run_http_error` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:156` |
45
45
  | `cloud_run_unknown_status` | domain | NetworkError | `packages/sdk/src/internal/cloud-agent/real-cloud-run.ts:285` +1 |
46
46
  | `cloud_runtime_pre_release` | domain | ConfigurationError | `packages/sdk/src/agent.ts:419` +2 |
@@ -80,7 +80,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
80
80
  | `handoff_target_invalid` | domain | ConfigurationError | `packages/sdk-handoff/src/handoff.ts:116` |
81
81
  | `handoff_target_required` | domain | ConfigurationError | `packages/sdk-handoff/src/handoff.ts:111` |
82
82
  | `hitl_timeout` | domain | HitlTimeoutError | `packages/sdk/src/internal/runtime/tools/hitl-middleware.ts:42` +1 |
83
- | `hook_denied` | domain | ConfigurationError | `packages/sdk/src/internal/local-agent/local-agent.ts:455` |
83
+ | `hook_denied` | domain | ConfigurationError | `packages/sdk/src/internal/local-agent/local-agent.ts:467` |
84
84
  | `hooks_invalid_command` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:415` |
85
85
  | `hooks_json_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:252` +2 |
86
86
  | `hooks_read_error` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/hooks/hooks-source.ts:243` |
@@ -172,12 +172,14 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
172
172
  | `personality_not_found` | domain | ConfigurationError | `packages/sdk/src/internal/personality/switch.ts:60` |
173
173
  | `personality_reserved_name` | domain | ConfigurationError | `packages/sdk/src/internal/personality/registry.ts:110` |
174
174
  | `pipeline_duplicate_provider` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/system-prompt/pipeline.ts:33` |
175
- | `plugin_entry_missing` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:134` |
175
+ | `plugin_entry_import_failed` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/manifest-entry-import.ts:78` |
176
+ | `plugin_entry_missing` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:170` |
177
+ | `plugin_entry_shape` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/manifest-entry-import.ts:85` |
176
178
  | `plugin_frontmatter_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugin-frontmatter.ts:39` |
177
179
  | `plugin_late_register_kind` | domain | ConfigurationError | `packages/sdk/src/internal/plugins/manager.ts:103` |
178
- | `plugin_manifest_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:185` |
179
- | `plugin_manifest_shape` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:191` |
180
- | `plugin_missing_manifest` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:176` +2 |
180
+ | `plugin_manifest_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:221` |
181
+ | `plugin_manifest_shape` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:227` |
182
+ | `plugin_missing_manifest` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/plugin-loader/plugins-manager.ts:212` +2 |
181
183
  | `programmatic_hooks_rejected` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:99` |
182
184
  | `provider_unresolved` | domain | ConfigurationError | `packages/sdk/src/internal/llm/router.ts:107` +2 |
183
185
  | `quota_exceeded` | domain | — | `packages/sdk/src/internal/error-mappers/openai-compatible.ts:148` |
@@ -189,9 +191,9 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
189
191
  | `run_cancelled` | domain | — | `packages/sdk/src/errors.ts:656` |
190
192
  | `run_not_found` | domain | UnknownAgentError | `packages/sdk/src/agent.ts:426` |
191
193
  | `runtime_exclusive` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/validation/validate-agent-options.ts:90` |
192
- | `sandbox_derived_helper_failed` | domain | ConfigurationError | `packages/sdk/src/sandbox/types.ts:185` +1 |
193
- | `sandbox_not_available` | domain | SandboxNotAvailableError | `packages/sdk/src/sandbox/types.ts:92` +1 |
194
- | `sandbox_security` | domain | SandboxSecurityError | `packages/sdk/src/sandbox/types.ts:73` +1 |
194
+ | `sandbox_derived_helper_failed` | domain | ConfigurationError | `packages/sdk/src/sandbox/types.ts:223` +1 |
195
+ | `sandbox_not_available` | domain | SandboxNotAvailableError | `packages/sdk/src/sandbox/types.ts:108` +1 |
196
+ | `sandbox_security` | domain | SandboxSecurityError | `packages/sdk/src/sandbox/types.ts:89` +1 |
195
197
  | `schema_invalid` | domain | ConfigurationError | `packages/sdk/src/internal/runtime/skills/skill-frontmatter.ts:99` +5 |
196
198
  | `server_error` | domain | buildErrorMetadata | `packages/sdk/src/internal/error-mappers/ollama.ts:92` +1 |
197
199
  | `session_busy` | domain | — | `packages/sdk/src/internal/persistence/session-writer.ts:56` +1 |
@@ -246,7 +248,7 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
246
248
  | `work_threw` | domain | — | `packages/sdk/src/internal/task/registry.ts:295` |
247
249
  | `workflow_already_committed` | domain | ConfigurationError | `packages/sdk/src/workflow.ts:269` |
248
250
  | `workflow_already_running` | domain | — | `packages/sdk/src/workflow-errors.ts:141` |
249
- | `workflow_compensate_not_implemented` | domain | — | `packages/sdk/src/workflow-errors.ts:246` +1 |
251
+ | `workflow_compensate_not_implemented` | domain | — | `packages/sdk/src/workflow-errors.ts:270` +1 |
250
252
  | `workflow_duplicate_step_id` | domain | — | `packages/sdk/src/workflow-errors.ts:31` |
251
253
  | `workflow_input_invalid` | domain | — | `packages/sdk/src/workflow-errors.ts:48` |
252
254
  | `workflow_max_iterations_exceeded` | domain | — | `packages/sdk/src/workflow-errors.ts:181` |
@@ -254,11 +256,12 @@ Branch on `code`, never on the message: messages carry context (an id, a path, a
254
256
  | `workflow_not_serializable` | domain | — | `packages/sdk/src/workflow-errors.ts:195` +1 |
255
257
  | `workflow_output_invalid` | domain | — | `packages/sdk/src/workflow-errors.ts:65` |
256
258
  | `workflow_resume_step_not_found` | domain | — | `packages/sdk/src/workflow-errors.ts:210` +1 |
259
+ | `workflow_resume_workflow_mismatch` | domain | — | `packages/sdk/src/workflow-errors.ts:234` +1 |
257
260
  | `workflow_snapshot_not_found` | domain | — | `packages/sdk/src/workflow-errors.ts:159` |
258
261
  | `workflow_state_invalid` | domain | — | `packages/sdk/src/workflow-errors.ts:82` |
259
- | `workflow_tool_failed` | domain | WorkflowToolError | `packages/sdk/src/workflow-as-tool.ts:40` +2 |
262
+ | `workflow_tool_failed` | domain | WorkflowToolError | `packages/sdk/src/workflow-as-tool.ts:41` +2 |
260
263
  | `ws_global_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/theokit-subscribe.ts:184` |
261
264
  | `ws_peer_missing` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/ws-adapter-node.ts:48` |
262
265
  | `ws_transport_mismatch` | domain | SubscriptionError | `packages/sdk/src/subscription/internal/server-integration.ts:351` |
263
- | `zod_not_installed` | domain | ConfigurationError | `packages/sdk/src/internal/structured-output-helpers.ts:33` +1 |
266
+ | `zod_not_installed` | domain | ConfigurationError | `packages/sdk/src/internal/structured-output-helpers.ts:40` +1 |
264
267
 
@@ -4,7 +4,7 @@ Every public symbol the TheoKit workspace publishes, and the exact specifier to
4
4
 
5
5
  A symbol listed under two specifiers is reachable from both, but that does NOT make the two interchangeable: a class emitted separately into a subpath entry is a distinct nominal type from the one in the root bundle, so passing one where the other is expected fails on a private field. When a symbol appears twice, import it and everything it is passed to from the SAME specifier.
6
6
 
7
- 1233 export(s) across 46 entry point(s).
7
+ 1259 export(s) across 50 entry point(s).
8
8
 
9
9
  ## `@theokit/acp`
10
10
 
@@ -771,6 +771,8 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
771
771
  | `createSessionArtifactStore` | function | Create a generic artifact store rooted at `dir`. |
772
772
  | `createShellTool` | function | Build the `shell_exec` tool: run a command through `/bin/sh -c` with `projectRoot` as the working directory. |
773
773
  | `CreateShellToolOptions` | interface | `shell_exec` — built-in tool for coding agents. |
774
+ | `createTextToSpeechTool` | function | Build the `text_to_speech` tool over a caller-supplied provider. |
775
+ | `CreateTextToSpeechToolOptions` | interface | Options for {@link createTextToSpeechTool } . |
774
776
  | `createTodolistTool` | function | Build the `todolist` tool: an in-memory checklist the agent keeps across the turns of one session. |
775
777
  | `createUpdatePlanTool` | function | `update_plan` — built-in tool for coding agents. |
776
778
  | `createViewImageTool` | function | Read an image from the project so the model can look at it. |
@@ -782,7 +784,9 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
782
784
  | `createWriteFileTool` | function | Build the `write_file` tool. |
783
785
  | `CreateWriteFileToolOptions` | interface | Options for {@link createWriteFileTool } . |
784
786
  | `createWriteStdinTool` | function | Write to a live interactive session's stdin and read the output it produces. |
787
+ | `DEFAULT_MAX_AUDIO_BYTES` | const | Default ceiling on the clip written to disk: 10 MiB, by analogy with `DEFAULT_MAX_IMAGE_BYTES`. |
785
788
  | `DEFAULT_MAX_IMAGE_BYTES` | const | Default ceiling: 5 MB on disk. |
789
+ | `DEFAULT_MAX_TEXT_CHARS` | const | Default ceiling on the text sent to the provider, in UTF-16 code units. |
786
790
  | `DEFAULT_TOOL_GUIDANCE` | const | Curated hints for the common cross-tool error codes. |
787
791
  | `denyCatastrophicCommands` | function | A policy that denies catastrophic commands by composing the M3-2 guardrail. |
788
792
  | `EnvContextOptions` | interface | Options for {@link buildEnvContext } . |
@@ -812,6 +816,9 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
812
816
  | `SessionArtifactStore` | interface | A generic, id-keyed, atomic artifact store. |
813
817
  | `SessionArtifactStoreOptions` | interface | Options for {@link createSessionArtifactStore } . |
814
818
  | `SsrfBlockedError` | class | Thrown when a host/redirect resolves to a blocked (private/reserved) address. |
819
+ | `SynthesizedAudio` | interface | What the provider returns: the encoded clip and its mime type. |
820
+ | `TextToSpeechCallback` | type | The speech provider {@link createTextToSpeechTool } calls. |
821
+ | `TextToSpeechResult` | type | The tool's result, before it is serialised to the JSON string the handler returns. |
815
822
  | `TodoItem` | interface | `todolist` — in-session task tracking for multi-step work. |
816
823
  | `todoItemsToPlanNodes` | function | Convert structured todo items (from a `todolist` tool result's `items`, M4-5) into versioned `PlanNode`s for rendering. |
817
824
  | `TodolistTool` | interface | The `todolist` tool object. |
@@ -829,6 +836,40 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
829
836
  | `withShellExitGuidance` | function | Wrap `shell_exec` so a SOFT failure — `{ ok: true, exit_code != 0 }` (the TOOL ran, the COMMAND failed) — gains a `guidance` hint. |
830
837
  | `withToolResultGuidance` | function | Wrap a `CustomTool` so its failed results gain a `guidance` hint from `guidance`. |
831
838
 
839
+ ## `@theokit/sdk-tools/extract-document`
840
+
841
+ | Symbol | Kind | Summary |
842
+ |---|---|---|
843
+ | `createExtractDocumentTool` | function | Extract the text of a `.docx` inside the project root. |
844
+ | `CreateExtractDocumentToolOptions` | interface | Options for {@link createExtractDocumentTool } . |
845
+
846
+ ## `@theokit/sdk-tools/github-link-preview`
847
+
848
+ | Symbol | Kind | Summary |
849
+ |---|---|---|
850
+ | `createGithubLinkPreviewTool` | function | Build the `github_link_preview` tool. |
851
+ | `CreateGithubLinkPreviewToolOptions` | interface | Options for {@link createGithubLinkPreviewTool } ; every one is optional. |
852
+ | `GithubLinkKind` | type | What a previewed GitHub URL points at, taken from its path. |
853
+ | `GithubLinkPreviewResult` | type | The JSON the `github_link_preview` tool returns: a preview, or a typed failure. |
854
+
855
+ ## `@theokit/sdk-tools/read-pdf`
856
+
857
+ | Symbol | Kind | Summary |
858
+ |---|---|---|
859
+ | `createReadPdfTool` | function | Read the text of a PDF inside the project root. |
860
+ | `CreateReadPdfToolOptions` | interface | Options for {@link createReadPdfTool } . |
861
+
862
+ ## `@theokit/sdk-tools/screenshot-logbook`
863
+
864
+ | Symbol | Kind | Summary |
865
+ |---|---|---|
866
+ | `createScreenshotLogbookTool` | function | Build the `screenshot_logbook` tool over a log under `projectRoot`. |
867
+ | `CreateScreenshotLogbookToolOptions` | interface | Options for {@link createScreenshotLogbookTool } . |
868
+ | `DEFAULT_MAX_CAPTION_CHARS` | const | Default ceiling on a caption, in UTF-16 code units. |
869
+ | `DEFAULT_MAX_ENTRIES` | const | Default ceiling on the entries one log holds; it bounds the cost of each rewrite. |
870
+ | `LogbookEntry` | type | One line of the log. |
871
+ | `ScreenshotLogbookResult` | type | The tool's result, before it is serialised to the JSON string the handler returns. |
872
+
832
873
  ## `@theokit/sdk/a2a`
833
874
 
834
875
  | Symbol | Kind | Summary |
@@ -1293,7 +1334,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
1293
1334
  | `buildBwrapArgv` | function | Pure argv builder. |
1294
1335
  | `buildSeccompFilter` | function | Build the cBPF seccomp program as a `Buffer` (each `sock_filter` = 8 bytes). |
1295
1336
  | `BwrapArgvOptions` | interface | Everything {@link buildBwrapArgv } needs besides the {@link SandboxMode } . |
1296
- | `BwrapDetection` | type | Result of {@link detectBwrap } / {@link detectBwrapMemoized } , discriminated on `ok`: `{ ok: true, bin }` carries the absolute path of the validated `bwrap`, `{ ok: false, reason }` a human-readab... |
1337
+ | `BwrapDetection` | type | Result of probing for bubblewrap. |
1297
1338
  | `BwrapProbes` | interface | Injectable probes — each mirrors one Codex availability check. |
1298
1339
  | `createSandboxBackend` | function | Honest factory: bwrap available + mode wants confinement → `LinuxSandbox` (kernel enforcement, running the VALIDATED absolute bin); `danger-full-access` → plain `LocalSandbox` silently (explicit op... |
1299
1340
  | `CreateSandboxBackendOptions` | interface | Options for `createSandboxBackend`, which probes for bubblewrap and returns a {@link LinuxSandbox } when confinement is genuinely available or a `LocalSandbox` when it is not — warning once when th... |
@@ -1317,13 +1358,15 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
1317
1358
  | `restrictedSeccompPath` | function | M57 — the memoized x64-gated seccomp program, written once per process to a temp file. |
1318
1359
  | `SandboxBackend` | class | The execution capability handed to an agent tool, and the extension point for new environments. |
1319
1360
  | `SandboxConfig` | interface | Construction-time settings shared by every {@link SandboxBackend } . |
1320
- | `SandboxMode` | type | Codex's three canonical modes. |
1361
+ | `SandboxMode` | type | Codex's three canonical sandbox modes; lives in this leaf module so bwrap.ts and deny-read.ts need not import each other. |
1362
+ | `SandboxNetworkPolicy` | interface | What a {@link SandboxBackend } states about its outbound network. |
1321
1363
  | `SandboxNotAvailableError` | class | A backend cannot be used at all: its runtime is missing or unusable. |
1322
1364
  | `SandboxPosture` | interface | Durable sandbox posture for the UI — the honest answer to "am I kernel-enforced right now?". |
1323
1365
  | `SandboxProvider` | type | A backend OR a per-request resolver of one — mirrors `FilesystemProvider` / `InteractiveProvider`. |
1324
1366
  | `SandboxSecurityError` | class | A backend refused a command on policy grounds — the environment works, and it said no. |
1325
1367
  | `SeccompOptions` | interface | Input to {@link buildSeccompFilter } — the one axis the generated cBPF program varies on. |
1326
1368
  | `seccompPathForArch` | function | M63 — the restricted-network seccomp program is DETERMINISTIC, so write it ONCE per process and reuse the path across every LinuxSandbox (no per-instance temp accumulation). |
1369
+ | `shellEscapePosix` | function | Quotes `arg` as one word for POSIX `sh`, for a command line you build yourself and hand to `SandboxBackend.execute`. |
1327
1370
  | `wrapCommandForSandbox` | function | M57 — the single source of truth for the sandbox command wrap. |
1328
1371
  | `writableRootsFor` | function | U-6 — the roots a mode may write to, answerable WITHOUT spawning anything. |
1329
1372
 
@@ -1459,6 +1502,9 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
1459
1502
  | `WorkflowPersistenceOptions` | interface | Where suspend snapshots are kept. |
1460
1503
  | `WorkflowResumeOptions` | interface | Arguments for `Workflow.resume()`. |
1461
1504
  | `WorkflowResumeStepNotFoundError` | class | EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. |
1505
+ | `workflowResumeTool` | function | B-677 — a {@link CustomTool } that resumes a suspended run of `workflow` by its run id, with an optional payload validated against the suspend step's schema. |
1506
+ | `WorkflowResumeToolSpec` | interface | Spec for {@link workflowResumeTool } . |
1507
+ | `WorkflowResumeWorkflowMismatchError` | class | Thrown by `Workflow.resume()` (and so by a `workflowResumeTool` tool) when the snapshot for the run id was written by a workflow of another name. |
1462
1508
  | `WorkflowRun` | interface | The terminal record of one run — what `Workflow.run()` resolves to, what `Workflow.resume()` returns, and what the `result` promise of `Workflow.stream()` settles with. |
1463
1509
  | `WorkflowRunOptions` | interface | Per-run options for `Workflow.run()` and `Workflow.stream()`. |
1464
1510
  | `WorkflowSnapshot` | interface | The persisted state of a suspended run: written when a step calls `StepContext.suspend()`, read back by `Workflow.resume()`. |
@@ -1467,5 +1513,5 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
1467
1513
  | `workflowStep` | function | SE30 — use a committed {@link Workflow } as a step inside another workflow. |
1468
1514
  | `WorkflowStepDescription` | interface | theokit#161 — one step of a workflow, as a reflection surface sees it. |
1469
1515
  | `WorkflowStream` | type | SE28 — the async iterator returned by `Workflow.stream()`. |
1470
- | `WorkflowToolError` | class | Raised by a {@link workflowAsTool } tool when the wrapped workflow run does not reach `status: "completed"` (a step failed, the run was cancelled/suspended). |
1516
+ | `WorkflowToolError` | class | Raised by a {@link workflowAsTool } or {@link workflowResumeTool } tool when the run does not reach `status: "completed"` (a step failed, the run was cancelled, or it suspended without `reportSuspe... |
1471
1517
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "5.12.1",
3
+ "version": "5.13.0",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheokit/theokit-sdk#readme",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/generate-object.ts"],"names":["StructuredOutputError","disposeAndDeleteTransient","setupStructuredOutput","makeOutputTool","buildTransientAgentOptions","buildToolPrompt","extractUsage","STRUCTURED_OUTPUT_MESSAGES"],"mappings":";;;;;;AA0FO,IAAM,mBAAA,GAAN,cAAkCA,uCAAA,CAAsB;AAAA,EAC3C,IAAA,GAAO,qBAAA;AAC3B;AAaA,SAAS,cAAA,CAAkC,QAAW,GAAA,EAAuB;AAC3E,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,MAAM,OAAO,GAAA;AACpD,EAAA,MAAM,QAAS,MAAA,CAA+C,KAAA;AAC9D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,OAAO,KAAA,KAAU,UAAU,OAAO,GAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,GAAA;AACf,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,WAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AACtD,IAAA,IAAI,OAAO,WAAA,EAAa,SAAA,KAAc,UAAA,EAAY;AAClD,IAAA,MAAM,MAAA,GAAS,WAAA,CAAY,SAAA,CAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAChD,IAAA,IAAI,MAAA,CAAO,OAAA,EAAS,GAAA,CAAI,GAAG,IAAI,MAAA,CAAO,IAAA;AAAA,EACxC;AACA,EA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1B;AAIA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,YAAA,EAAc;AAC1C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,WAAA;AAAA,QACR,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,IAAI,OAAA,CAAQ,kBAAkB,gBAAA,EAAkB;AAC9C,MAAA,OAAO;AAAA,QACL,MAAA,EAAQ,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,WAAW,CAAA;AAAA,QAClD,GAAA,EAAK,WAAA;AAAA,QACL,KAAA,EAAO,SAAA;AAAA,QACP,YAAA,EAAc;AAAA,OAChB;AAAA,IACF;AACA,IAAA,MAAM,IAAI,mBAAA;AAAA,MACR,cAAA;AAAA,MACAA,4CAAA,CAA2B,WAAA;AAAA,MAC3B;AAAA,KACF;AAAA,EACF,CAAA,SAAE;AAGA,IAAA,MAAMN,2CAAA,CAA0B,KAAA,EAAO,IAAA,CAAK,MAAM,CAAA;AAAA,EACpD;AACF","file":"chunk-4YD2WI57.cjs","sourcesContent":["import type { z as ZodNamespace, ZodType } from \"zod\";\nimport { StructuredOutputError } from \"./errors.js\";\nimport {\n buildToolPrompt,\n buildTransientAgentOptions,\n disposeAndDeleteTransient,\n extractUsage,\n makeOutputTool,\n STRUCTURED_OUTPUT_MESSAGES,\n setupStructuredOutput,\n} from \"./internal/structured-output-helpers.js\";\nimport type { AgentOptions, LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\nimport type { ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Options accepted by {@link Agent.generateObject}. Returns a typed object\n * matching the supplied Zod schema. See ADR D33.\n *\n * @public\n */\nexport interface GenerateObjectOptions<T extends ZodType> {\n /** Zod schema describing the expected object shape. */\n schema: T;\n /** User prompt — the model is asked to fill the schema given this prompt. */\n prompt: string;\n /** Optional system prompt steering the model. */\n systemPrompt?: string;\n /** Model selection. Required (transient agents need a model). SE8 — accepts a\n * bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model: string | ModelSelection;\n /**\n * M21 — optional separate model for the STRUCTURING step. When set, `model` first produces a\n * free-text reasoned answer to the prompt (phase 1), then `structuringModel` extracts the\n * schema-matched object by calling the `output` tool over that answer (phase 2). Lets a large\n * model reason while a cheap fast model does the extraction. Absent ⇒ today's single-model flow.\n */\n structuringModel?: string | ModelSelection;\n /** API key. Falls back to env (THEOKIT_API_KEY etc). */\n apiKey?: string;\n /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */\n local: LocalOptions;\n /**\n * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).\n * The transient agent is REUSED across retries so the registry sees a\n * single entry (EC-3).\n */\n maxRetries?: number;\n /**\n * Optional provider routing forwarded to the transient agent. Required when\n * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is\n * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers\n * provider from the prefix and may fail with `provider_unresolved` even\n * when the right env key is set under a different provider name.\n */\n providers?: ProviderRoutingSettings;\n /**\n * What to do when the model's output fails schema validation after all\n * retries are exhausted (M14):\n * - `'throw'` (default) — throw {@link GenerateObjectError} `parse_failed`.\n * - `'return-raw'` — resolve with the raw, UNVALIDATED input the model sent\n * (`object` may not match the schema; inspect `raw` too).\n * - `'return-partial'` — for object schemas, resolve with only the fields that\n * individually validate (best-effort salvage); non-object schemas fall back\n * to raw.\n */\n errorStrategy?: \"throw\" | \"return-partial\" | \"return-raw\";\n}\n\n/**\n * Successful return from {@link Agent.generateObject}.\n *\n * @public\n */\nexport interface GenerateObjectResult<T> {\n /** Typed object parsed via the Zod schema. */\n object: T;\n /** Raw input the model passed to the synthetic tool, before Zod parse. */\n raw: unknown;\n /** Token usage of the LLM call(s) that produced the result. */\n usage: { inputTokens: number; outputTokens: number };\n /** Stop reason of the underlying agent run. */\n finishReason: \"tool_use\" | \"error\";\n}\n\n/**\n * Typed error thrown by {@link Agent.generateObject} when the model refuses\n * to call the synthetic `output` tool or when retries are exhausted.\n *\n * @public\n */\nexport class GenerateObjectError extends StructuredOutputError {\n override readonly name = \"GenerateObjectError\";\n}\n\ninterface GenerateObjectDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n /** Hard-delete the transient agent from the registry after dispose. */\n delete: (agentId: string) => Promise<void>;\n}\n\n/**\n * M14 — best-effort partial salvage for `errorStrategy: 'return-partial'`. For an object schema,\n * keep only the fields that individually validate; anything else (non-object schema or non-object\n * raw) falls back to the raw value. Works across Zod v3/v4 via the `.shape` record both expose.\n */\nfunction salvagePartial<T extends ZodType>(schema: T, raw: unknown): unknown {\n if (typeof raw !== \"object\" || raw === null) return raw;\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape === undefined || typeof shape !== \"object\") return raw;\n const rawObj = raw as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const [key, fieldSchema] of Object.entries(shape)) {\n if (typeof fieldSchema?.safeParse !== \"function\") continue;\n const parsed = fieldSchema.safeParse(rawObj[key]);\n if (parsed.success) out[key] = parsed.data;\n }\n return out;\n}\n\n/**\n * M21 — phase 1: run `options.model` as a plain reasoning agent (no output tool) and return its\n * free-text answer, which phase 2's structuring model then extracts. The transient reasoning agent\n * is disposed + hard-deleted so the registry count stays stable (EC-3, mirrors the phase-2 finally).\n */\nasync function runReasoningPhase<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<string> {\n const reasoningOptions: AgentOptions = {\n model: options.model,\n local: options.local,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n };\n const reasoningAgent = await deps.create(reasoningOptions);\n try {\n const run = await reasoningAgent.send(options.prompt);\n const result = await run.wait();\n const text = (result as { result?: unknown }).result;\n return typeof text === \"string\" ? text : options.prompt;\n } finally {\n await disposeAndDeleteTransient(reasoningAgent, deps.delete);\n }\n}\n\n/**\n * Implementation of `Agent.generateObject`. Receives the `Agent.create`\n * factory as a callback to keep the dependency graph acyclic (mirrors the\n * AgentBuilder pattern in D25 / agent.ts injection).\n *\n * Algorithm:\n * 1. Convert the consumer's Zod schema to JSON Schema.\n * 2. Build a single synthetic `output` CustomTool whose handler captures\n * the raw input and short-circuits the agent loop. The handler\n * THROWS a sentinel so the loop terminates immediately without a\n * second LLM round-trip.\n * 3. Create ONE transient agent (per the entire generateObject call,\n * not per retry — EC-3). Each retry re-sends through the same agent,\n * driving fresh LLM rounds.\n * 4. On each attempt, send a wrapper prompt instructing the model to\n * call the `output` tool. Capture the raw input via the sentinel.\n * 5. Parse the raw input via schema.parse. On success, return typed.\n * On failure, retry until the budget is exhausted.\n * 6. Always dispose the transient agent in `finally`.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: retry loop + capture sentinel + dispose-and-delete is a single transaction; splitting harms locality and the finally block.\nexport async function generateObjectImpl<T extends ZodType>(\n options: GenerateObjectOptions<T>,\n deps: GenerateObjectDeps,\n): Promise<GenerateObjectResult<ZodNamespace.infer<T>>> {\n const { jsonSchema, maxRetries, initialUsage } = setupStructuredOutput(\n options.schema,\n options.maxRetries,\n );\n let capturedRaw: unknown;\n let lastUsage = initialUsage;\n const sentinel = Symbol(\"generate-object-sentinel\");\n class CaptureSentinel extends Error {\n readonly [sentinel] = true;\n constructor(public readonly captured: unknown) {\n super(\"generate-object-capture\");\n }\n }\n\n const outputTool = makeOutputTool(jsonSchema, (input) => {\n // EC-D10 (parallel tool use): first capture wins. Subsequent calls\n // in the same response are ignored.\n if (capturedRaw === undefined) {\n capturedRaw = input;\n }\n throw new CaptureSentinel(input);\n });\n\n // M21 — when a separate structuring model is set, `model` first reasons in free text (phase 1),\n // and `structuringModel` extracts the object over that text (phase 2). Absent ⇒ single-model flow.\n const reasoningText =\n options.structuringModel !== undefined ? await runReasoningPhase(options, deps) : undefined;\n const structuringModel = options.structuringModel ?? options.model;\n const structuringPrompt = reasoningText ?? options.prompt;\n\n const agentOptions: AgentOptions = buildTransientAgentOptions({\n model: structuringModel,\n local: options.local,\n outputTool,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),\n ...(options.providers !== undefined ? { providers: options.providers } : {}),\n });\n const agent = await deps.create(agentOptions);\n\n try {\n const userMessage = buildToolPrompt(structuringPrompt);\n let lastParseError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n capturedRaw = undefined;\n const run = await agent.send(userMessage);\n const result = await run.wait();\n lastUsage = extractUsage(result);\n\n if (capturedRaw === undefined) {\n // EC: when the underlying run errored (e.g. provider_unresolved),\n // surface the original cause instead of the misleading \"model\n // returned text\" message — there was no model call at all.\n if (result.status === \"error\" && result.error !== undefined) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n STRUCTURED_OUTPUT_MESSAGES.runFailed(result.error.message, result.error.code),\n result.error,\n );\n }\n // Model didn't call the output tool.\n if (attempt === maxRetries) {\n throw new GenerateObjectError(\"no_tool_call\", STRUCTURED_OUTPUT_MESSAGES.noToolCall);\n }\n continue;\n }\n\n const parsed = options.schema.safeParse(capturedRaw);\n if (parsed.success) {\n return {\n object: parsed.data,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n lastParseError = parsed.error;\n }\n\n // M14 — all retries exhausted with a parse failure. `errorStrategy` decides the outcome; the\n // tool WAS called (capturedRaw is set), so `finishReason` stays `tool_use`.\n if (options.errorStrategy === \"return-raw\") {\n return {\n object: capturedRaw as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n if (options.errorStrategy === \"return-partial\") {\n return {\n object: salvagePartial(options.schema, capturedRaw) as ZodNamespace.infer<T>,\n raw: capturedRaw,\n usage: lastUsage,\n finishReason: \"tool_use\",\n };\n }\n throw new GenerateObjectError(\n \"parse_failed\",\n STRUCTURED_OUTPUT_MESSAGES.parseFailed,\n lastParseError,\n );\n } finally {\n // EC-3: dispose AND hard-delete the transient agent so registry count\n // stays stable across retries.\n await disposeAndDeleteTransient(agent, deps.delete);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/structured-output-helpers.ts"],"names":[],"mappings":";;;;AAmBA,IAAI,OAAA;AAMG,SAAS,UAAA,GAAkC;AAChD,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,OAAA;AAClC,EAAA,MAAM,CAAA,GAAI,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA;AACvC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,EAAE,KAAK,CAAA;AAAA,EACf,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR,qIAAA;AAAA,MAEA,EAAE,IAAA,EAAM,mBAAA,EAAqB,KAAA;AAAM,KACrC;AAAA,EACF;AACA,EAAA,OAAA,GAAW,IAAI,CAAA,IAAK,GAAA;AACpB,EAAA,OAAO,OAAA;AACT;AAQO,SAAS,cAAA,CACd,YACA,SAAA,EACY;AACZ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,QAAA;AAAA,IACN,WAAA,EAAa,kFAAA;AAAA,IACb,WAAA,EAAa,UAAA;AAAA,IACb,OAAA,EAAS,CAAC,KAAA,KAAU;AAClB,MAAA,MAAM,GAAA,GAAM,UAAU,KAAK,CAAA;AAG3B,MAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,MAAA,IAAI,GAAA,YAAe,SAAS,OAAO,GAAA;AACnC,MAAA,OAAO,EAAA;AAAA,IACT;AAAA,GACF;AACF;AAMO,SAAS,2BAA2B,MAAA,EAS1B;AACf,EAAA,OAAO;AAAA,IACL,OAAO,MAAA,CAAO,KAAA;AAAA,I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;AAUO,IAAM,0BAAA,GAA6B;AAAA,EACxC,SAAA,EAAW,CAAC,OAAA,EAA6B,IAAA,KACvC,kDAAkD,OAAA,IAAW,eAAe,CAAA,EAAA,EAAK,IAAA,IAAQ,GAAG,CAAA,CAAA,CAAA;AAAA,EAC9F,UAAA,EAAY,+DAAA;AAAA,EACZ,WAAA,EAAa;AACf","file":"chunk-AQW54OWQ.js","sourcesContent":["import { createRequire } from \"node:module\";\nimport type { z as ZodNamespace, ZodType } from \"zod\";\nimport { ConfigurationError } from \"../errors.js\";\nimport type { AgentOptions, CustomTool, LocalOptions, ModelSelection } from \"../types/agent.js\";\nimport type { ProviderRoutingSettings } from \"../types/providers.js\";\nimport { toJsonSchema } from \"./zod-to-json-schema.js\";\n\n/**\n * Shared helpers for `Agent.generateObject` (ADR D33) and\n * `Agent.streamObject` (ADR D39). Both build a transient agent with a\n * single synthetic `output` tool whose handler captures the model's\n * structured response.\n *\n * Extracted from inline duplicates to keep jscpd quiet AND to keep the\n * two public APIs in lockstep.\n *\n * @internal\n */\n\nlet cachedZ: typeof ZodNamespace | undefined;\n\n/**\n * Load Zod via createRequire (it's an optional peer dep). Throws a typed\n * ConfigurationError if Zod isn't installed.\n */\nexport function requireZod(): typeof ZodNamespace {\n if (cachedZ !== undefined) return cachedZ;\n const r = createRequire(import.meta.url);\n let mod: { z?: typeof ZodNamespace } & typeof ZodNamespace;\n try {\n mod = r(\"zod\") as typeof mod;\n } catch (cause) {\n throw new ConfigurationError(\n \"Structured output requires the optional peer dependency `zod`. \" +\n 'Add `\"zod\": \"^3.25.0 || ^4.0.0\"` to your package.json and reinstall.',\n { code: \"zod_not_installed\", cause },\n );\n }\n cachedZ = (mod.z ?? mod) as typeof ZodNamespace;\n return cachedZ;\n}\n\n/**\n * Build the synthetic `output` tool used by both `generateObject` and\n * `streamObject`. The handler captures the raw input on first call only\n * (EC-D10 / EC-6: parallel tool use in Claude 3.5+ may invoke `output`\n * twice; later calls are ignored).\n */\nexport function makeOutputTool(\n jsonSchema: Record<string, unknown>,\n onCapture: (input: unknown) => string | Promise<string> | undefined,\n): CustomTool {\n return {\n name: \"output\",\n description: \"Call this tool with your final structured answer. Match the JSON schema exactly.\",\n inputSchema: jsonSchema,\n handler: (input) => {\n const out = onCapture(input);\n // Some callers throw a sentinel (generate-object) and never return.\n // Others return a string (stream-object). Anything else → empty string.\n if (typeof out === \"string\") return out;\n if (out instanceof Promise) return out;\n return \"\";\n },\n };\n}\n\n/**\n * Assemble the AgentOptions for the transient agent. Shared shape:\n * model + local + tools[output] + systemPrompt + apiKey.\n */\nexport function buildTransientAgentOptions(params: {\n // SE8 — accepts the bare-string shorthand; forwarded to AgentOptions.model\n // (normalized at Agent.create).\n model: string | ModelSelection;\n local: LocalOptions;\n outputTool: CustomTool;\n systemPrompt?: string;\n apiKey?: string;\n providers?: ProviderRoutingSettings;\n}): AgentOptions {\n return {\n model: params.model,\n local: params.local,\n tools: [params.outputTool],\n systemPrompt:\n params.systemPrompt ??\n \"You produce structured output by calling the `output` tool exactly once. Match the JSON schema.\",\n ...(params.apiKey !== undefined ? { apiKey: params.apiKey } : {}),\n ...(params.providers !== undefined ? { providers: params.providers } : {}),\n };\n}\n\n/**\n * Best-effort extraction of token usage from a run result. Local runtimes\n * may not expose it; default to zeros.\n */\nexport function extractUsage(result: unknown): { inputTokens: number; outputTokens: number } {\n const u = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;\n if (u === undefined) return { inputTokens: 0, outputTokens: 0 };\n return { inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0 };\n}\n\n/**\n * Build the user-message prompt that instructs the model to call the\n * `output` tool with a schema-matched structured answer.\n */\nexport function buildToolPrompt(prompt: string): string {\n return `${prompt}\\n\\nRespond by calling the \\`output\\` tool with the structured answer that matches the schema.`;\n}\n\n/**\n * One-shot setup shared by both `generateObject` and `streamObject`. Loads\n * Zod, computes the JSON schema, primes the captured-raw / usage / retry\n * state. Returns the values needed by the caller's loop.\n */\nexport function setupStructuredOutput<T extends ZodType>(\n schema: T,\n maxRetries: number | undefined,\n) {\n const z = requireZod();\n // Universal Zod 3+4 conversion (feature-detects native v4, falls back to lib on v3).\n const jsonSchema = toJsonSchema(schema, { unrepresentable: \"any\" });\n return {\n z,\n jsonSchema,\n maxRetries: maxRetries ?? 1,\n initialUsage: { inputTokens: 0, outputTokens: 0 },\n };\n}\n\n/**\n * Cleanup the transient agent after generateObject/streamObject finish.\n * Disposes AND hard-deletes from the registry so the count stays stable.\n *\n * @internal\n */\nexport async function disposeAndDeleteTransient(\n agent: { dispose: () => Promise<void>; agentId: string },\n deletor: (agentId: string) => Promise<void>,\n): Promise<void> {\n await agent.dispose();\n try {\n await deletor(agent.agentId);\n } catch {\n // Best-effort cleanup.\n }\n}\n\n/**\n * The three failure messages, verbatim from what both entry points already emit.\n *\n * Identical strings in two files is how two APIs start describing the same failure differently: the\n * first person to improve one of them improves half the product.\n *\n * @internal\n */\nexport const STRUCTURED_OUTPUT_MESSAGES = {\n runFailed: (message: string | undefined, code: string | undefined): string =>\n `Agent run failed before the model could reply: ${message ?? \"unknown error\"} [${code ?? \"?\"}]`,\n noToolCall: \"The model returned text instead of calling the `output` tool.\",\n parseFailed: \"Schema parse failed after all retries.\",\n} as const;\n"]}