deft-bridge 0.3.1 → 0.3.2

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.
package/dist/bridge.js CHANGED
@@ -14,6 +14,960 @@ var __export = (target, all) => {
14
14
  __defProp(target, name, { get: all[name], enumerable: true });
15
15
  };
16
16
 
17
+ // packages/core/src/acp.ts
18
+ var init_acp = __esm({
19
+ "packages/core/src/acp.ts"() {
20
+ "use strict";
21
+ }
22
+ });
23
+
24
+ // packages/core/src/types.ts
25
+ var init_types = __esm({
26
+ "packages/core/src/types.ts"() {
27
+ "use strict";
28
+ }
29
+ });
30
+
31
+ // packages/core/src/meta.ts
32
+ import { z } from "zod";
33
+ function asRecord(value) {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
35
+ }
36
+ function readTelemetry(value) {
37
+ const telemetry = asRecord(value);
38
+ const rawChars = typeof telemetry?.rawChars === "number" ? telemetry.rawChars : 0;
39
+ const reducedChars = typeof telemetry?.reducedChars === "number" ? telemetry.reducedChars : 0;
40
+ const savedChars = typeof telemetry?.savedChars === "number" ? telemetry.savedChars : 0;
41
+ const toolResultCount = typeof telemetry?.toolResultCount === "number" ? telemetry.toolResultCount : 0;
42
+ const reducers = asRecord(telemetry?.reducers);
43
+ return {
44
+ toolResultCount,
45
+ rawChars,
46
+ reducedChars,
47
+ savedChars,
48
+ retentionRatio: rawChars === 0 ? 1 : reducedChars / rawChars,
49
+ savingsRatio: rawChars === 0 ? 0 : savedChars / rawChars,
50
+ reducers: Object.fromEntries(
51
+ Object.entries(reducers ?? {}).filter((entry) => {
52
+ return typeof entry[1] === "number";
53
+ })
54
+ )
55
+ };
56
+ }
57
+ function recordReductionTelemetry(metadata, reduction) {
58
+ const bridge = asRecord(metadata.bridge) ?? {};
59
+ const current = readTelemetry(bridge.reductionTelemetry);
60
+ const reducerId = reduction.reducerId ?? "unknown";
61
+ const nextRawChars = current.rawChars + reduction.rawChars;
62
+ const nextReducedChars = current.reducedChars + reduction.reducedChars;
63
+ const nextSavedChars = current.savedChars + reduction.savedChars;
64
+ const next = {
65
+ toolResultCount: current.toolResultCount + 1,
66
+ rawChars: nextRawChars,
67
+ reducedChars: nextReducedChars,
68
+ savedChars: nextSavedChars,
69
+ retentionRatio: nextRawChars === 0 ? 1 : nextReducedChars / nextRawChars,
70
+ savingsRatio: nextRawChars === 0 ? 0 : nextSavedChars / nextRawChars,
71
+ reducers: {
72
+ ...current.reducers,
73
+ [reducerId]: (current.reducers[reducerId] ?? 0) + 1
74
+ }
75
+ };
76
+ metadata.bridge = {
77
+ ...bridge,
78
+ reductionTelemetry: next
79
+ };
80
+ return next;
81
+ }
82
+ var ProxyMetaSchema, ReductionTelemetrySchema, BridgeMetaSchema, AnthropicMetaSchema, OpenAIMetaSchema, OllamaMetaSchema, MetadataSchema;
83
+ var init_meta = __esm({
84
+ "packages/core/src/meta.ts"() {
85
+ "use strict";
86
+ ProxyMetaSchema = z.object({
87
+ version: z.string().optional(),
88
+ backend: z.string().optional(),
89
+ model: z.string().optional(),
90
+ requestId: z.string().optional(),
91
+ traceId: z.string().optional(),
92
+ startTime: z.number().optional(),
93
+ usage: z.object({
94
+ inputTokens: z.number().optional(),
95
+ outputTokens: z.number().optional(),
96
+ totalTokens: z.number().optional(),
97
+ thinkingTokens: z.number().optional()
98
+ }).optional(),
99
+ cost: z.object({
100
+ inputCost: z.number().optional(),
101
+ outputCost: z.number().optional(),
102
+ totalCost: z.number().optional(),
103
+ currency: z.string().optional()
104
+ }).optional(),
105
+ timing: z.object({
106
+ queuedMs: z.number().optional(),
107
+ processingMs: z.number().optional(),
108
+ totalMs: z.number().optional()
109
+ }).optional(),
110
+ retryAfterMs: z.number().optional()
111
+ });
112
+ ReductionTelemetrySchema = z.object({
113
+ toolResultCount: z.number(),
114
+ rawChars: z.number(),
115
+ reducedChars: z.number(),
116
+ savedChars: z.number(),
117
+ retentionRatio: z.number(),
118
+ savingsRatio: z.number(),
119
+ reducers: z.record(z.string(), z.number())
120
+ });
121
+ BridgeMetaSchema = z.object({
122
+ reductionTelemetry: ReductionTelemetrySchema.optional()
123
+ });
124
+ AnthropicMetaSchema = z.object({
125
+ model: z.string().optional(),
126
+ maxTokens: z.number().optional(),
127
+ thinking: z.enum(["disabled", "enabled", "streaming"]).optional(),
128
+ maxThinkingTokens: z.number().optional(),
129
+ thinkingBlockId: z.string().optional(),
130
+ thinkingBlockIndex: z.number().optional(),
131
+ cacheControl: z.object({
132
+ type: z.literal("ephemeral"),
133
+ ttl: z.number().optional()
134
+ }).optional(),
135
+ cacheReadInputTokens: z.number().optional(),
136
+ cacheCreationInputTokens: z.number().optional(),
137
+ stopSequences: z.array(z.string()).optional(),
138
+ interleaved_thinking: z.boolean().optional(),
139
+ stopReason: z.string().optional(),
140
+ stopSequence: z.string().nullable().optional()
141
+ });
142
+ OpenAIMetaSchema = z.object({
143
+ model: z.string().optional(),
144
+ reasoning: z.object({
145
+ effort: z.enum(["low", "medium", "high"]),
146
+ summary: z.enum(["disabled", "auto", "always"]).optional()
147
+ }).optional(),
148
+ reasoningTokens: z.number().optional(),
149
+ reasoningSummary: z.boolean().optional(),
150
+ builtinTools: z.array(
151
+ z.object({
152
+ type: z.enum(["web_search", "code_interpreter", "file_search"]),
153
+ config: z.record(z.string(), z.unknown()).optional()
154
+ })
155
+ ).optional(),
156
+ builtinTool: z.boolean().optional(),
157
+ serverExecuted: z.boolean().optional(),
158
+ fileIds: z.array(z.string()).optional(),
159
+ vectorStoreIds: z.array(z.string()).optional(),
160
+ responseFormat: z.object({
161
+ type: z.enum(["text", "json_object", "json_schema"]),
162
+ schema: z.record(z.string(), z.unknown()).optional()
163
+ }).optional(),
164
+ prediction: z.object({
165
+ type: z.literal("content"),
166
+ content: z.string()
167
+ }).optional()
168
+ });
169
+ OllamaMetaSchema = z.object({
170
+ model: z.string().optional(),
171
+ temperature: z.number().optional(),
172
+ topP: z.number().optional(),
173
+ topK: z.number().optional(),
174
+ repeatPenalty: z.number().optional(),
175
+ contextLength: z.number().optional(),
176
+ numPredict: z.number().optional(),
177
+ numGpu: z.number().optional(),
178
+ mainGpu: z.number().optional(),
179
+ keepAlive: z.string().optional()
180
+ });
181
+ MetadataSchema = z.object({
182
+ proxy: ProxyMetaSchema.optional(),
183
+ bridge: BridgeMetaSchema.optional(),
184
+ anthropic: AnthropicMetaSchema.optional(),
185
+ openai: OpenAIMetaSchema.optional(),
186
+ ollama: OllamaMetaSchema.optional()
187
+ });
188
+ }
189
+ });
190
+
191
+ // packages/core/src/errors.ts
192
+ var init_errors = __esm({
193
+ "packages/core/src/errors.ts"() {
194
+ "use strict";
195
+ init_acp();
196
+ }
197
+ });
198
+
199
+ // packages/core/src/context.ts
200
+ import { randomUUID } from "crypto";
201
+ function createTurnScope(id = randomUUID(), logger) {
202
+ let phase = "running";
203
+ let cancelReason;
204
+ let onFinish;
205
+ let onCancel;
206
+ const ignored = (call) => logger?.debug(`Turn ${call} ignored`, { turnId: id, phase });
207
+ return {
208
+ id,
209
+ store: /* @__PURE__ */ new Map(),
210
+ get phase() {
211
+ return phase;
212
+ },
213
+ finish() {
214
+ if (phase === "finished") return ignored("finish");
215
+ phase = "finished";
216
+ onFinish?.();
217
+ },
218
+ cancel(reason) {
219
+ if (phase !== "running") return ignored("cancel");
220
+ phase = "cancelling";
221
+ cancelReason = reason;
222
+ onCancel?.(reason);
223
+ },
224
+ onFinish(handler) {
225
+ onFinish = handler;
226
+ if (phase === "finished") handler();
227
+ },
228
+ onCancel(handler) {
229
+ onCancel = handler;
230
+ if (phase === "cancelling") handler(cancelReason);
231
+ }
232
+ };
233
+ }
234
+ function turnStore(ctx, key2, create) {
235
+ let store = ctx.turn?.store;
236
+ if (!store) {
237
+ store = contextStores.get(ctx);
238
+ if (!store) contextStores.set(ctx, store = /* @__PURE__ */ new Map());
239
+ }
240
+ if (!store.has(key2)) store.set(key2, create());
241
+ return store.get(key2);
242
+ }
243
+ function sessionCwd(ctx, fallback) {
244
+ return ctx.session?.cwd ?? fallback ?? process.cwd();
245
+ }
246
+ var contextStores;
247
+ var init_context = __esm({
248
+ "packages/core/src/context.ts"() {
249
+ "use strict";
250
+ contextStores = /* @__PURE__ */ new WeakMap();
251
+ }
252
+ });
253
+
254
+ // packages/core/src/version.ts
255
+ var BRIDGE_VERSION;
256
+ var init_version = __esm({
257
+ "packages/core/src/version.ts"() {
258
+ "use strict";
259
+ BRIDGE_VERSION = "0.3.2";
260
+ }
261
+ });
262
+
263
+ // packages/core/src/safe-pattern.ts
264
+ function unsafePatternReason(pattern) {
265
+ try {
266
+ new RegExp(pattern);
267
+ } catch {
268
+ return "not a valid regular expression";
269
+ }
270
+ const groups = [
271
+ { quantified: false, alternation: false }
272
+ ];
273
+ const quantifierAt = (i) => {
274
+ const c = pattern[i];
275
+ if (c === "*" || c === "+") return { length: 1, repeats: true };
276
+ if (c === "?") return { length: 1, repeats: false };
277
+ if (c === "{") {
278
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(i));
279
+ if (!m) return { length: 0, repeats: false };
280
+ const max = m[2] === void 0 ? Number(m[1]) : m[3] === "" ? Infinity : Number(m[3]);
281
+ return { length: m[0].length, repeats: max > 1 };
282
+ }
283
+ return { length: 0, repeats: false };
284
+ };
285
+ for (let i = 0; i < pattern.length; i++) {
286
+ const c = pattern[i];
287
+ const top = groups[groups.length - 1];
288
+ if (c === "\\") {
289
+ const next = pattern[i + 1] ?? "";
290
+ if (/[1-9]/.test(next) || next === "k") return "backreferences are not allowed";
291
+ i++;
292
+ continue;
293
+ }
294
+ if (c === "[") {
295
+ for (i++; i < pattern.length && pattern[i] !== "]"; i++) if (pattern[i] === "\\") i++;
296
+ continue;
297
+ }
298
+ if (c === "(") {
299
+ groups.push({ quantified: false, alternation: false });
300
+ if (pattern[i + 1] === "?") {
301
+ const m = /^\?(<[A-Za-z_$][\w$]*>|<=|<!|[:=!])/.exec(pattern.slice(i + 1));
302
+ if (m) i += m[0].length;
303
+ }
304
+ continue;
305
+ }
306
+ if (c === "|") {
307
+ top.alternation = true;
308
+ continue;
309
+ }
310
+ if (c === ")") {
311
+ if (groups.length === 1) continue;
312
+ const group = groups.pop();
313
+ const parent = groups[groups.length - 1];
314
+ const quantifier2 = quantifierAt(i + 1);
315
+ if (quantifier2.repeats && (group.quantified || group.alternation))
316
+ return "a repeated group that contains a quantifier or alternation can take exponential time. Drop the repeat around the group (`^(Read|Edit) ` rather than `(Read|Edit)+`), or repeat a character class instead (`[a-z]+` rather than `(a|b)+`, `\\w+` rather than `(\\w+)+`)";
317
+ if (group.quantified) parent.quantified = true;
318
+ if (group.alternation) parent.alternation = true;
319
+ continue;
320
+ }
321
+ const quantifier = quantifierAt(i);
322
+ if (quantifier.length > 0) {
323
+ top.quantified = true;
324
+ i += quantifier.length - 1;
325
+ }
326
+ }
327
+ return void 0;
328
+ }
329
+ function compileSafePattern(pattern, what) {
330
+ const reason = unsafePatternReason(pattern);
331
+ if (reason) throw new Error(`${what} ${JSON.stringify(pattern)} is refused: ${reason}`);
332
+ return new RegExp(pattern);
333
+ }
334
+ var init_safe_pattern = __esm({
335
+ "packages/core/src/safe-pattern.ts"() {
336
+ "use strict";
337
+ }
338
+ });
339
+
340
+ // packages/core/src/index.ts
341
+ var init_src = __esm({
342
+ "packages/core/src/index.ts"() {
343
+ init_acp();
344
+ init_types();
345
+ init_meta();
346
+ init_errors();
347
+ init_context();
348
+ init_version();
349
+ init_safe_pattern();
350
+ }
351
+ });
352
+
353
+ // packages/config/src/schema.ts
354
+ import { isAbsolute } from "node:path";
355
+ import { z as z2 } from "zod";
356
+ function exportersOf(setting) {
357
+ if (setting === "none") return [];
358
+ return typeof setting === "string" ? [setting] : [...new Set(setting)];
359
+ }
360
+ var BACKENDS, ProxyConfigSchema, AnthropicBackendSchema, OpenAIBackendSchema, BackendsConfigSchema, ServerConfigSchema, GraphConfigSchema, LoggingConfigSchema, OTEL_EXPORTERS, ExporterSettingSchema, TelemetryConfigSchema, ReductionConfigSchema, ConfigSchema, TrustedFoldersSchema, RawConfigSchema, EnvironmentSchema;
361
+ var init_schema = __esm({
362
+ "packages/config/src/schema.ts"() {
363
+ "use strict";
364
+ init_src();
365
+ BACKENDS = [
366
+ "openai",
367
+ "anthropic",
368
+ "grok",
369
+ "ideal",
370
+ "claude-sdk",
371
+ "codex-app-server"
372
+ ];
373
+ ProxyConfigSchema = z2.object({
374
+ defaultBackend: z2.enum(BACKENDS).default("openai")
375
+ });
376
+ AnthropicBackendSchema = z2.object({
377
+ apiKey: z2.string().optional(),
378
+ /** Base URL override (a proxy, or a local test server). */
379
+ baseURL: z2.string().optional(),
380
+ defaultModel: z2.string().default("claude-sonnet-4-20250514"),
381
+ defaultMaxTokens: z2.number().optional(),
382
+ maxRetries: z2.number().default(3),
383
+ timeoutMs: z2.number().default(12e4)
384
+ });
385
+ OpenAIBackendSchema = z2.object({
386
+ apiKey: z2.string().optional(),
387
+ baseURL: z2.string().optional(),
388
+ defaultModel: z2.string().default("gpt-4.1"),
389
+ maxRetries: z2.number().default(3),
390
+ timeoutMs: z2.number().default(12e4),
391
+ /**
392
+ * Tool calling: 'native' (default) offers the model Bridge's built-in tools and the
393
+ * client's MCP servers' tools in the OpenAI tools parameter; 'none' offers no tools,
394
+ * and Bridge does not advertise or connect the client's MCP servers.
395
+ * ('gemma-prompt' was dropped with the classic server; the Gemma nodes remain for graphs.)
396
+ */
397
+ toolMode: z2.enum(["native", "none"]).default("native"),
398
+ /** Maximum tool calling loop iterations per prompt (default: 5) */
399
+ maxToolIterations: z2.number().default(5)
400
+ });
401
+ BackendsConfigSchema = z2.object({
402
+ anthropic: AnthropicBackendSchema.optional(),
403
+ openai: OpenAIBackendSchema.optional(),
404
+ ideal: z2.object({
405
+ /** Required for defaultBackend = "ideal" (the only backend with an `enabled`). */
406
+ enabled: z2.boolean().default(true),
407
+ module: z2.string().min(1),
408
+ sessionCodeExec: z2.string().min(1).optional(),
409
+ permissionMode: z2.enum(["manual", "acp", "auto-allow"]).optional(),
410
+ options: z2.record(z2.string(), z2.unknown()).default({})
411
+ }).optional(),
412
+ grok: z2.object({
413
+ command: z2.string().default("grok"),
414
+ args: z2.array(z2.string()).default(["agent", "stdio"]),
415
+ env: z2.record(z2.string(), z2.string()).optional(),
416
+ defaultModel: z2.string().optional(),
417
+ requestTimeoutMs: z2.number().int().nonnegative().optional()
418
+ }).optional(),
419
+ codex: z2.object({
420
+ command: z2.string().default("codex"),
421
+ args: z2.array(z2.string()).default(["app-server", "--listen", "stdio://"]),
422
+ env: z2.record(z2.string(), z2.string()).optional(),
423
+ model: z2.string().min(1).optional(),
424
+ mode: z2.enum(["default", "read-only", "auto", "full-access"]).optional(),
425
+ allowFullAccess: z2.boolean().optional(),
426
+ dynamicTools: z2.boolean().optional(),
427
+ cancelGraceMs: z2.number().int().nonnegative().optional(),
428
+ requestTimeoutMs: z2.number().int().nonnegative().optional()
429
+ }).optional()
430
+ });
431
+ ServerConfigSchema = z2.object({
432
+ port: z2.number().default(6809),
433
+ host: z2.string().default("localhost"),
434
+ transport: z2.enum(["stdio", "http", "pi-rpc"]).default("stdio"),
435
+ /** Browser origins allowed to call the HTTP transport (default: none). */
436
+ allowedOrigins: z2.array(z2.string()).default([]),
437
+ /**
438
+ * Bearer token for the HTTP transport (env BRIDGE_HTTP_TOKEN). When set, every request
439
+ * must carry `Authorization: Bearer <token>`. Required to listen on a host that is not
440
+ * loopback (localhost, 127.0.0.0/8, ::1).
441
+ */
442
+ httpToken: z2.string().min(1).optional(),
443
+ /**
444
+ * Internal hosts an HTTP client's http/sse MCP servers may point at (env
445
+ * BRIDGE_MCP_ALLOWED_HOSTS, comma-separated): host names, IP addresses or CIDR ranges.
446
+ * Over HTTP, MCP server URLs on loopback, private, link-local (cloud metadata), CGNAT or
447
+ * unspecified addresses are refused unless listed here. Stdio clients are not checked.
448
+ */
449
+ mcpAllowedHosts: z2.array(z2.string()).default([]),
450
+ /**
451
+ * The ACP versions served (env BRIDGE_ACP_PROTOCOLS, CLI --acp-protocols, e.g. `1,2`).
452
+ * Default v1 and v2: a client gets the one it asks for.
453
+ */
454
+ acpProtocols: z2.array(z2.union([z2.literal(1), z2.literal(2)])).min(1).default([1, 2])
455
+ });
456
+ GraphConfigSchema = z2.object({
457
+ defaultGraph: z2.string().default("graphs/default.json"),
458
+ graphDir: z2.string().default("graphs")
459
+ });
460
+ LoggingConfigSchema = z2.object({
461
+ level: z2.enum(["debug", "info", "warn", "error"]).default("info"),
462
+ pretty: z2.boolean().default(false),
463
+ /** Output format. `pretty` remains as a legacy alias for format = "pretty". */
464
+ format: z2.enum(["json", "pretty"]).default("json"),
465
+ /** Optional file sink. stderr remains the default and stdout is never used for logs. */
466
+ file: z2.string().optional(),
467
+ /** Whether to keep stderr logging enabled when a file sink is configured. */
468
+ stderr: z2.boolean().default(true)
469
+ });
470
+ OTEL_EXPORTERS = ["console", "otlp"];
471
+ ExporterSettingSchema = z2.union([
472
+ z2.enum(["none", ...OTEL_EXPORTERS]),
473
+ z2.array(z2.enum(OTEL_EXPORTERS))
474
+ ]);
475
+ TelemetryConfigSchema = z2.object({
476
+ enabled: z2.boolean().default(false),
477
+ serviceName: z2.string().default("bridge"),
478
+ serviceVersion: z2.string().default(BRIDGE_VERSION),
479
+ otlpEndpoint: z2.string().optional(),
480
+ traces: z2.object({
481
+ enabled: z2.boolean().default(true),
482
+ exporter: ExporterSettingSchema.default("console"),
483
+ sampleRate: z2.number().min(0).max(1).default(1)
484
+ }).prefault({}),
485
+ metrics: z2.object({
486
+ enabled: z2.boolean().default(true),
487
+ exporter: ExporterSettingSchema.default("console"),
488
+ exportIntervalMs: z2.number().int().positive().default(6e4)
489
+ }).prefault({}),
490
+ logs: z2.object({
491
+ /** Export Bridge's log lines as OpenTelemetry log records: those [logging] level lets through. */
492
+ export: z2.boolean().default(false),
493
+ exporter: ExporterSettingSchema.default("none")
494
+ }).prefault({}),
495
+ instrumentation: z2.object({
496
+ http: z2.boolean().default(false),
497
+ pino: z2.boolean().default(true)
498
+ }).prefault({})
499
+ });
500
+ ReductionConfigSchema = z2.object({
501
+ enabled: z2.boolean().default(true),
502
+ maxInlineChars: z2.number().int().positive().default(1200),
503
+ storeArtifacts: z2.boolean().default(false),
504
+ recordStats: z2.boolean().default(true),
505
+ preserveFileReads: z2.boolean().default(true),
506
+ projectRulesDir: z2.string().default(".bridge/reducers"),
507
+ tokenjuiceCompatibilityRulesDir: z2.string().default(".tokenjuice/rules"),
508
+ artifactDir: z2.string().default(".bridge/reduction-artifacts"),
509
+ /** Stored artifacts kept: past any of these, the oldest are deleted (an open session's stay). */
510
+ artifactMaxCount: z2.number().int().positive().default(1e3),
511
+ artifactMaxBytes: z2.number().int().positive().default(256 * 1024 * 1024),
512
+ artifactMaxAgeDays: z2.number().positive().default(7)
513
+ });
514
+ ConfigSchema = z2.object({
515
+ proxy: ProxyConfigSchema,
516
+ backends: BackendsConfigSchema,
517
+ server: ServerConfigSchema,
518
+ graph: GraphConfigSchema,
519
+ logging: LoggingConfigSchema,
520
+ telemetry: TelemetryConfigSchema.prefault({}),
521
+ reduction: ReductionConfigSchema.prefault({})
522
+ }).superRefine((config, ctx) => {
523
+ if (config.proxy.defaultBackend === "ideal" && !config.backends.ideal?.enabled) {
524
+ ctx.addIssue({
525
+ code: "custom",
526
+ path: ["backends", "ideal"],
527
+ message: "The Ideal backend requires an enabled runtime module"
528
+ });
529
+ }
530
+ });
531
+ TrustedFoldersSchema = z2.array(
532
+ z2.string().min(1).refine((entry) => isAbsolute(entry) || /^~(?=$|[\\/])/.test(entry), {
533
+ message: "trustedFolders entries must be absolute paths or start with ~/"
534
+ })
535
+ );
536
+ RawConfigSchema = z2.object({
537
+ profiles: z2.record(z2.string(), z2.record(z2.string(), z2.unknown())).optional(),
538
+ trustedFolders: TrustedFoldersSchema.optional()
539
+ });
540
+ EnvironmentSchema = z2.object({
541
+ ANTHROPIC_API_KEY: z2.string().optional(),
542
+ OPENAI_API_KEY: z2.string().optional(),
543
+ BRIDGE_BACKEND: z2.enum(BACKENDS).optional(),
544
+ GROK_COMMAND: z2.string().optional(),
545
+ CODEX_COMMAND: z2.string().optional(),
546
+ LOG_LEVEL: z2.enum(["debug", "info", "warn", "error"]).optional(),
547
+ BRIDGE_LOG_LEVEL: z2.enum(["debug", "info", "warn", "error"]).optional(),
548
+ BRIDGE_LOG_FILE: z2.string().optional(),
549
+ BRIDGE_LOG_FORMAT: z2.enum(["json", "pretty"]).optional(),
550
+ BRIDGE_PROFILE: z2.string().optional(),
551
+ BRIDGE_PORT: z2.coerce.number().int().positive().optional(),
552
+ /** Comma-separated ACP versions to serve, e.g. `1,2` (server.acpProtocols). */
553
+ BRIDGE_ACP_PROTOCOLS: z2.string().optional(),
554
+ /** Comma-separated browser origins allowed to call the HTTP transport. */
555
+ BRIDGE_ALLOWED_ORIGINS: z2.string().optional(),
556
+ /** Bearer token the HTTP transport requires (server.httpToken). */
557
+ BRIDGE_HTTP_TOKEN: z2.string().optional(),
558
+ /** Comma-separated internal hosts HTTP clients' MCP servers may use (server.mcpAllowedHosts). */
559
+ BRIDGE_MCP_ALLOWED_HOSTS: z2.string().optional(),
560
+ TRANSPORT: z2.enum(["stdio", "http", "pi-rpc"]).optional(),
561
+ BRIDGE_TRANSPORT: z2.enum(["stdio", "http", "pi-rpc"]).optional(),
562
+ BRIDGE_TELEMETRY_ENABLED: z2.enum(["true", "false"]).optional().transform((value) => value === void 0 ? void 0 : value === "true"),
563
+ BRIDGE_TELEMETRY_LOGS_EXPORT: z2.enum(["true", "false"]).optional().transform((value) => value === void 0 ? void 0 : value === "true"),
564
+ /** Normalized by loadEnvironment from a comma-separated list. */
565
+ OTEL_LOGS_EXPORTER: ExporterSettingSchema.optional(),
566
+ OTEL_SERVICE_NAME: z2.string().optional(),
567
+ OTEL_EXPORTER_OTLP_ENDPOINT: z2.string().optional()
568
+ });
569
+ }
570
+ });
571
+
572
+ // packages/config/src/trust.ts
573
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
574
+ import { homedir, userInfo } from "node:os";
575
+ import { dirname, isAbsolute as isAbsolute2, join, resolve } from "node:path";
576
+ import { parse as parseToml } from "smol-toml";
577
+ function homeFolder() {
578
+ const home = homedir();
579
+ if (isAbsolute2(home)) return home;
580
+ const account = userInfo().homedir;
581
+ if (isAbsolute2(account)) return account;
582
+ throw new Error(
583
+ "Cannot find the home folder for the user config ($HOME is not an absolute path)"
584
+ );
585
+ }
586
+ function userConfigPath(homeDir = homeFolder()) {
587
+ return join(homeDir, ".config", "bridge", "config.toml");
588
+ }
589
+ function expandHome(path2, homeDir = homeFolder()) {
590
+ return /^~(?=$|[\\/])/.test(path2) ? join(homeDir, path2.slice(1)) : path2;
591
+ }
592
+ function realPath(path2) {
593
+ try {
594
+ return realpathSync(path2);
595
+ } catch {
596
+ return resolve(path2);
597
+ }
598
+ }
599
+ function readTrustedFolders(configPath, homeDir = homeFolder()) {
600
+ if (!existsSync(configPath)) return [];
601
+ let raw;
602
+ try {
603
+ raw = parseToml(readFileSync(configPath, "utf8"));
604
+ } catch (error) {
605
+ throw new Error(
606
+ `Cannot read trustedFolders from ${configPath}: ${error instanceof Error ? error.message : String(error)}`
607
+ );
608
+ }
609
+ if (raw.trustedFolders === void 0) return [];
610
+ const parsed = TrustedFoldersSchema.safeParse(raw.trustedFolders);
611
+ if (!parsed.success) {
612
+ throw new Error(`Invalid trustedFolders in ${configPath}: ${parsed.error.message}`);
613
+ }
614
+ return parsed.data.map((entry) => realPath(expandHome(entry, homeDir)));
615
+ }
616
+ function isTrustedFolder(folder, options = {}) {
617
+ const homeDir = options.homeDir ?? homeFolder();
618
+ const trusted = readTrustedFolders(options.userConfig ?? userConfigPath(homeDir), homeDir);
619
+ return trusted.includes(realPath(folder));
620
+ }
621
+ function untrustedConfigWarning(path2, options = {}) {
622
+ const homeDir = options.homeDir ?? homeFolder();
623
+ const userConfig = options.userConfig ?? userConfigPath(homeDir);
624
+ const folder = realPath(dirname(path2));
625
+ const hint = options.explicitHint ?? "--config";
626
+ return `Bridge: ignoring ${path2}: config files in the working folder are used only if the folder is trusted. To use it, add ${JSON.stringify(folder)} to trustedFolders in ${userConfig}, or name the file with ${hint}.
627
+ `;
628
+ }
629
+ function locateConfigFile(options = {}) {
630
+ const homeDir = options.homeDir ?? homeFolder();
631
+ const userConfig = options.userConfig ?? userConfigPath(homeDir);
632
+ if (options.explicit) return { path: resolve(options.explicit), source: "explicit", userConfig };
633
+ const cwd = options.cwd ?? process.cwd();
634
+ const folderFile = FOLDER_CONFIG_NAMES.map((name) => resolve(cwd, name)).find(
635
+ (path2) => existsSync(path2)
636
+ );
637
+ if (folderFile) {
638
+ if (isTrustedFolder(cwd, { homeDir, userConfig })) {
639
+ return { path: folderFile, source: "folder", userConfig };
640
+ }
641
+ const warn = options.warn ?? ((message) => process.stderr.write(message));
642
+ warn(
643
+ untrustedConfigWarning(folderFile, {
644
+ homeDir,
645
+ userConfig,
646
+ explicitHint: options.explicitHint
647
+ })
648
+ );
649
+ }
650
+ return existsSync(userConfig) ? { path: userConfig, source: "user", userConfig } : { userConfig };
651
+ }
652
+ var FOLDER_CONFIG_NAMES;
653
+ var init_trust = __esm({
654
+ "packages/config/src/trust.ts"() {
655
+ "use strict";
656
+ init_schema();
657
+ FOLDER_CONFIG_NAMES = ["bridge.toml", ".bridge.toml"];
658
+ }
659
+ });
660
+
661
+ // packages/config/src/loader.ts
662
+ import { readFile } from "fs/promises";
663
+ import { parse as parseToml2 } from "smol-toml";
664
+ function isPlainObject(value) {
665
+ return typeof value === "object" && value !== null && !Array.isArray(value);
666
+ }
667
+ function deepMergeConfig(base, overlay) {
668
+ const merged = { ...base };
669
+ for (const [key2, value] of Object.entries(overlay)) {
670
+ const current = merged[key2];
671
+ merged[key2] = isPlainObject(current) && isPlainObject(value) ? deepMergeConfig(current, value) : value;
672
+ }
673
+ return merged;
674
+ }
675
+ function withoutProfiles(config) {
676
+ const rest = { ...config };
677
+ delete rest.profiles;
678
+ return rest;
679
+ }
680
+ function parseProfileList(profile) {
681
+ return profile ? profile.split(",").map((name) => name.trim()).filter((name) => name.length > 0) : [];
682
+ }
683
+ function applyProfileConfig(rawConfig, profile) {
684
+ const base = withoutProfiles(rawConfig);
685
+ const selectedProfileNames = parseProfileList(profile);
686
+ if (selectedProfileNames.length === 0) {
687
+ return base;
688
+ }
689
+ const profiles = isPlainObject(rawConfig.profiles) ? rawConfig.profiles : {};
690
+ const selectedProfiles = selectedProfileNames.map((profileName) => {
691
+ const selected = profiles[profileName];
692
+ if (!isPlainObject(selected)) {
693
+ throw new Error(`Configuration profile not found: ${profileName}`);
694
+ }
695
+ if ("profiles" in selected) {
696
+ throw new Error(`Configuration profile cannot define nested profiles: ${profileName}`);
697
+ }
698
+ return selected;
699
+ });
700
+ return selectedProfiles.reduceRight(
701
+ (merged, selected) => deepMergeConfig(merged, selected),
702
+ base
703
+ );
704
+ }
705
+ function normalizeLoadConfigArgs(configPathOrOptions, maybeOptions) {
706
+ if (typeof configPathOrOptions === "string" || configPathOrOptions === void 0) {
707
+ return { configPath: configPathOrOptions, options: maybeOptions ?? {} };
708
+ }
709
+ return { options: configPathOrOptions };
710
+ }
711
+ async function loadConfig(configPathOrOptions, maybeOptions) {
712
+ const { configPath, options } = normalizeLoadConfigArgs(configPathOrOptions, maybeOptions);
713
+ const path2 = configPath || findConfigPath(options);
714
+ try {
715
+ const content2 = await readFile(path2, "utf-8");
716
+ const parsed = RawConfigSchema.passthrough().parse(parseToml2(content2));
717
+ const env3 = loadEnvironment({ warn: options.warn });
718
+ const profile = options.profile ?? env3.BRIDGE_PROFILE;
719
+ const config = ConfigSchema.parse(
720
+ deepMergeConfig(generateDefaultConfig(), applyProfileConfig(parsed, profile))
721
+ );
722
+ const envMerged = mergeEnvironment(config, env3);
723
+ return ConfigSchema.parse(deepMergeConfig(envMerged, options.overrides ?? {}));
724
+ } catch (error) {
725
+ if (error.code === "ENOENT") {
726
+ const notFoundError = new Error(
727
+ `Configuration file not found: ${path2}`
728
+ );
729
+ notFoundError.code = "ENOENT";
730
+ throw notFoundError;
731
+ }
732
+ throw error;
733
+ }
734
+ }
735
+ function findConfigPath(options) {
736
+ const location = locateConfigFile({
737
+ explicit: process.env.BRIDGE_CONFIG,
738
+ explicitHint: "--config or BRIDGE_CONFIG",
739
+ cwd: options.cwd,
740
+ homeDir: options.homeDir,
741
+ userConfig: options.userConfig,
742
+ warn: options.warn
743
+ });
744
+ return location.path ?? location.userConfig;
745
+ }
746
+ function parseAcpProtocols(value, source = "ACP protocols") {
747
+ const versions = value.split(",").map((part) => part.trim()).filter(Boolean);
748
+ if (!versions.length || versions.some((v) => v !== "1" && v !== "2"))
749
+ throw new Error(`${source}: expected 1, 2 or 1,2, got "${value}"`);
750
+ return [...new Set(versions.map((v) => Number(v)))].sort();
751
+ }
752
+ function normalizeLogLevel(value) {
753
+ return value === void 0 ? void 0 : LOG_LEVELS.get(value.trim().toLowerCase());
754
+ }
755
+ function normalizeTransport(value) {
756
+ return value === void 0 ? void 0 : TRANSPORTS.get(value.trim().toLowerCase());
757
+ }
758
+ function parseOtelExporters(name, value, warn = () => {
759
+ }) {
760
+ if (value === void 0) return void 0;
761
+ const names = [
762
+ ...new Set(
763
+ value.split(",").map((part) => part.trim().toLowerCase()).filter(Boolean)
764
+ )
765
+ ];
766
+ if (!names.length) return void 0;
767
+ const known = (n) => OTEL_EXPORTERS.includes(n);
768
+ const unknown = names.filter((n) => n !== "none" && !known(n));
769
+ const exporters = names.filter(known);
770
+ const supported = `${OTEL_EXPORTERS.join(", ")} or none`;
771
+ if (names.includes("none")) {
772
+ if (names.length > 1)
773
+ warn(
774
+ `Bridge: ${name}=${JSON.stringify(value)} names none with other exporters: exporting nothing.
775
+ `
776
+ );
777
+ return "none";
778
+ }
779
+ if (unknown.length)
780
+ warn(
781
+ `Bridge: ${name}=${JSON.stringify(value)}: ignoring ${unknown.join(", ")}; Bridge has ${supported}.${exporters.length ? "" : ` Leaving ${name} unset.`}
782
+ `
783
+ );
784
+ if (!exporters.length) return void 0;
785
+ return exporters.length === 1 ? exporters[0] : exporters;
786
+ }
787
+ function loadEnvironment(options = {}) {
788
+ const input = { ...options.env ?? process.env };
789
+ const warn = options.warn ?? ((message) => process.stderr.write(message));
790
+ for (const { bridge, generic, normalize: normalize2, expected } of SHARED_SETTINGS) {
791
+ if (input[bridge]?.trim() === "") delete input[bridge];
792
+ else if (input[bridge] !== void 0) input[bridge] = normalize2(input[bridge]) ?? input[bridge];
793
+ const value = input[generic];
794
+ if (value === void 0) continue;
795
+ const normalized = normalize2(value);
796
+ if (normalized !== void 0) {
797
+ input[generic] = normalized;
798
+ continue;
799
+ }
800
+ delete input[generic];
801
+ if (value.trim() !== "" && input[bridge] === void 0) {
802
+ warn(
803
+ `Bridge: ignoring ${generic}=${JSON.stringify(value)}: Bridge reads ${expected}. Set ${bridge} to choose one for Bridge.
804
+ `
805
+ );
806
+ }
807
+ }
808
+ const logsExporter = parseOtelExporters("OTEL_LOGS_EXPORTER", input.OTEL_LOGS_EXPORTER, warn);
809
+ delete input.OTEL_LOGS_EXPORTER;
810
+ const env3 = EnvironmentSchema.parse(input);
811
+ if (logsExporter !== void 0) env3.OTEL_LOGS_EXPORTER = logsExporter;
812
+ return env3;
813
+ }
814
+ function mergeEnvironment(config, env3) {
815
+ const merged = ConfigSchema.parse(config);
816
+ const backend = env3.BRIDGE_BACKEND;
817
+ const logLevel = env3.BRIDGE_LOG_LEVEL ?? env3.LOG_LEVEL;
818
+ const port = env3.BRIDGE_PORT;
819
+ const transport = env3.BRIDGE_TRANSPORT ?? env3.TRANSPORT;
820
+ if (env3.ANTHROPIC_API_KEY && merged.backends.anthropic) {
821
+ merged.backends.anthropic.apiKey = env3.ANTHROPIC_API_KEY;
822
+ }
823
+ if (env3.OPENAI_API_KEY && merged.backends.openai) {
824
+ merged.backends.openai.apiKey = env3.OPENAI_API_KEY;
825
+ }
826
+ if (merged.backends.grok) {
827
+ if (env3.GROK_COMMAND) merged.backends.grok.command = env3.GROK_COMMAND;
828
+ }
829
+ if (env3.CODEX_COMMAND) {
830
+ merged.backends.codex = {
831
+ args: ["app-server", "--listen", "stdio://"],
832
+ ...merged.backends.codex,
833
+ command: env3.CODEX_COMMAND
834
+ };
835
+ }
836
+ if (backend) {
837
+ merged.proxy.defaultBackend = backend;
838
+ }
839
+ if (logLevel) {
840
+ merged.logging.level = logLevel;
841
+ }
842
+ if (env3.BRIDGE_LOG_FILE) {
843
+ merged.logging.file = env3.BRIDGE_LOG_FILE;
844
+ }
845
+ if (env3.BRIDGE_LOG_FORMAT) {
846
+ merged.logging.format = env3.BRIDGE_LOG_FORMAT;
847
+ merged.logging.pretty = env3.BRIDGE_LOG_FORMAT === "pretty";
848
+ }
849
+ if (env3.BRIDGE_TELEMETRY_ENABLED !== void 0) {
850
+ merged.telemetry.enabled = env3.BRIDGE_TELEMETRY_ENABLED;
851
+ }
852
+ if (env3.BRIDGE_TELEMETRY_LOGS_EXPORT !== void 0) {
853
+ merged.telemetry.logs.export = env3.BRIDGE_TELEMETRY_LOGS_EXPORT;
854
+ }
855
+ if (env3.OTEL_LOGS_EXPORTER !== void 0) {
856
+ merged.telemetry.logs.exporter = env3.OTEL_LOGS_EXPORTER;
857
+ }
858
+ if (env3.OTEL_SERVICE_NAME) {
859
+ merged.telemetry.serviceName = env3.OTEL_SERVICE_NAME;
860
+ }
861
+ if (env3.OTEL_EXPORTER_OTLP_ENDPOINT) {
862
+ merged.telemetry.otlpEndpoint = env3.OTEL_EXPORTER_OTLP_ENDPOINT;
863
+ }
864
+ if (port) {
865
+ merged.server.port = port;
866
+ }
867
+ if (env3.BRIDGE_ALLOWED_ORIGINS !== void 0) {
868
+ merged.server.allowedOrigins = env3.BRIDGE_ALLOWED_ORIGINS.split(",").map((origin) => origin.trim()).filter(Boolean);
869
+ }
870
+ if (env3.BRIDGE_MCP_ALLOWED_HOSTS !== void 0) {
871
+ merged.server.mcpAllowedHosts = env3.BRIDGE_MCP_ALLOWED_HOSTS.split(",").map((host) => host.trim()).filter(Boolean);
872
+ }
873
+ if (env3.BRIDGE_HTTP_TOKEN) {
874
+ merged.server.httpToken = env3.BRIDGE_HTTP_TOKEN;
875
+ }
876
+ if (transport) {
877
+ merged.server.transport = transport;
878
+ }
879
+ if (env3.BRIDGE_ACP_PROTOCOLS !== void 0 && env3.BRIDGE_ACP_PROTOCOLS !== "") {
880
+ merged.server.acpProtocols = parseAcpProtocols(
881
+ env3.BRIDGE_ACP_PROTOCOLS,
882
+ "BRIDGE_ACP_PROTOCOLS"
883
+ );
884
+ }
885
+ return merged;
886
+ }
887
+ function validateConfig(config) {
888
+ return ConfigSchema.parse(config);
889
+ }
890
+ function generateDefaultConfig() {
891
+ return ConfigSchema.parse({
892
+ proxy: {
893
+ defaultBackend: "openai"
894
+ },
895
+ backends: {
896
+ anthropic: {
897
+ defaultModel: "claude-sonnet-4-20250514",
898
+ maxRetries: 3,
899
+ timeoutMs: 12e4
900
+ },
901
+ grok: {
902
+ command: "grok",
903
+ args: ["agent", "stdio"]
904
+ }
905
+ },
906
+ server: {
907
+ port: 6809,
908
+ host: "localhost",
909
+ transport: "stdio"
910
+ },
911
+ graph: {
912
+ defaultGraph: "graphs/default.json",
913
+ graphDir: "graphs"
914
+ },
915
+ logging: {
916
+ level: "info",
917
+ pretty: false,
918
+ format: "json",
919
+ stderr: true
920
+ },
921
+ telemetry: {},
922
+ reduction: {}
923
+ });
924
+ }
925
+ var LOG_LEVELS, TRANSPORTS, SHARED_SETTINGS;
926
+ var init_loader = __esm({
927
+ "packages/config/src/loader.ts"() {
928
+ "use strict";
929
+ init_schema();
930
+ init_trust();
931
+ LOG_LEVELS = /* @__PURE__ */ new Map([
932
+ ["debug", "debug"],
933
+ ["trace", "debug"],
934
+ ["info", "info"],
935
+ ["warn", "warn"],
936
+ ["warning", "warn"],
937
+ ["error", "error"],
938
+ ["fatal", "error"]
939
+ ]);
940
+ TRANSPORTS = /* @__PURE__ */ new Map([
941
+ ["stdio", "stdio"],
942
+ ["http", "http"],
943
+ ["pi-rpc", "pi-rpc"]
944
+ ]);
945
+ SHARED_SETTINGS = [
946
+ {
947
+ bridge: "BRIDGE_LOG_LEVEL",
948
+ generic: "LOG_LEVEL",
949
+ normalize: normalizeLogLevel,
950
+ expected: "debug, info, warn or error"
951
+ },
952
+ {
953
+ bridge: "BRIDGE_TRANSPORT",
954
+ generic: "TRANSPORT",
955
+ normalize: normalizeTransport,
956
+ expected: "stdio, http or pi-rpc"
957
+ }
958
+ ];
959
+ }
960
+ });
961
+
962
+ // packages/config/src/index.ts
963
+ var init_src2 = __esm({
964
+ "packages/config/src/index.ts"() {
965
+ init_schema();
966
+ init_loader();
967
+ init_trust();
968
+ }
969
+ });
970
+
17
971
  // packages/nodes/src/sockets.ts
18
972
  import { ClassicPreset } from "rete";
19
973
  var PipelineSocket, ControlSocket, ConfigSocket, Sockets;
@@ -171,83 +1125,6 @@ var init_log_summary = __esm({
171
1125
  }
172
1126
  });
173
1127
 
174
- // packages/core/src/safe-pattern.ts
175
- function unsafePatternReason(pattern) {
176
- try {
177
- new RegExp(pattern);
178
- } catch {
179
- return "not a valid regular expression";
180
- }
181
- const groups = [
182
- { quantified: false, alternation: false }
183
- ];
184
- const quantifierAt = (i) => {
185
- const c = pattern[i];
186
- if (c === "*" || c === "+") return { length: 1, repeats: true };
187
- if (c === "?") return { length: 1, repeats: false };
188
- if (c === "{") {
189
- const m = /^\{(\d+)(,(\d*))?\}/.exec(pattern.slice(i));
190
- if (!m) return { length: 0, repeats: false };
191
- const max = m[2] === void 0 ? Number(m[1]) : m[3] === "" ? Infinity : Number(m[3]);
192
- return { length: m[0].length, repeats: max > 1 };
193
- }
194
- return { length: 0, repeats: false };
195
- };
196
- for (let i = 0; i < pattern.length; i++) {
197
- const c = pattern[i];
198
- const top = groups[groups.length - 1];
199
- if (c === "\\") {
200
- const next = pattern[i + 1] ?? "";
201
- if (/[1-9]/.test(next) || next === "k") return "backreferences are not allowed";
202
- i++;
203
- continue;
204
- }
205
- if (c === "[") {
206
- for (i++; i < pattern.length && pattern[i] !== "]"; i++) if (pattern[i] === "\\") i++;
207
- continue;
208
- }
209
- if (c === "(") {
210
- groups.push({ quantified: false, alternation: false });
211
- if (pattern[i + 1] === "?") {
212
- const m = /^\?(<[A-Za-z_$][\w$]*>|<=|<!|[:=!])/.exec(pattern.slice(i + 1));
213
- if (m) i += m[0].length;
214
- }
215
- continue;
216
- }
217
- if (c === "|") {
218
- top.alternation = true;
219
- continue;
220
- }
221
- if (c === ")") {
222
- if (groups.length === 1) continue;
223
- const group = groups.pop();
224
- const parent = groups[groups.length - 1];
225
- const quantifier2 = quantifierAt(i + 1);
226
- if (quantifier2.repeats && (group.quantified || group.alternation))
227
- return "a repeated group that contains a quantifier or alternation can take exponential time. Drop the repeat around the group (`^(Read|Edit) ` rather than `(Read|Edit)+`), or repeat a character class instead (`[a-z]+` rather than `(a|b)+`, `\\w+` rather than `(\\w+)+`)";
228
- if (group.quantified) parent.quantified = true;
229
- if (group.alternation) parent.alternation = true;
230
- continue;
231
- }
232
- const quantifier = quantifierAt(i);
233
- if (quantifier.length > 0) {
234
- top.quantified = true;
235
- i += quantifier.length - 1;
236
- }
237
- }
238
- return void 0;
239
- }
240
- function compileSafePattern(pattern, what) {
241
- const reason = unsafePatternReason(pattern);
242
- if (reason) throw new Error(`${what} ${JSON.stringify(pattern)} is refused: ${reason}`);
243
- return new RegExp(pattern);
244
- }
245
- var init_safe_pattern = __esm({
246
- "packages/core/src/safe-pattern.ts"() {
247
- "use strict";
248
- }
249
- });
250
-
251
1128
  // packages/nodes/src/catalog/references.ts
252
1129
  function isConfigReference(value) {
253
1130
  return isRecord(value) && (Object.hasOwn(value, "$config") || Object.hasOwn(value, "$env") || Object.hasOwn(value, "$default"));
@@ -278,7 +1155,7 @@ var init_references = __esm({
278
1155
  });
279
1156
 
280
1157
  // packages/nodes/src/catalog/schemas.ts
281
- import { z } from "zod";
1158
+ import { z as z3 } from "zod";
282
1159
  function configProblems(schema, config, options = {}) {
283
1160
  const references = options.references === "opaque" ? referencePaths(config) : [];
284
1161
  const result = schema.safeParse(references.length ? withoutReferences(config) : config);
@@ -302,23 +1179,23 @@ var init_schemas = __esm({
302
1179
  "use strict";
303
1180
  init_safe_pattern();
304
1181
  init_references();
305
- positiveInt = z.number().int().positive();
306
- sessionRepository = z.custom(
1182
+ positiveInt = z3.number().int().positive();
1183
+ sessionRepository = z3.custom(
307
1184
  (value) => typeof value === "object" && value !== null && ["get", "create", "update"].every(
308
1185
  (method) => typeof value[method] === "function"
309
1186
  ),
310
1187
  { message: "must have get, create and update methods" }
311
1188
  );
312
- fn = z.custom((value) => typeof value === "function", {
1189
+ fn = z3.custom((value) => typeof value === "function", {
313
1190
  message: "must be a function"
314
1191
  });
315
1192
  thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh"];
316
- piTranslator = () => z.looseObject({
317
- defaultThinkingLevel: z.enum(thinkingLevels, {
1193
+ piTranslator = () => z3.looseObject({
1194
+ defaultThinkingLevel: z3.enum(thinkingLevels, {
318
1195
  error: `defaultThinkingLevel must be one of ${thinkingLevels.join(", ")}`
319
1196
  }).optional(),
320
- defaultProvider: z.string().min(1).optional(),
321
- defaultModel: z.string().min(1).optional()
1197
+ defaultProvider: z3.string().min(1).optional(),
1198
+ defaultModel: z3.string().min(1).optional()
322
1199
  }).refine(
323
1200
  (config) => config.defaultProvider === void 0 === (config.defaultModel === void 0),
324
1201
  {
@@ -326,126 +1203,126 @@ var init_schemas = __esm({
326
1203
  }
327
1204
  );
328
1205
  grokBackend = {
329
- command: z.string().min(1).optional(),
330
- args: z.array(z.string()).optional(),
331
- env: z.record(z.string(), z.string()).optional(),
1206
+ command: z3.string().min(1).optional(),
1207
+ args: z3.array(z3.string()).optional(),
1208
+ env: z3.record(z3.string(), z3.string()).optional(),
332
1209
  /** 0: no limit. */
333
- requestTimeoutMs: z.number().int().nonnegative().optional()
1210
+ requestTimeoutMs: z3.number().int().nonnegative().optional()
334
1211
  };
335
1212
  configSchemas = {
336
- "OpenAI Translator": z.looseObject({
337
- defaultModel: z.string().min(1).optional(),
1213
+ "OpenAI Translator": z3.looseObject({
1214
+ defaultModel: z3.string().min(1).optional(),
338
1215
  defaultMaxTokens: positiveInt.optional(),
339
- defaultTemperature: z.number().min(0).max(2).optional()
1216
+ defaultTemperature: z3.number().min(0).max(2).optional()
340
1217
  }),
341
- "OpenAI Client": z.looseObject({
342
- apiKey: z.string().optional(),
343
- organization: z.string().optional(),
344
- baseURL: z.url().optional(),
1218
+ "OpenAI Client": z3.looseObject({
1219
+ apiKey: z3.string().optional(),
1220
+ organization: z3.string().optional(),
1221
+ baseURL: z3.url().optional(),
345
1222
  timeout: positiveInt.optional(),
346
- maxRetries: z.number().int().min(0).optional(),
1223
+ maxRetries: z3.number().int().min(0).optional(),
347
1224
  maxToolIterations: positiveInt.optional(),
348
- toolMode: z.enum(["native", "none"]).optional(),
349
- streamUsage: z.boolean().optional()
1225
+ toolMode: z3.enum(["native", "none"]).optional(),
1226
+ streamUsage: z3.boolean().optional()
350
1227
  }),
351
- "OpenAI Normalizer": z.looseObject({
352
- includeModel: z.boolean().optional(),
353
- includeId: z.boolean().optional()
1228
+ "OpenAI Normalizer": z3.looseObject({
1229
+ includeModel: z3.boolean().optional(),
1230
+ includeId: z3.boolean().optional()
354
1231
  }),
355
- "Tool Executor": z.looseObject({
1232
+ "Tool Executor": z3.looseObject({
356
1233
  maxConsecutiveDuplicates: positiveInt.optional()
357
1234
  }),
358
1235
  // ReductionSettings (`[reduction]`, each execution's ctx.reduction); what is set here wins.
359
- "Tool Result Reducer": z.looseObject({
360
- enabled: z.boolean().optional(),
1236
+ "Tool Result Reducer": z3.looseObject({
1237
+ enabled: z3.boolean().optional(),
361
1238
  maxInlineChars: positiveInt.optional(),
362
- storeArtifacts: z.boolean().optional(),
363
- artifactDir: z.string().min(1).optional(),
1239
+ storeArtifacts: z3.boolean().optional(),
1240
+ artifactDir: z3.string().min(1).optional(),
364
1241
  artifactMaxCount: positiveInt.optional(),
365
1242
  artifactMaxBytes: positiveInt.optional(),
366
- artifactMaxAgeDays: z.number().positive().optional(),
367
- recordStats: z.boolean().optional(),
368
- preserveFileReads: z.boolean().optional(),
369
- projectRulesDir: z.string().min(1).optional(),
370
- tokenjuiceRulesDir: z.string().min(1).optional(),
1243
+ artifactMaxAgeDays: z3.number().positive().optional(),
1244
+ recordStats: z3.boolean().optional(),
1245
+ preserveFileReads: z3.boolean().optional(),
1246
+ projectRulesDir: z3.string().min(1).optional(),
1247
+ tokenjuiceRulesDir: z3.string().min(1).optional(),
371
1248
  isSessionOpen: fn.optional(),
372
1249
  // Compiled rules, from code (they hold regular expressions); a graph names rule directories.
373
- rules: z.array(z.record(z.string(), z.unknown())).optional()
1250
+ rules: z3.array(z3.record(z3.string(), z3.unknown())).optional()
374
1251
  }),
375
- "Content Accumulator": z.looseObject({
376
- includeThinking: z.boolean().optional(),
1252
+ "Content Accumulator": z3.looseObject({
1253
+ includeThinking: z3.boolean().optional(),
377
1254
  maxBlocks: positiveInt.optional(),
378
- debug: z.boolean().optional()
1255
+ debug: z3.boolean().optional()
379
1256
  }),
380
- "Session Load": z.looseObject({
1257
+ "Session Load": z3.looseObject({
381
1258
  repository: sessionRepository.optional(),
382
- cwd: z.string().min(1).optional()
1259
+ cwd: z3.string().min(1).optional()
383
1260
  }),
384
- "History Window": z.looseObject({
385
- maxEntries: z.number().int().min(0).optional()
1261
+ "History Window": z3.looseObject({
1262
+ maxEntries: z3.number().int().min(0).optional()
386
1263
  }),
387
- "CWD Context": z.looseObject({
388
- cwd: z.string().min(1).optional(),
389
- enabled: z.boolean().optional()
1264
+ "CWD Context": z3.looseObject({
1265
+ cwd: z3.string().min(1).optional(),
1266
+ enabled: z3.boolean().optional()
390
1267
  }),
391
- "Session Persistence": z.looseObject({
1268
+ "Session Persistence": z3.looseObject({
392
1269
  repository: sessionRepository.optional()
393
1270
  }),
394
- "ACP Endpoint": z.looseObject({
395
- transport: z.enum(["stdio"], { error: "transport must be stdio (more later)" }).optional(),
1271
+ "ACP Endpoint": z3.looseObject({
1272
+ transport: z3.enum(["stdio"], { error: "transport must be stdio (more later)" }).optional(),
396
1273
  interactionTimeoutMs: positiveInt.optional()
397
1274
  }),
398
- "ACP Client": z.looseObject({
399
- command: z.string().min(1).optional(),
400
- args: z.array(z.string()).optional(),
401
- env: z.record(z.string(), z.string()).optional(),
402
- cwd: z.string().min(1).optional(),
403
- capabilities: z.object({
404
- client: z.object({ remove: z.array(z.string()).optional() }).optional(),
405
- agent: z.object({
406
- remove: z.array(z.string()).optional(),
407
- set: z.record(z.string(), z.unknown()).optional()
1275
+ "ACP Client": z3.looseObject({
1276
+ command: z3.string().min(1).optional(),
1277
+ args: z3.array(z3.string()).optional(),
1278
+ env: z3.record(z3.string(), z3.string()).optional(),
1279
+ cwd: z3.string().min(1).optional(),
1280
+ capabilities: z3.object({
1281
+ client: z3.object({ remove: z3.array(z3.string()).optional() }).optional(),
1282
+ agent: z3.object({
1283
+ remove: z3.array(z3.string()).optional(),
1284
+ set: z3.record(z3.string(), z3.unknown()).optional()
408
1285
  }).optional()
409
1286
  }).optional(),
410
- serveV2: z.boolean().optional(),
411
- protocols: z.array(z.union([z.literal(1), z.literal(2)])).min(1).optional()
1287
+ serveV2: z3.boolean().optional(),
1288
+ protocols: z3.array(z3.union([z3.literal(1), z3.literal(2)])).min(1).optional()
412
1289
  }),
413
- "Session MCP Tools": z.looseObject({}),
414
- "Telemetry Sink": z.looseObject({
415
- recordTypes: z.array(z.string().min(1)).optional(),
416
- spans: z.boolean().optional(),
417
- continueClientTrace: z.boolean().optional()
1290
+ "Session MCP Tools": z3.looseObject({}),
1291
+ "Telemetry Sink": z3.looseObject({
1292
+ recordTypes: z3.array(z3.string().min(1)).optional(),
1293
+ spans: z3.boolean().optional(),
1294
+ continueClientTrace: z3.boolean().optional()
418
1295
  }),
419
- "MCP Endpoint": z.looseObject({
420
- transport: z.enum(["stdio"], { error: "transport must be stdio (more later)" }).optional(),
1296
+ "MCP Endpoint": z3.looseObject({
1297
+ transport: z3.enum(["stdio"], { error: "transport must be stdio (more later)" }).optional(),
421
1298
  interactionTimeoutMs: positiveInt.optional()
422
1299
  }),
423
- "Turn Limits": z.looseObject({
424
- limits: z.object({
425
- maxTurnSeconds: z.number().positive().optional(),
426
- idleSeconds: z.number().positive().optional(),
427
- maxToolCalls: z.number().int().nonnegative().optional()
1300
+ "Turn Limits": z3.looseObject({
1301
+ limits: z3.object({
1302
+ maxTurnSeconds: z3.number().positive().optional(),
1303
+ idleSeconds: z3.number().positive().optional(),
1304
+ maxToolCalls: z3.number().int().nonnegative().optional()
428
1305
  }).optional()
429
1306
  }),
430
- "Agent Sessions": z.looseObject({}),
431
- "Pi Endpoint": z.looseObject({
432
- transport: z.enum(["stdio"], { error: "transport must be stdio" }).optional()
1307
+ "Agent Sessions": z3.looseObject({}),
1308
+ "Pi Endpoint": z3.looseObject({
1309
+ transport: z3.enum(["stdio"], { error: "transport must be stdio" }).optional()
433
1310
  }),
434
- "Pi Commands": z.looseObject({ cwd: z.string().min(1).optional() }),
435
- "Pi Projection": z.looseObject({}),
436
- "Pi Responder": z.looseObject({}),
437
- "Ideal Admission": z.looseObject({
438
- sessionCodeExec: z.string().min(1).optional(),
439
- agentName: z.string().min(1).optional(),
440
- agentTitle: z.string().min(1).optional()
1311
+ "Pi Commands": z3.looseObject({ cwd: z3.string().min(1).optional() }),
1312
+ "Pi Projection": z3.looseObject({}),
1313
+ "Pi Responder": z3.looseObject({}),
1314
+ "Ideal Admission": z3.looseObject({
1315
+ sessionCodeExec: z3.string().min(1).optional(),
1316
+ agentName: z3.string().min(1).optional(),
1317
+ agentTitle: z3.string().min(1).optional()
441
1318
  }),
442
- "Ideal Projection": z.looseObject({}),
443
- "MCP Responder": z.looseObject({}),
444
- "Permission Policy": z.looseObject({
445
- rules: z.array(
446
- z.object({
447
- kind: z.string().min(1).optional(),
448
- title: z.string().superRefine((pattern, check2) => {
1319
+ "Ideal Projection": z3.looseObject({}),
1320
+ "MCP Responder": z3.looseObject({}),
1321
+ "Permission Policy": z3.looseObject({
1322
+ rules: z3.array(
1323
+ z3.object({
1324
+ kind: z3.string().min(1).optional(),
1325
+ title: z3.string().superRefine((pattern, check2) => {
449
1326
  const reason = unsafePatternReason(pattern);
450
1327
  if (reason)
451
1328
  check2.addIssue({
@@ -453,130 +1330,130 @@ var init_schemas = __esm({
453
1330
  message: reason === "not a valid regular expression" ? "title must be a valid regular expression" : `title is refused: ${reason}`
454
1331
  });
455
1332
  }).optional(),
456
- decision: z.enum(["allow", "deny", "ask"], {
1333
+ decision: z3.enum(["allow", "deny", "ask"], {
457
1334
  error: "decision must be allow, deny or ask"
458
1335
  })
459
1336
  })
460
1337
  ).optional(),
461
- default: z.enum(["allow", "deny", "ask", "session"], {
1338
+ default: z3.enum(["allow", "deny", "ask", "session"], {
462
1339
  error: "default must be allow, deny, ask or session"
463
1340
  }).optional()
464
1341
  }),
465
- "ACP Normalizer": z.looseObject({
466
- agentName: z.string().min(1).optional(),
467
- agentTitle: z.string().min(1).optional(),
468
- agentVersion: z.string().min(1).optional(),
469
- agentCapabilities: z.record(z.string(), z.unknown()).optional(),
470
- protocols: z.array(z.union([z.literal(1), z.literal(2)])).min(1).optional()
1342
+ "ACP Normalizer": z3.looseObject({
1343
+ agentName: z3.string().min(1).optional(),
1344
+ agentTitle: z3.string().min(1).optional(),
1345
+ agentVersion: z3.string().min(1).optional(),
1346
+ agentCapabilities: z3.record(z3.string(), z3.unknown()).optional(),
1347
+ protocols: z3.array(z3.union([z3.literal(1), z3.literal(2)])).min(1).optional()
471
1348
  }),
472
- "ACP Responder": z.looseObject({}),
473
- "Prompt Messages": z.looseObject({
474
- systemPrompt: z.string().optional()
1349
+ "ACP Responder": z3.looseObject({}),
1350
+ "Prompt Messages": z3.looseObject({
1351
+ systemPrompt: z3.string().optional()
475
1352
  }),
476
- "Update Projection": z.looseObject({}),
477
- "Claude SDK Client": z.looseObject({
478
- model: z.string().min(1).optional(),
479
- permissionMode: z.enum(["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"]).optional(),
480
- cwd: z.string().optional(),
481
- pathToClaudeCodeExecutable: z.string().optional(),
1353
+ "Update Projection": z3.looseObject({}),
1354
+ "Claude SDK Client": z3.looseObject({
1355
+ model: z3.string().min(1).optional(),
1356
+ permissionMode: z3.enum(["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"]).optional(),
1357
+ cwd: z3.string().optional(),
1358
+ pathToClaudeCodeExecutable: z3.string().optional(),
482
1359
  cancelGraceMs: positiveInt.optional(),
483
- terminalOutput: z.enum(["delta", "snapshot", "none"], {
1360
+ terminalOutput: z3.enum(["delta", "snapshot", "none"], {
484
1361
  error: "terminalOutput must be one of 'delta', 'snapshot', or 'none'"
485
1362
  }).optional(),
486
1363
  taskOutputPollMs: positiveInt.optional(),
487
- keepEnv: z.array(z.string()).optional()
1364
+ keepEnv: z3.array(z3.string()).optional()
488
1365
  }),
489
- "Claude SDK Normalizer": z.looseObject({
490
- includeRawEvents: z.boolean().optional()
1366
+ "Claude SDK Normalizer": z3.looseObject({
1367
+ includeRawEvents: z3.boolean().optional()
491
1368
  }),
492
- "Claude SDK Sessions": z.looseObject({}),
493
- "Claude SDK Translator": z.looseObject({}),
494
- "Codex Client": z.looseObject({
495
- command: z.string().min(1).optional(),
496
- args: z.array(z.string()).optional(),
497
- env: z.record(z.string(), z.string()).optional(),
498
- cwd: z.string().optional(),
499
- model: z.string().min(1).optional(),
500
- mode: z.enum(["default", "read-only", "auto", "full-access"]).optional(),
501
- allowFullAccess: z.boolean().optional(),
502
- dynamicTools: z.boolean().optional(),
503
- cancelGraceMs: z.number().int().nonnegative().optional(),
504
- requestTimeoutMs: z.number().int().nonnegative().optional(),
505
- terminalOutput: z.enum(["delta", "snapshot", "none"], {
1369
+ "Claude SDK Sessions": z3.looseObject({}),
1370
+ "Claude SDK Translator": z3.looseObject({}),
1371
+ "Codex Client": z3.looseObject({
1372
+ command: z3.string().min(1).optional(),
1373
+ args: z3.array(z3.string()).optional(),
1374
+ env: z3.record(z3.string(), z3.string()).optional(),
1375
+ cwd: z3.string().optional(),
1376
+ model: z3.string().min(1).optional(),
1377
+ mode: z3.enum(["default", "read-only", "auto", "full-access"]).optional(),
1378
+ allowFullAccess: z3.boolean().optional(),
1379
+ dynamicTools: z3.boolean().optional(),
1380
+ cancelGraceMs: z3.number().int().nonnegative().optional(),
1381
+ requestTimeoutMs: z3.number().int().nonnegative().optional(),
1382
+ terminalOutput: z3.enum(["delta", "snapshot", "none"], {
506
1383
  error: "terminalOutput must be one of 'delta', 'snapshot', or 'none'"
507
1384
  }).optional()
508
1385
  }),
509
- "Codex Normalizer": z.looseObject({
510
- includeRawEvents: z.boolean().optional()
1386
+ "Codex Normalizer": z3.looseObject({
1387
+ includeRawEvents: z3.boolean().optional()
511
1388
  }),
512
- "Codex Sessions": z.looseObject({}),
513
- "Codex Translator": z.looseObject({}),
514
- "Anthropic Adapter": z.looseObject({
1389
+ "Codex Sessions": z3.looseObject({}),
1390
+ "Codex Translator": z3.looseObject({}),
1391
+ "Anthropic Adapter": z3.looseObject({
515
1392
  // Empty is the constructor's default: ANTHROPIC_API_KEY is used then.
516
- apiKey: z.string().optional(),
517
- defaultModel: z.string().min(1).optional(),
1393
+ apiKey: z3.string().optional(),
1394
+ defaultModel: z3.string().min(1).optional(),
518
1395
  maxTokens: positiveInt.optional()
519
1396
  }),
520
- "Anthropic Translator": z.looseObject({
521
- defaultModel: z.string().min(1).optional(),
1397
+ "Anthropic Translator": z3.looseObject({
1398
+ defaultModel: z3.string().min(1).optional(),
522
1399
  defaultMaxTokens: positiveInt.optional(),
523
- defaultTemperature: z.number().min(0).max(1).optional()
1400
+ defaultTemperature: z3.number().min(0).max(1).optional()
524
1401
  }),
525
- "Anthropic Client": z.looseObject({
526
- apiKey: z.string().optional(),
527
- baseURL: z.url().optional(),
1402
+ "Anthropic Client": z3.looseObject({
1403
+ apiKey: z3.string().optional(),
1404
+ baseURL: z3.url().optional(),
528
1405
  timeout: positiveInt.optional(),
529
- maxRetries: z.number().int().min(0).optional()
1406
+ maxRetries: z3.number().int().min(0).optional()
530
1407
  }),
531
- "Anthropic Normalizer": z.looseObject({
532
- includeModel: z.boolean().optional(),
533
- includeId: z.boolean().optional()
1408
+ "Anthropic Normalizer": z3.looseObject({
1409
+ includeModel: z3.boolean().optional(),
1410
+ includeId: z3.boolean().optional()
534
1411
  }),
535
1412
  // Reads no config (the process is the client's).
536
- "Grok Translator": z.looseObject({}),
537
- "Grok Client": z.looseObject({
1413
+ "Grok Translator": z3.looseObject({}),
1414
+ "Grok Client": z3.looseObject({
538
1415
  ...grokBackend,
539
- sessionIsolation: z.boolean().optional(),
1416
+ sessionIsolation: z3.boolean().optional(),
540
1417
  // Test hooks (GrokClientConfig): one process, driven directly.
541
1418
  _processFactory: fn.optional(),
542
- _testResponses: z.array(z.record(z.string(), z.unknown())).optional()
1419
+ _testResponses: z3.array(z3.record(z3.string(), z3.unknown())).optional()
543
1420
  }),
544
- "Grok Normalizer": z.looseObject({}),
1421
+ "Grok Normalizer": z3.looseObject({}),
545
1422
  "Pi Translator": piTranslator(),
546
- "Pi Client": z.looseObject({
547
- cwd: z.string().min(1).optional(),
548
- piCommand: z.string().min(1).optional(),
549
- sessionPath: z.string().min(1).optional(),
1423
+ "Pi Client": z3.looseObject({
1424
+ cwd: z3.string().min(1).optional(),
1425
+ piCommand: z3.string().min(1).optional(),
1426
+ sessionPath: z3.string().min(1).optional(),
550
1427
  /** 0: no limit. */
551
- requestTimeoutMs: z.number().int().nonnegative().optional()
1428
+ requestTimeoutMs: z3.number().int().nonnegative().optional()
552
1429
  }),
553
- "Pi Normalizer": z.looseObject({
554
- includeRawEvents: z.boolean().optional()
1430
+ "Pi Normalizer": z3.looseObject({
1431
+ includeRawEvents: z3.boolean().optional()
555
1432
  }),
556
1433
  "Pi SDK Translator": piTranslator(),
557
- "Pi SDK Client": z.looseObject({
558
- tools: z.enum(["coding", "readonly", "none"], {
1434
+ "Pi SDK Client": z3.looseObject({
1435
+ tools: z3.enum(["coding", "readonly", "none"], {
559
1436
  error: "tools must be one of 'coding', 'readonly', or 'none'"
560
1437
  }).optional(),
561
- cwd: z.string().min(1).optional(),
562
- exposeToolEvents: z.boolean().optional(),
563
- defaultProvider: z.string().min(1).optional(),
564
- defaultModel: z.string().min(1).optional(),
565
- defaultThinkingLevel: z.enum(thinkingLevels, {
1438
+ cwd: z3.string().min(1).optional(),
1439
+ exposeToolEvents: z3.boolean().optional(),
1440
+ defaultProvider: z3.string().min(1).optional(),
1441
+ defaultModel: z3.string().min(1).optional(),
1442
+ defaultThinkingLevel: z3.enum(thinkingLevels, {
566
1443
  error: `defaultThinkingLevel must be one of ${thinkingLevels.join(", ")}`
567
1444
  }).optional()
568
1445
  }),
569
- "Pi SDK Normalizer": z.looseObject({
570
- includeRawEvents: z.boolean().optional()
1446
+ "Pi SDK Normalizer": z3.looseObject({
1447
+ includeRawEvents: z3.boolean().optional()
571
1448
  }),
572
- "Gemma Reasoning Prompt": z.looseObject({
573
- model: z.string().min(1).optional(),
574
- reasoningMode: z.enum(["auto", "on", "off"], { error: "reasoningMode must be auto, on or off" }).optional()
1449
+ "Gemma Reasoning Prompt": z3.looseObject({
1450
+ model: z3.string().min(1).optional(),
1451
+ reasoningMode: z3.enum(["auto", "on", "off"], { error: "reasoningMode must be auto, on or off" }).optional()
575
1452
  }),
576
1453
  // Reads no config: GemmaToolAdapterConfig's maxIterations is not read (the limit is fixed).
577
- "Gemma Tool Adapter": z.looseObject({}),
578
- "Gemma Finalization JSON Guard": z.looseObject({}),
579
- "Ideal Harness": z.looseObject({})
1454
+ "Gemma Tool Adapter": z3.looseObject({}),
1455
+ "Gemma Finalization JSON Guard": z3.looseObject({}),
1456
+ "Ideal Harness": z3.looseObject({})
580
1457
  };
581
1458
  startsWith = (path2, prefix) => prefix.length <= path2.length && prefix.every((key2, i) => key2 === path2[i]);
582
1459
  }
@@ -1339,7 +2216,7 @@ var init_descriptions = __esm({
1339
2216
  "Claude SDK Sessions": {
1340
2217
  name: "Claude SDK Sessions",
1341
2218
  category: "transform",
1342
- description: "Set up Claude Code sessions: new (with modes, models and config options), load and resume (Claude Code's own sessions, with history replay), and list",
2219
+ description: "Set up Claude Code sessions: new (with modes, models and config options), load and resume (Claude Code's own sessions, with history replay), fork, delete, and list",
1343
2220
  inputs: [{ name: "in", type: "pipeline", label: "Protocol", required: true }],
1344
2221
  outputs: [{ name: "out", type: "pipeline", label: "Protocol" }]
1345
2222
  },
@@ -2562,7 +3439,7 @@ function unwrapMarkdownLink(value) {
2562
3439
  }
2563
3440
  return ANGLE_LINK.exec(trimmed)?.[1];
2564
3441
  }
2565
- function isPlainObject(value) {
3442
+ function isPlainObject2(value) {
2566
3443
  return typeof value === "object" && value !== null && !Array.isArray(value);
2567
3444
  }
2568
3445
  function matchesType(type, value) {
@@ -2570,7 +3447,7 @@ function matchesType(type, value) {
2570
3447
  case void 0:
2571
3448
  return true;
2572
3449
  case "object":
2573
- return isPlainObject(value);
3450
+ return isPlainObject2(value);
2574
3451
  case "array":
2575
3452
  return Array.isArray(value);
2576
3453
  case "string":
@@ -2604,7 +3481,7 @@ function collectIssues(schema, value, segments, optional, issues) {
2604
3481
  );
2605
3482
  return;
2606
3483
  }
2607
- if (isPlainObject(value)) {
3484
+ if (isPlainObject2(value)) {
2608
3485
  const properties = schema.properties ?? {};
2609
3486
  const required = new Set(schema.required ?? []);
2610
3487
  for (const key2 of required) {
@@ -3320,265 +4197,6 @@ var init_client_requests = __esm({
3320
4197
  }
3321
4198
  });
3322
4199
 
3323
- // packages/core/src/acp.ts
3324
- var init_acp = __esm({
3325
- "packages/core/src/acp.ts"() {
3326
- "use strict";
3327
- }
3328
- });
3329
-
3330
- // packages/core/src/types.ts
3331
- var init_types = __esm({
3332
- "packages/core/src/types.ts"() {
3333
- "use strict";
3334
- }
3335
- });
3336
-
3337
- // packages/core/src/meta.ts
3338
- import { z as z2 } from "zod";
3339
- function asRecord(value) {
3340
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3341
- }
3342
- function readTelemetry(value) {
3343
- const telemetry = asRecord(value);
3344
- const rawChars = typeof telemetry?.rawChars === "number" ? telemetry.rawChars : 0;
3345
- const reducedChars = typeof telemetry?.reducedChars === "number" ? telemetry.reducedChars : 0;
3346
- const savedChars = typeof telemetry?.savedChars === "number" ? telemetry.savedChars : 0;
3347
- const toolResultCount = typeof telemetry?.toolResultCount === "number" ? telemetry.toolResultCount : 0;
3348
- const reducers = asRecord(telemetry?.reducers);
3349
- return {
3350
- toolResultCount,
3351
- rawChars,
3352
- reducedChars,
3353
- savedChars,
3354
- retentionRatio: rawChars === 0 ? 1 : reducedChars / rawChars,
3355
- savingsRatio: rawChars === 0 ? 0 : savedChars / rawChars,
3356
- reducers: Object.fromEntries(
3357
- Object.entries(reducers ?? {}).filter((entry) => {
3358
- return typeof entry[1] === "number";
3359
- })
3360
- )
3361
- };
3362
- }
3363
- function recordReductionTelemetry(metadata, reduction) {
3364
- const bridge = asRecord(metadata.bridge) ?? {};
3365
- const current = readTelemetry(bridge.reductionTelemetry);
3366
- const reducerId = reduction.reducerId ?? "unknown";
3367
- const nextRawChars = current.rawChars + reduction.rawChars;
3368
- const nextReducedChars = current.reducedChars + reduction.reducedChars;
3369
- const nextSavedChars = current.savedChars + reduction.savedChars;
3370
- const next = {
3371
- toolResultCount: current.toolResultCount + 1,
3372
- rawChars: nextRawChars,
3373
- reducedChars: nextReducedChars,
3374
- savedChars: nextSavedChars,
3375
- retentionRatio: nextRawChars === 0 ? 1 : nextReducedChars / nextRawChars,
3376
- savingsRatio: nextRawChars === 0 ? 0 : nextSavedChars / nextRawChars,
3377
- reducers: {
3378
- ...current.reducers,
3379
- [reducerId]: (current.reducers[reducerId] ?? 0) + 1
3380
- }
3381
- };
3382
- metadata.bridge = {
3383
- ...bridge,
3384
- reductionTelemetry: next
3385
- };
3386
- return next;
3387
- }
3388
- var ProxyMetaSchema, ReductionTelemetrySchema, BridgeMetaSchema, AnthropicMetaSchema, OpenAIMetaSchema, OllamaMetaSchema, MetadataSchema;
3389
- var init_meta = __esm({
3390
- "packages/core/src/meta.ts"() {
3391
- "use strict";
3392
- ProxyMetaSchema = z2.object({
3393
- version: z2.string().optional(),
3394
- backend: z2.string().optional(),
3395
- model: z2.string().optional(),
3396
- requestId: z2.string().optional(),
3397
- traceId: z2.string().optional(),
3398
- startTime: z2.number().optional(),
3399
- usage: z2.object({
3400
- inputTokens: z2.number().optional(),
3401
- outputTokens: z2.number().optional(),
3402
- totalTokens: z2.number().optional(),
3403
- thinkingTokens: z2.number().optional()
3404
- }).optional(),
3405
- cost: z2.object({
3406
- inputCost: z2.number().optional(),
3407
- outputCost: z2.number().optional(),
3408
- totalCost: z2.number().optional(),
3409
- currency: z2.string().optional()
3410
- }).optional(),
3411
- timing: z2.object({
3412
- queuedMs: z2.number().optional(),
3413
- processingMs: z2.number().optional(),
3414
- totalMs: z2.number().optional()
3415
- }).optional(),
3416
- retryAfterMs: z2.number().optional()
3417
- });
3418
- ReductionTelemetrySchema = z2.object({
3419
- toolResultCount: z2.number(),
3420
- rawChars: z2.number(),
3421
- reducedChars: z2.number(),
3422
- savedChars: z2.number(),
3423
- retentionRatio: z2.number(),
3424
- savingsRatio: z2.number(),
3425
- reducers: z2.record(z2.string(), z2.number())
3426
- });
3427
- BridgeMetaSchema = z2.object({
3428
- reductionTelemetry: ReductionTelemetrySchema.optional()
3429
- });
3430
- AnthropicMetaSchema = z2.object({
3431
- model: z2.string().optional(),
3432
- maxTokens: z2.number().optional(),
3433
- thinking: z2.enum(["disabled", "enabled", "streaming"]).optional(),
3434
- maxThinkingTokens: z2.number().optional(),
3435
- thinkingBlockId: z2.string().optional(),
3436
- thinkingBlockIndex: z2.number().optional(),
3437
- cacheControl: z2.object({
3438
- type: z2.literal("ephemeral"),
3439
- ttl: z2.number().optional()
3440
- }).optional(),
3441
- cacheReadInputTokens: z2.number().optional(),
3442
- cacheCreationInputTokens: z2.number().optional(),
3443
- stopSequences: z2.array(z2.string()).optional(),
3444
- interleaved_thinking: z2.boolean().optional(),
3445
- stopReason: z2.string().optional(),
3446
- stopSequence: z2.string().nullable().optional()
3447
- });
3448
- OpenAIMetaSchema = z2.object({
3449
- model: z2.string().optional(),
3450
- reasoning: z2.object({
3451
- effort: z2.enum(["low", "medium", "high"]),
3452
- summary: z2.enum(["disabled", "auto", "always"]).optional()
3453
- }).optional(),
3454
- reasoningTokens: z2.number().optional(),
3455
- reasoningSummary: z2.boolean().optional(),
3456
- builtinTools: z2.array(
3457
- z2.object({
3458
- type: z2.enum(["web_search", "code_interpreter", "file_search"]),
3459
- config: z2.record(z2.string(), z2.unknown()).optional()
3460
- })
3461
- ).optional(),
3462
- builtinTool: z2.boolean().optional(),
3463
- serverExecuted: z2.boolean().optional(),
3464
- fileIds: z2.array(z2.string()).optional(),
3465
- vectorStoreIds: z2.array(z2.string()).optional(),
3466
- responseFormat: z2.object({
3467
- type: z2.enum(["text", "json_object", "json_schema"]),
3468
- schema: z2.record(z2.string(), z2.unknown()).optional()
3469
- }).optional(),
3470
- prediction: z2.object({
3471
- type: z2.literal("content"),
3472
- content: z2.string()
3473
- }).optional()
3474
- });
3475
- OllamaMetaSchema = z2.object({
3476
- model: z2.string().optional(),
3477
- temperature: z2.number().optional(),
3478
- topP: z2.number().optional(),
3479
- topK: z2.number().optional(),
3480
- repeatPenalty: z2.number().optional(),
3481
- contextLength: z2.number().optional(),
3482
- numPredict: z2.number().optional(),
3483
- numGpu: z2.number().optional(),
3484
- mainGpu: z2.number().optional(),
3485
- keepAlive: z2.string().optional()
3486
- });
3487
- MetadataSchema = z2.object({
3488
- proxy: ProxyMetaSchema.optional(),
3489
- bridge: BridgeMetaSchema.optional(),
3490
- anthropic: AnthropicMetaSchema.optional(),
3491
- openai: OpenAIMetaSchema.optional(),
3492
- ollama: OllamaMetaSchema.optional()
3493
- });
3494
- }
3495
- });
3496
-
3497
- // packages/core/src/errors.ts
3498
- var init_errors = __esm({
3499
- "packages/core/src/errors.ts"() {
3500
- "use strict";
3501
- init_acp();
3502
- }
3503
- });
3504
-
3505
- // packages/core/src/context.ts
3506
- import { randomUUID } from "crypto";
3507
- function createTurnScope(id = randomUUID(), logger) {
3508
- let phase = "running";
3509
- let cancelReason;
3510
- let onFinish;
3511
- let onCancel;
3512
- const ignored = (call) => logger?.debug(`Turn ${call} ignored`, { turnId: id, phase });
3513
- return {
3514
- id,
3515
- store: /* @__PURE__ */ new Map(),
3516
- get phase() {
3517
- return phase;
3518
- },
3519
- finish() {
3520
- if (phase === "finished") return ignored("finish");
3521
- phase = "finished";
3522
- onFinish?.();
3523
- },
3524
- cancel(reason) {
3525
- if (phase !== "running") return ignored("cancel");
3526
- phase = "cancelling";
3527
- cancelReason = reason;
3528
- onCancel?.(reason);
3529
- },
3530
- onFinish(handler) {
3531
- onFinish = handler;
3532
- if (phase === "finished") handler();
3533
- },
3534
- onCancel(handler) {
3535
- onCancel = handler;
3536
- if (phase === "cancelling") handler(cancelReason);
3537
- }
3538
- };
3539
- }
3540
- function turnStore(ctx, key2, create) {
3541
- let store = ctx.turn?.store;
3542
- if (!store) {
3543
- store = contextStores.get(ctx);
3544
- if (!store) contextStores.set(ctx, store = /* @__PURE__ */ new Map());
3545
- }
3546
- if (!store.has(key2)) store.set(key2, create());
3547
- return store.get(key2);
3548
- }
3549
- function sessionCwd(ctx, fallback) {
3550
- return ctx.session?.cwd ?? fallback ?? process.cwd();
3551
- }
3552
- var contextStores;
3553
- var init_context = __esm({
3554
- "packages/core/src/context.ts"() {
3555
- "use strict";
3556
- contextStores = /* @__PURE__ */ new WeakMap();
3557
- }
3558
- });
3559
-
3560
- // packages/core/src/version.ts
3561
- var BRIDGE_VERSION;
3562
- var init_version = __esm({
3563
- "packages/core/src/version.ts"() {
3564
- "use strict";
3565
- BRIDGE_VERSION = "0.3.1";
3566
- }
3567
- });
3568
-
3569
- // packages/core/src/index.ts
3570
- var init_src = __esm({
3571
- "packages/core/src/index.ts"() {
3572
- init_acp();
3573
- init_types();
3574
- init_meta();
3575
- init_errors();
3576
- init_context();
3577
- init_version();
3578
- init_safe_pattern();
3579
- }
3580
- });
3581
-
3582
4200
  // packages/context-reduction/src/types.ts
3583
4201
  var init_types2 = __esm({
3584
4202
  "packages/context-reduction/src/types.ts"() {
@@ -3595,9 +4213,9 @@ var init_validate_rules = __esm({
3595
4213
  });
3596
4214
 
3597
4215
  // packages/context-reduction/src/rules.ts
3598
- import { readdir, readFile, realpath } from "node:fs/promises";
3599
- import { homedir } from "node:os";
3600
- import { isAbsolute, join, relative, resolve } from "node:path";
4216
+ import { readdir, readFile as readFile2, realpath } from "node:fs/promises";
4217
+ import { homedir as homedir2 } from "node:os";
4218
+ import { isAbsolute as isAbsolute3, join as join2, relative, resolve as resolve2 } from "node:path";
3601
4219
  import { loadBuiltinRules } from "tokenjuice";
3602
4220
  function mergeRegexFlags(flags) {
3603
4221
  return [...new Set(`u${flags ?? ""}`.split(""))].join("");
@@ -3668,7 +4286,7 @@ async function listRuleFiles(root) {
3668
4286
  );
3669
4287
  const nested = await Promise.all(
3670
4288
  entries.map(async (entry) => {
3671
- const fullPath = join(currentDir, entry.name);
4289
+ const fullPath = join2(currentDir, entry.name);
3672
4290
  if (entry.isSymbolicLink()) {
3673
4291
  return [];
3674
4292
  }
@@ -3683,7 +4301,7 @@ async function listRuleFiles(root) {
3683
4301
  return [];
3684
4302
  }
3685
4303
  const relativePath = relative(rootRealPath, realFilePath);
3686
- if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
4304
+ if (relativePath.startsWith("..") || isAbsolute3(relativePath)) {
3687
4305
  return [];
3688
4306
  }
3689
4307
  return [realFilePath];
@@ -3698,7 +4316,7 @@ async function loadRuleDescriptors(root, source) {
3698
4316
  const rules = [];
3699
4317
  for (const filePath of files) {
3700
4318
  try {
3701
- const parsed = JSON.parse(await readFile(filePath, "utf8"));
4319
+ const parsed = JSON.parse(await readFile2(filePath, "utf8"));
3702
4320
  assertValidRule(parsed);
3703
4321
  rules.push(compileRule(parsed, source, filePath));
3704
4322
  } catch (error) {
@@ -3730,14 +4348,14 @@ async function loadRules(options = {}) {
3730
4348
  const cwd = options.cwd ?? process.cwd();
3731
4349
  const compiledRules = options.builtinRules === void 0 ? await loadBundledRules() : options.builtinRules.map((rule) => compileRule(rule, "builtin", `builtin:${rule.id}`));
3732
4350
  if (options.includeUser ?? true) {
3733
- const userRulesDir = options.userRulesDir ?? join(homedir(), ".config", "bridge", "reducers");
4351
+ const userRulesDir = options.userRulesDir ?? join2(homedir2(), ".config", "bridge", "reducers");
3734
4352
  compiledRules.push(...await loadRuleDescriptors(userRulesDir, "user"));
3735
4353
  }
3736
4354
  if (options.includeProject ?? true) {
3737
- const projectRulesDir = resolve(cwd, options.projectRulesDir ?? join(".bridge", "reducers"));
3738
- const tokenjuiceRulesDir = resolve(
4355
+ const projectRulesDir = resolve2(cwd, options.projectRulesDir ?? join2(".bridge", "reducers"));
4356
+ const tokenjuiceRulesDir = resolve2(
3739
4357
  cwd,
3740
- options.tokenjuiceRulesDir ?? join(".tokenjuice", "rules")
4358
+ options.tokenjuiceRulesDir ?? join2(".tokenjuice", "rules")
3741
4359
  );
3742
4360
  compiledRules.push(...await loadRuleDescriptors(projectRulesDir, "project"));
3743
4361
  compiledRules.push(...await loadRuleDescriptors(tokenjuiceRulesDir, "project"));
@@ -3796,7 +4414,7 @@ var init_reduce = __esm({
3796
4414
  });
3797
4415
 
3798
4416
  // packages/context-reduction/src/artifacts.ts
3799
- import { mkdir, open, readdir as readdir2, readFile as readFile2, stat, unlink, writeFile } from "node:fs/promises";
4417
+ import { mkdir, open, readdir as readdir2, readFile as readFile3, stat, unlink, writeFile } from "node:fs/promises";
3800
4418
  import { randomUUID as randomUUID2 } from "node:crypto";
3801
4419
  import * as nodePath from "node:path";
3802
4420
  async function artifactSessionId(path2) {
@@ -3939,7 +4557,7 @@ var init_artifacts = __esm({
3939
4557
  return record5.metadata;
3940
4558
  }
3941
4559
  async readArtifact(artifactId) {
3942
- const content2 = await readFile2(this.artifactPath(artifactId), "utf8");
4560
+ const content2 = await readFile3(this.artifactPath(artifactId), "utf8");
3943
4561
  return JSON.parse(content2);
3944
4562
  }
3945
4563
  artifactPath(artifactId) {
@@ -3957,7 +4575,7 @@ var init_artifacts = __esm({
3957
4575
  // packages/context-reduction/src/index.ts
3958
4576
  import { classifyExecution, tokenizeCommand } from "tokenjuice";
3959
4577
  import { loadBuiltinFixtures } from "tokenjuice";
3960
- var init_src2 = __esm({
4578
+ var init_src3 = __esm({
3961
4579
  "packages/context-reduction/src/index.ts"() {
3962
4580
  init_types2();
3963
4581
  init_validate_rules();
@@ -4013,7 +4631,7 @@ var init_result_reducer = __esm({
4013
4631
  "packages/nodes/src/tools/result-reducer.ts"() {
4014
4632
  "use strict";
4015
4633
  init_src();
4016
- init_src2();
4634
+ init_src3();
4017
4635
  init_node();
4018
4636
  init_sockets();
4019
4637
  init_descriptions();
@@ -4857,7 +5475,7 @@ import { spawn } from "node:child_process";
4857
5475
  import * as readline from "node:readline";
4858
5476
  import { randomUUID as randomUUID3 } from "node:crypto";
4859
5477
  import { mkdirSync } from "node:fs";
4860
- import { dirname } from "node:path";
5478
+ import { dirname as dirname2 } from "node:path";
4861
5479
  var PI_REQUEST_TIMEOUT_MS, UNTIMED_COMMANDS, PiRpcClient;
4862
5480
  var init_rpc_client = __esm({
4863
5481
  "packages/nodes/src/pi/rpc-client.ts"() {
@@ -4947,7 +5565,7 @@ var init_rpc_client = __esm({
4947
5565
  const state = await client.getState();
4948
5566
  const sessionFile = state?.sessionFile;
4949
5567
  if (sessionFile && typeof sessionFile === "string") {
4950
- const dir = dirname(sessionFile);
5568
+ const dir = dirname2(sessionFile);
4951
5569
  mkdirSync(dir, { recursive: true });
4952
5570
  }
4953
5571
  } catch (err) {
@@ -7279,7 +7897,7 @@ var init_env = __esm({
7279
7897
  });
7280
7898
 
7281
7899
  // packages/nodes/src/claude-sdk/types.ts
7282
- var CLAUDE_SESSION_START, CLAUDE_SESSION_CONFIGURE, DEFT_STOP_TERMINAL, DEFT_CAPABILITIES, CLAUDE_TERMINAL_STOP, CLAUDE_SESSION_LIST;
7900
+ var CLAUDE_SESSION_START, CLAUDE_SESSION_CONFIGURE, DEFT_STOP_TERMINAL, DEFT_CAPABILITIES, CLAUDE_TERMINAL_STOP, CLAUDE_SESSION_LIST, CLAUDE_SESSION_DELETE, CLAUDE_SESSION_FORK;
7283
7901
  var init_types3 = __esm({
7284
7902
  "packages/nodes/src/claude-sdk/types.ts"() {
7285
7903
  "use strict";
@@ -7289,6 +7907,8 @@ var init_types3 = __esm({
7289
7907
  DEFT_CAPABILITIES = { _meta: { "deft.co": { stopTerminal: {} } } };
7290
7908
  CLAUDE_TERMINAL_STOP = "claude/terminal.stop";
7291
7909
  CLAUDE_SESSION_LIST = "claude/session.list";
7910
+ CLAUDE_SESSION_DELETE = "claude/session.delete";
7911
+ CLAUDE_SESSION_FORK = "claude/session.fork";
7292
7912
  }
7293
7913
  });
7294
7914
 
@@ -8376,7 +8996,13 @@ import { ClassicPreset as ClassicPreset19 } from "rete";
8376
8996
  import {
8377
8997
  query as sdkQuery
8378
8998
  } from "@anthropic-ai/claude-agent-sdk";
8379
- import { getSessionMessages, listSessions } from "@anthropic-ai/claude-agent-sdk";
8999
+ import {
9000
+ deleteSession as sdkDeleteSession,
9001
+ forkSession as sdkForkSession,
9002
+ getSessionInfo,
9003
+ getSessionMessages,
9004
+ listSessions
9005
+ } from "@anthropic-ai/claude-agent-sdk";
8380
9006
  function terminalOutputFor(ctx) {
8381
9007
  if (ctx.connection?.protocol === 2) return "delta";
8382
9008
  const meta = ctx.connection?.clientCapabilities?._meta;
@@ -8444,7 +9070,13 @@ var init_client5 = __esm({
8444
9070
  /** How the node starts its session streams (the engine's source; none outside a front graph). */
8445
9071
  source;
8446
9072
  createQuery = sdkQuery;
8447
- transcripts = { getSessionMessages, listSessions };
9073
+ transcripts = {
9074
+ getSessionMessages,
9075
+ listSessions,
9076
+ getSessionInfo,
9077
+ deleteSession: sdkDeleteSession,
9078
+ forkSession: sdkForkSession
9079
+ };
8448
9080
  constructor(config = {}) {
8449
9081
  super("Claude SDK Client", {
8450
9082
  cancelGraceMs: 5e3,
@@ -8472,7 +9104,9 @@ var init_client5 = __esm({
8472
9104
  useServices(services) {
8473
9105
  const backends = services.backends;
8474
9106
  if (backends?.createClaudeQuery) this.createQuery = backends.createClaudeQuery;
8475
- if (backends?.claudeTranscripts) this.transcripts = backends.claudeTranscripts;
9107
+ if (backends?.claudeTranscripts) {
9108
+ this.transcripts = { ...this.transcripts, ...backends.claudeTranscripts };
9109
+ }
8476
9110
  }
8477
9111
  /** The runtime's source for this node: its session streams start here. */
8478
9112
  startSource(source) {
@@ -8491,6 +9125,10 @@ var init_client5 = __esm({
8491
9125
  return from(this.start(message, ctx)).pipe(mergeMap3((events) => events));
8492
9126
  if (message.type === "request" && message.request.method === CLAUDE_SESSION_LIST)
8493
9127
  return from(this.list(message, ctx));
9128
+ if (message.type === "request" && message.request.method === CLAUDE_SESSION_DELETE)
9129
+ return from(this.deleteSession(message, ctx));
9130
+ if (message.type === "request" && message.request.method === CLAUDE_SESSION_FORK)
9131
+ return from(this.fork(message, ctx)).pipe(mergeMap3((events) => events));
8494
9132
  if (message.type === "request" && message.request.method === CLAUDE_SESSION_CONFIGURE)
8495
9133
  return from(this.configure(message, ctx)).pipe(mergeMap3((events) => events));
8496
9134
  if (message.type === "request" && message.request.method === CLAUDE_TERMINAL_STOP)
@@ -8806,6 +9444,196 @@ var init_client5 = __esm({
8806
9444
  timestamp: Date.now()
8807
9445
  };
8808
9446
  }
9447
+ /** `session/delete`: delete Claude Code's stored session transcript and close any open session. */
9448
+ async deleteSession(message, ctx) {
9449
+ const params = message.request.params;
9450
+ const closeLocal = async () => {
9451
+ if (ctx.sessions?.get(params.sessionId)) {
9452
+ await ctx.sessions.close(params.sessionId);
9453
+ } else {
9454
+ await this.closeSession(params.sessionId);
9455
+ }
9456
+ };
9457
+ let reply;
9458
+ if (ctx.signal?.aborted) {
9459
+ reply = { error: { code: -32800, message: "Request cancelled" } };
9460
+ } else {
9461
+ const wasOpen = Boolean(
9462
+ ctx.sessions?.get(params.sessionId) || this.sessions.has(params.sessionId) || this.resumable.has(params.sessionId)
9463
+ );
9464
+ try {
9465
+ await this.transcripts.deleteSession(params.sessionId);
9466
+ await closeLocal();
9467
+ reply = { result: {} };
9468
+ } catch (error) {
9469
+ const text5 = error instanceof Error ? error.message : String(error);
9470
+ const notFound = /not found|no conversation found/i.test(text5);
9471
+ const invalidId = /invalid sessionid/i.test(text5);
9472
+ if (wasOpen && (notFound || invalidId)) {
9473
+ await closeLocal();
9474
+ reply = { result: {} };
9475
+ } else if (notFound || invalidId) {
9476
+ reply = {
9477
+ error: {
9478
+ code: -32002,
9479
+ message: `Unknown session ${params.sessionId}`,
9480
+ data: { sessionId: params.sessionId }
9481
+ }
9482
+ };
9483
+ } else {
9484
+ this.logger?.warn("Could not delete Claude Code's session", {
9485
+ sessionId: params.sessionId,
9486
+ error: text5
9487
+ });
9488
+ reply = { error: { code: -32603, message: "Internal error", data: text5 } };
9489
+ }
9490
+ }
9491
+ }
9492
+ return {
9493
+ type: "protocol.reply",
9494
+ ctx,
9495
+ request: message.request,
9496
+ correlation: {
9497
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
9498
+ sessionId: params.sessionId,
9499
+ rpcId: message.request.id
9500
+ },
9501
+ reply,
9502
+ timestamp: Date.now()
9503
+ };
9504
+ }
9505
+ /** `session/fork`: branch a Claude Code session into a new UUID and start its query. */
9506
+ async fork(message, ctx) {
9507
+ const params = message.request.params;
9508
+ const config = this.config;
9509
+ const makeReply = (sessionId, value) => ({
9510
+ type: "protocol.reply",
9511
+ ctx,
9512
+ request: message.request,
9513
+ correlation: {
9514
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
9515
+ ...sessionId ? { sessionId } : {},
9516
+ rpcId: message.request.id
9517
+ },
9518
+ reply: value,
9519
+ timestamp: Date.now()
9520
+ });
9521
+ const makeUpdate = (u) => ({
9522
+ type: "acp_update",
9523
+ ctx,
9524
+ request: message.request,
9525
+ update: u,
9526
+ timestamp: Date.now()
9527
+ });
9528
+ if (ctx.signal?.aborted) {
9529
+ return [
9530
+ makeReply(params.sessionId, { error: { code: -32800, message: "Request cancelled" } })
9531
+ ];
9532
+ }
9533
+ const sourceSession = this.sessions.get(params.sessionId);
9534
+ const sourceOpen = sourceSession?.phase === "open" ? sourceSession : void 0;
9535
+ const title = typeof params.setup.params.title === "string" && params.setup.params.title.trim() ? params.setup.params.title.trim() : void 0;
9536
+ let forkedId;
9537
+ let openedBridgeSession = false;
9538
+ try {
9539
+ const storedCwd = params.setup.cwd || ctx.sessions?.get(params.sessionId)?.cwd ? void 0 : (await this.transcripts.getSessionInfo(params.sessionId))?.cwd;
9540
+ const cwd = params.setup.cwd || ctx.sessions?.get(params.sessionId)?.cwd || storedCwd || config.cwd || process.cwd();
9541
+ if (ctx.signal?.aborted) {
9542
+ return [
9543
+ makeReply(params.sessionId, { error: { code: -32800, message: "Request cancelled" } })
9544
+ ];
9545
+ }
9546
+ const forked = await this.transcripts.forkSession(
9547
+ params.sessionId,
9548
+ title ? { title } : void 0
9549
+ );
9550
+ forkedId = forked?.sessionId;
9551
+ if (typeof forkedId !== "string" || !forkedId) {
9552
+ throw new Error("Claude forkSession returned no sessionId");
9553
+ }
9554
+ if (ctx.signal?.aborted) {
9555
+ await this.transcripts.deleteSession(forkedId).catch(() => {
9556
+ });
9557
+ return [
9558
+ makeReply(params.sessionId, { error: { code: -32800, message: "Request cancelled" } })
9559
+ ];
9560
+ }
9561
+ if (ctx.sessions) {
9562
+ await ctx.sessions.open({
9563
+ cwd,
9564
+ mcpServers: params.setup.mcpServers,
9565
+ params: params.setup.params,
9566
+ id: forkedId
9567
+ });
9568
+ openedBridgeSession = true;
9569
+ ctx.sessionId = forkedId;
9570
+ const scope = ctx.sessions.get(forkedId);
9571
+ if (scope) ctx.session = scope;
9572
+ }
9573
+ const inheritedModel = sourceOpen?.choices.model;
9574
+ const inheritedMode = sourceOpen?.choices.mode;
9575
+ const session = this.getOrCreateSession(forkedId, ctx, {
9576
+ cwd,
9577
+ resume: forkedId,
9578
+ ...inheritedModel !== void 0 ? { model: inheritedModel } : {},
9579
+ ...inheritedMode ? { mode: inheritedMode } : {}
9580
+ });
9581
+ const init = await session.initialization();
9582
+ if (ctx.signal?.aborted) {
9583
+ if (openedBridgeSession) {
9584
+ await ctx.sessions?.close(forkedId);
9585
+ } else {
9586
+ await this.closeSession(forkedId);
9587
+ }
9588
+ await this.transcripts.deleteSession(forkedId).catch(() => {
9589
+ });
9590
+ return [
9591
+ makeReply(params.sessionId, { error: { code: -32800, message: "Request cancelled" } })
9592
+ ];
9593
+ }
9594
+ session.choices.models = init.models;
9595
+ session.choices.commands = init.commands;
9596
+ if (sourceOpen?.choices.effort && sourceOpen.choices.effort !== DEFAULT_EFFORT) {
9597
+ await session.setEffort(sourceOpen.choices.effort);
9598
+ }
9599
+ const events = [];
9600
+ const v2 = ctx.connection?.protocol === 2;
9601
+ if (!v2 && init.commands.length) {
9602
+ events.push(
9603
+ makeUpdate({
9604
+ sessionUpdate: "available_commands_update",
9605
+ availableCommands: v1Commands(init.commands)
9606
+ })
9607
+ );
9608
+ }
9609
+ const fields = v2 ? v2SetupFields(session.choices) : v1SetupFields(session.choices);
9610
+ return [...events, makeReply(forkedId, { result: { sessionId: forkedId, ...fields } })];
9611
+ } catch (error) {
9612
+ const text5 = error instanceof Error ? error.message : String(error);
9613
+ if (forkedId) {
9614
+ if (openedBridgeSession) {
9615
+ await ctx.sessions?.close(forkedId);
9616
+ } else {
9617
+ await this.closeSession(forkedId);
9618
+ }
9619
+ await this.transcripts.deleteSession(forkedId).catch(() => {
9620
+ });
9621
+ }
9622
+ const unknown = /not found|invalid sessionid|no conversation found/i.test(text5);
9623
+ return [
9624
+ makeReply(
9625
+ params.sessionId,
9626
+ unknown ? {
9627
+ error: {
9628
+ code: -32002,
9629
+ message: `Unknown session ${params.sessionId}`,
9630
+ data: { sessionId: params.sessionId }
9631
+ }
9632
+ } : { error: { code: -32603, message: "Internal error", data: text5 } }
9633
+ )
9634
+ ];
9635
+ }
9636
+ }
8809
9637
  /** usage, final_response, end; or an error for a result that failed. */
8810
9638
  finishTurn(emit, result, fullText, events, subscriber) {
8811
9639
  const stopReason = acpStopReason(result);
@@ -8856,10 +9684,12 @@ var init_client5 = __esm({
8856
9684
  }
8857
9685
  const config = this.config;
8858
9686
  const resume = start.resume ?? this.resumable.get(key2);
8859
- const model = start.model ?? config.model;
9687
+ const chosenModel = start.model ?? config.model;
9688
+ const sdkModel = chosenModel && chosenModel !== DEFAULT_MODEL_ID ? chosenModel : void 0;
9689
+ const mode = start.mode ?? config.permissionMode ?? "default";
8860
9690
  const elicitation = elicitationSupport(ctx.connection?.clientCapabilities);
8861
9691
  const options = {
8862
- cwd: ctx.session?.cwd ?? config.cwd ?? process.cwd(),
9692
+ cwd: start.cwd ?? ctx.session?.cwd ?? config.cwd ?? process.cwd(),
8863
9693
  systemPrompt: { type: "preset", preset: "claude_code" },
8864
9694
  settingSources: ["user", "project", "local"],
8865
9695
  includePartialMessages: true,
@@ -8867,7 +9697,7 @@ var init_client5 = __esm({
8867
9697
  forwardSubagentText: true,
8868
9698
  // AskUserQuestion needs a form to ask in; without one Claude Code does without it.
8869
9699
  ...elicitation.form ? {} : { disallowedTools: ["AskUserQuestion"] },
8870
- permissionMode: config.permissionMode ?? "default",
9700
+ permissionMode: mode,
8871
9701
  mcpServers: sdkMcpServers(ctx.session?.mcpServers),
8872
9702
  // Without Bridge's own settings and other providers' keys (see env.ts).
8873
9703
  env: {
@@ -8876,7 +9706,7 @@ var init_client5 = __esm({
8876
9706
  },
8877
9707
  // Claude Code echoes each prompt it takes in: the turn's output follows from there.
8878
9708
  extraArgs: { "replay-user-messages": "" },
8879
- ...model ? { model } : {},
9709
+ ...sdkModel ? { model: sdkModel } : {},
8880
9710
  ...config.pathToClaudeCodeExecutable ? { pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable } : {},
8881
9711
  // Claude Code keeps the Bridge session's id when it is a UUID (it must be one).
8882
9712
  ...resume ? { resume } : UUID.test(key2) ? { sessionId: key2 } : {}
@@ -8886,8 +9716,8 @@ var init_client5 = __esm({
8886
9716
  v2: ctx.connection?.protocol === 2,
8887
9717
  elicitation,
8888
9718
  choices: {
8889
- mode: config.permissionMode ?? "default",
8890
- model: model ?? DEFAULT_MODEL_ID,
9719
+ mode,
9720
+ model: chosenModel ?? DEFAULT_MODEL_ID,
8891
9721
  modes: availableModes(config.permissionMode === "bypassPermissions")
8892
9722
  },
8893
9723
  createQuery: this.createQuery,
@@ -9147,6 +9977,7 @@ function initializeResultToV2(result) {
9147
9977
  info: isRecord2(result.agentInfo) ? result.agentInfo : { name: "agent", version: "0.0.0" },
9148
9978
  capabilities: {
9149
9979
  ...Object.keys(session).length ? { session } : {},
9980
+ ...isRecord2(caps.auth) ? { auth: caps.auth } : {},
9150
9981
  ...isRecord2(caps._meta) ? { _meta: caps._meta } : {}
9151
9982
  },
9152
9983
  authMethods: Array.isArray(result.authMethods) ? result.authMethods : [],
@@ -9304,6 +10135,8 @@ var init_sessions = __esm({
9304
10135
  "session/load",
9305
10136
  "session/resume",
9306
10137
  "session/list",
10138
+ "session/delete",
10139
+ "session/fork",
9307
10140
  "session/set_mode",
9308
10141
  "session/set_model",
9309
10142
  "session/set_config_option",
@@ -9353,6 +10186,42 @@ var init_sessions = __esm({
9353
10186
  const sessions = ctx.sessions;
9354
10187
  if (!sessions)
9355
10188
  return [this.reply(event, rpcError(-32603, "Internal error", "No session service"))];
10189
+ if (method === "session/delete") {
10190
+ if (typeof params.sessionId !== "string" || !params.sessionId.trim())
10191
+ return [this.reply(event, rpcError(-32602, "sessionId is required"))];
10192
+ const del = { sessionId: params.sessionId };
10193
+ return [
10194
+ {
10195
+ type: "request",
10196
+ ctx,
10197
+ request: { id: rpcId, method: CLAUDE_SESSION_DELETE, params: { ...del } },
10198
+ timestamp: Date.now()
10199
+ }
10200
+ ];
10201
+ }
10202
+ if (method === "session/fork") {
10203
+ if (typeof params.sessionId !== "string" || !params.sessionId.trim())
10204
+ return [this.reply(event, rpcError(-32602, "sessionId is required"))];
10205
+ if (params.cwd !== void 0 && params.cwd !== null && typeof params.cwd !== "string")
10206
+ return [this.reply(event, rpcError(-32602, "cwd must be a string"))];
10207
+ const mcpServers2 = Array.isArray(params.mcpServers) ? mcpServersToV1(params.mcpServers) : [];
10208
+ const fork = {
10209
+ sessionId: params.sessionId,
10210
+ setup: {
10211
+ ...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
10212
+ mcpServers: mcpServers2,
10213
+ params
10214
+ }
10215
+ };
10216
+ return [
10217
+ {
10218
+ type: "request",
10219
+ ctx,
10220
+ request: { id: rpcId, method: CLAUDE_SESSION_FORK, params: { ...fork } },
10221
+ timestamp: Date.now()
10222
+ }
10223
+ ];
10224
+ }
9356
10225
  if (method === "session/list") {
9357
10226
  if (params.cwd !== void 0 && params.cwd !== null && typeof params.cwd !== "string")
9358
10227
  return [this.reply(event, rpcError(-32602, "cwd must be a string"))];
@@ -9513,15 +10382,21 @@ var init_claude_sdk = __esm({
9513
10382
  });
9514
10383
 
9515
10384
  // packages/nodes/src/codex/types.ts
9516
- var CODEX_SESSION_START, CODEX_SESSION_CONFIGURE, CODEX_SESSION_LIST, DEFT_STOP_TERMINAL2, DEFT_CALL_TOOL, CODEX_TERMINAL_STOP;
10385
+ var CODEX_SESSION_START, CODEX_SESSION_CONFIGURE, AUTH_REQUIRED_CODE, CODEX_SESSION_LIST, CODEX_SESSION_DELETE, CODEX_SESSION_FORK, CODEX_AUTHENTICATE, CODEX_LOGOUT, DEFT_STOP_TERMINAL2, DEFT_CALL_TOOL, DEFT_WAIT_FOR_KEY, CODEX_TERMINAL_STOP;
9517
10386
  var init_types4 = __esm({
9518
10387
  "packages/nodes/src/codex/types.ts"() {
9519
10388
  "use strict";
9520
10389
  CODEX_SESSION_START = "codex/session.start";
9521
10390
  CODEX_SESSION_CONFIGURE = "codex/session.configure";
10391
+ AUTH_REQUIRED_CODE = -32e3;
9522
10392
  CODEX_SESSION_LIST = "codex/session.list";
10393
+ CODEX_SESSION_DELETE = "codex/session.delete";
10394
+ CODEX_SESSION_FORK = "codex/session.fork";
10395
+ CODEX_AUTHENTICATE = "codex/auth.authenticate";
10396
+ CODEX_LOGOUT = "codex/auth.logout";
9523
10397
  DEFT_STOP_TERMINAL2 = "_deft.co/stop_terminal";
9524
10398
  DEFT_CALL_TOOL = "deft.co/call_tool";
10399
+ DEFT_WAIT_FOR_KEY = "deft.co/wait_for_key";
9525
10400
  CODEX_TERMINAL_STOP = "codex/terminal.stop";
9526
10401
  }
9527
10402
  });
@@ -10885,12 +11760,13 @@ function extractDynamicTools(clientCapabilities) {
10885
11760
  const nameMap = /* @__PURE__ */ new Map();
10886
11761
  const meta = isRecord11(clientCapabilities?._meta) ? clientCapabilities._meta : void 0;
10887
11762
  const deft = isRecord11(meta?.["deft.co"]) ? meta["deft.co"] : void 0;
10888
- const tools = deft?.tools;
10889
- if (!Array.isArray(tools)) return { specs, nameMap };
11763
+ const rawTools = Array.isArray(deft?.tools) ? deft.tools : [];
10890
11764
  const used = /* @__PURE__ */ new Set();
10891
- for (const entry of tools) {
11765
+ const originalNames = /* @__PURE__ */ new Set();
11766
+ for (const entry of rawTools) {
10892
11767
  if (!isRecord11(entry) || typeof entry.name !== "string" || !entry.name.trim()) continue;
10893
11768
  const originalName = entry.name.trim();
11769
+ originalNames.add(originalName);
10894
11770
  const registeredName = sanitizeToolName(originalName, used);
10895
11771
  const description = typeof entry.description === "string" ? entry.description : originalName;
10896
11772
  const rawSchema = isRecord11(entry.inputSchema) ? entry.inputSchema : {};
@@ -10913,7 +11789,53 @@ function extractDynamicTools(clientCapabilities) {
10913
11789
  });
10914
11790
  nameMap.set(registeredName, originalName);
10915
11791
  }
10916
- return { specs, nameMap };
11792
+ let waitForKeyTool;
11793
+ if (isRecord11(deft?.waitForKey) && !originalNames.has("wait_for_key")) {
11794
+ waitForKeyTool = sanitizeToolName("wait_for_key", used);
11795
+ specs.push({
11796
+ type: "function",
11797
+ name: waitForKeyTool,
11798
+ description: "Pause and show a single-key choice bar to the user in Deft Console, returning which key was pressed or whether it was cancelled.",
11799
+ inputSchema: {
11800
+ type: "object",
11801
+ properties: {
11802
+ message: {
11803
+ type: "string",
11804
+ description: "Prompt message shown next to the key choices."
11805
+ },
11806
+ keys: {
11807
+ type: "array",
11808
+ description: "1 to 9 single-character printable non-space keys with short labels.",
11809
+ minItems: 1,
11810
+ maxItems: 9,
11811
+ items: {
11812
+ type: "object",
11813
+ properties: {
11814
+ key: {
11815
+ type: "string",
11816
+ description: 'Single printable non-space character (e.g. "y", "n", "1").'
11817
+ },
11818
+ label: {
11819
+ type: "string",
11820
+ description: "Short label shown for this key."
11821
+ }
11822
+ },
11823
+ required: ["key", "label"],
11824
+ additionalProperties: false
11825
+ }
11826
+ }
11827
+ },
11828
+ required: ["keys"],
11829
+ additionalProperties: false
11830
+ }
11831
+ });
11832
+ nameMap.set(waitForKeyTool, "wait_for_key");
11833
+ }
11834
+ return {
11835
+ specs,
11836
+ nameMap,
11837
+ ...waitForKeyTool ? { waitForKeyTool } : {}
11838
+ };
10917
11839
  }
10918
11840
  function extractSystemPrompt(params) {
10919
11841
  const sp = params.systemPrompt;
@@ -11380,7 +12302,37 @@ async function handleMcpElicitation(params, support, ask, signal) {
11380
12302
  return { action: "cancel", content: null, _meta: null };
11381
12303
  }
11382
12304
  }
11383
- async function handleDynamicToolCall(params, rootThreadId, nameMap, ask, signal) {
12305
+ function validateWaitForKeyEntries(rawKeys) {
12306
+ if (!Array.isArray(rawKeys) || rawKeys.length < 1 || rawKeys.length > 9) {
12307
+ return { ok: false, error: "wait_for_key requires 1 to 9 key entries." };
12308
+ }
12309
+ const seen = /* @__PURE__ */ new Set();
12310
+ const keys = [];
12311
+ for (const entry of rawKeys) {
12312
+ if (!isRecord12(entry) || typeof entry.key !== "string" || typeof entry.label !== "string") {
12313
+ return { ok: false, error: "Each wait_for_key entry must provide string key and label." };
12314
+ }
12315
+ const chars = [...entry.key];
12316
+ const codePoint = chars[0]?.codePointAt(0) ?? 0;
12317
+ if (chars.length !== 1 || /\s/.test(entry.key) || codePoint < 33 || codePoint >= 127 && codePoint <= 159) {
12318
+ return {
12319
+ ok: false,
12320
+ error: `Invalid key ${JSON.stringify(entry.key)}: keys must be a single printable non-space character.`
12321
+ };
12322
+ }
12323
+ const label = entry.label.trim();
12324
+ if (!label) {
12325
+ return { ok: false, error: `Key "${entry.key}" must have a non-empty label.` };
12326
+ }
12327
+ if (seen.has(entry.key)) {
12328
+ return { ok: false, error: `Duplicate key "${entry.key}" in wait_for_key.` };
12329
+ }
12330
+ seen.add(entry.key);
12331
+ keys.push({ key: entry.key, label });
12332
+ }
12333
+ return { ok: true, keys };
12334
+ }
12335
+ async function handleDynamicToolCall(params, rootThreadId, nameMap, ask, signal, waitForKeyTool) {
11384
12336
  const threadId = typeof params.threadId === "string" ? params.threadId : "";
11385
12337
  if (threadId && threadId !== rootThreadId) {
11386
12338
  return {
@@ -11394,8 +12346,73 @@ async function handleDynamicToolCall(params, rootThreadId, nameMap, ask, signal)
11394
12346
  };
11395
12347
  }
11396
12348
  const registeredName = typeof params.tool === "string" ? params.tool : "";
11397
- const originalName = nameMap.get(registeredName) ?? registeredName;
11398
12349
  const args = isRecord12(params.arguments) ? params.arguments : {};
12350
+ if (waitForKeyTool && registeredName === waitForKeyTool) {
12351
+ const validated = validateWaitForKeyEntries(args.keys);
12352
+ if (!validated.ok) {
12353
+ return {
12354
+ success: false,
12355
+ contentItems: [{ type: "inputText", text: validated.error }]
12356
+ };
12357
+ }
12358
+ const message = typeof args.message === "string" && args.message.trim() ? args.message : "Choose an option";
12359
+ try {
12360
+ const result = await ask(
12361
+ DEFT_WAIT_FOR_KEY,
12362
+ {
12363
+ message,
12364
+ keys: validated.keys
12365
+ },
12366
+ signal
12367
+ );
12368
+ const resObj = isRecord12(result) ? result : void 0;
12369
+ if (resObj?.outcome === "pressed" && typeof resObj.key === "string") {
12370
+ const matched = validated.keys.find((k) => k.key === resObj.key);
12371
+ if (!matched) {
12372
+ return {
12373
+ success: false,
12374
+ contentItems: [
12375
+ { type: "inputText", text: `Unexpected wait_for_key key: ${resObj.key}` }
12376
+ ]
12377
+ };
12378
+ }
12379
+ return {
12380
+ success: true,
12381
+ contentItems: [
12382
+ {
12383
+ type: "inputText",
12384
+ text: JSON.stringify({
12385
+ outcome: "pressed",
12386
+ key: matched.key,
12387
+ label: matched.label
12388
+ })
12389
+ }
12390
+ ]
12391
+ };
12392
+ }
12393
+ if (resObj?.outcome === "cancelled") {
12394
+ return {
12395
+ success: true,
12396
+ contentItems: [{ type: "inputText", text: JSON.stringify({ outcome: "cancelled" }) }]
12397
+ };
12398
+ }
12399
+ return {
12400
+ success: false,
12401
+ contentItems: [{ type: "inputText", text: "Unexpected wait_for_key response." }]
12402
+ };
12403
+ } catch (err) {
12404
+ return {
12405
+ success: false,
12406
+ contentItems: [
12407
+ {
12408
+ type: "inputText",
12409
+ text: err instanceof Error ? err.message : String(err)
12410
+ }
12411
+ ]
12412
+ };
12413
+ }
12414
+ }
12415
+ const originalName = nameMap.get(registeredName) ?? registeredName;
11399
12416
  try {
11400
12417
  const result = await ask(
11401
12418
  DEFT_CALL_TOOL,
@@ -11458,6 +12475,7 @@ var init_session2 = __esm({
11458
12475
  choices;
11459
12476
  terminalOutput;
11460
12477
  dynamicToolNames;
12478
+ waitForKeyTool;
11461
12479
  phase = "open";
11462
12480
  needsResume = false;
11463
12481
  items;
@@ -11487,6 +12505,7 @@ var init_session2 = __esm({
11487
12505
  this.choices = options.choices;
11488
12506
  this.terminalOutput = options.terminalOutput;
11489
12507
  this.dynamicToolNames = options.dynamicToolNames ?? /* @__PURE__ */ new Map();
12508
+ this.waitForKeyTool = options.waitForKeyTool;
11490
12509
  this.items = new CodexItemTracker(this.terminalOutput, this.dynamicToolNames);
11491
12510
  this.mcpServersConfig = options.mcpServersConfig ?? {};
11492
12511
  this.developerInstructions = options.developerInstructions;
@@ -11511,6 +12530,9 @@ var init_session2 = __esm({
11511
12530
  this.dynamicToolNames.set(k, v);
11512
12531
  }
11513
12532
  }
12533
+ if (options.waitForKeyTool !== void 0) {
12534
+ this.waitForKeyTool = options.waitForKeyTool;
12535
+ }
11514
12536
  this.mcpServersConfig = options.mcpServersConfig;
11515
12537
  this.developerInstructions = options.developerInstructions;
11516
12538
  this.baseInstructions = options.baseInstructions;
@@ -12171,7 +13193,8 @@ var init_session2 = __esm({
12171
13193
  this.threadId,
12172
13194
  this.dynamicToolNames,
12173
13195
  ask,
12174
- combinedSignal
13196
+ combinedSignal,
13197
+ this.waitForKeyTool
12175
13198
  );
12176
13199
  req.replyResult(res);
12177
13200
  return;
@@ -12317,10 +13340,15 @@ var init_sessions2 = __esm({
12317
13340
  init_config2();
12318
13341
  init_types4();
12319
13342
  METHODS2 = /* @__PURE__ */ new Set([
13343
+ "authenticate",
13344
+ "logout",
13345
+ "auth/logout",
12320
13346
  "session/new",
12321
13347
  "session/load",
12322
13348
  "session/resume",
13349
+ "session/fork",
12323
13350
  "session/list",
13351
+ "session/delete",
12324
13352
  "session/set_mode",
12325
13353
  "session/set_model",
12326
13354
  "session/set_config_option",
@@ -12368,9 +13396,78 @@ var init_sessions2 = __esm({
12368
13396
  const { method, id: rpcId } = event.message;
12369
13397
  const params = isRecord2(event.message.params) ? event.message.params : {};
12370
13398
  const sessions = ctx.sessions;
13399
+ if (method === "authenticate") {
13400
+ if (typeof params.methodId !== "string" || !params.methodId.trim()) {
13401
+ return [this.reply(event, rpcError(-32602, "methodId is required"))];
13402
+ }
13403
+ const meta = isRecord2(params._meta) ? params._meta : void 0;
13404
+ const apiKey = typeof params.apiKey === "string" ? params.apiKey : typeof meta?.apiKey === "string" ? meta.apiKey : void 0;
13405
+ const auth = {
13406
+ methodId: params.methodId.trim(),
13407
+ ...apiKey !== void 0 ? { apiKey } : {},
13408
+ ...meta ? { _meta: meta } : {}
13409
+ };
13410
+ return [
13411
+ {
13412
+ type: "request",
13413
+ ctx,
13414
+ request: { id: rpcId, method: CODEX_AUTHENTICATE, params: { ...auth } },
13415
+ timestamp: Date.now()
13416
+ }
13417
+ ];
13418
+ }
13419
+ if (method === "logout" || method === "auth/logout") {
13420
+ return [
13421
+ {
13422
+ type: "request",
13423
+ ctx,
13424
+ request: { id: rpcId, method: CODEX_LOGOUT, params: {} },
13425
+ timestamp: Date.now()
13426
+ }
13427
+ ];
13428
+ }
12371
13429
  if (!sessions) {
12372
13430
  return [this.reply(event, rpcError(-32603, "Internal error", "No session service"))];
12373
13431
  }
13432
+ if (method === "session/delete") {
13433
+ if (typeof params.sessionId !== "string" || !params.sessionId.trim()) {
13434
+ return [this.reply(event, rpcError(-32602, "sessionId is required"))];
13435
+ }
13436
+ const del = { sessionId: params.sessionId };
13437
+ return [
13438
+ {
13439
+ type: "request",
13440
+ ctx,
13441
+ request: { id: rpcId, method: CODEX_SESSION_DELETE, params: { ...del } },
13442
+ timestamp: Date.now()
13443
+ }
13444
+ ];
13445
+ }
13446
+ if (method === "session/fork") {
13447
+ if (typeof params.sessionId !== "string" || !params.sessionId.trim()) {
13448
+ return [this.reply(event, rpcError(-32602, "sessionId is required"))];
13449
+ }
13450
+ if (params.cwd !== void 0 && params.cwd !== null && typeof params.cwd !== "string") {
13451
+ return [this.reply(event, rpcError(-32602, "cwd must be a string"))];
13452
+ }
13453
+ const mcpServers2 = Array.isArray(params.mcpServers) ? mcpServersToV1(params.mcpServers) : [];
13454
+ const fork = {
13455
+ sessionId: params.sessionId,
13456
+ setup: {
13457
+ ...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
13458
+ mcpServers: mcpServers2,
13459
+ params
13460
+ }
13461
+ };
13462
+ return [
13463
+ {
13464
+ type: "request",
13465
+ ctx,
13466
+ request: { id: rpcId, method: CODEX_SESSION_FORK, params: { ...fork } },
13467
+ timestamp: Date.now()
13468
+ }
13469
+ ];
13470
+ }
12374
13471
  if (method === "session/list") {
12375
13472
  if (params.cwd !== void 0 && params.cwd !== null && typeof params.cwd !== "string") {
12376
13473
  return [this.reply(event, rpcError(-32602, "cwd must be a string"))];
@@ -12621,7 +13718,20 @@ var init_translator6 = __esm({
12621
13718
  import { randomUUID as randomUUID9 } from "node:crypto";
12622
13719
  import { from as from4, mergeMap as mergeMap6, Observable as Observable21 } from "rxjs";
12623
13720
  import { ClassicPreset as ClassicPreset24 } from "rete";
12624
- var LIST_PAGE2, isRecord15, CodexClientNode;
13721
+ function isAuthError(err) {
13722
+ if (err instanceof CodexAuthRequiredError) return true;
13723
+ if (err instanceof CodexRpcError && err.code === AUTH_REQUIRED_CODE) return true;
13724
+ const text5 = err instanceof Error ? err.message : String(err);
13725
+ return /\b(401|unauthorized|unauthenticated|not logged in|login required|authentication required|missing openai_api_key|requires authentication|invalid api key)\b/i.test(
13726
+ text5
13727
+ );
13728
+ }
13729
+ function authErrorMessage(err) {
13730
+ if (err instanceof CodexAuthRequiredError) return err.message;
13731
+ const text5 = err instanceof Error ? err.message : String(err);
13732
+ return text5 || "Authentication required. Sign in to Codex to continue.";
13733
+ }
13734
+ var LIST_PAGE2, isRecord15, CodexAuthRequiredError, CodexClientNode;
12625
13735
  var init_client6 = __esm({
12626
13736
  "packages/nodes/src/codex/client.ts"() {
12627
13737
  "use strict";
@@ -12635,12 +13745,19 @@ var init_client6 = __esm({
12635
13745
  init_mcp2();
12636
13746
  init_mapper2();
12637
13747
  init_permissions2();
13748
+ init_elicitation();
12638
13749
  init_replay2();
12639
13750
  init_session2();
12640
13751
  init_transport();
12641
13752
  init_types4();
12642
13753
  LIST_PAGE2 = 50;
12643
13754
  isRecord15 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
13755
+ CodexAuthRequiredError = class extends Error {
13756
+ constructor(message = "Authentication required. Sign in to Codex to continue.") {
13757
+ super(message);
13758
+ this.name = "CodexAuthRequiredError";
13759
+ }
13760
+ };
12644
13761
  CodexClientNode = class extends StreamingNode {
12645
13762
  static meta = nodeDescriptions["Codex Client"];
12646
13763
  sessions = /* @__PURE__ */ new Map();
@@ -12653,6 +13770,9 @@ var init_client6 = __esm({
12653
13770
  createProcess;
12654
13771
  transport;
12655
13772
  cachedModels;
13773
+ authVerified = false;
13774
+ loginWaiters = /* @__PURE__ */ new Set();
13775
+ unmatchedLoginOutcomes = /* @__PURE__ */ new Map();
12656
13776
  constructor(config = {}) {
12657
13777
  super("Codex Client", {
12658
13778
  cancelGraceMs: 5e3,
@@ -12668,6 +13788,7 @@ var init_client6 = __esm({
12668
13788
  }
12669
13789
  /**
12670
13790
  * Capabilities contributed to `initialize`:
13791
+ * - `auth.logout: {}` (`logout` -> Codex `account/logout`)
12671
13792
  * - `stopTerminal: {}` (verified via `thread/backgroundTerminals/terminate`)
12672
13793
  * - `tools: {}` when `dynamicTools !== false` (suppressing duplicate Console MCP registration;
12673
13794
  * omitted when `dynamicTools === false` so Console falls back to its MCP server).
@@ -12676,6 +13797,9 @@ var init_client6 = __esm({
12676
13797
  const cfg = this.config;
12677
13798
  const directTools = cfg.dynamicTools !== false;
12678
13799
  return {
13800
+ auth: {
13801
+ logout: {}
13802
+ },
12679
13803
  _meta: {
12680
13804
  "deft.co": {
12681
13805
  stopTerminal: {},
@@ -12684,6 +13808,49 @@ var init_client6 = __esm({
12684
13808
  }
12685
13809
  };
12686
13810
  }
13811
+ /**
13812
+ * Authentication methods advertised in ACP `initialize` for Codex App Server:
13813
+ * - `chatgpt`: OAuth browser login via `account/login/start` + URL elicitation
13814
+ * - `chatgpt-device-code`: device code login via `account/login/start` + URL/form elicitation
13815
+ * - `codex-login`: interactive terminal login (`<bridge> --login` -> `codex login`)
13816
+ * - `openai-api-key`: `OPENAI_API_KEY` environment variable (and direct `authenticate` support)
13817
+ */
13818
+ authMethods() {
13819
+ return [
13820
+ {
13821
+ id: "chatgpt",
13822
+ name: "Sign in with ChatGPT",
13823
+ description: "Open your browser to sign in with your ChatGPT subscription.",
13824
+ type: "agent"
13825
+ },
13826
+ {
13827
+ id: "chatgpt-device-code",
13828
+ name: "Sign in with Device Code",
13829
+ description: "Sign in using a one-time device code in any browser.",
13830
+ type: "agent"
13831
+ },
13832
+ {
13833
+ id: "codex-login",
13834
+ name: "Interactive Codex CLI Login",
13835
+ description: "Run codex login interactively in a terminal.",
13836
+ type: "terminal",
13837
+ args: ["--login"]
13838
+ },
13839
+ {
13840
+ id: "openai-api-key",
13841
+ name: "OpenAI API Key",
13842
+ description: "Authenticate using an OPENAI_API_KEY.",
13843
+ type: "env_var",
13844
+ vars: [
13845
+ {
13846
+ name: "OPENAI_API_KEY",
13847
+ label: "OpenAI API Key",
13848
+ secret: true
13849
+ }
13850
+ ]
13851
+ }
13852
+ ];
13853
+ }
12687
13854
  useServices(services) {
12688
13855
  if (services.backends?.createCodexProcess) {
12689
13856
  this.createProcess = services.backends.createCodexProcess;
@@ -12700,12 +13867,24 @@ var init_client6 = __esm({
12700
13867
  processStream(message, ctx) {
12701
13868
  const stream = SessionStream.entryOf(message, ctx);
12702
13869
  if (stream) return stream.events$;
13870
+ if (message.type === "request" && message.request.method === CODEX_AUTHENTICATE) {
13871
+ return this.authenticate(message, ctx);
13872
+ }
13873
+ if (message.type === "request" && message.request.method === CODEX_LOGOUT) {
13874
+ return from4(this.logout(message, ctx));
13875
+ }
12703
13876
  if (message.type === "request" && message.request.method === CODEX_SESSION_START) {
12704
13877
  return from4(this.start(message, ctx)).pipe(mergeMap6((events) => events));
12705
13878
  }
13879
+ if (message.type === "request" && message.request.method === CODEX_SESSION_FORK) {
13880
+ return from4(this.forkSession(message, ctx));
13881
+ }
12706
13882
  if (message.type === "request" && message.request.method === CODEX_SESSION_LIST) {
12707
13883
  return from4(this.list(message, ctx));
12708
13884
  }
13885
+ if (message.type === "request" && message.request.method === CODEX_SESSION_DELETE) {
13886
+ return from4(this.deleteSession(message, ctx));
13887
+ }
12709
13888
  if (message.type === "request" && message.request.method === CODEX_SESSION_CONFIGURE) {
12710
13889
  return from4(this.configure(message, ctx));
12711
13890
  }
@@ -12777,6 +13956,23 @@ var init_client6 = __esm({
12777
13956
  }
12778
13957
  end("done");
12779
13958
  if (error) {
13959
+ if (isAuthError(error)) {
13960
+ this.authVerified = false;
13961
+ subscriber.next({
13962
+ type: "protocol.reply",
13963
+ ctx,
13964
+ request: message.request,
13965
+ correlation: {
13966
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
13967
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {},
13968
+ rpcId: message.request.id
13969
+ },
13970
+ reply: { error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(error) } },
13971
+ timestamp: Date.now()
13972
+ });
13973
+ subscriber.complete();
13974
+ return;
13975
+ }
12780
13976
  subscriber.error(error);
12781
13977
  return;
12782
13978
  }
@@ -12808,6 +14004,8 @@ var init_client6 = __esm({
12808
14004
  };
12809
14005
  void (async () => {
12810
14006
  try {
14007
+ const transport = await this.getOrStartTransport();
14008
+ await this.ensureAuthenticated(transport);
12811
14009
  currentSession = await this.ensureSessionForPrompt(key2, ctx, {
12812
14010
  ...translated.model ? { model: translated.model } : {}
12813
14011
  });
@@ -12820,6 +14018,23 @@ var init_client6 = __esm({
12820
14018
  });
12821
14019
  } catch (err) {
12822
14020
  end("done");
14021
+ if (isAuthError(err)) {
14022
+ this.authVerified = false;
14023
+ subscriber.next({
14024
+ type: "protocol.reply",
14025
+ ctx,
14026
+ request: message.request,
14027
+ correlation: {
14028
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
14029
+ ...ctx.sessionId ? { sessionId: ctx.sessionId } : {},
14030
+ rpcId: message.request.id
14031
+ },
14032
+ reply: { error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(err) } },
14033
+ timestamp: Date.now()
14034
+ });
14035
+ subscriber.complete();
14036
+ return;
14037
+ }
12823
14038
  subscriber.error(err instanceof Error ? err : new Error(String(err)));
12824
14039
  }
12825
14040
  })();
@@ -12858,6 +14073,7 @@ var init_client6 = __esm({
12858
14073
  }
12859
14074
  try {
12860
14075
  const transport = await this.getOrStartTransport();
14076
+ await this.ensureAuthenticated(transport);
12861
14077
  const models = await this.loadModels(transport);
12862
14078
  const cwd = params.setup.cwd || config.cwd || process.cwd();
12863
14079
  const mcpServersConfig = codexMcpServers(params.setup.mcpServers);
@@ -12907,6 +14123,7 @@ var init_client6 = __esm({
12907
14123
  },
12908
14124
  terminalOutput: config.terminalOutput ?? terminalOutputFor(ctx),
12909
14125
  dynamicToolNames: dynamicTools.nameMap,
14126
+ ...dynamicTools.waitForKeyTool ? { waitForKeyTool: dynamicTools.waitForKeyTool } : {},
12910
14127
  mcpServersConfig,
12911
14128
  ...instructions.developerInstructions ? { developerInstructions: instructions.developerInstructions } : {},
12912
14129
  ...instructions.baseInstructions ? { baseInstructions: instructions.baseInstructions } : {},
@@ -12950,6 +14167,7 @@ var init_client6 = __esm({
12950
14167
  subagentSessions: subagentSessionsSupport(ctx.connection?.clientCapabilities),
12951
14168
  terminalOutput: config.terminalOutput ?? terminalOutputFor(ctx),
12952
14169
  dynamicToolNames: dynamicTools.nameMap,
14170
+ ...dynamicTools.waitForKeyTool ? { waitForKeyTool: dynamicTools.waitForKeyTool } : {},
12953
14171
  mcpServersConfig,
12954
14172
  ...instructions.developerInstructions ? { developerInstructions: instructions.developerInstructions } : {},
12955
14173
  ...instructions.baseInstructions ? { baseInstructions: instructions.baseInstructions } : {},
@@ -12973,6 +14191,7 @@ var init_client6 = __esm({
12973
14191
  },
12974
14192
  terminalOutput: config.terminalOutput ?? terminalOutputFor(ctx),
12975
14193
  dynamicToolNames: dynamicTools.nameMap,
14194
+ ...dynamicTools.waitForKeyTool ? { waitForKeyTool: dynamicTools.waitForKeyTool } : {},
12976
14195
  mcpServersConfig,
12977
14196
  ...instructions.developerInstructions ? { developerInstructions: instructions.developerInstructions } : {},
12978
14197
  ...instructions.baseInstructions ? { baseInstructions: instructions.baseInstructions } : {},
@@ -13006,6 +14225,14 @@ var init_client6 = __esm({
13006
14225
  if (params.opened && params.sessionId) {
13007
14226
  await ctx.sessions?.close(params.sessionId);
13008
14227
  }
14228
+ if (isAuthError(error)) {
14229
+ this.authVerified = false;
14230
+ return [
14231
+ reply(params.sessionId, {
14232
+ error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(error) }
14233
+ })
14234
+ ];
14235
+ }
13009
14236
  const text5 = error instanceof Error ? error.message : String(error);
13010
14237
  const isUnknownThread = /no rollout found|not found|unknown thread|invalid thread/i.test(
13011
14238
  text5
@@ -13029,6 +14256,7 @@ var init_client6 = __esm({
13029
14256
  let reply;
13030
14257
  try {
13031
14258
  const transport = await this.getOrStartTransport();
14259
+ await this.ensureAuthenticated(transport);
13032
14260
  const res = await transport.request("thread/list", {
13033
14261
  limit: LIST_PAGE2,
13034
14262
  ...params.cwd ? { cwd: params.cwd } : {},
@@ -13060,9 +14288,314 @@ var init_client6 = __esm({
13060
14288
  }
13061
14289
  };
13062
14290
  } catch (error) {
13063
- const text5 = error instanceof Error ? error.message : String(error);
13064
- this.logger?.warn("Could not list Codex's threads", { error: text5 });
13065
- reply = { error: { code: -32603, message: "Internal error", data: text5 } };
14291
+ if (isAuthError(error)) {
14292
+ this.authVerified = false;
14293
+ reply = { error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(error) } };
14294
+ } else {
14295
+ const text5 = error instanceof Error ? error.message : String(error);
14296
+ this.logger?.warn("Could not list Codex's threads", { error: text5 });
14297
+ reply = { error: { code: -32603, message: "Internal error", data: text5 } };
14298
+ }
14299
+ }
14300
+ return {
14301
+ type: "protocol.reply",
14302
+ ctx,
14303
+ request: message.request,
14304
+ correlation: {
14305
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
14306
+ rpcId: message.request.id
14307
+ },
14308
+ reply,
14309
+ timestamp: Date.now()
14310
+ };
14311
+ }
14312
+ authenticate(message, ctx) {
14313
+ return new Observable21((subscriber) => {
14314
+ const params = message.request.params;
14315
+ const config = this.config;
14316
+ let settled = false;
14317
+ const finishReply = (value) => {
14318
+ if (settled) return;
14319
+ settled = true;
14320
+ subscriber.next({
14321
+ type: "protocol.reply",
14322
+ ctx,
14323
+ request: message.request,
14324
+ correlation: {
14325
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
14326
+ rpcId: message.request.id
14327
+ },
14328
+ reply: value,
14329
+ timestamp: Date.now()
14330
+ });
14331
+ subscriber.complete();
14332
+ };
14333
+ const emitOutbound = (method, outboundParams) => {
14334
+ if (settled) return;
14335
+ subscriber.next({
14336
+ type: "protocol.outbound",
14337
+ ctx,
14338
+ request: message.request,
14339
+ message: { method, params: outboundParams },
14340
+ correlation: {
14341
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {}
14342
+ },
14343
+ timestamp: Date.now()
14344
+ });
14345
+ };
14346
+ let activeWaiter;
14347
+ let activeLoginId;
14348
+ let activeTransport;
14349
+ const cancelActiveLogin = () => {
14350
+ if (activeWaiter) {
14351
+ this.loginWaiters.delete(activeWaiter);
14352
+ activeWaiter = void 0;
14353
+ }
14354
+ if (activeLoginId && activeTransport && !activeTransport.isClosed) {
14355
+ const id = activeLoginId;
14356
+ activeLoginId = void 0;
14357
+ void activeTransport.request("account/login/cancel", { loginId: id }).catch(() => {
14358
+ });
14359
+ }
14360
+ };
14361
+ const onAbort = () => {
14362
+ cancelActiveLogin();
14363
+ finishReply({ error: { code: -32800, message: "Request cancelled" } });
14364
+ };
14365
+ if (ctx.signal?.aborted) {
14366
+ onAbort();
14367
+ return;
14368
+ }
14369
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
14370
+ void (async () => {
14371
+ try {
14372
+ const methodId = params.methodId;
14373
+ if (methodId === "codex-login") {
14374
+ finishReply({
14375
+ error: {
14376
+ code: -32602,
14377
+ message: "codex-login is a terminal authentication method; run deft-bridge with --login in an interactive terminal."
14378
+ }
14379
+ });
14380
+ return;
14381
+ }
14382
+ if (methodId !== "chatgpt" && methodId !== "chatgpt-device-code" && methodId !== "openai-api-key") {
14383
+ finishReply({
14384
+ error: { code: -32602, message: `Unknown authentication method: ${methodId}` }
14385
+ });
14386
+ return;
14387
+ }
14388
+ const transport = await this.getOrStartTransport();
14389
+ activeTransport = transport;
14390
+ const support = elicitationSupport(ctx.connection?.clientCapabilities);
14391
+ if (methodId === "openai-api-key") {
14392
+ let apiKey = typeof params.apiKey === "string" && params.apiKey.trim() || typeof config.env?.OPENAI_API_KEY === "string" && config.env.OPENAI_API_KEY.trim() || typeof process.env.OPENAI_API_KEY === "string" && process.env.OPENAI_API_KEY.trim() || "";
14393
+ if (!apiKey && support.form) {
14394
+ const formRes = await this.ask(
14395
+ ctx,
14396
+ (ev) => subscriber.next(ev),
14397
+ ELICITATION_METHOD,
14398
+ {
14399
+ mode: "form",
14400
+ message: "Enter your OpenAI API key to authenticate Codex.",
14401
+ requestedSchema: {
14402
+ type: "object",
14403
+ properties: {
14404
+ apiKey: {
14405
+ type: "string",
14406
+ title: "OpenAI API Key",
14407
+ description: "Your OpenAI API key (sk-...)."
14408
+ }
14409
+ },
14410
+ required: ["apiKey"]
14411
+ }
14412
+ },
14413
+ ctx.signal
14414
+ );
14415
+ if (!isRecord15(formRes) || formRes.action !== "accept") {
14416
+ finishReply({
14417
+ error: { code: AUTH_REQUIRED_CODE, message: "Sign-in cancelled." }
14418
+ });
14419
+ return;
14420
+ }
14421
+ const content2 = isRecord15(formRes.content) ? formRes.content : {};
14422
+ if (typeof content2.apiKey === "string") {
14423
+ apiKey = content2.apiKey.trim();
14424
+ }
14425
+ }
14426
+ if (!apiKey) {
14427
+ finishReply({
14428
+ error: {
14429
+ code: -32602,
14430
+ message: "OpenAI API key is required (set OPENAI_API_KEY or pass apiKey)."
14431
+ }
14432
+ });
14433
+ return;
14434
+ }
14435
+ await transport.request("account/login/start", { type: "apiKey", apiKey });
14436
+ this.authVerified = true;
14437
+ this.cachedModels = void 0;
14438
+ finishReply({ result: {} });
14439
+ return;
14440
+ }
14441
+ if (!support.url && !support.form) {
14442
+ finishReply({
14443
+ error: {
14444
+ code: -32602,
14445
+ message: "Client must support elicitation (url or form) for interactive browser sign-in; use codex-login (--login) or openai-api-key instead."
14446
+ }
14447
+ });
14448
+ return;
14449
+ }
14450
+ let resolveOutcome;
14451
+ const loginOutcomePromise = new Promise((resolve19) => {
14452
+ resolveOutcome = resolve19;
14453
+ });
14454
+ const waiter = { resolve: resolveOutcome };
14455
+ activeWaiter = waiter;
14456
+ this.loginWaiters.add(waiter);
14457
+ const startType = methodId === "chatgpt" ? "chatgpt" : "chatgptDeviceCode";
14458
+ const started = await transport.request("account/login/start", { type: startType });
14459
+ const loginId = typeof started?.loginId === "string" ? started.loginId : "";
14460
+ if (loginId) {
14461
+ activeLoginId = loginId;
14462
+ const buffered = this.unmatchedLoginOutcomes.get(loginId);
14463
+ if (buffered) {
14464
+ this.unmatchedLoginOutcomes.delete(loginId);
14465
+ this.loginWaiters.delete(waiter);
14466
+ activeWaiter = void 0;
14467
+ resolveOutcome(buffered);
14468
+ } else {
14469
+ waiter.loginId = loginId;
14470
+ }
14471
+ }
14472
+ const url = methodId === "chatgpt" ? typeof started?.authUrl === "string" ? started.authUrl : "" : typeof started?.verificationUrl === "string" ? started.verificationUrl : "";
14473
+ if (!url) {
14474
+ cancelActiveLogin();
14475
+ finishReply({
14476
+ error: {
14477
+ code: -32603,
14478
+ message: "Codex account/login/start returned no sign-in URL."
14479
+ }
14480
+ });
14481
+ return;
14482
+ }
14483
+ const userCode = typeof started?.userCode === "string" ? started.userCode : "";
14484
+ const promptMsg = methodId === "chatgpt" ? "Open this link in your browser to sign in to Codex with ChatGPT." : userCode ? `Open ${url} and enter code ${userCode} to sign in to Codex.` : "Open this link in your browser to complete Codex device-code sign-in.";
14485
+ const elicitationId = loginId || randomUUID9();
14486
+ const elicitParams = support.url ? {
14487
+ mode: "url",
14488
+ url,
14489
+ elicitationId,
14490
+ message: promptMsg
14491
+ } : {
14492
+ mode: "form",
14493
+ message: `${promptMsg}${!promptMsg.includes(url) ? `
14494
+
14495
+ ${url}` : ""}`,
14496
+ requestedSchema: { type: "object", properties: {} }
14497
+ };
14498
+ const elicitAbort = new AbortController();
14499
+ const forwardAbort = () => elicitAbort.abort(ctx.signal?.reason);
14500
+ if (ctx.signal?.aborted) elicitAbort.abort(ctx.signal.reason);
14501
+ else ctx.signal?.addEventListener("abort", forwardAbort, { once: true });
14502
+ const elicitRace = this.ask(
14503
+ ctx,
14504
+ (ev) => subscriber.next(ev),
14505
+ ELICITATION_METHOD,
14506
+ elicitParams,
14507
+ elicitAbort.signal
14508
+ ).then(
14509
+ (value) => ({ kind: "elicit", value }),
14510
+ (err) => ({ kind: "elicit_error", err })
14511
+ ).finally(() => {
14512
+ ctx.signal?.removeEventListener("abort", forwardAbort);
14513
+ });
14514
+ const loginRace = loginOutcomePromise.then((outcome2) => ({
14515
+ kind: "login",
14516
+ outcome: outcome2
14517
+ }));
14518
+ const winner = await Promise.race([elicitRace, loginRace]);
14519
+ if (winner.kind === "login") {
14520
+ activeLoginId = void 0;
14521
+ if (support.url) {
14522
+ emitOutbound("elicitation/complete", { elicitationId });
14523
+ }
14524
+ elicitAbort.abort();
14525
+ if (winner.outcome.success) {
14526
+ this.authVerified = true;
14527
+ this.cachedModels = void 0;
14528
+ finishReply({ result: {} });
14529
+ } else {
14530
+ finishReply({
14531
+ error: {
14532
+ code: AUTH_REQUIRED_CODE,
14533
+ message: winner.outcome.error || "Codex sign-in failed."
14534
+ }
14535
+ });
14536
+ }
14537
+ return;
14538
+ }
14539
+ if (winner.kind === "elicit_error" || !isRecord15(winner.value) || winner.value.action !== "accept") {
14540
+ cancelActiveLogin();
14541
+ finishReply({
14542
+ error: { code: AUTH_REQUIRED_CODE, message: "Sign-in cancelled." }
14543
+ });
14544
+ return;
14545
+ }
14546
+ const outcome = await loginOutcomePromise;
14547
+ activeLoginId = void 0;
14548
+ if (outcome.success) {
14549
+ this.authVerified = true;
14550
+ this.cachedModels = void 0;
14551
+ finishReply({ result: {} });
14552
+ } else {
14553
+ finishReply({
14554
+ error: {
14555
+ code: AUTH_REQUIRED_CODE,
14556
+ message: outcome.error || "Codex sign-in failed."
14557
+ }
14558
+ });
14559
+ }
14560
+ } catch (err) {
14561
+ cancelActiveLogin();
14562
+ const text5 = err instanceof Error ? err.message : String(err);
14563
+ finishReply({
14564
+ error: {
14565
+ code: isAuthError(err) ? AUTH_REQUIRED_CODE : -32603,
14566
+ message: isAuthError(err) ? authErrorMessage(err) : "Internal error",
14567
+ ...isAuthError(err) ? {} : { data: text5 }
14568
+ }
14569
+ });
14570
+ } finally {
14571
+ ctx.signal?.removeEventListener("abort", onAbort);
14572
+ }
14573
+ })();
14574
+ return () => {
14575
+ ctx.signal?.removeEventListener("abort", onAbort);
14576
+ cancelActiveLogin();
14577
+ };
14578
+ });
14579
+ }
14580
+ async logout(message, ctx) {
14581
+ let reply;
14582
+ if (ctx.signal?.aborted) {
14583
+ reply = { error: { code: -32800, message: "Request cancelled" } };
14584
+ } else {
14585
+ try {
14586
+ const transport = await this.getOrStartTransport();
14587
+ if (ctx.signal?.aborted) {
14588
+ reply = { error: { code: -32800, message: "Request cancelled" } };
14589
+ } else {
14590
+ await transport.request("account/logout", void 0);
14591
+ this.authVerified = false;
14592
+ this.cachedModels = void 0;
14593
+ reply = { result: {} };
14594
+ }
14595
+ } catch (error) {
14596
+ const text5 = error instanceof Error ? error.message : String(error);
14597
+ reply = { error: { code: -32603, message: "Internal error", data: text5 } };
14598
+ }
13066
14599
  }
13067
14600
  return {
13068
14601
  type: "protocol.reply",
@@ -13076,6 +14609,187 @@ var init_client6 = __esm({
13076
14609
  timestamp: Date.now()
13077
14610
  };
13078
14611
  }
14612
+ async deleteSession(message, ctx) {
14613
+ const params = message.request.params;
14614
+ let reply;
14615
+ try {
14616
+ const transport = await this.getOrStartTransport();
14617
+ await this.ensureAuthenticated(transport);
14618
+ await transport.request("thread/delete", { threadId: params.sessionId });
14619
+ if (ctx.sessions?.get(params.sessionId)) {
14620
+ await ctx.sessions.close(params.sessionId);
14621
+ } else {
14622
+ await this.closeSession(params.sessionId);
14623
+ }
14624
+ reply = { result: {} };
14625
+ } catch (error) {
14626
+ if (isAuthError(error)) {
14627
+ this.authVerified = false;
14628
+ reply = { error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(error) } };
14629
+ } else {
14630
+ const text5 = error instanceof Error ? error.message : String(error);
14631
+ const isUnknownThread = /no rollout found|not found|unknown thread|invalid thread/i.test(
14632
+ text5
14633
+ );
14634
+ reply = isUnknownThread ? {
14635
+ error: {
14636
+ code: -32002,
14637
+ message: `Unknown session ${params.sessionId}`,
14638
+ data: { sessionId: params.sessionId }
14639
+ }
14640
+ } : { error: { code: -32603, message: "Internal error", data: text5 } };
14641
+ }
14642
+ }
14643
+ return {
14644
+ type: "protocol.reply",
14645
+ ctx,
14646
+ request: message.request,
14647
+ correlation: {
14648
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
14649
+ sessionId: params.sessionId,
14650
+ rpcId: message.request.id
14651
+ },
14652
+ reply,
14653
+ timestamp: Date.now()
14654
+ };
14655
+ }
14656
+ async forkSession(message, ctx) {
14657
+ const params = message.request.params;
14658
+ const config = this.config;
14659
+ const makeReply = (sessionId, value) => ({
14660
+ type: "protocol.reply",
14661
+ ctx,
14662
+ request: message.request,
14663
+ correlation: {
14664
+ ...ctx.connection?.id ? { connectionId: ctx.connection.id } : {},
14665
+ ...sessionId ? { sessionId } : {},
14666
+ rpcId: message.request.id
14667
+ },
14668
+ reply: value,
14669
+ timestamp: Date.now()
14670
+ });
14671
+ let instructions;
14672
+ try {
14673
+ instructions = extractSystemPrompt(params.setup.params);
14674
+ } catch (err) {
14675
+ const msg = err instanceof Error ? err.message : String(err);
14676
+ return makeReply(params.sessionId, { error: { code: -32602, message: msg } });
14677
+ }
14678
+ try {
14679
+ const transport = await this.getOrStartTransport();
14680
+ await this.ensureAuthenticated(transport);
14681
+ const models = await this.loadModels(transport);
14682
+ const sourceSession = this.sessions.get(params.sessionId);
14683
+ const cwd = params.setup.cwd || sourceSession?.cwd || config.cwd || process.cwd();
14684
+ const mcpServersConfig = codexMcpServers(params.setup.mcpServers);
14685
+ const allowFullAccess = config.allowFullAccess === true;
14686
+ const baseMode = sourceSession?.choices.mode ?? config.mode;
14687
+ const settings = baseMode ? modeSettings(baseMode, cwd) : void 0;
14688
+ const configuredModel = sourceSession && sourceSession.choices.model !== DEFAULT_MODEL_ID2 ? sourceSession.choices.model : config.model;
14689
+ const directToolsEnabled = config.dynamicTools !== false;
14690
+ const dynamicTools = directToolsEnabled ? extractDynamicTools(ctx.connection?.clientCapabilities) : { specs: [], nameMap: /* @__PURE__ */ new Map() };
14691
+ const res = await transport.request("thread/fork", {
14692
+ threadId: params.sessionId,
14693
+ cwd,
14694
+ ...settings ? {
14695
+ approvalPolicy: settings.approvalPolicy,
14696
+ sandbox: settings.sandboxMode
14697
+ } : {},
14698
+ ...configuredModel ? { model: configuredModel } : {},
14699
+ ...Object.keys(mcpServersConfig).length ? { config: { mcp_servers: mcpServersConfig } } : {},
14700
+ ...instructions.developerInstructions ? { developerInstructions: instructions.developerInstructions } : {},
14701
+ ...instructions.baseInstructions ? { baseInstructions: instructions.baseInstructions } : {}
14702
+ });
14703
+ const forkedId = res?.thread?.id;
14704
+ if (typeof forkedId !== "string" || !forkedId) {
14705
+ throw new Error("Codex thread/fork returned no thread id");
14706
+ }
14707
+ const resolvedCwd = typeof res?.cwd === "string" && res.cwd ? res.cwd : typeof res?.thread?.cwd === "string" && res.thread.cwd ? res.thread.cwd : cwd;
14708
+ if (ctx.sessions) {
14709
+ await ctx.sessions.open({
14710
+ cwd: resolvedCwd,
14711
+ mcpServers: params.setup.mcpServers,
14712
+ params: params.setup.params,
14713
+ id: forkedId
14714
+ });
14715
+ ctx.sessionId = forkedId;
14716
+ const scope = ctx.sessions.get(forkedId);
14717
+ if (scope) ctx.session = scope;
14718
+ }
14719
+ const inferredMode = inferCodexMode(res?.approvalPolicy, res?.sandbox, allowFullAccess);
14720
+ const forkedSession = new CodexSession({
14721
+ threadId: forkedId,
14722
+ cwd: resolvedCwd,
14723
+ v2: ctx.connection?.protocol === 2,
14724
+ elicitation: elicitationSupport(ctx.connection?.clientCapabilities),
14725
+ subagentSessions: subagentSessionsSupport(ctx.connection?.clientCapabilities),
14726
+ choices: {
14727
+ mode: baseMode ?? inferredMode,
14728
+ model: configuredModel ?? (typeof res?.model === "string" && res.model ? res.model : DEFAULT_MODEL_ID2),
14729
+ effort: typeof res?.reasoningEffort === "string" && res.reasoningEffort ? res.reasoningEffort : sourceSession?.choices.effort ?? DEFAULT_EFFORT2,
14730
+ modes: availableCodexModes(allowFullAccess),
14731
+ models
14732
+ },
14733
+ terminalOutput: config.terminalOutput ?? terminalOutputFor(ctx),
14734
+ dynamicToolNames: dynamicTools.nameMap,
14735
+ ...dynamicTools.waitForKeyTool ? { waitForKeyTool: dynamicTools.waitForKeyTool } : {},
14736
+ mcpServersConfig,
14737
+ ...instructions.developerInstructions ? { developerInstructions: instructions.developerInstructions } : {},
14738
+ ...instructions.baseInstructions ? { baseInstructions: instructions.baseInstructions } : {},
14739
+ getTransport: () => this.getOrStartTransport(),
14740
+ ...this.logger ? { logger: this.logger } : {},
14741
+ ...ctx.sessionId ? { background: this.backgroundSink(forkedId, ctx) } : {}
14742
+ });
14743
+ this.sessions.set(forkedId, forkedSession);
14744
+ const v2 = ctx.connection?.protocol === 2;
14745
+ const fields = v2 ? v2SetupFields2(forkedSession.choices) : v1SetupFields2(forkedSession.choices);
14746
+ return makeReply(forkedId, { result: { sessionId: forkedId, ...fields } });
14747
+ } catch (error) {
14748
+ if (isAuthError(error)) {
14749
+ this.authVerified = false;
14750
+ return makeReply(params.sessionId, {
14751
+ error: { code: AUTH_REQUIRED_CODE, message: authErrorMessage(error) }
14752
+ });
14753
+ }
14754
+ const text5 = error instanceof Error ? error.message : String(error);
14755
+ const isUnknownThread = /no rollout found|not found|unknown thread|invalid thread/i.test(
14756
+ text5
14757
+ );
14758
+ return makeReply(
14759
+ params.sessionId,
14760
+ isUnknownThread ? {
14761
+ error: {
14762
+ code: -32002,
14763
+ message: `Unknown session ${params.sessionId}`,
14764
+ data: { sessionId: params.sessionId }
14765
+ }
14766
+ } : { error: { code: -32603, message: "Internal error", data: text5 } }
14767
+ );
14768
+ }
14769
+ }
14770
+ async ensureAuthenticated(transport) {
14771
+ if (this.authVerified) return;
14772
+ let res;
14773
+ try {
14774
+ res = await transport.request(
14775
+ "account/read",
14776
+ {}
14777
+ );
14778
+ } catch (err) {
14779
+ if (err instanceof CodexRpcError && err.code === -32601) {
14780
+ this.authVerified = true;
14781
+ return;
14782
+ }
14783
+ if (isAuthError(err)) {
14784
+ throw new CodexAuthRequiredError(err instanceof Error ? err.message : String(err));
14785
+ }
14786
+ return;
14787
+ }
14788
+ if (res?.requiresOpenaiAuth === true && !res.account) {
14789
+ throw new CodexAuthRequiredError();
14790
+ }
14791
+ this.authVerified = true;
14792
+ }
13079
14793
  configure(message, ctx) {
13080
14794
  const params = message.request.params;
13081
14795
  const reply = (value) => ({
@@ -13217,6 +14931,7 @@ var init_client6 = __esm({
13217
14931
  },
13218
14932
  terminalOutput: config.terminalOutput ?? terminalOutputFor(ctx),
13219
14933
  dynamicToolNames: dynamicTools.nameMap,
14934
+ ...dynamicTools.waitForKeyTool ? { waitForKeyTool: dynamicTools.waitForKeyTool } : {},
13220
14935
  mcpServersConfig,
13221
14936
  getTransport: () => this.getOrStartTransport(),
13222
14937
  ...this.logger ? { logger: this.logger } : {},
@@ -13249,7 +14964,17 @@ var init_client6 = __esm({
13249
14964
  if (this.transport === transport) {
13250
14965
  this.transport = void 0;
13251
14966
  this.cachedModels = void 0;
14967
+ this.authVerified = false;
13252
14968
  this.attachedChildThreads.clear();
14969
+ this.unmatchedLoginOutcomes.clear();
14970
+ for (const waiter of [...this.loginWaiters]) {
14971
+ this.loginWaiters.delete(waiter);
14972
+ waiter.resolve({
14973
+ loginId: waiter.loginId ?? null,
14974
+ success: false,
14975
+ error: error?.message ?? "Codex App Server closed during login."
14976
+ });
14977
+ }
13253
14978
  }
13254
14979
  if (error) {
13255
14980
  const seen = /* @__PURE__ */ new Set();
@@ -13336,6 +15061,43 @@ var init_client6 = __esm({
13336
15061
  }
13337
15062
  routeNotification(notification) {
13338
15063
  const { method, params } = notification;
15064
+ if (method === "account/login/completed") {
15065
+ const loginId = typeof params.loginId === "string" ? params.loginId : null;
15066
+ const success = params.success === true;
15067
+ const error = typeof params.error === "string" ? params.error : null;
15068
+ const outcome = { loginId, success, error };
15069
+ if (success) {
15070
+ this.authVerified = true;
15071
+ this.cachedModels = void 0;
15072
+ }
15073
+ let matched = false;
15074
+ for (const waiter of [...this.loginWaiters]) {
15075
+ if (!loginId || !waiter.loginId || waiter.loginId === loginId) {
15076
+ this.loginWaiters.delete(waiter);
15077
+ waiter.resolve(outcome);
15078
+ matched = true;
15079
+ break;
15080
+ }
15081
+ }
15082
+ if (!matched && loginId) {
15083
+ if (this.unmatchedLoginOutcomes.size >= 32) {
15084
+ const oldest = this.unmatchedLoginOutcomes.keys().next().value;
15085
+ if (oldest !== void 0) this.unmatchedLoginOutcomes.delete(oldest);
15086
+ }
15087
+ this.unmatchedLoginOutcomes.set(loginId, outcome);
15088
+ }
15089
+ return;
15090
+ }
15091
+ if (method === "account/updated") {
15092
+ if ("authMode" in params && params.authMode === null) {
15093
+ this.authVerified = false;
15094
+ this.cachedModels = void 0;
15095
+ } else if (typeof params.authMode === "string") {
15096
+ this.authVerified = true;
15097
+ this.cachedModels = void 0;
15098
+ }
15099
+ return;
15100
+ }
13339
15101
  if (method === "thread/started" && isRecord15(params.thread)) {
13340
15102
  const childId = typeof params.thread.id === "string" ? params.thread.id : "";
13341
15103
  const parentId = extractSubagentParentThreadId(params.thread);
@@ -13379,7 +15141,7 @@ var init_client6 = __esm({
13379
15141
  await session.handleServerRequest(req);
13380
15142
  }
13381
15143
  async ask(ctx, emit, method, params, signal) {
13382
- const full = { sessionId: ctx.sessionId, ...params };
15144
+ const full = ctx.sessionId !== void 0 ? { sessionId: ctx.sessionId, ...params } : { ...params };
13383
15145
  const signals = [signal, ctx.signal].filter((s) => s !== void 0);
13384
15146
  const wait = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
13385
15147
  if (ctx.interactions && ctx.client) return requestThroughGraph(ctx, emit, method, full, wait);
@@ -15834,12 +17596,12 @@ var init_normalizer7 = __esm({
15834
17596
  });
15835
17597
 
15836
17598
  // packages/nodes/src/grok/filesystem-fulfillment.ts
15837
- import { existsSync, readdirSync, readFileSync } from "node:fs";
15838
- import { basename, isAbsolute as isAbsolute2, join as join3, resolve as resolve3 } from "node:path";
17599
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
17600
+ import { basename, isAbsolute as isAbsolute4, join as join4, resolve as resolve4 } from "node:path";
15839
17601
  function resolveTargetPath(path2, cwd) {
15840
17602
  if (!path2) return void 0;
15841
17603
  const base = cwd ?? process.cwd();
15842
- return isAbsolute2(path2) ? path2 : resolve3(base, path2);
17604
+ return isAbsolute4(path2) ? path2 : resolve4(base, path2);
15843
17605
  }
15844
17606
  function isReadMethod(method) {
15845
17607
  return method.endsWith("/read_file") || method.endsWith("/read") || method.endsWith("/read_file/") || method.endsWith("/read/");
@@ -15873,7 +17635,7 @@ function fulfillFilesystemRequest(method, params = {}, sessionCwd2) {
15873
17635
  const target = resolveTargetPath(path2, cwd);
15874
17636
  if (!target) return { exists: false };
15875
17637
  try {
15876
- return { exists: existsSync(target) };
17638
+ return { exists: existsSync2(target) };
15877
17639
  } catch {
15878
17640
  return { exists: false };
15879
17641
  }
@@ -15885,7 +17647,7 @@ function fulfillFilesystemRequest(method, params = {}, sessionCwd2) {
15885
17647
  const entries = readdirSync(dirPath, { withFileTypes: true });
15886
17648
  const limit = params.limit !== void 0 ? Number(params.limit) : entries.length;
15887
17649
  const nodes = entries.slice(0, limit).map((entry) => ({
15888
- path: join3(dirPath, entry.name),
17650
+ path: join4(dirPath, entry.name),
15889
17651
  name: entry.name,
15890
17652
  kind: entry.isDirectory() ? "directory" : "file"
15891
17653
  }));
@@ -15900,7 +17662,7 @@ function fulfillFilesystemRequest(method, params = {}, sessionCwd2) {
15900
17662
  return method.includes("read_file") ? { content_base64: "", total_bytes: 0 } : { content: "" };
15901
17663
  }
15902
17664
  try {
15903
- const raw = readFileSync(target, "utf8");
17665
+ const raw = readFileSync2(target, "utf8");
15904
17666
  const content2 = sliceFileContent(raw, params);
15905
17667
  if (method.includes("read_file")) {
15906
17668
  const bytes2 = Buffer.from(content2, "utf8");
@@ -17070,15 +18832,33 @@ var init_interactions = __esm({
17070
18832
  import { randomUUID as randomUUID12 } from "node:crypto";
17071
18833
  import { ClassicPreset as ClassicPreset39 } from "rete";
17072
18834
  import { concat, concatMap as concatMap2, defer, EMPTY as EMPTY3, from as from5, mergeMap as mergeMap11 } from "rxjs";
17073
- function graphAgentCapabilities(nodes) {
18835
+ function mergeCapabilities(...sources) {
17074
18836
  const out = {};
17075
- for (const node of nodes) {
17076
- const caps = node.agentCapabilities?.();
17077
- for (const [key2, value] of Object.entries(caps ?? {}))
18837
+ for (const source of sources) {
18838
+ if (!source) continue;
18839
+ for (const [key2, value] of Object.entries(source))
17078
18840
  out[key2] = isRecord2(value) && isRecord2(out[key2]) ? { ...out[key2], ...value } : value;
17079
18841
  }
17080
18842
  return out;
17081
18843
  }
18844
+ function graphAgentCapabilities(nodes) {
18845
+ let out = {};
18846
+ for (const node of nodes) out = mergeCapabilities(out, node.agentCapabilities?.());
18847
+ return out;
18848
+ }
18849
+ function graphAuthMethods(nodes) {
18850
+ const out = [];
18851
+ const seen = /* @__PURE__ */ new Set();
18852
+ for (const node of nodes) {
18853
+ for (const method of node.authMethods?.() ?? []) {
18854
+ const id = typeof method.id === "string" ? method.id : void 0;
18855
+ if (id && seen.has(id)) continue;
18856
+ if (id) seen.add(id);
18857
+ out.push(method);
18858
+ }
18859
+ }
18860
+ return out;
18861
+ }
17082
18862
  function graphAcceptsPromptsMidTurn(nodes) {
17083
18863
  for (const node of nodes) if (node.acceptsPromptsMidTurn?.() === true) return true;
17084
18864
  return false;
@@ -17311,6 +19091,7 @@ var init_nodes = __esm({
17311
19091
  sessions: connection?.sessions ?? front.sessions,
17312
19092
  ...front.store ? { store: front.store } : {},
17313
19093
  ...front.agentCapabilities ? { agentCapabilities: front.agentCapabilities() } : {},
19094
+ ...front.authMethods ? { authMethods: front.authMethods() } : {},
17314
19095
  ...front.reduction ? { reduction: front.reduction } : {}
17315
19096
  };
17316
19097
  }
@@ -17520,13 +19301,15 @@ var init_nodes = __esm({
17520
19301
  title: config.agentTitle ?? "Bridge",
17521
19302
  version: config.agentVersion ?? BRIDGE_VERSION
17522
19303
  },
17523
- agentCapabilities: {
17524
- loadSession: false,
17525
- promptCapabilities: { image: false, audio: false, embeddedContext: false },
17526
- ...ctx.agentCapabilities ?? {},
17527
- ...config.agentCapabilities ?? {}
17528
- },
17529
- authMethods: []
19304
+ agentCapabilities: mergeCapabilities(
19305
+ {
19306
+ loadSession: false,
19307
+ promptCapabilities: { image: false, audio: false, embeddedContext: false }
19308
+ },
19309
+ ctx.agentCapabilities,
19310
+ config.agentCapabilities
19311
+ ),
19312
+ authMethods: config.authMethods ?? ctx.authMethods ?? []
17530
19313
  };
17531
19314
  return [this.reply(event, { result: version === 2 ? initializeResultToV2(v1) : v1 })];
17532
19315
  }
@@ -20095,7 +21878,7 @@ var init_streaming2 = __esm({
20095
21878
  });
20096
21879
 
20097
21880
  // packages/nodes/src/index.ts
20098
- var init_src3 = __esm({
21881
+ var init_src4 = __esm({
20099
21882
  "packages/nodes/src/index.ts"() {
20100
21883
  init_sockets();
20101
21884
  init_registry();
@@ -20996,754 +22779,136 @@ function jsonErrorOffset(text5) {
20996
22779
  }
20997
22780
  for (; ; ) {
20998
22781
  member();
20999
- ws();
21000
- if (text5[i] === close) {
21001
- i += 1;
21002
- return;
21003
- }
21004
- if (text5[i] !== ",") fail2();
21005
- i += 1;
21006
- }
21007
- };
21008
- const value = () => {
21009
- ws();
21010
- const ch = text5[i];
21011
- if (ch === "{") {
21012
- return members("}", () => {
21013
- ws();
21014
- if (text5[i] !== '"') fail2();
21015
- string();
21016
- ws();
21017
- if (text5[i] !== ":") fail2();
21018
- i += 1;
21019
- value();
21020
- });
21021
- }
21022
- if (ch === "[") return members("]", value);
21023
- if (ch === '"') return string();
21024
- if (ch === "t") return literal("true");
21025
- if (ch === "f") return literal("false");
21026
- if (ch === "n") return literal("null");
21027
- if (ch === "-" || ch !== void 0 && ch >= "0" && ch <= "9") {
21028
- if (text5[i] === "-") i += 1;
21029
- if (text5[i] === "0") i += 1;
21030
- else digits();
21031
- if (text5[i] === ".") {
21032
- i += 1;
21033
- digits();
21034
- }
21035
- if (text5[i] === "e" || text5[i] === "E") {
21036
- i += 1;
21037
- if (text5[i] === "+" || text5[i] === "-") i += 1;
21038
- digits();
21039
- }
21040
- return;
21041
- }
21042
- fail2();
21043
- };
21044
- try {
21045
- value();
21046
- ws();
21047
- if (i < text5.length) fail2();
21048
- } catch (error) {
21049
- return error instanceof JsonOffset ? Math.min(error.offset, text5.length) : void 0;
21050
- }
21051
- return void 0;
21052
- }
21053
- function describeOffset(text5, offset) {
21054
- if (offset === void 0) return "a position Bridge could not find";
21055
- if (offset >= text5.length) return "the end (it is incomplete)";
21056
- const before = text5.slice(0, offset);
21057
- const line = before.split("\n").length;
21058
- const column = offset - before.lastIndexOf("\n");
21059
- return `position ${offset} (line ${line} column ${column})`;
21060
- }
21061
- function resolveReferences(value, options, at = "config") {
21062
- const env3 = options.env ?? process.env;
21063
- if (isReference(value)) {
21064
- const fromConfig = value.$config !== void 0 ? lookup(options.config, value.$config) : void 0;
21065
- if (fromConfig !== void 0 && fromConfig !== "") return fromConfig;
21066
- const fromEnv = value.$env !== void 0 && Object.hasOwn(env3, value.$env) ? env3[value.$env] : void 0;
21067
- if (fromEnv !== void 0 && fromEnv !== "") {
21068
- if (value.$json !== true) return fromEnv;
21069
- try {
21070
- return JSON.parse(fromEnv);
21071
- } catch {
21072
- throw new Error(
21073
- `${at}: environment variable ${value.$env} must be JSON (it is read with "$json": true), but it is not valid JSON at ${describeOffset(fromEnv, jsonErrorOffset(fromEnv))}`
21074
- );
21075
- }
21076
- }
21077
- return value.$default;
21078
- }
21079
- if (Array.isArray(value)) {
21080
- return value.map((item, index) => resolveReferences(item, options, `${at}[${index}]`));
21081
- }
21082
- if (isRecord19(value)) {
21083
- const out = {};
21084
- for (const [key2, item] of Object.entries(value)) {
21085
- const resolved = resolveReferences(item, options, `${at}.${key2}`);
21086
- if (resolved !== void 0) out[key2] = resolved;
21087
- }
21088
- return out;
21089
- }
21090
- return value;
21091
- }
21092
- function resolveGraphReferences(graph, options) {
21093
- return {
21094
- ...graph,
21095
- nodes: graph.nodes.map((node) => ({
21096
- ...node,
21097
- config: resolveReferences(node.config ?? {}, options, `node "${node.id}" config`) ?? {}
21098
- }))
21099
- };
21100
- }
21101
- var isRecord19, isReference, isPlainRecord, JsonOffset;
21102
- var init_references2 = __esm({
21103
- "packages/engine/src/references.ts"() {
21104
- "use strict";
21105
- init_src3();
21106
- isRecord19 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
21107
- isReference = isConfigReference;
21108
- isPlainRecord = (value) => {
21109
- if (!isRecord19(value)) return false;
21110
- const proto = Object.getPrototypeOf(value);
21111
- return proto === Object.prototype || proto === null;
21112
- };
21113
- JsonOffset = class extends Error {
21114
- constructor(offset) {
21115
- super(`invalid JSON at ${offset}`);
21116
- this.offset = offset;
21117
- }
21118
- offset;
21119
- };
21120
- }
21121
- });
21122
-
21123
- // packages/engine/src/index.ts
21124
- var init_src4 = __esm({
21125
- "packages/engine/src/index.ts"() {
21126
- init_graph();
21127
- init_engine();
21128
- init_references2();
21129
- }
21130
- });
21131
-
21132
- // packages/config/src/schema.ts
21133
- import { isAbsolute as isAbsolute3 } from "node:path";
21134
- import { z as z3 } from "zod";
21135
- function exportersOf(setting) {
21136
- if (setting === "none") return [];
21137
- return typeof setting === "string" ? [setting] : [...new Set(setting)];
21138
- }
21139
- var BACKENDS, ProxyConfigSchema, AnthropicBackendSchema, OpenAIBackendSchema, BackendsConfigSchema, ServerConfigSchema, GraphConfigSchema, LoggingConfigSchema, OTEL_EXPORTERS, ExporterSettingSchema, TelemetryConfigSchema, ReductionConfigSchema, ConfigSchema, TrustedFoldersSchema, RawConfigSchema, EnvironmentSchema;
21140
- var init_schema = __esm({
21141
- "packages/config/src/schema.ts"() {
21142
- "use strict";
21143
- init_src();
21144
- BACKENDS = [
21145
- "openai",
21146
- "anthropic",
21147
- "grok",
21148
- "ideal",
21149
- "claude-sdk",
21150
- "codex-app-server"
21151
- ];
21152
- ProxyConfigSchema = z3.object({
21153
- defaultBackend: z3.enum(BACKENDS).default("openai")
21154
- });
21155
- AnthropicBackendSchema = z3.object({
21156
- apiKey: z3.string().optional(),
21157
- /** Base URL override (a proxy, or a local test server). */
21158
- baseURL: z3.string().optional(),
21159
- defaultModel: z3.string().default("claude-sonnet-4-20250514"),
21160
- defaultMaxTokens: z3.number().optional(),
21161
- maxRetries: z3.number().default(3),
21162
- timeoutMs: z3.number().default(12e4)
21163
- });
21164
- OpenAIBackendSchema = z3.object({
21165
- apiKey: z3.string().optional(),
21166
- baseURL: z3.string().optional(),
21167
- defaultModel: z3.string().default("gpt-4.1"),
21168
- maxRetries: z3.number().default(3),
21169
- timeoutMs: z3.number().default(12e4),
21170
- /**
21171
- * Tool calling: 'native' (default) offers the model Bridge's built-in tools and the
21172
- * client's MCP servers' tools in the OpenAI tools parameter; 'none' offers no tools,
21173
- * and Bridge does not advertise or connect the client's MCP servers.
21174
- * ('gemma-prompt' was dropped with the classic server; the Gemma nodes remain for graphs.)
21175
- */
21176
- toolMode: z3.enum(["native", "none"]).default("native"),
21177
- /** Maximum tool calling loop iterations per prompt (default: 5) */
21178
- maxToolIterations: z3.number().default(5)
21179
- });
21180
- BackendsConfigSchema = z3.object({
21181
- anthropic: AnthropicBackendSchema.optional(),
21182
- openai: OpenAIBackendSchema.optional(),
21183
- ideal: z3.object({
21184
- /** Required for defaultBackend = "ideal" (the only backend with an `enabled`). */
21185
- enabled: z3.boolean().default(true),
21186
- module: z3.string().min(1),
21187
- sessionCodeExec: z3.string().min(1).optional(),
21188
- permissionMode: z3.enum(["manual", "acp", "auto-allow"]).optional(),
21189
- options: z3.record(z3.string(), z3.unknown()).default({})
21190
- }).optional(),
21191
- grok: z3.object({
21192
- command: z3.string().default("grok"),
21193
- args: z3.array(z3.string()).default(["agent", "stdio"]),
21194
- env: z3.record(z3.string(), z3.string()).optional(),
21195
- defaultModel: z3.string().optional(),
21196
- requestTimeoutMs: z3.number().int().nonnegative().optional()
21197
- }).optional(),
21198
- codex: z3.object({
21199
- command: z3.string().default("codex"),
21200
- args: z3.array(z3.string()).default(["app-server", "--listen", "stdio://"]),
21201
- env: z3.record(z3.string(), z3.string()).optional(),
21202
- model: z3.string().min(1).optional(),
21203
- mode: z3.enum(["default", "read-only", "auto", "full-access"]).optional(),
21204
- allowFullAccess: z3.boolean().optional(),
21205
- dynamicTools: z3.boolean().optional(),
21206
- cancelGraceMs: z3.number().int().nonnegative().optional(),
21207
- requestTimeoutMs: z3.number().int().nonnegative().optional()
21208
- }).optional()
21209
- });
21210
- ServerConfigSchema = z3.object({
21211
- port: z3.number().default(6809),
21212
- host: z3.string().default("localhost"),
21213
- transport: z3.enum(["stdio", "http", "pi-rpc"]).default("stdio"),
21214
- /** Browser origins allowed to call the HTTP transport (default: none). */
21215
- allowedOrigins: z3.array(z3.string()).default([]),
21216
- /**
21217
- * Bearer token for the HTTP transport (env BRIDGE_HTTP_TOKEN). When set, every request
21218
- * must carry `Authorization: Bearer <token>`. Required to listen on a host that is not
21219
- * loopback (localhost, 127.0.0.0/8, ::1).
21220
- */
21221
- httpToken: z3.string().min(1).optional(),
21222
- /**
21223
- * Internal hosts an HTTP client's http/sse MCP servers may point at (env
21224
- * BRIDGE_MCP_ALLOWED_HOSTS, comma-separated): host names, IP addresses or CIDR ranges.
21225
- * Over HTTP, MCP server URLs on loopback, private, link-local (cloud metadata), CGNAT or
21226
- * unspecified addresses are refused unless listed here. Stdio clients are not checked.
21227
- */
21228
- mcpAllowedHosts: z3.array(z3.string()).default([]),
21229
- /**
21230
- * The ACP versions served (env BRIDGE_ACP_PROTOCOLS, CLI --acp-protocols, e.g. `1,2`).
21231
- * Default v1 and v2: a client gets the one it asks for.
21232
- */
21233
- acpProtocols: z3.array(z3.union([z3.literal(1), z3.literal(2)])).min(1).default([1, 2])
21234
- });
21235
- GraphConfigSchema = z3.object({
21236
- defaultGraph: z3.string().default("graphs/default.json"),
21237
- graphDir: z3.string().default("graphs")
21238
- });
21239
- LoggingConfigSchema = z3.object({
21240
- level: z3.enum(["debug", "info", "warn", "error"]).default("info"),
21241
- pretty: z3.boolean().default(false),
21242
- /** Output format. `pretty` remains as a legacy alias for format = "pretty". */
21243
- format: z3.enum(["json", "pretty"]).default("json"),
21244
- /** Optional file sink. stderr remains the default and stdout is never used for logs. */
21245
- file: z3.string().optional(),
21246
- /** Whether to keep stderr logging enabled when a file sink is configured. */
21247
- stderr: z3.boolean().default(true)
21248
- });
21249
- OTEL_EXPORTERS = ["console", "otlp"];
21250
- ExporterSettingSchema = z3.union([
21251
- z3.enum(["none", ...OTEL_EXPORTERS]),
21252
- z3.array(z3.enum(OTEL_EXPORTERS))
21253
- ]);
21254
- TelemetryConfigSchema = z3.object({
21255
- enabled: z3.boolean().default(false),
21256
- serviceName: z3.string().default("bridge"),
21257
- serviceVersion: z3.string().default(BRIDGE_VERSION),
21258
- otlpEndpoint: z3.string().optional(),
21259
- traces: z3.object({
21260
- enabled: z3.boolean().default(true),
21261
- exporter: ExporterSettingSchema.default("console"),
21262
- sampleRate: z3.number().min(0).max(1).default(1)
21263
- }).prefault({}),
21264
- metrics: z3.object({
21265
- enabled: z3.boolean().default(true),
21266
- exporter: ExporterSettingSchema.default("console"),
21267
- exportIntervalMs: z3.number().int().positive().default(6e4)
21268
- }).prefault({}),
21269
- logs: z3.object({
21270
- /** Export Bridge's log lines as OpenTelemetry log records: those [logging] level lets through. */
21271
- export: z3.boolean().default(false),
21272
- exporter: ExporterSettingSchema.default("none")
21273
- }).prefault({}),
21274
- instrumentation: z3.object({
21275
- http: z3.boolean().default(false),
21276
- pino: z3.boolean().default(true)
21277
- }).prefault({})
21278
- });
21279
- ReductionConfigSchema = z3.object({
21280
- enabled: z3.boolean().default(true),
21281
- maxInlineChars: z3.number().int().positive().default(1200),
21282
- storeArtifacts: z3.boolean().default(false),
21283
- recordStats: z3.boolean().default(true),
21284
- preserveFileReads: z3.boolean().default(true),
21285
- projectRulesDir: z3.string().default(".bridge/reducers"),
21286
- tokenjuiceCompatibilityRulesDir: z3.string().default(".tokenjuice/rules"),
21287
- artifactDir: z3.string().default(".bridge/reduction-artifacts"),
21288
- /** Stored artifacts kept: past any of these, the oldest are deleted (an open session's stay). */
21289
- artifactMaxCount: z3.number().int().positive().default(1e3),
21290
- artifactMaxBytes: z3.number().int().positive().default(256 * 1024 * 1024),
21291
- artifactMaxAgeDays: z3.number().positive().default(7)
21292
- });
21293
- ConfigSchema = z3.object({
21294
- proxy: ProxyConfigSchema,
21295
- backends: BackendsConfigSchema,
21296
- server: ServerConfigSchema,
21297
- graph: GraphConfigSchema,
21298
- logging: LoggingConfigSchema,
21299
- telemetry: TelemetryConfigSchema.prefault({}),
21300
- reduction: ReductionConfigSchema.prefault({})
21301
- }).superRefine((config, ctx) => {
21302
- if (config.proxy.defaultBackend === "ideal" && !config.backends.ideal?.enabled) {
21303
- ctx.addIssue({
21304
- code: "custom",
21305
- path: ["backends", "ideal"],
21306
- message: "The Ideal backend requires an enabled runtime module"
21307
- });
21308
- }
21309
- });
21310
- TrustedFoldersSchema = z3.array(
21311
- z3.string().min(1).refine((entry) => isAbsolute3(entry) || /^~(?=$|[\\/])/.test(entry), {
21312
- message: "trustedFolders entries must be absolute paths or start with ~/"
21313
- })
21314
- );
21315
- RawConfigSchema = z3.object({
21316
- profiles: z3.record(z3.string(), z3.record(z3.string(), z3.unknown())).optional(),
21317
- trustedFolders: TrustedFoldersSchema.optional()
21318
- });
21319
- EnvironmentSchema = z3.object({
21320
- ANTHROPIC_API_KEY: z3.string().optional(),
21321
- OPENAI_API_KEY: z3.string().optional(),
21322
- BRIDGE_BACKEND: z3.enum(BACKENDS).optional(),
21323
- GROK_COMMAND: z3.string().optional(),
21324
- CODEX_COMMAND: z3.string().optional(),
21325
- LOG_LEVEL: z3.enum(["debug", "info", "warn", "error"]).optional(),
21326
- BRIDGE_LOG_LEVEL: z3.enum(["debug", "info", "warn", "error"]).optional(),
21327
- BRIDGE_LOG_FILE: z3.string().optional(),
21328
- BRIDGE_LOG_FORMAT: z3.enum(["json", "pretty"]).optional(),
21329
- BRIDGE_PROFILE: z3.string().optional(),
21330
- BRIDGE_PORT: z3.coerce.number().int().positive().optional(),
21331
- /** Comma-separated ACP versions to serve, e.g. `1,2` (server.acpProtocols). */
21332
- BRIDGE_ACP_PROTOCOLS: z3.string().optional(),
21333
- /** Comma-separated browser origins allowed to call the HTTP transport. */
21334
- BRIDGE_ALLOWED_ORIGINS: z3.string().optional(),
21335
- /** Bearer token the HTTP transport requires (server.httpToken). */
21336
- BRIDGE_HTTP_TOKEN: z3.string().optional(),
21337
- /** Comma-separated internal hosts HTTP clients' MCP servers may use (server.mcpAllowedHosts). */
21338
- BRIDGE_MCP_ALLOWED_HOSTS: z3.string().optional(),
21339
- TRANSPORT: z3.enum(["stdio", "http", "pi-rpc"]).optional(),
21340
- BRIDGE_TRANSPORT: z3.enum(["stdio", "http", "pi-rpc"]).optional(),
21341
- BRIDGE_TELEMETRY_ENABLED: z3.enum(["true", "false"]).optional().transform((value) => value === void 0 ? void 0 : value === "true"),
21342
- BRIDGE_TELEMETRY_LOGS_EXPORT: z3.enum(["true", "false"]).optional().transform((value) => value === void 0 ? void 0 : value === "true"),
21343
- /** Normalized by loadEnvironment from a comma-separated list. */
21344
- OTEL_LOGS_EXPORTER: ExporterSettingSchema.optional(),
21345
- OTEL_SERVICE_NAME: z3.string().optional(),
21346
- OTEL_EXPORTER_OTLP_ENDPOINT: z3.string().optional()
21347
- });
21348
- }
21349
- });
21350
-
21351
- // packages/config/src/trust.ts
21352
- import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync } from "node:fs";
21353
- import { homedir as homedir2, userInfo } from "node:os";
21354
- import { dirname as dirname2, isAbsolute as isAbsolute4, join as join4, resolve as resolve4 } from "node:path";
21355
- import { parse as parseToml } from "smol-toml";
21356
- function homeFolder() {
21357
- const home = homedir2();
21358
- if (isAbsolute4(home)) return home;
21359
- const account = userInfo().homedir;
21360
- if (isAbsolute4(account)) return account;
21361
- throw new Error(
21362
- "Cannot find the home folder for the user config ($HOME is not an absolute path)"
21363
- );
21364
- }
21365
- function userConfigPath(homeDir = homeFolder()) {
21366
- return join4(homeDir, ".config", "bridge", "config.toml");
21367
- }
21368
- function expandHome(path2, homeDir = homeFolder()) {
21369
- return /^~(?=$|[\\/])/.test(path2) ? join4(homeDir, path2.slice(1)) : path2;
21370
- }
21371
- function realPath(path2) {
21372
- try {
21373
- return realpathSync(path2);
21374
- } catch {
21375
- return resolve4(path2);
21376
- }
21377
- }
21378
- function readTrustedFolders(configPath, homeDir = homeFolder()) {
21379
- if (!existsSync2(configPath)) return [];
21380
- let raw;
21381
- try {
21382
- raw = parseToml(readFileSync2(configPath, "utf8"));
21383
- } catch (error) {
21384
- throw new Error(
21385
- `Cannot read trustedFolders from ${configPath}: ${error instanceof Error ? error.message : String(error)}`
21386
- );
21387
- }
21388
- if (raw.trustedFolders === void 0) return [];
21389
- const parsed = TrustedFoldersSchema.safeParse(raw.trustedFolders);
21390
- if (!parsed.success) {
21391
- throw new Error(`Invalid trustedFolders in ${configPath}: ${parsed.error.message}`);
21392
- }
21393
- return parsed.data.map((entry) => realPath(expandHome(entry, homeDir)));
21394
- }
21395
- function isTrustedFolder(folder, options = {}) {
21396
- const homeDir = options.homeDir ?? homeFolder();
21397
- const trusted = readTrustedFolders(options.userConfig ?? userConfigPath(homeDir), homeDir);
21398
- return trusted.includes(realPath(folder));
21399
- }
21400
- function untrustedConfigWarning(path2, options = {}) {
21401
- const homeDir = options.homeDir ?? homeFolder();
21402
- const userConfig = options.userConfig ?? userConfigPath(homeDir);
21403
- const folder = realPath(dirname2(path2));
21404
- const hint = options.explicitHint ?? "--config";
21405
- return `Bridge: ignoring ${path2}: config files in the working folder are used only if the folder is trusted. To use it, add ${JSON.stringify(folder)} to trustedFolders in ${userConfig}, or name the file with ${hint}.
21406
- `;
21407
- }
21408
- function locateConfigFile(options = {}) {
21409
- const homeDir = options.homeDir ?? homeFolder();
21410
- const userConfig = options.userConfig ?? userConfigPath(homeDir);
21411
- if (options.explicit) return { path: resolve4(options.explicit), source: "explicit", userConfig };
21412
- const cwd = options.cwd ?? process.cwd();
21413
- const folderFile = FOLDER_CONFIG_NAMES.map((name) => resolve4(cwd, name)).find(
21414
- (path2) => existsSync2(path2)
21415
- );
21416
- if (folderFile) {
21417
- if (isTrustedFolder(cwd, { homeDir, userConfig })) {
21418
- return { path: folderFile, source: "folder", userConfig };
22782
+ ws();
22783
+ if (text5[i] === close) {
22784
+ i += 1;
22785
+ return;
22786
+ }
22787
+ if (text5[i] !== ",") fail2();
22788
+ i += 1;
21419
22789
  }
21420
- const warn = options.warn ?? ((message) => process.stderr.write(message));
21421
- warn(
21422
- untrustedConfigWarning(folderFile, {
21423
- homeDir,
21424
- userConfig,
21425
- explicitHint: options.explicitHint
21426
- })
21427
- );
21428
- }
21429
- return existsSync2(userConfig) ? { path: userConfig, source: "user", userConfig } : { userConfig };
21430
- }
21431
- var FOLDER_CONFIG_NAMES;
21432
- var init_trust = __esm({
21433
- "packages/config/src/trust.ts"() {
21434
- "use strict";
21435
- init_schema();
21436
- FOLDER_CONFIG_NAMES = ["bridge.toml", ".bridge.toml"];
21437
- }
21438
- });
21439
-
21440
- // packages/config/src/loader.ts
21441
- import { readFile as readFile3 } from "fs/promises";
21442
- import { parse as parseToml2 } from "smol-toml";
21443
- function isPlainObject2(value) {
21444
- return typeof value === "object" && value !== null && !Array.isArray(value);
21445
- }
21446
- function deepMergeConfig(base, overlay) {
21447
- const merged = { ...base };
21448
- for (const [key2, value] of Object.entries(overlay)) {
21449
- const current = merged[key2];
21450
- merged[key2] = isPlainObject2(current) && isPlainObject2(value) ? deepMergeConfig(current, value) : value;
21451
- }
21452
- return merged;
21453
- }
21454
- function withoutProfiles(config) {
21455
- const rest = { ...config };
21456
- delete rest.profiles;
21457
- return rest;
21458
- }
21459
- function parseProfileList(profile) {
21460
- return profile ? profile.split(",").map((name) => name.trim()).filter((name) => name.length > 0) : [];
21461
- }
21462
- function applyProfileConfig(rawConfig, profile) {
21463
- const base = withoutProfiles(rawConfig);
21464
- const selectedProfileNames = parseProfileList(profile);
21465
- if (selectedProfileNames.length === 0) {
21466
- return base;
21467
- }
21468
- const profiles = isPlainObject2(rawConfig.profiles) ? rawConfig.profiles : {};
21469
- const selectedProfiles = selectedProfileNames.map((profileName) => {
21470
- const selected = profiles[profileName];
21471
- if (!isPlainObject2(selected)) {
21472
- throw new Error(`Configuration profile not found: ${profileName}`);
22790
+ };
22791
+ const value = () => {
22792
+ ws();
22793
+ const ch = text5[i];
22794
+ if (ch === "{") {
22795
+ return members("}", () => {
22796
+ ws();
22797
+ if (text5[i] !== '"') fail2();
22798
+ string();
22799
+ ws();
22800
+ if (text5[i] !== ":") fail2();
22801
+ i += 1;
22802
+ value();
22803
+ });
21473
22804
  }
21474
- if ("profiles" in selected) {
21475
- throw new Error(`Configuration profile cannot define nested profiles: ${profileName}`);
22805
+ if (ch === "[") return members("]", value);
22806
+ if (ch === '"') return string();
22807
+ if (ch === "t") return literal("true");
22808
+ if (ch === "f") return literal("false");
22809
+ if (ch === "n") return literal("null");
22810
+ if (ch === "-" || ch !== void 0 && ch >= "0" && ch <= "9") {
22811
+ if (text5[i] === "-") i += 1;
22812
+ if (text5[i] === "0") i += 1;
22813
+ else digits();
22814
+ if (text5[i] === ".") {
22815
+ i += 1;
22816
+ digits();
22817
+ }
22818
+ if (text5[i] === "e" || text5[i] === "E") {
22819
+ i += 1;
22820
+ if (text5[i] === "+" || text5[i] === "-") i += 1;
22821
+ digits();
22822
+ }
22823
+ return;
21476
22824
  }
21477
- return selected;
21478
- });
21479
- return selectedProfiles.reduceRight(
21480
- (merged, selected) => deepMergeConfig(merged, selected),
21481
- base
21482
- );
21483
- }
21484
- function normalizeLoadConfigArgs(configPathOrOptions, maybeOptions) {
21485
- if (typeof configPathOrOptions === "string" || configPathOrOptions === void 0) {
21486
- return { configPath: configPathOrOptions, options: maybeOptions ?? {} };
21487
- }
21488
- return { options: configPathOrOptions };
21489
- }
21490
- async function loadConfig(configPathOrOptions, maybeOptions) {
21491
- const { configPath, options } = normalizeLoadConfigArgs(configPathOrOptions, maybeOptions);
21492
- const path2 = configPath || findConfigPath(options);
22825
+ fail2();
22826
+ };
21493
22827
  try {
21494
- const content2 = await readFile3(path2, "utf-8");
21495
- const parsed = RawConfigSchema.passthrough().parse(parseToml2(content2));
21496
- const env3 = loadEnvironment({ warn: options.warn });
21497
- const profile = options.profile ?? env3.BRIDGE_PROFILE;
21498
- const config = ConfigSchema.parse(
21499
- deepMergeConfig(generateDefaultConfig(), applyProfileConfig(parsed, profile))
21500
- );
21501
- const envMerged = mergeEnvironment(config, env3);
21502
- return ConfigSchema.parse(deepMergeConfig(envMerged, options.overrides ?? {}));
22828
+ value();
22829
+ ws();
22830
+ if (i < text5.length) fail2();
21503
22831
  } catch (error) {
21504
- if (error.code === "ENOENT") {
21505
- const notFoundError = new Error(
21506
- `Configuration file not found: ${path2}`
21507
- );
21508
- notFoundError.code = "ENOENT";
21509
- throw notFoundError;
21510
- }
21511
- throw error;
22832
+ return error instanceof JsonOffset ? Math.min(error.offset, text5.length) : void 0;
21512
22833
  }
22834
+ return void 0;
21513
22835
  }
21514
- function findConfigPath(options) {
21515
- const location = locateConfigFile({
21516
- explicit: process.env.BRIDGE_CONFIG,
21517
- explicitHint: "--config or BRIDGE_CONFIG",
21518
- cwd: options.cwd,
21519
- homeDir: options.homeDir,
21520
- userConfig: options.userConfig,
21521
- warn: options.warn
21522
- });
21523
- return location.path ?? location.userConfig;
21524
- }
21525
- function parseAcpProtocols(value, source = "ACP protocols") {
21526
- const versions = value.split(",").map((part) => part.trim()).filter(Boolean);
21527
- if (!versions.length || versions.some((v) => v !== "1" && v !== "2"))
21528
- throw new Error(`${source}: expected 1, 2 or 1,2, got "${value}"`);
21529
- return [...new Set(versions.map((v) => Number(v)))].sort();
21530
- }
21531
- function normalizeLogLevel(value) {
21532
- return value === void 0 ? void 0 : LOG_LEVELS.get(value.trim().toLowerCase());
21533
- }
21534
- function normalizeTransport(value) {
21535
- return value === void 0 ? void 0 : TRANSPORTS.get(value.trim().toLowerCase());
21536
- }
21537
- function parseOtelExporters(name, value, warn = () => {
21538
- }) {
21539
- if (value === void 0) return void 0;
21540
- const names = [
21541
- ...new Set(
21542
- value.split(",").map((part) => part.trim().toLowerCase()).filter(Boolean)
21543
- )
21544
- ];
21545
- if (!names.length) return void 0;
21546
- const known = (n) => OTEL_EXPORTERS.includes(n);
21547
- const unknown = names.filter((n) => n !== "none" && !known(n));
21548
- const exporters = names.filter(known);
21549
- const supported = `${OTEL_EXPORTERS.join(", ")} or none`;
21550
- if (names.includes("none")) {
21551
- if (names.length > 1)
21552
- warn(
21553
- `Bridge: ${name}=${JSON.stringify(value)} names none with other exporters: exporting nothing.
21554
- `
21555
- );
21556
- return "none";
21557
- }
21558
- if (unknown.length)
21559
- warn(
21560
- `Bridge: ${name}=${JSON.stringify(value)}: ignoring ${unknown.join(", ")}; Bridge has ${supported}.${exporters.length ? "" : ` Leaving ${name} unset.`}
21561
- `
21562
- );
21563
- if (!exporters.length) return void 0;
21564
- return exporters.length === 1 ? exporters[0] : exporters;
22836
+ function describeOffset(text5, offset) {
22837
+ if (offset === void 0) return "a position Bridge could not find";
22838
+ if (offset >= text5.length) return "the end (it is incomplete)";
22839
+ const before = text5.slice(0, offset);
22840
+ const line = before.split("\n").length;
22841
+ const column = offset - before.lastIndexOf("\n");
22842
+ return `position ${offset} (line ${line} column ${column})`;
21565
22843
  }
21566
- function loadEnvironment(options = {}) {
21567
- const input = { ...options.env ?? process.env };
21568
- const warn = options.warn ?? ((message) => process.stderr.write(message));
21569
- for (const { bridge, generic, normalize: normalize2, expected } of SHARED_SETTINGS) {
21570
- if (input[bridge]?.trim() === "") delete input[bridge];
21571
- else if (input[bridge] !== void 0) input[bridge] = normalize2(input[bridge]) ?? input[bridge];
21572
- const value = input[generic];
21573
- if (value === void 0) continue;
21574
- const normalized = normalize2(value);
21575
- if (normalized !== void 0) {
21576
- input[generic] = normalized;
21577
- continue;
21578
- }
21579
- delete input[generic];
21580
- if (value.trim() !== "" && input[bridge] === void 0) {
21581
- warn(
21582
- `Bridge: ignoring ${generic}=${JSON.stringify(value)}: Bridge reads ${expected}. Set ${bridge} to choose one for Bridge.
21583
- `
21584
- );
22844
+ function resolveReferences(value, options, at = "config") {
22845
+ const env3 = options.env ?? process.env;
22846
+ if (isReference(value)) {
22847
+ const fromConfig = value.$config !== void 0 ? lookup(options.config, value.$config) : void 0;
22848
+ if (fromConfig !== void 0 && fromConfig !== "") return fromConfig;
22849
+ const fromEnv = value.$env !== void 0 && Object.hasOwn(env3, value.$env) ? env3[value.$env] : void 0;
22850
+ if (fromEnv !== void 0 && fromEnv !== "") {
22851
+ if (value.$json !== true) return fromEnv;
22852
+ try {
22853
+ return JSON.parse(fromEnv);
22854
+ } catch {
22855
+ throw new Error(
22856
+ `${at}: environment variable ${value.$env} must be JSON (it is read with "$json": true), but it is not valid JSON at ${describeOffset(fromEnv, jsonErrorOffset(fromEnv))}`
22857
+ );
22858
+ }
21585
22859
  }
22860
+ return value.$default;
21586
22861
  }
21587
- const logsExporter = parseOtelExporters("OTEL_LOGS_EXPORTER", input.OTEL_LOGS_EXPORTER, warn);
21588
- delete input.OTEL_LOGS_EXPORTER;
21589
- const env3 = EnvironmentSchema.parse(input);
21590
- if (logsExporter !== void 0) env3.OTEL_LOGS_EXPORTER = logsExporter;
21591
- return env3;
21592
- }
21593
- function mergeEnvironment(config, env3) {
21594
- const merged = ConfigSchema.parse(config);
21595
- const backend = env3.BRIDGE_BACKEND;
21596
- const logLevel = env3.BRIDGE_LOG_LEVEL ?? env3.LOG_LEVEL;
21597
- const port = env3.BRIDGE_PORT;
21598
- const transport = env3.BRIDGE_TRANSPORT ?? env3.TRANSPORT;
21599
- if (env3.ANTHROPIC_API_KEY && merged.backends.anthropic) {
21600
- merged.backends.anthropic.apiKey = env3.ANTHROPIC_API_KEY;
21601
- }
21602
- if (env3.OPENAI_API_KEY && merged.backends.openai) {
21603
- merged.backends.openai.apiKey = env3.OPENAI_API_KEY;
21604
- }
21605
- if (merged.backends.grok) {
21606
- if (env3.GROK_COMMAND) merged.backends.grok.command = env3.GROK_COMMAND;
21607
- }
21608
- if (env3.CODEX_COMMAND) {
21609
- merged.backends.codex = {
21610
- args: ["app-server", "--listen", "stdio://"],
21611
- ...merged.backends.codex,
21612
- command: env3.CODEX_COMMAND
21613
- };
21614
- }
21615
- if (backend) {
21616
- merged.proxy.defaultBackend = backend;
21617
- }
21618
- if (logLevel) {
21619
- merged.logging.level = logLevel;
21620
- }
21621
- if (env3.BRIDGE_LOG_FILE) {
21622
- merged.logging.file = env3.BRIDGE_LOG_FILE;
21623
- }
21624
- if (env3.BRIDGE_LOG_FORMAT) {
21625
- merged.logging.format = env3.BRIDGE_LOG_FORMAT;
21626
- merged.logging.pretty = env3.BRIDGE_LOG_FORMAT === "pretty";
21627
- }
21628
- if (env3.BRIDGE_TELEMETRY_ENABLED !== void 0) {
21629
- merged.telemetry.enabled = env3.BRIDGE_TELEMETRY_ENABLED;
21630
- }
21631
- if (env3.BRIDGE_TELEMETRY_LOGS_EXPORT !== void 0) {
21632
- merged.telemetry.logs.export = env3.BRIDGE_TELEMETRY_LOGS_EXPORT;
21633
- }
21634
- if (env3.OTEL_LOGS_EXPORTER !== void 0) {
21635
- merged.telemetry.logs.exporter = env3.OTEL_LOGS_EXPORTER;
21636
- }
21637
- if (env3.OTEL_SERVICE_NAME) {
21638
- merged.telemetry.serviceName = env3.OTEL_SERVICE_NAME;
21639
- }
21640
- if (env3.OTEL_EXPORTER_OTLP_ENDPOINT) {
21641
- merged.telemetry.otlpEndpoint = env3.OTEL_EXPORTER_OTLP_ENDPOINT;
21642
- }
21643
- if (port) {
21644
- merged.server.port = port;
21645
- }
21646
- if (env3.BRIDGE_ALLOWED_ORIGINS !== void 0) {
21647
- merged.server.allowedOrigins = env3.BRIDGE_ALLOWED_ORIGINS.split(",").map((origin) => origin.trim()).filter(Boolean);
21648
- }
21649
- if (env3.BRIDGE_MCP_ALLOWED_HOSTS !== void 0) {
21650
- merged.server.mcpAllowedHosts = env3.BRIDGE_MCP_ALLOWED_HOSTS.split(",").map((host) => host.trim()).filter(Boolean);
21651
- }
21652
- if (env3.BRIDGE_HTTP_TOKEN) {
21653
- merged.server.httpToken = env3.BRIDGE_HTTP_TOKEN;
21654
- }
21655
- if (transport) {
21656
- merged.server.transport = transport;
22862
+ if (Array.isArray(value)) {
22863
+ return value.map((item, index) => resolveReferences(item, options, `${at}[${index}]`));
21657
22864
  }
21658
- if (env3.BRIDGE_ACP_PROTOCOLS !== void 0 && env3.BRIDGE_ACP_PROTOCOLS !== "") {
21659
- merged.server.acpProtocols = parseAcpProtocols(
21660
- env3.BRIDGE_ACP_PROTOCOLS,
21661
- "BRIDGE_ACP_PROTOCOLS"
21662
- );
22865
+ if (isRecord19(value)) {
22866
+ const out = {};
22867
+ for (const [key2, item] of Object.entries(value)) {
22868
+ const resolved = resolveReferences(item, options, `${at}.${key2}`);
22869
+ if (resolved !== void 0) out[key2] = resolved;
22870
+ }
22871
+ return out;
21663
22872
  }
21664
- return merged;
21665
- }
21666
- function validateConfig(config) {
21667
- return ConfigSchema.parse(config);
22873
+ return value;
21668
22874
  }
21669
- function generateDefaultConfig() {
21670
- return ConfigSchema.parse({
21671
- proxy: {
21672
- defaultBackend: "openai"
21673
- },
21674
- backends: {
21675
- anthropic: {
21676
- defaultModel: "claude-sonnet-4-20250514",
21677
- maxRetries: 3,
21678
- timeoutMs: 12e4
21679
- },
21680
- grok: {
21681
- command: "grok",
21682
- args: ["agent", "stdio"]
21683
- }
21684
- },
21685
- server: {
21686
- port: 6809,
21687
- host: "localhost",
21688
- transport: "stdio"
21689
- },
21690
- graph: {
21691
- defaultGraph: "graphs/default.json",
21692
- graphDir: "graphs"
21693
- },
21694
- logging: {
21695
- level: "info",
21696
- pretty: false,
21697
- format: "json",
21698
- stderr: true
21699
- },
21700
- telemetry: {},
21701
- reduction: {}
21702
- });
22875
+ function resolveGraphReferences(graph, options) {
22876
+ return {
22877
+ ...graph,
22878
+ nodes: graph.nodes.map((node) => ({
22879
+ ...node,
22880
+ config: resolveReferences(node.config ?? {}, options, `node "${node.id}" config`) ?? {}
22881
+ }))
22882
+ };
21703
22883
  }
21704
- var LOG_LEVELS, TRANSPORTS, SHARED_SETTINGS;
21705
- var init_loader = __esm({
21706
- "packages/config/src/loader.ts"() {
22884
+ var isRecord19, isReference, isPlainRecord, JsonOffset;
22885
+ var init_references2 = __esm({
22886
+ "packages/engine/src/references.ts"() {
21707
22887
  "use strict";
21708
- init_schema();
21709
- init_trust();
21710
- LOG_LEVELS = /* @__PURE__ */ new Map([
21711
- ["debug", "debug"],
21712
- ["trace", "debug"],
21713
- ["info", "info"],
21714
- ["warn", "warn"],
21715
- ["warning", "warn"],
21716
- ["error", "error"],
21717
- ["fatal", "error"]
21718
- ]);
21719
- TRANSPORTS = /* @__PURE__ */ new Map([
21720
- ["stdio", "stdio"],
21721
- ["http", "http"],
21722
- ["pi-rpc", "pi-rpc"]
21723
- ]);
21724
- SHARED_SETTINGS = [
21725
- {
21726
- bridge: "BRIDGE_LOG_LEVEL",
21727
- generic: "LOG_LEVEL",
21728
- normalize: normalizeLogLevel,
21729
- expected: "debug, info, warn or error"
21730
- },
21731
- {
21732
- bridge: "BRIDGE_TRANSPORT",
21733
- generic: "TRANSPORT",
21734
- normalize: normalizeTransport,
21735
- expected: "stdio, http or pi-rpc"
22888
+ init_src4();
22889
+ isRecord19 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22890
+ isReference = isConfigReference;
22891
+ isPlainRecord = (value) => {
22892
+ if (!isRecord19(value)) return false;
22893
+ const proto = Object.getPrototypeOf(value);
22894
+ return proto === Object.prototype || proto === null;
22895
+ };
22896
+ JsonOffset = class extends Error {
22897
+ constructor(offset) {
22898
+ super(`invalid JSON at ${offset}`);
22899
+ this.offset = offset;
21736
22900
  }
21737
- ];
22901
+ offset;
22902
+ };
21738
22903
  }
21739
22904
  });
21740
22905
 
21741
- // packages/config/src/index.ts
22906
+ // packages/engine/src/index.ts
21742
22907
  var init_src5 = __esm({
21743
- "packages/config/src/index.ts"() {
21744
- init_schema();
21745
- init_loader();
21746
- init_trust();
22908
+ "packages/engine/src/index.ts"() {
22909
+ init_graph();
22910
+ init_engine();
22911
+ init_references2();
21747
22912
  }
21748
22913
  });
21749
22914
 
@@ -28155,7 +29320,7 @@ var PermissionPolicySchema, STRICTNESS, PERMISSION_SKIPPING_MODES, SKIPPING, SAF
28155
29320
  var init_config4 = __esm({
28156
29321
  "packages/mcp-front/src/config.ts"() {
28157
29322
  "use strict";
28158
- init_src5();
29323
+ init_src2();
28159
29324
  init_src7();
28160
29325
  init_node3();
28161
29326
  PermissionPolicySchema = z4.enum(["ask", "user", "allow", "deny"]);
@@ -28267,7 +29432,7 @@ var SERVER_VERSION;
28267
29432
  var init_version2 = __esm({
28268
29433
  "packages/mcp-front/src/version.ts"() {
28269
29434
  "use strict";
28270
- SERVER_VERSION = "0.3.1";
29435
+ SERVER_VERSION = "0.3.2";
28271
29436
  }
28272
29437
  });
28273
29438
 
@@ -29893,8 +31058,8 @@ var DEFAULT_WAIT_SECONDS, MAX_WAIT_SECONDS, DEFAULT_MAX_CHARS, RECENT_TOOL_CALLS
29893
31058
  var init_server = __esm({
29894
31059
  "packages/mcp-front/src/server.ts"() {
29895
31060
  "use strict";
31061
+ init_src5();
29896
31062
  init_src4();
29897
- init_src3();
29898
31063
  init_config4();
29899
31064
  init_session_manager();
29900
31065
  init_version2();
@@ -30071,14 +31236,17 @@ var init_src8 = __esm({
30071
31236
  });
30072
31237
 
30073
31238
  // packages/cli/src/cli-main.ts
31239
+ init_src2();
31240
+ init_src();
31241
+ import { spawn as spawn6 } from "node:child_process";
30074
31242
  import { statSync as statSync2 } from "node:fs";
30075
31243
  import { resolve as resolve18 } from "node:path";
30076
31244
  import { pathToFileURL as pathToFileURL3 } from "node:url";
30077
31245
 
30078
31246
  // packages/cli/src/bridge-server.ts
30079
- init_src3();
30080
- init_src3();
30081
31247
  init_src4();
31248
+ init_src4();
31249
+ init_src5();
30082
31250
 
30083
31251
  // packages/session/src/repository.ts
30084
31252
  var SessionNotFoundError = class extends Error {
@@ -30308,7 +31476,7 @@ var MemorySessionRepository = class {
30308
31476
  };
30309
31477
 
30310
31478
  // packages/cli/src/bridge-server.ts
30311
- init_src5();
31479
+ init_src2();
30312
31480
 
30313
31481
  // packages/cli/src/logger.ts
30314
31482
  import { appendFileSync, mkdirSync as mkdirSync2, writeFileSync } from "node:fs";
@@ -30497,7 +31665,7 @@ function createLogger(options = {}) {
30497
31665
  }
30498
31666
 
30499
31667
  // packages/cli/src/observability.ts
30500
- init_src5();
31668
+ init_src2();
30501
31669
  import {
30502
31670
  ROOT_CONTEXT,
30503
31671
  SpanKind,
@@ -31002,7 +32170,7 @@ import { existsSync as existsSync4 } from "node:fs";
31002
32170
  import { fileURLToPath } from "node:url";
31003
32171
 
31004
32172
  // packages/cli/src/ideal-runtime.ts
31005
- init_src3();
32173
+ init_src4();
31006
32174
  import { resolve as resolve5 } from "node:path";
31007
32175
  import { pathToFileURL } from "node:url";
31008
32176
  async function resolveOwnedIdealCodeBundle(settings, baseDir, recorded) {
@@ -31055,7 +32223,7 @@ async function createOwnedIdealRuntime(settings, baseDir, observerError, injecte
31055
32223
  }
31056
32224
 
31057
32225
  // packages/cli/src/ideal-permissions.ts
31058
- init_src3();
32226
+ init_src4();
31059
32227
  var IdealPermissionBridge = class {
31060
32228
  constructor(service, requestClient, onError, mode = "acp") {
31061
32229
  this.service = service;
@@ -31804,8 +32972,37 @@ var McpUrlGuard = class {
31804
32972
  };
31805
32973
 
31806
32974
  // packages/cli/src/cli-options.ts
31807
- init_src5();
32975
+ init_src2();
31808
32976
  import { isAbsolute as isAbsolute5, resolve as resolve6 } from "node:path";
32977
+ var BRIDGE_USAGE = `Usage: deft-bridge [options]
32978
+ deft-bridge mcp [--config <bridge.toml>] [--graph <graph.json>]
32979
+ deft-bridge ideal prompt-preview --config <bridge.toml> [options]
32980
+
32981
+ Runs Deft Bridge as an Agent Client Protocol (ACP) server on stdio (default),
32982
+ HTTP, or Pi RPC.
32983
+
32984
+ Options:
32985
+ --backend <name> Backend to serve: openai (default), anthropic, grok,
32986
+ claude-sdk, codex-app-server, ideal (or $BRIDGE_BACKEND)
32987
+ --config <path> Load configuration from <path> (or $BRIDGE_CONFIG)
32988
+ --profile <name> Named profile from the configuration file
32989
+ --transport <mode> Transport mode: stdio, http, pi-rpc (or $BRIDGE_TRANSPORT)
32990
+ --http Shorthand for --transport http
32991
+ --pi-rpc Shorthand for --transport pi-rpc
32992
+ --acp-protocols <list> Accepted ACP protocol versions: 1, 2, or 1,2
32993
+ --code-exec <id> Override the Ideal backend session code executor
32994
+ --log-level <level> Log level: trace, debug, info, warn, error, fatal
32995
+ --log-file <path> Write logs to <path> instead of stderr
32996
+ --log-format <format> Log format: json or pretty
32997
+ --login Run interactive CLI login for codex-app-server or claude-sdk
32998
+ -V, --version Print version and exit
32999
+ -h, --help Print this usage help and exit
33000
+
33001
+ Configuration:
33002
+ Reads --config or $BRIDGE_CONFIG when given; otherwise ./bridge.toml when the
33003
+ working directory is listed in trustedFolders in ~/.config/bridge/config.toml,
33004
+ falling back to ~/.config/bridge/config.toml and built-in defaults.
33005
+ `;
31809
33006
  function readFlagValue(argv, index, name) {
31810
33007
  const current = argv[index];
31811
33008
  const prefix = `${name}=`;
@@ -31832,13 +33029,53 @@ function codeExecValue(value, previous) {
31832
33029
  throw new Error("Conflicting --code-exec values");
31833
33030
  return selected;
31834
33031
  }
33032
+ function consumeFlag(argv, index, name) {
33033
+ const current = argv[index];
33034
+ const prefix = `${name}=`;
33035
+ if (current.startsWith(prefix)) {
33036
+ const value = current.slice(prefix.length);
33037
+ if (!value.trim()) throw new Error(`Missing value for ${name}`);
33038
+ return { value, nextIndex: index };
33039
+ }
33040
+ if (current === name) {
33041
+ const value = argv[index + 1];
33042
+ if (!value?.trim() || value.startsWith("--")) {
33043
+ throw new Error(`Missing value for ${name}`);
33044
+ }
33045
+ return { value, nextIndex: index + 1 };
33046
+ }
33047
+ return void 0;
33048
+ }
31835
33049
  function parseCliOptions(argv = process.argv) {
31836
33050
  let overrides = {};
31837
33051
  let profile;
31838
33052
  let configPath;
31839
33053
  let codeExec;
33054
+ let help = false;
33055
+ let version = false;
33056
+ let login = false;
31840
33057
  for (let index = 2; index < argv.length; index++) {
31841
33058
  const arg = argv[index];
33059
+ if (arg === "-h" || arg === "--help") {
33060
+ help = true;
33061
+ continue;
33062
+ }
33063
+ if (arg === "-V" || arg === "--version") {
33064
+ version = true;
33065
+ continue;
33066
+ }
33067
+ if (arg === "--login") {
33068
+ login = true;
33069
+ continue;
33070
+ }
33071
+ if (arg === "--http") {
33072
+ overrides = deepMergeConfig(overrides, { server: { transport: "http" } });
33073
+ continue;
33074
+ }
33075
+ if (arg === "--pi-rpc") {
33076
+ overrides = deepMergeConfig(overrides, { server: { transport: "pi-rpc" } });
33077
+ continue;
33078
+ }
31842
33079
  if (arg === "--code-exec" || arg.startsWith("--code-exec=")) {
31843
33080
  codeExec = codeExecValue(readFlagValue(argv, index, "--code-exec"), codeExec);
31844
33081
  if (arg === "--code-exec") index += 1;
@@ -31847,55 +33084,71 @@ function parseCliOptions(argv = process.argv) {
31847
33084
  });
31848
33085
  continue;
31849
33086
  }
31850
- const configValue = readFlagValue(argv, index, "--config");
31851
- const profileValue = readFlagValue(argv, index, "--profile");
31852
- const logLevel = readFlagValue(argv, index, "--log-level");
31853
- const logFile = readFlagValue(argv, index, "--log-file");
31854
- const logFormat = readFlagValue(argv, index, "--log-format");
31855
- const transport = readFlagValue(argv, index, "--transport");
31856
- const acpProtocols = readFlagValue(argv, index, "--acp-protocols");
31857
- const backend = readFlagValue(argv, index, "--backend");
31858
- if (configValue) {
31859
- configPath = resolveConfigPath(configValue);
31860
- if (arg === "--config") {
31861
- index += 1;
31862
- }
33087
+ const configMatch = consumeFlag(argv, index, "--config");
33088
+ if (configMatch) {
33089
+ configPath = resolveConfigPath(configMatch.value);
33090
+ index = configMatch.nextIndex;
33091
+ continue;
31863
33092
  }
31864
- if (profileValue) {
31865
- profile = profileValue;
33093
+ const profileMatch = consumeFlag(argv, index, "--profile");
33094
+ if (profileMatch) {
33095
+ profile = profileMatch.value;
33096
+ index = profileMatch.nextIndex;
33097
+ continue;
31866
33098
  }
31867
- if (logLevel) {
31868
- overrides = deepMergeConfig(overrides, { logging: { level: logLevel } });
33099
+ const logLevelMatch = consumeFlag(argv, index, "--log-level");
33100
+ if (logLevelMatch) {
33101
+ overrides = deepMergeConfig(overrides, { logging: { level: logLevelMatch.value } });
33102
+ index = logLevelMatch.nextIndex;
33103
+ continue;
31869
33104
  }
31870
- if (logFile) {
31871
- overrides = deepMergeConfig(overrides, { logging: { file: logFile } });
33105
+ const logFileMatch = consumeFlag(argv, index, "--log-file");
33106
+ if (logFileMatch) {
33107
+ overrides = deepMergeConfig(overrides, { logging: { file: logFileMatch.value } });
33108
+ index = logFileMatch.nextIndex;
33109
+ continue;
31872
33110
  }
31873
- if (logFormat) {
33111
+ const logFormatMatch = consumeFlag(argv, index, "--log-format");
33112
+ if (logFormatMatch) {
31874
33113
  overrides = deepMergeConfig(overrides, {
31875
- logging: { format: logFormat, pretty: logFormat === "pretty" }
33114
+ logging: { format: logFormatMatch.value, pretty: logFormatMatch.value === "pretty" }
31876
33115
  });
33116
+ index = logFormatMatch.nextIndex;
33117
+ continue;
31877
33118
  }
31878
- if (transport) {
31879
- overrides = deepMergeConfig(overrides, { server: { transport } });
33119
+ const transportMatch = consumeFlag(argv, index, "--transport");
33120
+ if (transportMatch) {
33121
+ overrides = deepMergeConfig(overrides, { server: { transport: transportMatch.value } });
33122
+ index = transportMatch.nextIndex;
33123
+ continue;
31880
33124
  }
31881
- if (acpProtocols) {
33125
+ const acpProtocolsMatch = consumeFlag(argv, index, "--acp-protocols");
33126
+ if (acpProtocolsMatch) {
31882
33127
  overrides = deepMergeConfig(overrides, {
31883
- server: { acpProtocols: parseAcpProtocols(acpProtocols, "--acp-protocols") }
33128
+ server: {
33129
+ acpProtocols: parseAcpProtocols(acpProtocolsMatch.value, "--acp-protocols")
33130
+ }
31884
33131
  });
31885
- if (arg === "--acp-protocols") index += 1;
31886
- }
31887
- if (backend) {
31888
- overrides = deepMergeConfig(overrides, { proxy: { defaultBackend: backend } });
31889
- if (arg === "--backend") index += 1;
31890
- }
31891
- if (arg === "--http") {
31892
- overrides = deepMergeConfig(overrides, { server: { transport: "http" } });
33132
+ index = acpProtocolsMatch.nextIndex;
33133
+ continue;
31893
33134
  }
31894
- if (arg === "--pi-rpc") {
31895
- overrides = deepMergeConfig(overrides, { server: { transport: "pi-rpc" } });
33135
+ const backendMatch = consumeFlag(argv, index, "--backend");
33136
+ if (backendMatch) {
33137
+ overrides = deepMergeConfig(overrides, { proxy: { defaultBackend: backendMatch.value } });
33138
+ index = backendMatch.nextIndex;
33139
+ continue;
31896
33140
  }
33141
+ throw new Error(`Unknown argument: ${arg}. Run with --help for usage.`);
31897
33142
  }
31898
- return { configPath, profile, overrides, ...codeExec ? { codeExec } : {} };
33143
+ return {
33144
+ configPath,
33145
+ profile,
33146
+ overrides,
33147
+ ...codeExec ? { codeExec } : {},
33148
+ ...help ? { help: true } : {},
33149
+ ...version ? { version: true } : {},
33150
+ ...login ? { login: true } : {}
33151
+ };
31899
33152
  }
31900
33153
  function selectTransportMode(env3 = process.env, argv = process.argv, configuredMode = "stdio") {
31901
33154
  const envTransport = normalizeTransport(env3.BRIDGE_TRANSPORT) ?? normalizeTransport(env3.TRANSPORT);
@@ -32417,7 +33670,7 @@ function piPort(channel) {
32417
33670
  init_src6();
32418
33671
 
32419
33672
  // packages/cli/src/graph-file.ts
32420
- init_src4();
33673
+ init_src5();
32421
33674
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
32422
33675
  import { isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
32423
33676
  var MARKER_TYPES = {
@@ -32516,7 +33769,7 @@ function subspacePort(channel, name = "bridge", options = {}) {
32516
33769
 
32517
33770
  // packages/cli/src/front/agent-connector.ts
32518
33771
  init_src6();
32519
- init_src3();
33772
+ init_src4();
32520
33773
  import { spawn as spawn4 } from "node:child_process";
32521
33774
  import { Readable, Writable as Writable2 } from "node:stream";
32522
33775
  function peerAgent(channel, handlers) {
@@ -32628,7 +33881,7 @@ function processConnector(options = {}) {
32628
33881
  import { Readable as Readable2, Writable as Writable3 } from "node:stream";
32629
33882
 
32630
33883
  // packages/cli/src/response-utils.ts
32631
- init_src3();
33884
+ init_src4();
32632
33885
  function asRecord3(value) {
32633
33886
  return typeof value === "object" && value !== null ? value : void 0;
32634
33887
  }
@@ -32637,7 +33890,7 @@ function asString2(value) {
32637
33890
  }
32638
33891
 
32639
33892
  // packages/cli/src/bridge-server.ts
32640
- init_src3();
33893
+ init_src4();
32641
33894
  var SHUTDOWN_STEP_TIMEOUT_MS = 1e4;
32642
33895
  var defaultDependencies = {
32643
33896
  loadConfig,
@@ -33019,6 +34272,7 @@ var BridgeServer = class {
33019
34272
  ...this.mcpToolManager() ? { mcpTools: this.mcpToolManager() } : {},
33020
34273
  // What the graph's nodes add to initialize (§7).
33021
34274
  agentCapabilities: () => graphAgentCapabilities(engine.getNodes().values()),
34275
+ authMethods: () => graphAuthMethods(engine.getNodes().values()),
33022
34276
  // Ideal (graphs/acp-ideal.json): the permission gate, and where its questions go.
33023
34277
  ...this.idealRuntime ? {
33024
34278
  ideal: {
@@ -33161,7 +34415,7 @@ function builtInGraph(name) {
33161
34415
  }
33162
34416
 
33163
34417
  // packages/cli/src/ideal-prompt-preview-command.ts
33164
- init_src5();
34418
+ init_src2();
33165
34419
 
33166
34420
  // packages/cli/src/ideal-prompt-preview.ts
33167
34421
  import { createHash as createHash3 } from "node:crypto";
@@ -33467,6 +34721,52 @@ function idealPromptPreviewUsage() {
33467
34721
  function isMcpCommand(argv = process.argv) {
33468
34722
  return argv[2] === "mcp";
33469
34723
  }
34724
+ async function runBackendLogin(cliOptions) {
34725
+ let config = generateDefaultConfig();
34726
+ try {
34727
+ config = await loadConfig(cliOptions.configPath, {
34728
+ profile: cliOptions.profile,
34729
+ overrides: cliOptions.overrides
34730
+ });
34731
+ } catch (err) {
34732
+ if (err.code !== "ENOENT") throw err;
34733
+ config = mergeEnvironment(
34734
+ deepMergeConfig(config, cliOptions.overrides),
34735
+ loadEnvironment()
34736
+ );
34737
+ }
34738
+ const backend = config.proxy.defaultBackend;
34739
+ let command;
34740
+ let args;
34741
+ let extraEnv = {};
34742
+ if (backend === "codex-app-server") {
34743
+ const codexCfg = config.backends.codex;
34744
+ command = process.env.CODEX_COMMAND?.trim() || (typeof codexCfg?.command === "string" && codexCfg.command.trim() ? codexCfg.command.trim() : "codex");
34745
+ args = ["login"];
34746
+ if (codexCfg?.env) extraEnv = codexCfg.env;
34747
+ } else if (backend === "claude-sdk") {
34748
+ command = process.env.CLAUDE_COMMAND?.trim() || "claude";
34749
+ args = ["auth", "login"];
34750
+ } else {
34751
+ throw new Error(
34752
+ `--login is supported for --backend codex-app-server and --backend claude-sdk (got "${backend}").`
34753
+ );
34754
+ }
34755
+ return new Promise((resolveExit, reject) => {
34756
+ const child = spawn6(command, args, {
34757
+ stdio: "inherit",
34758
+ env: { ...process.env, ...extraEnv }
34759
+ });
34760
+ child.on("error", (err) => {
34761
+ if (err.code === "ENOENT") {
34762
+ reject(new Error(`Command "${command}" was not found on PATH.`));
34763
+ return;
34764
+ }
34765
+ reject(err);
34766
+ });
34767
+ child.on("close", (code) => resolveExit(code ?? 1));
34768
+ });
34769
+ }
33470
34770
  async function main(argv = process.argv) {
33471
34771
  if (isMcpCommand(argv)) {
33472
34772
  const { runMcpServer: runMcpServer2 } = await Promise.resolve().then(() => (init_src8(), src_exports));
@@ -33482,7 +34782,42 @@ async function main(argv = process.argv) {
33482
34782
  return;
33483
34783
  }
33484
34784
  if (isIdealPromptPreviewCommand(argv)) {
33485
- await runIdealPromptPreviewCommand();
34785
+ try {
34786
+ await runIdealPromptPreviewCommand(argv);
34787
+ } catch (err) {
34788
+ process.stderr.write(`bridge: ${err instanceof Error ? err.message : String(err)}
34789
+ `);
34790
+ process.exitCode = 1;
34791
+ }
34792
+ return;
34793
+ }
34794
+ if (argv.slice(2).some((arg) => arg === "-h" || arg === "--help")) {
34795
+ process.stdout.write(BRIDGE_USAGE);
34796
+ return;
34797
+ }
34798
+ let cliOptions;
34799
+ try {
34800
+ cliOptions = parseCliOptions(argv);
34801
+ } catch (err) {
34802
+ process.stderr.write(`bridge: ${err instanceof Error ? err.message : String(err)}
34803
+ `);
34804
+ process.exitCode = 1;
34805
+ return;
34806
+ }
34807
+ if (cliOptions.version) {
34808
+ process.stdout.write(`${BRIDGE_VERSION}
34809
+ `);
34810
+ return;
34811
+ }
34812
+ if (cliOptions.login) {
34813
+ try {
34814
+ const code = await runBackendLogin(cliOptions);
34815
+ if (code !== 0) process.exitCode = code;
34816
+ } catch (err) {
34817
+ process.stderr.write(`bridge: ${err instanceof Error ? err.message : String(err)}
34818
+ `);
34819
+ process.exitCode = 1;
34820
+ }
33486
34821
  return;
33487
34822
  }
33488
34823
  const server = new BridgeServer();