@theokit/sdk 5.15.2 → 5.16.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 (92) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{agent-QRIFX2SY.js → agent-FB56RAXD.js} +11 -10
  3. package/dist/{agent-QRIFX2SY.js.map → agent-FB56RAXD.js.map} +1 -1
  4. package/dist/{agent-D6WBBNGR.cjs → agent-TM634NHQ.cjs} +12 -11
  5. package/dist/{agent-D6WBBNGR.cjs.map → agent-TM634NHQ.cjs.map} +1 -1
  6. package/dist/chunk-22HVMMXX.cjs +13 -0
  7. package/dist/chunk-22HVMMXX.cjs.map +1 -0
  8. package/dist/{chunk-PDFSLD5P.cjs → chunk-3JGRKXA7.cjs} +4 -4
  9. package/dist/{chunk-PDFSLD5P.cjs.map → chunk-3JGRKXA7.cjs.map} +1 -1
  10. package/dist/{chunk-CMDM4VF6.js → chunk-4XYCF5PA.js} +3 -3
  11. package/dist/{chunk-CMDM4VF6.js.map → chunk-4XYCF5PA.js.map} +1 -1
  12. package/dist/{chunk-PSMWZYW6.js → chunk-6WPNFZH3.js} +4 -4
  13. package/dist/{chunk-PSMWZYW6.js.map → chunk-6WPNFZH3.js.map} +1 -1
  14. package/dist/{chunk-5L7S2VOL.js → chunk-A3T2A2WU.js} +3 -69
  15. package/dist/chunk-A3T2A2WU.js.map +1 -0
  16. package/dist/{chunk-BTGYRM4J.cjs → chunk-BJB6RDEA.cjs} +59 -59
  17. package/dist/{chunk-BTGYRM4J.cjs.map → chunk-BJB6RDEA.cjs.map} +1 -1
  18. package/dist/{chunk-6XT5LAZG.cjs → chunk-BXEHUUDJ.cjs} +69 -30
  19. package/dist/chunk-BXEHUUDJ.cjs.map +1 -0
  20. package/dist/{chunk-ATGSV4GS.js → chunk-DLCYS5RI.js} +3 -3
  21. package/dist/{chunk-ATGSV4GS.js.map → chunk-DLCYS5RI.js.map} +1 -1
  22. package/dist/chunk-GA4ZRKYF.cjs +75 -0
  23. package/dist/chunk-GA4ZRKYF.cjs.map +1 -0
  24. package/dist/chunk-ICBNSAO4.js +11 -0
  25. package/dist/chunk-ICBNSAO4.js.map +1 -0
  26. package/dist/{chunk-JRQJMZKY.js → chunk-MNE4633K.js} +45 -6
  27. package/dist/chunk-MNE4633K.js.map +1 -0
  28. package/dist/{chunk-CG64VPPU.js → chunk-NHD5IN3E.js} +10 -10
  29. package/dist/{chunk-CG64VPPU.js.map → chunk-NHD5IN3E.js.map} +1 -1
  30. package/dist/{chunk-Q4UOCMAO.cjs → chunk-S5WTJ6LL.cjs} +5 -5
  31. package/dist/{chunk-Q4UOCMAO.cjs.map → chunk-S5WTJ6LL.cjs.map} +1 -1
  32. package/dist/chunk-SGKMTBCO.cjs +18 -0
  33. package/dist/{chunk-EDIYR4VR.cjs.map → chunk-SGKMTBCO.cjs.map} +1 -1
  34. package/dist/{chunk-VT3NWHFH.cjs → chunk-TDKLSWHU.cjs} +4 -4
  35. package/dist/{chunk-VT3NWHFH.cjs.map → chunk-TDKLSWHU.cjs.map} +1 -1
  36. package/dist/{chunk-AQ23NII7.js → chunk-UNUGF36D.js} +3 -3
  37. package/dist/{chunk-AQ23NII7.js.map → chunk-UNUGF36D.js.map} +1 -1
  38. package/dist/{chunk-Z5MB2HAN.cjs → chunk-WVQRE7CO.cjs} +4 -70
  39. package/dist/chunk-WVQRE7CO.cjs.map +1 -0
  40. package/dist/chunk-Z2UVCAYS.js +72 -0
  41. package/dist/chunk-Z2UVCAYS.js.map +1 -0
  42. package/dist/{compact-session-5DWFHMW4.cjs → compact-session-OHA543HN.cjs} +14 -13
  43. package/dist/{compact-session-5DWFHMW4.cjs.map → compact-session-OHA543HN.cjs.map} +1 -1
  44. package/dist/{compact-session-AL65PEMX.js → compact-session-XPJS27JD.js} +5 -4
  45. package/dist/{compact-session-AL65PEMX.js.map → compact-session-XPJS27JD.js.map} +1 -1
  46. package/dist/cron.cjs +11 -10
  47. package/dist/cron.js +10 -9
  48. package/dist/eval.cjs +10 -9
  49. package/dist/eval.cjs.map +1 -1
  50. package/dist/eval.js +9 -8
  51. package/dist/eval.js.map +1 -1
  52. package/dist/index.cjs +219 -45
  53. package/dist/index.cjs.map +1 -1
  54. package/dist/index.d.cts +106 -1
  55. package/dist/index.d.ts +106 -1
  56. package/dist/index.js +185 -14
  57. package/dist/index.js.map +1 -1
  58. package/dist/{inject-session-QZULG65O.cjs → inject-session-NTL2UAE6.cjs} +5 -5
  59. package/dist/{inject-session-QZULG65O.cjs.map → inject-session-NTL2UAE6.cjs.map} +1 -1
  60. package/dist/{inject-session-E2SZ4A35.js → inject-session-SCJ6MTUT.js} +4 -4
  61. package/dist/{inject-session-E2SZ4A35.js.map → inject-session-SCJ6MTUT.js.map} +1 -1
  62. package/dist/internal/llm/openai.d.ts +2 -0
  63. package/dist/internal/llm/responses.d.ts +2 -0
  64. package/dist/internal/llm/sse.d.ts +6 -0
  65. package/dist/internal/providers/builtin/openai-chatgpt.d.ts +8 -0
  66. package/dist/internal/trim-trailing-slashes.d.ts +6 -0
  67. package/dist/models.cjs +12 -16
  68. package/dist/models.cjs.map +1 -1
  69. package/dist/models.js +4 -8
  70. package/dist/models.js.map +1 -1
  71. package/dist/openai-chatgpt-IVAL4MW6.cjs +22 -0
  72. package/dist/openai-chatgpt-IVAL4MW6.cjs.map +1 -0
  73. package/dist/openai-chatgpt-ZFNZWT2L.js +9 -0
  74. package/dist/openai-chatgpt-ZFNZWT2L.js.map +1 -0
  75. package/dist/providers.cjs +5 -4
  76. package/dist/providers.js +3 -2
  77. package/dist/sandbox/e2b-sandbox.d.cts +61 -0
  78. package/dist/sandbox/e2b-sandbox.d.ts +61 -0
  79. package/dist/sandbox/index.cjs +55 -0
  80. package/dist/sandbox/index.cjs.map +1 -1
  81. package/dist/sandbox/index.d.cts +1 -0
  82. package/dist/sandbox/index.d.ts +1 -0
  83. package/dist/sandbox/index.js +54 -1
  84. package/dist/sandbox/index.js.map +1 -1
  85. package/docs/error-codes.md +6 -4
  86. package/docs/harness-capability-map.md +21 -1
  87. package/package.json +5 -1
  88. package/dist/chunk-5L7S2VOL.js.map +0 -1
  89. package/dist/chunk-6XT5LAZG.cjs.map +0 -1
  90. package/dist/chunk-EDIYR4VR.cjs +0 -18
  91. package/dist/chunk-JRQJMZKY.js.map +0 -1
  92. package/dist/chunk-Z5MB2HAN.cjs.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1582,6 +1582,67 @@ interface CredentialReport {
1582
1582
  */
1583
1583
  declare function describeCredential(input: CredentialInput): CredentialReport;
1584
1584
 
1585
+ /**
1586
+ * `decide` — a typed decision (one label from a declared enum) answered by a pinned, checksum-verified
1587
+ * local ONNX classifier. It makes no provider request. The model file is hashed (SHA-256) before it is
1588
+ * loaded; a mismatch is refused. The ONNX runtime (`onnxruntime-node`) is an optional peer, loaded on use.
1589
+ */
1590
+
1591
+ /** Token ids for one input, as the classifier expects them. @public */
1592
+ interface DecisionTokens {
1593
+ inputIds: number[];
1594
+ attentionMask?: number[];
1595
+ }
1596
+ /** A loaded ONNX session, reduced to what `decide` uses. @public */
1597
+ interface DecisionSession {
1598
+ /** Runs the model and returns one logit per label, in label order. */
1599
+ run(tokens: DecisionTokens): Promise<number[]>;
1600
+ }
1601
+ /** Options for {@link decide}. @public */
1602
+ interface DecideOptions<L extends string> {
1603
+ /** The text to classify. */
1604
+ text: string;
1605
+ /** The allowed labels, in the order of the model's output logits. */
1606
+ labels: readonly L[];
1607
+ /** Path to the `.onnx` model file. */
1608
+ modelPath: string;
1609
+ /** Pinned lowercase hex SHA-256 of the model file. A different file is refused. */
1610
+ sha256: string;
1611
+ /** Turns text into token ids (the tokenizer that belongs to the pinned model). */
1612
+ tokenize: (text: string) => DecisionTokens | Promise<DecisionTokens>;
1613
+ /** Overrides the session loader (default: `onnxruntime-node`). Receives the verified model bytes. */
1614
+ loadSession?: (model: Uint8Array) => Promise<DecisionSession>;
1615
+ }
1616
+ /** Result of {@link decide}. @public */
1617
+ interface Decision<L extends string> {
1618
+ /** The chosen label. */
1619
+ label: L;
1620
+ /** Softmax probability per label. */
1621
+ scores: Record<L, number>;
1622
+ /** Always `"local-onnx"`: the answer came from the pinned local model, not a provider request. */
1623
+ source: "local-onnx";
1624
+ /** SHA-256 of the verified model that answered. */
1625
+ modelSha256: string;
1626
+ }
1627
+ /** Thrown when the model file's checksum differs from the pinned one. @public */
1628
+ declare class DecisionChecksumError extends TheokitAgentError {
1629
+ readonly modelPath: string;
1630
+ readonly expected: string;
1631
+ readonly actual: string;
1632
+ readonly name: string;
1633
+ constructor(modelPath: string, expected: string, actual: string);
1634
+ }
1635
+ /**
1636
+ * No model or tokenizer is bundled: pass the pinned model file, its SHA-256 and its tokenizer. The model
1637
+ * must take int64 `input_ids` and `attention_mask` and output one logit per label.
1638
+ *
1639
+ * Classify `text` into one of `labels` with a local ONNX model. Rejects with
1640
+ * {@link DecisionChecksumError} when the file does not match `sha256`.
1641
+ *
1642
+ * @public
1643
+ */
1644
+ declare function decide<L extends string>(opts: DecideOptions<L>): Promise<Decision<L>>;
1645
+
1585
1646
  /**
1586
1647
  * Plugin contract — RUNTIME value + type re-exports (T1.1, ADRs D97-D101).
1587
1648
  *
@@ -1938,6 +1999,50 @@ declare class EventBus<Events extends Record<string, unknown>> {
1938
1999
  once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void;
1939
2000
  }
1940
2001
 
2002
+ /**
2003
+ * `generateImage` — one image from an OpenAI-compatible `/images/generations` endpoint.
2004
+ *
2005
+ * A provider primitive: it holds no state, writes no file and returns the decoded bytes. The
2006
+ * `route: "chatgpt"` goes through the ChatGPT subscription login instead of an API key.
2007
+ */
2008
+ /** Options for {@link generateImage}. @public */
2009
+ interface GenerateImageOptions {
2010
+ /** What to draw. */
2011
+ prompt: string;
2012
+ /**
2013
+ * `"api"` (default): OpenAI-compatible `/images/generations` with an API key.
2014
+ * `"chatgpt"`: the ChatGPT-subscription (Codex) route, using the stored OpenAI device login and the
2015
+ * Responses API `image_generation` tool; `model` then names the chat model (default `gpt-5.4`).
2016
+ */
2017
+ route?: "api" | "chatgpt";
2018
+ /** API key (`"api"` route). Falls back to `OPENAI_API_KEY`. */
2019
+ apiKey?: string;
2020
+ /** Model id. Default `gpt-image-1`. */
2021
+ model?: string;
2022
+ /** Endpoint base. Default `https://api.openai.com/v1`. */
2023
+ baseUrl?: string;
2024
+ /** Size such as `1024x1024`. Omitted ⇒ provider default. */
2025
+ size?: string;
2026
+ /** Abort signal. */
2027
+ signal?: AbortSignal;
2028
+ /** Fetch implementation. Default global `fetch`. */
2029
+ fetch?: typeof fetch;
2030
+ }
2031
+ /** Result of {@link generateImage}. @public */
2032
+ interface GeneratedImage {
2033
+ /** Encoded image bytes. */
2034
+ image: Uint8Array;
2035
+ /** Mime type sniffed from the bytes (`application/octet-stream` when not png/jpeg/webp). */
2036
+ mimeType: string;
2037
+ }
2038
+ /**
2039
+ * Generate one image. Rejects with an `Error` on a missing key, a non-2xx status or a response
2040
+ * without `data[0].b64_json`.
2041
+ *
2042
+ * @public
2043
+ */
2044
+ declare function generateImage(opts: GenerateImageOptions): Promise<GeneratedImage>;
2045
+
1941
2046
  /** Inputs to the judge — pure data. */
1942
2047
  interface JudgeContext {
1943
2048
  goal: string;
@@ -4485,4 +4590,4 @@ interface WiringRecordInput<K extends string> {
4485
4590
  */
4486
4591
  declare function recordWiring<K extends string>(input: WiringRecordInput<K>): Readonly<Record<K, WiredEntity>>;
4487
4592
 
4488
- export { Agent, AgentBuilder, type AgentBuilderDeps, AgentDefinition, type AgentDescription, AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type ApprovalDecision, type ApprovalInput, type ApprovalMode, type ApprovalOutcome, type ApprovalReason, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, type BlastRadiusDecision, type BlastRadiusInput, type BlastRadiusOutcome, type BlastRadiusReason, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, type BudgetTracker, BuiltinToolName, CloudOptions, ContextSettings, type CounterBudgetTrackerOptions, type CredentialInput, type CredentialReport, type CustomTool, type DeclaredAction, type DeclaredLayer, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DiagnosticsSink, type DreamingSweepOptions, type DreamingSweepResult, type EffectiveToolCatalog, type EnvOptOut, type EnvReachabilityAudit, type EnvReachabilityInput, ErrorMetadata, EventBus, type EvictReason, GOAL_CONTINUATION_MARKER, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, GoalEvent, type GoalLoopAgent, GoalOptions, GoalResult, InlineSkill, JobQueue, type JobQueueOptions, JudgeCredentialError, type JudgeResult, type KeepReason, type KeptArtifact, LayerOrderError, type LayerValues, ListAgentsOptions, ListResult, ListRunsOptions, type LiveAgentRegistry, LiveSessionError, type LiveSessionReason, LocalOptions, type ManagedSettings, McpServerConfig, Memory, MemoryId, type MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, NoopMemoryProvider, type NormalizedJsonSchema, type OTelSpan, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionFloorContext, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, PermissionMode, PermissionPlugin, type PermissionPluginOptions, type PermissionRule, type PermissionRuleSet, Plugin, PluginsSettings, PreToolCallDecision, type Processor, Provider, type ProviderProfile, ProviderRoutingSettings, type ReadSessionMessagesOptions, type ReapPlan, type ReapPlanInput, type ReapableArtifact, type RetentionPolicy, RetentionPolicyError, Run, RunEventSink$1 as RunEventSink, RunResult, type SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, SOVEREIGN_ENV_KEYS, Security, type SecurityFloorInput, type SessionMessage, type SessionMessagePart, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillReadTool, SkillsSettings, type SovereignEnvKey, Squad, type SquadOptions, type SquadRun, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, type TelemetryHandle, Theokit, TheokitAgentError, type TheokitRequestOptions, TokenLimiter, type TokenLimiterOptions, Tool, ToolError, type ToolResultContentBlock, type TrustLevel, type TrustPosture, type TrustPostureInput, type TrustSource, UngatedCapabilityError, UnicodeNormalizer, type UnicodeNormalizerOptions, type UnresolvedToolSource, UsageAccumulator, type WiredEntity, type WiringRecordInput, type WithBlastRadius, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decideApproval, describeAction, describeCredential, effectiveToolNames, emitRunEvent, estimateTokens, evaluateBlastRadius, extractRawId, foldLayers, getPricingEntry, guardSessionDestruction, inferApiMode, isInside, isValidTaskId, loadProjectEnv, managedSettingsPathFor, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readManagedSettings, readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, setDiagnosticsSink, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
4593
+ export { Agent, AgentBuilder, type AgentBuilderDeps, AgentDefinition, type AgentDescription, AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type ApprovalDecision, type ApprovalInput, type ApprovalMode, type ApprovalOutcome, type ApprovalReason, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, type BlastRadiusDecision, type BlastRadiusInput, type BlastRadiusOutcome, type BlastRadiusReason, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, type BudgetTracker, BuiltinToolName, CloudOptions, ContextSettings, type CounterBudgetTrackerOptions, type CredentialInput, type CredentialReport, type CustomTool, type DecideOptions, type Decision, DecisionChecksumError, type DecisionSession, type DecisionTokens, type DeclaredAction, type DeclaredLayer, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DiagnosticsSink, type DreamingSweepOptions, type DreamingSweepResult, type EffectiveToolCatalog, type EnvOptOut, type EnvReachabilityAudit, type EnvReachabilityInput, ErrorMetadata, EventBus, type EvictReason, GOAL_CONTINUATION_MARKER, type GenerateImageOptions, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, type GeneratedImage, GetAgentOptions, GetRunOptions, GoalEvent, type GoalLoopAgent, GoalOptions, GoalResult, InlineSkill, JobQueue, type JobQueueOptions, JudgeCredentialError, type JudgeResult, type KeepReason, type KeptArtifact, LayerOrderError, type LayerValues, ListAgentsOptions, ListResult, ListRunsOptions, type LiveAgentRegistry, LiveSessionError, type LiveSessionReason, LocalOptions, type ManagedSettings, McpServerConfig, Memory, MemoryId, type MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, NoopMemoryProvider, type NormalizedJsonSchema, type OTelSpan, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionFloorContext, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, PermissionMode, PermissionPlugin, type PermissionPluginOptions, type PermissionRule, type PermissionRuleSet, Plugin, PluginsSettings, PreToolCallDecision, type Processor, Provider, type ProviderProfile, ProviderRoutingSettings, type ReadSessionMessagesOptions, type ReapPlan, type ReapPlanInput, type ReapableArtifact, type RetentionPolicy, RetentionPolicyError, Run, RunEventSink$1 as RunEventSink, RunResult, type SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, SOVEREIGN_ENV_KEYS, Security, type SecurityFloorInput, type SessionMessage, type SessionMessagePart, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillReadTool, SkillsSettings, type SovereignEnvKey, Squad, type SquadOptions, type SquadRun, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, type TelemetryHandle, Theokit, TheokitAgentError, type TheokitRequestOptions, TokenLimiter, type TokenLimiterOptions, Tool, ToolError, type ToolResultContentBlock, type TrustLevel, type TrustPosture, type TrustPostureInput, type TrustSource, UngatedCapabilityError, UnicodeNormalizer, type UnicodeNormalizerOptions, type UnresolvedToolSource, UsageAccumulator, type WiredEntity, type WiringRecordInput, type WithBlastRadius, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decide, decideApproval, describeAction, describeCredential, effectiveToolNames, emitRunEvent, estimateTokens, evaluateBlastRadius, extractRawId, foldLayers, generateImage, getPricingEntry, guardSessionDestruction, inferApiMode, isInside, isValidTaskId, loadProjectEnv, managedSettingsPathFor, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readManagedSettings, readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, setDiagnosticsSink, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
package/dist/index.d.ts CHANGED
@@ -1582,6 +1582,67 @@ interface CredentialReport {
1582
1582
  */
1583
1583
  declare function describeCredential(input: CredentialInput): CredentialReport;
1584
1584
 
1585
+ /**
1586
+ * `decide` — a typed decision (one label from a declared enum) answered by a pinned, checksum-verified
1587
+ * local ONNX classifier. It makes no provider request. The model file is hashed (SHA-256) before it is
1588
+ * loaded; a mismatch is refused. The ONNX runtime (`onnxruntime-node`) is an optional peer, loaded on use.
1589
+ */
1590
+
1591
+ /** Token ids for one input, as the classifier expects them. @public */
1592
+ interface DecisionTokens {
1593
+ inputIds: number[];
1594
+ attentionMask?: number[];
1595
+ }
1596
+ /** A loaded ONNX session, reduced to what `decide` uses. @public */
1597
+ interface DecisionSession {
1598
+ /** Runs the model and returns one logit per label, in label order. */
1599
+ run(tokens: DecisionTokens): Promise<number[]>;
1600
+ }
1601
+ /** Options for {@link decide}. @public */
1602
+ interface DecideOptions<L extends string> {
1603
+ /** The text to classify. */
1604
+ text: string;
1605
+ /** The allowed labels, in the order of the model's output logits. */
1606
+ labels: readonly L[];
1607
+ /** Path to the `.onnx` model file. */
1608
+ modelPath: string;
1609
+ /** Pinned lowercase hex SHA-256 of the model file. A different file is refused. */
1610
+ sha256: string;
1611
+ /** Turns text into token ids (the tokenizer that belongs to the pinned model). */
1612
+ tokenize: (text: string) => DecisionTokens | Promise<DecisionTokens>;
1613
+ /** Overrides the session loader (default: `onnxruntime-node`). Receives the verified model bytes. */
1614
+ loadSession?: (model: Uint8Array) => Promise<DecisionSession>;
1615
+ }
1616
+ /** Result of {@link decide}. @public */
1617
+ interface Decision<L extends string> {
1618
+ /** The chosen label. */
1619
+ label: L;
1620
+ /** Softmax probability per label. */
1621
+ scores: Record<L, number>;
1622
+ /** Always `"local-onnx"`: the answer came from the pinned local model, not a provider request. */
1623
+ source: "local-onnx";
1624
+ /** SHA-256 of the verified model that answered. */
1625
+ modelSha256: string;
1626
+ }
1627
+ /** Thrown when the model file's checksum differs from the pinned one. @public */
1628
+ declare class DecisionChecksumError extends TheokitAgentError {
1629
+ readonly modelPath: string;
1630
+ readonly expected: string;
1631
+ readonly actual: string;
1632
+ readonly name: string;
1633
+ constructor(modelPath: string, expected: string, actual: string);
1634
+ }
1635
+ /**
1636
+ * No model or tokenizer is bundled: pass the pinned model file, its SHA-256 and its tokenizer. The model
1637
+ * must take int64 `input_ids` and `attention_mask` and output one logit per label.
1638
+ *
1639
+ * Classify `text` into one of `labels` with a local ONNX model. Rejects with
1640
+ * {@link DecisionChecksumError} when the file does not match `sha256`.
1641
+ *
1642
+ * @public
1643
+ */
1644
+ declare function decide<L extends string>(opts: DecideOptions<L>): Promise<Decision<L>>;
1645
+
1585
1646
  /**
1586
1647
  * Plugin contract — RUNTIME value + type re-exports (T1.1, ADRs D97-D101).
1587
1648
  *
@@ -1938,6 +1999,50 @@ declare class EventBus<Events extends Record<string, unknown>> {
1938
1999
  once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void;
1939
2000
  }
1940
2001
 
2002
+ /**
2003
+ * `generateImage` — one image from an OpenAI-compatible `/images/generations` endpoint.
2004
+ *
2005
+ * A provider primitive: it holds no state, writes no file and returns the decoded bytes. The
2006
+ * `route: "chatgpt"` goes through the ChatGPT subscription login instead of an API key.
2007
+ */
2008
+ /** Options for {@link generateImage}. @public */
2009
+ interface GenerateImageOptions {
2010
+ /** What to draw. */
2011
+ prompt: string;
2012
+ /**
2013
+ * `"api"` (default): OpenAI-compatible `/images/generations` with an API key.
2014
+ * `"chatgpt"`: the ChatGPT-subscription (Codex) route, using the stored OpenAI device login and the
2015
+ * Responses API `image_generation` tool; `model` then names the chat model (default `gpt-5.4`).
2016
+ */
2017
+ route?: "api" | "chatgpt";
2018
+ /** API key (`"api"` route). Falls back to `OPENAI_API_KEY`. */
2019
+ apiKey?: string;
2020
+ /** Model id. Default `gpt-image-1`. */
2021
+ model?: string;
2022
+ /** Endpoint base. Default `https://api.openai.com/v1`. */
2023
+ baseUrl?: string;
2024
+ /** Size such as `1024x1024`. Omitted ⇒ provider default. */
2025
+ size?: string;
2026
+ /** Abort signal. */
2027
+ signal?: AbortSignal;
2028
+ /** Fetch implementation. Default global `fetch`. */
2029
+ fetch?: typeof fetch;
2030
+ }
2031
+ /** Result of {@link generateImage}. @public */
2032
+ interface GeneratedImage {
2033
+ /** Encoded image bytes. */
2034
+ image: Uint8Array;
2035
+ /** Mime type sniffed from the bytes (`application/octet-stream` when not png/jpeg/webp). */
2036
+ mimeType: string;
2037
+ }
2038
+ /**
2039
+ * Generate one image. Rejects with an `Error` on a missing key, a non-2xx status or a response
2040
+ * without `data[0].b64_json`.
2041
+ *
2042
+ * @public
2043
+ */
2044
+ declare function generateImage(opts: GenerateImageOptions): Promise<GeneratedImage>;
2045
+
1941
2046
  /** Inputs to the judge — pure data. */
1942
2047
  interface JudgeContext {
1943
2048
  goal: string;
@@ -4485,4 +4590,4 @@ interface WiringRecordInput<K extends string> {
4485
4590
  */
4486
4591
  declare function recordWiring<K extends string>(input: WiringRecordInput<K>): Readonly<Record<K, WiredEntity>>;
4487
4592
 
4488
- export { Agent, AgentBuilder, type AgentBuilderDeps, AgentDefinition, type AgentDescription, AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type ApprovalDecision, type ApprovalInput, type ApprovalMode, type ApprovalOutcome, type ApprovalReason, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, type BlastRadiusDecision, type BlastRadiusInput, type BlastRadiusOutcome, type BlastRadiusReason, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, type BudgetTracker, BuiltinToolName, CloudOptions, ContextSettings, type CounterBudgetTrackerOptions, type CredentialInput, type CredentialReport, type CustomTool, type DeclaredAction, type DeclaredLayer, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DiagnosticsSink, type DreamingSweepOptions, type DreamingSweepResult, type EffectiveToolCatalog, type EnvOptOut, type EnvReachabilityAudit, type EnvReachabilityInput, ErrorMetadata, EventBus, type EvictReason, GOAL_CONTINUATION_MARKER, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, GoalEvent, type GoalLoopAgent, GoalOptions, GoalResult, InlineSkill, JobQueue, type JobQueueOptions, JudgeCredentialError, type JudgeResult, type KeepReason, type KeptArtifact, LayerOrderError, type LayerValues, ListAgentsOptions, ListResult, ListRunsOptions, type LiveAgentRegistry, LiveSessionError, type LiveSessionReason, LocalOptions, type ManagedSettings, McpServerConfig, Memory, MemoryId, type MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, NoopMemoryProvider, type NormalizedJsonSchema, type OTelSpan, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionFloorContext, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, PermissionMode, PermissionPlugin, type PermissionPluginOptions, type PermissionRule, type PermissionRuleSet, Plugin, PluginsSettings, PreToolCallDecision, type Processor, Provider, type ProviderProfile, ProviderRoutingSettings, type ReadSessionMessagesOptions, type ReapPlan, type ReapPlanInput, type ReapableArtifact, type RetentionPolicy, RetentionPolicyError, Run, RunEventSink$1 as RunEventSink, RunResult, type SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, SOVEREIGN_ENV_KEYS, Security, type SecurityFloorInput, type SessionMessage, type SessionMessagePart, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillReadTool, SkillsSettings, type SovereignEnvKey, Squad, type SquadOptions, type SquadRun, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, type TelemetryHandle, Theokit, TheokitAgentError, type TheokitRequestOptions, TokenLimiter, type TokenLimiterOptions, Tool, ToolError, type ToolResultContentBlock, type TrustLevel, type TrustPosture, type TrustPostureInput, type TrustSource, UngatedCapabilityError, UnicodeNormalizer, type UnicodeNormalizerOptions, type UnresolvedToolSource, UsageAccumulator, type WiredEntity, type WiringRecordInput, type WithBlastRadius, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decideApproval, describeAction, describeCredential, effectiveToolNames, emitRunEvent, estimateTokens, evaluateBlastRadius, extractRawId, foldLayers, getPricingEntry, guardSessionDestruction, inferApiMode, isInside, isValidTaskId, loadProjectEnv, managedSettingsPathFor, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readManagedSettings, readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, setDiagnosticsSink, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
4593
+ export { Agent, AgentBuilder, type AgentBuilderDeps, AgentDefinition, type AgentDescription, AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type ApprovalDecision, type ApprovalInput, type ApprovalMode, type ApprovalOutcome, type ApprovalReason, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, type BlastRadiusDecision, type BlastRadiusInput, type BlastRadiusOutcome, type BlastRadiusReason, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, type BudgetTracker, BuiltinToolName, CloudOptions, ContextSettings, type CounterBudgetTrackerOptions, type CredentialInput, type CredentialReport, type CustomTool, type DecideOptions, type Decision, DecisionChecksumError, type DecisionSession, type DecisionTokens, type DeclaredAction, type DeclaredLayer, type DeepPartial, type DefineProviderOptions, type DefineToolSpec, type DiagnosticsSink, type DreamingSweepOptions, type DreamingSweepResult, type EffectiveToolCatalog, type EnvOptOut, type EnvReachabilityAudit, type EnvReachabilityInput, ErrorMetadata, EventBus, type EvictReason, GOAL_CONTINUATION_MARKER, type GenerateImageOptions, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, type GeneratedImage, GetAgentOptions, GetRunOptions, GoalEvent, type GoalLoopAgent, GoalOptions, GoalResult, InlineSkill, JobQueue, type JobQueueOptions, JudgeCredentialError, type JudgeResult, type KeepReason, type KeptArtifact, LayerOrderError, type LayerValues, ListAgentsOptions, ListResult, ListRunsOptions, type LiveAgentRegistry, LiveSessionError, type LiveSessionReason, LocalOptions, type ManagedSettings, McpServerConfig, Memory, MemoryId, type MemoryProvider, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, NoopMemoryProvider, type NormalizedJsonSchema, type OTelSpan, type PermissionAction, PermissionEngine, type PermissionEngineOptions, type PermissionFloorContext, type PermissionGate, type PermissionGateContext, type PermissionGateDecision, PermissionMode, PermissionPlugin, type PermissionPluginOptions, type PermissionRule, type PermissionRuleSet, Plugin, PluginsSettings, PreToolCallDecision, type Processor, Provider, type ProviderProfile, ProviderRoutingSettings, type ReadSessionMessagesOptions, type ReapPlan, type ReapPlanInput, type ReapableArtifact, type RetentionPolicy, RetentionPolicyError, Run, RunEventSink$1 as RunEventSink, RunResult, type SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, SOVEREIGN_ENV_KEYS, Security, type SecurityFloorInput, type SessionMessage, type SessionMessagePart, type SessionScope, type ShareGptMessage, type ShareGptTrajectory, SkillReadTool, SkillsSettings, type SovereignEnvKey, Squad, type SquadOptions, type SquadRun, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, type TelemetryHandle, Theokit, TheokitAgentError, type TheokitRequestOptions, TokenLimiter, type TokenLimiterOptions, Tool, ToolError, type ToolResultContentBlock, type TrustLevel, type TrustPosture, type TrustPostureInput, type TrustSource, UngatedCapabilityError, UnicodeNormalizer, type UnicodeNormalizerOptions, type UnresolvedToolSource, UsageAccumulator, type WiredEntity, type WiringRecordInput, type WithBlastRadius, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, computeCost, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decide, decideApproval, describeAction, describeCredential, effectiveToolNames, emitRunEvent, estimateTokens, evaluateBlastRadius, extractRawId, foldLayers, generateImage, getPricingEntry, guardSessionDestruction, inferApiMode, isInside, isValidTaskId, loadProjectEnv, managedSettingsPathFor, migrateSqliteToLance, mkMemoryId, normalizeSchema, normalizeUsage, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readManagedSettings, readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, setDiagnosticsSink, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
package/dist/index.js CHANGED
@@ -9,28 +9,28 @@ export { Workflow, agentStep, fn } from './chunk-4C37ELQL.js';
9
9
  import './chunk-PCPYTBVV.js';
10
10
  export { SqliteSessionStore } from './chunk-VFT63FJF.js';
11
11
  import './chunk-HY66GLM6.js';
12
- export { Cron } from './chunk-ATGSV4GS.js';
13
- import { MEMORY_EMBEDDING_ADAPTERS, resolveSessionDir, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-CG64VPPU.js';
14
- export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry, managedSettingsPathFor, readManagedSettings } from './chunk-CG64VPPU.js';
12
+ export { Cron } from './chunk-DLCYS5RI.js';
13
+ import { MEMORY_EMBEDDING_ADAPTERS, resolveSessionDir, DEFAULT_AGENTIC_MODEL_ID, Agent } from './chunk-NHD5IN3E.js';
14
+ export { Agent, AgentBuilder, Tool, ToolError, UsageAccumulator, computeCost, getPricingEntry, managedSettingsPathFor, readManagedSettings } from './chunk-NHD5IN3E.js';
15
+ import './chunk-2SFBB54R.js';
15
16
  import { configure, submit, list, get, cancel, subscribe } from './chunk-GEQLHBJM.js';
16
17
  export { emitRunEvent } from './chunk-GEQLHBJM.js';
17
- import './chunk-PSMWZYW6.js';
18
+ import './chunk-6WPNFZH3.js';
18
19
  import './chunk-3GQYMKVJ.js';
20
+ import { readSessionMessages } from './chunk-4E4D6H77.js';
19
21
  import './chunk-L5B7EWWH.js';
20
22
  import './chunk-ZUWVO442.js';
21
- import './chunk-2SFBB54R.js';
22
23
  import './chunk-TTXRNCXY.js';
23
24
  import './chunk-H73MEMQB.js';
24
25
  import './chunk-BH6M2DGV.js';
25
26
  import { resolveMemoryRoot } from './chunk-DB5RYCXX.js';
26
27
  import { FsSessionStore } from './chunk-P7B64NFK.js';
27
- import { discoverProviderPlugins, shouldUseFixtureMode, isFixtureApiKey, httpRequest, mapOllamaTransportError, readErrorResponseBody, mapOllamaHttpError } from './chunk-JRQJMZKY.js';
28
- export { inferApiMode, normalizeUsage } from './chunk-JRQJMZKY.js';
28
+ import { discoverProviderPlugins, shouldUseFixtureMode, isFixtureApiKey, httpRequest, mapOllamaTransportError, readErrorResponseBody, mapOllamaHttpError } from './chunk-MNE4633K.js';
29
+ export { inferApiMode, normalizeUsage } from './chunk-MNE4633K.js';
29
30
  import './chunk-OIOSY5G6.js';
30
31
  import './chunk-2XC6KDJM.js';
31
32
  import './chunk-7ACS6P5Z.js';
32
33
  import './chunk-24MGQDK3.js';
33
- import { readSessionMessages } from './chunk-4E4D6H77.js';
34
34
  import './chunk-HKCKOAIO.js';
35
35
  import './chunk-YUQNHLKN.js';
36
36
  import './chunk-S7IZEVXX.js';
@@ -65,15 +65,17 @@ import { CLAUDE_DIR_NAME, THEOKIT_DIR_LITERAL } from './chunk-PISZRLES.js';
65
65
  import './chunk-TIYQDJFK.js';
66
66
  import { estimateTokens, CHARS_PER_TOKEN } from './chunk-SZQFCHU6.js';
67
67
  export { estimateTokens } from './chunk-SZQFCHU6.js';
68
- import './chunk-CMDM4VF6.js';
68
+ import { trimTrailingSlashes } from './chunk-ICBNSAO4.js';
69
+ import './chunk-4XYCF5PA.js';
69
70
  import { parseModelId } from './chunk-R7WIIPUR.js';
70
- import './chunk-AQ23NII7.js';
71
- import { registerBuiltins, listProviders, getCatalogCapabilities, getProviderProfile } from './chunk-5L7S2VOL.js';
71
+ import './chunk-UNUGF36D.js';
72
+ import { registerBuiltins, listProviders, getCatalogCapabilities, getProviderProfile } from './chunk-A3T2A2WU.js';
72
73
  import './chunk-AGACYRJ2.js';
74
+ import './chunk-Z2UVCAYS.js';
73
75
  import './chunk-UNP4NCMZ.js';
74
76
  import './chunk-L2KC2G7H.js';
75
77
  import './chunk-5IUDICRK.js';
76
- import './chunk-Q7GYMXVC.js';
78
+ import { boundFetch } from './chunk-Q7GYMXVC.js';
77
79
  import { BudgetExceededError, ConfigurationError, TheokitAgentError, MemoryAdapterError, AuthenticationError } from './chunk-TNFOU6SB.js';
78
80
  export { AgentDisposedError, AgentRunError, AuthenticationError, BudgetExceededError, ConfigurationError, IntegrationNotConnectedError, InvalidTaskIdError, MemoryAdapterError, NetworkError, RateLimitError, TaskNotFoundError, TheokitAgentError, UnknownAgentError, UnsupportedBudgetOperationError, UnsupportedRunOperationError, UnsupportedTaskOperationError, isTransientError } from './chunk-TNFOU6SB.js';
79
81
  import { diag, redactSecrets, addPattern, resolveApiKey } from './chunk-3OY6H3I7.js';
@@ -554,6 +556,94 @@ function describeCredential(input) {
554
556
  fingerprint: createHash("sha256").update(secret).digest("hex").slice(0, 8)
555
557
  };
556
558
  }
559
+ var DecisionChecksumError = class extends TheokitAgentError {
560
+ constructor(modelPath, expected, actual) {
561
+ super(`decide: checksum mismatch for ${modelPath} (expected ${expected}, got ${actual})`, {
562
+ code: "decision_checksum_mismatch",
563
+ isRetryable: false
564
+ });
565
+ this.modelPath = modelPath;
566
+ this.expected = expected;
567
+ this.actual = actual;
568
+ }
569
+ modelPath;
570
+ expected;
571
+ actual;
572
+ name = "DecisionChecksumError";
573
+ };
574
+ var sessionCache = /* @__PURE__ */ new Map();
575
+ async function defaultLoadSession(model) {
576
+ const name = "onnxruntime-node";
577
+ let ort;
578
+ try {
579
+ ort = await import(
580
+ /* @vite-ignore */
581
+ name
582
+ );
583
+ } catch {
584
+ throw new Error("decide: install `onnxruntime-node` to run a local classifier");
585
+ }
586
+ const session = await ort.InferenceSession.create(model);
587
+ const tensor = (a) => new ort.Tensor("int64", BigInt64Array.from(a, BigInt), [1, a.length]);
588
+ return {
589
+ async run(t) {
590
+ const feeds = {
591
+ input_ids: tensor(t.inputIds),
592
+ attention_mask: tensor(t.attentionMask ?? t.inputIds.map(() => 1))
593
+ };
594
+ const out = await session.run(feeds);
595
+ const first = Object.values(out)[0];
596
+ if (!first) throw new Error("decide: model returned no output");
597
+ return Array.from(first.data, Number);
598
+ }
599
+ };
600
+ }
601
+ function softmax(logits) {
602
+ const max = Math.max(...logits);
603
+ const exps = logits.map((x) => Math.exp(x - max));
604
+ const sum = exps.reduce((a, b) => a + b, 0);
605
+ return exps.map((e) => e / sum);
606
+ }
607
+ async function decide(opts) {
608
+ if (opts.labels.length === 0) throw new Error("decide: labels must not be empty");
609
+ if (new Set(opts.labels).size !== opts.labels.length) {
610
+ throw new Error("decide: labels must be unique");
611
+ }
612
+ if (!/^[0-9a-f]{64}$/i.test(opts.sha256)) {
613
+ throw new Error("decide: sha256 must be 64 hex characters");
614
+ }
615
+ const bytes = await readFile(opts.modelPath);
616
+ const actual = createHash("sha256").update(bytes).digest("hex");
617
+ const expected = opts.sha256.toLowerCase();
618
+ if (actual !== expected) throw new DecisionChecksumError(opts.modelPath, expected, actual);
619
+ const load = () => (opts.loadSession ?? defaultLoadSession)(new Uint8Array(bytes));
620
+ let session;
621
+ if (opts.loadSession) {
622
+ session = await load();
623
+ } else {
624
+ let cached = sessionCache.get(actual);
625
+ if (!cached) {
626
+ cached = load();
627
+ sessionCache.set(actual, cached);
628
+ cached.catch(() => sessionCache.delete(actual));
629
+ }
630
+ session = await cached;
631
+ }
632
+ const logits = await session.run(await opts.tokenize(opts.text));
633
+ if (logits.length !== opts.labels.length) {
634
+ throw new Error(
635
+ `decide: model returned ${logits.length} scores for ${opts.labels.length} labels`
636
+ );
637
+ }
638
+ const probs = softmax(logits);
639
+ const scores = {};
640
+ let best = 0;
641
+ opts.labels.forEach((l, i) => {
642
+ scores[l] = probs[i];
643
+ if (probs[i] > probs[best]) best = i;
644
+ });
645
+ return { label: opts.labels[best], scores, source: "local-onnx", modelSha256: actual };
646
+ }
557
647
 
558
648
  // src/define-provider.ts
559
649
  function defineProvider(profile, opts) {
@@ -766,6 +856,87 @@ var EventBus = class {
766
856
  }
767
857
  };
768
858
 
859
+ // src/generate-image.ts
860
+ function sniffMime(b) {
861
+ const at = (i, ...v) => v.every((x, k) => b[i + k] === x);
862
+ if (at(0, 137, 80, 78, 71, 13, 10, 26, 10)) return "image/png";
863
+ if (at(0, 255, 216, 255)) return "image/jpeg";
864
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "image/webp";
865
+ return "application/octet-stream";
866
+ }
867
+ function parseSseLine(line) {
868
+ if (!line.startsWith("data:")) return void 0;
869
+ try {
870
+ return JSON.parse(line.slice(5));
871
+ } catch {
872
+ return void 0;
873
+ }
874
+ }
875
+ function imageFromSse(sse) {
876
+ for (const line of sse.split("\n")) {
877
+ const ev = parseSseLine(line);
878
+ const done = ev?.type === "response.output_item.done" && ev.item?.type === "image_generation_call";
879
+ if (done && ev?.item?.result) return ev.item.result;
880
+ }
881
+ return void 0;
882
+ }
883
+ async function assertOk(res) {
884
+ if (res.ok) return;
885
+ const text = await res.text().catch(() => "");
886
+ throw new Error(`generateImage: provider returned ${res.status} ${text.slice(0, 300)}`);
887
+ }
888
+ async function generateViaChatGpt(opts) {
889
+ const { codexFetch } = await import('./openai-chatgpt-ZFNZWT2L.js');
890
+ const base = trimTrailingSlashes(opts.baseUrl ?? "https://chatgpt.com/backend-api/codex");
891
+ const res = await (opts.fetch ?? codexFetch())(`${base}/responses`, {
892
+ method: "POST",
893
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
894
+ body: JSON.stringify({
895
+ model: opts.model ?? "gpt-5.4",
896
+ instructions: "Generate the requested image with the image_generation tool.",
897
+ input: [{ role: "user", content: [{ type: "input_text", text: opts.prompt }] }],
898
+ tools: [{ type: "image_generation" }],
899
+ tool_choice: { type: "image_generation" },
900
+ store: false,
901
+ stream: true
902
+ }),
903
+ signal: opts.signal
904
+ });
905
+ await assertOk(res);
906
+ const b64 = imageFromSse(await res.text());
907
+ if (b64 === void 0) throw new Error("generateImage: provider returned no image data");
908
+ return b64;
909
+ }
910
+ async function generateImage(opts) {
911
+ if (opts.route === "chatgpt") {
912
+ const image2 = new Uint8Array(Buffer.from(await generateViaChatGpt(opts), "base64"));
913
+ return { image: image2, mimeType: sniffMime(image2) };
914
+ }
915
+ const apiKey = opts.apiKey ?? process.env.OPENAI_API_KEY;
916
+ if (!apiKey) throw new Error("generateImage: no API key (pass apiKey or set OPENAI_API_KEY)");
917
+ const base = trimTrailingSlashes(opts.baseUrl ?? "https://api.openai.com/v1");
918
+ const body = {
919
+ model: opts.model ?? "gpt-image-1",
920
+ prompt: opts.prompt,
921
+ n: 1
922
+ };
923
+ if (opts.size !== void 0) body.size = opts.size;
924
+ const res = await boundFetch(opts.fetch)(`${base}/images/generations`, {
925
+ method: "POST",
926
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
927
+ body: JSON.stringify(body),
928
+ signal: opts.signal
929
+ });
930
+ await assertOk(res);
931
+ const json = await res.json();
932
+ const b64 = json.data?.[0]?.b64_json;
933
+ if (typeof b64 !== "string" || b64.length === 0) {
934
+ throw new Error("generateImage: provider returned no image data");
935
+ }
936
+ const image = new Uint8Array(Buffer.from(b64, "base64"));
937
+ return { image, mimeType: sniffMime(image) };
938
+ }
939
+
769
940
  // src/goal-loop.ts
770
941
  function runGoalLoop(agent, goal, options, depsOverride) {
771
942
  async function* wrap() {
@@ -1745,7 +1916,7 @@ function isBuiltAgent(m) {
1745
1916
  return typeof m.send === "function";
1746
1917
  }
1747
1918
  async function materialize(def, index) {
1748
- const { Agent: Agent2 } = await import('./agent-QRIFX2SY.js');
1919
+ const { Agent: Agent2 } = await import('./agent-FB56RAXD.js');
1749
1920
  return Agent2.create({
1750
1921
  // `AgentDefinition.model` admits the sentinel `'inherit'`, which is not a model id. Inheriting
1751
1922
  // here means "declare nothing and let the default apply" — forwarding the literal would create
@@ -2279,6 +2450,6 @@ function recordWiring(input) {
2279
2450
  return record;
2280
2451
  }
2281
2452
 
2282
- export { AgentFactory, Budget, EventBus, JobQueue, LayerOrderError, LiveSessionError, Memory, NoopMemoryProvider, PermissionEngine, PermissionPlugin, Plugin, Provider, RetentionPolicyError, SOVEREIGN_ENV_KEYS, Security, Skill, SkillReadTool, Squad, Task, Theokit, TokenLimiter, UngatedCapabilityError, UnicodeNormalizer, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decideApproval, describeAction, describeCredential, effectiveToolNames, evaluateBlastRadius, extractRawId, foldLayers, guardSessionDestruction, isInside, loadProjectEnv, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeSchema, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readSessionMessages2 as readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
2453
+ export { AgentFactory, Budget, DecisionChecksumError, EventBus, JobQueue, LayerOrderError, LiveSessionError, Memory, NoopMemoryProvider, PermissionEngine, PermissionPlugin, Plugin, Provider, RetentionPolicyError, SOVEREIGN_ENV_KEYS, Security, Skill, SkillReadTool, Squad, Task, Theokit, TokenLimiter, UngatedCapabilityError, UnicodeNormalizer, applyMode, applySecurityFloor, auditEnvReachability, chargeAndCheckThresholds, createCounterBudgetTracker, createTokenLimiter, createUnicodeNormalizer, decide, decideApproval, describeAction, describeCredential, effectiveToolNames, evaluateBlastRadius, extractRawId, foldLayers, generateImage, guardSessionDestruction, isInside, loadProjectEnv, migrateSqliteToLance2 as migrateSqliteToLance, mkMemoryId, normalizeSchema, parsePermissionRules, permissionFloorReason, planReaping, preflightCheck, readSessionMessages2 as readSessionMessages, recordWiring, resolveTrustPosture, runGoalLoop, scopedConversationId, sessionScopePrefix, toShareGptTrajectory, verifyLayerOrdering, withBlastRadius };
2283
2454
  //# sourceMappingURL=index.js.map
2284
2455
  //# sourceMappingURL=index.js.map