llmz 0.9.0 → 1.0.2

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 (238) hide show
  1. package/DOCS.md +232 -1794
  2. package/ERRORS.md +101 -0
  3. package/README.md +96 -582
  4. package/dist/chat/chat.d.ts +63 -0
  5. package/dist/chat/component.d.ts +31 -0
  6. package/dist/chat/component.default.d.ts +58 -0
  7. package/dist/chat/response.d.ts +15 -0
  8. package/dist/compiler/compiler.d.ts +2 -7
  9. package/dist/compiler/plugins/dynamic-code.d.ts +7 -0
  10. package/dist/compiler/plugins/replace-comment.d.ts +2 -3
  11. package/dist/compiler/plugins/return-async.d.ts +5 -4
  12. package/dist/compiler/plugins/termination.d.ts +8 -0
  13. package/dist/compiler/plugins/tool-resolution.d.ts +4 -0
  14. package/dist/compiler/plugins/variable-extraction.d.ts +2 -8
  15. package/dist/component-CMFoCHyu.cjs +649 -0
  16. package/dist/component-DncqP4fB.js +614 -0
  17. package/dist/context.d.ts +71 -378
  18. package/dist/custom-client-C-WXvLD9.js +1655 -0
  19. package/dist/custom-client-Cgt9_0r1.cjs +1732 -0
  20. package/dist/custom-client.d.ts +12 -2
  21. package/dist/errors/catalog.d.ts +294 -0
  22. package/dist/errors/hooks.d.ts +2 -0
  23. package/dist/errors-C6ppQUZX.cjs +893 -0
  24. package/dist/errors-Crk5P8jo.js +636 -0
  25. package/dist/errors.d.ts +24 -36
  26. package/dist/execute-CiYvPs5Q.js +2061 -0
  27. package/dist/execute-DTTfacsi.cjs +2062 -0
  28. package/dist/{exit-DUM96DN1.cjs → exit-BOtKWPuT.cjs} +38 -28
  29. package/dist/{exit-CDdxDBRT.js → exit-DMPwCSba.js} +37 -27
  30. package/dist/exit.d.ts +19 -16
  31. package/dist/index.cjs +177 -1237
  32. package/dist/index.d.ts +25 -28
  33. package/dist/index.js +137 -1213
  34. package/dist/index.workerd.js +8974 -11145
  35. package/dist/inspect.d.ts +18 -4
  36. package/dist/inspection.d.ts +40 -0
  37. package/dist/native-0bq5ATZM.cjs +212 -0
  38. package/dist/native-n_718Z-T.js +177 -0
  39. package/dist/objects.d.ts +2 -57
  40. package/dist/prompts/native.d.ts +2 -0
  41. package/dist/prompts/prompt.d.ts +10 -101
  42. package/dist/quickjs-variant-21IO97PF.cjs +1080 -0
  43. package/dist/quickjs-variant-CtuGagsb.js +985 -0
  44. package/dist/result.d.ts +30 -861
  45. package/dist/runtime/execute.d.ts +3 -2
  46. package/dist/runtime/execution-activity.d.ts +11 -0
  47. package/dist/runtime/execution-diagnostics.d.ts +11 -0
  48. package/dist/runtime/execution-report.d.ts +51 -0
  49. package/dist/runtime/fixtures/chat.d.ts +8 -0
  50. package/dist/runtime/fixtures/long-search.d.ts +1 -1
  51. package/dist/runtime/fixtures/native-client.d.ts +33 -0
  52. package/dist/runtime/fixtures/protocol-languages.d.ts +1 -1
  53. package/dist/runtime/forced-inspection.d.ts +13 -0
  54. package/dist/runtime/forced-inspection.test.d.ts +1 -0
  55. package/dist/runtime/generate.d.ts +23 -20
  56. package/dist/runtime/generate.test.d.ts +1 -0
  57. package/dist/runtime/hook-provenance.test.d.ts +1 -0
  58. package/dist/runtime/inspection-hook.test.d.ts +1 -0
  59. package/dist/runtime/inspection-values.d.ts +14 -0
  60. package/dist/runtime/inspection-values.test.d.ts +1 -0
  61. package/dist/runtime/interruption-control-flow.test.d.ts +1 -0
  62. package/dist/runtime/interruption-settings.test.d.ts +1 -0
  63. package/dist/runtime/javascript-api.d.ts +62 -0
  64. package/dist/runtime/javascript-api.test.d.ts +1 -0
  65. package/dist/runtime/native-review.test.d.ts +1 -0
  66. package/dist/runtime/native-tools.d.ts +18 -0
  67. package/dist/runtime/native-tools.test.d.ts +1 -0
  68. package/dist/runtime/object-memory.test.d.ts +1 -0
  69. package/dist/runtime/single-tool.test.d.ts +1 -0
  70. package/dist/runtime/think-signal.test.d.ts +1 -0
  71. package/dist/runtime/token-budget.d.ts +22 -0
  72. package/dist/runtime/token-budget.test.d.ts +1 -0
  73. package/dist/runtime/tool-wrapper.d.ts +6 -5
  74. package/dist/runtime/traces.test.d.ts +1 -0
  75. package/dist/runtime/truncation.test.d.ts +1 -0
  76. package/dist/runtime/types.d.ts +47 -31
  77. package/dist/runtime/variable-recovery.test.d.ts +1 -0
  78. package/dist/runtime/vm-context.d.ts +6 -1
  79. package/dist/runtime/worker-completion.test.d.ts +1 -0
  80. package/dist/runtime-names.d.ts +4 -0
  81. package/dist/schema-CXlnbb3n.cjs +68 -0
  82. package/dist/schema-GE4ISPCR.js +45 -0
  83. package/dist/schema.d.ts +10 -0
  84. package/dist/schema.test.d.ts +1 -0
  85. package/dist/session/compactor.d.ts +51 -0
  86. package/dist/session/compactor.test.d.ts +1 -0
  87. package/dist/session/history.d.ts +36 -0
  88. package/dist/session/history.test.d.ts +1 -0
  89. package/dist/session/json.d.ts +3 -0
  90. package/dist/session/json.test.d.ts +1 -0
  91. package/dist/session/memory-codec.d.ts +9 -0
  92. package/dist/session/memory-codec.test.d.ts +1 -0
  93. package/dist/session/memory-render.d.ts +15 -0
  94. package/dist/session/memory-render.test.d.ts +1 -0
  95. package/dist/session/memory.d.ts +112 -0
  96. package/dist/session/memory.test.d.ts +1 -0
  97. package/dist/session/messages.d.ts +19 -0
  98. package/dist/session/messages.test.d.ts +1 -0
  99. package/dist/session/serialization.d.ts +36 -0
  100. package/dist/session/serialization.test.d.ts +1 -0
  101. package/dist/session/session-memory.test.d.ts +1 -0
  102. package/dist/session/session.d.ts +121 -0
  103. package/dist/session/session.test.d.ts +1 -0
  104. package/dist/session/speaker.test.d.ts +1 -0
  105. package/dist/{transcript.d.ts → session/transcript.d.ts} +4 -8
  106. package/dist/session/transcript.test.d.ts +1 -0
  107. package/dist/{tool-Bv8N4IPj.js → tool-DstssiAs.js} +144 -92
  108. package/dist/{tool-Dy6AJpJH.cjs → tool-_wK9hQOb.cjs} +146 -94
  109. package/dist/tool.d.ts +25 -17
  110. package/dist/truncate-BEKbdo3t.js +79 -0
  111. package/dist/truncate-uomAMGPs.cjs +102 -0
  112. package/dist/truncate.d.ts +24 -0
  113. package/dist/truncate.test.d.ts +1 -0
  114. package/dist/types.d.ts +33 -9
  115. package/dist/{typings-3lsqCbkn.cjs → typings-BA_XxAcY.cjs} +38 -193
  116. package/dist/{typings-CrBa7Tyy.js → typings-BEVDvtuk.js} +38 -175
  117. package/dist/typings-formatter.d.ts +1 -1
  118. package/dist/typings.d.ts +3 -0
  119. package/dist/{uniq-BYQ7GWwb.js → uniq-DfUeSNaX.js} +2 -2
  120. package/dist/{uniq-G872RWmE.cjs → uniq-DiXgysNV.cjs} +6 -18
  121. package/dist/{_baseIteratee-P_firB7b.js → utils-BOFzb8Ok.js} +1134 -16
  122. package/dist/{_baseIteratee-CF4qP2a8.cjs → utils-CTlsXvdj.cjs} +1281 -84
  123. package/dist/vm/drivers/node.d.ts +1 -1
  124. package/dist/vm/drivers/quickjs.d.ts +1 -1
  125. package/dist/vm/errors.d.ts +4 -4
  126. package/dist/vm/index.d.ts +3 -4
  127. package/dist/vm/instrument.d.ts +14 -6
  128. package/dist/vm/member-proxy.d.ts +4 -0
  129. package/dist/vm/member-proxy.test.d.ts +1 -0
  130. package/dist/vm/memory.test.d.ts +1 -0
  131. package/dist/vm/return-semantics.test.d.ts +1 -0
  132. package/dist/vm/types.d.ts +20 -3
  133. package/dist/{vm-BLsHw1da.js → vm-C7SfutHn.js} +1187 -180
  134. package/dist/{vm-D6s1zF6M.cjs → vm-gmekHc0i.cjs} +1221 -207
  135. package/package.json +13 -6
  136. package/dist/_baseForOwn-BfWDTL8L.cjs +0 -53
  137. package/dist/_baseForOwn-CFhWe_W6.js +0 -48
  138. package/dist/_getPrototype-CG7Dxrrz.js +0 -6
  139. package/dist/_getPrototype-DQDlNVVM.cjs +0 -10
  140. package/dist/_overArg-C5Hy7oCi.cjs +0 -196
  141. package/dist/_overArg-CRYbj1NH.js +0 -155
  142. package/dist/chat.d.ts +0 -401
  143. package/dist/common-BlRFtdf2.js +0 -807
  144. package/dist/common-BnvrDnIT.cjs +0 -860
  145. package/dist/compiler/plugins/track-tool-calls.d.ts +0 -33
  146. package/dist/compiler-C-OI9sim.cjs +0 -547
  147. package/dist/compiler-CW1VjQsn.js +0 -473
  148. package/dist/component-C6Agl2ns.cjs +0 -73
  149. package/dist/component-DGG7d_Mz.js +0 -44
  150. package/dist/component.d.ts +0 -88
  151. package/dist/component.default.d.ts +0 -278
  152. package/dist/custom-client-ChuZ63zp.js +0 -2658
  153. package/dist/custom-client-DAsGRnYc.cjs +0 -2729
  154. package/dist/dual-modes-DDkoCp3R.js +0 -3006
  155. package/dist/dual-modes-DPXiuvNe.cjs +0 -3090
  156. package/dist/errors-C962uJdS.cjs +0 -220
  157. package/dist/errors-Cg1G0Awu.js +0 -161
  158. package/dist/example-format.d.ts +0 -8
  159. package/dist/example.d.ts +0 -45
  160. package/dist/execute-BWcdv9so.js +0 -1059
  161. package/dist/execute-DM2-7y86.cjs +0 -1060
  162. package/dist/exit-parser.d.ts +0 -39
  163. package/dist/handlers.d.ts +0 -10
  164. package/dist/hoist.d.ts +0 -2
  165. package/dist/isEmpty-BhJRCqIF.js +0 -52
  166. package/dist/isEmpty-LY533Wmh.cjs +0 -57
  167. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  168. package/dist/isPlainObject-D39AzPO2.js +0 -51
  169. package/dist/jsx-CIgdGGVs.js +0 -52
  170. package/dist/jsx-owqxrquU.cjs +0 -75
  171. package/dist/jsx.d.ts +0 -11
  172. package/dist/message-stream/index.d.ts +0 -9
  173. package/dist/message-stream/instructions.d.ts +0 -30
  174. package/dist/message-stream/normalizer.d.ts +0 -21
  175. package/dist/message-stream/parser.d.ts +0 -89
  176. package/dist/message-stream/registry.d.ts +0 -14
  177. package/dist/message-stream/replayable.d.ts +0 -27
  178. package/dist/message-stream/response-parser.d.ts +0 -24
  179. package/dist/message-stream/sanitize.d.ts +0 -10
  180. package/dist/message-stream/stream.d.ts +0 -54
  181. package/dist/message-stream/types.d.ts +0 -97
  182. package/dist/message-stream/validator.d.ts +0 -23
  183. package/dist/prompts/chat-mode/protocol.d.ts +0 -2
  184. package/dist/prompts/chat-mode/system.d.ts +0 -2
  185. package/dist/prompts/chat-mode/system.md.d.ts +0 -2
  186. package/dist/prompts/chat-mode/user.d.ts +0 -2
  187. package/dist/prompts/chat-mode/user.md.d.ts +0 -2
  188. package/dist/prompts/code-examples.d.ts +0 -2
  189. package/dist/prompts/common.d.ts +0 -7
  190. package/dist/prompts/dual-modes.d.ts +0 -2
  191. package/dist/prompts/execution-history.d.ts +0 -6
  192. package/dist/prompts/execution-state.d.ts +0 -3
  193. package/dist/prompts/protocol-basics.d.ts +0 -5
  194. package/dist/prompts/protocol.d.ts +0 -31
  195. package/dist/prompts/worker-mode/protocol.d.ts +0 -2
  196. package/dist/prompts/worker-mode/system.d.ts +0 -2
  197. package/dist/prompts/worker-mode/system.md.d.ts +0 -2
  198. package/dist/prompts/worker-mode/user.d.ts +0 -2
  199. package/dist/prompts/worker-mode/user.md.d.ts +0 -2
  200. package/dist/quickjs-variant-BYhMBpwU.js +0 -45
  201. package/dist/quickjs-variant-CsIwTVFC.cjs +0 -56
  202. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  203. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +0 -29
  204. package/dist/runtime/interpret-result.d.ts +0 -22
  205. package/dist/snapshots.d.ts +0 -249
  206. package/dist/stack-traces-BIE_5Xwf.js +0 -21
  207. package/dist/stack-traces-ntw_qhoy.cjs +0 -26
  208. package/dist/truncator-CLkouTCO.cjs +0 -276
  209. package/dist/truncator-DZqEqnpD.js +0 -253
  210. package/dist/truncator.d.ts +0 -118
  211. package/dist/utils-3ESwP3yg.cjs +0 -1075
  212. package/dist/utils-UBeAFeEI.js +0 -950
  213. /package/dist/{citations.d.ts → chat/citations.d.ts} +0 -0
  214. /package/dist/{citations.test.d.ts → chat/citations.test.d.ts} +0 -0
  215. /package/dist/{component.default.test.d.ts → chat/component.default.test.d.ts} +0 -0
  216. /package/dist/{compiler/plugins/track-tool-calls.test.d.ts → chat/component.test.d.ts} +0 -0
  217. /package/dist/{example.test.d.ts → chat/response.test.d.ts} +0 -0
  218. /package/dist/{exit-parser.test.d.ts → compiler/plugins/dynamic-code.test.d.ts} +0 -0
  219. /package/dist/{handlers.test.d.ts → compiler/plugins/tool-resolution.test.d.ts} +0 -0
  220. /package/dist/{hoist.test.d.ts → errors/catalog.test.d.ts} +0 -0
  221. /package/dist/{message-stream/instructions.test.d.ts → exit.test.d.ts} +0 -0
  222. /package/dist/{message-stream/normalizer.test.d.ts → inspection.test.d.ts} +0 -0
  223. /package/dist/{message-stream/parser.test.d.ts → prompts/native.test.d.ts} +0 -0
  224. /package/dist/{message-stream/response-parser.test.d.ts → result.test.d.ts} +0 -0
  225. /package/dist/{message-stream/stream.test.d.ts → runtime/chat-completion.test.d.ts} +0 -0
  226. /package/dist/{message-stream/validator.test.d.ts → runtime/chat-delivery.test.d.ts} +0 -0
  227. /package/dist/{prompts/adherence.test.d.ts → runtime/chat-last-speaker.test.d.ts} +0 -0
  228. /package/dist/{prompts/catalogue-examples.test.d.ts → runtime/compatibility-regressions.test.d.ts} +0 -0
  229. /package/dist/{prompts/code-examples.test.d.ts → runtime/context-registration.test.d.ts} +0 -0
  230. /package/dist/{prompts/common.test.d.ts → runtime/empty-completion.test.d.ts} +0 -0
  231. /package/dist/{prompts/concrete-patterns.test.d.ts → runtime/error-recovery.test.d.ts} +0 -0
  232. /package/dist/{prompts/long-search.test.d.ts → runtime/errors.test.d.ts} +0 -0
  233. /package/dist/{prompts/protocol-simple.test.d.ts → runtime/execution-activity.test.d.ts} +0 -0
  234. /package/dist/{prompts/protocol.test.d.ts → runtime/execution-diagnostics.test.d.ts} +0 -0
  235. /package/dist/{prompts/sections.test.d.ts → runtime/execution-report.test.d.ts} +0 -0
  236. /package/dist/runtime/{interpret-result.test.d.ts → execution-safety.test.d.ts} +0 -0
  237. /package/dist/{transcript.test.d.ts → runtime/exit-control-flow.test.d.ts} +0 -0
  238. /package/dist/{truncator.test.d.ts → runtime/fixtures/long-search.test.d.ts} +0 -0
package/dist/inspect.d.ts CHANGED
@@ -1,8 +1,22 @@
1
- type PreviewOptions = {
1
+ import { type TruncatePreserve, type TruncationPolicy } from './truncate.js';
2
+ export type InspectionPolicyLookup = (value: unknown) => TruncationPolicy | undefined;
3
+ export type InspectOptions = {
2
4
  tokens: number;
3
- /** Latest tool results defer string clipping to the request context budget. */
5
+ /** Maximum characters shown from a string, within the overall token budget. */
4
6
  maxStringLength?: number;
7
+ /** Render a single-line value without headings or analysis. */
8
+ compact?: boolean;
9
+ /** Disable per-value overrides for compact inventories and other fixed budgets. */
10
+ honorTruncation?: boolean;
11
+ /** Policies retained for unchanged tool values during the current execution. */
12
+ policies?: InspectionPolicyLookup;
13
+ preserve?: TruncatePreserve;
5
14
  };
15
+ export declare function limitInspectionOutput(output: string, tokens: number, truncated: boolean, preserve?: TruncatePreserve): string;
6
16
  export declare function extractType(value: unknown, generic?: boolean): string;
7
- export declare const inspect: (value: unknown, name?: string, options?: PreviewOptions) => string;
8
- export {};
17
+ export declare function resolveInspectionBudget(value: unknown, options: InspectOptions): {
18
+ tokens: number;
19
+ preserve: TruncatePreserve;
20
+ explicit: boolean;
21
+ };
22
+ export declare const inspect: (value: unknown, name?: string, options?: InspectOptions) => string;
@@ -0,0 +1,40 @@
1
+ import { type InspectionPolicyLookup } from './inspect.js';
2
+ import { type TruncatePreserve } from './truncate.js';
3
+ export type InspectionPurpose = 'result' | 'variable' | 'property' | 'tool-input' | 'tool-output' | 'message' | 'error' | 'code' | 'event' | 'name';
4
+ export type InspectionIdentity = {
5
+ sessionId?: string;
6
+ turn?: number;
7
+ turnId?: string;
8
+ iteration?: number;
9
+ iterationId?: string;
10
+ variable?: string;
11
+ object?: string;
12
+ property?: string;
13
+ tool?: string;
14
+ component?: string;
15
+ name?: string;
16
+ };
17
+ export type InspectEvent = {
18
+ /** An isolated, read-only copy. Changing a preview never changes runtime memory. */
19
+ readonly value: unknown;
20
+ readonly purpose: InspectionPurpose;
21
+ readonly maxTokens: number;
22
+ readonly preserve: TruncatePreserve;
23
+ readonly compact: boolean;
24
+ readonly identity?: Readonly<InspectionIdentity>;
25
+ };
26
+ /** Return undefined to use LLMz's default formatter. Returned text remains token-bounded. */
27
+ export type OnInspect = (event: InspectEvent) => string | undefined;
28
+ export type InspectionOptions = {
29
+ purpose: InspectionPurpose;
30
+ maxTokens: number;
31
+ preserve?: TruncatePreserve;
32
+ compact?: boolean;
33
+ identity?: InspectionIdentity;
34
+ policies?: InspectionPolicyLookup;
35
+ };
36
+ export type Inspector = (value: unknown, options: InspectionOptions) => string;
37
+ /** The shared boundary for values displayed in prompts, reports, and memory inventories. */
38
+ export declare function createInspector(onInspect?: OnInspect): Inspector;
39
+ /** Isolate evidence from subsequent guest mutations without invoking getters. */
40
+ export declare function snapshotInspectionValue(value: unknown, copies?: WeakMap<object, unknown>): unknown;
@@ -0,0 +1,212 @@
1
+ const require_utils = require("./utils-CTlsXvdj.cjs");
2
+ const require_errors = require("./errors-C6ppQUZX.cjs");
3
+ const require_typings = require("./typings-BA_XxAcY.cjs");
4
+ //#region src/chat/response.ts
5
+ const presets = {
6
+ markdown: { instructions: "Write natural Markdown directly in the assistant response. Use paragraphs, lists, links, and code blocks where useful. Do not wrap the entire response in JSON or a Markdown fence." },
7
+ text: { instructions: "Write plain text directly in the assistant response. Use natural sentences and paragraph breaks. Do not use Markdown formatting, headings, tables, or code fences." },
8
+ speech: { instructions: "Write plain conversational prose for text-to-speech. Use short sentences that sound natural when spoken. Do not use Markdown, links, URLs, emojis, code, bullet points, tables, or headings. Spell out numbers, dates, units, and abbreviations as they should be pronounced." }
9
+ };
10
+ /** Resolve one response style for the entire generation, including its stream. */
11
+ function resolveResponse(response = "markdown") {
12
+ var _config$instructions;
13
+ const config = typeof response === "string" ? { preset: response } : response;
14
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new require_errors.InvalidConfigurationError("Chat response must be a preset or a response configuration.");
15
+ if (Object.keys(config).some((key) => ![
16
+ "preset",
17
+ "instructions",
18
+ "handler",
19
+ "onDelta"
20
+ ].includes(key))) throw new require_errors.InvalidConfigurationError("Chat response only accepts preset, instructions, handler, and onDelta.");
21
+ if (config.preset !== void 0 && (typeof config.preset !== "string" || !Object.hasOwn(presets, config.preset))) throw new require_errors.InvalidConfigurationError("Chat response preset must be \"markdown\", \"text\", or \"speech\".");
22
+ if (config.instructions !== void 0 && (typeof config.instructions !== "string" || !config.instructions.trim())) throw new require_errors.InvalidConfigurationError("Chat response instructions must be a non-empty string.");
23
+ for (const key of ["handler", "onDelta"]) if (config[key] !== void 0 && typeof config[key] !== "function") throw new require_errors.InvalidConfigurationError(`Chat response ${key} must be a function.`);
24
+ const presetName = config.preset ?? (config.instructions === void 0 ? "markdown" : void 0);
25
+ const preset = presetName === void 0 ? void 0 : presets[presetName];
26
+ return {
27
+ instructions: [preset === null || preset === void 0 ? void 0 : preset.instructions, (_config$instructions = config.instructions) === null || _config$instructions === void 0 ? void 0 : _config$instructions.trim()].filter(Boolean).join("\n\n"),
28
+ ...config.handler === void 0 ? {} : { handler: config.handler },
29
+ ...config.onDelta === void 0 ? {} : { onDelta: config.onDelta }
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/runtime/native-tools.ts
34
+ const WORKER_RESPONSE_INSTRUCTION = "You are running in worker mode. Respond only with a run_javascript tool call. Keep assistant text empty: do not send messages, preambles, progress updates, explanations, acknowledgements such as \"Done\", Markdown, or JSON outside the tool call. This applies before and after tools, during recovery, and when completing the task.";
35
+ const RUN_JAVASCRIPT_TOOL = {
36
+ name: "run_javascript",
37
+ description: "Run business tools, send requested chat components, or finish a worker task by executing JavaScript. For text plus actions, write the requested text as a preamble to this tool call; do not end with a text-only answer before the actions. Exact requested text needs no separator before this call: do not append a space or newline to the preamble. An ordinary chat reply with no remaining action needs no tool call just to finish the turn. Code displayed in an answer is text, not a program to execute. See \"run_javascript syntax\" and the documented functions and memory.",
38
+ parameters: {
39
+ type: "object",
40
+ properties: { code: {
41
+ type: "string",
42
+ minLength: 1,
43
+ description: "JavaScript source with an explicit return statement. Top-level await is supported."
44
+ } },
45
+ required: ["code"],
46
+ additionalProperties: false
47
+ }
48
+ };
49
+ /** Select delivery guidance without changing the native tool name or input schema. */
50
+ function getRunJavaScriptTool(chat) {
51
+ if (chat) return RUN_JAVASCRIPT_TOOL;
52
+ return {
53
+ ...RUN_JAVASCRIPT_TOOL,
54
+ description: `${WORKER_RESPONSE_INSTRUCTION} See "run_javascript syntax" and the documented functions and memory.`
55
+ };
56
+ }
57
+ /** Validate the entire response before any delivery or business action begins. */
58
+ function validateNativeToolCalls(calls) {
59
+ if (!calls.length) return { valid: true };
60
+ if (calls.length > 1) return {
61
+ valid: false,
62
+ errors: ["Use at most one run_javascript call per response. Put all operations inside its JavaScript program."]
63
+ };
64
+ const [call] = calls;
65
+ if (!call || typeof call.id !== "string" || !call.id.trim()) return {
66
+ valid: false,
67
+ errors: ["Every native tool call requires a non-empty ID."]
68
+ };
69
+ if (call.name !== RUN_JAVASCRIPT_TOOL.name) return {
70
+ valid: false,
71
+ errors: [`Unknown native tool ${JSON.stringify(call.name)}. Use run_javascript.`]
72
+ };
73
+ const input = call.input;
74
+ if (!input || typeof input !== "object" || Array.isArray(input)) return {
75
+ valid: false,
76
+ errors: ["Tool arguments must be a JSON object."]
77
+ };
78
+ if (Object.keys(input).some((key) => key !== "code") || typeof input.code !== "string" || !input.code.trim()) return {
79
+ valid: false,
80
+ errors: ["run_javascript requires exactly one non-empty code string."]
81
+ };
82
+ return {
83
+ valid: true,
84
+ call: {
85
+ id: call.id,
86
+ code: input.code
87
+ }
88
+ };
89
+ }
90
+ //#endregion
91
+ //#region src/prompts/native.ts
92
+ var native_exports = /* @__PURE__ */ require_utils.__exportAll({ getNativeSystemMessage: () => getNativeSystemMessage });
93
+ const runJavaScriptSyntax = [
94
+ "# run_javascript syntax",
95
+ "run_javascript is the only native tool. Call it with a JSON object containing exactly one property: \"code\", a non-empty string of JavaScript source.",
96
+ "The code string is the body of an async JavaScript program. Top-level await and return are supported. Send plain JavaScript without Markdown fences, an enclosing function, type annotations, imports, or JSX. eval, Function constructors, and dynamically generated code are not supported.",
97
+ "Make at most one run_javascript call per response. Put multiple operations in that program: await dependent business calls in order, or await Promise.all for independent operations when safe. Await all business operations before the final return, including unfinished siblings after a Promise.all failure.",
98
+ "Use only the functions documented in the JavaScript API and variables listed in Memory. Do not assume browser, network, filesystem, or package APIs are available.",
99
+ "Match each function signature exactly. A string parameter takes a string, not an object containing that string."
100
+ ].join("\n\n");
101
+ function runtimeRules(props, chat) {
102
+ const hasExits = props.exits.length > 0;
103
+ const listen = props.exits.find((exit) => exit.name.toLowerCase() === "listen");
104
+ const rules = [
105
+ "# Responses and execution",
106
+ hasExits ? "Every run_javascript program must explicitly return inspect(value) for inspection or return exit(\"NAME\", payload) with a registered name and its required payload for completion." : "Every run_javascript program must explicitly return inspect(value).",
107
+ "The only way for the model to see a business tool return value is return inspect(value). JavaScript can use tool results immediately to compute, branch, or call other functions. Inspection exposes the result in the next response.",
108
+ "If completing the task requires interpreting natural-language tool output, inspect it before constructing the completion payload. Do not substitute the whole returned text for an extracted field, guess facts, or fill required fields with placeholders. Structured results may be used directly when the program can compute the complete payload from them.",
109
+ "inspect(...) constructs an opaque decision that takes effect only when returned as the result of the JavaScript program. Never fabricate, serialize, or store a decision as persistent memory."
110
+ ];
111
+ if (chat) rules.push("Reply to the user with normal assistant text. Assistant text streams normally and is visible to the user. A completed response without tool calls finishes the turn. Choose text-only only when no requested action remains; a requested component or business operation requires a tool call in this response, even when you already wrote the requested text. Keep private reasoning out of assistant text.", "Follow the task's response constraints exactly. When exact text is requested, reproduce it byte-for-byte, without a greeting, explanation, translation, or extra whitespace. Do not add a leading or trailing space or newline, including before a tool call. This constrains assistant text, not the tool calls needed to carry out the task. Response style applies to free-form prose; it must not rewrite supplied text or code that the task asks you to preserve, including whitespace, quotes, and escapes. When transcribing source, check each line against the supplied source rather than completing familiar patterns from memory.", "Keep routine business lookups and recovery silent unless progress updates are requested; answer from inspected results. This does not suppress text explicitly requested alongside components. When more work remains, send a requested progress update alongside the run_javascript call that continues that work; a text-only update ends the turn.");
112
+ else {
113
+ rules.push(WORKER_RESPONSE_INSTRUCTION);
114
+ if (hasExits) rules.push("Complete the assigned task with return exit(\"NAME\", payload) inside JavaScript. Assistant prose alone does not complete a worker task. Every worker response, including completion after an inspection, must call run_javascript. Return the completion payload through exit, never as assistant text or a Markdown/JSON response.");
115
+ }
116
+ if (hasExits) rules.push("Complete all required work before returning the registered exit. JavaScript can compute its payload from tool results without another model response. Completion validates the payload and requires its hook to succeed. Omit the payload when an exit signature has no payload parameter.");
117
+ if (chat && props.exits.some((exit) => exit !== listen)) rules.push("When a known outcome matches a registered task exit description, return exit(\"NAME\", payload) for that outcome, even if you also explain it in assistant text. Prose does not select a typed exit.");
118
+ if (chat && listen) rules.push(`Use return exit(${JSON.stringify(listen.name)}) only when waiting for the user or when no task outcome matches another registered exit, within a program that already needs to run. A plain assistant reply automatically waits for the user when its text ends. Do not call run_javascript solely to listen after a text-only reply, even if the task says "then listen".`);
119
+ if (chat && props.components.size) {
120
+ rules.push("Send rich messages with the registered chat methods. Each method accepts its documented props, sends synchronously, and returns void; do not await it. Messages are delivered in invocation order. A component call does not finish the program; follow it with the required return.", `When the task requests text AND components, put the requested text in the assistant preamble to a native tool call, then call run_javascript to send the components. Use a tool-call response with a text preamble, not a final text-only answer. Both belong in this response.${hasExits ? " exit ends the turn and cannot send the missing text afterward." : ""} Text alone omits the components; components alone omit the text. When only components are requested, keep assistant output empty and do not add an acknowledgement afterward.`, "Never print a rich-message description instead of sending its component. Reuse acknowledged deliveries; a failed delivery may have an uncertain external outcome.");
121
+ if (listen) rules.push(`After sending all requested components, finish in the same program with return exit(${JSON.stringify(listen.name)}) when waiting for the user. Returning inspect(undefined) requests another response and does not finish the turn.`);
122
+ }
123
+ rules.push("Execution may overlap the remaining response stream. The runtime waits for the stream, code, and queued message deliveries before the next response.", "# Memory", "Declare retained variables at top level with const or let. Bare assignment only updates a variable already declared in this program or listed in Memory. Named variables survive transcript compaction; assignment age records when they were set, not when the underlying data was fetched.", "Object properties are immutable snapshots. Replace a writable property completely, such as account.profile = { ...account.profile, age: 42 }; nested edits are forbidden and replacements are schema-validated.", "$return is the latest successful inspection result. $iterations is read-only retained history, newest first: [0] is the last settled iteration and [1] the preceding one. The current execution is not included. Entries without results still occupy indexes; check hasResult. Compaction prunes automatic results. Assign useful data to named variables to retain it independently.", "# Recovery", "Execution reports identify completed actions, inspected values, memory changes, and errors. Reuse preserved variables and completed actions; retry only failed work. Build completion payloads from those values, not by calling successful tools again. An inspection has already run the recorded calls; it is not a dry run.", "An operational error does not by itself finish the task. Inspect the actual error, repair its cause when safe and authorized, then retry. Unchanged retries do not establish that recovery is exhausted. If another response must diagnose the error, return inspect({ errors, completed }) or let the error reach the runtime. Honor task instructions defining terminal failure outcomes.");
124
+ if (hasExits) rules.push("Use a failure exit only when recovery is unavailable, unsafe, forbidden, its budget is exhausted, or task instructions make the failure terminal. Do not select failure in advance for an unseen error. Do not turn an unexpected exception or rejected Promise.allSettled entry directly into failure completion: first expose it with inspect or let it reach the runtime, then diagnose the actual cause and available recovery tools. Explicit task instructions may define an error as terminal.");
125
+ rules.push("A tool may request forced inspection through ThinkSignal. The tool succeeded and its context is returned to JavaScript. Other calls and assignments continue normally. At the end of the program, forced inspection takes precedence over completion: review the reported results as an inspect() call, then continue from retained values without repeating successful calls.", "Respect tool-attempt limits separately from the model-response budget. An empty successful inspection result is not a failure.");
126
+ return rules.join("\n\n");
127
+ }
128
+ async function describeRuntimeAPI(props, chat) {
129
+ const declarations = ["declare function inspect<T>(value: T): InspectionDecision;"];
130
+ for (const exit of props.exits) {
131
+ const name = JSON.stringify(exit.name);
132
+ const description = `${exit.description}${!exit.zSchema && chat ? " This does not send a message." : ""}`;
133
+ const parameters = exit.zSchema ? `name: ${name}, payload${exit.zSchema.isOptional() ? "?" : ""}: ${await require_typings.getTypings(exit.zSchema)}` : `name: ${name}`;
134
+ declarations.push(require_utils.getMultilineComment(description), `declare function exit(${parameters}): never;`);
135
+ }
136
+ if (chat && props.components.size) {
137
+ declarations.push("declare const chat: {");
138
+ for (const [name, component] of props.components) declarations.push(require_utils.getMultilineComment(component.definition.description), `${name}(props: ${await require_typings.getTypings(component.definition.props)}): void;`);
139
+ declarations.push("};");
140
+ }
141
+ return "```typescript\n" + await require_typings.formatTypings(declarations.join("\n")) + "\n```";
142
+ }
143
+ async function getNativeSystemMessage(props) {
144
+ var _props$instructions;
145
+ const chat = props.isChatEnabled;
146
+ const declarations = await Promise.all([...props.objects.filter((object) => {
147
+ var _object$tools;
148
+ return (_object$tools = object.tools) === null || _object$tools === void 0 ? void 0 : _object$tools.length;
149
+ }).map((object) => object.getToolTypings()), ...props.globalTools.map((tool) => tool.getTypings())]);
150
+ const instructions = ((_props$instructions = props.instructions) === null || _props$instructions === void 0 ? void 0 : _props$instructions.trim()) || "Carry out the assigned task.";
151
+ const tools = [await describeRuntimeAPI(props, chat), ...declarations.length ? ["```typescript\n" + declarations.join("\n\n") + "\n```"] : []].join("\n\n");
152
+ const protocol = [
153
+ runJavaScriptSyntax,
154
+ runtimeRules(props, chat),
155
+ ...chat ? ["# Assistant response", (props.response ?? resolveResponse()).instructions] : []
156
+ ].join("\n\n");
157
+ return {
158
+ message: {
159
+ role: "system",
160
+ content: [
161
+ protocol,
162
+ "# JavaScript API",
163
+ "These TypeScript declarations describe functions inside run_javascript. Object properties, their types, values, and read/write rules are listed in Memory.",
164
+ tools,
165
+ "# Task instructions",
166
+ instructions
167
+ ].join("\n\n")
168
+ },
169
+ parts: {
170
+ instructions,
171
+ tools,
172
+ protocol
173
+ }
174
+ };
175
+ }
176
+ //#endregion
177
+ Object.defineProperty(exports, "WORKER_RESPONSE_INSTRUCTION", {
178
+ enumerable: true,
179
+ get: function() {
180
+ return WORKER_RESPONSE_INSTRUCTION;
181
+ }
182
+ });
183
+ Object.defineProperty(exports, "getNativeSystemMessage", {
184
+ enumerable: true,
185
+ get: function() {
186
+ return getNativeSystemMessage;
187
+ }
188
+ });
189
+ Object.defineProperty(exports, "getRunJavaScriptTool", {
190
+ enumerable: true,
191
+ get: function() {
192
+ return getRunJavaScriptTool;
193
+ }
194
+ });
195
+ Object.defineProperty(exports, "native_exports", {
196
+ enumerable: true,
197
+ get: function() {
198
+ return native_exports;
199
+ }
200
+ });
201
+ Object.defineProperty(exports, "resolveResponse", {
202
+ enumerable: true,
203
+ get: function() {
204
+ return resolveResponse;
205
+ }
206
+ });
207
+ Object.defineProperty(exports, "validateNativeToolCalls", {
208
+ enumerable: true,
209
+ get: function() {
210
+ return validateNativeToolCalls;
211
+ }
212
+ });
@@ -0,0 +1,177 @@
1
+ import { Y as __exportAll, i as getMultilineComment } from "./utils-BOFzb8Ok.js";
2
+ import { b as InvalidConfigurationError } from "./errors-Crk5P8jo.js";
3
+ import { i as formatTypings, t as getTypings } from "./typings-BEVDvtuk.js";
4
+ //#region src/chat/response.ts
5
+ const presets = {
6
+ markdown: { instructions: "Write natural Markdown directly in the assistant response. Use paragraphs, lists, links, and code blocks where useful. Do not wrap the entire response in JSON or a Markdown fence." },
7
+ text: { instructions: "Write plain text directly in the assistant response. Use natural sentences and paragraph breaks. Do not use Markdown formatting, headings, tables, or code fences." },
8
+ speech: { instructions: "Write plain conversational prose for text-to-speech. Use short sentences that sound natural when spoken. Do not use Markdown, links, URLs, emojis, code, bullet points, tables, or headings. Spell out numbers, dates, units, and abbreviations as they should be pronounced." }
9
+ };
10
+ /** Resolve one response style for the entire generation, including its stream. */
11
+ function resolveResponse(response = "markdown") {
12
+ var _config$instructions;
13
+ const config = typeof response === "string" ? { preset: response } : response;
14
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new InvalidConfigurationError("Chat response must be a preset or a response configuration.");
15
+ if (Object.keys(config).some((key) => ![
16
+ "preset",
17
+ "instructions",
18
+ "handler",
19
+ "onDelta"
20
+ ].includes(key))) throw new InvalidConfigurationError("Chat response only accepts preset, instructions, handler, and onDelta.");
21
+ if (config.preset !== void 0 && (typeof config.preset !== "string" || !Object.hasOwn(presets, config.preset))) throw new InvalidConfigurationError("Chat response preset must be \"markdown\", \"text\", or \"speech\".");
22
+ if (config.instructions !== void 0 && (typeof config.instructions !== "string" || !config.instructions.trim())) throw new InvalidConfigurationError("Chat response instructions must be a non-empty string.");
23
+ for (const key of ["handler", "onDelta"]) if (config[key] !== void 0 && typeof config[key] !== "function") throw new InvalidConfigurationError(`Chat response ${key} must be a function.`);
24
+ const presetName = config.preset ?? (config.instructions === void 0 ? "markdown" : void 0);
25
+ const preset = presetName === void 0 ? void 0 : presets[presetName];
26
+ return {
27
+ instructions: [preset === null || preset === void 0 ? void 0 : preset.instructions, (_config$instructions = config.instructions) === null || _config$instructions === void 0 ? void 0 : _config$instructions.trim()].filter(Boolean).join("\n\n"),
28
+ ...config.handler === void 0 ? {} : { handler: config.handler },
29
+ ...config.onDelta === void 0 ? {} : { onDelta: config.onDelta }
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/runtime/native-tools.ts
34
+ const WORKER_RESPONSE_INSTRUCTION = "You are running in worker mode. Respond only with a run_javascript tool call. Keep assistant text empty: do not send messages, preambles, progress updates, explanations, acknowledgements such as \"Done\", Markdown, or JSON outside the tool call. This applies before and after tools, during recovery, and when completing the task.";
35
+ const RUN_JAVASCRIPT_TOOL = {
36
+ name: "run_javascript",
37
+ description: "Run business tools, send requested chat components, or finish a worker task by executing JavaScript. For text plus actions, write the requested text as a preamble to this tool call; do not end with a text-only answer before the actions. Exact requested text needs no separator before this call: do not append a space or newline to the preamble. An ordinary chat reply with no remaining action needs no tool call just to finish the turn. Code displayed in an answer is text, not a program to execute. See \"run_javascript syntax\" and the documented functions and memory.",
38
+ parameters: {
39
+ type: "object",
40
+ properties: { code: {
41
+ type: "string",
42
+ minLength: 1,
43
+ description: "JavaScript source with an explicit return statement. Top-level await is supported."
44
+ } },
45
+ required: ["code"],
46
+ additionalProperties: false
47
+ }
48
+ };
49
+ /** Select delivery guidance without changing the native tool name or input schema. */
50
+ function getRunJavaScriptTool(chat) {
51
+ if (chat) return RUN_JAVASCRIPT_TOOL;
52
+ return {
53
+ ...RUN_JAVASCRIPT_TOOL,
54
+ description: `${WORKER_RESPONSE_INSTRUCTION} See "run_javascript syntax" and the documented functions and memory.`
55
+ };
56
+ }
57
+ /** Validate the entire response before any delivery or business action begins. */
58
+ function validateNativeToolCalls(calls) {
59
+ if (!calls.length) return { valid: true };
60
+ if (calls.length > 1) return {
61
+ valid: false,
62
+ errors: ["Use at most one run_javascript call per response. Put all operations inside its JavaScript program."]
63
+ };
64
+ const [call] = calls;
65
+ if (!call || typeof call.id !== "string" || !call.id.trim()) return {
66
+ valid: false,
67
+ errors: ["Every native tool call requires a non-empty ID."]
68
+ };
69
+ if (call.name !== RUN_JAVASCRIPT_TOOL.name) return {
70
+ valid: false,
71
+ errors: [`Unknown native tool ${JSON.stringify(call.name)}. Use run_javascript.`]
72
+ };
73
+ const input = call.input;
74
+ if (!input || typeof input !== "object" || Array.isArray(input)) return {
75
+ valid: false,
76
+ errors: ["Tool arguments must be a JSON object."]
77
+ };
78
+ if (Object.keys(input).some((key) => key !== "code") || typeof input.code !== "string" || !input.code.trim()) return {
79
+ valid: false,
80
+ errors: ["run_javascript requires exactly one non-empty code string."]
81
+ };
82
+ return {
83
+ valid: true,
84
+ call: {
85
+ id: call.id,
86
+ code: input.code
87
+ }
88
+ };
89
+ }
90
+ //#endregion
91
+ //#region src/prompts/native.ts
92
+ var native_exports = /* @__PURE__ */ __exportAll({ getNativeSystemMessage: () => getNativeSystemMessage });
93
+ const runJavaScriptSyntax = [
94
+ "# run_javascript syntax",
95
+ "run_javascript is the only native tool. Call it with a JSON object containing exactly one property: \"code\", a non-empty string of JavaScript source.",
96
+ "The code string is the body of an async JavaScript program. Top-level await and return are supported. Send plain JavaScript without Markdown fences, an enclosing function, type annotations, imports, or JSX. eval, Function constructors, and dynamically generated code are not supported.",
97
+ "Make at most one run_javascript call per response. Put multiple operations in that program: await dependent business calls in order, or await Promise.all for independent operations when safe. Await all business operations before the final return, including unfinished siblings after a Promise.all failure.",
98
+ "Use only the functions documented in the JavaScript API and variables listed in Memory. Do not assume browser, network, filesystem, or package APIs are available.",
99
+ "Match each function signature exactly. A string parameter takes a string, not an object containing that string."
100
+ ].join("\n\n");
101
+ function runtimeRules(props, chat) {
102
+ const hasExits = props.exits.length > 0;
103
+ const listen = props.exits.find((exit) => exit.name.toLowerCase() === "listen");
104
+ const rules = [
105
+ "# Responses and execution",
106
+ hasExits ? "Every run_javascript program must explicitly return inspect(value) for inspection or return exit(\"NAME\", payload) with a registered name and its required payload for completion." : "Every run_javascript program must explicitly return inspect(value).",
107
+ "The only way for the model to see a business tool return value is return inspect(value). JavaScript can use tool results immediately to compute, branch, or call other functions. Inspection exposes the result in the next response.",
108
+ "If completing the task requires interpreting natural-language tool output, inspect it before constructing the completion payload. Do not substitute the whole returned text for an extracted field, guess facts, or fill required fields with placeholders. Structured results may be used directly when the program can compute the complete payload from them.",
109
+ "inspect(...) constructs an opaque decision that takes effect only when returned as the result of the JavaScript program. Never fabricate, serialize, or store a decision as persistent memory."
110
+ ];
111
+ if (chat) rules.push("Reply to the user with normal assistant text. Assistant text streams normally and is visible to the user. A completed response without tool calls finishes the turn. Choose text-only only when no requested action remains; a requested component or business operation requires a tool call in this response, even when you already wrote the requested text. Keep private reasoning out of assistant text.", "Follow the task's response constraints exactly. When exact text is requested, reproduce it byte-for-byte, without a greeting, explanation, translation, or extra whitespace. Do not add a leading or trailing space or newline, including before a tool call. This constrains assistant text, not the tool calls needed to carry out the task. Response style applies to free-form prose; it must not rewrite supplied text or code that the task asks you to preserve, including whitespace, quotes, and escapes. When transcribing source, check each line against the supplied source rather than completing familiar patterns from memory.", "Keep routine business lookups and recovery silent unless progress updates are requested; answer from inspected results. This does not suppress text explicitly requested alongside components. When more work remains, send a requested progress update alongside the run_javascript call that continues that work; a text-only update ends the turn.");
112
+ else {
113
+ rules.push(WORKER_RESPONSE_INSTRUCTION);
114
+ if (hasExits) rules.push("Complete the assigned task with return exit(\"NAME\", payload) inside JavaScript. Assistant prose alone does not complete a worker task. Every worker response, including completion after an inspection, must call run_javascript. Return the completion payload through exit, never as assistant text or a Markdown/JSON response.");
115
+ }
116
+ if (hasExits) rules.push("Complete all required work before returning the registered exit. JavaScript can compute its payload from tool results without another model response. Completion validates the payload and requires its hook to succeed. Omit the payload when an exit signature has no payload parameter.");
117
+ if (chat && props.exits.some((exit) => exit !== listen)) rules.push("When a known outcome matches a registered task exit description, return exit(\"NAME\", payload) for that outcome, even if you also explain it in assistant text. Prose does not select a typed exit.");
118
+ if (chat && listen) rules.push(`Use return exit(${JSON.stringify(listen.name)}) only when waiting for the user or when no task outcome matches another registered exit, within a program that already needs to run. A plain assistant reply automatically waits for the user when its text ends. Do not call run_javascript solely to listen after a text-only reply, even if the task says "then listen".`);
119
+ if (chat && props.components.size) {
120
+ rules.push("Send rich messages with the registered chat methods. Each method accepts its documented props, sends synchronously, and returns void; do not await it. Messages are delivered in invocation order. A component call does not finish the program; follow it with the required return.", `When the task requests text AND components, put the requested text in the assistant preamble to a native tool call, then call run_javascript to send the components. Use a tool-call response with a text preamble, not a final text-only answer. Both belong in this response.${hasExits ? " exit ends the turn and cannot send the missing text afterward." : ""} Text alone omits the components; components alone omit the text. When only components are requested, keep assistant output empty and do not add an acknowledgement afterward.`, "Never print a rich-message description instead of sending its component. Reuse acknowledged deliveries; a failed delivery may have an uncertain external outcome.");
121
+ if (listen) rules.push(`After sending all requested components, finish in the same program with return exit(${JSON.stringify(listen.name)}) when waiting for the user. Returning inspect(undefined) requests another response and does not finish the turn.`);
122
+ }
123
+ rules.push("Execution may overlap the remaining response stream. The runtime waits for the stream, code, and queued message deliveries before the next response.", "# Memory", "Declare retained variables at top level with const or let. Bare assignment only updates a variable already declared in this program or listed in Memory. Named variables survive transcript compaction; assignment age records when they were set, not when the underlying data was fetched.", "Object properties are immutable snapshots. Replace a writable property completely, such as account.profile = { ...account.profile, age: 42 }; nested edits are forbidden and replacements are schema-validated.", "$return is the latest successful inspection result. $iterations is read-only retained history, newest first: [0] is the last settled iteration and [1] the preceding one. The current execution is not included. Entries without results still occupy indexes; check hasResult. Compaction prunes automatic results. Assign useful data to named variables to retain it independently.", "# Recovery", "Execution reports identify completed actions, inspected values, memory changes, and errors. Reuse preserved variables and completed actions; retry only failed work. Build completion payloads from those values, not by calling successful tools again. An inspection has already run the recorded calls; it is not a dry run.", "An operational error does not by itself finish the task. Inspect the actual error, repair its cause when safe and authorized, then retry. Unchanged retries do not establish that recovery is exhausted. If another response must diagnose the error, return inspect({ errors, completed }) or let the error reach the runtime. Honor task instructions defining terminal failure outcomes.");
124
+ if (hasExits) rules.push("Use a failure exit only when recovery is unavailable, unsafe, forbidden, its budget is exhausted, or task instructions make the failure terminal. Do not select failure in advance for an unseen error. Do not turn an unexpected exception or rejected Promise.allSettled entry directly into failure completion: first expose it with inspect or let it reach the runtime, then diagnose the actual cause and available recovery tools. Explicit task instructions may define an error as terminal.");
125
+ rules.push("A tool may request forced inspection through ThinkSignal. The tool succeeded and its context is returned to JavaScript. Other calls and assignments continue normally. At the end of the program, forced inspection takes precedence over completion: review the reported results as an inspect() call, then continue from retained values without repeating successful calls.", "Respect tool-attempt limits separately from the model-response budget. An empty successful inspection result is not a failure.");
126
+ return rules.join("\n\n");
127
+ }
128
+ async function describeRuntimeAPI(props, chat) {
129
+ const declarations = ["declare function inspect<T>(value: T): InspectionDecision;"];
130
+ for (const exit of props.exits) {
131
+ const name = JSON.stringify(exit.name);
132
+ const description = `${exit.description}${!exit.zSchema && chat ? " This does not send a message." : ""}`;
133
+ const parameters = exit.zSchema ? `name: ${name}, payload${exit.zSchema.isOptional() ? "?" : ""}: ${await getTypings(exit.zSchema)}` : `name: ${name}`;
134
+ declarations.push(getMultilineComment(description), `declare function exit(${parameters}): never;`);
135
+ }
136
+ if (chat && props.components.size) {
137
+ declarations.push("declare const chat: {");
138
+ for (const [name, component] of props.components) declarations.push(getMultilineComment(component.definition.description), `${name}(props: ${await getTypings(component.definition.props)}): void;`);
139
+ declarations.push("};");
140
+ }
141
+ return "```typescript\n" + await formatTypings(declarations.join("\n")) + "\n```";
142
+ }
143
+ async function getNativeSystemMessage(props) {
144
+ var _props$instructions;
145
+ const chat = props.isChatEnabled;
146
+ const declarations = await Promise.all([...props.objects.filter((object) => {
147
+ var _object$tools;
148
+ return (_object$tools = object.tools) === null || _object$tools === void 0 ? void 0 : _object$tools.length;
149
+ }).map((object) => object.getToolTypings()), ...props.globalTools.map((tool) => tool.getTypings())]);
150
+ const instructions = ((_props$instructions = props.instructions) === null || _props$instructions === void 0 ? void 0 : _props$instructions.trim()) || "Carry out the assigned task.";
151
+ const tools = [await describeRuntimeAPI(props, chat), ...declarations.length ? ["```typescript\n" + declarations.join("\n\n") + "\n```"] : []].join("\n\n");
152
+ const protocol = [
153
+ runJavaScriptSyntax,
154
+ runtimeRules(props, chat),
155
+ ...chat ? ["# Assistant response", (props.response ?? resolveResponse()).instructions] : []
156
+ ].join("\n\n");
157
+ return {
158
+ message: {
159
+ role: "system",
160
+ content: [
161
+ protocol,
162
+ "# JavaScript API",
163
+ "These TypeScript declarations describe functions inside run_javascript. Object properties, their types, values, and read/write rules are listed in Memory.",
164
+ tools,
165
+ "# Task instructions",
166
+ instructions
167
+ ].join("\n\n")
168
+ },
169
+ parts: {
170
+ instructions,
171
+ tools,
172
+ protocol
173
+ }
174
+ };
175
+ }
176
+ //#endregion
177
+ export { validateNativeToolCalls as a, getRunJavaScriptTool as i, native_exports as n, resolveResponse as o, WORKER_RESPONSE_INSTRUCTION as r, getNativeSystemMessage as t };
package/dist/objects.d.ts CHANGED
@@ -217,25 +217,6 @@ export declare namespace ObjectInstance {
217
217
  * })
218
218
  * ```
219
219
  *
220
- * ## TypeScript Integration
221
- *
222
- * Objects generate TypeScript namespace declarations:
223
- *
224
- * ```typescript
225
- * // Generated types for the LLM context:
226
- * export namespace user {
227
- * const name: Writable<string | null> = null
228
- * const age: Writable<number | null> = null
229
- * const id: Readonly<string> = "user_123"
230
- * }
231
- *
232
- * export namespace fs {
233
- * function readFile(args: { path: string }): Promise<string>
234
- * function writeFile(args: { path: string, content: string }): Promise<void>
235
- * }
236
- * ```
237
- *
238
- * @see {@link https://github.com/botpress/botpress/blob/master/packages/llmz/examples/09_chat_variables/index.ts} Example usage
239
220
  */
240
221
  export declare class ObjectInstance implements Serializable<ObjectInstance.JSON> {
241
222
  name: string;
@@ -306,44 +287,8 @@ export declare class ObjectInstance implements Serializable<ObjectInstance.JSON>
306
287
  properties?: ObjectProperty[];
307
288
  metadata?: Record<string, unknown>;
308
289
  });
309
- /**
310
- * Generates TypeScript namespace declarations for this object.
311
- *
312
- * This method creates TypeScript definitions that are included in the LLM context
313
- * to help it understand the available properties and tools. Properties become
314
- * const declarations with appropriate Readonly/Writable types, and tools become
315
- * function signatures.
316
- *
317
- * @returns Promise resolving to TypeScript namespace declaration
318
- *
319
- * @example
320
- * ```typescript
321
- * const obj = new ObjectInstance({
322
- * name: 'user',
323
- * properties: [
324
- * { name: 'name', value: 'John', writable: true },
325
- * { name: 'id', value: 123, writable: false },
326
- * ],
327
- * tools: [
328
- * new Tool({
329
- * name: 'save',
330
- * input: z.object({ data: z.string() }),
331
- * handler: async ({ data }) => { /* ... *\/ },
332
- * }),
333
- * ],
334
- * })
335
- *
336
- * const typings = await obj.getTypings()
337
- * console.log(typings)
338
- * // Output:
339
- * // export namespace user {
340
- * // const name: Writable<string> = "John"
341
- * // const id: Readonly<number> = 123
342
- * // function save(args: { data: string }): Promise<void>
343
- * // }
344
- * ```
345
- */
346
- getTypings(): Promise<string>;
290
+ /** Callable API only. Property values, schemas, and access rules belong in Memory. */
291
+ getToolTypings(): Promise<string>;
347
292
  /**
348
293
  * Converts this ObjectInstance to its JSON representation.
349
294
  *
@@ -0,0 +1,2 @@
1
+ import type { LLMzPrompts } from './prompt.js';
2
+ export declare function getNativeSystemMessage(props: LLMzPrompts.InitialStateProps): Promise<LLMzPrompts.SystemMessage>;