arcane-os 0.13.2 → 0.14.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.
@@ -320,6 +320,68 @@ Ordinary iteration exposes only text/reasoning chunks; raw structural deltas
320
320
  remain internal until the complete terminal result validates. Explicit
321
321
  `onResponse` or inspection consumers retain the complete raw terminal response.
322
322
 
323
+ ## Stream selected tool text
324
+
325
+ Both `AI.streamRequest()` and this browser controller's `streamRequest()` accept
326
+ `toolText:{name,field}` with `onToolText(text,call,displayId)`. Select the exact
327
+ tool name and one root-level string argument. The callback receives newly
328
+ decoded text in arrival order, preserving whitespace and JSON string escapes as
329
+ their original characters. Its `call` record is
330
+ `{id,name,field,index,choiceIndex}`: the actual normalized tool-call ID, matching
331
+ tool name, selected field, call index within the response choice, and choice
332
+ index. Delivery waits until the matching name and ID are known. `displayId` is
333
+ the request's existing `M-${id}` display ID.
334
+
335
+ This callback is distinct from ordinary `onChunk`; display the text in the
336
+ corresponding tool turn and keep ordinary prose in its own existing turn.
337
+ `onToolCall` still receives only the complete normalized call after terminal
338
+ settlement. The text callback does not execute a tool, rewrite arguments, or
339
+ retain a transcript. The application owns the completed call's execution and
340
+ stores its complete visible result once through its normal history path.
341
+ If a provider supplies arguments only at completion, the callback runs only
342
+ when that actual complete response arrives. Repeated terminal snapshots do not
343
+ replay text already emitted. Callback errors reach the request owner, and a
344
+ cancelled or superseded request stops further text delivery.
345
+
346
+ For example, an application that already supplies a closing-report tool can
347
+ connect its existing display operations without parsing provider protocol:
348
+
349
+ ```javascript
350
+ import {
351
+ formatConversationClosingReportText
352
+ } from '/arcane/modules/ConversationClosingReport.js';
353
+
354
+ async function streamClosingReport(ai, messages, closingTool, view, signal) {
355
+ return ai.streamRequest(
356
+ {
357
+ messages,
358
+ tools:[closingTool],
359
+ signal,
360
+ toolText:{name:closingTool.function.name, field:'final_message'},
361
+ onChunk:function appendOrdinaryText(text, displayId, thinking) {
362
+ return view.appendAssistantText(text, displayId, thinking);
363
+ },
364
+ onToolText:function appendClosingText(text, call, displayId) {
365
+ return view.appendToolText(
366
+ formatConversationClosingReportText(text),
367
+ call.id,
368
+ displayId
369
+ );
370
+ }
371
+ }
372
+ );
373
+ }
374
+ ```
375
+
376
+ The application supplies `view` and the existing `closingTool`; those are not
377
+ SDK exports. The formatter applies the same existing `&`, `<`, and `>` escaping
378
+ used for the complete closing report, including whitespace-only chunks. The
379
+ returned terminal call remains available to the application's normal tool
380
+ execution and persistence path. These options do not change the tool schema,
381
+ tool choice, or authored request content. Omitting `toolText` creates no text
382
+ observer. Invalid selection or callback input throws `TypeError`; malformed
383
+ selected argument text reports `ARCANE_AI_TOOL_TEXT_INVALID`.
384
+
323
385
  ## Errors and unavailable states
324
386
 
325
387
  Invalid configuration can throw `TypeError` or `RangeError`. Operational
@@ -6,7 +6,7 @@
6
6
  "minimumVersion": "22.23.2 for Node entrypoints",
7
7
  "moduleSystem": "ESM"
8
8
  },
9
- "memberCount": 208,
9
+ "memberCount": 209,
10
10
  "members": [
11
11
  {
12
12
  "id": "root:APP_BUNDLE_DESCRIPTOR_NAME",
@@ -2902,7 +2902,23 @@
2902
2902
  "summary": "Creates the provider-neutral browser AI API module and LLM lifecycle controller around one compatible provider or controller.",
2903
2903
  "availability": "Browser; the selected provider observes its own WebAssembly, storage, and model readiness",
2904
2904
  "protocol": "arcane-ai-adapter/1",
2905
- "normalization": "Normalizes lazy or manual load, mutable complete lifecycle status, cancellation, complete all-choice nonstructural stream projection, complete provider data callbacks, single-choice text or multi-choice terminal output, required structural arguments.message, and atomic exact matching nonblank all-ID tool-result sequencing without executing tools; an existing ModelController retains its preconfigured load policy and rejects a new security option"
2905
+ "normalization": "Normalizes lazy or manual load, mutable complete lifecycle status, cancellation, complete all-choice nonstructural stream projection, provider chunks with private structural fields removed, complete terminal data callbacks, optional toolText:{name,field} and distinct onToolText(text,call,displayId) delivery of selected decoded argument text, single-choice text or multi-choice terminal output, required structural arguments.message, and atomic exact matching nonblank all-ID tool-result sequencing without executing tools; an existing ModelController retains its preconfigured load policy and rejects a new security option"
2906
+ },
2907
+ {
2908
+ "id": "tool-text-stream:createToolTextObserver",
2909
+ "name": "createToolTextObserver",
2910
+ "displayName": "createToolTextObserver()",
2911
+ "kind": "function",
2912
+ "signature": "createToolTextObserver(selection, onText, {signal}={})",
2913
+ "entrypoints": [
2914
+ "arcane-os/ai/tool-text-stream"
2915
+ ],
2916
+ "primaryImport": "arcane-os/ai/tool-text-stream",
2917
+ "group": "AI provider integration",
2918
+ "summary": "Observes one selected root string argument from actual tool-call chunks before provider structural filtering.",
2919
+ "availability": "Compatible JavaScript module host; no browser capability required",
2920
+ "protocol": "OpenAI-compatible tool-call deltas and complete message snapshots",
2921
+ "normalization": "Returns null for absent selection or an async chunk observer; preserves decoded text and whitespace, emits actual normalized call identity metadata, observes each raw delta once, avoids replay from complete snapshots, awaits callbacks, and stops later observation after cancellation without altering payloads, executing tools, or persisting history"
2906
2922
  },
2907
2923
  {
2908
2924
  "id": "browser-wasm:createBrowserModelSource",
@@ -10,7 +10,7 @@
10
10
  },
11
11
  "artifactCount": 85,
12
12
  "javascriptArtifactCount": 83,
13
- "esmExportCount": 352,
13
+ "esmExportCount": 353,
14
14
  "artifacts": [
15
15
  {
16
16
  "file": "runtime/arcane/modules/AI.js",
@@ -30,7 +30,7 @@
30
30
  "availability": "Browser + native bridge + TWiN Cloud",
31
31
  "protocol": "arcane-ai-browser-speech-configuration/1, AIProviderRuntime arcane-ai-provider/2 routes, globalThis.arcaneEvents, TWiN Cloud HTTPS, Arcane.ollama, Arcane.speech, Android WebView bridge",
32
32
  "normalization": "Complete mutable caller-owned browser speech authority, SDK-owned provider registration/replacement/disposal, explicit STT/TTS activation, normalized Whisper STT and Kokoro TTS execution with default capacities 1 and 4 respectively, explicit provider-neutral execution snapshots through status(role,{execution:true}), sticky readiness, canonical window.user readiness without compatibility-event object-identity admission or polling, exact ordered structural calls with required arguments.message, atomic nonblank all-ID tool-result sequencing, complete all-choice streaming/data validation, native Ollama structural adaptation, complete-response then all validated tool callbacks then completion ordering, observed async callbacks, Blob/File transcription, automatic repeated-formatting-mark removal from cloned outbound TTS input while caller and visible content stays exact, immediate exact-segment synthesis, per-call voice/speed capture, optional final-segment pause on the existing audio clock, optional per-call terminal playback completion, detached preparation with complete semantic DBOPFS audio reuse and same-owner pending request sharing, independent prepared playback without a model load for cached audio, ordered audio-clock scheduling, playable audio, active-generation TTS operation-failure routing, mute, and cancellation are normalized; provider/model/runtime/voice policy remains caller-owned. Both speech roles default execution.device to auto: webnn-npu when navigator.ml.createContext is exposed, then webgpu when navigator.gpu is exposed, then wasm for CPU execution. Failed backend loads clean up the pool before trying fresh Workers with the same prepared model and dtype; explicit devices never fall back. STT capacity only accepts 1; TTS accepts 1 through 4. Execution snapshots expose requestedDevice, selectedDevice, maxConcurrentRequests, and activeRequestCount for both roles; selectedDevice is null while unloaded and names the successful upstream session backend request when loaded. It does not prove every operation used the physical NPU: WebNN unsupported operations may use WASM, and compatibility depends on the browser, driver, hardware, and graph.",
33
- "surface": "Browser-speech protocol/event/error/reason constants; default `AI`; read-only `providerRuntime`, `browserSpeechConfiguration`, and `browserSpeechDescriptor`; explicit `providerRuntime.status(role,{execution:true})` snapshots; `streamTTS(text,end,options={})` with optional voice, speed, pauseAfterMs, and waitForPlayback; automatic speech-input cleanup with SDK-internal preparation metadata; `prepareTTS({parts,storage,identity,signal,onState})` returning ordered segments, state, ready, getAudio(index), and cancel(); `playPreparedTTS(prepared,{signal,onState})` returning state, error, finished, pause(), resume(), and stop() with one playback lane per AI and observational state/error callbacks; configure/dispose speech, route lifecycle, declaration-validated chat/stream requests with exact ordered calls, synthesis/transcription, and playback controls; initializes from current canonical user readiness, installs `window.ai`, and projects `ai-ready` plus active-generation `ai-tts-failure`."
33
+ "surface": "Browser-speech protocol/event/error/reason constants; default `AI`; read-only `providerRuntime`, `browserSpeechConfiguration`, and `browserSpeechDescriptor`; explicit `providerRuntime.status(role,{execution:true})` snapshots; `streamTTS(text,end,options={})` with optional voice, speed, pauseAfterMs, and waitForPlayback; automatic speech-input cleanup with SDK-internal preparation metadata; `prepareTTS({parts,storage,identity,signal,onState})` returning ordered segments, state, ready, getAudio(index), and cancel(); `playPreparedTTS(prepared,{signal,onState})` returning state, error, finished, pause(), resume(), and stop() with one playback lane per AI and observational state/error callbacks; configure/dispose speech, route lifecycle, declaration-validated chat/stream requests with exact ordered calls; optional streamRequest toolText:{name,field} and onToolText(text,call,displayId) for decoded selected argument text with actual call identity, distinct from ordinary prose and terminal tool execution; synthesis/transcription and playback controls; initializes from current canonical user readiness, installs `window.ai`, and projects `ai-ready` plus active-generation `ai-tts-failure`."
34
34
  },
35
35
  {
36
36
  "file": "runtime/arcane/modules/AIPreferenceRuntime.js",
@@ -456,13 +456,14 @@
456
456
  "conversationClosingReportInstruction",
457
457
  "createConversationClosingReportTool",
458
458
  "formatConversationClosingReport",
459
+ "formatConversationClosingReportText",
459
460
  "normalizeConversationClosingReport"
460
461
  ],
461
462
  "summary": "Defines the closing-report tool, instruction, result normalizer, call classifier, and formatter.",
462
463
  "availability": "Cross-host",
463
464
  "protocol": "In-process only",
464
465
  "normalization": "Required user-facing message remains distinct from the complete final_message; normalized results expose message, finalMessage, and rememberedActions.",
465
- "surface": "Six constants/helpers for closing reports; the sole-call schema requires message and final_message."
466
+ "surface": "Seven constants/helpers for closing reports; the sole-call schema requires message and final_message. formatConversationClosingReportText(value) exposes the existing &, <, and > escaping for any string, including whitespace-only chunks, and the complete report formatter reuses it."
466
467
  },
467
468
  {
468
469
  "file": "runtime/arcane/modules/ConversationTimebox.js",
@@ -432,7 +432,7 @@ declined, cancelled, or not-executed result.
432
432
  That tool-result content must be a nonblank string and is preserved exactly.
433
433
 
434
434
  `streamRequest()` owns the complete terminal callback sequence. `onDataChunk`
435
- receives each complete provider chunk before ordinary projection, while
435
+ receives each provider chunk after private structural fields are removed, while
436
436
  `onChunk` receives every nonstructural content or reasoning value from every
437
437
  choice in provider order. After the stream settles, `onDataResult` receives the
438
438
  complete terminal completion, `onResponse` receives that same unprojected
@@ -442,8 +442,29 @@ output is the ordered structural-call array when the selected result contains
442
442
  tools, the complete completion object when it contains multiple choices, or
443
443
  the ordinary single-result text/completion otherwise; later choices are never
444
444
  discarded.
445
- Partial structural deltas remain private until the matching terminal envelope
446
- validates. Request observers receive
445
+ Raw structural deltas remain private until the matching terminal envelope
446
+ validates. To display one tool argument's text as it arrives, supply
447
+ `toolText:{name,field}` and `onToolText(text,call,displayId)`. `name` is the exact
448
+ tool name and `field` is one root-level string argument. The callback receives
449
+ each newly decoded text fragment in order, including whitespace and JSON string
450
+ escapes decoded to their original characters. Its `call` record contains
451
+ `{id,name,field,index,choiceIndex}`; `id` is the actual normalized tool-call ID,
452
+ `index` identifies the call within its choice, and `choiceIndex` identifies the
453
+ response choice. Delivery starts once the matching tool name and call ID are
454
+ known. `displayId` is the same `M-${id}` request display ID used by `onChunk`.
455
+
456
+ `onToolText` is separate from ordinary `onChunk`, so callers can append to the
457
+ tool's existing display without duplicating assistant prose or saved history.
458
+ It observes text only: it does not execute a tool, alter arguments, persist a
459
+ turn, or change the terminal callbacks. A provider that supplies arguments only
460
+ at completion emits text only when that complete response arrives. Repeated
461
+ terminal snapshots do not replay text already emitted. Omitting `toolText`
462
+ preserves the existing callback path. Invalid selection or callback input throws
463
+ `TypeError`; malformed selected argument text reports
464
+ `ARCANE_AI_TOOL_TEXT_INVALID`. Callback errors reach the request owner and
465
+ cancellation prevents later delivery.
466
+
467
+ Request observers receive
447
468
  `onRequest(request,id,metadata)` and any transport metadata supplied by the
448
469
  selected route is forwarded unchanged. Every async native, HTTP, provider, and
449
470
  built-in callback is observed before the next callback or terminal settlement.
@@ -1609,7 +1630,7 @@ Defines the closing-report tool, instruction, result normalizer, call classifier
1609
1630
 
1610
1631
  ### Public surface
1611
1632
 
1612
- Six constants/helpers for closing reports.
1633
+ Seven constants/helpers for closing reports.
1613
1634
 
1614
1635
  The generated sole-call schema requires both `message` and `final_message`.
1615
1636
  `message` is brief user-facing progress shown while the application accepts and
@@ -1617,9 +1638,14 @@ renders the call. `final_message` remains the complete terminal closeout and is
1617
1638
  never replaced by or duplicated into `message`; `remembered_actions` remains
1618
1639
  optional. `normalizeConversationClosingReport()` returns
1619
1640
  `{message,finalMessage,rememberedActions}`, while
1620
- `formatConversationClosingReport()` escapes and renders only `finalMessage`.
1641
+ `formatConversationClosingReport()` normalizes the complete report and formats
1642
+ only `finalMessage`. Its shared `formatConversationClosingReportText(value)`
1643
+ operation accepts a string, including an empty or whitespace-only chunk, and
1644
+ replaces `&`, `<`, and `>` with `&amp;`, `&lt;`, and `&gt;` respectively. It
1645
+ preserves all other text and does not trim, validate a report, render, or persist
1646
+ anything. Use the same operation for live text chunks and complete final text.
1621
1647
 
1622
- Exact exports: `CONVERSATION_CLOSING_REPORT_TOOL_NAME`, `classifyConversationClosingReportCalls`, `conversationClosingReportInstruction`, `createConversationClosingReportTool`, `formatConversationClosingReport`, `normalizeConversationClosingReport`.
1648
+ Exact exports: `CONVERSATION_CLOSING_REPORT_TOOL_NAME`, `classifyConversationClosingReportCalls`, `conversationClosingReportInstruction`, `createConversationClosingReportTool`, `formatConversationClosingReport`, `formatConversationClosingReportText`, `normalizeConversationClosingReport`.
1623
1649
 
1624
1650
  ### Availability and normalization
1625
1651
 
@@ -1628,9 +1654,11 @@ Exact exports: `CONVERSATION_CLOSING_REPORT_TOOL_NAME`, `classifyConversationClo
1628
1654
  ### Example
1629
1655
 
1630
1656
  ```javascript
1631
- import * as module from '/arcane/modules/ConversationClosingReport.js';
1657
+ import {
1658
+ formatConversationClosingReportText
1659
+ } from '/arcane/modules/ConversationClosingReport.js';
1632
1660
 
1633
- console.log(Object.keys(module));
1661
+ console.log(formatConversationClosingReportText('Complete <draft> & next step.'));
1634
1662
  ```
1635
1663
 
1636
1664
  ## ConversationTimebox.js
@@ -3,7 +3,7 @@
3
3
  The npm package exposes a Node.js ESM control plane, the portable
4
4
  `arcane-os/event-manager`, `arcane-os/logging`, `arcane-os/mail`,
5
5
  `arcane-os/preference-store`, `arcane-os/speech-playback`,
6
- `arcane-os/speech-text`, and `arcane-os/browser-device` entrypoints, and the browser-only
6
+ `arcane-os/speech-text`, `arcane-os/ai/tool-text-stream`, and `arcane-os/browser-device` entrypoints, and the browser-only
7
7
  `arcane-os/pwa`, `arcane-os/ai/browser-wasm` and `arcane-os/ai/browser-speech` entrypoints.
8
8
  Those package subpaths are distinct from application-facing projection modules
9
9
  in the managed browser map, such as `arcane/AIProviderRuntime`,
@@ -41,6 +41,7 @@ for the installed-inventory-derived physical-runtime contract in SDK `0.5.18`.
41
41
  | `arcane-os/browser-device` | Synchronous mobile or desktop identity hints for application-owned settings. |
42
42
  | `arcane-os/pwa` | Nonblocking PWA registration, worker updates, native installation state and a dismissible installation component. |
43
43
  | `arcane-os/ai/browser-wasm` | Caller-selected browser-local Wllama inference, complete DBOPFS model storage, streaming, cancellation, and structural tool-call results. |
44
+ | `arcane-os/ai/tool-text-stream` | Shared selected tool-argument text observer for provider integration. |
44
45
  | `arcane-os/ai/browser-speech` | Caller-selected browser-local Whisper STT and Kokoro TTS provider mechanisms, ordinary upstream assets, materialized/native routing, Workers, and cancellation. |
45
46
  | `arcane-os/mail` | Portable Mail runtime, durable outbox, complete transport responses, and provider-neutral acceptance contracts. |
46
47
 
@@ -138,6 +139,7 @@ browser map are cataloged separately in [Runtime modules](runtime-modules.md).
138
139
  | `createNativeTargetAdapter()` | function | `arcane-os` | Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
139
140
  | `createReporter()` | function | `arcane-os` | Events, processes, and testing | Node |
140
141
  | `createToolchain()` | function | `arcane-os` | Headless toolchain operations | Node; selected operation may produce browser or native output |
142
+ | `createToolTextObserver()` | function | `arcane-os/ai/tool-text-stream` | AI provider integration | Compatible JavaScript module host; no browser capability required |
141
143
  | `createWorkspace()` | function | `arcane-os` | Workspace, doctor, repository, and server | Node |
142
144
  | `default()` | function | `arcane-os/testing` | Events, processes, and testing | Node |
143
145
  | `DEFAULT_TEST_TIMEOUT_MS` | constant | `arcane-os` | Events, processes, and testing | Node |
@@ -5905,8 +5907,20 @@ At least one `llm` or `provider` is required. The mutable API object contains
5905
5907
  delivers every choice's ordinary content/reasoning values in provider order,
5906
5908
  and returns ordinary terminal text for one choice, a structural-call array for
5907
5909
  selected tool output, or complete JSON text for a multi-choice completion.
5908
- `onDataChunk` and `onDataResult` preserve the complete provider chunk and
5909
- terminal record independently of that application-facing projection. Use
5910
+ `onDataChunk` receives provider chunks with private structural fields removed;
5911
+ `onDataResult` preserves the complete terminal record independently of that
5912
+ application-facing projection. Supply `toolText:{name,field}` with
5913
+ `onToolText(text,call,displayId)` to receive one selected root string argument
5914
+ as it arrives. `call` contains `{id,name,field,index,choiceIndex}` with the real
5915
+ normalized call ID, call position, and response-choice index. The SDK decodes
5916
+ JSON string escapes, preserves whitespace and order, and starts delivery once
5917
+ the matching tool name and call ID are known. `displayId` is the same request
5918
+ display ID as `onChunk`. This separate callback does not add ordinary prose,
5919
+ execute tools, or persist history. Complete-only providers emit the selected
5920
+ text only on actual completion; repeated terminal snapshots do not replay
5921
+ emitted text. Callback failures reach the request owner and cancellation
5922
+ prevents later delivery. Omitting `toolText` preserves the existing behavior.
5923
+ See the [tool-text example](ai/browser-wasm.md#stream-selected-tool-text). Use
5910
5924
  `ai.llm.stream()` for the async iterator; structural fragments remain private
5911
5925
  until the complete terminal result validates.
5912
5926
 
@@ -5991,6 +6005,61 @@ async function openLocalReviewAfterUserChoice() {
5991
6005
  }
5992
6006
  ```
5993
6007
 
6008
+ ## createToolTextObserver()
6009
+
6010
+ ### Overview
6011
+
6012
+ Creates the shared tool-text observer used by SDK provider integrations before
6013
+ private structural fields are removed. Application callers normally use
6014
+ `streamRequest({toolText,onToolText})` instead.
6015
+
6016
+ ### Signature and result
6017
+
6018
+ ```text
6019
+ createToolTextObserver(selection, onText, {signal}={})
6020
+ ```
6021
+
6022
+ `selection` is `{name,field}`: the exact tool name and one root string argument.
6023
+ `undefined`, `null`, or `false` selection returns `null`. An active selection
6024
+ requires nonblank string `name` and `field` values and an `onText` function;
6025
+ invalid configuration throws `TypeError`.
6026
+
6027
+ The result is an async `observeToolText(chunk)` function. It accepts raw
6028
+ OpenAI-compatible `choices[].delta.tool_calls` fragments and complete
6029
+ `choices[].message.tool_calls` or `message.tool_calls` snapshots. `onText` is
6030
+ awaited with each newly decoded fragment and
6031
+ `{id,name,field,index,choiceIndex}`. It preserves decoded string content and
6032
+ whitespace, waits for the matching name and real normalized ID, and reports
6033
+ malformed selected argument text with `ARCANE_AI_TOOL_TEXT_INVALID`.
6034
+
6035
+ ### Availability and normalization
6036
+
6037
+ **Compatible JavaScript module host.** One observer owns one request's call
6038
+ state. Consume each raw delta once, before any structural filtering; pass the
6039
+ same observer through the provider integration instead of creating another
6040
+ parser. Complete snapshots may be observed again without replaying emitted
6041
+ text. A complete-only response emits only when received. `signal` stops later
6042
+ observation after cancellation; callback errors propagate to the caller. The
6043
+ observer does not modify the supplied chunk, invoke tools, persist history, or
6044
+ start inference.
6045
+
6046
+ ### Example
6047
+
6048
+ ```javascript
6049
+ import {createToolTextObserver} from 'arcane-os/ai/tool-text-stream';
6050
+
6051
+ function createProviderTextObserver(onText, signal) {
6052
+ return createToolTextObserver(
6053
+ {name:'prepare_conversation_closing_report', field:'final_message'},
6054
+ onText,
6055
+ {signal}
6056
+ );
6057
+ }
6058
+ ```
6059
+
6060
+ The provider owner passes actual raw chunks to the returned observer and awaits
6061
+ it before continuing its existing filtered stream delivery.
6062
+
5994
6063
  ## createBrowserModelSource()
5995
6064
 
5996
6065
  ### Overview
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arcane-os",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "Arcane OS JavaScript SDK, project-local CLI, browser runtime, and repository-portable application packager.",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -20,6 +20,7 @@
20
20
  "./speech-playback": "./runtime/arcane/modules/SpeechPlayback.js",
21
21
  "./speech-text": "./browser-runtime/speech-text.mjs",
22
22
  "./ai/browser-wasm": "./browser-runtime/ai/browser-wasm.mjs",
23
+ "./ai/tool-text-stream": "./browser-runtime/ai/tool-text-stream.mjs",
23
24
  "./ai/browser-speech": "./browser-runtime/ai/browser-speech.mjs",
24
25
  "./mail": "./src/mail-api.mjs",
25
26
  "./testing": "./src/testing.mjs",
@@ -18,6 +18,7 @@ import {normalizeOllamaModelIdentifier} from './OllamaModelIdentifier.js';
18
18
  import {arcaneLogging} from 'arcane-os/logging';
19
19
  import {MarkdownSpeech,stripSpeechFormatting} from 'arcane-os/speech-text';
20
20
  import {prepareSpeech} from './PreparedSpeech.js';
21
+ import {createToolTextObserver} from 'arcane-os/ai/tool-text-stream';
21
22
 
22
23
  const completeValue=(value)=>value;
23
24
 
@@ -1470,7 +1471,7 @@ class AI {
1470
1471
  status:statusBuiltInLLMProvider()
1471
1472
  });
1472
1473
  },
1473
- request:function requestBuiltInLLMProvider(context={}){
1474
+ request:function requestBuiltInLLMProvider(context={},controls={}){
1474
1475
  if(context.signal?.aborted){
1475
1476
  throw normalizeAIRequestAbort(context.signal.reason);
1476
1477
  }
@@ -1502,7 +1503,8 @@ class AI {
1502
1503
  function executeBuiltInLLMProviderStream(bridge){
1503
1504
  return runtime.#requestBuiltInLLMStream(
1504
1505
  context.payload,
1505
- bridge
1506
+ bridge,
1507
+ controls.observeToolText
1506
1508
  );
1507
1509
  },
1508
1510
  context.signal
@@ -4285,7 +4287,7 @@ class AI {
4285
4287
  );
4286
4288
  }
4287
4289
 
4288
- #requestBuiltInLLMStream(payload={},bridge){
4290
+ #requestBuiltInLLMStream(payload={},bridge,observeToolText=null){
4289
4291
  const parallelToolCalls=payload.parallelToolCalls!==undefined
4290
4292
  ?payload.parallelToolCalls
4291
4293
  :payload.parallel_tool_calls;
@@ -4310,7 +4312,8 @@ class AI {
4310
4312
  true,
4311
4313
  emitBuiltInLLMStreamData,
4312
4314
  function ignoreBuiltInLLMStreamResult(){},
4313
- payload.reasoningEffort
4315
+ payload.reasoningEffort,
4316
+ observeToolText
4314
4317
  );
4315
4318
  }
4316
4319
 
@@ -4459,6 +4462,8 @@ class AI {
4459
4462
  structuredOutput=false,
4460
4463
  localOnly=false,
4461
4464
  onChunk=function ignoreStreamChunk(){},
4465
+ toolText,
4466
+ onToolText,
4462
4467
  onComplete=function finishIgnoredStream(){},
4463
4468
  onDataChunk=function ignoreStreamDataChunk(){},
4464
4469
  onDataResult=function ignoreStreamDataResult(){},
@@ -4484,6 +4489,15 @@ class AI {
4484
4489
  reasoningEffort
4485
4490
  }={}){
4486
4491
  validateAIStructuralRequest(messages,tools,parallelToolCalls);
4492
+ const observeToolText=createToolTextObserver(
4493
+ toolText,
4494
+ is.function(onToolText)
4495
+ ?function reportAIStreamToolText(text,call){
4496
+ return onToolText(text,call,`M-${id}`);
4497
+ }
4498
+ :onToolText,
4499
+ {signal}
4500
+ );
4487
4501
  const normalizedReasoningEffort=normalizeAIReasoningEffort(
4488
4502
  reasoningEffort===undefined?this.reasoningEffort:reasoningEffort
4489
4503
  );
@@ -4538,7 +4552,8 @@ class AI {
4538
4552
  payload:request,
4539
4553
  localOnly,
4540
4554
  signal
4541
- }
4555
+ },
4556
+ {observeToolText}
4542
4557
  );
4543
4558
  for await(const chunk of handle){
4544
4559
  if(signal?.aborted){
@@ -4589,7 +4604,7 @@ class AI {
4589
4604
  if(signal?.aborted){
4590
4605
  throw normalizeAIRequestAbort();
4591
4606
  }
4592
- this.finishTTS();
4607
+ this.#finishStreamingSpeech();
4593
4608
  return result;
4594
4609
  }catch(error){
4595
4610
  if(handle){
@@ -4622,7 +4637,8 @@ class AI {
4622
4637
  true,
4623
4638
  onDataChunk,
4624
4639
  onDataResult,
4625
- normalizedReasoningEffort
4640
+ normalizedReasoningEffort,
4641
+ observeToolText
4626
4642
  );
4627
4643
  const structuralToolCalls=normalizeAICompletionToolCalls(
4628
4644
  completion
@@ -4645,7 +4661,7 @@ class AI {
4645
4661
  if(signal?.aborted){
4646
4662
  throw normalizeAIRequestAbort();
4647
4663
  }
4648
- this.finishTTS();
4664
+ this.#finishStreamingSpeech();
4649
4665
  return result;
4650
4666
  }catch(error){
4651
4667
  this.stopAudio();
@@ -4729,7 +4745,8 @@ class AI {
4729
4745
  returnCompletion=false,
4730
4746
  dataChunkHandler=function ignoreBuiltInStreamDataChunk(){},
4731
4747
  dataResultHandler=function ignoreBuiltInStreamDataResult(){},
4732
- reasoningEffort
4748
+ reasoningEffort,
4749
+ observeToolText=null
4733
4750
  ){
4734
4751
  let speechTurnCompleted=false;
4735
4752
 
@@ -4845,6 +4862,12 @@ class AI {
4845
4862
  );
4846
4863
  }
4847
4864
  streamedNativeToolCalls=observed;
4865
+ if(observeToolText){
4866
+ await observeToolText({message:{tool_calls:observed}});
4867
+ }
4868
+ }
4869
+ if(signal?.aborted){
4870
+ return;
4848
4871
  }
4849
4872
  const thinking=seeThinking
4850
4873
  ?String(message.thinking||'')
@@ -4918,6 +4941,12 @@ class AI {
4918
4941
  structuralToolCalls,
4919
4942
  tool_choice
4920
4943
  );
4944
+ if(observeToolText){
4945
+ await observeToolText(nativeCompletion);
4946
+ }
4947
+ if(signal?.aborted){
4948
+ throw normalizeAIRequestAbort();
4949
+ }
4921
4950
  await dataResultHandler(nativeCompletion,id);
4922
4951
  for(const call of structuralToolCalls){
4923
4952
  if(signal?.aborted){
@@ -4928,7 +4957,7 @@ class AI {
4928
4957
 
4929
4958
  const nativeResult=this.#providerCompletionOutput(nativeCompletion);
4930
4959
  if(finishSpeech){
4931
- this.finishTTS();
4960
+ this.#finishStreamingSpeech();
4932
4961
  }
4933
4962
  await streamComplete(nativeResult,`M-${id}`,isThinking);
4934
4963
  speechTurnCompleted=true;
@@ -5096,6 +5125,12 @@ class AI {
5096
5125
  'The AI stream returned a non-object event payload.'
5097
5126
  );
5098
5127
  }
5128
+ if(observeToolText){
5129
+ await observeToolText(streamedResponse);
5130
+ }
5131
+ if(signal?.aborted){
5132
+ throw normalizeAIRequestAbort();
5133
+ }
5099
5134
  const dataChunk=projectAIStreamChunk(streamedResponse);
5100
5135
  if(dataChunk!==OMITTED_AI_STREAM_DATA){
5101
5136
  await dataChunkHandler(dataChunk,id);
@@ -5253,6 +5288,13 @@ class AI {
5253
5288
  await drainSseBuffer(true);
5254
5289
  }
5255
5290
  }catch(error){
5291
+ if(observeToolText){
5292
+ await reader.cancel(error).catch(
5293
+ function reportToolTextReaderCleanupFailure(cleanupError){
5294
+ arcaneLogging.error('Arcane tool text reader cleanup failed.',cleanupError);
5295
+ }
5296
+ );
5297
+ }
5256
5298
  if(isAIRequestAbort(error,signal)){
5257
5299
  throw normalizeAIRequestAbort(error);
5258
5300
  }
@@ -5383,6 +5425,12 @@ class AI {
5383
5425
  terminalToolCalls,
5384
5426
  'The built-in HTTP stream'
5385
5427
  );
5428
+ if(observeToolText){
5429
+ await observeToolText(completion);
5430
+ }
5431
+ if(signal?.aborted){
5432
+ throw normalizeAIRequestAbort();
5433
+ }
5386
5434
  await dataResultHandler(completion,id);
5387
5435
  for(const call of terminalToolCalls){
5388
5436
  if(signal?.aborted){
@@ -5392,7 +5440,7 @@ class AI {
5392
5440
  }
5393
5441
  const streamResult=this.#providerCompletionOutput(completion);
5394
5442
  if(finishSpeech){
5395
- this.finishTTS();
5443
+ this.#finishStreamingSpeech();
5396
5444
  }
5397
5445
  await streamComplete(streamResult, `M-${id}`,isThinking);
5398
5446
 
@@ -6075,6 +6123,16 @@ class AI {
6075
6123
  );
6076
6124
  }
6077
6125
 
6126
+ #finishStreamingSpeech(){
6127
+ if(this.muted){
6128
+ for(const playback of this.#preparedSpeechPlaybacks) playback.stop();
6129
+ this.audioMessageChunks='';
6130
+ this.#markdownSpeech.reset();
6131
+ return;
6132
+ }
6133
+ this.finishTTS();
6134
+ }
6135
+
6078
6136
  finishTTS(){
6079
6137
  this.#traceSpeech('finishTTS.call');
6080
6138
  return this.streamTTS('',true);
@@ -3347,14 +3347,14 @@ export class AIProviderRuntime {
3347
3347
  return this.#disposeAllPromise;
3348
3348
  }
3349
3349
 
3350
- request(role, options = {}, {speechInputPrepared = false} = {}) {
3350
+ request(role, options = {}, {speechInputPrepared = false, observeToolText = null} = {}) {
3351
3351
  if (SPEECH_ROLES.includes(role)) {
3352
3352
  arcaneLogging.debug('[Arcane speech runtime] request', role, options);
3353
3353
  }
3354
- return this.#requestRole(role, options, false, speechInputPrepared);
3354
+ return this.#requestRole(role, options, false, speechInputPrepared, observeToolText);
3355
3355
  }
3356
3356
 
3357
- #requestRole(role, options, queued, speechInputPrepared = false) {
3357
+ #requestRole(role, options, queued, speechInputPrepared = false, observeToolText = null) {
3358
3358
  this.#assertOpen();
3359
3359
  this.#assertNotConfiguring();
3360
3360
  assertRole(role);
@@ -3486,7 +3486,7 @@ export class AIProviderRuntime {
3486
3486
  }
3487
3487
  if ((!queued && slot.requestQueue.length)
3488
3488
  || slot.activeRequests.size >= maxConcurrentRequests) {
3489
- return this.#enqueueRoleRequest(slot, options);
3489
+ return this.#enqueueRoleRequest(slot, options, observeToolText);
3490
3490
  }
3491
3491
  if (!slot.ready
3492
3492
  || providerStatus.state !== 'ready'
@@ -3556,6 +3556,17 @@ export class AIProviderRuntime {
3556
3556
  }
3557
3557
 
3558
3558
  if (options.operation === 'stream') {
3559
+ const observeCurrentToolText = role === 'llm' && observeToolText
3560
+ ? async function observeCurrentAIProviderToolText(chunk) {
3561
+ runtime.#assertCurrentRequest(
3562
+ slot, generation, requestSequence, requestRecord, controller.signal
3563
+ );
3564
+ await observeToolText(chunk);
3565
+ runtime.#assertCurrentRequest(
3566
+ slot, generation, requestSequence, requestRecord, controller.signal
3567
+ );
3568
+ }
3569
+ : null;
3559
3570
  let providerHandle = null;
3560
3571
  let providerOpenPromise = null;
3561
3572
  let iterator = null;
@@ -3796,7 +3807,8 @@ export class AIProviderRuntime {
3796
3807
  operation: options.operation,
3797
3808
  payload: options.payload,
3798
3809
  signal: controller.signal
3799
- }
3810
+ },
3811
+ {observeToolText: observeCurrentToolText}
3800
3812
  );
3801
3813
  }
3802
3814
  );
@@ -3862,6 +3874,7 @@ export class AIProviderRuntime {
3862
3874
  continue;
3863
3875
  }
3864
3876
  llmToolCallCorrelation.observe(result.value);
3877
+ if (observeCurrentToolText) await observeCurrentToolText(result.value);
3865
3878
  const projected = projectLLMStreamChunk(result.value);
3866
3879
  if (projected !== OMITTED_LLM_STREAM_DATA) {
3867
3880
  publishProjectedAIProviderStreamChunk(projected);
@@ -3902,6 +3915,7 @@ export class AIProviderRuntime {
3902
3915
  )
3903
3916
  : value;
3904
3917
  llmToolCallCorrelation?.assertTerminal(terminalValue);
3918
+ if (observeCurrentToolText) await observeCurrentToolText(terminalValue);
3905
3919
  settleAIProviderStream(null, terminalValue);
3906
3920
  } catch (error) {
3907
3921
  if (cleanupPromise) {
@@ -4208,7 +4222,7 @@ export class AIProviderRuntime {
4208
4222
  );
4209
4223
  }
4210
4224
 
4211
- #enqueueRoleRequest(slot, options) {
4225
+ #enqueueRoleRequest(slot, options, observeToolText = null) {
4212
4226
  if (SPEECH_ROLES.includes(slot.role)) {
4213
4227
  arcaneLogging.debug('[Arcane speech runtime] queue.enqueue', {
4214
4228
  role: slot.role,
@@ -4222,6 +4236,7 @@ export class AIProviderRuntime {
4222
4236
  return new Promise(function queueAIProviderRoleRequest(resolve, reject) {
4223
4237
  const entry = {
4224
4238
  options,
4239
+ observeToolText,
4225
4240
  resolve,
4226
4241
  reject,
4227
4242
  detachSignal: null
@@ -4293,7 +4308,9 @@ export class AIProviderRuntime {
4293
4308
  }
4294
4309
  let operation;
4295
4310
  try {
4296
- operation = runtime.#requestRole(slot.role, entry.options, true);
4311
+ operation = runtime.#requestRole(
4312
+ slot.role, entry.options, true, false, entry.observeToolText
4313
+ );
4297
4314
  } catch (error) {
4298
4315
  if (SPEECH_ROLES.includes(slot.role)) {
4299
4316
  arcaneLogging.debug('[Arcane speech runtime] queue.error', slot.role, entry.options, error);