@llmguard/opencode 0.0.0-stage → 0.1.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 (77) hide show
  1. package/README.md +53 -2
  2. package/bin/darwin-amd64/helper +0 -0
  3. package/bin/darwin-arm64/helper +0 -0
  4. package/bin/linux-amd64/helper +0 -0
  5. package/bin/linux-arm64/helper +0 -0
  6. package/bin/manifest.json +51 -0
  7. package/bin/windows-amd64/helper.exe +0 -0
  8. package/bin/windows-arm64/helper.exe +0 -0
  9. package/bridge/client.d.ts +55 -0
  10. package/bridge/client.js +425 -0
  11. package/bridge/framing.d.ts +19 -0
  12. package/bridge/framing.js +110 -0
  13. package/bridge/process.d.ts +38 -0
  14. package/bridge/process.js +378 -0
  15. package/bridge/protocol.d.ts +184 -0
  16. package/bridge/protocol.js +683 -0
  17. package/connection-catalog.d.ts +69 -0
  18. package/connection-catalog.js +287 -0
  19. package/connections-tui.d.ts +11 -0
  20. package/connections-tui.js +394 -0
  21. package/demasking.d.ts +2 -0
  22. package/demasking.js +445 -0
  23. package/gui-experimental.cjs +33 -0
  24. package/hook-trace.d.ts +2 -0
  25. package/hook-trace.js +35 -0
  26. package/index.d.ts +1 -0
  27. package/index.js +1 -0
  28. package/licenses/Go-LICENSE +27 -0
  29. package/messages.d.ts +230 -0
  30. package/messages.js +231 -0
  31. package/native/index.d.ts +1 -0
  32. package/native/index.js +1 -0
  33. package/native/tui.d.ts +1 -0
  34. package/native/tui.js +1 -0
  35. package/package.json +47 -4
  36. package/plugin-runtime.d.ts +3 -0
  37. package/plugin-runtime.js +3 -0
  38. package/plugin-settings.d.ts +77 -0
  39. package/plugin-settings.js +487 -0
  40. package/plugin.d.ts +41 -0
  41. package/plugin.js +10 -0
  42. package/response-diagnostics.d.ts +13 -0
  43. package/response-diagnostics.js +142 -0
  44. package/runtime/attachments.d.ts +4 -0
  45. package/runtime/attachments.js +19 -0
  46. package/runtime/errors.d.ts +18 -0
  47. package/runtime/errors.js +26 -0
  48. package/runtime/json.d.ts +14 -0
  49. package/runtime/json.js +243 -0
  50. package/runtime/limits.d.ts +2 -0
  51. package/runtime/limits.js +3 -0
  52. package/runtime/native-edit.d.ts +14 -0
  53. package/runtime/native-edit.js +73 -0
  54. package/runtime/runtime.d.ts +43 -0
  55. package/runtime/runtime.js +345 -0
  56. package/runtime/session-state.d.ts +13 -0
  57. package/runtime/session-state.js +73 -0
  58. package/runtime/text-layout.d.ts +9 -0
  59. package/runtime/text-layout.js +47 -0
  60. package/server.d.ts +1 -0
  61. package/server.js +1 -0
  62. package/settings-rpc.d.ts +511 -0
  63. package/settings-rpc.js +197 -0
  64. package/tui-messages.d.ts +1 -0
  65. package/tui-messages.js +84 -0
  66. package/tui.d.ts +17 -0
  67. package/tui.js +427 -0
  68. package/v1/hooks.d.ts +81 -0
  69. package/v1/hooks.js +97 -0
  70. package/v1/projection.d.ts +32 -0
  71. package/v1/projection.js +217 -0
  72. package/v1.d.ts +2 -0
  73. package/v1.js +2 -0
  74. package/v2/projection.d.ts +36 -0
  75. package/v2/projection.js +374 -0
  76. package/v2/server.d.ts +6 -0
  77. package/v2/server.js +633 -0
@@ -0,0 +1,487 @@
1
+ import { ConnectionCatalog, } from "./connection-catalog.js";
2
+ import { BridgeClient } from "./bridge/client.js";
3
+ import { ProtocolError } from "./bridge/protocol.js";
4
+ import { createOpenCodeRuntime, DEFAULT_GUARD_TIMEOUT_MS, } from "./runtime/runtime.js";
5
+ import { OpenCodeGuardError } from "./runtime/errors.js";
6
+ export class SettingsError extends Error {
7
+ constructor() {
8
+ super("LLMGuard: invalid or unavailable settings");
9
+ }
10
+ }
11
+ // Shape validation is local; connection and bearer-token policy belongs to Go.
12
+ const profileShape = (value, restore = false) => {
13
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
14
+ throw new SettingsError();
15
+ }
16
+ const p = value;
17
+ if (Object.keys(p).some((key) => ![
18
+ "baseURL",
19
+ "projectSID",
20
+ "allowLoopbackHTTP",
21
+ ...(restore ? ["connectionID", "token"] : []),
22
+ ].includes(key)) ||
23
+ (p.connectionID !== undefined &&
24
+ (typeof p.connectionID !== "string" ||
25
+ !/^[a-zA-Z0-9-]{1,64}$/.test(p.connectionID))) ||
26
+ (p.token !== undefined && typeof p.token !== "string") ||
27
+ typeof p.baseURL !== "string" ||
28
+ typeof p.projectSID !== "string" ||
29
+ typeof p.allowLoopbackHTTP !== "boolean") {
30
+ throw new SettingsError();
31
+ }
32
+ return {
33
+ baseURL: p.baseURL,
34
+ projectSID: p.projectSID,
35
+ allowLoopbackHTTP: p.allowLoopbackHTTP,
36
+ };
37
+ };
38
+ const emptyProfile = () => ({
39
+ baseURL: "",
40
+ projectSID: "",
41
+ allowLoopbackHTTP: false,
42
+ });
43
+ function params(options) {
44
+ return {
45
+ origin: options.baseURL,
46
+ project_sid: options.projectSID,
47
+ token: options.token,
48
+ allow_loopback_http: options.allowLoopbackHTTP ?? false,
49
+ timeout_ms: options.timeoutMs ?? DEFAULT_GUARD_TIMEOUT_MS,
50
+ };
51
+ }
52
+ const filesView = (policy) => ({
53
+ inspect: policy.inspect,
54
+ allowUninspectable: policy.allow_uninspectable,
55
+ source: policy.source,
56
+ damaged: policy.damaged,
57
+ });
58
+ export class PluginSettings {
59
+ store;
60
+ cwd;
61
+ connections;
62
+ #generation = 0;
63
+ #activeConnectionID;
64
+ #profile = emptyProfile();
65
+ #display = emptyProfile();
66
+ #runtimes = new Map();
67
+ #disposed = false;
68
+ #pending = 0;
69
+ #stopVersion = 0;
70
+ #enabled = false;
71
+ #configured = false;
72
+ #configuration = Promise.resolve();
73
+ #tail = Promise.resolve();
74
+ #tokenOverride;
75
+ #bridge = new BridgeClient();
76
+ #environment;
77
+ constructor(store, cwd, environment) {
78
+ this.store = store;
79
+ this.cwd = cwd;
80
+ this.connections = new ConnectionCatalog({
81
+ read: () => this.store.get("connections"),
82
+ write: (value) => this.store.set("connections", value),
83
+ current: () => ({
84
+ ...this.#connection(),
85
+ ...(this.#activeConnectionID && !this.#overridden()
86
+ ? { connectionID: this.#activeConnectionID }
87
+ : {}),
88
+ allowLoopbackHTTP: this.#connection().allowLoopbackHTTP ?? false,
89
+ }),
90
+ status: () => this.status(),
91
+ generation: () => this.#generation,
92
+ validate: (profile, token) => this.#valid({ ...profile, token }),
93
+ probe: async (profile, token, signal) => {
94
+ const bridge = new BridgeClient();
95
+ try {
96
+ const options = {
97
+ ...profile,
98
+ token,
99
+ ...(this.#connection().timeoutMs === undefined
100
+ ? {}
101
+ : { timeoutMs: this.#connection().timeoutMs }),
102
+ };
103
+ await bridge.configure(params(options));
104
+ const result = await bridge.test({
105
+ ...(signal ? { signal } : {}),
106
+ deadline: performance.now() +
107
+ (options.timeoutMs ?? DEFAULT_GUARD_TIMEOUT_MS) +
108
+ 250,
109
+ });
110
+ return {
111
+ connected: result.connected,
112
+ code: result.check_code,
113
+ decision: result.decision,
114
+ };
115
+ }
116
+ finally {
117
+ await bridge.dispose();
118
+ }
119
+ },
120
+ apply: (profile, token, generation) => {
121
+ if (this.#generation !== generation || this.#overridden()) {
122
+ return Promise.reject(new SettingsError());
123
+ }
124
+ const stopVersion = this.#stopVersion;
125
+ return this.#mutate(async () => {
126
+ const saved = {
127
+ baseURL: profile.baseURL,
128
+ projectSID: profile.projectSID,
129
+ allowLoopbackHTTP: profile.allowLoopbackHTTP,
130
+ };
131
+ await this.store.set("connection", {
132
+ ...saved,
133
+ connectionID: profile.id,
134
+ token,
135
+ });
136
+ if (this.#disposed) {
137
+ throw new SettingsError();
138
+ }
139
+ this.#profile = saved;
140
+ this.#activeConnectionID = profile.id;
141
+ this.#tokenOverride = token;
142
+ await this.#refresh();
143
+ if (!this.#configured ||
144
+ this.#disposed ||
145
+ stopVersion !== this.#stopVersion) {
146
+ throw new SettingsError();
147
+ }
148
+ await this.store.set("enabled", true);
149
+ if (!this.#disposed && stopVersion === this.#stopVersion) {
150
+ this.#enabled = true;
151
+ }
152
+ });
153
+ },
154
+ });
155
+ this.#environment = Object.fromEntries([
156
+ "LLMGUARD_BASE_URL",
157
+ "LLMGUARD_PROJECT_SID",
158
+ "LLMGUARD_ALLOW_LOOPBACK_HTTP",
159
+ "LLMGUARD_TOKEN",
160
+ "LLMGUARD_API_KEY",
161
+ "LLMGUARD_TIMEOUT_MS",
162
+ ].map((key) => [key, environment[key]]));
163
+ }
164
+ #retire() {
165
+ // dispose clears state synchronously; a shared runtime does not own helper lifetime.
166
+ for (const runtime of this.#runtimes.values()) {
167
+ void runtime.dispose();
168
+ }
169
+ this.#runtimes.clear();
170
+ }
171
+ #mutate(action) {
172
+ this.#generation++;
173
+ this.#retire();
174
+ this.#pending++;
175
+ const result = this.#tail
176
+ .then(async () => {
177
+ if (this.#disposed) {
178
+ throw new SettingsError();
179
+ }
180
+ return action();
181
+ })
182
+ .catch(() => {
183
+ throw new SettingsError();
184
+ });
185
+ const settled = result.finally(() => {
186
+ this.#pending--;
187
+ });
188
+ this.#tail = settled.catch(() => { });
189
+ return settled;
190
+ }
191
+ async #valid(options) {
192
+ try {
193
+ return (await this.#bridge.validate(params(options))).valid;
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ }
199
+ async #refresh() {
200
+ this.#retire();
201
+ this.#configured = false;
202
+ this.#display = emptyProfile();
203
+ const connection = this.#connection();
204
+ const valid = await this.#valid({ ...connection, token: "validation" });
205
+ if (this.#disposed) {
206
+ return;
207
+ }
208
+ if (valid) {
209
+ this.#display = {
210
+ baseURL: connection.baseURL,
211
+ projectSID: connection.projectSID,
212
+ allowLoopbackHTTP: connection.allowLoopbackHTTP ?? false,
213
+ };
214
+ }
215
+ if (this.#disposed || !connection.token) {
216
+ return;
217
+ }
218
+ this.#configuration = this.#bridge.configure(params(connection));
219
+ try {
220
+ await this.#configuration;
221
+ if (!this.#disposed) {
222
+ this.#configured = true;
223
+ }
224
+ }
225
+ catch {
226
+ /* Never disable protection because a helper/configuration failed. */
227
+ }
228
+ }
229
+ async load() {
230
+ return this.#mutate(async () => {
231
+ const enabled = (await this.store.get("enabled")) === true;
232
+ const saved = await this.store.get("connection");
233
+ if (this.#disposed) {
234
+ throw new SettingsError();
235
+ }
236
+ this.#enabled = enabled;
237
+ try {
238
+ if (saved !== undefined) {
239
+ this.#profile = profileShape(saved, true);
240
+ this.#tokenOverride = saved.token;
241
+ this.#activeConnectionID = saved.connectionID;
242
+ }
243
+ }
244
+ catch {
245
+ /* Invalid saved shape can be repaired through TUI. */
246
+ }
247
+ await this.#refresh();
248
+ });
249
+ }
250
+ #overridden() {
251
+ return !!(this.#environment.LLMGUARD_BASE_URL ||
252
+ this.#environment.LLMGUARD_PROJECT_SID);
253
+ }
254
+ #connection() {
255
+ // Slow Guard deployments can opt in to a longer timeout.
256
+ const timeoutRaw = this.#environment.LLMGUARD_TIMEOUT_MS;
257
+ const timeoutValue = typeof timeoutRaw === "string" &&
258
+ /^\d+$/.test(timeoutRaw) &&
259
+ Number(timeoutRaw) > 0 &&
260
+ Number(timeoutRaw) <= 180_000
261
+ ? Number(timeoutRaw)
262
+ : undefined;
263
+ return {
264
+ ...(this.#overridden()
265
+ ? {
266
+ baseURL: this.#environment.LLMGUARD_BASE_URL ?? "",
267
+ projectSID: this.#environment.LLMGUARD_PROJECT_SID ?? "",
268
+ allowLoopbackHTTP: this.#environment.LLMGUARD_ALLOW_LOOPBACK_HTTP === "true" ||
269
+ this.#environment.LLMGUARD_ALLOW_LOOPBACK_HTTP === "1",
270
+ }
271
+ : this.#profile),
272
+ token: this.#tokenOverride ??
273
+ this.#environment.LLMGUARD_TOKEN ??
274
+ this.#environment.LLMGUARD_API_KEY ??
275
+ "",
276
+ ...(timeoutValue === undefined ? {} : { timeoutMs: timeoutValue }),
277
+ };
278
+ }
279
+ gatewayConnection() {
280
+ if (!this.enforcing() || !this.#configured || this.#pending) {
281
+ throw new OpenCodeGuardError("not_configured");
282
+ }
283
+ return this.#connection();
284
+ }
285
+ status() {
286
+ const { token } = this.#connection();
287
+ return {
288
+ ...this.#display,
289
+ configured: this.#configured && !this.#disposed,
290
+ enabled: this.enforcing(),
291
+ tokenPresent: !!token,
292
+ environmentOverride: this.#overridden(),
293
+ tokenSource: this.#tokenOverride !== undefined
294
+ ? "session"
295
+ : token
296
+ ? "environment"
297
+ : "missing",
298
+ };
299
+ }
300
+ save(input) {
301
+ return this.#mutate(async () => {
302
+ if (this.#overridden()) {
303
+ throw new SettingsError();
304
+ }
305
+ const profile = profileShape(input);
306
+ if (!(await this.#valid({ ...profile, token: "validation" }))) {
307
+ throw new SettingsError();
308
+ }
309
+ if (this.#disposed) {
310
+ throw new SettingsError();
311
+ }
312
+ await this.store.set("connection", this.#tokenOverride !== undefined
313
+ ? { ...profile, token: this.#tokenOverride }
314
+ : profile);
315
+ if (this.#disposed) {
316
+ throw new SettingsError();
317
+ }
318
+ this.#profile = profile;
319
+ this.#activeConnectionID = undefined;
320
+ await this.#refresh();
321
+ return this.status();
322
+ });
323
+ }
324
+ setKey(input) {
325
+ return this.#mutate(async () => {
326
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
327
+ throw new SettingsError();
328
+ }
329
+ const value = input;
330
+ if (Object.keys(value).join(",") !== "token" ||
331
+ typeof value.token !== "string") {
332
+ throw new SettingsError();
333
+ }
334
+ const token = value.token;
335
+ // Validate just the key even before a connection is configured, without HTTP.
336
+ if (!(await this.#valid({
337
+ baseURL: "https://validation.invalid",
338
+ projectSID: "00000000-0000-0000-0000-000000000001",
339
+ token,
340
+ }))) {
341
+ throw new SettingsError();
342
+ }
343
+ if (this.#disposed) {
344
+ throw new SettingsError();
345
+ }
346
+ await this.store.set("connection", {
347
+ ...(this.#profile ?? emptyProfile()),
348
+ ...(this.#activeConnectionID
349
+ ? { connectionID: this.#activeConnectionID }
350
+ : {}),
351
+ token,
352
+ });
353
+ if (this.#disposed) {
354
+ throw new SettingsError();
355
+ }
356
+ this.#tokenOverride = token;
357
+ await this.#refresh();
358
+ return this.status();
359
+ });
360
+ }
361
+ enforcing() {
362
+ return this.#enabled && !this.#disposed;
363
+ }
364
+ setEnabled(input) {
365
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
366
+ return Promise.reject(new SettingsError());
367
+ }
368
+ const value = input;
369
+ if (Object.keys(value).join(",") !== "enabled" ||
370
+ typeof value.enabled !== "boolean") {
371
+ return Promise.reject(new SettingsError());
372
+ }
373
+ const enabled = value.enabled;
374
+ // Explicit stop takes effect before storage or queued configuration can await.
375
+ if (!enabled) {
376
+ this.#enabled = false;
377
+ this.#stopVersion++;
378
+ }
379
+ const stopVersion = this.#stopVersion;
380
+ return this.#mutate(async () => {
381
+ if (enabled && !this.status().configured) {
382
+ throw new SettingsError();
383
+ }
384
+ await this.store.set("enabled", enabled);
385
+ if (!this.#disposed && stopVersion === this.#stopVersion) {
386
+ this.#enabled = enabled;
387
+ }
388
+ return this.status();
389
+ });
390
+ }
391
+ // The attachment policy lives in the helper (a private file and the
392
+ // environment). These only read and store it; nothing here interprets it.
393
+ async files(signal) {
394
+ return filesView(await this.#bridge.attachmentsPolicy({
395
+ ...(signal ? { signal } : {}),
396
+ deadline: performance.now() + 5000,
397
+ }));
398
+ }
399
+ async setFiles(input, signal) {
400
+ const value = input && typeof input === "object" && !Array.isArray(input)
401
+ ? input
402
+ : undefined;
403
+ if (!value ||
404
+ Object.keys(value).sort().join(",") !== "allowUninspectable,inspect" ||
405
+ typeof value.inspect !== "boolean" ||
406
+ typeof value.allowUninspectable !== "boolean") {
407
+ throw new SettingsError();
408
+ }
409
+ try {
410
+ return filesView(await this.#bridge.configureAttachments({
411
+ file_inspection: value.inspect ? "inspect" : "off",
412
+ uninspectable_files: value.allowUninspectable ? "allow" : "block",
413
+ }, {
414
+ ...(signal ? { signal } : {}),
415
+ deadline: performance.now() + 5000,
416
+ }));
417
+ }
418
+ catch (error) {
419
+ // An environment override (or no way to store) is a refusal, not a crash.
420
+ if (error instanceof ProtocolError && error.code === "invalid_state") {
421
+ throw new SettingsError();
422
+ }
423
+ throw error;
424
+ }
425
+ }
426
+ runtime(cwd = this.cwd) {
427
+ if (this.#disposed) {
428
+ throw new OpenCodeGuardError("disposed");
429
+ }
430
+ if (this.#pending) {
431
+ throw new OpenCodeGuardError("configuration_pending");
432
+ }
433
+ if (!this.#configured) {
434
+ throw new OpenCodeGuardError("not_configured");
435
+ }
436
+ let runtime = this.#runtimes.get(cwd);
437
+ if (!runtime) {
438
+ runtime = createOpenCodeRuntime({ ...this.#connection(), cwd }, this.#bridge, { configured: this.#configuration });
439
+ this.#runtimes.set(cwd, runtime);
440
+ }
441
+ return runtime;
442
+ }
443
+ async releaseRuntime(cwd) {
444
+ const runtime = this.#runtimes.get(cwd);
445
+ this.#runtimes.delete(cwd);
446
+ await runtime?.dispose();
447
+ }
448
+ async test(signal) {
449
+ if (this.#disposed || this.#pending || !this.#configured) {
450
+ return { connected: false, code: "unavailable", decision: null };
451
+ }
452
+ const deadline = performance.now() +
453
+ (this.#connection().timeoutMs ?? DEFAULT_GUARD_TIMEOUT_MS) +
454
+ 250;
455
+ try {
456
+ await this.#configuration;
457
+ const result = await this.#bridge.test({
458
+ ...(signal ? { signal } : {}),
459
+ deadline,
460
+ });
461
+ return {
462
+ connected: result.connected,
463
+ code: result.check_code,
464
+ decision: result.decision,
465
+ };
466
+ }
467
+ catch (error) {
468
+ return {
469
+ connected: false,
470
+ code: error instanceof ProtocolError ? error.code : "unavailable",
471
+ decision: null,
472
+ };
473
+ }
474
+ }
475
+ async forgetSession(id, cwd = this.cwd) {
476
+ await this.#runtimes.get(cwd)?.forgetSession(id);
477
+ }
478
+ async dispose() {
479
+ this.#disposed = true;
480
+ this.connections.dispose();
481
+ this.#enabled = false;
482
+ this.#configured = false;
483
+ this.#tokenOverride = undefined;
484
+ this.#retire();
485
+ await this.#bridge.dispose();
486
+ }
487
+ }
package/plugin.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ export default function LLMGuardPlugin(context: {
2
+ directory: string;
3
+ }): Promise<{
4
+ checkModelTexts: (name: string, texts: string[], session: string | null, sourcePayload?: Record<string, import("./runtime/json.js").JsonValue>) => Promise<string[]>;
5
+ "experimental.chat.messages.transform": (_input: object, output: {
6
+ messages: import("./v1/projection.js").Message[];
7
+ }) => Promise<void>;
8
+ "experimental.chat.system.transform": (input: {
9
+ sessionID?: string;
10
+ }, output: {
11
+ system: string[];
12
+ }) => Promise<void>;
13
+ "tool.execute.before": (input: import("./runtime/runtime.js").ToolInput, output: {
14
+ args: unknown;
15
+ }) => Promise<undefined>;
16
+ "tool.execute.after": (input: import("./runtime/runtime.js").ToolInput, output: {
17
+ output: string;
18
+ title: string;
19
+ metadata: unknown;
20
+ }) => Promise<void>;
21
+ "experimental.text.complete": (input: {
22
+ sessionID: string;
23
+ }, output: {
24
+ text: string;
25
+ }) => Promise<void>;
26
+ hasRestoration: (session: string) => boolean;
27
+ restoreText: (session: string, text: string) => string;
28
+ observeToolAfter: (tool: import("./runtime/runtime.js").ToolInput, output: string) => Promise<void>;
29
+ demaskResponse: (session: string | null, response: Response, trace?: (reason: string) => void) => Promise<Response>;
30
+ event: ({ event, }: {
31
+ event: {
32
+ type: string;
33
+ properties?: {
34
+ info?: {
35
+ id?: string;
36
+ };
37
+ };
38
+ };
39
+ }) => Promise<void>;
40
+ dispose: () => Promise<void>;
41
+ }>;
package/plugin.js ADDED
@@ -0,0 +1,10 @@
1
+ import { createOpenCodeHooks } from "./plugin-runtime.js";
2
+ // Keep a single function export: OpenCode invokes all module exports.
3
+ export default async function LLMGuardPlugin(context) {
4
+ return createOpenCodeHooks({
5
+ baseURL: process.env.LLMGUARD_BASE_URL ?? "",
6
+ projectSID: process.env.LLMGUARD_PROJECT_SID ?? "",
7
+ token: process.env.LLMGUARD_TOKEN ?? "",
8
+ cwd: context.directory,
9
+ });
10
+ }
@@ -0,0 +1,13 @@
1
+ export declare function createResponseDiagnostics(): {
2
+ json: (source: string) => void;
3
+ frame: (wire: string) => void;
4
+ report(other: {
5
+ has(key: string): boolean;
6
+ complete(): boolean;
7
+ fields(): number;
8
+ }, trace: (reason: string) => void): void;
9
+ has: (key: string) => boolean;
10
+ complete: () => boolean;
11
+ fields: () => number;
12
+ ended: () => boolean;
13
+ };
@@ -0,0 +1,142 @@
1
+ import { parseLossless } from "./runtime/json.js";
2
+ const encoder = new TextEncoder();
3
+ const signatures = {
4
+ system_reminder: "<system-reminder",
5
+ message: "<message>",
6
+ conversation: "<conversation>",
7
+ title_instruction: "reply with only the title",
8
+ };
9
+ const tailLength = Math.max(...Object.values(signatures).map((s) => s.length)) - 1;
10
+ const object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
11
+ // Observe only decoded provider text fields. Keep bounded transient suffixes
12
+ // for signatures split across deltas; diagnostics expose booleans only, never
13
+ // suffixes, text, masking tokens, session IDs or provider metadata.
14
+ export function createResponseDiagnostics() {
15
+ const tails = new Map();
16
+ const seen = new Set();
17
+ let incomplete = false;
18
+ let observedFields = 0;
19
+ let ended = false;
20
+ const text = (channel, key, value, delta = false) => {
21
+ if (typeof value !== "string") {
22
+ return;
23
+ }
24
+ observedFields++;
25
+ const joined = ((delta ? (tails.get(key) ?? "") : "") + value).toLowerCase();
26
+ for (const [name, signature] of Object.entries(signatures)) {
27
+ if (joined.includes(signature)) {
28
+ seen.add(`${channel}.${name}`);
29
+ }
30
+ }
31
+ if (delta) {
32
+ if (tails.size >= 4096 && !tails.has(key)) {
33
+ incomplete = true;
34
+ return;
35
+ }
36
+ tails.set(key, joined.slice(-tailLength));
37
+ }
38
+ };
39
+ const identity = (value) => JSON.stringify(value ?? null);
40
+ const json = (source) => {
41
+ let root;
42
+ try {
43
+ root = parseLossless(encoder.encode(source.replace(/^\uFEFF/, "")));
44
+ }
45
+ catch {
46
+ incomplete = true;
47
+ return;
48
+ }
49
+ if (!object(root)) {
50
+ return;
51
+ }
52
+ if ([
53
+ "message_stop",
54
+ "response.completed",
55
+ "response.incomplete",
56
+ "response.failed",
57
+ ].includes(String(root.type))) {
58
+ ended = true;
59
+ }
60
+ if (Array.isArray(root.choices)) {
61
+ for (const choice of root.choices) {
62
+ if (!object(choice)) {
63
+ continue;
64
+ }
65
+ const key = `chat:${identity(root.id)}:${identity(choice.index)}`;
66
+ if (object(choice.delta)) {
67
+ text("answer", key + ":content", choice.delta.content, true);
68
+ for (const name of ["reasoning", "reasoning_content"]) {
69
+ text("reasoning", key + ":" + name, choice.delta[name], true);
70
+ }
71
+ }
72
+ if (object(choice.message)) {
73
+ text("answer", key, choice.message.content);
74
+ for (const name of ["reasoning", "reasoning_content"]) {
75
+ text("reasoning", key, choice.message[name]);
76
+ }
77
+ }
78
+ }
79
+ }
80
+ if (root.type === "content_block_delta" && object(root.delta)) {
81
+ const key = `anthropic:${identity(root.index)}`;
82
+ text("answer", key + ":text", root.delta.text, true);
83
+ text("reasoning", key + ":thinking", root.delta.thinking, true);
84
+ }
85
+ if (typeof root.type === "string" &&
86
+ /^response\.(output_text|reasoning_text|reasoning_summary_text)\.delta$/.test(root.type)) {
87
+ const key = `responses:${identity(root.item_id)}:${identity(root.output_index)}:${identity(root.content_index ?? root.summary_index)}:${root.type}`;
88
+ text(root.type === "response.output_text.delta" ? "answer" : "reasoning", key, root.delta, true);
89
+ }
90
+ if (typeof root.type === "string" &&
91
+ /^response\..+\.done$/.test(root.type)) {
92
+ text("snapshot", "", root.text);
93
+ }
94
+ if (Array.isArray(root.content)) {
95
+ for (const part of root.content) {
96
+ if (!object(part)) {
97
+ continue;
98
+ }
99
+ text("answer", "", part.text);
100
+ text("reasoning", "", part.thinking);
101
+ }
102
+ }
103
+ if (typeof root.type !== "string") {
104
+ text("answer", "generic", root.text);
105
+ }
106
+ };
107
+ const frame = (wire) => {
108
+ for (const block of wire
109
+ .replace(/^\uFEFF/, "")
110
+ .split(/\r\n\r\n|\n\n|\r\r/)) {
111
+ const data = block
112
+ .split(/\r\n|\n|\r/)
113
+ .filter((line) => line.startsWith("data:"))
114
+ .map((line) => line.slice(5).replace(/^ /, ""))
115
+ .join("\n");
116
+ if (data === "[DONE]") {
117
+ ended = true;
118
+ }
119
+ else if (data) {
120
+ json(data);
121
+ }
122
+ }
123
+ };
124
+ return {
125
+ json,
126
+ frame,
127
+ report(other, trace) {
128
+ for (const channel of ["answer", "reasoning", "snapshot"]) {
129
+ const flags = Object.keys(signatures)
130
+ .map((name) => `${name}=${Number(seen.has(`${channel}.${name}`))}/${Number(other.has(`${channel}.${name}`))}`)
131
+ .join(" ");
132
+ trace(`markup channel=${channel} before/after ${flags}`);
133
+ }
134
+ trace(`markup_complete before=${Number(!incomplete && observedFields > 0)} after=${Number(other.complete())} fields_before=${observedFields} fields_after=${other.fields()}`);
135
+ tails.clear();
136
+ },
137
+ has: (key) => seen.has(key),
138
+ complete: () => !incomplete && observedFields > 0,
139
+ fields: () => observedFields,
140
+ ended: () => ended,
141
+ };
142
+ }