llmz 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +45 -11
  2. package/dist/{_baseForOwn-buOZDFbK.cjs → _baseForOwn-BfWDTL8L.cjs} +0 -50
  3. package/dist/chat.d.ts +6 -6
  4. package/dist/common-BlRFtdf2.js +807 -0
  5. package/dist/common-BnvrDnIT.cjs +860 -0
  6. package/dist/compiler-C-OI9sim.cjs +547 -0
  7. package/dist/compiler-CW1VjQsn.js +473 -0
  8. package/dist/{component-BwixNVH8.cjs → component-C6Agl2ns.cjs} +3 -3
  9. package/dist/component.d.ts +4 -4
  10. package/dist/component.default.d.ts +70 -87
  11. package/dist/component.default.test.d.ts +1 -0
  12. package/dist/context.d.ts +14 -8
  13. package/dist/{custom-client-CMuy7fXU.js → custom-client-ChuZ63zp.js} +128 -30
  14. package/dist/{custom-client-Bp1TgTKk.cjs → custom-client-DAsGRnYc.cjs} +131 -33
  15. package/dist/{dual-modes-mNyMThtf.js → dual-modes-DDkoCp3R.js} +1771 -1489
  16. package/dist/{dual-modes-CfqTk9M8.cjs → dual-modes-DPXiuvNe.cjs} +1767 -1491
  17. package/dist/example-format.d.ts +8 -0
  18. package/dist/example.d.ts +45 -0
  19. package/dist/example.test.d.ts +1 -0
  20. package/dist/{execute-DP_17lYZ.js → execute-BWcdv9so.js} +77 -85
  21. package/dist/{execute-msui51b2.cjs → execute-DM2-7y86.cjs} +83 -92
  22. package/dist/{exit-BGi0Kk0y.cjs → exit-DUM96DN1.cjs} +3 -3
  23. package/dist/exit-parser.d.ts +2 -0
  24. package/dist/index.cjs +137 -217
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.js +115 -196
  27. package/dist/index.workerd.js +16664 -15533
  28. package/dist/inspect.d.ts +2 -0
  29. package/dist/{jsx-BWvT6ukg.cjs → jsx-owqxrquU.cjs} +2 -2
  30. package/dist/message-stream/instructions.d.ts +8 -0
  31. package/dist/message-stream/parser.d.ts +9 -0
  32. package/dist/message-stream/response-parser.d.ts +24 -0
  33. package/dist/message-stream/response-parser.test.d.ts +1 -0
  34. package/dist/message-stream/types.d.ts +3 -2
  35. package/dist/prompts/adherence.test.d.ts +1 -0
  36. package/dist/prompts/catalogue-examples.test.d.ts +1 -0
  37. package/dist/prompts/chat-mode/protocol.d.ts +2 -0
  38. package/dist/prompts/chat-mode/system.d.ts +2 -0
  39. package/dist/prompts/chat-mode/user.d.ts +2 -0
  40. package/dist/prompts/code-examples.d.ts +2 -0
  41. package/dist/prompts/code-examples.test.d.ts +1 -0
  42. package/dist/prompts/common.d.ts +2 -1
  43. package/dist/prompts/concrete-patterns.test.d.ts +1 -0
  44. package/dist/prompts/execution-history.d.ts +6 -0
  45. package/dist/prompts/execution-state.d.ts +3 -0
  46. package/dist/prompts/long-search.test.d.ts +1 -0
  47. package/dist/prompts/prompt.d.ts +31 -2
  48. package/dist/prompts/protocol-basics.d.ts +5 -0
  49. package/dist/prompts/protocol-simple.test.d.ts +1 -0
  50. package/dist/prompts/protocol.d.ts +13 -0
  51. package/dist/prompts/protocol.test.d.ts +1 -0
  52. package/dist/prompts/sections.test.d.ts +1 -0
  53. package/dist/prompts/worker-mode/protocol.d.ts +2 -0
  54. package/dist/prompts/worker-mode/system.d.ts +2 -0
  55. package/dist/prompts/worker-mode/user.d.ts +2 -0
  56. package/dist/runtime/citations.test.d.ts +1 -0
  57. package/dist/runtime/fixtures/long-search.d.ts +19 -0
  58. package/dist/runtime/fixtures/protocol-languages.d.ts +74 -0
  59. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +29 -0
  60. package/dist/runtime/generate.d.ts +2 -9
  61. package/dist/runtime/protocol-adherence.test.d.ts +1 -0
  62. package/dist/runtime/types.d.ts +13 -7
  63. package/dist/{tool-ReA9gxMp.cjs → tool-Dy6AJpJH.cjs} +4 -4
  64. package/dist/{truncator-B6aaJaN1.cjs → truncator-CLkouTCO.cjs} +3 -3
  65. package/dist/{typings-BwAz_TM9.cjs → typings-3lsqCbkn.cjs} +3 -3
  66. package/dist/{utils-ZpJm00ed.cjs → utils-3ESwP3yg.cjs} +2 -2
  67. package/dist/{vm-C5vf1LH3.js → vm-BLsHw1da.js} +3 -462
  68. package/dist/{vm-BjkJqSQH.cjs → vm-D6s1zF6M.cjs} +28 -489
  69. package/package.json +1 -1
package/README.md CHANGED
@@ -64,6 +64,7 @@ const ticketId = await buyTicket({ from: 'quebec', to: 'new york' })
64
64
  Every model response is a sequence of streaming-native `■` blocks:
65
65
 
66
66
  ```
67
+ ■start
67
68
  ■send=message
68
69
  Let me check the next launch dates for the Moon...
69
70
  ■run
@@ -71,17 +72,50 @@ const dates = await checkAvailability({ destination: 'moon' })
71
72
  const reservation = await bookTrip({ destination: 'moon', date: dates[0], travelerName: 'Ada' })
72
73
  const payment = await processPayment({ reservationId: reservation.reservationId })
73
74
  return { ...payment, date: dates[0] }
75
+ ■end
74
76
  ```
75
77
 
76
- - **`■send=<component> {props?}`** — sends a message to the user, delivered (and streamable) the moment it is parsed
77
- - **`■run`** — executes the TypeScript body in the sandbox; the returned value is fed back to the model
78
+ - **`■send=<component> {props?}`** — sends a message to the user, streamed provisionally, then delivered after successful validation
79
+ - **`■run`** — executes the JavaScript body in the sandbox; the returned value is fed back to the model
78
80
  - **`■next=<exit> {props?}`** — ends the turn through a typed exit (the built-in `listen` hands the turn back to the user)
79
81
 
80
- Because the protocol is parsed incrementally, messages stream to your UI token-by-token, tool calls surface live, and code execution can start before the response has even finished streaming.
82
+ Every generated response must contain a standalone `■start` and end with `■end`. Text before the start marker is retained for debugging and discarded before parsing any blocks. There is no unwrapped response mode. Only explicit `■send` blocks can produce messages. Markdown (`■send=md`) remains supported.
81
83
 
82
- Only explicit `■send` blocks produce messages or message deltas. Unexpected text outside protocol blocks is discarded in streaming, fallback restarts, and nonstreaming execution. Explicit Markdown (`■send=md`) is supported. A response with only unexpected text follows the normal invalid-response retry/error path. For debugging, `iteration.llm.output` retains the raw response and `iteration.llm.diagnostics` records parser diagnostics, including `unexpected-text`.
84
+ Message bodies stream as provisional deltas. Completed message handlers and code execution wait for the entire valid response and successful generation. A missing start marker, unmarked prose inside the envelope, multiple run blocks, and messages after code reject the response through the normal malformed-response/error path. A failed or restarted attempt cannot execute code or commit a message. Any previews from it are retracted with a reset delta.
83
85
 
84
- As of 0.7.0, the parser options `strict` and `recoveryComponent` have been removed. All parsing requires explicit send blocks; callers relying on implicit messages must emit `■send=<component>` instead.
86
+ The first `■end` is a reserved terminator anywhere after `■start`, including inline and inside a JavaScript string or comment. Everything after it is discarded with a diagnostic; it never reaches message handlers or code execution. This intentionally accepts concatenated output such as `■end■start`. The prefix must still form valid blocks and valid JavaScript before any code runs. A terminator inside a string can therefore invalidate the response; do not use the raw sequence as content. In JavaScript, construct literal text with a Unicode escape such as `"\u25a0end"` instead. This is a protocol delimiter, not a JavaScript-aware scanner.
87
+
88
+ Cognitive receives `stopSequences: ['\n■end']` to stop generation at the end boundary. Since providers consume the stop string, normal `stop` metadata closes the response even when the literal end marker is absent. Cognitive does not distinguish a matched stop string from ordinary end-of-generation; the response must still have a start marker and valid blocks. Missing metadata, truncation, filtering, and transport failure never supply this closure.
89
+
90
+ Raw output and diagnostics remain available in `iteration.llm.output` and `iteration.llm.diagnostics`, including on failed streams. A valid framed exit alone permits intentional silence. Tools completed in earlier successful iterations remain completed during later recovery.
91
+
92
+ Prompt examples use standalone triple quotes (`"""`) to show their boundaries, with BAD/CORRECT comparisons and a menu of response shapes. These quotes are documentation, not protocol. If copied, standalone example delimiter lines are stripped before customer callbacks and recorded as `example-delimiter` diagnostics. Inline quotes, JSON props, and interior Markdown/code content remain literal. A standalone triple-quote line immediately before a protocol boundary is reserved for this purpose; to display it literally, include it inline or inside a fenced code sample.
93
+
94
+ The prompts use ordinary headings and put the response format after task context and the current execution budget. Historical replies are kept as recorded, without synthetic protocol headers. The low-level block parser remains useful for parsing individual blocks; execution uses the mandatory response envelope.
95
+
96
+ This is a breaking protocol change: custom model clients and cached wire responses must include the start boundary and a successful response termination. Completed handlers now run after successful generation; only deltas stream during generation. `■run` followed by `■send` is invalid. Return a tool result, then answer in a new iteration. The removed `strict` and `recoveryComponent` options are not restored.
97
+
98
+ To measure first-response adherence independently of runtime recovery, configure `CLOUD_PAT`, `CLOUD_BOT_ID`, and optionally `CLOUD_API_ENDPOINT`, then run:
99
+
100
+ ```bash
101
+ LLMZ_EVAL_MODELS=cerebras:qwen-3.8-27b LLMZ_EVAL_REPEATS=1 pnpm test:e2e e2e/protocol-matrix.test.ts
102
+ ```
103
+
104
+ The matrix contains 144 synthetic tasks across 12 languages, each in streaming and nonstreaming mode: greetings, intake, long context, tools, progress messages, tool results, silent actions, typed exits, buttons, JSON text, Markdown, and error recovery. It disables test retries and cache and rejects fallback credit. Optional `LLMZ_EVAL_RECORDS=/absolute/path/results.jsonl` records raw outputs, diagnostics, task checks, and actual model metadata. Failures remain visible: passing runtime rejection tests does not establish perfect model adherence. Protocol/control-flow assertions are separate from exact task wording checks, which are retained in the evaluation records.
105
+
106
+ ---
107
+
108
+ ## Long search results and citations
109
+
110
+ The RAG benchmark uses the same citation contract as VDK: a search tool registers source metadata, returns passages labelled with `【id】` through `ThinkSignal`, and the completed message handler extracts inline tags into citation metadata with text offsets. Its documents are entirely synthetic.
111
+
112
+ ```bash
113
+ LLMZ_EVAL_MODELS=groq:qwen3.8-27b LLMZ_EVAL_REPEATS=1 pnpm test:e2e e2e/long-search-citations.test.ts
114
+ ```
115
+
116
+ The 48 cases pair compact controls with long corpora in both streaming modes. They cover exact scope matching, superseded/future policies, joins across distant documents, and quota arithmetic, with answers near the beginning, middle, or end. Results span roughly 12,000–39,000 tokens and four response languages. Tests require correct facts, every required supporting source, no unrelated citations, intact evidence in the actual model request, no extra search/recovery hops, and the requested model without cache or fallback credit. Near-match sources may additionally support scope/date disambiguation (for example, explaining why an archived account does not apply); they cannot replace required evidence. These checks validate retrieval and source coverage, not every possible natural-language claim.
117
+
118
+ Latest tool-result strings are preserved until the request context budget is applied; they are no longer silently clipped at 4,096 characters. Inputs exceeding the model/context budget still undergo normal truncation. Separate deterministic tests cover citation offsets, grouped/repeated tags, structured component props, chunk boundaries, discarded preambles, stream restarts, failed delivery, and unknown source IDs.
85
119
 
86
120
  ---
87
121
 
@@ -331,7 +365,7 @@ const chat = new Chat({
331
365
  // Fires per token-chunk while the LLM is still generating
332
366
  onMessageDelta: (delta) => {
333
367
  if (delta.restart) {
334
- // Remove ALL this iteration's messages, including completed handler sends.
368
+ // Remove this iteration's provisional previews.
335
369
  return clearIterationMessages(delta.iterationId)
336
370
  }
337
371
  return updateBubble(delta.iterationId, delta.id, delta.content)
@@ -355,13 +389,13 @@ const result = await execute({
355
389
  - **Message deltas** stream to your UI token-by-token (`handler` remains the authoritative delivery)
356
390
  - **Live traces** cover the full turn lifecycle: `llm_call_started` → message deltas → `code_generation_started` → `llm_call_success` (with the code) → `tool_call`s → exit
357
391
  - **Fallback**: a `restart: true` delta invalidates the current iteration's messages before replacement output arrives. Replacement messages have fresh IDs under the same `iterationId`. Code executes only after the replacement stream succeeds; abandoned code never runs.
358
- - **Early execution**: without `midStreamFallback`, a closed `■run` block can start executing while the response tail is still streaming. A later generation failure returns an error without retrying the code. The VM pre-warms when code generation begins in either mode.
392
+ - **Execution**: code runs only after a complete, valid envelope and successful stream completion in every mode. The VM still pre-warms when a run block opens.
359
393
 
360
- Terminal failures return an `ErrorExecutionResult`; they do not emit a restart delta because there is no replacement attempt. Handle that result to clear or mark unfinished messages as failed. Already delivered messages remain delivered unless your consumer retracts them. Nonstreaming Cognitive fallback exposes only the successful response, so no message reset is needed.
394
+ Terminal failures return an `ErrorExecutionResult` and retract any provisional previews with a reset delta; no replacement is required for a reset. Completed handlers from abandoned attempts are never called. Nonstreaming fallback exposes only the surviving response.
361
395
 
362
- LLMz rejects explicit Cognitive errors, error metadata (`provider: "unknown"`), and responses stopped by a token limit or content filter before finalizing unfinished blocks. Such failures cannot turn a partial code prefix into executable code. With fallback disabled, this cannot undo code that already ran after a block boundary.
396
+ Explicit Cognitive errors, unknown-provider error metadata, missing streaming metadata, token-limit truncation, and content filtering cannot turn partial output into executable code. A complete code block inside an unfinished response is still provisional.
363
397
 
364
- `■run` followed by `■send` is currently accepted, but that message was generated without seeing the code's result. Prefer sending an acknowledgement before `■run`, returning the needed data, then answering in the next iteration. A top-level `return` always requests another iteration; side-effect-only code can finish immediately with `■next`.
398
+ Send messages before code. A returning run requests another iteration and must be followed directly by `■end`. Side-effect-only code may finish with `■next` before `■end`.
365
399
 
366
400
  Forward these events over a websocket or SSE stream and your frontend renders the agent live — see [example 22](https://github.com/botpress/botpress/tree/master/packages/llmz/examples/22_chat_streaming).
367
401
 
@@ -513,7 +547,7 @@ LLMz has been running in production for over a year:
513
547
  1. **Prompt Generation**: Injects tools, schemas, and context into dual-mode prompts
514
548
  2. **Streaming Generation**: The LLM streams ■ blocks — messages dispatch to the chat as they are parsed
515
549
  3. **Compilation**: Babel AST transformation with instrumentation plugins (line tracking, tool call tracking, variable extraction)
516
- 4. **Execution**: Runs in QuickJS WASM sandbox with full isolation — starting while the response tail is still streaming
550
+ 4. **Execution**: Runs in QuickJS WASM sandbox with full isolation — after successful generation and protocol validation
517
551
  5. **Result Processing**: Type-safe exit handling, thinking loops and error recovery
518
552
 
519
553
  **Security:**
@@ -1,35 +1,3 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
9
- var __exportAll = (all, no_symbols) => {
10
- let target = {};
11
- for (var name in all) __defProp(target, name, {
12
- get: all[name],
13
- enumerable: true
14
- });
15
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
- return target;
17
- };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
- key = keys[i];
21
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
- get: ((k) => from[k]).bind(null, key),
23
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
- });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
29
- value: mod,
30
- enumerable: true
31
- }) : target, mod));
32
- //#endregion
33
1
  const require__baseIteratee = require("./_baseIteratee-CF4qP2a8.cjs");
34
2
  //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseFor.js
35
3
  /**
@@ -77,24 +45,6 @@ function baseForOwn(object, iteratee) {
77
45
  return object && baseFor(object, iteratee, require__baseIteratee.keys);
78
46
  }
79
47
  //#endregion
80
- Object.defineProperty(exports, "__commonJSMin", {
81
- enumerable: true,
82
- get: function() {
83
- return __commonJSMin;
84
- }
85
- });
86
- Object.defineProperty(exports, "__exportAll", {
87
- enumerable: true,
88
- get: function() {
89
- return __exportAll;
90
- }
91
- });
92
- Object.defineProperty(exports, "__toESM", {
93
- enumerable: true,
94
- get: function() {
95
- return __toESM;
96
- }
97
- });
98
48
  Object.defineProperty(exports, "baseForOwn", {
99
49
  enumerable: true,
100
50
  get: function() {
package/dist/chat.d.ts CHANGED
@@ -39,9 +39,9 @@ export type MessageHandler = (input: RenderedComponent, metadata: MessageMetadat
39
39
  * Each chunk is forwarded to {@link Chat} `onMessageDelta` as soon as it is parsed, so the
40
40
  * client can render the message progressively (e.g. typewriter effect in a chat UI).
41
41
  *
42
- * In mid-stream fallback mode, both deltas and completed `handler` messages
43
- * are live and retractable: restart deltas invalidate every message from that
44
- * iteration. Consumers must retract them; only code execution waits for success.
42
+ * Deltas are provisional: restart deltas retract previews from that iteration
43
+ * after a provider restart, malformed response, or transport failure. Completed
44
+ * `handler` messages and code wait for a valid response and successful transport.
45
45
  */
46
46
  export type MessageDelta = {
47
47
  restart: false;
@@ -60,12 +60,12 @@ export type MessageDelta = {
60
60
  } | {
61
61
  /**
62
62
  * Reset-only delta, emitted before replacement text (even if none follows).
63
- * Clear ALL messages for iterationId, including completed `handler` sends.
64
- * Other iterations are unaffected. Irreversible sends cannot be undone.
63
+ * Clear provisional messages for iterationId. Other iterations are unaffected.
64
+ * Completed handler sends are never produced by an abandoned generation.
65
65
  */
66
66
  restart: true;
67
67
  iterationId: string;
68
- /** 1-based index of the new attempt. */
68
+ /** 1-based index of the next attempt; a terminal failure may have no replacement. */
69
69
  attempt: number;
70
70
  fromModel: string;
71
71
  toModel: string;