@glassly/engine 0.3.5-beta.734 → 0.3.5-beta.760

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 (95) hide show
  1. package/build/engine.d.ts +3 -0
  2. package/build/engine.d.ts.map +1 -1
  3. package/build/engine.js +4 -0
  4. package/build/engine.js.map +1 -1
  5. package/build/facades/glasses.d.ts +5 -1
  6. package/build/facades/glasses.d.ts.map +1 -1
  7. package/build/facades/glasses.js +5 -0
  8. package/build/facades/glasses.js.map +1 -1
  9. package/build/generated/releaseMetadata.js +3 -3
  10. package/build/generated/releaseMetadata.js.map +1 -1
  11. package/build/services/GestureDotsService.d.ts.map +1 -1
  12. package/build/services/GestureDotsService.js +2 -1
  13. package/build/services/GestureDotsService.js.map +1 -1
  14. package/build/services/GlassesTouchInput.d.ts +2 -1
  15. package/build/services/GlassesTouchInput.d.ts.map +1 -1
  16. package/build/services/GlassesTouchInput.js +64 -26
  17. package/build/services/GlassesTouchInput.js.map +1 -1
  18. package/build/services/LocalLlmModelManager.d.ts +3 -1
  19. package/build/services/LocalLlmModelManager.d.ts.map +1 -1
  20. package/build/services/LocalLlmModelManager.js +13 -5
  21. package/build/services/LocalLlmModelManager.js.map +1 -1
  22. package/build/services/LocalLlmPrompt.d.ts +10 -9
  23. package/build/services/LocalLlmPrompt.d.ts.map +1 -1
  24. package/build/services/LocalLlmPrompt.js +43 -32
  25. package/build/services/LocalLlmPrompt.js.map +1 -1
  26. package/build/services/LocalLlmProvider.d.ts.map +1 -1
  27. package/build/services/LocalLlmProvider.js +39 -20
  28. package/build/services/LocalLlmProvider.js.map +1 -1
  29. package/build/services/LocalMiniappRuntime.d.ts +19 -4
  30. package/build/services/LocalMiniappRuntime.d.ts.map +1 -1
  31. package/build/services/LocalMiniappRuntime.js +68 -125
  32. package/build/services/LocalMiniappRuntime.js.map +1 -1
  33. package/build/services/SceneRenderer.d.ts.map +1 -1
  34. package/build/services/SceneRenderer.js +3 -1
  35. package/build/services/SceneRenderer.js.map +1 -1
  36. package/build/services/actionInvoke.d.ts +37 -0
  37. package/build/services/actionInvoke.d.ts.map +1 -0
  38. package/build/services/actionInvoke.js +89 -0
  39. package/build/services/actionInvoke.js.map +1 -0
  40. package/build/services/appleWatch/AppleWatchLink.d.ts +42 -0
  41. package/build/services/appleWatch/AppleWatchLink.d.ts.map +1 -0
  42. package/build/services/appleWatch/AppleWatchLink.js +259 -0
  43. package/build/services/appleWatch/AppleWatchLink.js.map +1 -0
  44. package/build/services/controllers.d.ts.map +1 -1
  45. package/build/services/controllers.js +16 -0
  46. package/build/services/controllers.js.map +1 -1
  47. package/build/services/settingsBridge.d.ts +4 -4
  48. package/build/services/settingsBridge.d.ts.map +1 -1
  49. package/build/services/settingsBridge.js +9 -4
  50. package/build/services/settingsBridge.js.map +1 -1
  51. package/build/stores/bluetoothSettingKeys.d.ts +2 -0
  52. package/build/stores/bluetoothSettingKeys.d.ts.map +1 -1
  53. package/build/stores/bluetoothSettingKeys.js +17 -0
  54. package/build/stores/bluetoothSettingKeys.js.map +1 -1
  55. package/build/stores/settings.d.ts.map +1 -1
  56. package/build/stores/settings.js +32 -2
  57. package/build/stores/settings.js.map +1 -1
  58. package/build/types/capabilities/rayneo-io.d.ts.map +1 -1
  59. package/build/types/capabilities/rayneo-io.js +2 -0
  60. package/build/types/capabilities/rayneo-io.js.map +1 -1
  61. package/build/types/enums.d.ts +2 -1
  62. package/build/types/enums.d.ts.map +1 -1
  63. package/build/types/enums.js +1 -0
  64. package/build/types/enums.js.map +1 -1
  65. package/build/utils/display/scene/index.d.ts +1 -1
  66. package/build/utils/display/scene/index.d.ts.map +1 -1
  67. package/build/utils/display/scene/index.js.map +1 -1
  68. package/build/utils/display/scene/process.d.ts.map +1 -1
  69. package/build/utils/display/scene/process.js +20 -1
  70. package/build/utils/display/scene/process.js.map +1 -1
  71. package/build/utils/display/scene/types.d.ts +1 -1
  72. package/build/utils/display/scene/types.d.ts.map +1 -1
  73. package/build/utils/display/scene/types.js.map +1 -1
  74. package/package.json +7 -7
  75. package/src/engine.ts +4 -0
  76. package/src/facades/glasses.ts +7 -0
  77. package/src/generated/releaseMetadata.ts +3 -3
  78. package/src/services/GestureDotsService.ts +2 -1
  79. package/src/services/GlassesTouchInput.ts +69 -23
  80. package/src/services/LocalLlmModelManager.ts +16 -6
  81. package/src/services/LocalLlmPrompt.ts +56 -37
  82. package/src/services/LocalLlmProvider.ts +49 -22
  83. package/src/services/LocalMiniappRuntime.ts +103 -125
  84. package/src/services/SceneRenderer.ts +3 -1
  85. package/src/services/actionInvoke.ts +105 -0
  86. package/src/services/appleWatch/AppleWatchLink.ts +297 -0
  87. package/src/services/controllers.ts +17 -0
  88. package/src/services/settingsBridge.ts +9 -4
  89. package/src/stores/bluetoothSettingKeys.ts +20 -0
  90. package/src/stores/settings.ts +34 -2
  91. package/src/types/capabilities/rayneo-io.ts +2 -0
  92. package/src/types/enums.ts +1 -0
  93. package/src/utils/display/scene/index.ts +1 -0
  94. package/src/utils/display/scene/process.ts +17 -1
  95. package/src/utils/display/scene/types.ts +1 -0
@@ -4,6 +4,7 @@ import BluetoothSdk from "@glassly/bluetooth-sdk/internal";
4
4
  import { useAppStatusStore } from "../stores/apps";
5
5
  import { useGlassesStore } from "../stores/glasses";
6
6
  import { BgTimer } from "../utils/timers";
7
+ import { hasInput2d } from "./controllers";
7
8
  import dashboardOpenTrace from "./debug/DashboardOpenTrace";
8
9
  import gestureDotsService from "./GestureDotsService";
9
10
  import { isGlassesConnected } from "./GlassesReadiness";
@@ -22,23 +23,54 @@ const miniappExitGesture = new MiniappExitGesture({
22
23
  setTimeout: (callback, delay) => BgTimer.setTimeout(callback, delay),
23
24
  clearTimeout: (timerId) => BgTimer.clearTimeout(timerId),
24
25
  });
25
- // Raw ring reports include every scroll step, whether the CFW forwards them
26
- // (deviceModel G2) or the ring sends them to the phone itself (deviceModel R1);
27
- // both tag source 2. Rate-limit scroll actions separately from press/release
28
- // recognition, per ring, using native receipt timestamps so a JS backlog does
29
- // not collapse otherwise separate gestures.
30
- const RING_SCROLL_INTERVAL_MS = 100;
31
- const lastRingScrollAt = new Map();
32
- function shouldForwardScroll(event) {
33
- if (event.source !== 2 || (event.gestureName !== "swipe_up" && event.gestureName !== "swipe_down"))
34
- return true;
35
- const ring = event.controllerId ?? `source:${event.source}`;
36
- const last = lastRingScrollAt.get(ring);
26
+ // The ring reports a slide once per step of travel, whether the CFW forwards
27
+ // it (deviceModel G2) or the ring sends it to the phone itself (deviceModel
28
+ // R1); both tag source 2. One press is one swipe: the stroke's first step goes
29
+ // out as swipe_up / swipe_down, and every step, the first included, as
30
+ // scroll_up / scroll_down with its distance and speed for smooth scrolling. A
31
+ // stroke ends at the ring's next touch_down or tap_end, or after
32
+ // RING_STROKE_IDLE_MS without a step when a report was lost. Reversing within
33
+ // a stroke fires no swipe (a finger rolling back at lift-off). Native receipt
34
+ // timestamps keep strokes apart when JS drains a backlog.
35
+ const RING_STROKE_IDLE_MS = 1000;
36
+ /** Per ring, when the open stroke's last step arrived. */
37
+ const ringStrokes = new Map();
38
+ function ringKey(event) {
39
+ return event.controllerId ?? `source:${event.source}`;
40
+ }
41
+ function isRingSlideStep(event) {
42
+ return event.source === 2 && (event.gestureName === "swipe_up" || event.gestureName === "swipe_down");
43
+ }
44
+ function opensRingStroke(event) {
45
+ const last = ringStrokes.get(ringKey(event));
46
+ ringStrokes.set(ringKey(event), event.timestamp);
37
47
  const elapsed = last === undefined ? null : event.timestamp - last;
38
- if (elapsed !== null && elapsed >= 0 && elapsed < RING_SCROLL_INTERVAL_MS)
39
- return false;
40
- lastRingScrollAt.set(ring, event.timestamp);
41
- return true;
48
+ return elapsed === null || elapsed < 0 || elapsed >= RING_STROKE_IDLE_MS;
49
+ }
50
+ function endRingStroke(event) {
51
+ if (event.source === 2 && (event.gestureName === "touch_down" || event.gestureName === "tap_end")) {
52
+ ringStrokes.delete(ringKey(event));
53
+ }
54
+ }
55
+ /** The discrete swipe a stroke opens with: the step's travel belongs to scroll_*. */
56
+ function strokeSwipe(step) {
57
+ const swipe = { ...step };
58
+ delete swipe.distance;
59
+ delete swipe.speed;
60
+ return swipe;
61
+ }
62
+ /**
63
+ * Miniapps' copy of the touch: `input2d: true` when it came from a controller
64
+ * that swipes in two dimensions (the Neural Band), the field absent otherwise,
65
+ * so a 1D swipe from the temples or the ring stays tellable while a band is
66
+ * connected under the same gesture names.
67
+ */
68
+ function toMiniapps(event) {
69
+ const id = event.controllerId;
70
+ if (id === undefined)
71
+ return event;
72
+ const model = useGlassesStore.getState().controllers?.[id]?.model;
73
+ return model !== undefined && hasInput2d(model) ? { ...event, input2d: true } : event;
42
74
  }
43
75
  /**
44
76
  * Route both real glasses input and phone mirror controls through the same
@@ -50,9 +82,20 @@ function shouldForwardScroll(event) {
50
82
  * dashboard's claim is for the screen with no app in it. Head position
51
83
  * (head_up / head_down) is a gesture like any other: the dashboard claims it
52
84
  * while it runs, and an unclaimed head_up on glasses that defer the dashboard
53
- * to the phone opens the native one, as it would with no app at all.
85
+ * to the phone opens the native one, as it would with no app at all. A ring
86
+ * slide step becomes one swipe per stroke plus a scroll step (see above).
54
87
  */
55
88
  export function dispatchTouchEvent(event) {
89
+ if (isRingSlideStep(event)) {
90
+ if (opensRingStroke(event))
91
+ routeTouchEvent(strokeSwipe(event));
92
+ routeTouchEvent({ ...event, gestureName: event.gestureName === "swipe_up" ? "scroll_up" : "scroll_down" });
93
+ return;
94
+ }
95
+ endRingStroke(event);
96
+ routeTouchEvent(event);
97
+ }
98
+ function routeTouchEvent(event) {
56
99
  const gesture = event.gestureName;
57
100
  const claimant = localMiniappRuntime.gestureClaimant(gesture);
58
101
  // The Neural Band's middle finger (index 1) shares the tap names but is left
@@ -80,18 +123,13 @@ export function dispatchTouchEvent(event) {
80
123
  }
81
124
  // The press may have started before this app claimed its release edge.
82
125
  gestureDotsService.noteGesture(gesture, true, event.index, event.controllerId);
83
- if (!shouldForwardScroll(event))
84
- return;
85
- localMiniappRuntime.forwardEvent("touch_event", event, undefined, claimant);
126
+ localMiniappRuntime.forwardEvent("touch_event", toMiniapps(event), undefined, claimant);
86
127
  return;
87
128
  }
88
129
  // Gesture-dots debug indicator (any device, gated by its setting). It
89
- // only paints while the screen is otherwise empty. Process even suppressed
90
- // scroll repeats here so their completion still clears a held dot.
130
+ // only paints while the screen is otherwise empty.
91
131
  gestureDotsService.noteGesture(gesture, false, event.index, event.controllerId);
92
- if (!shouldForwardScroll(event))
93
- return;
94
- localMiniappRuntime.forwardEvent("touch_event", event);
132
+ localMiniappRuntime.forwardEvent("touch_event", toMiniapps(event));
95
133
  // Nobody claimed a double tap or a head-up: the glasses' native dashboard.
96
134
  // On eligible Glassly CFW glasses the dashboard miniapp claims both while it
97
135
  // runs (ADR-0006); stock firmware keeps its native dashboard (ADR-0002) and
@@ -110,7 +148,7 @@ export function dispatchTouchEvent(event) {
110
148
  }
111
149
  export function resetTouchInput() {
112
150
  miniappExitGesture.reset();
113
- lastRingScrollAt.clear();
151
+ ringStrokes.clear();
114
152
  }
115
153
  /** Phone mirror input uses the same dashboard/miniapp policy as real glasses. */
116
154
  export function sendGesture(gestureName) {
@@ -1 +1 @@
1
- {"version":3,"file":"GlassesTouchInput.js","sourceRoot":"","sources":["../../src/services/GlassesTouchInput.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAC,YAAY,EAAkB,MAAM,wBAAwB,CAAA;AACpE,OAAO,YAAY,MAAM,iCAAiC,CAAA;AAE1D,OAAO,EAAC,iBAAiB,EAAC,MAAM,gBAAgB,CAAA;AAChD,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAA;AACvC,OAAO,kBAAkB,MAAM,4BAA4B,CAAA;AAC3D,OAAO,kBAAkB,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAC,kBAAkB,EAAC,MAAM,oBA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B,IAAI,CAAC,uBAAuB,CAAC,QAAQ,IAAI,kBAAkB,CAAC,eAAe,CAAC,QAAQ,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;QAC3H,eAAe,CAAC,QAAQ,EAAE,CAAC,eAAe,CAAC,EAAC,MAAM,EAAE,EAAC,UAAU,EAAE,aAAa,EAAE,MAAM,EAAE,oBAAoB,EAAC,EAAC,CAAC,CAAA;QAC/G,KAAK,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;YAC/D,OAAO,CAAC,KAAK,CAAC,0CAA0C,EAAE,GAAG,CAAC,CAAA;QAChE,CAAC,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,kBAAkB,CAAC,KAAK,EAAE,CAAA;IAC1B,gBAAgB,CAAC,KAAK,EAAE,CAAA;AAC1B,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,WAAW,CACzB,WAee;IAEf,MAAM,KAAK,GAAG,eAAe,CAAC,QAAQ,EAAE,CAAC,WAAW,CAAA;IACpD,kBAAkB,CAAC;QACjB,IAAI,EAAE,aAAa;QACnB,WAAW;QACX,WAAW,EAAE,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,KAAK,KAAK,CAAC,IAAI,YAAY,CAAC,SAAS;QAC3G,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACtB,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {useDisplayStore} from \"../stores/display\"\nimport {DeviceModels, type TouchEvent} from \"@glassly/bluetooth-sdk\"\nimport BluetoothSdk from \"@glassly/bluetooth-sdk/internal\"\n\nimport {useAppStatusStore} from \"../stores/apps\"\nimport {useGlassesStore} from \"../stores/glasses\"\nimport {BgTimer} from \"../utils/timers\"\nimport dashboardOpenTrace from \"./debug/DashboardOpenTrace\"\nimport gestureDotsService from \"./GestureDotsService\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport localDisplayManager from \"./LocalDisplayManager\"\nimport localMiniappRuntime from \"./LocalMiniappRuntime\"\nimport {MiniappExitGesture} from \"./MiniappExitGesture\"\nimport nativeNavigationService from \"./NativeNavigationService\"\nimport {isOverlayApp} from \"./pages/overlayApps\"\nimport {pagesEligible} from \"./pages/pageEligibility\"\n\nconst miniappExitGesture = new MiniappExitGesture({\n getState: () => useAppStatusStore.getState(),\n getTargetPackageName: () => localDisplayManager.getMiniappToLeave(),\n beginExitNotice: (packageName, text) => localDisplayManager.beginMiniappExit(packageName, text),\n finishExitNotice: (packageName) => localDisplayManager.finishMiniappExit(packageName),\n cancelExitNotice: (packageName) => localDisplayManager.cancelMiniappExit(packageName),\n setTimeout: (callback, delay) => BgTimer.setTimeout(callback, delay),\n clearTimeout: (timerId) => BgTimer.clearTimeout(timerId),\n})\n\n// Raw ring reports include every scroll step, whether the CFW forwards them\n// (deviceModel G2) or the ring sends them to the phone itself (deviceModel R1);\n// both tag source 2. Rate-limit scroll actions separately from press/release\n// recognition, per ring, using native receipt timestamps so a JS backlog does\n// not collapse otherwise separate gestures.\nconst RING_SCROLL_INTERVAL_MS = 100\nconst lastRingScrollAt = new Map<string, number>()\n\nfunction shouldForwardScroll(event: TouchEvent): boolean {\n if (event.source !== 2 || (event.gestureName !== \"swipe_up\" && event.gestureName !== \"swipe_down\")) return true\n const ring = event.controllerId ?? `source:${event.source}`\n const last = lastRingScrollAt.get(ring)\n const elapsed = last === undefined ? null : event.timestamp - last\n if (elapsed !== null && elapsed >= 0 && elapsed < RING_SCROLL_INTERVAL_MS) return false\n lastRingScrollAt.set(ring, event.timestamp)\n return true\n}\n\n/**\n * Route both real glasses input and phone mirror controls through the same\n * policy. A claimed gesture goes to the app holding the claim, alone; an\n * unclaimed one goes to every subscriber and then the engine's default. The\n * one rule ahead of the claims: an unclaimed double tap leaves the miniapp\n * the wearer is in — the one visibly on the glasses, else the running\n * standard app on an empty screen — whoever else claimed the gesture; the\n * dashboard's claim is for the screen with no app in it. Head position\n * (head_up / head_down) is a gesture like any other: the dashboard claims it\n * while it runs, and an unclaimed head_up on glasses that defer the dashboard\n * to the phone opens the native one, as it would with no app at all.\n */\nexport function dispatchTouchEvent(event: TouchEvent): void {\n const gesture = event.gestureName\n const claimant = localMiniappRuntime.gestureClaimant(gesture)\n // The Neural Band's middle finger (index 1) shares the tap names but is left\n // to miniapps: the engine's own double-tap behaviors are the index finger's.\n const osDoubleTap = gesture === \"double_tap\" && event.index !== 1\n const osHeadUp = gesture === \"head_up\"\n\n if (osDoubleTap) {\n // The app being left opts out of OS exit by registering double tap (the\n // terminal's back-to-menu). The latest claimant still receives it. Otherwise\n // the tap means \"leave the app\". The controller shows the bounded OS\n // notice first, then uses the normal store stop path (and closes its\n // phone overlay).\n const leaving = localDisplayManager.getMiniappToLeave()\n if (\n leaving !== null &&\n !localMiniappRuntime.hasGestureClaim(leaving, gesture) &&\n miniappExitGesture.tryExitMiniapp()\n ) {\n gestureDotsService.noteGesture(gesture, true, event.index, event.controllerId)\n return\n }\n }\n\n if (claimant !== null) {\n // An overlay app claims the double tap and head-up on an empty screen to open the dashboard.\n if ((gesture === \"double_tap\" || osHeadUp) && isOverlayApp(claimant)) {\n dashboardOpenTrace.trigger(osHeadUp ? \"head-up\" : \"double-tap\", event.timestamp)\n }\n // The press may have started before this app claimed its release edge.\n gestureDotsService.noteGesture(gesture, true, event.index, event.controllerId)\n if (!shouldForwardScroll(event)) return\n localMiniappRuntime.forwardEvent(\"touch_event\", event, undefined, claimant)\n return\n }\n\n // Gesture-dots debug indicator (any device, gated by its setting). It\n // only paints while the screen is otherwise empty. Process even suppressed\n // scroll repeats here so their completion still clears a held dot.\n gestureDotsService.noteGesture(gesture, false, event.index, event.controllerId)\n\n if (!shouldForwardScroll(event)) return\n localMiniappRuntime.forwardEvent(\"touch_event\", event)\n\n // Nobody claimed a double tap or a head-up: the glasses' native dashboard.\n // On eligible Glassly CFW glasses the dashboard miniapp claims both while it\n // runs (ADR-0006); stock firmware keeps its native dashboard (ADR-0002) and\n // opens it on a head-up by itself, so only the double tap is relayed there.\n // The modal nav UI owns the screen; showDashboard would fight it. Without\n // glasses there is no dashboard to open, and the mirror keeps its frame.\n // pagesEligible: connected Glassly CFW glasses, whose firmware leaves the\n // dashboard to the phone; other firmware opens its own on a lift.\n const opensNativeDashboard = osDoubleTap || (osHeadUp && pagesEligible())\n if (opensNativeDashboard && !nativeNavigationService.isActive && isGlassesConnected(useGlassesStore.getState().connection)) {\n useDisplayStore.getState().setDisplayEvent({layout: {layoutType: \"unavailable\", reason: \"firmware-dashboard\"}})\n void Promise.resolve(BluetoothSdk.showDashboard()).catch((err) => {\n console.error(\"DeviceEventRouter: showDashboard failed:\", err)\n })\n }\n}\n\nexport function resetTouchInput(): void {\n miniappExitGesture.reset()\n lastRingScrollAt.clear()\n}\n\n/** Phone mirror input uses the same dashboard/miniapp policy as real glasses. */\nexport function sendGesture(\n gestureName:\n | \"single_tap\"\n | \"tap_start\"\n | \"double_tap\"\n | \"tap_end\"\n | \"tap_then_hold\"\n | \"touch_down\"\n | \"swipe_up\"\n | \"swipe_down\"\n | \"swipe_left\"\n | \"swipe_right\"\n | \"long_press\"\n | \"dial_up\"\n | \"dial_down\"\n | \"head_up\"\n | \"head_down\",\n): void {\n const model = useGlassesStore.getState().deviceModel\n dispatchTouchEvent({\n type: \"touch_event\",\n gestureName,\n deviceModel: Object.values(DeviceModels).find((candidate) => candidate === model) ?? DeviceModels.Simulated,\n timestamp: Date.now(),\n })\n}\n"]}
1
+ {"version":3,"file":"GlassesTouchInput.js","sourceRoot":"","sources":["../../src/services/GlassesTouchInput.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAC,YAAY,EAAkB,MAAM,wBAAwB,CAAA;AACpE,OAAO,YAAY,MAAM,iCAAiC,CAAA;AAE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,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,KAAK,KAAK,CAAC,IAAI,YAAY,CAAC,SAAS;QAC3G,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACtB,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {useDisplayStore} from \"../stores/display\"\nimport {DeviceModels, type TouchEvent} from \"@glassly/bluetooth-sdk\"\nimport BluetoothSdk from \"@glassly/bluetooth-sdk/internal\"\n\nimport {useAppStatusStore} from \"../stores/apps\"\nimport {useGlassesStore} from \"../stores/glasses\"\nimport {BgTimer} from \"../utils/timers\"\nimport {hasInput2d} from \"./controllers\"\nimport dashboardOpenTrace from \"./debug/DashboardOpenTrace\"\nimport gestureDotsService from \"./GestureDotsService\"\nimport {isGlassesConnected} from \"./GlassesReadiness\"\nimport localDisplayManager from \"./LocalDisplayManager\"\nimport localMiniappRuntime from \"./LocalMiniappRuntime\"\nimport {MiniappExitGesture} from \"./MiniappExitGesture\"\nimport nativeNavigationService from \"./NativeNavigationService\"\nimport {isOverlayApp} from \"./pages/overlayApps\"\nimport {pagesEligible} from \"./pages/pageEligibility\"\n\nconst miniappExitGesture = new MiniappExitGesture({\n getState: () => useAppStatusStore.getState(),\n getTargetPackageName: () => localDisplayManager.getMiniappToLeave(),\n beginExitNotice: (packageName, text) => localDisplayManager.beginMiniappExit(packageName, text),\n finishExitNotice: (packageName) => localDisplayManager.finishMiniappExit(packageName),\n cancelExitNotice: (packageName) => localDisplayManager.cancelMiniappExit(packageName),\n setTimeout: (callback, delay) => BgTimer.setTimeout(callback, delay),\n clearTimeout: (timerId) => BgTimer.clearTimeout(timerId),\n})\n\n// The ring reports a slide once per step of travel, whether the CFW forwards\n// it (deviceModel G2) or the ring sends it to the phone itself (deviceModel\n// R1); both tag source 2. One press is one swipe: the stroke's first step goes\n// out as swipe_up / swipe_down, and every step, the first included, as\n// scroll_up / scroll_down with its distance and speed for smooth scrolling. A\n// stroke ends at the ring's next touch_down or tap_end, or after\n// RING_STROKE_IDLE_MS without a step when a report was lost. Reversing within\n// a stroke fires no swipe (a finger rolling back at lift-off). Native receipt\n// timestamps keep strokes apart when JS drains a backlog.\nconst RING_STROKE_IDLE_MS = 1000\n/** Per ring, when the open stroke's last step arrived. */\nconst ringStrokes = new Map<string, number>()\n\nfunction ringKey(event: TouchEvent): string {\n return event.controllerId ?? `source:${event.source}`\n}\n\nfunction isRingSlideStep(event: TouchEvent): boolean {\n return event.source === 2 && (event.gestureName === \"swipe_up\" || event.gestureName === \"swipe_down\")\n}\n\nfunction opensRingStroke(event: TouchEvent): boolean {\n const last = ringStrokes.get(ringKey(event))\n ringStrokes.set(ringKey(event), event.timestamp)\n const elapsed = last === undefined ? null : event.timestamp - last\n return elapsed === null || elapsed < 0 || elapsed >= RING_STROKE_IDLE_MS\n}\n\nfunction endRingStroke(event: TouchEvent): void {\n if (event.source === 2 && (event.gestureName === \"touch_down\" || event.gestureName === \"tap_end\")) {\n ringStrokes.delete(ringKey(event))\n }\n}\n\n/** The discrete swipe a stroke opens with: the step's travel belongs to scroll_*. */\nfunction strokeSwipe(step: TouchEvent): TouchEvent {\n const swipe = {...step}\n delete swipe.distance\n delete swipe.speed\n return swipe\n}\n\n/**\n * Miniapps' copy of the touch: `input2d: true` when it came from a controller\n * that swipes in two dimensions (the Neural Band), the field absent otherwise,\n * so a 1D swipe from the temples or the ring stays tellable while a band is\n * connected under the same gesture names.\n */\nfunction toMiniapps(event: TouchEvent): TouchEvent & {input2d?: true} {\n const id = event.controllerId\n if (id === undefined) return event\n const model = useGlassesStore.getState().controllers?.[id]?.model\n return model !== undefined && hasInput2d(model) ? {...event, input2d: true} : event\n}\n\n/**\n * Route both real glasses input and phone mirror controls through the same\n * policy. A claimed gesture goes to the app holding the claim, alone; an\n * unclaimed one goes to every subscriber and then the engine's default. The\n * one rule ahead of the claims: an unclaimed double tap leaves the miniapp\n * the wearer is in — the one visibly on the glasses, else the running\n * standard app on an empty screen — whoever else claimed the gesture; the\n * dashboard's claim is for the screen with no app in it. Head position\n * (head_up / head_down) is a gesture like any other: the dashboard claims it\n * while it runs, and an unclaimed head_up on glasses that defer the dashboard\n * to the phone opens the native one, as it would with no app at all. A ring\n * slide step becomes one swipe per stroke plus a scroll step (see above).\n */\nexport function dispatchTouchEvent(event: TouchEvent): void {\n if (isRingSlideStep(event)) {\n if (opensRingStroke(event)) routeTouchEvent(strokeSwipe(event))\n routeTouchEvent({...event, gestureName: event.gestureName === \"swipe_up\" ? \"scroll_up\" : \"scroll_down\"})\n return\n }\n endRingStroke(event)\n routeTouchEvent(event)\n}\n\nfunction routeTouchEvent(event: TouchEvent): void {\n const gesture = event.gestureName\n const claimant = localMiniappRuntime.gestureClaimant(gesture)\n // The Neural Band's middle finger (index 1) shares the tap names but is left\n // to miniapps: the engine's own double-tap behaviors are the index finger's.\n const osDoubleTap = gesture === \"double_tap\" && event.index !== 1\n const osHeadUp = gesture === \"head_up\"\n\n if (osDoubleTap) {\n // The app being left opts out of OS exit by registering double tap (the\n // terminal's back-to-menu). The latest claimant still receives it. Otherwise\n // the tap means \"leave the app\". The controller shows the bounded OS\n // notice first, then uses the normal store stop path (and closes its\n // phone overlay).\n const leaving = localDisplayManager.getMiniappToLeave()\n if (\n leaving !== null &&\n !localMiniappRuntime.hasGestureClaim(leaving, gesture) &&\n miniappExitGesture.tryExitMiniapp()\n ) {\n gestureDotsService.noteGesture(gesture, true, event.index, event.controllerId)\n return\n }\n }\n\n if (claimant !== null) {\n // An overlay app claims the double tap and head-up on an empty screen to open the dashboard.\n if ((gesture === \"double_tap\" || osHeadUp) && isOverlayApp(claimant)) {\n dashboardOpenTrace.trigger(osHeadUp ? \"head-up\" : \"double-tap\", event.timestamp)\n }\n // The press may have started before this app claimed its release edge.\n gestureDotsService.noteGesture(gesture, true, event.index, event.controllerId)\n localMiniappRuntime.forwardEvent(\"touch_event\", toMiniapps(event), undefined, claimant)\n return\n }\n\n // Gesture-dots debug indicator (any device, gated by its setting). It\n // only paints while the screen is otherwise empty.\n gestureDotsService.noteGesture(gesture, false, event.index, event.controllerId)\n\n localMiniappRuntime.forwardEvent(\"touch_event\", toMiniapps(event))\n\n // Nobody claimed a double tap or a head-up: the glasses' native dashboard.\n // On eligible Glassly CFW glasses the dashboard miniapp claims both while it\n // runs (ADR-0006); stock firmware keeps its native dashboard (ADR-0002) and\n // opens it on a head-up by itself, so only the double tap is relayed there.\n // The modal nav UI owns the screen; showDashboard would fight it. Without\n // glasses there is no dashboard to open, and the mirror keeps its frame.\n // pagesEligible: connected Glassly CFW glasses, whose firmware leaves the\n // dashboard to the phone; other firmware opens its own on a lift.\n const opensNativeDashboard = osDoubleTap || (osHeadUp && pagesEligible())\n if (opensNativeDashboard && !nativeNavigationService.isActive && isGlassesConnected(useGlassesStore.getState().connection)) {\n useDisplayStore.getState().setDisplayEvent({layout: {layoutType: \"unavailable\", reason: \"firmware-dashboard\"}})\n void Promise.resolve(BluetoothSdk.showDashboard()).catch((err) => {\n console.error(\"DeviceEventRouter: showDashboard failed:\", err)\n })\n }\n}\n\nexport function resetTouchInput(): void {\n miniappExitGesture.reset()\n ringStrokes.clear()\n}\n\n/** Phone mirror input uses the same dashboard/miniapp policy as real glasses. */\nexport function sendGesture(\n gestureName:\n | \"single_tap\"\n | \"tap_start\"\n | \"double_tap\"\n | \"tap_end\"\n | \"tap_then_hold\"\n | \"touch_down\"\n | \"swipe_up\"\n | \"swipe_down\"\n | \"swipe_left\"\n | \"swipe_right\"\n | \"long_press\"\n | \"dial_up\"\n | \"dial_down\"\n | \"head_up\"\n | \"head_down\",\n): void {\n const model = useGlassesStore.getState().deviceModel\n dispatchTouchEvent({\n type: \"touch_event\",\n gestureName,\n deviceModel: Object.values(DeviceModels).find((candidate) => candidate === model) ?? DeviceModels.Simulated,\n timestamp: Date.now(),\n })\n}\n"]}
@@ -4,8 +4,10 @@ export interface LocalLlmModelConfig {
4
4
  id: LocalLlmModelId;
5
5
  /** Human label for the Settings dropdown. */
6
6
  label: string;
7
- /** Approximate download size in bytes (the .pte dominates). */
7
+ /** Total download size in bytes (the .pte dominates). */
8
8
  sizeBytes: number;
9
+ /** Exact size of the published .pte; the availability check compares against it. */
10
+ modelBytes: number;
9
11
  /** Rough resident memory while loaded; the Settings copy warns above ~half of device RAM. */
10
12
  ramBytes: number;
11
13
  urls: {
@@ -1 +1 @@
1
- {"version":3,"file":"LocalLlmModelManager.d.ts","sourceRoot":"","sources":["../../src/services/LocalLlmModelManager.ts"],"names":[],"mappings":"AAkBA,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,YAAY,GAAG,UAAU,CAAA;AAEtE,eAAO,MAAM,uBAAuB,EAAE,eAA8B,CAAA;AAEpE,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,eAAe,CAAA;IACnB,6CAA6C;IAC7C,KAAK,EAAE,MAAM,CAAA;IACb,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAA;IACjB,6FAA6F;IAC7F,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE;QACJ,KAAK,EAAE,MAAM,CAAA;QACb,SAAS,EAAE,MAAM,CAAA;QACjB,eAAe,EAAE,MAAM,CAAA;KACxB,CAAA;CACF;AAED,qGAAqG;AACrG,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE,MAAM,CAAA;IACjB,eAAe,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,MAAM,qBAAqB,GAAG,MAAM,GAAG,aAAa,GAAG,UAAU,GAAG,QAAQ,CAAA;AAElF,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,eAAe,CAAA;IACxB,KAAK,EAAE,qBAAqB,CAAA;IAC5B,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AA6CD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,eAAe,CAE1E;AAED,KAAK,cAAc,GAA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,IAAI,OAAO,CAAC,IAAI,CAAC;IAO/B,WAAW,CAAC,EAAE,GAAE,eAAwC,GAAG,OAAO,CAAC,IAAI,CAAC;IAM9E,OAAO,CAAC,SAAS;IAWjB,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;CAI1C;AAED,QAAA,MAAM,QAAQ,sBAAqC,CAAA;AACnD,OAAO,EAAC,oBAAoB,EAAC,CAAA;AAC7B,eAAe,QAAQ,CAAA"}
@@ -17,15 +17,18 @@ import { SETTINGS, useSettingsStore } from "../stores/settings";
17
17
  export const DEFAULT_LOCAL_LLM_MODEL = "qwen3-1.7b";
18
18
  // XNNPACK 8da4w exports from software-mansion/react-native-executorch-qwen-3,
19
19
  // pinned to the v0.10.0 release tag that react-native-executorch 0.10.x
20
- // expects. Sizes are the .pte file sizes on the Hub (tokenizer adds ~11 MB).
20
+ // expects. modelBytes are the .pte sizes on the Hub; sizeBytes adds the
21
+ // tokenizer files (~11 MB).
21
22
  const QWEN3_BASE = "https://huggingface.co/software-mansion/react-native-executorch-qwen-3/resolve/v0.10.0";
23
+ const TOKENIZER_BYTES = 11_431_080;
22
24
  const MB = 1024 * 1024;
23
25
  const GB = 1024 * MB;
24
26
  const MODELS = {
25
27
  "qwen3-0.6b": {
26
28
  id: "qwen3-0.6b",
27
29
  label: "Qwen3 0.6B",
28
- sizeBytes: 517 * MB,
30
+ sizeBytes: 505_686_400 + TOKENIZER_BYTES,
31
+ modelBytes: 505_686_400,
29
32
  ramBytes: 0.9 * GB,
30
33
  urls: {
31
34
  model: `${QWEN3_BASE}/0_6b/xnnpack/qwen_3_0_6b_xnnpack_8da4w.pte`,
@@ -36,7 +39,8 @@ const MODELS = {
36
39
  "qwen3-1.7b": {
37
40
  id: "qwen3-1.7b",
38
41
  label: "Qwen3 1.7B",
39
- sizeBytes: 1315 * MB,
42
+ sizeBytes: 1_303_738_496 + TOKENIZER_BYTES,
43
+ modelBytes: 1_303_738_496,
40
44
  ramBytes: 1.8 * GB,
41
45
  urls: {
42
46
  model: `${QWEN3_BASE}/1_7b/xnnpack/qwen_3_1_7b_xnnpack_8da4w.pte`,
@@ -47,7 +51,8 @@ const MODELS = {
47
51
  "qwen3-4b": {
48
52
  id: "qwen3-4b",
49
53
  label: "Qwen3 4B",
50
- sizeBytes: 2693 * MB,
54
+ sizeBytes: 2_681_646_976 + TOKENIZER_BYTES,
55
+ modelBytes: 2_681_646_976,
51
56
  ramBytes: 3.4 * GB,
52
57
  urls: {
53
58
  model: `${QWEN3_BASE}/4b/xnnpack/qwen_3_4b_xnnpack_8da4w.pte`,
@@ -110,7 +115,7 @@ class LocalLlmModelManager {
110
115
  // most of the published size. Downloads land in a .part file and are
111
116
  // renamed only once whole, so this only catches external tampering.
112
117
  const stat = await RNFS.stat(paths.model);
113
- return Number(stat.size) >= MODELS[id].sizeBytes * 0.95;
118
+ return Number(stat.size) >= MODELS[id].modelBytes * 0.95;
114
119
  }
115
120
  catch (error) {
116
121
  console.warn("LOCAL_LLM: availability check failed:", error);
@@ -186,6 +191,9 @@ class LocalLlmModelManager {
186
191
  await this.fetchFile(config.urls.tokenizerConfig, paths.tokenizerConfig);
187
192
  await this.fetchFile(config.urls.tokenizer, paths.tokenizer);
188
193
  await this.fetchFile(config.urls.model, paths.model, (percent) => this.setStatus({ modelId: id, stage: "downloading", percent }));
194
+ if (!(await this.isModelAvailable(id))) {
195
+ throw new Error(`downloaded model is smaller than the expected ${config.modelBytes} bytes`);
196
+ }
189
197
  this.setStatus({ modelId: id, stage: "complete", percent: 100 });
190
198
  for (const listener of this.modelReadyListeners) {
191
199
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"LocalLlmModelManager.js","sourceRoot":"","sources":["../../src/services/LocalLlmModelManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AAEnD,OAAO,EAA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AAC,KAAK,CAAA;IACvC,CAAC;CACF;AAED,MAAM,QAAQ,GAAG,oBAAoB,CAAC,WAAW,EAAE,CAAA;AACnD,OAAO,EAAC,oBAAoB,EAAC,CAAA;AAC7B,eAAe,QAAQ,CAAA","sourcesContent":["/**\n * LocalLlmModelManager — the on-device LLM model files: a catalog of\n * ExecuTorch exports (Software Mansion's Qwen3 .pte builds on Hugging Face),\n * their download into Documents/llm_models/<id>/, availability checks, and a\n * status stream the Settings > AI Models screen renders. Modelled on\n * STTModelManager; the download itself is RNFS so the Settings screen can\n * list, cancel, and delete models with the same calls the STT rows use.\n *\n * Which model is \"the\" on-device model is the `local_llm_model` setting\n * (Settings > AI Models). Downloads are on demand: the first request that\n * routes on-device without a model present starts one (ensureSelectedModel),\n * and the Settings screen can start one explicitly.\n */\nimport {Platform} from \"react-native\"\nimport * as RNFS from \"@dr.pogodin/react-native-fs\"\n\nimport {SETTINGS, useSettingsStore} from \"../stores/settings\"\n\nexport type LocalLlmModelId = \"qwen3-0.6b\" | \"qwen3-1.7b\" | \"qwen3-4b\"\n\nexport const DEFAULT_LOCAL_LLM_MODEL: LocalLlmModelId = \"qwen3-1.7b\"\n\nexport interface LocalLlmModelConfig {\n id: LocalLlmModelId\n /** Human label for the Settings dropdown. */\n label: string\n /** Approximate download size in bytes (the .pte dominates). */\n sizeBytes: number\n /** Rough resident memory while loaded; the Settings copy warns above ~half of device RAM. */\n ramBytes: number\n urls: {\n model: string\n tokenizer: string\n tokenizerConfig: string\n }\n}\n\n/** The three files every model directory holds; names are fixed so paths never depend on the URL. */\nexport interface LocalLlmModelPaths {\n model: string\n tokenizer: string\n tokenizerConfig: string\n}\n\nexport type LocalLlmDownloadStage = \"idle\" | \"downloading\" | \"complete\" | \"failed\"\n\nexport interface LocalLlmDownloadStatus {\n modelId: LocalLlmModelId\n stage: LocalLlmDownloadStage\n /** 0–100, meaningful while stage is \"downloading\". */\n percent: number\n error?: string\n}\n\n// XNNPACK 8da4w exports from software-mansion/react-native-executorch-qwen-3,\n// pinned to the v0.10.0 release tag that react-native-executorch 0.10.x\n// expects. Sizes are the .pte file sizes on the Hub (tokenizer adds ~11 MB).\nconst QWEN3_BASE = \"https://huggingface.co/software-mansion/react-native-executorch-qwen-3/resolve/v0.10.0\"\nconst MB = 1024 * 1024\nconst GB = 1024 * MB\n\nconst MODELS: Record<LocalLlmModelId, LocalLlmModelConfig> = {\n \"qwen3-0.6b\": {\n id: \"qwen3-0.6b\",\n label: \"Qwen3 0.6B\",\n sizeBytes: 517 * MB,\n ramBytes: 0.9 * GB,\n urls: {\n model: `${QWEN3_BASE}/0_6b/xnnpack/qwen_3_0_6b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n \"qwen3-1.7b\": {\n id: \"qwen3-1.7b\",\n label: \"Qwen3 1.7B\",\n sizeBytes: 1315 * MB,\n ramBytes: 1.8 * GB,\n urls: {\n model: `${QWEN3_BASE}/1_7b/xnnpack/qwen_3_1_7b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n \"qwen3-4b\": {\n id: \"qwen3-4b\",\n label: \"Qwen3 4B\",\n sizeBytes: 2693 * MB,\n ramBytes: 3.4 * GB,\n urls: {\n model: `${QWEN3_BASE}/4b/xnnpack/qwen_3_4b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n}\n\nexport function isLocalLlmModelId(value: unknown): value is LocalLlmModelId {\n return typeof value === \"string\" && value in MODELS\n}\n\ntype StatusListener = (status: LocalLlmDownloadStatus | null) => void\n\nclass LocalLlmModelManager {\n private static instance: LocalLlmModelManager\n\n private downloadJobId?: number\n private inFlight: {modelId: LocalLlmModelId; promise: Promise<void>} | null = null\n private cancelled = false\n private currentStatus: LocalLlmDownloadStatus | null = null\n private listeners = new Set<StatusListener>()\n private modelReadyListeners = new Set<(modelId: LocalLlmModelId) => void>()\n\n private constructor() {}\n\n static getInstance(): LocalLlmModelManager {\n if (!LocalLlmModelManager.instance) {\n LocalLlmModelManager.instance = new LocalLlmModelManager()\n }\n return LocalLlmModelManager.instance\n }\n\n models(): LocalLlmModelConfig[] {\n return Object.values(MODELS)\n }\n\n model(id: LocalLlmModelId): LocalLlmModelConfig {\n return MODELS[id]\n }\n\n /** The Settings > AI Models pick; garbage in the store resolves to the default. */\n selectedModelId(): LocalLlmModelId {\n const raw = useSettingsStore.getState().getSetting(SETTINGS.local_llm_model.key)\n return isLocalLlmModelId(raw) ? raw : DEFAULT_LOCAL_LLM_MODEL\n }\n\n async select(id: LocalLlmModelId): Promise<void> {\n await useSettingsStore.getState().setSetting(SETTINGS.local_llm_model.key, id)\n }\n\n getModelDirectory(): string {\n return `${RNFS.DocumentDirectoryPath}/llm_models`\n }\n\n paths(id: LocalLlmModelId = this.selectedModelId()): LocalLlmModelPaths {\n const dir = `${this.getModelDirectory()}/${id}`\n return {\n model: `${dir}/model.pte`,\n tokenizer: `${dir}/tokenizer.json`,\n tokenizerConfig: `${dir}/tokenizer_config.json`,\n }\n }\n\n async isModelAvailable(id: LocalLlmModelId = this.selectedModelId()): Promise<boolean> {\n const paths = this.paths(id)\n try {\n for (const path of [paths.tokenizerConfig, paths.tokenizer, paths.model]) {\n if (!(await RNFS.exists(path))) return false\n }\n // A truncated .pte loads as garbage or crashes the runtime: insist on\n // most of the published size. Downloads land in a .part file and are\n // renamed only once whole, so this only catches external tampering.\n const stat = await RNFS.stat(paths.model)\n return Number(stat.size) >= MODELS[id].sizeBytes * 0.95\n } catch (error) {\n console.warn(\"LOCAL_LLM: availability check failed:\", error)\n return false\n }\n }\n\n async downloadedModelIds(): Promise<LocalLlmModelId[]> {\n const ids: LocalLlmModelId[] = []\n for (const id of Object.keys(MODELS) as LocalLlmModelId[]) {\n if (await this.isModelAvailable(id)) ids.push(id)\n }\n return ids\n }\n\n /** Subscribe to download status changes. Fires immediately with the current status. */\n subscribe(listener: StatusListener): () => void {\n this.listeners.add(listener)\n listener(this.currentStatus)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n getStatus(): LocalLlmDownloadStatus | null {\n return this.currentStatus\n }\n\n /** Fired once a model's files are complete on disk. */\n onModelReady(listener: (modelId: LocalLlmModelId) => void): () => void {\n this.modelReadyListeners.add(listener)\n return () => this.modelReadyListeners.delete(listener)\n }\n\n /**\n * True when the selected model is on disk. Otherwise starts (or joins) its\n * download in the background and returns false — the caller reports\n * \"downloading\" rather than waiting out a multi-GB transfer.\n */\n async ensureSelectedModel(): Promise<boolean> {\n const id = this.selectedModelId()\n if (await this.isModelAvailable(id)) return true\n void this.downloadModel(id).catch((error) => {\n console.warn(`LOCAL_LLM: background download of ${id} failed:`, error)\n })\n return false\n }\n\n /**\n * Download one model (three files, model last). Concurrent calls for the\n * same model share the transfer; a call for a different model waits for\n * the running one — the RNFS job slot is singular.\n */\n async downloadModel(id: LocalLlmModelId = this.selectedModelId()): Promise<void> {\n if (this.inFlight) {\n if (this.inFlight.modelId === id) return this.inFlight.promise\n await this.inFlight.promise.catch(() => undefined)\n }\n const promise = this.downloadInner(id).finally(() => {\n this.inFlight = null\n })\n this.inFlight = {modelId: id, promise}\n return promise\n }\n\n private async downloadInner(id: LocalLlmModelId): Promise<void> {\n const config = MODELS[id]\n const paths = this.paths(id)\n const dir = `${this.getModelDirectory()}/${id}`\n this.cancelled = false\n this.setStatus({modelId: id, stage: \"downloading\", percent: 0})\n\n try {\n await RNFS.mkdir(dir, {NSURLIsExcludedFromBackupKey: true})\n // Tokenizer files first (small), the weights last: a model directory\n // is only \"available\" once model.pte exists, so an interrupted run\n // never leaves a complete-looking directory behind.\n await this.fetchFile(config.urls.tokenizerConfig, paths.tokenizerConfig)\n await this.fetchFile(config.urls.tokenizer, paths.tokenizer)\n await this.fetchFile(config.urls.model, paths.model, (percent) =>\n this.setStatus({modelId: id, stage: \"downloading\", percent}),\n )\n this.setStatus({modelId: id, stage: \"complete\", percent: 100})\n for (const listener of this.modelReadyListeners) {\n try {\n listener(id)\n } catch (error) {\n console.warn(\"LOCAL_LLM: model-ready listener failed:\", error)\n }\n }\n } catch (error) {\n const message = this.cancelled ? \"download cancelled\" : error instanceof Error ? error.message : String(error)\n this.setStatus({modelId: id, stage: this.cancelled ? \"idle\" : \"failed\", percent: 0, error: message})\n try {\n if (await RNFS.exists(`${paths.model}.part`)) await RNFS.unlink(`${paths.model}.part`)\n } catch (cleanupError) {\n console.warn(\"LOCAL_LLM: partial cleanup failed:\", cleanupError)\n }\n throw error\n } finally {\n this.downloadJobId = undefined\n }\n }\n\n private async fetchFile(url: string, dest: string, onPercent?: (percent: number) => void): Promise<void> {\n if (this.cancelled) throw new Error(\"download cancelled\")\n const partial = `${dest}.part`\n const download = RNFS.downloadFile({\n fromUrl: url,\n toFile: partial,\n // iOS keeps a background URLSession transfer going while the app is\n // suspended; the files here are large enough to need it.\n background: Platform.OS === \"ios\",\n discretionary: false,\n progressDivider: 1,\n connectionTimeout: 30_000,\n readTimeout: 60_000,\n progress: (res) => {\n if (!onPercent || res.contentLength <= 0) return\n onPercent(Math.min(99, Math.floor((res.bytesWritten / res.contentLength) * 100)))\n },\n })\n this.downloadJobId = download.jobId\n const result = await download.promise\n if (result.statusCode !== 200) {\n throw new Error(`download failed with status ${result.statusCode}`)\n }\n if (await RNFS.exists(dest)) await RNFS.unlink(dest)\n await RNFS.moveFile(partial, dest)\n }\n\n async cancelDownload(): Promise<void> {\n if (this.downloadJobId === undefined) return\n this.cancelled = true\n await RNFS.stopDownload(this.downloadJobId)\n this.downloadJobId = undefined\n }\n\n async deleteModel(id: LocalLlmModelId = this.selectedModelId()): Promise<void> {\n const dir = `${this.getModelDirectory()}/${id}`\n if (await RNFS.exists(dir)) await RNFS.unlink(dir)\n if (this.currentStatus?.modelId === id) this.setStatus(null)\n }\n\n private setStatus(status: LocalLlmDownloadStatus | null): void {\n this.currentStatus = status\n for (const listener of this.listeners) {\n try {\n listener(status)\n } catch (error) {\n console.warn(\"LOCAL_LLM: status listener threw:\", error)\n }\n }\n }\n\n static formatBytes(bytes: number): string {\n if (bytes >= GB) return `${(bytes / GB).toFixed(1)} GB`\n return `${Math.round(bytes / MB)} MB`\n }\n}\n\nconst instance = LocalLlmModelManager.getInstance()\nexport {LocalLlmModelManager}\nexport default instance\n"]}
1
+ {"version":3,"file":"LocalLlmModelManager.js","sourceRoot":"","sources":["../../src/services/LocalLlmModelManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,IAAI,MAAM,6BAA6B,CAAA;AAEnD,OAAO,EAAC,QAAQ,EAAE,gBAAgB,EAAC,MAAM,oBAAoB,CAAA;AAI7D,MAAM,CAAC,MAAM,uBAAuB,GAAoB,YAAY,CAAA;AAoCpE,8EAA8E;AAC9E,wEAAwE;AACxE,wEAAwE;AACxE,4BAA4B;AAC5B,MAAM,UAAU,GAAG,wFAAwF,CAAA;AAC3G,MAAM,eAAe,GAAG,UAAU,CAAA;AAClC,MAAM,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA;AACtB,MAAM,EAAE,GAAG,IAAI,GAAG,EAAE,CAAA;AAEpB,MAAM,MAAM,GAAiD;IAC3D,YAAY,EAAE;QACZ,EAAE,EAAE,YAAY;QAChB,KAAK,EAAE,YAAY;QACnB,SAAS,EAAE,WAAW,GAAG,eAAe;QACxC,UAAU,EAAE,WAAW;QACvB,QAAQ,EAAE,GAAG,GAAG,EAAE;QAClB,IAAI,EAAE;YACJ,KAAK,EAAE,GAAG,UAAU,6CAA6C;YACjE,SAAS,EAAE,GAAG,UAAU,iBAAiB;YACzC,eAAe,EAAE,GAAG,UAAU,wBAAwB;SACvD;KACF;IACD,YAAY,EAAE;QACZ,EAAE,EAA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AG,GAAG,IAAI,CAAC,iBAAiB,EAAE,IAAI,EAAE,EAAE,CAAA;QAC/C,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;QAClD,IAAI,IAAI,CAAC,aAAa,EAAE,OAAO,KAAK,EAAE;YAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9D,CAAC;IAEO,SAAS,CAAC,MAAqC;QACrD,IAAI,CAAC,aAAa,GAAG,MAAM,CAAA;QAC3B,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACtC,IAAI,CAAC;gBACH,QAAQ,CAAC,MAAM,CAAC,CAAA;YAClB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAA;YAC1D,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,KAAa;QAC9B,IAAI,KAAK,IAAI,EAAE;YAAE,OAAO,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAA;QACvD,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,EAAE,CAAC,KAAK,CAAA;IACvC,CAAC;CACF;AAED,MAAM,QAAQ,GAAG,oBAAoB,CAAC,WAAW,EAAE,CAAA;AACnD,OAAO,EAAC,oBAAoB,EAAC,CAAA;AAC7B,eAAe,QAAQ,CAAA","sourcesContent":["/**\n * LocalLlmModelManager — the on-device LLM model files: a catalog of\n * ExecuTorch exports (Software Mansion's Qwen3 .pte builds on Hugging Face),\n * their download into Documents/llm_models/<id>/, availability checks, and a\n * status stream the Settings > AI Models screen renders. Modelled on\n * STTModelManager; the download itself is RNFS so the Settings screen can\n * list, cancel, and delete models with the same calls the STT rows use.\n *\n * Which model is \"the\" on-device model is the `local_llm_model` setting\n * (Settings > AI Models). Downloads are on demand: the first request that\n * routes on-device without a model present starts one (ensureSelectedModel),\n * and the Settings screen can start one explicitly.\n */\nimport {Platform} from \"react-native\"\nimport * as RNFS from \"@dr.pogodin/react-native-fs\"\n\nimport {SETTINGS, useSettingsStore} from \"../stores/settings\"\n\nexport type LocalLlmModelId = \"qwen3-0.6b\" | \"qwen3-1.7b\" | \"qwen3-4b\"\n\nexport const DEFAULT_LOCAL_LLM_MODEL: LocalLlmModelId = \"qwen3-1.7b\"\n\nexport interface LocalLlmModelConfig {\n id: LocalLlmModelId\n /** Human label for the Settings dropdown. */\n label: string\n /** Total download size in bytes (the .pte dominates). */\n sizeBytes: number\n /** Exact size of the published .pte; the availability check compares against it. */\n modelBytes: number\n /** Rough resident memory while loaded; the Settings copy warns above ~half of device RAM. */\n ramBytes: number\n urls: {\n model: string\n tokenizer: string\n tokenizerConfig: string\n }\n}\n\n/** The three files every model directory holds; names are fixed so paths never depend on the URL. */\nexport interface LocalLlmModelPaths {\n model: string\n tokenizer: string\n tokenizerConfig: string\n}\n\nexport type LocalLlmDownloadStage = \"idle\" | \"downloading\" | \"complete\" | \"failed\"\n\nexport interface LocalLlmDownloadStatus {\n modelId: LocalLlmModelId\n stage: LocalLlmDownloadStage\n /** 0–100, meaningful while stage is \"downloading\". */\n percent: number\n error?: string\n}\n\n// XNNPACK 8da4w exports from software-mansion/react-native-executorch-qwen-3,\n// pinned to the v0.10.0 release tag that react-native-executorch 0.10.x\n// expects. modelBytes are the .pte sizes on the Hub; sizeBytes adds the\n// tokenizer files (~11 MB).\nconst QWEN3_BASE = \"https://huggingface.co/software-mansion/react-native-executorch-qwen-3/resolve/v0.10.0\"\nconst TOKENIZER_BYTES = 11_431_080\nconst MB = 1024 * 1024\nconst GB = 1024 * MB\n\nconst MODELS: Record<LocalLlmModelId, LocalLlmModelConfig> = {\n \"qwen3-0.6b\": {\n id: \"qwen3-0.6b\",\n label: \"Qwen3 0.6B\",\n sizeBytes: 505_686_400 + TOKENIZER_BYTES,\n modelBytes: 505_686_400,\n ramBytes: 0.9 * GB,\n urls: {\n model: `${QWEN3_BASE}/0_6b/xnnpack/qwen_3_0_6b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n \"qwen3-1.7b\": {\n id: \"qwen3-1.7b\",\n label: \"Qwen3 1.7B\",\n sizeBytes: 1_303_738_496 + TOKENIZER_BYTES,\n modelBytes: 1_303_738_496,\n ramBytes: 1.8 * GB,\n urls: {\n model: `${QWEN3_BASE}/1_7b/xnnpack/qwen_3_1_7b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n \"qwen3-4b\": {\n id: \"qwen3-4b\",\n label: \"Qwen3 4B\",\n sizeBytes: 2_681_646_976 + TOKENIZER_BYTES,\n modelBytes: 2_681_646_976,\n ramBytes: 3.4 * GB,\n urls: {\n model: `${QWEN3_BASE}/4b/xnnpack/qwen_3_4b_xnnpack_8da4w.pte`,\n tokenizer: `${QWEN3_BASE}/tokenizer.json`,\n tokenizerConfig: `${QWEN3_BASE}/tokenizer_config.json`,\n },\n },\n}\n\nexport function isLocalLlmModelId(value: unknown): value is LocalLlmModelId {\n return typeof value === \"string\" && value in MODELS\n}\n\ntype StatusListener = (status: LocalLlmDownloadStatus | null) => void\n\nclass LocalLlmModelManager {\n private static instance: LocalLlmModelManager\n\n private downloadJobId?: number\n private inFlight: {modelId: LocalLlmModelId; promise: Promise<void>} | null = null\n private cancelled = false\n private currentStatus: LocalLlmDownloadStatus | null = null\n private listeners = new Set<StatusListener>()\n private modelReadyListeners = new Set<(modelId: LocalLlmModelId) => void>()\n\n private constructor() {}\n\n static getInstance(): LocalLlmModelManager {\n if (!LocalLlmModelManager.instance) {\n LocalLlmModelManager.instance = new LocalLlmModelManager()\n }\n return LocalLlmModelManager.instance\n }\n\n models(): LocalLlmModelConfig[] {\n return Object.values(MODELS)\n }\n\n model(id: LocalLlmModelId): LocalLlmModelConfig {\n return MODELS[id]\n }\n\n /** The Settings > AI Models pick; garbage in the store resolves to the default. */\n selectedModelId(): LocalLlmModelId {\n const raw = useSettingsStore.getState().getSetting(SETTINGS.local_llm_model.key)\n return isLocalLlmModelId(raw) ? raw : DEFAULT_LOCAL_LLM_MODEL\n }\n\n async select(id: LocalLlmModelId): Promise<void> {\n await useSettingsStore.getState().setSetting(SETTINGS.local_llm_model.key, id)\n }\n\n getModelDirectory(): string {\n return `${RNFS.DocumentDirectoryPath}/llm_models`\n }\n\n paths(id: LocalLlmModelId = this.selectedModelId()): LocalLlmModelPaths {\n const dir = `${this.getModelDirectory()}/${id}`\n return {\n model: `${dir}/model.pte`,\n tokenizer: `${dir}/tokenizer.json`,\n tokenizerConfig: `${dir}/tokenizer_config.json`,\n }\n }\n\n async isModelAvailable(id: LocalLlmModelId = this.selectedModelId()): Promise<boolean> {\n const paths = this.paths(id)\n try {\n for (const path of [paths.tokenizerConfig, paths.tokenizer, paths.model]) {\n if (!(await RNFS.exists(path))) return false\n }\n // A truncated .pte loads as garbage or crashes the runtime: insist on\n // most of the published size. Downloads land in a .part file and are\n // renamed only once whole, so this only catches external tampering.\n const stat = await RNFS.stat(paths.model)\n return Number(stat.size) >= MODELS[id].modelBytes * 0.95\n } catch (error) {\n console.warn(\"LOCAL_LLM: availability check failed:\", error)\n return false\n }\n }\n\n async downloadedModelIds(): Promise<LocalLlmModelId[]> {\n const ids: LocalLlmModelId[] = []\n for (const id of Object.keys(MODELS) as LocalLlmModelId[]) {\n if (await this.isModelAvailable(id)) ids.push(id)\n }\n return ids\n }\n\n /** Subscribe to download status changes. Fires immediately with the current status. */\n subscribe(listener: StatusListener): () => void {\n this.listeners.add(listener)\n listener(this.currentStatus)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n getStatus(): LocalLlmDownloadStatus | null {\n return this.currentStatus\n }\n\n /** Fired once a model's files are complete on disk. */\n onModelReady(listener: (modelId: LocalLlmModelId) => void): () => void {\n this.modelReadyListeners.add(listener)\n return () => this.modelReadyListeners.delete(listener)\n }\n\n /**\n * True when the selected model is on disk. Otherwise starts (or joins) its\n * download in the background and returns false — the caller reports\n * \"downloading\" rather than waiting out a multi-GB transfer.\n */\n async ensureSelectedModel(): Promise<boolean> {\n const id = this.selectedModelId()\n if (await this.isModelAvailable(id)) return true\n void this.downloadModel(id).catch((error) => {\n console.warn(`LOCAL_LLM: background download of ${id} failed:`, error)\n })\n return false\n }\n\n /**\n * Download one model (three files, model last). Concurrent calls for the\n * same model share the transfer; a call for a different model waits for\n * the running one — the RNFS job slot is singular.\n */\n async downloadModel(id: LocalLlmModelId = this.selectedModelId()): Promise<void> {\n if (this.inFlight) {\n if (this.inFlight.modelId === id) return this.inFlight.promise\n await this.inFlight.promise.catch(() => undefined)\n }\n const promise = this.downloadInner(id).finally(() => {\n this.inFlight = null\n })\n this.inFlight = {modelId: id, promise}\n return promise\n }\n\n private async downloadInner(id: LocalLlmModelId): Promise<void> {\n const config = MODELS[id]\n const paths = this.paths(id)\n const dir = `${this.getModelDirectory()}/${id}`\n this.cancelled = false\n this.setStatus({modelId: id, stage: \"downloading\", percent: 0})\n\n try {\n await RNFS.mkdir(dir, {NSURLIsExcludedFromBackupKey: true})\n // Tokenizer files first (small), the weights last: a model directory\n // is only \"available\" once model.pte exists, so an interrupted run\n // never leaves a complete-looking directory behind.\n await this.fetchFile(config.urls.tokenizerConfig, paths.tokenizerConfig)\n await this.fetchFile(config.urls.tokenizer, paths.tokenizer)\n await this.fetchFile(config.urls.model, paths.model, (percent) =>\n this.setStatus({modelId: id, stage: \"downloading\", percent}),\n )\n if (!(await this.isModelAvailable(id))) {\n throw new Error(`downloaded model is smaller than the expected ${config.modelBytes} bytes`)\n }\n this.setStatus({modelId: id, stage: \"complete\", percent: 100})\n for (const listener of this.modelReadyListeners) {\n try {\n listener(id)\n } catch (error) {\n console.warn(\"LOCAL_LLM: model-ready listener failed:\", error)\n }\n }\n } catch (error) {\n const message = this.cancelled ? \"download cancelled\" : error instanceof Error ? error.message : String(error)\n this.setStatus({modelId: id, stage: this.cancelled ? \"idle\" : \"failed\", percent: 0, error: message})\n try {\n if (await RNFS.exists(`${paths.model}.part`)) await RNFS.unlink(`${paths.model}.part`)\n } catch (cleanupError) {\n console.warn(\"LOCAL_LLM: partial cleanup failed:\", cleanupError)\n }\n throw error\n } finally {\n this.downloadJobId = undefined\n }\n }\n\n private async fetchFile(url: string, dest: string, onPercent?: (percent: number) => void): Promise<void> {\n if (this.cancelled) throw new Error(\"download cancelled\")\n const partial = `${dest}.part`\n const download = RNFS.downloadFile({\n fromUrl: url,\n toFile: partial,\n // iOS keeps a background URLSession transfer going while the app is\n // suspended; the files here are large enough to need it.\n background: Platform.OS === \"ios\",\n discretionary: false,\n progressDivider: 1,\n connectionTimeout: 30_000,\n readTimeout: 60_000,\n progress: (res) => {\n if (!onPercent || res.contentLength <= 0) return\n onPercent(Math.min(99, Math.floor((res.bytesWritten / res.contentLength) * 100)))\n },\n })\n this.downloadJobId = download.jobId\n const result = await download.promise\n if (result.statusCode !== 200) {\n throw new Error(`download failed with status ${result.statusCode}`)\n }\n if (await RNFS.exists(dest)) await RNFS.unlink(dest)\n await RNFS.moveFile(partial, dest)\n }\n\n async cancelDownload(): Promise<void> {\n if (this.downloadJobId === undefined) return\n this.cancelled = true\n await RNFS.stopDownload(this.downloadJobId)\n this.downloadJobId = undefined\n }\n\n async deleteModel(id: LocalLlmModelId = this.selectedModelId()): Promise<void> {\n const dir = `${this.getModelDirectory()}/${id}`\n if (await RNFS.exists(dir)) await RNFS.unlink(dir)\n if (this.currentStatus?.modelId === id) this.setStatus(null)\n }\n\n private setStatus(status: LocalLlmDownloadStatus | null): void {\n this.currentStatus = status\n for (const listener of this.listeners) {\n try {\n listener(status)\n } catch (error) {\n console.warn(\"LOCAL_LLM: status listener threw:\", error)\n }\n }\n }\n\n static formatBytes(bytes: number): string {\n if (bytes >= GB) return `${(bytes / GB).toFixed(1)} GB`\n return `${Math.round(bytes / MB)} MB`\n }\n}\n\nconst instance = LocalLlmModelManager.getInstance()\nexport {LocalLlmModelManager}\nexport default instance\n"]}
@@ -41,17 +41,18 @@ export declare function buildTemplateMessages(request: {
41
41
  jsonMode?: boolean;
42
42
  }): TemplateMessage[];
43
43
  export declare function toTemplateTools(tools?: LlmTool[]): TemplateTool[] | undefined;
44
- export declare function estimateTokens(text: string): number;
45
- export declare function estimateMessageTokens(message: TemplateMessage): number;
44
+ export interface FittedLocalPrompt {
45
+ prompt: string;
46
+ promptTokens: number;
47
+ truncated: boolean;
48
+ }
46
49
  /**
47
- * Fit the conversation into `budgetTokens`. History is grouped into turns
48
- * (a user message plus everything up to the next user message, so a tool
49
- * round stays with the question it answers); the oldest turns go first and
50
- * the last turn is never dropped — the model must at least see the question.
51
- * When that last turn alone still does not fit, tool outputs are cut to
52
- * their head.
50
+ * Measure the complete rendered prompt with the model's tokenizer, including
51
+ * template framing, system instructions and tool schemas. Drop old turns first,
52
+ * then shorten tool results / message text in the final turn. Never cut template
53
+ * delimiters, system instructions, or structured tool calls to make them fit.
53
54
  */
54
- export declare function fitToBudget(messages: TemplateMessage[], budgetTokens: number, toolTokens?: number): TemplateMessage[];
55
+ export declare function fitPromptToContext(messages: TemplateMessage[], budgetTokens: number, render: (messages: TemplateMessage[]) => string, countTokens: (prompt: string) => Promise<number>): Promise<FittedLocalPrompt>;
55
56
  /** Remove a leading `<think>…</think>` block (or an unterminated one). */
56
57
  export declare function stripThinking(text: string): string;
57
58
  /** Pull `<tool_call>` blocks out of the reply. Unparseable blocks are dropped, not surfaced. */
@@ -1 +1 @@
1
- {"version":3,"file":"LocalLlmPrompt.d.ts","sourceRoot":"","sources":["../../src/services/LocalLlmPrompt.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAC,UAAU,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAC,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ACjC,UAAU,EAAE,eAAe,EAC3B,IAAI,EAAE;IAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,YAAY,EAAE,OAAO,CAAC;IAAC,cAAc,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;CAAC,GAC1F,eAAe,CAkBjB"}
@@ -55,32 +55,16 @@ export function toTemplateTools(tools) {
55
55
  function: { name: tool.name, description: tool.description, parameters: tool.inputSchema },
56
56
  }));
57
57
  }
58
- /** Rough tokens-per-character for a BPE vocabulary over mixed prose/JSON. */
59
- const CHARS_PER_TOKEN = 3.2;
60
- /** Template framing per message (`<|im_start|>role … <|im_end|>`). */
61
- const TOKENS_PER_MESSAGE = 6;
62
- export function estimateTokens(text) {
63
- return Math.ceil(text.length / CHARS_PER_TOKEN);
64
- }
65
- export function estimateMessageTokens(message) {
66
- let total = TOKENS_PER_MESSAGE + estimateTokens(message.content);
67
- if (message.role === "assistant" && message.tool_calls) {
68
- for (const call of message.tool_calls)
69
- total += estimateTokens(JSON.stringify(call.function)) + 8;
70
- }
71
- return total;
72
- }
73
- const MIN_TOOL_CONTENT_CHARS = 1_200;
74
58
  /**
75
- * Fit the conversation into `budgetTokens`. History is grouped into turns
76
- * (a user message plus everything up to the next user message, so a tool
77
- * round stays with the question it answers); the oldest turns go first and
78
- * the last turn is never dropped — the model must at least see the question.
79
- * When that last turn alone still does not fit, tool outputs are cut to
80
- * their head.
59
+ * Measure the complete rendered prompt with the model's tokenizer, including
60
+ * template framing, system instructions and tool schemas. Drop old turns first,
61
+ * then shorten tool results / message text in the final turn. Never cut template
62
+ * delimiters, system instructions, or structured tool calls to make them fit.
81
63
  */
82
- export function fitToBudget(messages, budgetTokens, toolTokens = 0) {
83
- const total = (list) => list.reduce((sum, m) => sum + estimateMessageTokens(m), toolTokens);
64
+ export async function fitPromptToContext(messages, budgetTokens, render, countTokens) {
65
+ if (!Number.isInteger(budgetTokens) || budgetTokens < 1) {
66
+ throw new Error("On-device model has no room for a prompt after reserving output tokens");
67
+ }
84
68
  const system = messages[0]?.role === "system" ? [messages[0]] : [];
85
69
  const turns = [];
86
70
  for (const message of messages.slice(system.length)) {
@@ -89,16 +73,43 @@ export function fitToBudget(messages, budgetTokens, toolTokens = 0) {
89
73
  else
90
74
  turns[turns.length - 1].push(message);
91
75
  }
92
- while (turns.length > 1 && total([...system, ...turns.flat()]) > budgetTokens) {
93
- turns.shift();
94
- }
95
76
  let fitted = [...system, ...turns.flat()];
96
- if (total(fitted) > budgetTokens) {
97
- fitted = fitted.map((m) => m.role === "tool" && m.content.length > MIN_TOOL_CONTENT_CHARS
98
- ? { ...m, content: `${m.content.slice(0, MIN_TOOL_CONTENT_CHARS)}\n…[truncated]` }
99
- : m);
77
+ let truncated = false;
78
+ const marker = "\n…[truncated]…\n";
79
+ while (true) {
80
+ const prompt = render(fitted);
81
+ const promptTokens = await countTokens(prompt);
82
+ if (!Number.isInteger(promptTokens) || promptTokens < 1) {
83
+ throw new Error("On-device tokenizer returned an invalid prompt token count");
84
+ }
85
+ if (promptTokens <= budgetTokens)
86
+ return { prompt, promptTokens, truncated };
87
+ truncated = true;
88
+ if (turns.length > 1) {
89
+ turns.shift();
90
+ fitted = [...system, ...turns.flat()];
91
+ continue;
92
+ }
93
+ // Preserve the user's question while tool output can still be shortened.
94
+ const candidates = fitted
95
+ .map((message, index) => ({ message, index }))
96
+ .filter(({ message }) => message.role !== "system" && Array.from(message.content).length > marker.length * 2)
97
+ .sort((a, b) => Number(b.message.role === "tool") - Number(a.message.role === "tool") ||
98
+ b.message.content.length - a.message.content.length);
99
+ const candidate = candidates[0];
100
+ if (!candidate) {
101
+ throw new Error(`On-device prompt instructions and tool definitions exceed the context budget (${promptTokens} > ${budgetTokens} tokens)`);
102
+ }
103
+ // Keep both ends of long transcripts and questions, without splitting a
104
+ // Unicode code point. Each pass shrinks strictly, then remeasures the whole
105
+ // rendered prompt; character ratios are never used as a safety check.
106
+ const chars = Array.from(candidate.message.content);
107
+ const keep = Math.floor(chars.length / 4);
108
+ fitted[candidate.index] = {
109
+ ...candidate.message,
110
+ content: `${chars.slice(0, keep).join("")}${marker}${chars.slice(-keep).join("")}`,
111
+ };
100
112
  }
101
- return fitted;
102
113
  }
103
114
  /** Remove a leading `<think>…</think>` block (or an unterminated one). */
104
115
  export function stripThinking(text) {