@lotagate/cli 0.1.25 → 0.1.27

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 (256) hide show
  1. package/README.md +5 -4
  2. package/bin/lotagate.mjs +50 -8
  3. package/dist/application/agent/agent-constants.d.ts +6 -0
  4. package/dist/application/agent/agent-constants.js +1 -0
  5. package/dist/application/agent/agent-session-store-registry.d.ts +16 -0
  6. package/dist/application/agent/agent-session-store-registry.js +1 -0
  7. package/dist/application/agent/agent-session-store.d.ts +4 -0
  8. package/dist/application/agent/agent-session-store.js +5 -5
  9. package/dist/application/agent/bounded-text-accumulator.d.ts +15 -0
  10. package/dist/application/agent/bounded-text-accumulator.js +1 -0
  11. package/dist/application/agent/capability-profile.d.ts +0 -38
  12. package/dist/application/agent/capability-profile.js +0 -1
  13. package/dist/application/agent/cli-agent-execution-service.d.ts +23 -13
  14. package/dist/application/agent/cli-agent-execution-service.js +1 -1
  15. package/dist/application/agent/cli-agent-preparation-cache.d.ts +39 -0
  16. package/dist/application/agent/cli-agent-preparation-cache.js +1 -0
  17. package/dist/application/agent/context-compaction.d.ts +1 -0
  18. package/dist/application/agent/context-compaction.js +7 -6
  19. package/dist/application/agent/context-token-cache.d.ts +21 -0
  20. package/dist/application/agent/context-token-cache.js +4 -0
  21. package/dist/application/agent/context-usage-service.d.ts +52 -0
  22. package/dist/application/agent/context-usage-service.js +1 -0
  23. package/dist/application/agent/continuation-checkpoint.d.ts +15 -0
  24. package/dist/application/agent/continuation-checkpoint.js +2 -0
  25. package/dist/application/agent/interactive-agent-guidance.d.ts +3 -3
  26. package/dist/application/agent/interactive-agent-guidance.js +2 -2
  27. package/dist/application/chat/pending-attachment-store.d.ts +5 -2
  28. package/dist/application/chat/pending-attachment-store.js +1 -1
  29. package/dist/application/commands/application-command-executor.js +2 -2
  30. package/dist/application/commands/cli-command-services.d.ts +1 -1
  31. package/dist/application/commands/cli-command-services.js +31 -31
  32. package/dist/application/commands/command-catalog.js +1 -1
  33. package/dist/application/commands/goal-command-handlers.js +6 -6
  34. package/dist/application/commands/media-command-handlers.js +7 -6
  35. package/dist/application/commands/memory-command-handler.d.ts +1 -1
  36. package/dist/application/commands/memory-command-handler.js +11 -11
  37. package/dist/application/commands/runtime-command-handlers.js +11 -11
  38. package/dist/application/extensions/plugin-contribution-registry.js +1 -1
  39. package/dist/application/intent/completion-gate.d.ts +2 -5
  40. package/dist/application/intent/completion-gate.js +1 -1
  41. package/dist/application/intent/evidence-ledger.d.ts +2 -1
  42. package/dist/application/intent/evidence-recording-tool-executor.js +1 -1
  43. package/dist/application/intent/intent-compiler.js +2 -2
  44. package/dist/application/lifecycle/operation-registry.d.ts +11 -0
  45. package/dist/application/lifecycle/operation-registry.js +1 -0
  46. package/dist/application/memory/memory-extractor.js +2 -2
  47. package/dist/application/model/cached-model-catalog.d.ts +7 -1
  48. package/dist/application/model/cached-model-catalog.js +1 -1
  49. package/dist/application/model/model-catalog-service.js +1 -1
  50. package/dist/application/model/model-context-window.js +1 -1
  51. package/dist/application/model/model-response-retry.d.ts +7 -1
  52. package/dist/application/model/model-response-retry.js +1 -1
  53. package/dist/application/orchestration/cli-subagent-service.d.ts +4 -0
  54. package/dist/application/orchestration/cli-subagent-service.js +3 -3
  55. package/dist/application/orchestration/cli-turn-event-projector.js +1 -1
  56. package/dist/application/orchestration/cli-turn-events.d.ts +0 -7
  57. package/dist/application/orchestration/goal-input.d.ts +1 -1
  58. package/dist/application/orchestration/goal-input.js +1 -1
  59. package/dist/application/orchestration/headless-agent-turn.d.ts +1 -0
  60. package/dist/application/orchestration/headless-agent-turn.js +3 -3
  61. package/dist/application/orchestration/orchestration-constants.d.ts +3 -0
  62. package/dist/application/orchestration/orchestration-constants.js +1 -0
  63. package/dist/application/orchestration/subagent-handoff.js +3 -3
  64. package/dist/application/project-intelligence/project-intelligence-constants.d.ts +56 -0
  65. package/dist/application/project-intelligence/project-intelligence-constants.js +1 -0
  66. package/dist/application/project-intelligence/project-intelligence-service.js +1 -1
  67. package/dist/application/protocol/browser-host-tool-executor.d.ts +13 -3
  68. package/dist/application/protocol/browser-host-tool-executor.js +2 -2
  69. package/dist/application/protocol/computer-host-tool-executor.d.ts +3 -0
  70. package/dist/application/protocol/computer-host-tool-executor.js +2 -2
  71. package/dist/application/protocol/desktop-agent-command.d.ts +2 -2
  72. package/dist/application/protocol/desktop-agent-command.js +1 -3
  73. package/dist/application/protocol/desktop-agent-contracts.d.ts +34 -0
  74. package/dist/application/protocol/desktop-agent-contracts.js +1 -0
  75. package/dist/application/protocol/desktop-agent-helpers.d.ts +5 -0
  76. package/dist/application/protocol/desktop-agent-helpers.js +1 -0
  77. package/dist/application/protocol/desktop-agent-request-parser.d.ts +31 -6
  78. package/dist/application/protocol/desktop-agent-request-parser.js +1 -1
  79. package/dist/application/protocol/desktop-approval-broker.d.ts +14 -4
  80. package/dist/application/protocol/desktop-approval-broker.js +1 -1
  81. package/dist/application/protocol/desktop-attachment-store.d.ts +19 -2
  82. package/dist/application/protocol/desktop-attachment-store.js +1 -1
  83. package/dist/application/protocol/desktop-execution-policy.d.ts +2 -0
  84. package/dist/application/protocol/desktop-execution-policy.js +1 -1
  85. package/dist/application/protocol/desktop-host-bridge.d.ts +33 -0
  86. package/dist/application/protocol/desktop-host-bridge.js +1 -0
  87. package/dist/application/protocol/desktop-host-capabilities.d.ts +12 -0
  88. package/dist/application/protocol/desktop-host-capabilities.js +1 -0
  89. package/dist/application/protocol/desktop-host-tool-executor.d.ts +15 -2
  90. package/dist/application/protocol/desktop-host-tool-executor.js +2 -2
  91. package/dist/application/protocol/desktop-intent-event-writer.js +1 -1
  92. package/dist/application/protocol/desktop-protocol-helpers.js +1 -1
  93. package/dist/application/protocol/desktop-title-generator.d.ts +5 -0
  94. package/dist/application/protocol/desktop-title-generator.js +3 -0
  95. package/dist/application/protocol/json-line-writer.d.ts +24 -2
  96. package/dist/application/protocol/json-line-writer.js +2 -2
  97. package/dist/application/protocol/jsonl-agent-command.d.ts +1 -1
  98. package/dist/application/protocol/jsonl-agent-command.js +2 -2
  99. package/dist/application/protocol/jsonl-protocol.d.ts +1 -1
  100. package/dist/application/protocol/jsonl-protocol.js +2 -2
  101. package/dist/application/security/desktop-tool-scope-policy.js +1 -1
  102. package/dist/application/security/tool-action-risk-analyzer.js +1 -1
  103. package/dist/application/security/tool-approval-service.d.ts +9 -3
  104. package/dist/application/security/tool-approval-service.js +1 -1
  105. package/dist/application/security/tool-policy-registry.d.ts +20 -0
  106. package/dist/application/security/tool-policy-registry.js +1 -0
  107. package/dist/application/security/tool-risk-classifier.d.ts +2 -1
  108. package/dist/application/security/tool-risk-classifier.js +1 -1
  109. package/dist/application/security/workspace-permission-policy.js +1 -1
  110. package/dist/application/workspace/session-execution-workspace.d.ts +2 -2
  111. package/dist/application/workspace/session-execution-workspace.js +3 -3
  112. package/dist/application/workspace/workspace-constants.d.ts +17 -0
  113. package/dist/application/workspace/workspace-constants.js +1 -0
  114. package/dist/application/workspace/workspace-file-index.d.ts +2 -3
  115. package/dist/application/workspace/workspace-file-index.js +1 -1
  116. package/dist/application/workspace/workspace-instruction-loader.js +1 -1
  117. package/dist/bootstrap/composition-root.d.ts +1 -0
  118. package/dist/bootstrap/runtime-factory.d.ts +5 -0
  119. package/dist/bootstrap/runtime-factory.js +1 -1
  120. package/dist/domain/auth/auth-profile.d.ts +1 -0
  121. package/dist/domain/auth/auth-profile.js +1 -1
  122. package/dist/domain/errors/cli-error.js +1 -1
  123. package/dist/domain/extensions/extension-constants.d.ts +1 -0
  124. package/dist/domain/extensions/extension-constants.js +1 -0
  125. package/dist/domain/extensions/host-tool-plugin-ids.d.ts +0 -4
  126. package/dist/domain/extensions/host-tool-plugin-ids.js +1 -1
  127. package/dist/domain/extensions/plugin-manifest.js +1 -1
  128. package/dist/domain/intent/intent-contract.d.ts +0 -8
  129. package/dist/domain/intent/intent-contract.js +1 -1
  130. package/dist/domain/media/gateway-media-contract.js +1 -1
  131. package/dist/domain/media/media-constants.d.ts +3 -0
  132. package/dist/domain/media/media-constants.js +1 -0
  133. package/dist/domain/media/media-execution-policy.js +1 -1
  134. package/dist/domain/memory/memory-constants.d.ts +3 -0
  135. package/dist/domain/memory/memory-constants.js +1 -0
  136. package/dist/domain/memory/memory-search.js +2 -2
  137. package/dist/domain/orchestration/goal.d.ts +0 -1
  138. package/dist/domain/orchestration/goal.js +1 -1
  139. package/dist/domain/orchestration/work-plan.d.ts +0 -62
  140. package/dist/domain/orchestration/work-plan.js +0 -1
  141. package/dist/domain/runtime/assistant-stream-text.d.ts +11 -0
  142. package/dist/domain/runtime/assistant-stream-text.js +1 -0
  143. package/dist/domain/runtime/gateway-request-budget.d.ts +19 -0
  144. package/dist/domain/runtime/gateway-request-budget.js +1 -0
  145. package/dist/domain/runtime/resource-limits.d.ts +26 -0
  146. package/dist/domain/runtime/resource-limits.js +1 -1
  147. package/dist/domain/session/attachment.d.ts +2 -0
  148. package/dist/domain/workspace/workspace-settings.d.ts +2 -0
  149. package/dist/domain/workspace/workspace-settings.js +1 -1
  150. package/dist/infrastructure/agent-sdk/model-response-metrics.d.ts +7 -0
  151. package/dist/infrastructure/agent-sdk/model-response-metrics.js +1 -0
  152. package/dist/infrastructure/agent-sdk/model-tool-name-mapper.js +1 -1
  153. package/dist/infrastructure/agent-sdk/sdk-constants.d.ts +2 -0
  154. package/dist/infrastructure/agent-sdk/sdk-constants.js +1 -0
  155. package/dist/infrastructure/agent-sdk/tool-calling-model-client.js +1 -1
  156. package/dist/infrastructure/cache/cache-policy.d.ts +2 -0
  157. package/dist/infrastructure/cache/cache-policy.js +1 -1
  158. package/dist/infrastructure/cache/file-cache-store.d.ts +13 -0
  159. package/dist/infrastructure/cache/file-cache-store.js +2 -2
  160. package/dist/infrastructure/clipboard/clipboard-adapter-factory.js +1 -1
  161. package/dist/infrastructure/clipboard/clipboard-constants.d.ts +1 -0
  162. package/dist/infrastructure/clipboard/clipboard-constants.js +1 -0
  163. package/dist/infrastructure/clipboard/clipboard-process.d.ts +20 -0
  164. package/dist/infrastructure/clipboard/clipboard-process.js +1 -0
  165. package/dist/infrastructure/clipboard/clipboard-text-adapter-factory.js +1 -1
  166. package/dist/infrastructure/clipboard/image-normalizer.js +1 -1
  167. package/dist/infrastructure/clipboard/windows-clipboard-adapter.js +1 -1
  168. package/dist/infrastructure/clipboard/windows-clipboard-text-adapter.js +1 -1
  169. package/dist/infrastructure/credentials/encrypted-file-credential-store.js +2 -2
  170. package/dist/infrastructure/credentials/secret-input.d.ts +1 -1
  171. package/dist/infrastructure/credentials/secret-input.js +3 -3
  172. package/dist/infrastructure/extensions/extensions-constants.d.ts +6 -0
  173. package/dist/infrastructure/extensions/extensions-constants.js +1 -0
  174. package/dist/infrastructure/extensions/mcp-runtime.d.ts +9 -0
  175. package/dist/infrastructure/extensions/mcp-runtime.js +1 -1
  176. package/dist/infrastructure/extensions/plugin-agent-discovery.d.ts +3 -1
  177. package/dist/infrastructure/extensions/plugin-agent-discovery.js +1 -1
  178. package/dist/infrastructure/extensions/plugin-manager.js +2 -2
  179. package/dist/infrastructure/extensions/skill-manager.js +2 -2
  180. package/dist/infrastructure/extensions/skill-tool-executor.d.ts +3 -1
  181. package/dist/infrastructure/extensions/skill-tool-executor.js +2 -2
  182. package/dist/infrastructure/filesystem/atomic-file-store.d.ts +11 -0
  183. package/dist/infrastructure/filesystem/atomic-file-store.js +1 -1
  184. package/dist/infrastructure/filesystem/filesystem-constants.d.ts +8 -0
  185. package/dist/infrastructure/filesystem/filesystem-constants.js +1 -0
  186. package/dist/infrastructure/filesystem/local-filesystem-tool-executor.d.ts +3 -0
  187. package/dist/infrastructure/filesystem/local-filesystem-tool-executor.js +3 -3
  188. package/dist/infrastructure/logging/daily-rotating-file-writer.d.ts +1 -1
  189. package/dist/infrastructure/logging/daily-rotating-file-writer.js +2 -2
  190. package/dist/infrastructure/logging/log-redactor.js +1 -1
  191. package/dist/infrastructure/logging/logging-constants.d.ts +3 -0
  192. package/dist/infrastructure/logging/logging-constants.js +1 -0
  193. package/dist/infrastructure/logging/structured-logger.d.ts +1 -1
  194. package/dist/infrastructure/logging/structured-logger.js +2 -2
  195. package/dist/infrastructure/observability/tool-execution-logger.d.ts +11 -0
  196. package/dist/infrastructure/observability/tool-execution-logger.js +1 -0
  197. package/dist/infrastructure/platform/host-platform.d.ts +2 -0
  198. package/dist/infrastructure/platform/host-platform.js +1 -1
  199. package/dist/infrastructure/platform/host-process.d.ts +3 -1
  200. package/dist/infrastructure/platform/host-process.js +1 -1
  201. package/dist/infrastructure/platform/platform-constants.d.ts +4 -0
  202. package/dist/infrastructure/platform/platform-constants.js +1 -0
  203. package/dist/infrastructure/platform/process-identity.d.ts +8 -0
  204. package/dist/infrastructure/platform/process-identity.js +1 -0
  205. package/dist/infrastructure/platform/read-only-executable.d.ts +2 -1
  206. package/dist/infrastructure/platform/read-only-executable.js +1 -1
  207. package/dist/infrastructure/sdk/lotagate-client-factory.js +1 -1
  208. package/dist/infrastructure/sdk/sdk-media-gateway-client.d.ts +4 -0
  209. package/dist/infrastructure/sdk/sdk-media-gateway-client.js +1 -1
  210. package/dist/infrastructure/sessions/file-session-store.d.ts +11 -0
  211. package/dist/infrastructure/sessions/file-session-store.js +4 -4
  212. package/dist/infrastructure/sessions/session-constants.d.ts +3 -0
  213. package/dist/infrastructure/sessions/session-constants.js +1 -0
  214. package/dist/infrastructure/sessions/session-index.js +3 -3
  215. package/dist/infrastructure/sessions/session-journal-health.d.ts +7 -0
  216. package/dist/infrastructure/sessions/session-journal-health.js +1 -0
  217. package/dist/infrastructure/shell/shell-tool-executor.d.ts +5 -1
  218. package/dist/infrastructure/shell/shell-tool-executor.js +2 -2
  219. package/dist/infrastructure/tokens/tiktoken-token-estimator.js +1 -1
  220. package/dist/infrastructure/tokens/token-constants.d.ts +1 -0
  221. package/dist/infrastructure/tokens/token-constants.js +1 -0
  222. package/dist/infrastructure/workspace/workspace-settings-store.d.ts +1 -0
  223. package/dist/infrastructure/workspace/workspace-settings-store.js +4 -4
  224. package/dist/main.js +3 -3
  225. package/dist/ports/media-gateway-client.d.ts +6 -0
  226. package/dist/ports/session-store.d.ts +1 -0
  227. package/dist/presentation/tui/ink/components/composer.js +4 -4
  228. package/dist/presentation/tui/ink/components/transcript.d.ts +1 -0
  229. package/dist/presentation/tui/ink/components/transcript.js +5 -5
  230. package/dist/presentation/tui/ink/tui-bridge.d.ts +2 -2
  231. package/dist/presentation/tui/ink/tui-bridge.js +1 -1
  232. package/dist/presentation/tui/tui-agent-turn-controller.d.ts +45 -0
  233. package/dist/presentation/tui/tui-agent-turn-controller.js +1 -0
  234. package/dist/presentation/tui/tui-application-contract.d.ts +1 -0
  235. package/dist/presentation/tui/tui-application.d.ts +3 -4
  236. package/dist/presentation/tui/tui-application.js +3 -3
  237. package/dist/presentation/tui/tui-clipboard-paste-handlers.d.ts +2 -2
  238. package/dist/presentation/tui/tui-clipboard-paste-handlers.js +1 -1
  239. package/dist/presentation/tui/tui-command-executor.js +3 -3
  240. package/dist/presentation/tui/tui-context-compaction.d.ts +4 -1
  241. package/dist/presentation/tui/tui-context-compaction.js +1 -1
  242. package/dist/presentation/tui/tui-context-service.d.ts +2 -34
  243. package/dist/presentation/tui/tui-context-service.js +1 -2
  244. package/dist/presentation/tui/tui-initial-model.js +1 -1
  245. package/dist/presentation/tui/tui-tool-approval.d.ts +1 -1
  246. package/dist/presentation/tui/tui-tool-approval.js +1 -1
  247. package/dist/version.d.ts +1 -1
  248. package/dist/version.js +1 -1
  249. package/native-targets.mjs +1 -1
  250. package/package.json +9 -10
  251. package/scripts/install-native.mjs +5 -13
  252. package/bin/lotagate.exe +0 -1
  253. package/dist/application/protocol/document-host-tool-definitions.d.ts +0 -4
  254. package/dist/application/protocol/document-host-tool-definitions.js +0 -1
  255. package/dist/application/protocol/document-host-tool-executor.d.ts +0 -49
  256. package/dist/application/protocol/document-host-tool-executor.js +0 -2
@@ -1 +1 @@
1
- import{CliError as I}from"../errors/cli-error.js";import{CLI_ERROR_CODES as l}from"../errors/error-codes.js";const c=1e3,s=1e6,u={imagePromptCharacters:32e3,imageCount:16,imageEditFileBytes:47*s,imageEditMaskBytes:4*s,imageEditTotalBytes:128*s,audioUploadBytes:50*s,speechInputCharacters:4096,speechInstructionsCharacters:4096,speechVoiceCharacters:64,audioPromptCharacters:4096,transcriptionLanguageCharacters:10},M=50*1024*1024;function O(e,i,t){v(t),(e==="image.generate"||e==="image.edit")&&C(i,t),e==="image.edit"&&E(t),e==="audio.speech"&&_(i,t),e==="audio.transcribe"&&h(t,!0),e==="audio.translate"&&h(t,!1),e==="video.generate"&&$(t)}function T(e){if(e.length===0)throw n("`--image` requires at least one workspace image path.");if(e.length>u.imageCount)throw n(`Image edits support at most ${u.imageCount} input images.`)}function A(e,i,t){if(!(e>0&&e<=i))throw n(`${t} must be between 1 byte and ${f(i)}.`)}function q(e){if(!(e<=u.imageEditTotalBytes))throw n(`Image edit uploads must not exceed ${f(u.imageEditTotalBytes)} in total.`)}function f(e){return e>=s?`${e/s} MB`:e>=c?`${e/c} KB`:`${e} bytes`}function v(e){const i=r(e,"out");if(p(e,"force")&&i===void 0)throw n("`--force` is only valid with `--out`.")}function C(e,i){d(g(e,"image"),u.imagePromptCharacters,"Image prompt");const t=w(i,"n");if(t!==void 0&&(t<1||t>u.imageCount))throw n(`--n must be an integer between 1 and ${u.imageCount}.`);if(t!==void 0&&t>1&&r(i,"out")!==void 0)throw n("--out can only be used when exactly one image artifact is requested. Use --out-dir instead.");const o=r(i,"size");if(o!==void 0&&o!=="auto"&&!/^\d{2,4}x\d{2,4}$/u.test(o))throw n("--size must be `auto` or WIDTHxHEIGHT.");o!==void 0&&o!=="auto"&&S(o);const a=r(i,"output-format"),m=w(i,"output-compression");if(m!==void 0&&(m<0||m>100))throw n("--output-compression must be an integer between 0 and 100.");if(m!==void 0&&a!=="jpeg"&&a!=="webp")throw n("--output-compression requires --output-format jpeg or webp.");d(r(i,"moderation"),64,"Moderation value"),d(r(i,"user"),255,"User value")}function E(e){if(r(e,"image")===void 0)throw n("Missing required option --image.")}function _(e,i){d(g(e,"speech"),u.speechInputCharacters,"Speech input"),d(x(i,"voice"),u.speechVoiceCharacters,"Voice"),d(r(i,"instructions"),u.speechInstructionsCharacters,"Speech instructions");const t=b(i,"speed");if(t!==void 0&&(t<.25||t>4))throw n("--speed must be between 0.25 and 4.")}function h(e,i){d(r(e,"prompt"),u.audioPromptCharacters,"Audio prompt");const t=b(e,"temperature");if(t!==void 0&&(t<0||t>1))throw n("--temperature must be between 0 and 1.");if(i&&(d(r(e,"language"),u.transcriptionLanguageCharacters,"Language code"),r(e,"timestamp-granularities")!==void 0&&r(e,"response-format")!=="verbose_json"))throw n("--timestamp-granularities requires --response-format verbose_json.")}function $(e){if(p(e,"no-wait")&&(r(e,"out")!==void 0||r(e,"out-dir")!==void 0||p(e,"force")))throw n("--no-wait cannot be combined with output options. Use video download after the operation completes.")}function S(e){const[i,t]=e.split("x"),o=Number(i),a=Number(t);if(!Number.isSafeInteger(o)||!Number.isSafeInteger(a)||o<1||a<1||o>4096||a>4096||Math.max(o,a)/Math.min(o,a)>3||o%16!==0||a%16!==0)throw n("--size must use positive dimensions up to 4096px, a maximum 3:1 aspect ratio, and multiples of 16.")}function g(e,i){const t=e.join(" ").trim();if(t.length===0)throw n(`A prompt is required for ${i}.`);return t}function x(e,i){const t=r(e,i);if(t===void 0)throw n(`Missing required option --${i}.`);return t}function d(e,i,t){if(e!==void 0&&e.length>i)throw n(`${t} must not exceed ${i} characters.`)}function w(e,i){const t=r(e,i);if(t!==void 0){if(!/^\d+$/u.test(t)||!Number.isSafeInteger(Number(t)))throw n(`--${i} must be an integer.`);return Number(t)}}function b(e,i){const t=r(e,i);if(t===void 0)return;const o=Number(t);if(!Number.isFinite(o))throw n(`--${i} must be a finite number.`);return o}function r(e,i){const t=e.get(i);return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function p(e,i){return e.get(i)===!0||e.get(i)==="true"}function n(e){return new I(l.INVALID_ARGUMENT,e,{category:"media",userMessage:e})}export{u as GATEWAY_MEDIA_LIMITS,M as SDK_BINARY_MEDIA_RESPONSE_BYTES,f as formatByteLimit,T as validateImageEditInputCount,q as validateImageEditTotalSize,O as validateMediaCommandOptions,A as validateUploadSize};
1
+ import{CliError as I}from"../errors/cli-error.js";import{CLI_ERROR_CODES as l}from"../errors/error-codes.js";const p=1e3,s=1e6,u={imagePromptCharacters:32e3,imageCount:16,imageEditFileBytes:47*s,imageEditMaskBytes:4*s,imageEditTotalBytes:128*s,audioUploadBytes:50*s,speechInputCharacters:4096,speechInstructionsCharacters:4096,speechVoiceCharacters:64,audioPromptCharacters:4096,transcriptionLanguageCharacters:10},M=50*1024*1024;function O(e,t,i){v(i),(e==="image.generate"||e==="image.edit")&&C(t,i),e==="image.edit"&&E(i),e==="audio.speech"&&_(t,i),e==="audio.transcribe"&&h(i,!0),e==="audio.translate"&&h(i,!1),e==="video.generate"&&$(i)}function T(e){if(e.length===0)throw n("`--image` requires at least one workspace image path.");if(e.length>u.imageCount)throw n(`Image edits support at most ${u.imageCount} input images.`)}function A(e,t,i){if(!(e>0&&e<=t))throw n(`${i} must be between 1 byte and ${f(t)}.`)}function q(e){if(!(e<=u.imageEditTotalBytes))throw n(`Image edit uploads must not exceed ${f(u.imageEditTotalBytes)} in total.`)}function f(e){return e>=s?`${e/s} MB`:e>=p?`${e/p} KB`:`${e} bytes`}function v(e){const t=r(e,"out");if(c(e,"force")&&t===void 0)throw n("`--force` is only valid with `--out`.")}function C(e,t){d(w(e,"image"),u.imagePromptCharacters,"Image prompt");const i=g(t,"n");if(i!==void 0&&(i<1||i>u.imageCount))throw n(`--n must be an integer between 1 and ${u.imageCount}.`);if(i!==void 0&&i>1&&r(t,"out")!==void 0)throw n("--out can only be used when exactly one image artifact is requested. Use --out-dir instead.");const o=r(t,"size");if(o!==void 0&&o!=="auto"&&!/^\d{2,4}x\d{2,4}$/u.test(o))throw n("--size must be `auto` or WIDTHxHEIGHT.");o!==void 0&&o!=="auto"&&S(o);const a=r(t,"output-format"),m=g(t,"output-compression");if(m!==void 0&&(m<0||m>100))throw n("--output-compression must be an integer between 0 and 100.");if(m!==void 0&&a!=="jpeg"&&a!=="webp")throw n("--output-compression requires --output-format jpeg or webp.");d(r(t,"moderation"),64,"Moderation value"),d(r(t,"user"),255,"User value")}function E(e){if(r(e,"image")===void 0)throw n("Missing required option --image.")}function _(e,t){d(w(e,"speech"),u.speechInputCharacters,"Speech input"),d(x(t,"voice"),u.speechVoiceCharacters,"Voice"),d(r(t,"instructions"),u.speechInstructionsCharacters,"Speech instructions");const i=r(t,"stream-format");if(i!==void 0&&i!=="audio"&&i!=="sse")throw n("--stream-format must be either `audio` or `sse`.");if(i==="sse"&&(r(t,"out")!==void 0||r(t,"out-dir")!==void 0||c(t,"force")))throw n("--stream-format sse cannot be combined with output file options.");const o=b(t,"speed");if(o!==void 0&&(o<.25||o>4))throw n("--speed must be between 0.25 and 4.")}function h(e,t){d(r(e,"prompt"),u.audioPromptCharacters,"Audio prompt");const i=b(e,"temperature");if(i!==void 0&&(i<0||i>1))throw n("--temperature must be between 0 and 1.");if(t&&(d(r(e,"language"),u.transcriptionLanguageCharacters,"Language code"),r(e,"timestamp-granularities")!==void 0&&r(e,"response-format")!=="verbose_json"))throw n("--timestamp-granularities requires --response-format verbose_json.")}function $(e){if(c(e,"no-wait")&&(r(e,"out")!==void 0||r(e,"out-dir")!==void 0||c(e,"force")))throw n("--no-wait cannot be combined with output options. Use video download after the operation completes.")}function S(e){const[t,i]=e.split("x"),o=Number(t),a=Number(i);if(!Number.isSafeInteger(o)||!Number.isSafeInteger(a)||o<1||a<1||o>4096||a>4096||Math.max(o,a)/Math.min(o,a)>3||o%16!==0||a%16!==0)throw n("--size must use positive dimensions up to 4096px, a maximum 3:1 aspect ratio, and multiples of 16.")}function w(e,t){const i=e.join(" ").trim();if(i.length===0)throw n(`A prompt is required for ${t}.`);return i}function x(e,t){const i=r(e,t);if(i===void 0)throw n(`Missing required option --${t}.`);return i}function d(e,t,i){if(e!==void 0&&e.length>t)throw n(`${i} must not exceed ${t} characters.`)}function g(e,t){const i=r(e,t);if(i!==void 0){if(!/^\d+$/u.test(i)||!Number.isSafeInteger(Number(i)))throw n(`--${t} must be an integer.`);return Number(i)}}function b(e,t){const i=r(e,t);if(i===void 0)return;const o=Number(i);if(!Number.isFinite(o))throw n(`--${t} must be a finite number.`);return o}function r(e,t){const i=e.get(t);return typeof i=="string"&&i.trim().length>0?i.trim():void 0}function c(e,t){return e.get(t)===!0||e.get(t)==="true"}function n(e){return new I(l.INVALID_ARGUMENT,e,{category:"media",userMessage:e})}export{u as GATEWAY_MEDIA_LIMITS,M as SDK_BINARY_MEDIA_RESPONSE_BYTES,f as formatByteLimit,T as validateImageEditInputCount,q as validateImageEditTotalSize,O as validateMediaCommandOptions,A as validateUploadSize};
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_VIDEO_POLL_INTERVAL_MS = 5000;
2
+ export declare const DEFAULT_VIDEO_WAIT_TIMEOUT_MS: number;
3
+ export declare const DEFAULT_MEDIA_DOWNLOAD_TIMEOUT_MS = 60000;
@@ -0,0 +1 @@
1
+ const _=5e3,E=12e5,T=6e4;export{T as DEFAULT_MEDIA_DOWNLOAD_TIMEOUT_MS,_ as DEFAULT_VIDEO_POLL_INTERVAL_MS,E as DEFAULT_VIDEO_WAIT_TIMEOUT_MS};
@@ -1 +1 @@
1
- import{CliError as E}from"../errors/cli-error.js";import{CLI_ERROR_CODES as I}from"../errors/error-codes.js";const O=5e3,n=1200*1e3,A=6e4;function M(t=process.env){const _=T(t,"LOTAGATE_VIDEO_POLL_INTERVAL_MS",O),o=T(t,"LOTAGATE_VIDEO_WAIT_TIMEOUT_MS",n);if(o<_)throw r("LOTAGATE_VIDEO_WAIT_TIMEOUT_MS must not be smaller than LOTAGATE_VIDEO_POLL_INTERVAL_MS.");return{videoPollIntervalMs:_,videoWaitTimeoutMs:o,downloadTimeoutMs:T(t,"LOTAGATE_MEDIA_DOWNLOAD_TIMEOUT_MS",A)}}function T(t,_,o){const e=t[_];if(e===void 0||e.trim().length===0)return o;if(!/^\d+$/u.test(e))throw r(`${_} must be a positive integer.`);const i=Number(e);if(!Number.isSafeInteger(i)||i<=0)throw r(`${_} must be a positive integer.`);return i}function r(t){return new E(I.CONFIG_SCHEMA_INVALID,t,{category:"config",userMessage:t})}export{M as resolveMediaExecutionPolicy};
1
+ import{CliError as E}from"../errors/cli-error.js";import{CLI_ERROR_CODES as I}from"../errors/error-codes.js";import{DEFAULT_MEDIA_DOWNLOAD_TIMEOUT_MS as O,DEFAULT_VIDEO_POLL_INTERVAL_MS as A,DEFAULT_VIDEO_WAIT_TIMEOUT_MS as n}from"./media-constants.js";function D(t=process.env){const _=r(t,"LOTAGATE_VIDEO_POLL_INTERVAL_MS",A),o=r(t,"LOTAGATE_VIDEO_WAIT_TIMEOUT_MS",n);if(o<_)throw T("LOTAGATE_VIDEO_WAIT_TIMEOUT_MS must not be smaller than LOTAGATE_VIDEO_POLL_INTERVAL_MS.");return{videoPollIntervalMs:_,videoWaitTimeoutMs:o,downloadTimeoutMs:r(t,"LOTAGATE_MEDIA_DOWNLOAD_TIMEOUT_MS",O)}}function r(t,_,o){const e=t[_];if(e===void 0||e.trim().length===0)return o;if(!/^\d+$/u.test(e))throw T(`${_} must be a positive integer.`);const i=Number(e);if(!Number.isSafeInteger(i)||i<=0)throw T(`${_} must be a positive integer.`);return i}function T(t){return new E(I.CONFIG_SCHEMA_INVALID,t,{category:"config",userMessage:t})}export{D as resolveMediaExecutionPolicy};
@@ -0,0 +1,3 @@
1
+ export declare const SEARCH_TOKEN_MIN_LENGTH = 2;
2
+ export declare const BM25_K1 = 1.2;
3
+ export declare const BM25_B = 0.75;
@@ -0,0 +1 @@
1
+ const o=2,t=1.2,_=.75;export{_ as BM25_B,t as BM25_K1,o as SEARCH_TOKEN_MIN_LENGTH};
@@ -1,2 +1,2 @@
1
- const _=2,x=1.2,S=.75;function b(e){const n=new Map,c={};let u=0;for(const r of e){const t=new Map;for(const s of h(r))t.set(s,(t.get(s)??0)+1);const o=Object.fromEntries(t.entries()),i=Object.values(o).reduce((s,m)=>s+m,0);c[r.id]={id:r.id,termFrequency:o,length:i},u+=i;for(const s of t.keys()){const m=n.get(s)??new Set;m.add(r.id),n.set(s,m)}}const a=Object.fromEntries([...n.entries()].map(([r,t])=>[r,[...t].sort()])),l=Object.fromEntries(Object.entries(a).map(([r,t])=>[r,t.length]));return{documents:c,postings:a,documentFrequency:l,averageDocumentLength:e.length===0?0:u/e.length}}function y(e,n,c){if(c.maximum<=0)return[];const u=d(c.text);if(u.length===0)return[];const a=new Set;for(const t of u)for(const o of n.postings[t]??[])a.add(o);const l=Object.keys(n.documents).length,r=[...a].flatMap(t=>{const o=e[t],i=n.documents[t];if(o===void 0||i===void 0||!g(o))return[];const s=M(i,u,n,l);return s>0?[{record:o,lexicalScore:s,rank:0}]:[]});return r.sort((t,o)=>o.lexicalScore-t.lexicalScore||o.record.updatedAt.localeCompare(t.record.updatedAt)||t.record.id.localeCompare(o.record.id)),r.slice(0,c.maximum).map((t,o)=>({...t,rank:o+1}))}function p(e){return e.normalize("NFKC").toLocaleLowerCase()}function d(e){const n=p(e),c=n.normalize("NFD").replace(/[\u0300-\u036f]/gu,"");return[...new Set([...f(n),...f(c)])]}function g(e,n=Date.now()){return e.state==="active"&&(e.expiresAt===void 0||Date.parse(e.expiresAt)>n)}function h(e){return d([e.statement,e.rationale??"",...e.topics].join(`
2
- `))}function f(e){return e.split(/[^\p{L}\p{N}_-]+/u).filter(n=>n.length>=2)}function M(e,n,c,u){return c.averageDocumentLength<=0||e.length<=0?0:n.reduce((a,l)=>{const r=e.termFrequency[l]??0,t=c.documentFrequency[l]??0;if(r===0||t===0)return a;const o=Math.log(1+(u-t+.5)/(t+.5)),i=r+1.2*(1-.75+.75*e.length/c.averageDocumentLength);return a+o*r*(1.2+1)/i},0)}export{b as buildMemorySearchIndex,g as isMemoryRetrievable,p as normalizeSearchText,y as searchMemoryIndex,d as uniqueTokens};
1
+ import{BM25_B as d,BM25_K1 as f,SEARCH_TOKEN_MIN_LENGTH as h}from"./memory-constants.js";function k(e){const n=new Map,c={};let i=0;for(const r of e){const t=new Map;for(const s of y(r))t.set(s,(t.get(s)??0)+1);const o=Object.fromEntries(t.entries()),a=Object.values(o).reduce((s,l)=>s+l,0);c[r.id]={id:r.id,termFrequency:o,length:a},i+=a;for(const s of t.keys()){const l=n.get(s)??new Set;l.add(r.id),n.set(s,l)}}const u=Object.fromEntries([...n.entries()].map(([r,t])=>[r,[...t].sort()])),m=Object.fromEntries(Object.entries(u).map(([r,t])=>[r,t.length]));return{documents:c,postings:u,documentFrequency:m,averageDocumentLength:e.length===0?0:i/e.length}}function F(e,n,c){if(c.maximum<=0)return[];const i=p(c.text);if(i.length===0)return[];const u=new Set;for(const t of i)for(const o of n.postings[t]??[])u.add(o);const m=Object.keys(n.documents).length,r=[...u].flatMap(t=>{const o=e[t],a=n.documents[t];if(o===void 0||a===void 0||!b(o))return[];const s=M(a,i,n,m);return s>0?[{record:o,lexicalScore:s,rank:0}]:[]});return r.sort((t,o)=>o.lexicalScore-t.lexicalScore||o.record.updatedAt.localeCompare(t.record.updatedAt)||t.record.id.localeCompare(o.record.id)),r.slice(0,c.maximum).map((t,o)=>({...t,rank:o+1}))}function x(e){return e.normalize("NFKC").toLocaleLowerCase()}function p(e){const n=x(e),c=n.normalize("NFD").replace(/[\u0300-\u036f]/gu,"");return[...new Set([...g(n),...g(c)])]}function b(e,n=Date.now()){return e.state==="active"&&(e.expiresAt===void 0||Date.parse(e.expiresAt)>n)}function y(e){return p([e.statement,e.rationale??"",...e.topics].join(`
2
+ `))}function g(e){return e.split(/[^\p{L}\p{N}_-]+/u).filter(n=>n.length>=h)}function M(e,n,c,i){return c.averageDocumentLength<=0||e.length<=0?0:n.reduce((u,m)=>{const r=e.termFrequency[m]??0,t=c.documentFrequency[m]??0;if(r===0||t===0)return u;const o=Math.log(1+(i-t+.5)/(t+.5)),a=r+f*(1-d+d*e.length/c.averageDocumentLength);return u+o*r*(f+1)/a},0)}export{k as buildMemorySearchIndex,b as isMemoryRetrievable,x as normalizeSearchText,F as searchMemoryIndex,p as uniqueTokens};
@@ -53,6 +53,5 @@ export declare function isGoalState(value: unknown): value is GoalState;
53
53
  export declare function isGoalEvaluation(value: unknown): value is GoalEvaluation;
54
54
  /** Validates the data payload written by a durable goal lifecycle event. */
55
55
  export declare function isPersistedGoalEventData(value: unknown): boolean;
56
- export declare function transitionGoal(state: GoalState, status: GoalStatus): GoalState;
57
56
  export declare function addGoalUsage(current: GoalUsage, delta: GoalUsageDelta): GoalUsage;
58
57
  export declare const EMPTY_GOAL_USAGE: GoalUsage;
@@ -1 +1 @@
1
- import{RESOURCE_LIMITS as n}from"../runtime/resource-limits.js";const m=new Set(["goal.created","goal.replaced","goal.paused","goal.resumed","goal.evaluated","goal.completed","goal.blocked","goal.budget_limited","goal.usage_limited","goal.usage_recorded","goal.cleared","goal.turn.started"]);function x(t){const e=t.objective.trim();if(e.length===0||e.length>16384||/[\0\r\n]/u.test(e))throw new Error("Goal objective must contain between 1 and 16384 printable characters.");for(const[i,r]of Object.entries(t))if(!(i==="objective"||r===void 0)&&(!Number.isSafeInteger(r)||r<=0))throw new Error(`Goal limit ${i} must be a positive integer.`);if(t.maxDurationMs!==void 0&&t.maxDurationMs>n.goalMaximumMaxDurationMs)throw new Error("Goal maxDurationMs cannot exceed 8 hours.");return{objective:e,...t.tokenBudget===void 0?{}:{tokenBudget:t.tokenBudget},...t.maxTurns===void 0?{}:{maxTurns:t.maxTurns},...t.maxDurationMs===void 0?{}:{maxDurationMs:t.maxDurationMs}}}function G(t){return m.has(t)}function c(t){return a(t)?typeof t.id=="string"&&typeof t.sessionId=="string"&&E(t.objective)&&p(t.status)&&d(t.createdAt)&&d(t.updatedAt)&&d(t.startedAt)&&o(t.turns)&&o(t.evaluatorRuns)&&b(t.usage)&&f(t.tokenBudget)&&f(t.maxTurns)&&y(t.maxDurationMs)&&T(t.lastEvaluation)&&(t.lastError===void 0||typeof t.lastError=="string"&&Buffer.byteLength(t.lastError,"utf8")<=n.goalReasonBytes):!1}function u(t){return a(t)?l(t.decision)&&typeof t.reason=="string"&&Buffer.byteLength(t.reason,"utf8")<=n.goalReasonBytes&&Array.isArray(t.evidence)&&t.evidence.length<=n.goalEvidenceItems&&t.evidence.every(e=>typeof e=="string"&&Buffer.byteLength(e,"utf8")<=n.goalEvidenceBytes)&&d(t.timestamp)&&(t.evaluatorModel===void 0||typeof t.evaluatorModel=="string"):!1}function M(t){return!a(t)||!c(t.goal)?!1:t.evaluation===void 0||u(t.evaluation)}function h(t,e){if(t.status==="completed"||t.status==="blocked"||t.status==="budget_limited"||t.status==="usage_limited")throw new Error(`Cannot transition a terminal goal from ${t.status}.`);if(e==="active"&&t.status!=="paused")throw new Error(`Cannot resume a goal from ${t.status}.`);if(e==="paused"&&t.status!=="active")throw new Error(`Cannot pause a goal from ${t.status}.`);return{...t,status:e,updatedAt:new Date().toISOString()}}function S(t,e){const i=s(t.inputTokens+(e.inputTokens??0)),r=s(t.outputTokens+(e.outputTokens??0)),g=s(t.totalTokens+(e.totalTokens??(e.inputTokens??0)+(e.outputTokens??0)));return{inputTokens:i,outputTokens:r,totalTokens:g,modelCalls:s(t.modelCalls+(e.modelCalls??0)),estimated:t.estimated||e.estimated===!0}}const _=Object.freeze({inputTokens:0,outputTokens:0,totalTokens:0,modelCalls:0,estimated:!1});function s(t){return Number.isSafeInteger(t)&&t>=0?t:Number.MAX_SAFE_INTEGER}function a(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function p(t){return t==="active"||t==="paused"||t==="completed"||t==="blocked"||t==="budget_limited"||t==="usage_limited"}function l(t){return t==="continue"||t==="complete"||t==="blocked"||t==="budget_limited"||t==="usage_limited"}function b(t){return a(t)?o(t.inputTokens)&&o(t.outputTokens)&&o(t.totalTokens)&&o(t.modelCalls)&&typeof t.estimated=="boolean":!1}function T(t){return t===void 0||u(t)}function f(t){return t===void 0||typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function y(t){return t===void 0||typeof t=="number"&&Number.isSafeInteger(t)&&t>0&&t<=n.goalMaximumMaxDurationMs}function o(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function d(t){return typeof t=="string"&&Number.isFinite(Date.parse(t))}function E(t){return typeof t=="string"&&t.trim().length>0&&t.length<=n.goalObjectiveBytes&&!/[\0\r\n]/u.test(t)}export{_ as EMPTY_GOAL_USAGE,S as addGoalUsage,u as isGoalEvaluation,G as isGoalEventType,c as isGoalState,M as isPersistedGoalEventData,h as transitionGoal,x as validateGoalInput};
1
+ import{RESOURCE_LIMITS as n}from"../runtime/resource-limits.js";import{CliError as c}from"../errors/cli-error.js";import{CLI_ERROR_CODES as p}from"../errors/error-codes.js";const l=new Set(["goal.created","goal.replaced","goal.paused","goal.resumed","goal.evaluated","goal.completed","goal.blocked","goal.budget_limited","goal.usage_limited","goal.usage_recorded","goal.cleared","goal.turn.started"]);function S(t){const e=t.objective.trim();if(e.length===0||Buffer.byteLength(e,"utf8")>n.goalObjectiveBytes||/\0/u.test(e))throw d(`Goal objective must contain between 1 and ${n.goalObjectiveBytes} bytes and must not contain null characters.`);for(const[r,i]of Object.entries(t))if(!(r==="objective"||i===void 0)&&(!Number.isSafeInteger(i)||i<=0))throw d(`Goal limit ${r} must be a positive integer.`);if(t.maxDurationMs!==void 0&&t.maxDurationMs>n.goalMaximumMaxDurationMs)throw d("Goal maxDurationMs cannot exceed the supported maximum.");return{objective:e,...t.tokenBudget===void 0?{}:{tokenBudget:t.tokenBudget},...t.maxTurns===void 0?{}:{maxTurns:t.maxTurns},...t.maxDurationMs===void 0?{}:{maxDurationMs:t.maxDurationMs}}}function B(t){return l.has(t)}function b(t){return a(t)?typeof t.id=="string"&&typeof t.sessionId=="string"&&G(t.objective)&&y(t.status)&&f(t.createdAt)&&f(t.updatedAt)&&f(t.startedAt)&&o(t.turns)&&o(t.evaluatorRuns)&&k(t.usage)&&g(t.tokenBudget)&&g(t.maxTurns)&&E(t.maxDurationMs)&&x(t.lastEvaluation)&&(t.lastError===void 0||typeof t.lastError=="string"&&Buffer.byteLength(t.lastError,"utf8")<=n.goalReasonBytes):!1}function u(t){return a(t)?T(t.decision)&&typeof t.reason=="string"&&Buffer.byteLength(t.reason,"utf8")<=n.goalReasonBytes&&Array.isArray(t.evidence)&&t.evidence.length<=n.goalEvidenceItems&&t.evidence.every(e=>typeof e=="string"&&Buffer.byteLength(e,"utf8")<=n.goalEvidenceBytes)&&f(t.timestamp)&&(t.evaluatorModel===void 0||typeof t.evaluatorModel=="string"):!1}function D(t){return!a(t)||!b(t.goal)?!1:t.evaluation===void 0||u(t.evaluation)}function h(t,e){const r=s(t.inputTokens+(e.inputTokens??0)),i=s(t.outputTokens+(e.outputTokens??0)),m=s(t.totalTokens+(e.totalTokens??(e.inputTokens??0)+(e.outputTokens??0)));return{inputTokens:r,outputTokens:i,totalTokens:m,modelCalls:s(t.modelCalls+(e.modelCalls??0)),estimated:t.estimated||e.estimated===!0}}const A=Object.freeze({inputTokens:0,outputTokens:0,totalTokens:0,modelCalls:0,estimated:!1});function s(t){return Number.isSafeInteger(t)&&t>=0?t:Number.MAX_SAFE_INTEGER}function a(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function y(t){return t==="active"||t==="paused"||t==="completed"||t==="blocked"||t==="budget_limited"||t==="usage_limited"}function T(t){return t==="continue"||t==="complete"||t==="blocked"||t==="budget_limited"||t==="usage_limited"}function k(t){return a(t)?o(t.inputTokens)&&o(t.outputTokens)&&o(t.totalTokens)&&o(t.modelCalls)&&typeof t.estimated=="boolean":!1}function x(t){return t===void 0||u(t)}function g(t){return t===void 0||typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function E(t){return t===void 0||typeof t=="number"&&Number.isSafeInteger(t)&&t>0&&t<=n.goalMaximumMaxDurationMs}function o(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function f(t){return typeof t=="string"&&Number.isFinite(Date.parse(t))}function G(t){return typeof t=="string"&&t.trim().length>0&&Buffer.byteLength(t,"utf8")<=n.goalObjectiveBytes&&!/\0/u.test(t)}function d(t){return new c(p.INVALID_ARGUMENT,t,{category:"goal",userMessage:t})}export{A as EMPTY_GOAL_USAGE,h as addGoalUsage,u as isGoalEvaluation,B as isGoalEventType,b as isGoalState,D as isPersistedGoalEventData,S as validateGoalInput};
@@ -1,7 +1,4 @@
1
- export declare const MAX_WORK_PLAN_STEPS = 10;
2
1
  export type WorkItemStatus = 'queued' | 'active' | 'completed' | 'failed' | 'blocked';
3
- export type WorkPlanStatus = 'active' | 'completed' | 'failed' | 'blocked';
4
- export type WorkEvidenceKind = 'read' | 'diff' | 'test' | 'typecheck' | 'lint' | 'build' | 'runtime';
5
2
  export interface WorkItem {
6
3
  id: string;
7
4
  title: string;
@@ -10,68 +7,9 @@ export interface WorkItem {
10
7
  status: WorkItemStatus;
11
8
  assignedAgent?: string;
12
9
  }
13
- export interface WorkPlanStep extends WorkItem {
14
- index: number;
15
- scope: readonly string[];
16
- acceptanceCriteria: readonly string[];
17
- verificationHints: readonly string[];
18
- evidenceIds: readonly string[];
19
- }
20
- export interface WorkPlan {
21
- id: string;
22
- turnId: string;
23
- goal: string;
24
- language: string;
25
- version: number;
26
- status: WorkPlanStatus;
27
- steps: readonly WorkPlanStep[];
28
- createdAt: string;
29
- updatedAt: string;
30
- }
31
- export interface WorkEvidence {
32
- id: string;
33
- turnId: string;
34
- planId: string;
35
- stepId: string;
36
- kind: WorkEvidenceKind;
37
- summary: string;
38
- status: 'passed' | 'failed' | 'informational';
39
- command?: string;
40
- paths?: readonly string[];
41
- exitCode?: number;
42
- createdAt: string;
43
- }
44
10
  export interface SchedulerLimits {
45
11
  maxConcurrency: number;
46
12
  maxTasks: number;
47
13
  maxDurationMs: number;
48
14
  maxTokens?: number;
49
15
  }
50
- export interface WorkPlanUpdateInput {
51
- action: 'create' | 'replace' | 'step_status' | 'record_evidence' | 'complete' | 'fail' | 'block';
52
- goal?: string;
53
- language?: string;
54
- steps?: readonly WorkPlanStepInput[];
55
- stepId?: string;
56
- status?: Exclude<WorkItemStatus, 'queued'>;
57
- evidence?: WorkEvidenceInput;
58
- reason?: string;
59
- }
60
- export interface WorkPlanStepInput {
61
- id: string;
62
- title: string;
63
- description: string;
64
- dependencies?: readonly string[];
65
- scope?: readonly string[];
66
- acceptanceCriteria: readonly string[];
67
- verificationHints?: readonly string[];
68
- }
69
- export interface WorkEvidenceInput {
70
- stepId: string;
71
- kind: WorkEvidenceKind;
72
- summary: string;
73
- status: WorkEvidence['status'];
74
- command?: string;
75
- paths?: readonly string[];
76
- exitCode?: number;
77
- }
@@ -1 +0,0 @@
1
- const _=10;export{_ as MAX_WORK_PLAN_STEPS};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Converts a provider assistant frame into the text that has not already been
3
+ * emitted for the current model segment.
4
+ *
5
+ * Providers normally send incremental frames, but compatibility gateways can
6
+ * send cumulative snapshots or replay an already-complete text fragment. The
7
+ * model boundary is the single place where those representations are
8
+ * normalized before they reach the Agent SDK and the desktop JSONL protocol.
9
+ */
10
+ export declare function normalizeAssistantDelta(previousText: string, incomingDelta: string): string;
11
+ export declare function mergeAssistantText(previousText: string, incomingDelta: string): string;
@@ -0,0 +1 @@
1
+ function d(t,n){if(n.length===0)return"";const i=n.startsWith(t)?n.slice(t.length):n,r=f(i);return r.length===0||t.endsWith(r)&&c(r)?"":r}function h(t,n){return`${t}${d(t,n)}`}function f(t){if(t.length<2)return t;const n=new Array(t.length).fill(0);for(let s=1;s<t.length;s+=1){let e=n[s-1]??0;for(;e>0&&t[s]!==t[e];)e=n[e-1]??0;t[s]===t[e]&&(e+=1),n[s]=e}const i=n.at(-1)??0,r=t.length-i,o=t.slice(0,r);return i>0&&t.length%r===0&&c(o)?o:t}function c(t){const n=t.trimEnd().at(-1);return n!==void 0&&/[\p{P}\p{S}]/u.test(n)}export{h as mergeAssistantText,d as normalizeAssistantDelta};
@@ -0,0 +1,19 @@
1
+ /** Public Gateway JSON body limit mirrored from the server and SDK contract. */
2
+ export declare const GATEWAY_JSON_BODY_LIMIT_BYTES: number;
3
+ export declare const GATEWAY_JSON_NEAR_LIMIT_RATIO = 0.8;
4
+ export interface GatewayAttachmentBudgetInput {
5
+ readonly byteLength: number;
6
+ readonly mimeType: string;
7
+ readonly name?: string;
8
+ }
9
+ export interface GatewayRequestBudget {
10
+ readonly projectedBytes: number;
11
+ readonly limitBytes: number;
12
+ readonly remainingBytes: number;
13
+ readonly utilization: number;
14
+ readonly isWithinLimit: boolean;
15
+ readonly isNearLimit: boolean;
16
+ }
17
+ export declare function estimateGatewayMessageBytes(prompt: string, attachments?: readonly GatewayAttachmentBudgetInput[]): number;
18
+ export declare function evaluateGatewayRequestBudget(prompt: string, attachments?: readonly GatewayAttachmentBudgetInput[], reservedBytes?: number): GatewayRequestBudget;
19
+ export declare function base64ByteLength(byteLength: number): number;
@@ -0,0 +1 @@
1
+ const T=2e7,u=.8;function a(e,t=[]){const i=t.length===0?{role:"user",content:e}:{role:"user",content:[{type:"text",text:e},...t.map(o)]};return Buffer.byteLength(JSON.stringify({messages:[i]}),"utf8")+t.reduce((_,r)=>_+s(r.byteLength),0)}function A(e,t=[],i=0){const n=a(e,t)+Math.max(0,i),_=2e7-n;return{projectedBytes:n,limitBytes:2e7,remainingBytes:_,utilization:n/2e7,isWithinLimit:n<=2e7,isNearLimit:n>=2e7*.8}}function s(e){if(!Number.isSafeInteger(e)||e<0)throw new RangeError("Attachment byte length must be a non-negative safe integer.");return Math.ceil(e/3)*4}function o(e){const t=`data:${e.mimeType};base64:`;return e.mimeType.startsWith("image/")?{type:"image_url",image_url:{url:t,detail:"auto"}}:{type:"input_file",file_data:t,filename:e.name??"attachment",media_type:e.mimeType}}export{T as GATEWAY_JSON_BODY_LIMIT_BYTES,u as GATEWAY_JSON_NEAR_LIMIT_RATIO,s as base64ByteLength,a as estimateGatewayMessageBytes,A as evaluateGatewayRequestBudget};
@@ -3,15 +3,21 @@ export declare const RESOURCE_LIMITS: {
3
3
  readonly processTerminationGraceMs: 500;
4
4
  readonly processTerminationTimeoutMs: 2000;
5
5
  readonly configFileBytes: number;
6
+ readonly sessionIndexBytes: number;
6
7
  readonly workspaceSettingsBytes: number;
7
8
  readonly mcpConfigBytes: number;
8
9
  readonly sessionBundleBytes: number;
9
10
  readonly sessionJournalBytes: number;
11
+ readonly sessionJournalCacheMaxEntries: 8;
12
+ readonly sessionJournalCacheMaxBytes: number;
10
13
  readonly sessionEvents: 100000;
11
14
  readonly sessionTranscriptEntries: 50000;
12
15
  readonly sessionAttachments: 32;
13
16
  readonly sessionAttachmentTotalBytes: number;
14
17
  readonly sessionTextBytes: number;
18
+ readonly agentStreamBytes: number;
19
+ readonly agentToolArgumentBytes: number;
20
+ readonly agentToolMetadataBytes: number;
15
21
  readonly memoryJournalBytes: number;
16
22
  readonly memoryIndexBytes: number;
17
23
  readonly memoryBundleBytes: number;
@@ -25,12 +31,15 @@ export declare const RESOURCE_LIMITS: {
25
31
  readonly memoryEvidenceReferenceBytes: 512;
26
32
  readonly memoryContextRecords: 12;
27
33
  readonly jsonlLineBytes: number;
34
+ /** Desktop protocol responses may carry bounded base64 speech payloads. */
35
+ readonly desktopJsonlLineBytes: number;
28
36
  readonly desktopAttachmentChunkBytes: number;
29
37
  readonly jsonlIdBytes: 256;
30
38
  readonly jsonlPathBytes: 4096;
31
39
  readonly jsonlPromptBytes: number;
32
40
  readonly pendingAttachments: 16;
33
41
  readonly pendingAttachmentTotalBytes: number;
42
+ readonly desktopAttachmentTtlMs: number;
34
43
  readonly maxAttachmentBytes: number;
35
44
  readonly clipboardTextBytes: number;
36
45
  readonly clipboardTimeoutMs: 15000;
@@ -39,6 +48,10 @@ export declare const RESOURCE_LIMITS: {
39
48
  readonly instructionFiles: 32;
40
49
  readonly skillDocumentBytes: number;
41
50
  readonly pluginManifestBytes: number;
51
+ readonly pluginMaxEnabled: 64;
52
+ readonly pluginMaxAgentFiles: 64;
53
+ readonly pluginMaxAgentContributions: 256;
54
+ readonly pluginDiscoveryConcurrency: 4;
42
55
  readonly subagentTaskBytes: number;
43
56
  readonly subagentContextBytes: number;
44
57
  readonly subagentMaxWriteScopeItems: 32;
@@ -48,10 +61,12 @@ export declare const RESOURCE_LIMITS: {
48
61
  readonly subagentMaxTokens: 200000;
49
62
  readonly subagentMaxConcurrent: 4;
50
63
  readonly subagentMaxRetainedJobs: 32;
64
+ readonly desktopSessionStoreMaxEntries: 20;
51
65
  readonly subagentMaxIterations: 200;
52
66
  readonly subagentMaxToolCallsPerTurn: 100;
53
67
  readonly agentMaxIterations: 500;
54
68
  readonly agentMaxToolCallsPerTurn: 1;
69
+ readonly intentMaxCompletionAttempts: 2;
55
70
  readonly subagentToolArgumentBytes: number;
56
71
  readonly subagentToolResultBytes: number;
57
72
  readonly goalObjectiveBytes: number;
@@ -65,11 +80,22 @@ export declare const RESOURCE_LIMITS: {
65
80
  readonly goalMaximumMaxDurationMs: number;
66
81
  readonly goalDefaultMaxEvaluatorRuns: 100;
67
82
  readonly tuiTranscriptMessages: 2000;
83
+ readonly tuiAgentSessionMaxEntries: 4;
84
+ readonly tuiAgentSessionMaxBytes: number;
85
+ readonly agentPreparationCacheMaxEntries: 8;
86
+ readonly agentPreparationCacheMaxBytes: number;
87
+ readonly contextTokenCacheMaxEntries: 8;
88
+ readonly contextTokenCacheMaxBytes: number;
68
89
  readonly jsonlMaxInFlight: 4;
90
+ readonly protocolWriteQueueEntries: 256;
91
+ readonly protocolWriteQueueBytes: number;
69
92
  readonly workspaceReferenceCount: 32;
70
93
  readonly workspaceReferenceInstructionBytes: number;
71
94
  readonly logQueueEntries: 10000;
72
95
  readonly logQueueBytes: number;
73
96
  readonly internalProcessTimeoutMs: number;
74
97
  readonly internalProcessOutputBytes: number;
98
+ readonly hostShellTimeoutMs: 120000;
99
+ readonly guestShellTimeoutMs: number;
100
+ readonly defaultShellTimeoutMs: 30000;
75
101
  };
@@ -1 +1 @@
1
- const e={processTerminationGraceMs:500,processTerminationTimeoutMs:2e3,configFileBytes:262144,workspaceSettingsBytes:262144,mcpConfigBytes:524288,sessionBundleBytes:20971520,sessionJournalBytes:20971520,sessionEvents:1e5,sessionTranscriptEntries:5e4,sessionAttachments:32,sessionAttachmentTotalBytes:52428800,sessionTextBytes:524288,memoryJournalBytes:8388608,memoryIndexBytes:8388608,memoryBundleBytes:8388608,memoryRecords:2e3,memoryStatementBytes:4096,memoryRationaleBytes:2048,memoryTopics:16,memoryTopicBytes:256,memorySupersedes:16,memoryEvidenceReferences:32,memoryEvidenceReferenceBytes:512,memoryContextRecords:12,jsonlLineBytes:1048576,desktopAttachmentChunkBytes:524288,jsonlIdBytes:256,jsonlPathBytes:4096,jsonlPromptBytes:524288,pendingAttachments:16,pendingAttachmentTotalBytes:52428800,maxAttachmentBytes:10485760,clipboardTextBytes:10485760,clipboardTimeoutMs:15e3,instructionFileBytes:131072,instructionTotalBytes:262144,instructionFiles:32,skillDocumentBytes:524288,pluginManifestBytes:262144,subagentTaskBytes:16384,subagentContextBytes:16384,subagentMaxWriteScopeItems:32,subagentWriteScopeItemBytes:512,subagentSummaryBytes:24576,subagentMaxDurationMs:18e5,subagentMaxTokens:2e5,subagentMaxConcurrent:4,subagentMaxRetainedJobs:32,subagentMaxIterations:200,subagentMaxToolCallsPerTurn:100,agentMaxIterations:500,agentMaxToolCallsPerTurn:1,subagentToolArgumentBytes:65536,subagentToolResultBytes:262144,goalObjectiveBytes:16384,goalReasonBytes:2048,goalEvidenceItems:8,goalEvidenceBytes:4096,goalDefaultMaxTurns:100,goalMaximumMaxTurns:1e4,goalMaximumTokenBudget:1e7,goalDefaultMaxDurationMs:72e5,goalMaximumMaxDurationMs:288e5,goalDefaultMaxEvaluatorRuns:100,tuiTranscriptMessages:2e3,jsonlMaxInFlight:4,workspaceReferenceCount:32,workspaceReferenceInstructionBytes:16384,logQueueEntries:1e4,logQueueBytes:4194304,internalProcessTimeoutMs:12e4,internalProcessOutputBytes:4194304};export{e as RESOURCE_LIMITS};
1
+ const e=1e6,t={processTerminationGraceMs:500,processTerminationTimeoutMs:2e3,configFileBytes:262144,sessionIndexBytes:8388608,workspaceSettingsBytes:262144,mcpConfigBytes:524288,sessionBundleBytes:20971520,sessionJournalBytes:20971520,sessionJournalCacheMaxEntries:8,sessionJournalCacheMaxBytes:8e6,sessionEvents:1e5,sessionTranscriptEntries:5e4,sessionAttachments:32,sessionAttachmentTotalBytes:5e7,sessionTextBytes:524288,agentStreamBytes:4194304,agentToolArgumentBytes:262144,agentToolMetadataBytes:262144,memoryJournalBytes:8388608,memoryIndexBytes:8388608,memoryBundleBytes:8388608,memoryRecords:2e3,memoryStatementBytes:4096,memoryRationaleBytes:2048,memoryTopics:16,memoryTopicBytes:256,memorySupersedes:16,memoryEvidenceReferences:32,memoryEvidenceReferenceBytes:512,memoryContextRecords:12,jsonlLineBytes:1048576,desktopJsonlLineBytes:4194304,desktopAttachmentChunkBytes:524288,jsonlIdBytes:256,jsonlPathBytes:4096,jsonlPromptBytes:524288,pendingAttachments:16,pendingAttachmentTotalBytes:5e7,desktopAttachmentTtlMs:9e5,maxAttachmentBytes:1e7,clipboardTextBytes:1e7,clipboardTimeoutMs:15e3,instructionFileBytes:131072,instructionTotalBytes:262144,instructionFiles:32,skillDocumentBytes:524288,pluginManifestBytes:262144,pluginMaxEnabled:64,pluginMaxAgentFiles:64,pluginMaxAgentContributions:256,pluginDiscoveryConcurrency:4,subagentTaskBytes:16384,subagentContextBytes:16384,subagentMaxWriteScopeItems:32,subagentWriteScopeItemBytes:512,subagentSummaryBytes:24576,subagentMaxDurationMs:18e5,subagentMaxTokens:2e5,subagentMaxConcurrent:4,subagentMaxRetainedJobs:32,desktopSessionStoreMaxEntries:20,subagentMaxIterations:200,subagentMaxToolCallsPerTurn:100,agentMaxIterations:500,agentMaxToolCallsPerTurn:1,intentMaxCompletionAttempts:2,subagentToolArgumentBytes:65536,subagentToolResultBytes:262144,goalObjectiveBytes:16384,goalReasonBytes:2048,goalEvidenceItems:8,goalEvidenceBytes:4096,goalDefaultMaxTurns:100,goalMaximumMaxTurns:1e4,goalMaximumTokenBudget:1e7,goalDefaultMaxDurationMs:72e5,goalMaximumMaxDurationMs:288e5,goalDefaultMaxEvaluatorRuns:100,tuiTranscriptMessages:2e3,tuiAgentSessionMaxEntries:4,tuiAgentSessionMaxBytes:8388608,agentPreparationCacheMaxEntries:8,agentPreparationCacheMaxBytes:16777216,contextTokenCacheMaxEntries:8,contextTokenCacheMaxBytes:8388608,jsonlMaxInFlight:4,protocolWriteQueueEntries:256,protocolWriteQueueBytes:16777216,workspaceReferenceCount:32,workspaceReferenceInstructionBytes:16384,logQueueEntries:1e4,logQueueBytes:4194304,internalProcessTimeoutMs:12e4,internalProcessOutputBytes:4194304,hostShellTimeoutMs:12e4,guestShellTimeoutMs:6e5,defaultShellTimeoutMs:3e4};export{t as RESOURCE_LIMITS};
@@ -5,6 +5,8 @@ export interface Attachment {
5
5
  mimeType: string;
6
6
  sizeBytes: number;
7
7
  source: AttachmentSource;
8
+ /** Optional requested filename for session-backed Desktop attachments. */
9
+ storageName?: string;
8
10
  storagePath?: string;
9
11
  }
10
12
  export interface AttachmentPayload {
@@ -1,4 +1,5 @@
1
1
  export declare const WORKSPACE_SETTINGS_SCHEMA_VERSION = 1;
2
+ export declare const MAX_WORKSPACE_PERMISSION_RULE_LENGTH = 1024;
2
3
  export interface WorkspacePermissionPolicy {
3
4
  readonly allow: readonly string[];
4
5
  readonly ask: readonly string[];
@@ -10,3 +11,4 @@ export interface WorkspaceSettings {
10
11
  }
11
12
  export declare const DEFAULT_WORKSPACE_SETTINGS: WorkspaceSettings;
12
13
  export declare function validateWorkspaceSettings(value: unknown): WorkspaceSettings;
14
+ export declare function normalizePermissionRule(value: unknown, field?: string): string;
@@ -1 +1 @@
1
- import{CliError as a}from"../errors/cli-error.js";import{CLI_ERROR_CODES as m}from"../errors/error-codes.js";import{findUnexpectedRecordKey as d,isRecord as p}from"../validation/record-schema.js";const o=1,f={schemaVersion:o,permissions:{allow:[],ask:[],deny:[]}};function g(s){if(!p(s))throw r("Workspace settings must be a JSON object.");if(c(s,["schemaVersion","permissions"],"workspace settings"),s.schemaVersion!==void 0&&s.schemaVersion!==o)throw r("Unsupported workspace settings schema version.");const n=s.permissions===void 0?f.permissions:w(s.permissions);return{schemaVersion:o,permissions:n}}function w(s){if(!p(s))throw r("Workspace permissions must be a JSON object.");return c(s,["allow","ask","deny"],"workspace permissions"),{allow:i(s.allow,"permissions.allow"),ask:i(s.ask,"permissions.ask"),deny:i(s.deny,"permissions.deny")}}function i(s,n){if(s===void 0)return[];if(!Array.isArray(s)||s.some(e=>typeof e!="string"||e.trim().length===0||e.length>256))throw r(`${n} must be an array of non-empty strings (max 256 characters each).`);return[...new Set(s.map(e=>e.trim()))]}function r(s){return new a(m.CONFIG_SCHEMA_INVALID,s,{category:"config",userMessage:`Invalid workspace settings: ${s}`})}function c(s,n,e){const t=d(s,n);if(t!==void 0)throw r(`Unsupported ${e} field: \`${t}\`.`)}export{f as DEFAULT_WORKSPACE_SETTINGS,o as WORKSPACE_SETTINGS_SCHEMA_VERSION,g as validateWorkspaceSettings};
1
+ import{CliError as a}from"../errors/cli-error.js";import{CLI_ERROR_CODES as d}from"../errors/error-codes.js";import{findUnexpectedRecordKey as f,isRecord as c}from"../validation/record-schema.js";const i=1,o=1024,w={schemaVersion:i,permissions:{allow:[],ask:[],deny:[]}};function g(s){if(!c(s))throw r("Workspace settings must be a JSON object.");if(m(s,["schemaVersion","permissions"],"workspace settings"),s.schemaVersion!==void 0&&s.schemaVersion!==i)throw r("Unsupported workspace settings schema version.");const e=s.permissions===void 0?w.permissions:S(s.permissions);return{schemaVersion:i,permissions:e}}function S(s){if(!c(s))throw r("Workspace permissions must be a JSON object.");return m(s,["allow","ask","deny"],"workspace permissions"),{allow:t(s.allow,"permissions.allow"),ask:t(s.ask,"permissions.ask"),deny:t(s.deny,"permissions.deny")}}function t(s,e){if(s===void 0)return[];if(!Array.isArray(s))throw r(`${e} must be an array of non-empty strings (max ${o} characters each).`);return[...new Set(s.map(n=>h(n,e)))]}function h(s,e="permission rule"){if(typeof s!="string"||s.trim().length===0||s.length>o)throw r(`${e} must be a non-empty string (max ${o} characters).`);return s.trim()}function r(s){return new a(d.CONFIG_SCHEMA_INVALID,s,{category:"config",userMessage:`Invalid workspace settings: ${s}`})}function m(s,e,n){const p=f(s,e);if(p!==void 0)throw r(`Unsupported ${n} field: \`${p}\`.`)}export{w as DEFAULT_WORKSPACE_SETTINGS,o as MAX_WORKSPACE_PERMISSION_RULE_LENGTH,i as WORKSPACE_SETTINGS_SCHEMA_VERSION,h as normalizePermissionRule,g as validateWorkspaceSettings};
@@ -0,0 +1,7 @@
1
+ import type { ChatUsage } from '../../ports/chat-model.js';
2
+ export declare function textLength(content: unknown): number;
3
+ export declare function mapUsage(usage: {
4
+ prompt_tokens?: number;
5
+ completion_tokens?: number;
6
+ total_tokens?: number;
7
+ }): ChatUsage;
@@ -0,0 +1 @@
1
+ function r(t){return typeof t=="string"?t.length:Array.isArray(t)?t.reduce((o,e)=>{if(typeof e!="object"||e===null||!("text"in e))return o;const n=e.text;return o+(typeof n=="string"?n.length:0)},0):0}function p(t){return{...typeof t.prompt_tokens=="number"?{promptTokens:t.prompt_tokens}:{},...typeof t.completion_tokens=="number"?{completionTokens:t.completion_tokens}:{},...typeof t.total_tokens=="number"?{totalTokens:t.total_tokens}:{}}}export{p as mapUsage,r as textLength};
@@ -1 +1 @@
1
- const u=/^[A-Za-z0-9_-]+$/u,c=64;function _(n){const t=new Map,e=new Map;for(const o of[...new Set((n??[]).flatMap(d))]){const i=l(o),a=e.get(i);if(a!==void 0&&a!==o)throw new Error(`Tool names "${a}" and "${o}" normalize to the same provider name "${i}".`);t.set(o,i),e.set(i,o)}return{toProviderName:o=>t.get(o)??l(o),toInternalName:o=>e.get(o)??o}}function g(n,t){const e={...n,messages:n.messages.map(o=>!("tool_calls"in o)||o.tool_calls===void 0?o:{...o,tool_calls:o.tool_calls.map(i=>r(i,t.toProviderName))}),...n.tools===void 0?{}:{tools:n.tools.map(o=>m(o,t.toProviderName))}};return n.tool_choice!==void 0&&(e.tool_choice=f(n.tool_choice,t.toProviderName)),n.toolChoice!==void 0&&(e.toolChoice=f(n.toolChoice,t.toProviderName)),n.toolConfig!==void 0&&(e.toolConfig=f(n.toolConfig,t.toProviderName)),e}function p(n,t){return{...n,choices:n.choices.map(e=>({...e,message:e.message.tool_calls===void 0?e.message:{...e.message,tool_calls:e.message.tool_calls.map(o=>r(o,t.toInternalName))}}))}}function N(n,t){return{...n,choices:n.choices.map(e=>({...e,delta:e.delta.tool_calls===void 0?e.delta:{...e.delta,tool_calls:e.delta.tool_calls.map(o=>r(o,t.toInternalName))}}))}}function l(n){const t=n.replace(/[^A-Za-z0-9_-]+/gu,"_");if(t.length<=64&&u.test(t))return t;const e=s(n).slice(0,8);return`${t.slice(0,64-e.length-1)}_${e}`}function s(n){let t=2166136261;for(const e of n)t^=e.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function m(n,t){return"function"in n&&n.function!==void 0?{...n,function:{...n.function,name:t(n.function.name)}}:"functionDeclarations"in n?{...n,functionDeclarations:n.functionDeclarations.map(e=>({...e,name:t(e.name)}))}:"name"in n?{...n,name:t(n.name)}:n}function r(n,t){return{...n,function:{...n.function,name:t(n.function.name)}}}function f(n,t){return typeof n=="string"?n:"function"in n&&n.function!==void 0?{...n,function:{...n.function,name:t(n.function.name)}}:"name"in n&&typeof n.name=="string"?{...n,name:t(n.name)}:"functionCallingConfig"in n&&n.functionCallingConfig.allowedFunctionNames!==void 0?{...n,functionCallingConfig:{...n.functionCallingConfig,allowedFunctionNames:n.functionCallingConfig.allowedFunctionNames.map(t)}}:n}function d(n){return"function"in n&&n.function!==void 0?[n.function.name]:"name"in n&&typeof n.name=="string"?[n.name]:"functionDeclarations"in n?n.functionDeclarations.map(t=>t.name):[]}export{_ as createModelToolNameMap,N as mapChunkToolNames,g as mapRequestToolNames,p as mapResponseToolNames};
1
+ import{PROVIDER_TOOL_NAME_MAX_LENGTH as l,PROVIDER_TOOL_NAME_PATTERN as s}from"./sdk-constants.js";function g(n){const t=new Map,e=new Map;for(const o of[...new Set((n??[]).flatMap(c))]){const i=u(o),a=e.get(i);if(a!==void 0&&a!==o)throw new Error(`Tool names "${a}" and "${o}" normalize to the same provider name "${i}".`);t.set(o,i),e.set(i,o)}return{toProviderName:o=>t.get(o)??u(o),toInternalName:o=>e.get(o)??o}}function _(n,t){const e={...n,messages:n.messages.map(o=>!("tool_calls"in o)||o.tool_calls===void 0?o:{...o,tool_calls:o.tool_calls.map(i=>r(i,t.toProviderName))}),...n.tools===void 0?{}:{tools:n.tools.map(o=>d(o,t.toProviderName))}};return n.tool_choice!==void 0&&(e.tool_choice=f(n.tool_choice,t.toProviderName)),n.toolChoice!==void 0&&(e.toolChoice=f(n.toolChoice,t.toProviderName)),n.toolConfig!==void 0&&(e.toolConfig=f(n.toolConfig,t.toProviderName)),e}function N(n,t){return{...n,choices:n.choices.map(e=>({...e,message:e.message.tool_calls===void 0?e.message:{...e.message,tool_calls:e.message.tool_calls.map(o=>r(o,t.toInternalName))}}))}}function C(n,t){return{...n,choices:n.choices.map(e=>({...e,delta:e.delta.tool_calls===void 0?e.delta:{...e.delta,tool_calls:e.delta.tool_calls.map(o=>r(o,t.toInternalName))}}))}}function u(n){const t=n.replace(/[^A-Za-z0-9_-]+/gu,"_");if(t.length<=l&&s.test(t))return t;const e=m(n).slice(0,8);return`${t.slice(0,l-e.length-1)}_${e}`}function m(n){let t=2166136261;for(const e of n)t^=e.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function d(n,t){return"function"in n&&n.function!==void 0?{...n,function:{...n.function,name:t(n.function.name)}}:"functionDeclarations"in n?{...n,functionDeclarations:n.functionDeclarations.map(e=>({...e,name:t(e.name)}))}:"name"in n?{...n,name:t(n.name)}:n}function r(n,t){return{...n,function:{...n.function,name:t(n.function.name)}}}function f(n,t){return typeof n=="string"?n:"function"in n&&n.function!==void 0?{...n,function:{...n.function,name:t(n.function.name)}}:"name"in n&&typeof n.name=="string"?{...n,name:t(n.name)}:"functionCallingConfig"in n&&n.functionCallingConfig.allowedFunctionNames!==void 0?{...n,functionCallingConfig:{...n.functionCallingConfig,allowedFunctionNames:n.functionCallingConfig.allowedFunctionNames.map(t)}}:n}function c(n){return"function"in n&&n.function!==void 0?[n.function.name]:"name"in n&&typeof n.name=="string"?[n.name]:"functionDeclarations"in n?n.functionDeclarations.map(t=>t.name):[]}export{g as createModelToolNameMap,C as mapChunkToolNames,_ as mapRequestToolNames,N as mapResponseToolNames};
@@ -0,0 +1,2 @@
1
+ export declare const PROVIDER_TOOL_NAME_PATTERN: RegExp;
2
+ export declare const PROVIDER_TOOL_NAME_MAX_LENGTH = 64;
@@ -0,0 +1 @@
1
+ const _=/^[A-Za-z0-9_-]+$/u,E=64;export{E as PROVIDER_TOOL_NAME_MAX_LENGTH,_ as PROVIDER_TOOL_NAME_PATTERN};
@@ -1 +1 @@
1
- import"@lotagate/sdk";import{AssistantDeltaNormalizer as q}from"../../domain/runtime/assistant-delta-normalizer.js";import{createModelToolNameMap as nn,mapChunkToolNames as tn,mapRequestToolNames as U,mapResponseToolNames as z}from"./model-tool-name-mapper.js";import{isRetryableModelResponseError as en,MODEL_RESPONSE_MAX_RETRIES as on,retryModelStream as rn}from"../../application/model/model-response-retry.js";const W=on;function kn(n,t={}){return{chat:{completions:{create:((e,s)=>{const r=nn(e.tools),i=e.tools!==void 0&&e.tools.length>0?1:void 0;if(e.stream===!0){const l=U(v({...e,stream:!0}),r),f=cn(e)?ln(n,l,s,i):rn({create:async()=>await n.chat.completions.create(l,s),isObservable:un,...s?.signal===void 0?{}:{signal:s.signal}});return an(n,l,e.tools,s,f,e.model,t,r,i)}const a=U(v({...e,stream:!1}),r);return sn(n.chat.completions.create(a,s),e.model,t,r,i)})}}}}async function sn(n,t,o,e,s){const r=O(z(w(await n),e),s),i=r.choices[0]?.message;return o.onComplete?.({model:t,stream:!1,contentLength:$(i?.content),toolCallCount:i?.tool_calls?.length??0,toolNames:(i?.tool_calls??[]).map(a=>a.function.name),...r.usage===void 0?{}:{usage:k(r.usage)},...r.choices[0]?.finish_reason===void 0?{}:{finishReason:r.choices[0].finish_reason}}),r}async function*an(n,t,o,e,s,r,i,a,l){let f=0,c;const d=new Set,m=new Set,_=new dn(o);let S=!1,b,x,M=!1;const Z=new q;try{for await(const C of s){const h=tn(fn(C,Z),a),p=_.consume(h).chunk,y=p.choices[0];p.usage!==void 0&&(b=k(p.usage));const I=$(y?.delta.content);if(f+=I,c=y?.finish_reason??c,I>0&&(S=!0),y?.finish_reason==="tool_calls"&&!M){const J=_.flush(p);if(!S&&B(J)){const R=z(w(await N(n,t,e,l)),a);R.usage!==void 0&&(b=k(R.usage)),G(R,m,d),c=R.choices[0]?.finish_reason??c,yield T(R);return}const L=P(J,l);K(L,m,d),M=!0,yield p,yield L}else yield p;x=p}if(!M&&x!==void 0&&_.hasCalls()){const C=_.flush(x);if(!S&&B(C)){const g=z(w(await N(n,t,e,l)),a);g.usage!==void 0&&(b=k(g.usage)),G(g,m,d),c=g.choices[0]?.finish_reason??c,yield T(g);return}const h=P(C,l);K(h,m,d),M=!0,yield h}}catch(C){if(!S&&!M&&Y(C)&&e?.signal?.aborted!==!0){const h=z(w(await N(n,t,e,l)),a);h.usage!==void 0&&(b=k(h.usage));const g=h.choices[0]?.message,p=$(g?.content);f+=p;for(const y of g?.tool_calls??[])y.id.length>0&&m.add(y.id),y.function.name.length>0&&d.add(y.function.name);c=h.choices[0]?.finish_reason??c,yield T(h);return}throw C}finally{i.onComplete?.({model:r,stream:!0,contentLength:f,toolCallCount:m.size||d.size,toolNames:[...d],...c===void 0?{}:{finishReason:c},...b===void 0?{}:{usage:b}})}}async function N(n,t,o,e){const s=v({...t,stream:!1});for(let r=0;;r+=1)try{const i=w(await n.chat.completions.create(s,o));if(r<W&&B(i))continue;return O(i,e)}catch(i){if(r>=W||!Y(i)||o?.signal?.aborted===!0)throw i}}async function*ln(n,t,o,e){yield T(await N(n,t,o,e))}function v(n){return n.tools===void 0||n.tools.length===0?n:{...n,tool_choice:"auto"}}function cn(n){const t=n.messages.at(-1);return t!==void 0&&"role"in t&&t.role==="tool"}function un(n){return n.choices.some(t=>{const o=t.delta.content,e=t.delta.tool_calls,s=t.delta;return typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0||Array.isArray(e)&&e.length>0||u(s.function_call)})}function O(n,t){return t===void 0?n:{...n,choices:n.choices.map(o=>{const e=o.message.tool_calls;return e===void 0||e.length<=t?o:{...o,message:{...o.message,tool_calls:e.slice(0,t)}}})}}function P(n,t){return t===void 0?n:{...n,choices:n.choices.map(o=>{const e=o.delta.tool_calls;return e===void 0||e.length<=t?o:{...o,delta:{...o.delta,tool_calls:e.slice(0,t)}}})}}function T(n){const t=w(n),o=t.choices[0],e=o?.message;return{id:t.id,object:"chat.completion.chunk",created:t.created,model:t.model,choices:[{index:o?.index??0,delta:{role:"assistant",content:F(e?.content),...e?.tool_calls===void 0?{}:{tool_calls:e.tool_calls.map((s,r)=>({...s,index:r}))}},...o?.finish_reason===void 0?{}:{finish_reason:o.finish_reason}}],...t.usage===void 0?{}:{usage:t.usage}}}function fn(n,t){return{...n,choices:n.choices.map(o=>{const e=o.delta.content,r=Array.isArray(e)?t.normalize(F(e)):typeof e=="string"?t.normalize(e):e,i=o.delta,a=[...Array.isArray(e)?H(e):[],...Q(i.function_call,0)];return r===e&&a.length===0?o:{...o,delta:{...o.delta,...r===e?{}:{content:r},...a.length===0?{}:{tool_calls:[...o.delta.tool_calls??[],...a]}}}})}}class dn{knownNames;calls=new Map;order=[];keysByPosition=new Map;constructor(t){this.knownNames=new Set((t??[]).flatMap(o=>Cn(o)))}consume(t){let o=!1;const e=t.choices.map(s=>{const r=s.delta.tool_calls;if(r===void 0||r.length===0)return s;o=!0,r.forEach((a,l)=>{u(a)&&this.append(a,l)});const i={...s.delta};return delete i.tool_calls,{...s,delta:i}});return{chunk:{...t,choices:e},hadToolCalls:o}}hasCalls(){return this.order.length>0}flush(t){const o=this.order.map((i,a)=>{const l=this.calls.get(i);return{id:l.id||`tool-call-${a}`,type:l.type,function:{name:l.name,arguments:l.arguments},...l.providerMetadata===void 0?{}:{provider_metadata:l.providerMetadata}}}),e=new Set,s=o.filter(i=>{const a=`${i.function.name}\0${i.function.arguments}`;return e.has(a)?!1:(e.add(a),!0)}),r=t.choices.map((i,a)=>a===0?{...i,delta:{...i.delta,tool_calls:s}}:i);return{...t,choices:r}}append(t,o){const e=E(t),s=gn(t),r=j(t),i=X(t),a=A(t),l=hn(t,o),f=this.keysByPosition.get(l)??mn(e,l);this.keysByPosition.set(l,f);const c=this.calls.get(f),d=pn(c?.name??"",r,this.knownNames),m=yn(c?.arguments??"",i);if(c===void 0){this.calls.set(f,{id:e,type:s,name:d,arguments:m,...a===void 0?{}:{providerMetadata:a}}),this.order.push(f);return}const _=c.providerMetadata??a;this.calls.set(f,{id:c.id.length===0&&e.length>0?e:c.id,type:s||c.type,name:c.name+d,arguments:m,..._===void 0?{}:{providerMetadata:_}})}}function A(n){if(!u(n))return;const t=n.provider_metadata??n.providerMetadata;if(u(t))return t;const o=n.thoughtSignature??n.thought_signature;return typeof o=="string"&&o.length>0?{google:{thought_signature:o}}:void 0}function hn(n,t){const o=n.index;return typeof o=="number"&&Number.isInteger(o)?o:t}function mn(n,t){return n.length>0?`id:${n}`:`index:${t}`}function E(n){const t=n;return u(t)&&typeof t.id=="string"?t.id:""}function gn(n){const t=n;return u(t)&&typeof t.type=="string"&&t.type.length>0?t.type:"function"}function j(n){const t=n;return u(t)&&u(t.function)&&typeof t.function.name=="string"?t.function.name:""}function X(n){const t=n;return u(t)&&u(t.function)&&typeof t.function.arguments=="string"?t.function.arguments:""}function pn(n,t,o){return t.length===0||t===n?"":o!==void 0&&o.has(t)&&t.startsWith(n)||t.startsWith(n)&&n.length>0?t.slice(n.length):t}function yn(n,t){if(t.length===0)return n;if(n.length===0||t===n)return n.length===0?t:n;if(t.startsWith(n))return t;const o=_n(n,t);return o!==void 0?o:n+t}function B(n){const t=n.choices[0];return((t!==void 0&&"message"in t?t.message.tool_calls:t?.delta.tool_calls)??[]).some(e=>D(X(e))===void 0)}function _n(n,t){if(n.length===0||t.length===0)return;const o=D(n),e=D(t);if(!(o===void 0||e===void 0))return JSON.stringify({...o,...e})}function D(n){try{const t=JSON.parse(n);return u(t)?t:void 0}catch{return}}function K(n,t,o){for(const e of n.choices[0]?.delta.tool_calls??[]){const s=E(e),r=j(e);s.length>0&&t.add(s),r.length>0&&o.add(r)}}function G(n,t,o){for(const e of n.choices[0]?.message?.tool_calls??[]){const s=E(e),r=j(e);s.length>0&&t.add(s),r.length>0&&o.add(r)}}function Cn(n){return"function"in n&&typeof n.function.name=="string"?[n.function.name]:"name"in n&&typeof n.name=="string"?[n.name]:"functionDeclarations"in n?n.functionDeclarations.flatMap(t=>typeof t.name=="string"?[t.name]:[]):[]}function w(n){return{...n,choices:n.choices.map(t=>({...t,message:An(t.message)}))}}function An(n){const t=n,o=[...Array.isArray(n.content)?H(n.content):[],...Q(t.function_call,0)],e=Array.isArray(n.content)?F(n.content):typeof n.content=="string"?n.content:void 0,s=e??null,r=Array.isArray(n.content)||typeof n.content=="string"&&e!==n.content;return!r&&o.length===0?n:{...n,...r?{content:s}:{},...o.length===0?{}:{tool_calls:[...n.tool_calls??[],...o]}}}function H(n){const t=[];for(const[o,e]of n.entries())if(!(typeof e!="object"||e===null)){if("functionCall"in e&&u(e.functionCall)&&typeof e.functionCall.name=="string"){const s=e.functionCall.args;t.push({id:typeof e.functionCall.id=="string"&&e.functionCall.id.length>0?e.functionCall.id:`provider-call-${o}`,type:"function",function:{name:e.functionCall.name,arguments:V(s)},...A(e)===void 0?{}:{provider_metadata:A(e)}});continue}if("tool_use"in e&&u(e.tool_use)&&typeof e.tool_use.name=="string"){const s=e.tool_use.input;t.push({id:typeof e.tool_use.id=="string"&&e.tool_use.id.length>0?e.tool_use.id:`provider-call-${o}`,type:"function",function:{name:e.tool_use.name,arguments:JSON.stringify(s??{})},...A(e)===void 0?{}:{provider_metadata:A(e)}})}}return t}function Q(n,t){if(!u(n)||typeof n.name!="string")return[];const o=n.arguments;return[{id:typeof n.id=="string"&&n.id.length>0?n.id:`provider-call-${t}`,type:"function",function:{name:n.name,arguments:V(o)},...A(n)===void 0?{}:{provider_metadata:A(n)}}]}function V(n){if(n===void 0)return"";if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return""}}function u(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Y(n){return en(n)}function F(n){return typeof n=="string"?n:Array.isArray(n)?n.reduce((t,o)=>{if(typeof o!="object"||o===null||!("text"in o))return t;const e=o.text;return t+(typeof e=="string"?e:"")},""):""}function $(n){return typeof n=="string"?n.length:Array.isArray(n)?n.reduce((t,o)=>{if(typeof o!="object"||o===null||!("text"in o))return t;const e=o.text;return t+(typeof e=="string"?e.length:0)},0):0}function k(n){return{...typeof n.prompt_tokens=="number"?{promptTokens:n.prompt_tokens}:{},...typeof n.completion_tokens=="number"?{completionTokens:n.completion_tokens}:{},...typeof n.total_tokens=="number"?{totalTokens:n.total_tokens}:{}}}export{kn as createToolCallingModelClient};
1
+ import"@lotagate/sdk";import{AssistantDeltaNormalizer as st}from"../../domain/runtime/assistant-delta-normalizer.js";import{createModelToolNameMap as rt,mapChunkToolNames as it,mapRequestToolNames as K,mapResponseToolNames as L}from"./model-tool-name-mapper.js";import{isRetryableModelResponseError as at,isRetryableToolResultFollowUpError as lt,MODEL_RESPONSE_MAX_RETRIES as ct,retryModelStream as ft}from"../../application/model/model-response-retry.js";import{mapUsage as N,textLength as F}from"./model-response-metrics.js";import{assertTextWithinLimit as ut,modelResponseLimitError as w}from"../../application/agent/bounded-text-accumulator.js";import{RESOURCE_LIMITS as u}from"../../domain/runtime/resource-limits.js";const G=ct;function Ft(t,n={}){return{chat:{completions:{create:((e,s)=>{const r=rt(e.tools),a=e.tools!==void 0&&e.tools.length>0?1:void 0;if(e.stream===!0){const l=K(D({...e,stream:!0}),r),g=yt(e)?ht(t,l,s,a):ft({create:async()=>await t.chat.completions.create(l,s),isObservable:pt,...s?.signal===void 0?{}:{signal:s.signal}});return gt(t,l,e.tools,s,g,e.model,n,r,a)}const i=K(D({...e,stream:!1}),r);return dt(t.chat.completions.create(i,s),e.model,n,r,a)})}}}}async function dt(t,n,o,e,s){const r=H(L(S(await t),e),s);U(r);const a=r.choices[0]?.message;return o.onComplete?.({model:n,stream:!1,contentLength:F(a?.content),toolCallCount:a?.tool_calls?.length??0,toolNames:(a?.tool_calls??[]).map(i=>i.function.name),...r.usage===void 0?{}:{usage:N(r.usage)},...r.choices[0]?.finish_reason===void 0?{}:{finishReason:r.choices[0].finish_reason}}),r}async function*gt(t,n,o,e,s,r,a,i,l){let g=0,h=0,M=0,f;const m=new Set,B=new Set,E=new wt(o);let x=!1,A,J,R=!1;const ot=new st;try{for await(const C of s){const d=it(Ct(C,ot),i);if(h+=Buffer.byteLength(JSON.stringify(d),"utf8"),h>u.agentStreamBytes)throw w("stream",u.agentStreamBytes);const p=E.consume(d).chunk,_=p.choices[0];p.usage!==void 0&&(A=N(p.usage));const W=F(_?.delta.content);if(M+=Buffer.byteLength(z(_?.delta.content),"utf8"),M>u.sessionTextBytes)throw w("text",u.sessionTextBytes);if(g+=W,f=_?.finish_reason??f,W>0&&(x=!0),_?.finish_reason==="tool_calls"&&!R){const P=E.flush(p);if(!x&&j(P)){const T=L(S(await v(t,n,e,l)),i);T.usage!==void 0&&(A=N(T.usage)),Z(T,B,m),f=T.choices[0]?.finish_reason??f,yield k(T);return}const X=Q(P,l);Y(X,B,m),R=!0,yield p,yield X}else yield p;J=p}if(!R&&J!==void 0&&E.hasCalls()){const C=E.flush(J);if(!x&&j(C)){const y=L(S(await v(t,n,e,l)),i);y.usage!==void 0&&(A=N(y.usage)),Z(y,B,m),f=y.choices[0]?.finish_reason??f,yield k(y);return}const d=Q(C,l);Y(d,B,m),R=!0,yield d}}catch(C){if(!x&&!R&&et(C)&&e?.signal?.aborted!==!0){const d=L(S(await v(t,n,e,l)),i);d.usage!==void 0&&(A=N(d.usage));const y=d.choices[0]?.message,p=F(y?.content);U(d),g+=p;for(const _ of y?.tool_calls??[])_.id.length>0&&B.add(_.id),_.function.name.length>0&&m.add(_.function.name);f=d.choices[0]?.finish_reason??f,yield k(d);return}throw C}finally{a.onComplete?.({model:r,stream:!0,contentLength:g,toolCallCount:B.size||m.size,toolNames:[...m],...f===void 0?{}:{finishReason:f},...A===void 0?{}:{usage:A}})}}async function v(t,n,o,e,s=!1){const r=D({...n,stream:!1});for(let a=0;;a+=1)try{const i=S(await t.chat.completions.create(r,o));if(a<G&&j(i))continue;const l=H(i,e);return U(l),l}catch(i){const l=s?lt(i):et(i);if(a>=G||!l||o?.signal?.aborted===!0)throw i}}async function*ht(t,n,o,e){yield k(await v(t,n,o,e,!0))}function D(t){return t.tools===void 0||t.tools.length===0||mt(t)?t:{...t,tool_choice:"auto"}}function mt(t){return t.tool_choice!==void 0||t.toolChoice!==void 0||t.toolConfig!==void 0}function yt(t){const n=t.messages.at(-1);return n!==void 0&&"role"in n&&n.role==="tool"}function pt(t){return t.choices.some(n=>{const o=n.delta.content,e=n.delta.tool_calls,s=n.delta;return typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0||Array.isArray(e)&&e.length>0||typeof s.reasoning_content=="string"&&s.reasoning_content.length>0||c(s.function_call)})}function H(t,n){return n===void 0?t:{...t,choices:t.choices.map(o=>{const e=o.message.tool_calls;return e===void 0||e.length<=n?o:{...o,message:{...o.message,tool_calls:e.slice(0,n)}}})}}function Q(t,n){return n===void 0?t:{...t,choices:t.choices.map(o=>{const e=o.delta.tool_calls;return e===void 0||e.length<=n?o:{...o,delta:{...o.delta,tool_calls:e.slice(0,n)}}})}}function k(t){const n=S(t),o=n.choices[0],e=o?.message,s=_t(e);return{id:n.id,object:"chat.completion.chunk",created:n.created,model:n.model,choices:[{index:o?.index??0,delta:{role:"assistant",content:z(e?.content),...s===void 0?{}:{reasoning_content:s},...e?.tool_calls===void 0?{}:{tool_calls:e.tool_calls.map((r,a)=>({...r,index:a}))}},...o?.finish_reason===void 0?{}:{finish_reason:o.finish_reason}}],...n.usage===void 0?{}:{usage:n.usage}}}function _t(t){if(!c(t))return;const n=t.reasoning_content;return typeof n=="string"&&n.length>0?n:void 0}function Ct(t,n){return{...t,choices:t.choices.map(o=>{const e=o.delta.content,r=Array.isArray(e)?n.normalize(z(e)):typeof e=="string"?n.normalize(e):e,a=o.delta,i=[...Array.isArray(e)?q(e):[],...tt(a.function_call,0)];return r===e&&i.length===0?o:{...o,delta:{...o.delta,...r===e?{}:{content:r},...i.length===0?{}:{tool_calls:[...o.delta.tool_calls??[],...i]}}}})}}class wt{knownNames;calls=new Map;order=[];keysByPosition=new Map;constructor(n){this.knownNames=new Set((n??[]).flatMap(o=>Tt(o)))}consume(n){let o=!1;const e=n.choices.map(s=>{const r=s.delta.tool_calls;if(r===void 0||r.length===0)return s;o=!0,r.forEach((i,l)=>{c(i)&&this.append(i,l)});const a={...s.delta};return delete a.tool_calls,{...s,delta:a}});return{chunk:{...n,choices:e},hadToolCalls:o}}hasCalls(){return this.order.length>0}flush(n){const o=this.order.map((a,i)=>{const l=this.calls.get(a);return{id:l.id||`tool-call-${i}`,type:l.type,function:{name:l.name,arguments:l.arguments},...l.providerMetadata===void 0?{}:{provider_metadata:l.providerMetadata}}}),e=new Set,s=o.filter(a=>{const i=`${a.function.name}\0${a.function.arguments}`;return e.has(i)?!1:(e.add(i),!0)}),r=n.choices.map((a,i)=>i===0?{...a,delta:{...a.delta,tool_calls:s}}:a);return{...n,choices:r}}append(n,o){const e=I(n),s=At(n),r=$(n),a=V(n),i=b(n),l=bt(n,o),g=this.keysByPosition.get(l)??Bt(e,l);this.keysByPosition.set(l,g);const h=this.calls.get(g),M=St(h?.name??"",r,this.knownNames),f=Mt(h?.arguments??"",a);if(Buffer.byteLength(f,"utf8")>u.agentToolArgumentBytes)throw w("tool arguments",u.agentToolArgumentBytes);if(i!==void 0&&Buffer.byteLength(JSON.stringify(i),"utf8")>u.agentToolMetadataBytes)throw w("tool metadata",u.agentToolMetadataBytes);if(h===void 0){this.calls.set(g,{id:e,type:s,name:M,arguments:f,...i===void 0?{}:{providerMetadata:i}}),this.order.push(g);return}const m=h.providerMetadata??i;this.calls.set(g,{id:h.id.length===0&&e.length>0?e:h.id,type:s||h.type,name:h.name+M,arguments:f,...m===void 0?{}:{providerMetadata:m}})}}function b(t){if(!c(t))return;const n=t.provider_metadata??t.providerMetadata;if(c(n))return n;const o=t.thoughtSignature??t.thought_signature;return typeof o=="string"&&o.length>0?{google:{thought_signature:o}}:void 0}function bt(t,n){const o=t.index;return typeof o=="number"&&Number.isInteger(o)?o:n}function Bt(t,n){return t.length>0?`id:${t}`:`index:${n}`}function I(t){const n=t;return c(n)&&typeof n.id=="string"?n.id:""}function At(t){const n=t;return c(n)&&typeof n.type=="string"&&n.type.length>0?n.type:"function"}function $(t){const n=t;return c(n)&&c(n.function)&&typeof n.function.name=="string"?n.function.name:""}function V(t){const n=t;return c(n)&&c(n.function)&&typeof n.function.arguments=="string"?n.function.arguments:""}function St(t,n,o){return n.length===0||n===t?"":o!==void 0&&o.has(n)&&n.startsWith(t)||n.startsWith(t)&&t.length>0?n.slice(t.length):n}function Mt(t,n){if(n.length===0)return t;if(t.length===0||n===t)return t.length===0?n:t;if(n.startsWith(t))return n;const o=Rt(t,n);return o!==void 0?o:t+n}function j(t){const n=t.choices[0];return((n!==void 0&&"message"in n?n.message.tool_calls:n?.delta.tool_calls)??[]).some(e=>O(V(e))===void 0)}function Rt(t,n){if(t.length===0||n.length===0)return;const o=O(t),e=O(n);if(!(o===void 0||e===void 0))return JSON.stringify({...o,...e})}function O(t){try{const n=JSON.parse(t);return c(n)?n:void 0}catch{return}}function U(t){if(Buffer.byteLength(JSON.stringify(t),"utf8")>u.agentStreamBytes)throw w("response",u.agentStreamBytes);for(const o of t.choices){ut(z(o.message.content));for(const e of o.message.tool_calls??[]){if(Buffer.byteLength(e.function.arguments,"utf8")>u.agentToolArgumentBytes)throw w("tool arguments",u.agentToolArgumentBytes);const s=e.provider_metadata;if(s!==void 0&&Buffer.byteLength(JSON.stringify(s),"utf8")>u.agentToolMetadataBytes)throw w("tool metadata",u.agentToolMetadataBytes)}}}function Y(t,n,o){for(const e of t.choices[0]?.delta.tool_calls??[]){const s=I(e),r=$(e);s.length>0&&n.add(s),r.length>0&&o.add(r)}}function Z(t,n,o){for(const e of t.choices[0]?.message?.tool_calls??[]){const s=I(e),r=$(e);s.length>0&&n.add(s),r.length>0&&o.add(r)}}function Tt(t){return"function"in t&&typeof t.function.name=="string"?[t.function.name]:"name"in t&&typeof t.name=="string"?[t.name]:"functionDeclarations"in t?t.functionDeclarations.flatMap(n=>typeof n.name=="string"?[n.name]:[]):[]}function S(t){return{...t,choices:t.choices.map(n=>({...n,message:Nt(n.message)}))}}function Nt(t){const n=t,o=[...Array.isArray(t.content)?q(t.content):[],...tt(n.function_call,0)],e=Array.isArray(t.content)?z(t.content):typeof t.content=="string"?t.content:void 0,s=e??null,r=Array.isArray(t.content)||typeof t.content=="string"&&e!==t.content;return!r&&o.length===0?t:{...t,...r?{content:s}:{},...o.length===0?{}:{tool_calls:[...t.tool_calls??[],...o]}}}function q(t){const n=[];for(const[o,e]of t.entries())if(!(typeof e!="object"||e===null)){if("functionCall"in e&&c(e.functionCall)&&typeof e.functionCall.name=="string"){const s=e.functionCall.args;n.push({id:typeof e.functionCall.id=="string"&&e.functionCall.id.length>0?e.functionCall.id:`provider-call-${o}`,type:"function",function:{name:e.functionCall.name,arguments:nt(s)},...b(e)===void 0?{}:{provider_metadata:b(e)}});continue}if("tool_use"in e&&c(e.tool_use)&&typeof e.tool_use.name=="string"){const s=e.tool_use.input;n.push({id:typeof e.tool_use.id=="string"&&e.tool_use.id.length>0?e.tool_use.id:`provider-call-${o}`,type:"function",function:{name:e.tool_use.name,arguments:JSON.stringify(s??{})},...b(e)===void 0?{}:{provider_metadata:b(e)}})}}return n}function tt(t,n){if(!c(t)||typeof t.name!="string")return[];const o=t.arguments;return[{id:typeof t.id=="string"&&t.id.length>0?t.id:`provider-call-${n}`,type:"function",function:{name:t.name,arguments:nt(o)},...b(t)===void 0?{}:{provider_metadata:b(t)}}]}function nt(t){if(t===void 0)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function c(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function et(t){return at(t)}function z(t){return typeof t=="string"?t:Array.isArray(t)?t.reduce((n,o)=>{if(typeof o!="object"||o===null||!("text"in o))return n;const e=o.text;return n+(typeof e=="string"?e:"")},""):""}export{Ft as createToolCallingModelClient};
@@ -3,5 +3,7 @@ export interface CachePolicy {
3
3
  modelCatalogTtlMs: number;
4
4
  maxEntryBytes: number;
5
5
  maxTotalBytes: number;
6
+ maxMemoryEntries: number;
7
+ maxMemoryBytes: number;
6
8
  }
7
9
  export declare function resolveCachePolicy(env?: Readonly<Record<string, string | undefined>>): CachePolicy;
@@ -1 +1 @@
1
- function n(e=process.env){return{enabled:o(e.LOTAGATE_CACHE_ENABLED,!0),modelCatalogTtlMs:r(e.LOTAGATE_MODEL_CACHE_TTL_SECONDS,300,1,86400)*1e3,maxEntryBytes:r(e.LOTAGATE_CACHE_MAX_ENTRY_BYTES,5*1024*1024,1024,50*1024*1024),maxTotalBytes:r(e.LOTAGATE_CACHE_MAX_BYTES,50*1024*1024,1*1024*1024,500*1024*1024)}}function o(e,t){return e===void 0?t:e.trim().toLowerCase()==="true"?!0:e.trim().toLowerCase()==="false"?!1:t}import{readBoundedEnvironmentInteger as r}from"../config/environment-values.js";export{n as resolveCachePolicy};
1
+ function _(e=process.env){return{enabled:t(e.LOTAGATE_CACHE_ENABLED,!0),modelCatalogTtlMs:r(e.LOTAGATE_MODEL_CACHE_TTL_SECONDS,300,1,86400)*1e3,maxEntryBytes:r(e.LOTAGATE_CACHE_MAX_ENTRY_BYTES,5*1024*1024,1024,50*1024*1024),maxTotalBytes:r(e.LOTAGATE_CACHE_MAX_BYTES,50*1024*1024,1*1024*1024,500*1024*1024),maxMemoryEntries:r(e.LOTAGATE_CACHE_MAX_MEMORY_ENTRIES,64,1,1e4),maxMemoryBytes:r(e.LOTAGATE_CACHE_MAX_MEMORY_BYTES,8*1024*1024,1*1024*1024,500*1024*1024)}}function t(e,E){return e===void 0?E:e.trim().toLowerCase()==="true"?!0:e.trim().toLowerCase()==="false"?!1:E}import{readBoundedEnvironmentInteger as r}from"../config/environment-values.js";export{_ as resolveCachePolicy};
@@ -5,6 +5,10 @@ export declare class FileCacheStore implements CacheStore {
5
5
  private readonly policy;
6
6
  private readonly now;
7
7
  private prunePromise;
8
+ private mutationTail;
9
+ private readonly memoryCache;
10
+ private memoryBytes;
11
+ private lastPruneAt;
8
12
  constructor(root: string, policy: CachePolicy, now?: () => number);
9
13
  get<T>(namespace: string, key: string): Promise<T | undefined>;
10
14
  set<T>(namespace: string, key: string, value: T, options: CacheWriteOptions): Promise<void>;
@@ -12,6 +16,15 @@ export declare class FileCacheStore implements CacheStore {
12
16
  clear(namespace?: string): Promise<void>;
13
17
  prune(): Promise<void>;
14
18
  private schedulePrune;
19
+ private removeExpired;
20
+ private pruneUnlocked;
21
+ private withMutationLock;
22
+ private mutationLockPath;
15
23
  private namespacePath;
16
24
  private filePath;
25
+ private setMemoryEntry;
26
+ private removeMemoryEntry;
27
+ private touchMemoryEntry;
28
+ private clearMemory;
29
+ private pruneMemory;
17
30
  }
@@ -1,2 +1,2 @@
1
- import m from"node:crypto";import p from"node:fs";import a from"node:fs/promises";import c from"node:path";import{atomicWriteFile as y,withFileLock as w}from"../filesystem/atomic-file-store.js";import{isFileNotFound as u}from"../filesystem/fs-errors.js";import{readJsonFileBounded as l}from"../filesystem/bounded-json-reader.js";class v{root;policy;now;prunePromise;constructor(t,i,r=Date.now){this.root=t,this.policy=i,this.now=r;try{p.mkdirSync(t,{recursive:!0,mode:448})}catch{}}async get(t,i){if(!this.policy.enabled)return;const r=this.filePath(t,i);try{const e=await l(r,this.policy.maxEntryBytes);if(e.schemaVersion!==1||e.namespace!==t||e.keyHash!==f(t,i)||typeof e.expiresAt!="string")return;if(Date.parse(e.expiresAt)<=this.now()){await this.delete(t,i);return}return e.value}catch(e){u(e)||await this.delete(t,i).catch(()=>{});return}}async set(t,i,r,e){if(!this.policy.enabled||e.ttlMs<=0)return;const s={schemaVersion:1,namespace:t,keyHash:f(t,i),createdAt:new Date(this.now()).toISOString(),expiresAt:new Date(this.now()+e.ttlMs).toISOString(),value:r},n=`${JSON.stringify(s)}
2
- `;if(Buffer.byteLength(n,"utf8")>this.policy.maxEntryBytes)return;const h=this.filePath(t,i);await w(h,()=>y(h,n)),this.schedulePrune()}async delete(t,i){await a.rm(this.filePath(t,i),{force:!0})}async clear(t){await a.rm(t===void 0?this.root:this.namespacePath(t),{recursive:!0,force:!0})}async prune(){if(!this.policy.enabled)return;const t=await d(this.root),i=[];for(const e of t)try{const s=await a.stat(e),n=await l(e,this.policy.maxEntryBytes);if(n.schemaVersion!==1||typeof n.expiresAt!="string"||Date.parse(n.expiresAt)<=this.now()){await a.rm(e,{force:!0});continue}i.push({filePath:e,size:s.size,modifiedAt:s.mtimeMs})}catch{await a.rm(e,{force:!0})}let r=i.reduce((e,s)=>e+s.size,0);for(const e of i.sort((s,n)=>s.modifiedAt-n.modifiedAt)){if(r<=this.policy.maxTotalBytes)break;await a.rm(e.filePath,{force:!0}),r-=e.size}}schedulePrune(){this.prunePromise===void 0&&(this.prunePromise=this.prune().catch(()=>{}).finally(()=>{this.prunePromise=void 0}))}namespacePath(t){return c.join(this.root,P(t))}filePath(t,i){return c.join(this.namespacePath(t),`${f(t,i)}.json`)}}function f(o,t){return m.createHash("sha256").update(`${o}\0${t}`).digest("hex")}function P(o){return Buffer.from(o,"utf8").toString("base64url")}async function d(o){try{const t=await a.readdir(o,{withFileTypes:!0}),i=[];for(const r of t){const e=c.join(o,r.name);r.isDirectory()?i.push(...await d(e)):r.isFile()&&r.name.endsWith(".json")&&i.push(e)}return i}catch(t){if(u(t))return[];throw t}}export{v as FileCacheStore};
1
+ import p from"node:crypto";import w from"node:fs";import h from"node:fs/promises";import a from"node:path";import{atomicWriteFile as M,withFileLock as x}from"../filesystem/atomic-file-store.js";import{isFileNotFound as y}from"../filesystem/fs-errors.js";import{readJsonFileBounded as u}from"../filesystem/bounded-json-reader.js";const P=600*1e3;class b{root;policy;now;prunePromise;mutationTail=Promise.resolve();memoryCache=new Map;memoryBytes=0;lastPruneAt=0;constructor(t,e,r=Date.now){this.root=t,this.policy=e,this.now=r;try{w.mkdirSync(t,{recursive:!0,mode:448})}catch{}}async get(t,e){if(!this.policy.enabled)return;const r=`${t}\0${e}`,i=this.memoryCache.get(r);if(i!==void 0){if(i.expiresAtMs>this.now())return this.touchMemoryEntry(r,i),i.value;this.removeMemoryEntry(r)}const o=this.filePath(t,e);try{const s=await u(o,this.policy.maxEntryBytes);if(s.schemaVersion!==1||s.namespace!==t||s.keyHash!==m(t,e)||typeof s.expiresAt!="string")return;const c=Date.parse(s.expiresAt);if(c<=this.now()){await this.removeExpired(t,e);return}return this.setMemoryEntry(r,c,s.value),s.value}catch(s){y(s)||await this.delete(t,e).catch(()=>{});return}}async set(t,e,r,i){if(!this.policy.enabled||i.ttlMs<=0)return;const o=this.now()+i.ttlMs,s=`${t}\0${e}`,c={schemaVersion:1,namespace:t,keyHash:m(t,e),createdAt:new Date(this.now()).toISOString(),expiresAt:new Date(o).toISOString(),value:r},f=`${JSON.stringify(c)}
2
+ `;if(Buffer.byteLength(f,"utf8")>this.policy.maxEntryBytes)return;const d=this.filePath(t,e);await this.withMutationLock(()=>M(d,f)),this.setMemoryEntry(s,o,r),this.schedulePrune()}async delete(t,e){this.removeMemoryEntry(`${t}\0${e}`),await this.withMutationLock(()=>h.rm(this.filePath(t,e),{force:!0}))}async clear(t){if(t===void 0)this.clearMemory();else{const e=`${t}\0`;for(const r of[...this.memoryCache.keys()])r.startsWith(e)&&this.removeMemoryEntry(r)}await this.withMutationLock(()=>h.rm(t===void 0?this.root:this.namespacePath(t),{recursive:!0,force:!0}))}async prune(){this.policy.enabled&&await this.withMutationLock(()=>this.pruneUnlocked())}schedulePrune(){this.prunePromise===void 0&&(this.now()-this.lastPruneAt<P||(this.lastPruneAt=this.now(),this.prunePromise=this.prune().catch(()=>{}).finally(()=>{this.prunePromise=void 0})))}async removeExpired(t,e){const r=this.filePath(t,e);await this.withMutationLock(async()=>{try{const i=await u(r,this.policy.maxEntryBytes);if(i.schemaVersion===1&&i.namespace===t&&i.keyHash===m(t,e)&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>this.now())return}catch(i){if(y(i))return}await h.rm(r,{force:!0})})}async pruneUnlocked(){this.pruneMemory();const t=await l(this.root),e=[];for(const i of t)try{const o=await h.stat(i),s=await u(i,this.policy.maxEntryBytes);if(s.schemaVersion!==1||typeof s.expiresAt!="string"||Date.parse(s.expiresAt)<=this.now()){await h.rm(i,{force:!0});continue}e.push({filePath:i,size:o.size,modifiedAt:o.mtimeMs})}catch{await h.rm(i,{force:!0})}let r=e.reduce((i,o)=>i+o.size,0);for(const i of e.sort((o,s)=>o.modifiedAt-s.modifiedAt)){if(r<=this.policy.maxTotalBytes)break;await h.rm(i.filePath,{force:!0}),r-=i.size}this.pruneMemory()}withMutationLock(t){const e=this.mutationTail.then(()=>x(this.mutationLockPath(),t));return this.mutationTail=e.then(()=>{},()=>{}),e}mutationLockPath(){return a.join(a.dirname(this.root),`${a.basename(this.root)}.mutation`)}namespacePath(t){return a.join(this.root,E(t))}filePath(t,e){return a.join(this.namespacePath(t),`${m(t,e)}.json`)}setMemoryEntry(t,e,r){const i=A(r);this.removeMemoryEntry(t),!(i>this.policy.maxMemoryBytes)&&(this.memoryCache.set(t,{expiresAtMs:e,value:r,sizeBytes:i}),this.memoryBytes+=i,this.pruneMemory())}removeMemoryEntry(t){const e=this.memoryCache.get(t);e!==void 0&&(this.memoryCache.delete(t),this.memoryBytes-=e.sizeBytes)}touchMemoryEntry(t,e){this.memoryCache.delete(t),this.memoryCache.set(t,e)}clearMemory(){this.memoryCache.clear(),this.memoryBytes=0}pruneMemory(){const t=this.now();for(const[e,r]of[...this.memoryCache])r.expiresAtMs<=t&&this.removeMemoryEntry(e);for(;this.memoryCache.size>this.policy.maxMemoryEntries||this.memoryBytes>this.policy.maxMemoryBytes;){const e=this.memoryCache.keys().next().value;if(typeof e!="string")break;this.removeMemoryEntry(e)}}}function m(n,t){return p.createHash("sha256").update(`${n}\0${t}`).digest("hex")}function E(n){return Buffer.from(n,"utf8").toString("base64url")}function A(n){try{const t=JSON.stringify(n);return Buffer.byteLength(t??"","utf8")}catch{return Number.MAX_SAFE_INTEGER}}async function l(n){try{const t=await h.readdir(n,{withFileTypes:!0}),e=[];for(const r of t){const i=a.join(n,r.name);r.isDirectory()?e.push(...await l(i)):r.isFile()&&r.name.endsWith(".json")&&e.push(i)}return e}catch(t){if(y(t))return[];throw t}}export{b as FileCacheStore};
@@ -1 +1 @@
1
- import{CliError as f}from"../../domain/errors/cli-error.js";import{CLI_ERROR_CODES as b}from"../../domain/errors/error-codes.js";import{WindowsClipboardAdapter as h}from"./windows-clipboard-adapter.js";import{detectHostPlatform as c}from"../platform/host-platform.js";import{spawnPlatformProcess as w}from"../platform/host-process.js";import{CLIPBOARD_POLICY as d,clipboardUnavailableError as m,isClipboardUnavailableError as C}from"./clipboard-policy.js";function O(r=c()){return r.id==="windows"?new h(r):r.id==="macos"?new u([new p("pbpaste",["-Prefer","png"],"image/png",r)]):r.id==="linux"||r.id==="bsd"?new u([new p("wl-paste",["--no-newline","--type","image/png"],"image/png",r),new p("xclip",["-selection","clipboard","-target","image/png","-out"],"image/png",r)]):new y}class p{command;args;mimeType;platform;constructor(t,i,e,o=c()){this.command=t,this.args=i,this.mimeType=e,this.platform=o}async readImage(){return new Promise((t,i)=>{const e=w(this.command,this.args,this.platform,{stdio:["ignore","pipe","pipe"]}),o=[];let l=0,n=!1;const s=a=>{n||(n=!0,clearTimeout(g),a())},g=setTimeout(()=>{e.kill(),s(()=>i(m(`Clipboard image read timed out after ${d.timeoutMs}ms.`)))},d.timeoutMs);e.stdout?.on("data",a=>{if(!n){if(l+=a.byteLength,l>d.maxImageBytes){e.kill(),s(()=>i(new f(b.ATTACHMENT_TOO_LARGE,"Clipboard image is too large.",{category:"attachment",userMessage:"Clipboard image exceeds the maximum allowed size."})));return}o.push(a)}}),e.once("error",()=>s(()=>t(void 0))),e.once("close",a=>{s(()=>{a!==0||o.length===0?t(void 0):t({bytes:Buffer.concat(o),mimeType:this.mimeType})})})})}}class u{adapters;constructor(t){this.adapters=t}async readImage(){let t;for(const i of this.adapters)try{const e=await i.readImage();if(e!==void 0)return e}catch(e){if(!C(e))throw e;t=e}throw t??m("No supported clipboard image provider was found.")}}class y{async readImage(){throw m("Clipboard image support is unavailable on this platform.")}}export{p as ProcessClipboardAdapter,O as createClipboardAdapter};
1
+ import{CliError as d}from"../../domain/errors/cli-error.js";import{CLI_ERROR_CODES as l}from"../../domain/errors/error-codes.js";import{WindowsClipboardAdapter as c}from"./windows-clipboard-adapter.js";import{detectHostPlatform as n}from"../platform/host-platform.js";import{CLIPBOARD_POLICY as o,clipboardUnavailableError as t,isClipboardUnavailableError as g}from"./clipboard-policy.js";import{runBoundedClipboardProcess as u}from"./clipboard-process.js";function A(r=n()){return r.id==="windows"?new c(r):r.id==="macos"?new m([new s("pbpaste",["-Prefer","png"],"image/png",r)]):r.id==="linux"||r.id==="bsd"?new m([new s("wl-paste",["--no-newline","--type","image/png"],"image/png",r),new s("xclip",["-selection","clipboard","-target","image/png","-out"],"image/png",r)]):new b}class s{command;args;mimeType;platform;constructor(e,i,a,p=n()){this.command=e,this.args=i,this.mimeType=a,this.platform=p}async readImage(){try{const e=await u({command:this.command,args:this.args,platform:this.platform,maxStdoutBytes:o.maxImageBytes,maxStderrBytes:o.maxImageBytes,timeoutMs:o.timeoutMs,stdoutLimitError:new d(l.ATTACHMENT_TOO_LARGE,"Clipboard image is too large.",{category:"attachment",userMessage:"Clipboard image exceeds the maximum allowed size."}),stderrLimitError:t("Clipboard image helper diagnostics exceeded the supported limit.")});return e.exitCode===0&&e.stdout.length>0?{bytes:e.stdout,mimeType:this.mimeType}:void 0}catch(e){throw e instanceof d?e:t("Unable to read an image from the clipboard.",e)}}}class m{adapters;constructor(e){this.adapters=e}async readImage(){let e;for(const i of this.adapters)try{const a=await i.readImage();if(a!==void 0)return a}catch(a){if(!g(a))throw a;e=a}throw e??t("No supported clipboard image provider was found.")}}class b{async readImage(){throw t("Clipboard image support is unavailable on this platform.")}}export{s as ProcessClipboardAdapter,A as createClipboardAdapter};
@@ -0,0 +1 @@
1
+ export declare const IMAGE_MIME_SIGNATURES: Map<string, string>;
@@ -0,0 +1 @@
1
+ const a=new Map([["89504e470d0a1a0a","image/png"],["ffd8ff","image/jpeg"],["47494638","image/gif"],["424d","image/bmp"]]);export{a as IMAGE_MIME_SIGNATURES};
@@ -0,0 +1,20 @@
1
+ import type { SpawnOptions } from 'node:child_process';
2
+ import type { HostPlatformContext } from '../platform/host-platform.js';
3
+ export interface BoundedClipboardProcessOptions {
4
+ readonly command: string;
5
+ readonly args: readonly string[];
6
+ readonly platform: HostPlatformContext;
7
+ readonly maxStdoutBytes: number;
8
+ readonly maxStderrBytes: number;
9
+ readonly timeoutMs: number;
10
+ readonly env?: NonNullable<SpawnOptions['env']>;
11
+ readonly stdoutLimitError: Error;
12
+ readonly stderrLimitError: Error;
13
+ }
14
+ export interface BoundedClipboardProcessResult {
15
+ readonly stdout: Buffer;
16
+ readonly stderr: Buffer;
17
+ readonly exitCode: number | null;
18
+ }
19
+ /** Runs a clipboard helper with bounded pipes and confirmed process termination. */
20
+ export declare function runBoundedClipboardProcess(options: BoundedClipboardProcessOptions): Promise<BoundedClipboardProcessResult>;
@@ -0,0 +1 @@
1
+ import{spawnPlatformProcess as w,terminatePlatformProcess as x}from"../platform/host-process.js";function v(t){return new Promise((g,u)=>{const o=w(t.command,t.args,t.platform,{env:t.env,stdio:["ignore","pipe","pipe"]}),f=[],l=[];let m=0,c=0,s=!1,r=!1,a;const y=()=>{a!==void 0&&clearTimeout(a)},n=e=>{s||(s=!0,y(),e())},p=e=>{s||r||(r=!0,x(o,t.platform).then(()=>n(()=>u(e)),d=>n(()=>u(new AggregateError([e,d],"Clipboard helper termination could not be confirmed.")))))},B=(e,d,P,b,h)=>{const i=P+d.byteLength;return i>b?(p(h),i):(e.push(d),i)};o.stdout?.on("data",e=>{!s&&!r&&(m=B(f,e,m,t.maxStdoutBytes,t.stdoutLimitError))}),o.stderr?.on("data",e=>{!s&&!r&&(c=B(l,e,c,t.maxStderrBytes,t.stderrLimitError))}),o.once("error",e=>{r||n(()=>u(e))}),o.once("close",e=>{r||n(()=>g({stdout:Buffer.concat(f),stderr:Buffer.concat(l),exitCode:e}))}),a=setTimeout(()=>p(new Error(`Clipboard helper timed out after ${t.timeoutMs}ms.`)),t.timeoutMs)})}export{v as runBoundedClipboardProcess};
@@ -1 +1 @@
1
- import{CliError as f}from"../../domain/errors/cli-error.js";import{CLI_ERROR_CODES as x}from"../../domain/errors/error-codes.js";import{WindowsClipboardTextAdapter as b}from"./windows-clipboard-text-adapter.js";import{detectHostPlatform as u}from"../platform/host-platform.js";import{spawnPlatformProcess as h}from"../platform/host-process.js";import{CLIPBOARD_POLICY as d,clipboardUnavailableError as l,isClipboardUnavailableError as w}from"./clipboard-policy.js";function L(e=u()){return e.id==="windows"?new b(e):e.id==="macos"?new p("pbpaste",[],e):e.id==="linux"||e.id==="bsd"?new C([new p("wl-paste",["--no-newline"],e),new p("xclip",["-selection","clipboard","-out"],e)]):new T}class p{command;args;platform;constructor(r,o,t=u()){this.command=r,this.args=o,this.platform=t}async readText(){return new Promise((r,o)=>{const t=h(this.command,this.args,this.platform,{stdio:["ignore","pipe","pipe"]}),s=[];let c=0,n=!1;const a=i=>{n||(n=!0,clearTimeout(m),i())},m=setTimeout(()=>{t.kill(),a(()=>o(l(`Clipboard text read timed out after ${d.timeoutMs}ms.`)))},d.timeoutMs);t.stdout?.on("data",i=>{if(!n){if(c+=i.byteLength,c>d.maxTextBytes){t.kill(),a(()=>o(new f(x.ATTACHMENT_TOO_LARGE,"Clipboard text is too large.",{category:"attachment",userMessage:"Clipboard text exceeds the maximum allowed size."})));return}s.push(i)}}),t.once("error",()=>a(()=>r(void 0))),t.once("close",i=>a(()=>{i!==0||s.length===0?r(void 0):r(Buffer.concat(s).toString("utf8"))}))})}}class C{adapters;constructor(r){this.adapters=r}async readText(){let r;for(const o of this.adapters)try{const t=await o.readText();if(t!==void 0)return t}catch(t){if(!w(t))throw t;r=t}throw r??l("No supported clipboard text provider was found.")}}class T{async readText(){throw l("Clipboard text support is unavailable on this platform.")}}export{p as ProcessClipboardTextAdapter,L as createClipboardTextAdapter};
1
+ import{CliError as d}from"../../domain/errors/cli-error.js";import{CLI_ERROR_CODES as p}from"../../domain/errors/error-codes.js";import{WindowsClipboardTextAdapter as l}from"./windows-clipboard-text-adapter.js";import{detectHostPlatform as n}from"../platform/host-platform.js";import{CLIPBOARD_POLICY as i,clipboardUnavailableError as o,isClipboardUnavailableError as c}from"./clipboard-policy.js";import{runBoundedClipboardProcess as m}from"./clipboard-process.js";function g(r=n()){return r.id==="windows"?new l(r):r.id==="macos"?new s("pbpaste",[],r):r.id==="linux"||r.id==="bsd"?new u([new s("wl-paste",["--no-newline"],r),new s("xclip",["-selection","clipboard","-out"],r)]):new x}class s{command;args;platform;constructor(t,a,e=n()){this.command=t,this.args=a,this.platform=e}async readText(){try{const t=await m({command:this.command,args:this.args,platform:this.platform,maxStdoutBytes:i.maxTextBytes,maxStderrBytes:i.maxTextBytes,timeoutMs:i.timeoutMs,stdoutLimitError:new d(p.ATTACHMENT_TOO_LARGE,"Clipboard text is too large.",{category:"attachment",userMessage:"Clipboard text exceeds the maximum allowed size."}),stderrLimitError:o("Clipboard text helper diagnostics exceeded the supported limit.")});return t.exitCode===0&&t.stdout.length>0?t.stdout.toString("utf8"):void 0}catch(t){throw t instanceof d?t:o("Unable to read text from the clipboard.",t)}}}class u{adapters;constructor(t){this.adapters=t}async readText(){let t;for(const a of this.adapters)try{const e=await a.readText();if(e!==void 0)return e}catch(e){if(!c(e))throw e;t=e}throw t??o("No supported clipboard text provider was found.")}}class x{async readText(){throw o("Clipboard text support is unavailable on this platform.")}}export{s as ProcessClipboardTextAdapter,g as createClipboardTextAdapter};