@buoy-gg/agent-core 7.0.40 → 7.0.42

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 (202) hide show
  1. package/lib/commonjs/blocks/receipts.js +1 -761
  2. package/lib/commonjs/blocks/runId.js +1 -31
  3. package/lib/commonjs/blocks/types.js +1 -140
  4. package/lib/commonjs/blocks/uiTool.js +6 -1405
  5. package/lib/commonjs/catalog/catalog.g.js +5 -4207
  6. package/lib/commonjs/catalog/catalog.source.json +656 -12
  7. package/lib/commonjs/catalog/catalog.types.g.js +1 -44
  8. package/lib/commonjs/catalog/normalizeParams.js +2 -332
  9. package/lib/commonjs/catalog/signature.js +1 -68
  10. package/lib/commonjs/catalog/snapshotReads.js +1 -263
  11. package/lib/commonjs/catalog/toProviderTools.js +2 -145
  12. package/lib/commonjs/catalog/validateParams.js +1 -129
  13. package/lib/commonjs/context/buildContextPack.js +1 -489
  14. package/lib/commonjs/effects/digest.js +1 -34
  15. package/lib/commonjs/effects/ledger.js +1 -325
  16. package/lib/commonjs/engine/askGate.js +1 -287
  17. package/lib/commonjs/engine/effectFor.js +1 -176
  18. package/lib/commonjs/engine/evidence.js +3 -111
  19. package/lib/commonjs/engine/historyBudget.js +1 -363
  20. package/lib/commonjs/engine/retrieve.js +1 -214
  21. package/lib/commonjs/engine/runAgentTurn.js +8 -1803
  22. package/lib/commonjs/engine/systemPrompt.js +54 -163
  23. package/lib/commonjs/engine/textToolCalls.js +1 -276
  24. package/lib/commonjs/engine/tokenCalibration.js +1 -81
  25. package/lib/commonjs/engine/verify.js +4 -297
  26. package/lib/commonjs/index.js +1 -384
  27. package/lib/commonjs/policy/labels.js +1 -319
  28. package/lib/commonjs/policy/policy.js +1 -148
  29. package/lib/commonjs/policy/redact.js +1 -172
  30. package/lib/commonjs/providers/anthropic.js +3 -445
  31. package/lib/commonjs/providers/openai.js +4 -324
  32. package/lib/commonjs/providers/problem.js +1 -98
  33. package/lib/commonjs/providers/sse.js +1 -240
  34. package/lib/commonjs/providers/streamTimer.js +1 -123
  35. package/lib/commonjs/providers/transport.js +1 -123
  36. package/lib/commonjs/providers/types.js +1 -6
  37. package/lib/commonjs/providers/xhrStream.js +1 -212
  38. package/lib/commonjs/realNow.js +1 -0
  39. package/lib/commonjs/session.js +1 -393
  40. package/lib/commonjs/types.js +0 -1
  41. package/lib/module/blocks/receipts.js +1 -755
  42. package/lib/module/blocks/runId.js +1 -26
  43. package/lib/module/blocks/types.js +1 -134
  44. package/lib/module/blocks/uiTool.js +6 -1396
  45. package/lib/module/catalog/catalog.g.js +5 -4203
  46. package/lib/module/catalog/catalog.source.json +656 -12
  47. package/lib/module/catalog/catalog.types.g.js +1 -40
  48. package/lib/module/catalog/normalizeParams.js +2 -326
  49. package/lib/module/catalog/signature.js +1 -63
  50. package/lib/module/catalog/snapshotReads.js +1 -259
  51. package/lib/module/catalog/toProviderTools.js +2 -139
  52. package/lib/module/catalog/validateParams.js +1 -124
  53. package/lib/module/context/buildContextPack.js +1 -485
  54. package/lib/module/effects/digest.js +1 -29
  55. package/lib/module/effects/ledger.js +1 -319
  56. package/lib/module/engine/askGate.js +1 -280
  57. package/lib/module/engine/effectFor.js +1 -173
  58. package/lib/module/engine/evidence.js +3 -105
  59. package/lib/module/engine/historyBudget.js +1 -355
  60. package/lib/module/engine/retrieve.js +1 -210
  61. package/lib/module/engine/runAgentTurn.js +8 -1794
  62. package/lib/module/engine/systemPrompt.js +54 -157
  63. package/lib/module/engine/textToolCalls.js +1 -270
  64. package/lib/module/engine/tokenCalibration.js +1 -75
  65. package/lib/module/engine/verify.js +4 -289
  66. package/lib/module/index.js +1 -35
  67. package/lib/module/policy/labels.js +1 -312
  68. package/lib/module/policy/policy.js +1 -142
  69. package/lib/module/policy/redact.js +1 -165
  70. package/lib/module/providers/anthropic.js +3 -441
  71. package/lib/module/providers/openai.js +4 -320
  72. package/lib/module/providers/problem.js +1 -92
  73. package/lib/module/providers/sse.js +1 -231
  74. package/lib/module/providers/streamTimer.js +1 -118
  75. package/lib/module/providers/transport.js +1 -119
  76. package/lib/module/providers/types.js +1 -4
  77. package/lib/module/providers/xhrStream.js +1 -207
  78. package/lib/module/realNow.js +1 -0
  79. package/lib/module/session.js +1 -369
  80. package/lib/module/types.js +0 -1
  81. package/lib/typescript/catalog/catalog.g.d.ts +3 -3
  82. package/lib/typescript/catalog/catalog.types.g.d.ts +7 -4
  83. package/lib/typescript/effects/ledger.d.ts +16 -1
  84. package/lib/typescript/providers/problem.d.ts +0 -20
  85. package/lib/typescript/providers/streamTimer.d.ts +0 -24
  86. package/lib/typescript/realNow.d.ts +18 -0
  87. package/lib/web/index.mjs +152 -0
  88. package/package.json +24 -3
  89. package/lib/commonjs/blocks/receipts.js.map +0 -1
  90. package/lib/commonjs/blocks/runId.js.map +0 -1
  91. package/lib/commonjs/blocks/types.js.map +0 -1
  92. package/lib/commonjs/blocks/uiTool.js.map +0 -1
  93. package/lib/commonjs/catalog/catalog.g.js.map +0 -1
  94. package/lib/commonjs/catalog/catalog.types.g.js.map +0 -1
  95. package/lib/commonjs/catalog/normalizeParams.js.map +0 -1
  96. package/lib/commonjs/catalog/signature.js.map +0 -1
  97. package/lib/commonjs/catalog/snapshotReads.js.map +0 -1
  98. package/lib/commonjs/catalog/toProviderTools.js.map +0 -1
  99. package/lib/commonjs/catalog/validateParams.js.map +0 -1
  100. package/lib/commonjs/context/buildContextPack.js.map +0 -1
  101. package/lib/commonjs/effects/digest.js.map +0 -1
  102. package/lib/commonjs/effects/ledger.js.map +0 -1
  103. package/lib/commonjs/engine/askGate.js.map +0 -1
  104. package/lib/commonjs/engine/effectFor.js.map +0 -1
  105. package/lib/commonjs/engine/evidence.js.map +0 -1
  106. package/lib/commonjs/engine/historyBudget.js.map +0 -1
  107. package/lib/commonjs/engine/retrieve.js.map +0 -1
  108. package/lib/commonjs/engine/runAgentTurn.js.map +0 -1
  109. package/lib/commonjs/engine/systemPrompt.js.map +0 -1
  110. package/lib/commonjs/engine/textToolCalls.js.map +0 -1
  111. package/lib/commonjs/engine/tokenCalibration.js.map +0 -1
  112. package/lib/commonjs/engine/verify.js.map +0 -1
  113. package/lib/commonjs/index.js.map +0 -1
  114. package/lib/commonjs/policy/labels.js.map +0 -1
  115. package/lib/commonjs/policy/policy.js.map +0 -1
  116. package/lib/commonjs/policy/redact.js.map +0 -1
  117. package/lib/commonjs/providers/anthropic.js.map +0 -1
  118. package/lib/commonjs/providers/openai.js.map +0 -1
  119. package/lib/commonjs/providers/problem.js.map +0 -1
  120. package/lib/commonjs/providers/sse.js.map +0 -1
  121. package/lib/commonjs/providers/streamTimer.js.map +0 -1
  122. package/lib/commonjs/providers/transport.js.map +0 -1
  123. package/lib/commonjs/providers/types.js.map +0 -1
  124. package/lib/commonjs/providers/xhrStream.js.map +0 -1
  125. package/lib/commonjs/session.js.map +0 -1
  126. package/lib/commonjs/types.js.map +0 -1
  127. package/lib/module/blocks/receipts.js.map +0 -1
  128. package/lib/module/blocks/runId.js.map +0 -1
  129. package/lib/module/blocks/types.js.map +0 -1
  130. package/lib/module/blocks/uiTool.js.map +0 -1
  131. package/lib/module/catalog/catalog.g.js.map +0 -1
  132. package/lib/module/catalog/catalog.types.g.js.map +0 -1
  133. package/lib/module/catalog/normalizeParams.js.map +0 -1
  134. package/lib/module/catalog/signature.js.map +0 -1
  135. package/lib/module/catalog/snapshotReads.js.map +0 -1
  136. package/lib/module/catalog/toProviderTools.js.map +0 -1
  137. package/lib/module/catalog/validateParams.js.map +0 -1
  138. package/lib/module/context/buildContextPack.js.map +0 -1
  139. package/lib/module/effects/digest.js.map +0 -1
  140. package/lib/module/effects/ledger.js.map +0 -1
  141. package/lib/module/engine/askGate.js.map +0 -1
  142. package/lib/module/engine/effectFor.js.map +0 -1
  143. package/lib/module/engine/evidence.js.map +0 -1
  144. package/lib/module/engine/historyBudget.js.map +0 -1
  145. package/lib/module/engine/retrieve.js.map +0 -1
  146. package/lib/module/engine/runAgentTurn.js.map +0 -1
  147. package/lib/module/engine/systemPrompt.js.map +0 -1
  148. package/lib/module/engine/textToolCalls.js.map +0 -1
  149. package/lib/module/engine/tokenCalibration.js.map +0 -1
  150. package/lib/module/engine/verify.js.map +0 -1
  151. package/lib/module/index.js.map +0 -1
  152. package/lib/module/policy/labels.js.map +0 -1
  153. package/lib/module/policy/policy.js.map +0 -1
  154. package/lib/module/policy/redact.js.map +0 -1
  155. package/lib/module/providers/anthropic.js.map +0 -1
  156. package/lib/module/providers/openai.js.map +0 -1
  157. package/lib/module/providers/problem.js.map +0 -1
  158. package/lib/module/providers/sse.js.map +0 -1
  159. package/lib/module/providers/streamTimer.js.map +0 -1
  160. package/lib/module/providers/transport.js.map +0 -1
  161. package/lib/module/providers/types.js.map +0 -1
  162. package/lib/module/providers/xhrStream.js.map +0 -1
  163. package/lib/module/session.js.map +0 -1
  164. package/lib/module/types.js.map +0 -1
  165. package/lib/typescript/blocks/receipts.d.ts.map +0 -1
  166. package/lib/typescript/blocks/runId.d.ts.map +0 -1
  167. package/lib/typescript/blocks/types.d.ts.map +0 -1
  168. package/lib/typescript/blocks/uiTool.d.ts.map +0 -1
  169. package/lib/typescript/catalog/catalog.g.d.ts.map +0 -1
  170. package/lib/typescript/catalog/catalog.types.g.d.ts.map +0 -1
  171. package/lib/typescript/catalog/normalizeParams.d.ts.map +0 -1
  172. package/lib/typescript/catalog/signature.d.ts.map +0 -1
  173. package/lib/typescript/catalog/snapshotReads.d.ts.map +0 -1
  174. package/lib/typescript/catalog/toProviderTools.d.ts.map +0 -1
  175. package/lib/typescript/catalog/validateParams.d.ts.map +0 -1
  176. package/lib/typescript/context/buildContextPack.d.ts.map +0 -1
  177. package/lib/typescript/effects/digest.d.ts.map +0 -1
  178. package/lib/typescript/effects/ledger.d.ts.map +0 -1
  179. package/lib/typescript/engine/askGate.d.ts.map +0 -1
  180. package/lib/typescript/engine/effectFor.d.ts.map +0 -1
  181. package/lib/typescript/engine/evidence.d.ts.map +0 -1
  182. package/lib/typescript/engine/historyBudget.d.ts.map +0 -1
  183. package/lib/typescript/engine/retrieve.d.ts.map +0 -1
  184. package/lib/typescript/engine/runAgentTurn.d.ts.map +0 -1
  185. package/lib/typescript/engine/systemPrompt.d.ts.map +0 -1
  186. package/lib/typescript/engine/textToolCalls.d.ts.map +0 -1
  187. package/lib/typescript/engine/tokenCalibration.d.ts.map +0 -1
  188. package/lib/typescript/engine/verify.d.ts.map +0 -1
  189. package/lib/typescript/index.d.ts.map +0 -1
  190. package/lib/typescript/policy/labels.d.ts.map +0 -1
  191. package/lib/typescript/policy/policy.d.ts.map +0 -1
  192. package/lib/typescript/policy/redact.d.ts.map +0 -1
  193. package/lib/typescript/providers/anthropic.d.ts.map +0 -1
  194. package/lib/typescript/providers/openai.d.ts.map +0 -1
  195. package/lib/typescript/providers/problem.d.ts.map +0 -1
  196. package/lib/typescript/providers/sse.d.ts.map +0 -1
  197. package/lib/typescript/providers/streamTimer.d.ts.map +0 -1
  198. package/lib/typescript/providers/transport.d.ts.map +0 -1
  199. package/lib/typescript/providers/types.d.ts.map +0 -1
  200. package/lib/typescript/providers/xhrStream.d.ts.map +0 -1
  201. package/lib/typescript/session.d.ts.map +0 -1
  202. package/lib/typescript/types.d.ts.map +0 -1
@@ -1,485 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * The grounding digest — "here is what this app looks like".
5
- *
6
- * Composed entirely from readers that already exist. Most Buoy adapters ship a
7
- * compact action written explicitly for a remote driver (`listQueries`,
8
- * `listStores`, `listAtoms`, `getState`, `async.getAllKeys`), and those are
9
- * exactly the right size: measured on a live idle device the whole digest is
10
- * ~5.7KB (~1.5K tokens) covering routes, env, query keys, redux slices,
11
- * zustand stores, jotai atoms, storage keys and API hosts.
12
- *
13
- * TWO HALVES, READ ON TWO SCHEDULES.
14
- *
15
- * The STABLE half (routes, slices, stores, atoms, storage keys, env names) is
16
- * read once when the chat opens and rendered inside the cached system block.
17
- * It changes rarely, and when it does the cache re-warms once.
18
- *
19
- * The LIVE half — the current route, which queries are MOUNTED right now, the
20
- * last few requests — is read again before EVERY turn and rendered as a
21
- * separate, uncached block. This exists because of one failure: asked to
22
- * "rename the Pokémon I'm looking at", the model went to an empty zustand cart
23
- * because the once-at-open digest had been built before any query was cached,
24
- * so React Query never appeared in its prompt at all. A query with
25
- * `observers > 0` IS what the screen is rendering; that fact has to be in
26
- * front of the model at the moment it decides which tool to reach for.
27
- *
28
- * What this does NOT do, and why:
29
- * - No `getSnapshot('query')`. It returns the full dehydrated cache — 8.3KB for
30
- * ten queries in that same measurement, growing with every cached payload.
31
- * `listQueries` covers the same ground in 1.8KB.
32
- * - No console. It is the fattest payload in the system at ~1.1KB per entry
33
- * with up to 1000 retained; a naive "include recent logs" is a 1MB prompt.
34
- * - No values, only shapes and keys. `includeValues`/`includeData` are
35
- * unbounded on the action path — no adapter applies a size guard — and the
36
- * whole point of the digest is to tell the model where to look, not to
37
- * pre-fetch everything it might want.
38
- */
39
-
40
- import { projectSnapshot, SNAPSHOT_ACTION } from "../catalog/snapshotReads";
41
-
42
- /** Per-probe budget. A slow tool must not hold up the first message. */
43
- const PROBE_TIMEOUT_MS = 2500;
44
- const list = value => Array.isArray(value) ? value : Array.isArray(value?.items) ? value.items : [];
45
- const rec = value => value && typeof value === "object" ? value : {};
46
- const names = (value, keys, cap = 40) => list(value).slice(0, cap).map(item => {
47
- if (!item || typeof item !== "object") return item;
48
- const rec = item;
49
- for (const k of keys) {
50
- if (rec[k] !== undefined) return rec[k];
51
- }
52
- return rec.id ?? rec.name ?? rec.key;
53
- });
54
-
55
- /**
56
- * Budgets for the store sketches above. These ride in EVERY prompt, so they are
57
- * caps first and features second: a wide store must cost a bounded number of
58
- * characters, not however many lists it happens to hold.
59
- */
60
- const DIGEST_STORE_CAP = 30;
61
- const DIGEST_STORE_KEYS = 24;
62
- const DIGEST_LISTS_PER_STORE = 8;
63
- const DIGEST_ITEM_CHARS = 240;
64
- /**
65
- * TOTAL characters of item sketches across ALL stores — the cap that actually
66
- * bounds the prompt. The per-store limits above bound one store; thirty stores
67
- * each spending their full allowance is 60,000 characters of digest, in a
68
- * block that rides in every turn. Per-item and per-store budgets are not an
69
- * output budget, so this is the one that has to hold.
70
- *
71
- * Measured: the example app's single bag store costs ~490 tokens (+2% of the
72
- * rendered prompt). This allows roughly six of those before it starts cutting.
73
- */
74
- const DIGEST_SHAPES_TOTAL_CHARS = 12_000;
75
-
76
- /** Truncate visibly — a silently cut type sketch reads as a complete one. */
77
- const clampText = (s, max) => s.length <= max ? s : `${s.slice(0, max - 1)}…`;
78
-
79
- /**
80
- * The top-level `name: type` pairs of a `shapeOf` sketch, split on commas that
81
- * are not inside a nested `{...}` or `[...]`.
82
- *
83
- * Only used to drop the store's ACTION FUNCTIONS from `keys`. A zustand store
84
- * keeps its actions alongside its state, so `Object.keys()` on the Poké Mart
85
- * bag returns ten of `addLine`, `setQty`, `removeLine`, `clearLines`… for six
86
- * real fields. Those are not state, cannot be written, and cannot be sent over
87
- * the wire — putting them in front of the model as things the store "has" is
88
- * an invitation to try. The catalog documents `keys` as plain `Object.keys()`,
89
- * so the adapter's contract stays as it is and the filtering happens here.
90
- */
91
- function topLevelFields(sketch) {
92
- const out = new Map();
93
- if (typeof sketch !== "string" || !sketch.startsWith("{")) return out;
94
- let depth = 0;
95
- let part = "";
96
- const take = () => {
97
- const i = part.indexOf(":");
98
- if (i > 0) out.set(part.slice(0, i).trim(), part.slice(i + 1).trim());
99
- part = "";
100
- };
101
- for (const ch of sketch.slice(1, -1)) {
102
- if (ch === "{" || ch === "[" || ch === "(") depth++;else if (ch === "}" || ch === "]" || ch === ")") depth--;
103
- if (ch === "," && depth === 0) take();else part += ch;
104
- }
105
- take();
106
- return out;
107
- }
108
- const STABLE_PROBES = [{
109
- // `getSitemap` was never an action — the sitemap lives in the adapter's
110
- // snapshot, so this probe could only ever have been filtered out or
111
- // thrown. Same for env below.
112
- key: "routes",
113
- toolId: "route-events",
114
- action: SNAPSHOT_ACTION,
115
- // projectSnapshot already flattened the nested route tree to paths.
116
- shape: v => list(v?.routes).slice(0, 60)
117
- }, {
118
- key: "reduxSlices",
119
- toolId: "redux",
120
- action: "getState",
121
- params: {
122
- includeValues: false
123
- },
124
- shape: v => v && typeof v === "object" ? Object.keys(v.state ?? v).slice(0, 40) : v
125
- }, {
126
- // Carries `persists to <key>` for persisted stores. That mapping is the
127
- // only way the model can tell that an innocent-looking storage key is
128
- // actually a hydrated store's saved copy — write the key directly and the
129
- // screen does not change, then the store overwrites you. `listStores`
130
- // already reports `persistName`; nothing else surfaces it.
131
- //
132
- // IT ALSO CARRIES THE ITEM SHAPE OF EVERY LIST IN THE STORE, and for a
133
- // long time it did not. `listStores` returns `keys` and `shape`
134
- // (zustandSyncAdapter.ts) — computed by shared/sync/valueShape.ts, which
135
- // exists FOR this — and this probe threw both away, so the only bag-line
136
- // shape anywhere in the prompt was a six-field one appearing incidentally
137
- // inside a React Query cache key, while the store's line has nine. Models
138
- // copied the shape they were shown and invented names for the rest
139
- // (`price` for `unitPrice`, `imageUrl` for `image`). Both a weak and a
140
- // strong model did it identically, which is what makes it ours and not
141
- // theirs.
142
- //
143
- // `unknownLists` is the honest half. An EMPTY list has no observable item
144
- // shape — not unread, unknowable — and saying so is what stops a guess
145
- // going in unremarked, because the typed-edit guard builds its template
146
- // from `list[0]` and has nothing to check against either.
147
- key: "zustandStores",
148
- toolId: "zustand",
149
- action: "listStores",
150
- // Structured, not a display string: `session` reads `persistsTo` back out
151
- // to build the owner map the engine uses at dispatch time, and the digest
152
- // is JSON-stringified into the prompt anyway, so the model loses nothing.
153
- shape: v => {
154
- // Spent across every store, not per store — see DIGEST_SHAPES_TOTAL_CHARS.
155
- let spent = 0;
156
- return list(v?.stores ?? v).slice(0, DIGEST_STORE_CAP).map(raw => {
157
- const s = raw ?? {};
158
- const name = typeof s.name === "string" ? s.name : s.id;
159
- const lists = list(s.shape?.lists).map(rec);
160
- const known = {};
161
- const unknown = [];
162
- for (const l of lists.slice(0, DIGEST_LISTS_PER_STORE)) {
163
- const path = typeof l.path === "string" ? l.path : undefined;
164
- if (!path) continue;
165
- // One level of item fields is what a write needs; `lines[].addonIds`
166
- // is already covered by its parent's item sketch.
167
- if (path.includes("[].")) continue;
168
- if (typeof l.item !== "string") {
169
- // An empty list is cheap to report and the most important thing
170
- // here, so it is never what gets cut.
171
- unknown.push(path);
172
- continue;
173
- }
174
- const item = clampText(l.item, DIGEST_ITEM_CHARS);
175
- if (spent + item.length > DIGEST_SHAPES_TOTAL_CHARS) continue;
176
- spent += item.length;
177
- known[path] = item;
178
- }
179
- return {
180
- name,
181
- ...(typeof s.persistName === "string" ? {
182
- persistsTo: s.persistName
183
- } : {}),
184
- ...(() => {
185
- if (!Array.isArray(s.keys) || !s.keys.length) return {};
186
- const fields = topLevelFields(s.shape?.shape);
187
- const stateKeys = s.keys.filter(k => fields.get(String(k)) !== "function");
188
- return stateKeys.length ? {
189
- keys: stateKeys.slice(0, DIGEST_STORE_KEYS)
190
- } : {};
191
- })(),
192
- ...(Object.keys(known).length ? {
193
- listItemShapes: known
194
- } : {}),
195
- ...(unknown.length ? {
196
- unknownLists: unknown
197
- } : {})
198
- };
199
- });
200
- }
201
- }, {
202
- key: "jotaiAtoms",
203
- toolId: "jotai",
204
- action: "listAtoms",
205
- shape: v => names(v, ["debugLabel", "label", "id"], 40)
206
- }, {
207
- key: "storageKeys",
208
- toolId: "storage",
209
- action: "async.getAllKeys",
210
- shape: v => list(v).slice(0, 60)
211
- }, {
212
- key: "env",
213
- toolId: "env",
214
- action: SNAPSHOT_ACTION,
215
- // Names only. Env values are baked into the bundle and can hold anything
216
- // the app author put in an EXPO_PUBLIC_ var, so the digest lists the keys
217
- // and leaves reading a value to an explicit ask.
218
- shape: v => {
219
- const env = v?.env;
220
- return env && typeof env === "object" ? Object.keys(env).slice(0, 40) : undefined;
221
- }
222
- }];
223
-
224
- /** Most-recent queries carried per turn. Mounted ones are sorted first. */
225
- const LIVE_QUERY_CAP = 25;
226
- /**
227
- * How many queries to ASK the adapter for, before we cap to LIVE_QUERY_CAP.
228
- *
229
- * The adapter sorts by `dataUpdatedAt` and slices to `limit`
230
- * (reactQuerySyncAdapter.ts) — so asking it for 25 and sorting mounted-first
231
- * afterwards sorts a list the screen's own query may already have fallen out
232
- * of. A detail screen whose query settled a minute ago sits behind every
233
- * background refetch since; on an app with more than 25 live queries it was
234
- * simply absent from the prompt, and `likelyScreen` then had nothing to mark.
235
- * Our demo app never has enough queries to reach the cap, which is why this
236
- * survived: it is a bug that only appears on apps bigger than the example.
237
- *
238
- * The real fix is in the adapter, which now sorts mounted-first before it
239
- * applies `limit`. This modest over-fetch is defence in depth for the readers
240
- * that do NOT — an older device on a published version, or a desktop mirror
241
- * replaying its own payload — where prioritising here is the only chance left.
242
- * 2x, not more: this rides in every turn and an unbounded scan is how a cheap
243
- * call stops being cheap.
244
- */
245
- const LIVE_QUERY_SCAN = LIVE_QUERY_CAP * 2;
246
- /** Recent requests carried per turn — enough to find the call that fed the screen. */
247
- const LIVE_REQUEST_CAP = 8;
248
- const LIVE_PROBES = [{
249
- // `{path, params}` — the params matter as much as the path: "mewtwo" in
250
- // `params.id` is what ties `/pokemon/[id]` to the `["pokemon-detail",
251
- // "mewtwo", ...]` query below.
252
- key: "currentRoute",
253
- toolId: "route-events",
254
- action: "getCurrentRoute",
255
- shape: v => {
256
- const r = rec(v);
257
- if (typeof r.path !== "string") return undefined;
258
- return r.params && Object.keys(rec(r.params)).length ? {
259
- path: r.path,
260
- params: r.params
261
- } : {
262
- path: r.path
263
- };
264
- }
265
- }, {
266
- // `observers > 0` is the one field that says "a component on screen is
267
- // rendering this right now". Everything else about a query is secondary
268
- // to that when the question is "what am I looking at".
269
- key: "queries",
270
- toolId: "query",
271
- action: "listQueries",
272
- params: {
273
- limit: LIVE_QUERY_SCAN
274
- },
275
- shape: v => {
276
- const rows = list(v?.queries ?? v).map(rec);
277
- const shaped = rows.map(q => {
278
- const observers = typeof q.observers === "number" ? q.observers : 0;
279
- return {
280
- key: q.queryKey ?? q.queryHash,
281
- status: q.status,
282
- ...(observers > 0 ? {
283
- onScreen: true,
284
- observers
285
- } : {})
286
- };
287
- });
288
- // PRIORITISE, THEN CAP — in that order. The adapter has already dropped
289
- // everything past LIVE_QUERY_SCAN by recency; this keeps the mounted
290
- // ones out of the next cut, which is the whole point of the sort.
291
- shaped.sort((a, b) => Number(Boolean(b.onScreen)) - Number(Boolean(a.onScreen)));
292
- return shaped.slice(0, LIVE_QUERY_CAP);
293
- }
294
- }, {
295
- // Whether anything is being recorded AT ALL. Network only captures while
296
- // something holds a subscription, so the request list below can be empty
297
- // or stale for a reason that has nothing to do with the app. Put in front
298
- // of the model on the first turn, it was costing several turns to
299
- // discover ("The network recorder wasn't running when you asked…").
300
- key: "networkCapture",
301
- toolId: "network",
302
- action: "getCaptureStatus",
303
- shape: v => {
304
- const s = rec(v);
305
- if (typeof s.capturing !== "boolean") return undefined;
306
- return {
307
- recording: s.capturing,
308
- ...(s.interceptorLive === false ? {
309
- interceptorLive: false
310
- } : {}),
311
- captured: typeof s.eventCount === "number" ? s.eventCount : undefined
312
- };
313
- }
314
- }, {
315
- // Newest FIRST, as the adapter stores them (the projection keeps that
316
- // order; it once took the oldest N by mistake). Carries the request `id` so a
317
- // network override seeded from the real response is one call away
318
- // (`upsertOverrideRule({ fromRequestId })`), and `overridden` so the model
319
- // never presents mocked data as live.
320
- key: "recentRequests",
321
- toolId: "network",
322
- action: SNAPSHOT_ACTION,
323
- params: {
324
- limit: LIVE_REQUEST_CAP
325
- },
326
- shape: v => list(v?.requests).map(raw => {
327
- const e = rec(raw);
328
- return {
329
- id: e.id,
330
- method: e.method,
331
- url: e.url,
332
- status: e.status,
333
- ...(e.overridden ? {
334
- overridden: true
335
- } : {})
336
- };
337
- })
338
- }, {
339
- // An armed override rule explains a response that disagrees with the
340
- // server. Without this the model would tell the user the API is broken.
341
- key: "networkOverrides",
342
- toolId: "network",
343
- action: "listOverrideRules",
344
- shape: v => {
345
- const state = rec(v);
346
- const rules = list(state.rules).map(rec).filter(r => r.enabled !== false).slice(0, 10).map(r => ({
347
- id: r.id,
348
- urlPattern: r.urlPattern,
349
- kind: r.kind,
350
- status: r.status
351
- }));
352
- if (!rules.length) return undefined;
353
- return {
354
- enabled: state.enabled === true,
355
- rules
356
- };
357
- }
358
- }];
359
- async function withTimeout(p, ms) {
360
- return await Promise.race([p.catch(() => undefined), new Promise(resolve => setTimeout(() => resolve(undefined), ms))]);
361
- }
362
- async function runProbes(probes, {
363
- dispatch,
364
- readSnapshot,
365
- availableToolIds,
366
- availableActions
367
- }) {
368
- const runnable = probes.filter(p => {
369
- if (!availableToolIds.includes(p.toolId)) return false;
370
- const actions = availableActions?.[p.toolId];
371
- return !actions || actions.includes(p.action);
372
- });
373
-
374
- // All at once — these are independent reads and the first message should not
375
- // wait on the slowest one twice over.
376
- const settled = await Promise.all(runnable.map(async probe => {
377
- const read = probe.action === SNAPSHOT_ACTION ? readSnapshot ? Promise.resolve(readSnapshot(probe.toolId)).then(payload => projectSnapshot(probe.toolId, payload, probe.params ?? {})) : Promise.resolve(undefined) : Promise.resolve(dispatch(probe.toolId, probe.action, probe.params));
378
- const value = await withTimeout(read, PROBE_TIMEOUT_MS);
379
- if (value === undefined) return [probe.key, undefined];
380
- try {
381
- return [probe.key, probe.shape(value)];
382
- } catch {
383
- return [probe.key, undefined];
384
- }
385
- }));
386
- const digest = {};
387
- for (const [key, value] of settled) {
388
- const empty = value === undefined || value === null || Array.isArray(value) && value.length === 0;
389
- if (!empty) digest[key] = value;
390
- }
391
- return digest;
392
- }
393
-
394
- /** The stable half: read once at open, rendered inside the cached prompt. */
395
- export function buildContextDigest(input) {
396
- return runProbes(STABLE_PROBES, input);
397
- }
398
-
399
- /** Lowercased string tokens from a query key array (or a hash string). */
400
- function keyTokens(key) {
401
- const parts = Array.isArray(key) ? key : typeof key === "string" ? (() => {
402
- try {
403
- const p = JSON.parse(key);
404
- return Array.isArray(p) ? p : [key];
405
- } catch {
406
- return [key];
407
- }
408
- })() : [key];
409
- return parts.flatMap(p => p === null || p === undefined ? [] : splitTokens(String(typeof p === "object" ? JSON.stringify(p) : p)));
410
- }
411
-
412
- /**
413
- * The one tokeniser. Keys and route params MUST be split identically — that
414
- * they were not is exactly how the scoring came to work only on bare words.
415
- */
416
- function splitTokens(value) {
417
- return value.toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean);
418
- }
419
-
420
- /**
421
- * Tie the mounted queries to the FOCUSED route.
422
- *
423
- * `observers > 0` means "mounted somewhere in the nav stack", NOT "on the
424
- * visible screen" — a stack navigator keeps the screen beneath the current one
425
- * mounted, so its query still reports an observer. That is the exact bug behind
426
- * "it edited a query that isn't the screen I'm on": on /pokemon/charmander both
427
- * the pokemon-detail query and a still-mounted /shop/item/charmander query look
428
- * on-screen. So score each on-screen query against the focused route's param
429
- * VALUES (weighted) and path segments, and mark the single clear winner
430
- * `likelyScreen: true`. A tie marks none — the prompt then tells the model to
431
- * reason from currentRoute rather than guess.
432
- */
433
- function annotateLikelyScreen(live) {
434
- const route = live.currentRoute;
435
- const queries = live.queries;
436
- if (!route?.path || !Array.isArray(queries)) return;
437
-
438
- // Tokenised the SAME way the keys are. They were not, and `tokens.has(value)`
439
- // could therefore never match a param containing anything but letters and
440
- // digits — every UUID, slug, date, email and composite id silently scored
441
- // zero, and only the demo app's bare `mewtwo` / `25` ever matched. A param
442
- // counts as present when every one of its tokens is in the key, so
443
- // "double-cheese-burger" matches ["menu-item","double-cheese-burger"] and
444
- // does not match ["menu","burger"].
445
- const paramTokens = Object.values(route.params ?? {}).map(v => splitTokens(String(v))).filter(t => t.length > 0);
446
- const pathSegs = splitTokens(route.path);
447
- let best = -1;
448
- let bestIdx = -1;
449
- let tie = false;
450
- queries.forEach((q, i) => {
451
- if (!q.onScreen) return;
452
- const tokens = new Set(keyTokens(q.key));
453
- // A param value present in the key is the strong signal (this is THIS id);
454
- // a shared path segment breaks ties between two screens showing that id.
455
- const paramHits = paramTokens.filter(parts => parts.every(t => tokens.has(t))).length;
456
- const pathHits = pathSegs.filter(s => tokens.has(s) || [...tokens].some(t => t.includes(s) || s.includes(t))).length;
457
- const score = paramHits * 3 + pathHits;
458
- if (score <= 0) return;
459
- if (score > best) {
460
- best = score;
461
- bestIdx = i;
462
- tie = false;
463
- } else if (score === best) {
464
- tie = true;
465
- }
466
- });
467
- if (bestIdx >= 0 && !tie) {
468
- queries[bestIdx].likelyScreen = true;
469
- // float it to the very top so a capped list always shows it
470
- const [winner] = queries.splice(bestIdx, 1);
471
- queries.unshift(winner);
472
- }
473
- }
474
-
475
- /**
476
- * The live half: read before every turn. Current route, mounted queries,
477
- * recent requests, armed overrides. Rendered as the uncached "RIGHT NOW"
478
- * block — see `buildLiveBlock` in systemPrompt.ts.
479
- */
480
- export async function buildLiveContext(input) {
481
- const live = await runProbes(LIVE_PROBES, input);
482
- annotateLikelyScreen(live);
483
- return live;
484
- }
485
- //# sourceMappingURL=buildContextPack.js.map
1
+ "use strict";import{projectSnapshot as E,SNAPSHOT_ACTION as h}from"../catalog/snapshotReads";import{realSetTimeout as T}from"../realNow";const _=2500;const d=e=>Array.isArray(e)?e:Array.isArray(e?.items)?e.items:[];const f=e=>e&&typeof e==="object"?e:{};const b=(e,t,s=40)=>d(e).slice(0,s).map(n=>{if(!n||typeof n!=="object")return n;const a=n;for(const o of t){if(a[o]!==void 0)return a[o]}return a.id??a.name??a.key});const O=30;const w=24;const v=8;const P=240;const R=12e3;const C=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}\u2026`;function L(e){const t=new Map;if(typeof e!=="string"||!e.startsWith("{"))return t;let s=0;let n="";const a=()=>{const o=n.indexOf(":");if(o>0)t.set(n.slice(0,o).trim(),n.slice(o+1).trim());n=""};for(const o of e.slice(1,-1)){if(o==="{"||o==="["||o==="(")s++;else if(o==="}"||o==="]"||o===")")s--;if(o===","&&s===0)a();else n+=o}a();return t}const j=[{key:"routes",toolId:"route-events",action:h,shape:e=>d(e?.routes).slice(0,60)},{key:"reduxSlices",toolId:"redux",action:"getState",params:{includeValues:false},shape:e=>e&&typeof e==="object"?Object.keys(e.state??e).slice(0,40):e},{key:"zustandStores",toolId:"zustand",action:"listStores",shape:e=>{let t=0;return d(e?.stores??e).slice(0,O).map(s=>{const n=s??{};const a=typeof n.name==="string"?n.name:n.id;const o=d(n.shape?.lists).map(f);const u={};const l=[];for(const r of o.slice(0,v)){const i=typeof r.path==="string"?r.path:void 0;if(!i)continue;if(i.includes("[]."))continue;if(typeof r.item!=="string"){l.push(i);continue}const c=C(r.item,P);if(t+c.length>R)continue;t+=c.length;u[i]=c}return{name:a,...typeof n.persistName==="string"?{persistsTo:n.persistName}:{},...(()=>{if(!Array.isArray(n.keys)||!n.keys.length)return{};const r=L(n.shape?.shape);const i=n.keys.filter(c=>r.get(String(c))!=="function");return i.length?{keys:i.slice(0,w)}:{}})(),...Object.keys(u).length?{listItemShapes:u}:{},...l.length?{unknownLists:l}:{}}})}},{key:"jotaiAtoms",toolId:"jotai",action:"listAtoms",shape:e=>b(e,["debugLabel","label","id"],40)},{key:"storageKeys",toolId:"storage",action:"async.getAllKeys",shape:e=>d(e).slice(0,60)},{key:"env",toolId:"env",action:h,shape:e=>{const t=e?.env;return t&&typeof t==="object"?Object.keys(t).slice(0,40):void 0}}];const k=25;const N=k*2;const x=8;const B=[{key:"currentRoute",toolId:"route-events",action:"getCurrentRoute",shape:e=>{const t=f(e);if(typeof t.path!=="string")return void 0;return t.params&&Object.keys(f(t.params)).length?{path:t.path,params:t.params}:{path:t.path}}},{key:"queries",toolId:"query",action:"listQueries",params:{limit:N},shape:e=>{const t=d(e?.queries??e).map(f);const s=t.map(n=>{const a=typeof n.observers==="number"?n.observers:0;return{key:n.queryKey??n.queryHash,status:n.status,...a>0?{onScreen:true,observers:a}:{}}});s.sort((n,a)=>Number(Boolean(a.onScreen))-Number(Boolean(n.onScreen)));return s.slice(0,k)}},{key:"networkCapture",toolId:"network",action:"getCaptureStatus",shape:e=>{const t=f(e);if(typeof t.capturing!=="boolean")return void 0;return{recording:t.capturing,...t.interceptorLive===false?{interceptorLive:false}:{},captured:typeof t.eventCount==="number"?t.eventCount:void 0}}},{key:"recentRequests",toolId:"network",action:h,params:{limit:x},shape:e=>d(e?.requests).map(t=>{const s=f(t);return{id:s.id,method:s.method,url:s.url,status:s.status,...s.overridden?{overridden:true}:{}}})},{key:"appClock",toolId:"clock",action:"getState",shape:e=>{const t=f(e);if(t.active!==true||typeof t.virtualIso!=="string")return void 0;return{appTime:t.virtualIso,mode:t.mode,...typeof t.rate==="number"&&t.rate!==1?{rate:t.rate}:{},offsetMs:t.offsetMs}}},{key:"networkOverrides",toolId:"network",action:"listOverrideRules",shape:e=>{const t=f(e);const s=d(t.rules).map(f).filter(n=>n.enabled!==false).slice(0,10).map(n=>({id:n.id,urlPattern:n.urlPattern,kind:n.kind,status:n.status}));if(!s.length)return void 0;return{enabled:t.enabled===true,rules:s}}}];async function H(e,t){return await Promise.race([e.catch(()=>void 0),new Promise(s=>T(()=>s(void 0),t))])}async function I(e,{dispatch:t,readSnapshot:s,availableToolIds:n,availableActions:a}){const o=e.filter(r=>{if(!n.includes(r.toolId))return false;const i=a?.[r.toolId];return!i||i.includes(r.action)});const u=await Promise.all(o.map(async r=>{const i=r.action===h?s?Promise.resolve(s(r.toolId)).then(S=>E(r.toolId,S,r.params??{})):Promise.resolve(void 0):Promise.resolve(t(r.toolId,r.action,r.params));const c=await H(i,_);if(c===void 0)return[r.key,void 0];try{return[r.key,r.shape(c)]}catch{return[r.key,void 0]}}));const l={};for(const[r,i]of u){const c=i===void 0||i===null||Array.isArray(i)&&i.length===0;if(!c)l[r]=i}return l}export function buildContextDigest(e){return I(j,e)}function M(e){const t=Array.isArray(e)?e:typeof e==="string"?(()=>{try{const s=JSON.parse(e);return Array.isArray(s)?s:[e]}catch{return[e]}})():[e];return t.flatMap(s=>s===null||s===void 0?[]:g(String(typeof s==="object"?JSON.stringify(s):s)))}function g(e){return e.toLowerCase().split(/[^a-z0-9]+/i).filter(Boolean)}function D(e){const t=e.currentRoute;const s=e.queries;if(!t?.path||!Array.isArray(s))return;const n=Object.values(t.params??{}).map(r=>g(String(r))).filter(r=>r.length>0);const a=g(t.path);let o=-1;let u=-1;let l=false;s.forEach((r,i)=>{if(!r.onScreen)return;const c=new Set(M(r.key));const S=n.filter(p=>p.every(m=>c.has(m))).length;const A=a.filter(p=>c.has(p)||[...c].some(m=>m.includes(p)||p.includes(m))).length;const y=S*3+A;if(y<=0)return;if(y>o){o=y;u=i;l=false}else if(y===o){l=true}});if(u>=0&&!l){s[u].likelyScreen=true;const[r]=s.splice(u,1);s.unshift(r)}}export async function buildLiveContext(e){const t=await I(B,e);D(t);return t}
@@ -1,29 +1 @@
1
- "use strict";
2
-
3
- /**
4
- * A short, stable fingerprint of any JSON-able value. Not cryptographic —
5
- * it only has to answer "is this the same as what I saw?" — and deliberately
6
- * lossy so the thing persisted beside an unanswered approval or a ledger
7
- * entry is a hash of a store's state, never the state itself.
8
- */
9
- export function digestOf(value) {
10
- let json;
11
- try {
12
- json = JSON.stringify(value) ?? "";
13
- } catch {
14
- return undefined;
15
- }
16
- let h = 5381;
17
- for (let i = 0; i < json.length; i++) h = (h << 5) + h + json.charCodeAt(i) | 0;
18
- return `${(h >>> 0).toString(16)}:${json.length}`;
19
- }
20
-
21
- /** Byte-ish size of a value once serialised; Infinity when it cannot be. */
22
- export function jsonLength(value) {
23
- try {
24
- return JSON.stringify(value)?.length ?? 0;
25
- } catch {
26
- return Number.POSITIVE_INFINITY;
27
- }
28
- }
29
- //# sourceMappingURL=digest.js.map
1
+ "use strict";export function digestOf(n){let t;try{t=JSON.stringify(n)??""}catch{return void 0}let e=5381;for(let r=0;r<t.length;r++)e=(e<<5)+e+t.charCodeAt(r)|0;return`${(e>>>0).toString(16)}:${t.length}`}export function jsonLength(n){try{return JSON.stringify(n)?.length??0}catch{return Number.POSITIVE_INFINITY}}