@h1r-ai/croche 0.0.0-stage → 0.5.1

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 (105) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +1184 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/dist/archive.d.ts +47 -0
  5. package/dist/archive.js +217 -0
  6. package/dist/atomic-replace.d.ts +18 -0
  7. package/dist/atomic-replace.js +39 -0
  8. package/dist/commands.d.ts +56 -0
  9. package/dist/commands.js +1 -0
  10. package/dist/control.d.ts +62 -0
  11. package/dist/control.js +269 -0
  12. package/dist/core-abi.d.ts +110 -0
  13. package/dist/core-abi.js +1 -0
  14. package/dist/core-bindgen.d.ts +413 -0
  15. package/dist/core-bindgen.js +1533 -0
  16. package/dist/core-runtime.d.ts +214 -0
  17. package/dist/core-runtime.js +837 -0
  18. package/dist/core-wasm-bytes.d.ts +4 -0
  19. package/dist/core-wasm-bytes.js +5 -0
  20. package/dist/core-wasm.d.ts +16 -0
  21. package/dist/core-wasm.js +63 -0
  22. package/dist/debug.d.ts +26 -0
  23. package/dist/debug.js +171 -0
  24. package/dist/file-lock.d.ts +46 -0
  25. package/dist/file-lock.js +300 -0
  26. package/dist/images.d.ts +53 -0
  27. package/dist/images.js +179 -0
  28. package/dist/index.d.ts +14 -0
  29. package/dist/index.js +9 -0
  30. package/dist/markers.d.ts +1 -0
  31. package/dist/markers.js +1 -0
  32. package/dist/node.d.ts +46 -0
  33. package/dist/node.js +281 -0
  34. package/dist/project-core.d.ts +79 -0
  35. package/dist/project-core.js +261 -0
  36. package/dist/project-session.d.ts +44 -0
  37. package/dist/project-session.js +143 -0
  38. package/dist/project-types.d.ts +97 -0
  39. package/dist/project-types.js +1 -0
  40. package/dist/project-wire.d.ts +19 -0
  41. package/dist/project-wire.js +39 -0
  42. package/dist/sse.d.ts +19 -0
  43. package/dist/sse.js +53 -0
  44. package/dist/storage.d.ts +24 -0
  45. package/dist/storage.js +32 -0
  46. package/dist/stream-branch.d.ts +47 -0
  47. package/dist/stream-branch.js +107 -0
  48. package/dist/stream-hub.d.ts +207 -0
  49. package/dist/stream-hub.js +210 -0
  50. package/dist/stream.d.ts +3 -0
  51. package/dist/stream.js +5 -0
  52. package/dist/types.d.ts +928 -0
  53. package/dist/types.js +8 -0
  54. package/dist/wiki.d.ts +15 -0
  55. package/dist/wiki.js +25 -0
  56. package/docs/CODING-AGENT.md +96 -0
  57. package/docs/DEBUGGER.md +230 -0
  58. package/docs/S2-IMPLEMENTATION.md +585 -0
  59. package/docs/SKILL.md +337 -0
  60. package/docs/skills/croche/agents/openai.yaml +4 -0
  61. package/docs/skills/croche/references/agents.md +78 -0
  62. package/docs/skills/croche/references/first-turn.md +74 -0
  63. package/docs/skills/croche/references/tools.md +43 -0
  64. package/docs/skills/croche-cli/SKILL.md +158 -0
  65. package/docs/skills/croche-cli/agents/openai.yaml +4 -0
  66. package/docs/skills/croche-cli/references/powershell.md +47 -0
  67. package/docs/skills/croche-config/SKILL.md +152 -0
  68. package/docs/skills/croche-config/agents/openai.yaml +4 -0
  69. package/docs/skills/croche-config/references/models.md +12 -0
  70. package/docs/skills/croche-platforms/SKILL.md +55 -0
  71. package/docs/skills/croche-platforms/agents/openai.yaml +4 -0
  72. package/docs/skills/croche-platforms/references/android.md +185 -0
  73. package/docs/skills/croche-platforms/references/ios.md +165 -0
  74. package/docs/skills/croche-platforms/references/react-native.md +50 -0
  75. package/docs/skills/croche-platforms/references/web-backend.md +58 -0
  76. package/docs/skills/croche-troubleshoot/SKILL.md +72 -0
  77. package/docs/skills/croche-troubleshoot/agents/openai.yaml +4 -0
  78. package/docs/skills/croche-troubleshoot/references/recovery.md +31 -0
  79. package/package.json +52 -4
  80. package/src/archive.ts +188 -0
  81. package/src/atomic-replace.ts +43 -0
  82. package/src/commands.ts +62 -0
  83. package/src/control.ts +179 -0
  84. package/src/core-abi.ts +52 -0
  85. package/src/core-bindgen.ts +1557 -0
  86. package/src/core-runtime.ts +750 -0
  87. package/src/core-wasm-bytes.ts +5 -0
  88. package/src/core-wasm.ts +57 -0
  89. package/src/debug.ts +160 -0
  90. package/src/file-lock.ts +269 -0
  91. package/src/images.ts +174 -0
  92. package/src/index.ts +15 -0
  93. package/src/markers.ts +1 -0
  94. package/src/node.ts +194 -0
  95. package/src/project-core.ts +231 -0
  96. package/src/project-session.ts +118 -0
  97. package/src/project-types.ts +77 -0
  98. package/src/project-wire.ts +39 -0
  99. package/src/sse.ts +57 -0
  100. package/src/storage.ts +30 -0
  101. package/src/stream-branch.ts +112 -0
  102. package/src/stream-hub.ts +249 -0
  103. package/src/stream.ts +7 -0
  104. package/src/types.ts +838 -0
  105. package/src/wiki.ts +25 -0
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ export class CrocheError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = 'CrocheError';
6
+ this.code = code;
7
+ }
8
+ }
package/dist/wiki.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { type WikiDocument } from './types.js';
2
+ /**
3
+ * Wiki documents from a bundler's glob of markdown files, for web apps with no file system:
4
+ *
5
+ * ```ts
6
+ * const docs = wikiFromModules(import.meta.glob('./wiki/**\/*.md', { query: '?raw', import: 'default', eager: true }), './wiki/');
7
+ * ```
8
+ *
9
+ * Keys are the bundler's module paths; `base` is cut from the front of each to make the
10
+ * document path (`./wiki/menu/stew.md` → `menu/stew.md`). Values are the markdown, or a module
11
+ * whose `default` is. Only `.md` keys under `base` are taken, in path order.
12
+ */
13
+ export declare function wikiFromModules(modules: Record<string, string | {
14
+ default: string;
15
+ }>, base?: string): WikiDocument[];
package/dist/wiki.js ADDED
@@ -0,0 +1,25 @@
1
+ import { CrocheError } from './types.js';
2
+ /**
3
+ * Wiki documents from a bundler's glob of markdown files, for web apps with no file system:
4
+ *
5
+ * ```ts
6
+ * const docs = wikiFromModules(import.meta.glob('./wiki/**\/*.md', { query: '?raw', import: 'default', eager: true }), './wiki/');
7
+ * ```
8
+ *
9
+ * Keys are the bundler's module paths; `base` is cut from the front of each to make the
10
+ * document path (`./wiki/menu/stew.md` → `menu/stew.md`). Values are the markdown, or a module
11
+ * whose `default` is. Only `.md` keys under `base` are taken, in path order.
12
+ */
13
+ export function wikiFromModules(modules, base = './wiki/') {
14
+ const prefix = base === '' || base.endsWith('/') ? base : `${base}/`;
15
+ return Object.keys(modules)
16
+ .filter(key => key.startsWith(prefix) && key.endsWith('.md'))
17
+ .sort()
18
+ .map(key => {
19
+ const value = modules[key];
20
+ const markdown = typeof value === 'string' ? value : value?.default;
21
+ if (typeof markdown !== 'string')
22
+ throw new CrocheError('invalid_wiki', `${key} is not markdown text: import it raw (query: '?raw', import: 'default').`);
23
+ return { path: key.slice(prefix.length), markdown };
24
+ });
25
+ }
@@ -0,0 +1,96 @@
1
+ # Build an app using only the public SDK
2
+
3
+ ## What the Runtime does for you, and what you should not rebuild
4
+
5
+ Croche's Runtime owns two things. Leave both to it.
6
+
7
+ 1. **Context management.** The Runtime keeps the conversation and the long-term memory, and
8
+ decides what the agent sees on each turn. Do not summarise, trim, window or re-send history
9
+ yourself, and do not put app state in `instructions`. Send the current app state with each
10
+ message as `context`.
11
+ 2. **Commands.** Every app capability is a command of a grouped tool. You describe the
12
+ commands once (`name`, a one-line `summary`, flags); the Runtime describes them to the agent
13
+ and serves `help` on demand. Write only what the AI needs to choose and call a command
14
+ correctly: what it does and when to use it. Do not document every parameter in prose, do
15
+ not register one function per capability, and do not repeat the command list in
16
+ `instructions`. Validation errors from your handler (returned, not thrown) teach the model
17
+ the details at the moment it needs them.
18
+
19
+ The Runtime already tells the agent how to act through commands. It says how to act, never
20
+ whether: when an agent acts is your app's policy. So:
21
+ - Write each command's `summary` as what it does and when to use it, including allowed values
22
+ where they are few ("Sell food or drink: stew, bread, ale, honey_cake (evenings only)").
23
+ - Keep `instructions` to the character: who they are, how they talk, what they care about.
24
+ A few short paragraphs. Every character you add is paid on every call.
25
+ - Put stable content the model must quote (a menu, a price list) in the command result, not
26
+ in `instructions`, unless the model needs it on most turns.
27
+ - `context` is optional app state, separate from the person's words. Most turns contain
28
+ only a user message. It costs tokens each time and is useful when the request needs
29
+ app state: a command or button acting on app data, or after that state changed. Images
30
+ can share the same input. Without context, an input carries only the message; earlier
31
+ states stay as sent until older turns are folded. Tools check current app data themselves.
32
+ - Mark lookups (lists, status, search) with `reads: true`: their result is the answer, so the
33
+ agent always replies after seeing it. Do not tell the agent to "speak only after the
34
+ commands".
35
+
36
+ Where guidance goes (founder, 2026-09-28): what is common to every Croche app (how to run
37
+ commands, memory) is the Runtime's; everything specific to your app is yours.
38
+ Agents may act on their own judgement by default. To keep an agent reactive ("act only when
39
+ the user asks"), say so in `toolGuide`; the real boundary is the tool set you expose and the
40
+ validation in your handlers, not prompt wording. Write `instructions`, `toolGuide` and
41
+ command summaries in English; write the persona's voice and example lines in the user's
42
+ language when that is what the user hears.
43
+
44
+
45
+ Start with the package README. The distributable coding-agent skill/plugin is
46
+ `plugins/croche` in the release checkout. Use `croche --help` for account and local
47
+ Runtime control; authenticate account requests with `CROCHE_ACCOUNT_KEY` from
48
+ Studio, never with an app public key. Do not copy Croche Chat's model loop; the app has
49
+ none. Do not call a model provider, add an orchestration framework, or read SDK internals
50
+ to connect an ordinary character app.
51
+
52
+ 1. Install `@h1r-ai/croche` from npm into the app. Supply Cloud URL
53
+ and a Studio project's public key. The project must allow anonymous enrollment
54
+ and have an account allocation and active budget.
55
+ 2. Open one `CrocheRuntime` with a durable storage adapter and personality
56
+ instructions. Keep the returned handle for the application lifecycle.
57
+ 3. Define grouped Tools with typed CLI commands and one real callback per Tool.
58
+ The Runtime describes the commands to the agent and answers help. Validate
59
+ application permissions, update authoritative app storage, and return actual
60
+ outcomes. Check the cancellation signal before side effects. Return known
61
+ rejections as JSON (for example, `{ status: 'rejected', reason: 'occupied' }`)
62
+ so the model can correct its action. Any throw after a handler starts ends the
63
+ turn because effects may be unknown; a validation-related error code does not
64
+ authorize a retry.
65
+ 4. Input message IDs provide stable identities across delivery retries. Optional `context`
66
+ supplies app state (a JSON object or text), separate from the person's words. It is useful
67
+ when the request needs app state: a command or button, or after that state changed. Without
68
+ it, an input carries only the message; earlier states stay as sent until older turns are
69
+ folded. Tools check current app data themselves.
70
+ Append `text.delta.text` by `turnId` across model rounds and replace that same
71
+ assistant row with the final `TurnResult.text`. Render nonempty text even for
72
+ failed, cancelled and interrupted results. Check `status` separately for
73
+ success indicators and application progression; do not infer success from
74
+ visible text, a marker or a tool-start event.
75
+ 5. Use `history()` to restore conversation display. Keep explicit app memories,
76
+ unlock state and UI preferences separately. A successful response with
77
+ `causedBy` identifies precisely which message completed. Startup interruption
78
+ retains saved assistant prefaces without rerunning tools or observer events;
79
+ cached input replay returns the saved result, so do not depend on deltas alone.
80
+ 6. Supply `markerGuide` and map markers to presentation; emotion is not a Tool.
81
+ Update available capabilities with `setTools`. If a hidden feature must stay
82
+ unknown to the character, omit its tool, prompt text and context while locked.
83
+ 7. On cancellation, pass an aborted signal or call `close()`. An explicit retry
84
+ after failure needs a new message ID; same-ID delivery returns the saved result.
85
+ 8. Prove a real tool action, restart restoration, failed/cancelled input behavior,
86
+ and actual operations in Studio. Clearly distinguish injected transport tests
87
+ from live model calls.
88
+
89
+ Croche chooses the model for the project. If connection/credit setup is absent, report the
90
+ concrete missing setting.
91
+ Do not fabricate successful AI results or expose a provider key to make a demo work.
92
+
93
+ The Runtime has one current user/session per handle. Multiple characters can use
94
+ different `storageKey` values and instructions; they receive independent sessions.
95
+ Local user allowance is not globally synchronized across copied
96
+ stores or devices. Cloud project/account limits remain the financial authority.
@@ -0,0 +1,230 @@
1
+ # Opt-in local diagnostics
2
+
3
+ ## Start with the advertised Runtime
4
+
5
+ For Croche Chat development, keep the current tab open and run `croche debug`.
6
+ Choose its advertised Runtime, then open the CLI's already-paired standalone
7
+ debugger server URL in a separate browser tab. The CLI starts or reuses the local
8
+ broker and bundled debugger, requests runtime capture, and filters the viewer to
9
+ that exact instance. An immediate `runtime.ready` snapshot shows current status
10
+ and tool metadata without a model call or copied token. Chat has no debugger link
11
+ or pairing screen; trace inspection and capture controls live in the external
12
+ debugger.
13
+
14
+ Chat's passive development adapter retains session reconnection, and its
15
+ same-origin relay works from the existing HTTPS tab. It keeps the broker
16
+ credential in a private server file and automatically advertises only `status`,
17
+ `debug.attach` and `debug.detach`. Event delivery uses the existing collector on
18
+ port 8790. An authenticated running collector and its captures are preserved.
19
+ Full CLI send/cancel/history/budget control remains a separate opt-in. These
20
+ routes are absent from production and preview builds.
21
+
22
+ To detach, run `croche debug disconnect --runtime-id RUNTIME_ID`. This removes
23
+ the diagnostic observer and closes its transport; the debugger server, captured
24
+ history, Runtime and active turn remain intact. Chat's Developer desk retains a
25
+ generic local discovery opt-out and separate full CLI control settings.
26
+
27
+ Other SDK apps must register an adapter; Cloud registration alone does not enable
28
+ local discovery. This guide covers the JavaScript/TypeScript SDK. Swift/Kotlin
29
+ automatic discovery and Windows automatic-relay validation are not provided by
30
+ this integration.
31
+
32
+ ## Attach another JavaScript/TypeScript app
33
+
34
+ Call this factory once for an **already open** Runtime from your development
35
+ lifecycle. It advertises diagnostics only and serializes attach/detach requests.
36
+ `auth` comes from your development host: a Node host may read its broker token
37
+ from the CLI-created private connection file; a browser supplies an explicit
38
+ server-authenticated relay adapter, never a bundled broker token.
39
+
40
+ ```ts
41
+ import type { CrocheRuntime } from '@h1r-ai/croche';
42
+ import { attachRuntimeControl } from '@h1r-ai/croche/control';
43
+ import { createLocalDebugger, type LocalDebugger } from '@h1r-ai/croche/debug';
44
+
45
+ type ControlAuth =
46
+ | { token: string; fetch?: typeof fetch }
47
+ | { relayAuthentication: true; fetch: typeof fetch };
48
+
49
+ export async function advertiseDebugger(
50
+ runtime: CrocheRuntime,
51
+ auth: ControlAuth,
52
+ options: { appName?: string; debugFetch?: typeof fetch } = {},
53
+ ) {
54
+ let transport: LocalDebugger | undefined;
55
+ let closing = false;
56
+ let pending = Promise.resolve();
57
+ function serial<T>(work: () => Promise<T>): Promise<T> {
58
+ const result = pending.then(work);
59
+ pending = result.then(() => undefined, () => undefined);
60
+ return result;
61
+ }
62
+ async function detach() {
63
+ const previous = transport;
64
+ transport = undefined;
65
+ try { runtime.setDebugObserver(); }
66
+ finally { await previous?.close(); }
67
+ return { attached: false };
68
+ }
69
+ const control = await attachRuntimeControl({
70
+ ...auth,
71
+ runtime: {
72
+ status: () => ({ ...runtime.status(), appName: options.appName ?? 'My app' }),
73
+ },
74
+ debug: {
75
+ attach: config => serial(async () => {
76
+ if (closing) throw new Error('The app is closing.');
77
+ if (config.visibility !== 'runtime') throw new Error('Full projection is unavailable in public builds.');
78
+ const next = createLocalDebugger({
79
+ url: config.url, token: config.token,
80
+ appName: options.appName ?? 'My app', fetch: options.debugFetch,
81
+ });
82
+ try {
83
+ const previous = transport;
84
+ runtime.setDebugObserver({ onDebugEvent: next.onEvent, visibility: config.visibility });
85
+ transport = next;
86
+ await previous?.close();
87
+ // setDebugObserver queued current runtime.ready synchronously.
88
+ const delivery = await next.flush();
89
+ if (delivery.lastError || delivery.dropped || delivery.sent < 1) {
90
+ throw new Error('The debugger did not acknowledge the current snapshot.');
91
+ }
92
+ return { attached: true, runtimeInstanceId: runtime.status().runtimeInstanceId };
93
+ } catch (error) {
94
+ if (transport === next) {
95
+ transport = undefined;
96
+ try { runtime.setDebugObserver(); } catch { /* Runtime may already be closed. */ }
97
+ }
98
+ await next.close();
99
+ throw error;
100
+ }
101
+ }),
102
+ detach: () => serial(detach),
103
+ },
104
+ });
105
+ return {
106
+ async close() {
107
+ closing = true;
108
+ await control.close();
109
+ await serial(detach);
110
+ },
111
+ };
112
+ }
113
+ ```
114
+
115
+ For example, a Node development host with a privately loaded `brokerToken` calls
116
+ `await advertiseDebugger(runtime, { token: brokerToken }, { appName: 'My companion' })`.
117
+ Run `croche debug`, select that app, and open the standalone server URL printed
118
+ by the CLI. The adapter needs no app pairing screen or viewer link. At shutdown,
119
+ await the returned attachment's `close()` before `runtime.close()`. Keep the
120
+ credential in the host's private configuration, never in model context, source
121
+ files or browser bundles. The CLI's paired viewer URL is also a credential;
122
+ keep it out of prompts, repository files, screenshots and public reports.
123
+
124
+ A browser relay must authenticate on its server, use a fixed loopback target,
125
+ check same-origin requests, bind each browser attachment and restrict automatic
126
+ capabilities. The SDK's `relayAuthentication: true` requires an explicit `fetch`
127
+ adapter and no `token`; it does not create such a server by itself. Chat's adapter
128
+ first calls `GET /__croche_control/connection` with `credentials: 'same-origin'` to
129
+ establish an HttpOnly session, then relays only registration, polling, results and
130
+ unregistration with that cookie. It rediscovers the connection after the dev
131
+ server restarts or an idle session expires. Diagnostic `debugFetch` is a separate
132
+ probe/event relay when HTTPS or browser local-network policy requires one.
133
+
134
+ ## Dynamic observer and visibility
135
+
136
+ `runtime.setDebugObserver({ onDebugEvent, visibility: 'runtime' })` attaches or replaces
137
+ an observer on the existing handle. `runtime.setDebugObserver()` detaches it.
138
+ Neither call recreates the Runtime, cancels work, changes history or emits a model
139
+ request. The new observer immediately receives `runtime.ready` with current
140
+ status/tools and `capture: { reason: 'observer_attached', visibility, partial,
141
+ historyReplayed: false }`. `partial` is true if work was already active. Only
142
+ future diagnostic events follow; previous requests, text, markers and effects
143
+ are not replayed. Closing the transport remains the host's responsibility.
144
+
145
+ Creation-time `RuntimeOptions.onDebugEvent` and `debugVisibility` are also
146
+ supported. With no observer, diagnostics are not collected or sent. The default
147
+ visibility is `'runtime'`: app-to-Runtime observations and provider usage
148
+ summaries. Public builds compile no full-body projection: untyped `'full'` is
149
+ refused with `invalid_configuration` naming `debugVisibility`, with or without a
150
+ debug key. Private builds explicitly enabling `internal-debug` support full
151
+ model JSON, internal instructions and returned reasoning without a key; see
152
+ [the private-build contract](../../../docs/INTERNAL-DEBUG.md). Never publish those
153
+ artifacts. Studio still withholds private entries from internal captures.
154
+
155
+ Each event contains `id`, ISO `timestamp`, `sequence`, `runtimeInstanceId`,
156
+ `sessionId`, `projectId`, `type`, and JSON `data`. It may include `turnId`,
157
+ `operationId`, and `callId`. Sequence increases within one open Runtime handle;
158
+ it may restart after reopening, while event IDs remain unique. `appName` is added
159
+ by the optional local transport. Replayed input has its original turn identity.
160
+
161
+ | Event | Data |
162
+ | --- | --- |
163
+ | `runtime.ready` | Current non-secret Runtime status and tool metadata; dynamic attachment adds capture/replay flags |
164
+ | `input.received` | `{input}` with message identity, text, kind and app context |
165
+ | `input.replayed` | `{input,result}` or `{input,pending:true}`; no repeated execution |
166
+ | `model.request` | Full: `{body}` with the exact request; default: model, output limit and counts |
167
+ | `model.response` | Full: `{body}` with the unmodified response JSON; default: model/id, usage and finish summaries |
168
+ | `model.error` | Sanitized `{error:{code,message}}` from the request path |
169
+ | `model.recovery` | Empty-response repair reason, attempt number and disabled tool exposure |
170
+ | `marker` | `{name}`, with its parent model operation |
171
+ | `tool.requested` | Name and exact JSON argument string before validation |
172
+ | `tool.started` | Name and validated arguments immediately before dispatch |
173
+ | `tool.completed` | Name and the real application result |
174
+ | `tool.failed` | Name and sanitized validation/execution error |
175
+ | `turn.completed` | The durable final `TurnResult`, including raw/text/markers/status/cost |
176
+ | `runtime.error` | Sanitized input, lifecycle or turn failure |
177
+
178
+ Model response capture happens before response validation, marker parsing and
179
+ empty-response recovery. This makes empty, truncated, marker-only and tool-bearing
180
+ responses inspectable. Full mode preserves all returned JSON fields, including
181
+ finish reason, reasoning and usage. It does not promise a provider's original
182
+ HTTP whitespace or headers. Request authentication, control-plane credentials and
183
+ provider keys are never passed to the diagnostic observer.
184
+
185
+ Diagnostic data is a copy. Mutating it cannot change messages, tool arguments,
186
+ provider responses, receipts or accounting. Synchronous exceptions and asynchronous
187
+ rejections from an observer are ignored. A synchronous host callback can still
188
+ block JavaScript's event loop; keep it short. The supplied local helper queues
189
+ snapshots immediately and does network I/O asynchronously.
190
+
191
+ ## Local collector transport
192
+
193
+ ```ts
194
+ import { createLocalDebugger } from '@h1r-ai/croche/debug';
195
+
196
+ const debug = createLocalDebugger({
197
+ url: 'http://127.0.0.1:8790', // optional
198
+ token: pairingToken, // supplied by the authorized development attachment
199
+ appName: 'My App', // optional, at most 200 characters
200
+ });
201
+ ```
202
+
203
+ `onEvent` is the callback passed to Runtime. `flush()` performs best-effort
204
+ delivery of the current queue. `close()` stops capture and settles that bounded
205
+ queue. Both return cumulative `{sent,dropped,pending,droppedByReason,lastError?}`.
206
+ Explicit flushes may send loss metadata even if no events remain. There are no
207
+ automatic retries of failed batches or provider requests.
208
+
209
+ Only loopback HTTP(S) origins are accepted. The helper POSTs `/api/events` with
210
+ `Authorization: Bearer <pairing token>`, `credentials: 'omit'`, and redirects
211
+ disabled. The body is `{events:[...]}` with optional
212
+ `dropped:{sourceId,events,reasons}`. `sourceId` is unique to this helper connection;
213
+ loss counters are cumulative, so the collector deduplicates their high-water
214
+ mark per source rather than summing reports. Pairing tokens are unrelated to
215
+ Cloud or provider authentication and are not included in event bodies.
216
+
217
+ The limits are 128 KiB per event, 100 events and 1 MiB per batch, and 500 events
218
+ or 4 MiB in the pending queue. Oversized events are dropped whole, preserving
219
+ the complete content of accepted events. A full queue discards its oldest events
220
+ and retains the recent trace. New events normally flush after 100 ms; requests
221
+ time out after two seconds. Network failures, rejected/unacknowledged events,
222
+ oversized events and queue pressure are reported as losses. A partial debugger
223
+ capture must not be treated as an authoritative execution ledger.
224
+
225
+ The collector can pause capture, inspect events and deliberately export them.
226
+ Full mode includes conversation text, app context, internal prompts and reasoning;
227
+ enable it only in a development build. Production deployments should omit the
228
+ observer. If the app has a strict `connect-src` policy, allow the chosen loopback
229
+ debugger origin in the development policy only. Browser local-network permissions
230
+ remain under the browser's control.