@rynfar/meridian 1.68.0 → 1.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -0
  2. package/dist/{cli-0zhb8ss4.js → cli-198xnjcn.js} +1033 -525
  3. package/dist/{cli-sh8bzdwe.js → cli-zdbv40d5.js} +26 -7
  4. package/dist/cli.js +4 -4
  5. package/dist/meridian/index.js +252 -0
  6. package/dist/meridian/package.json +6 -0
  7. package/dist/meridian-v2/index.js +20384 -41
  8. package/dist/meridian-v2.js +20382 -45
  9. package/dist/proxy/adapter.d.ts +16 -0
  10. package/dist/proxy/adapter.d.ts.map +1 -1
  11. package/dist/proxy/adapters/claudecode.d.ts +23 -0
  12. package/dist/proxy/adapters/claudecode.d.ts.map +1 -1
  13. package/dist/proxy/adapters/detect.d.ts.map +1 -1
  14. package/dist/proxy/adapters/passthrough.d.ts.map +1 -1
  15. package/dist/proxy/adapters/polytoken.d.ts +36 -0
  16. package/dist/proxy/adapters/polytoken.d.ts.map +1 -0
  17. package/dist/proxy/errors.d.ts +2 -0
  18. package/dist/proxy/errors.d.ts.map +1 -1
  19. package/dist/proxy/openaiResponses.d.ts +106 -3
  20. package/dist/proxy/openaiResponses.d.ts.map +1 -1
  21. package/dist/proxy/passthroughEarlyStop.d.ts +3 -3
  22. package/dist/proxy/passthroughEarlyStop.d.ts.map +1 -1
  23. package/dist/proxy/passthroughTools.d.ts +63 -2
  24. package/dist/proxy/passthroughTools.d.ts.map +1 -1
  25. package/dist/proxy/query.d.ts +3 -0
  26. package/dist/proxy/query.d.ts.map +1 -1
  27. package/dist/proxy/sdkFeatures.d.ts.map +1 -1
  28. package/dist/proxy/server.d.ts.map +1 -1
  29. package/dist/proxy/session/cache.d.ts +20 -3
  30. package/dist/proxy/session/cache.d.ts.map +1 -1
  31. package/dist/proxy/session/lineage.d.ts +56 -0
  32. package/dist/proxy/session/lineage.d.ts.map +1 -1
  33. package/dist/proxy/session/processIncarnation.d.ts +55 -0
  34. package/dist/proxy/session/processIncarnation.d.ts.map +1 -1
  35. package/dist/proxy/setup.d.ts +12 -2
  36. package/dist/proxy/setup.d.ts.map +1 -1
  37. package/dist/proxy/transforms/codex.d.ts +12 -0
  38. package/dist/proxy/transforms/codex.d.ts.map +1 -1
  39. package/dist/proxy/transforms/polytoken.d.ts +18 -0
  40. package/dist/proxy/transforms/polytoken.d.ts.map +1 -0
  41. package/dist/proxy/transforms/registry.d.ts.map +1 -1
  42. package/dist/server.js +2 -2
  43. package/dist/{setup-knvctar4.js → setup-b3ymd9z8.js} +3 -1
  44. package/dist/telemetry/index.d.ts.map +1 -1
  45. package/package.json +4 -4
  46. package/plugin/meridian/index.js +1 -0
  47. package/plugin/meridian/package.json +6 -0
  48. package/plugin/meridian-v2.ts +223 -0
  49. package/plugin/meridian.ts +1 -1
@@ -77,7 +77,7 @@ import {
77
77
  init_priorityAttestation,
78
78
  notePluginlessOpenCodeRequest,
79
79
  verifyPriorityAttestation
80
- } from "./cli-sh8bzdwe.js";
80
+ } from "./cli-zdbv40d5.js";
81
81
  import {
82
82
  __commonJS,
83
83
  __esm,
@@ -633,7 +633,7 @@ __export(exports_pricingStore, {
633
633
  getPricingOverrides: () => getPricingOverrides,
634
634
  deletePricingOverride: () => deletePricingOverride
635
635
  });
636
- import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync, renameSync } from "node:fs";
636
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync, renameSync } from "node:fs";
637
637
  import { join, dirname } from "node:path";
638
638
  import { homedir } from "node:os";
639
639
  function getConfigPath() {
@@ -651,7 +651,7 @@ function readOverrides() {
651
651
  }
652
652
  try {
653
653
  if (existsSync2(path)) {
654
- const raw2 = JSON.parse(readFileSync(path, "utf-8"));
654
+ const raw2 = JSON.parse(readFileSync2(path, "utf-8"));
655
655
  const result = {};
656
656
  for (const [model, value] of Object.entries(raw2)) {
657
657
  try {
@@ -867,7 +867,7 @@ var require_process = __commonJS((exports, module) => {
867
867
  var require_filesystem = __commonJS((exports, module) => {
868
868
  var fs = __require("fs");
869
869
  var LDD_PATH = "/usr/bin/ldd";
870
- var readFileSync3 = (path) => fs.readFileSync(path, "utf-8");
870
+ var readFileSync4 = (path) => fs.readFileSync(path, "utf-8");
871
871
  var readFile = (path) => new Promise((resolve3, reject) => {
872
872
  fs.readFile(path, "utf-8", (err, data) => {
873
873
  if (err) {
@@ -879,7 +879,7 @@ var require_filesystem = __commonJS((exports, module) => {
879
879
  });
880
880
  module.exports = {
881
881
  LDD_PATH,
882
- readFileSync: readFileSync3,
882
+ readFileSync: readFileSync4,
883
883
  readFile
884
884
  };
885
885
  });
@@ -888,7 +888,7 @@ var require_filesystem = __commonJS((exports, module) => {
888
888
  var require_detect_libc = __commonJS((exports, module) => {
889
889
  var childProcess = __require("child_process");
890
890
  var { isLinux, getReport } = require_process();
891
- var { LDD_PATH, readFile, readFileSync: readFileSync3 } = require_filesystem();
891
+ var { LDD_PATH, readFile, readFileSync: readFileSync4 } = require_filesystem();
892
892
  var cachedFamilyFilesystem;
893
893
  var cachedVersionFilesystem;
894
894
  var command = "getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true";
@@ -968,7 +968,7 @@ var require_detect_libc = __commonJS((exports, module) => {
968
968
  }
969
969
  cachedFamilyFilesystem = null;
970
970
  try {
971
- const lddContent = readFileSync3(LDD_PATH);
971
+ const lddContent = readFileSync4(LDD_PATH);
972
972
  cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);
973
973
  } catch (e) {}
974
974
  return cachedFamilyFilesystem;
@@ -1023,7 +1023,7 @@ var require_detect_libc = __commonJS((exports, module) => {
1023
1023
  }
1024
1024
  cachedVersionFilesystem = null;
1025
1025
  try {
1026
- const lddContent = readFileSync3(LDD_PATH);
1026
+ const lddContent = readFileSync4(LDD_PATH);
1027
1027
  const versionMatch = lddContent.match(RE_GLIBC_VERSION);
1028
1028
  if (versionMatch) {
1029
1029
  cachedVersionFilesystem = versionMatch[1];
@@ -2117,7 +2117,7 @@ var init_messages = __esm(() => {
2117
2117
  });
2118
2118
 
2119
2119
  // src/proxy/session/fingerprint.ts
2120
- import { createHash as createHash2 } from "crypto";
2120
+ import { createHash as createHash3 } from "crypto";
2121
2121
  function extractClientCwd(body) {
2122
2122
  let systemText = "";
2123
2123
  if (typeof body.system === "string") {
@@ -2140,7 +2140,7 @@ function getConversationFingerprint(messages, workingDirectory) {
2140
2140
  return "";
2141
2141
  const seed = workingDirectory ? `${workingDirectory}
2142
2142
  ${text.slice(0, 2000)}` : text.slice(0, 2000);
2143
- return createHash2("sha256").update(seed).digest("hex").slice(0, 16);
2143
+ return createHash3("sha256").update(seed).digest("hex").slice(0, 16);
2144
2144
  }
2145
2145
  function getPriorityAssignmentKey(sessionId, messages, workingDirectory) {
2146
2146
  if (sessionId)
@@ -2463,6 +2463,119 @@ var init_jcode = __esm(() => {
2463
2463
  };
2464
2464
  });
2465
2465
 
2466
+ // src/proxy/adapters/claudecode.ts
2467
+ function extractClaudeCodeClientCwd(body) {
2468
+ let systemText = "";
2469
+ if (typeof body.system === "string") {
2470
+ systemText = body.system;
2471
+ } else if (Array.isArray(body.system)) {
2472
+ systemText = body.system.filter((b) => b.type === "text" && b.text).map((b) => b.text).join(`
2473
+ `);
2474
+ }
2475
+ if (!systemText)
2476
+ return;
2477
+ const match2 = systemText.match(/Primary working directory:\s*([^\n<]+)/i);
2478
+ return match2?.[1]?.trim() || undefined;
2479
+ }
2480
+ function extractClaudeCodeSessionIdentity(body) {
2481
+ if (!body || typeof body !== "object")
2482
+ return;
2483
+ const metadata = body.metadata;
2484
+ if (!metadata || typeof metadata !== "object")
2485
+ return;
2486
+ const rawUserId = metadata.user_id;
2487
+ let userMetadata = rawUserId;
2488
+ if (typeof rawUserId === "string") {
2489
+ try {
2490
+ userMetadata = JSON.parse(rawUserId);
2491
+ } catch {
2492
+ return;
2493
+ }
2494
+ }
2495
+ if (!userMetadata || typeof userMetadata !== "object")
2496
+ return;
2497
+ const sessionId = userMetadata.session_id;
2498
+ if (typeof sessionId !== "string" || sessionId.length === 0)
2499
+ return;
2500
+ const parentSessionId = userMetadata.parent_session_id;
2501
+ const parent = typeof parentSessionId === "string" && parentSessionId.length > 0 && parentSessionId !== sessionId ? parentSessionId : undefined;
2502
+ return parent ? { sessionId, parentSessionId: parent } : { sessionId };
2503
+ }
2504
+ function extractClaudeCodeSessionId(body) {
2505
+ return extractClaudeCodeSessionIdentity(body)?.sessionId;
2506
+ }
2507
+ function extractClaudeCodeParentSessionId(body) {
2508
+ return extractClaudeCodeSessionIdentity(body)?.parentSessionId;
2509
+ }
2510
+ function isClaudeCodeClient(c) {
2511
+ return Boolean(c.req.header("x-claude-code-session-id"));
2512
+ }
2513
+ var claudeCodeAdapter;
2514
+ var init_claudecode = __esm(() => {
2515
+ init_fileChanges();
2516
+ init_messages();
2517
+ init_tools();
2518
+ init_env();
2519
+ claudeCodeAdapter = {
2520
+ name: "claude-code",
2521
+ clientEnvironmentMayDifferFromProxy: true,
2522
+ getSessionId(_c, body) {
2523
+ return extractClaudeCodeSessionId(body);
2524
+ },
2525
+ getParentSessionId(_c, body) {
2526
+ return extractClaudeCodeParentSessionId(body);
2527
+ },
2528
+ extractWorkingDirectory(_body) {
2529
+ return;
2530
+ },
2531
+ extractClientWorkingDirectory(body) {
2532
+ return extractClaudeCodeClientCwd(body);
2533
+ },
2534
+ normalizeContent(content) {
2535
+ return normalizeContent(content);
2536
+ },
2537
+ getBlockedBuiltinTools() {
2538
+ return BLOCKED_BUILTIN_TOOLS;
2539
+ },
2540
+ getAgentIncompatibleTools() {
2541
+ return CLAUDE_CODE_ONLY_TOOLS;
2542
+ },
2543
+ getMcpServerName() {
2544
+ return MCP_SERVER_NAME;
2545
+ },
2546
+ getAllowedMcpTools() {
2547
+ return ALLOWED_MCP_TOOLS;
2548
+ },
2549
+ getCoreToolNames() {
2550
+ return ["Read", "Write", "Edit", "Bash", "Glob", "Grep"];
2551
+ },
2552
+ usesPassthrough() {
2553
+ return resolvePassthrough(true);
2554
+ },
2555
+ supportsThinking() {
2556
+ return true;
2557
+ },
2558
+ shouldTrackFileChanges() {
2559
+ return false;
2560
+ },
2561
+ extractFileChangesFromToolUse(toolName, toolInput) {
2562
+ const input = toolInput;
2563
+ const filePath = input?.file_path ?? input?.filePath ?? input?.path;
2564
+ const lowerName = toolName.toLowerCase();
2565
+ if (lowerName === "write" && filePath) {
2566
+ return [{ operation: "wrote", path: String(filePath) }];
2567
+ }
2568
+ if ((lowerName === "edit" || lowerName === "multiedit") && filePath) {
2569
+ return [{ operation: "edited", path: String(filePath) }];
2570
+ }
2571
+ if (lowerName === "bash" && input?.command) {
2572
+ return extractFileChangesFromBash(String(input.command));
2573
+ }
2574
+ return [];
2575
+ }
2576
+ };
2577
+ });
2578
+
2466
2579
  // src/proxy/transforms/droid.ts
2467
2580
  function resolveDroidPassthrough() {
2468
2581
  return resolvePassthrough(false);
@@ -2774,6 +2887,9 @@ var init_passthrough2 = __esm(() => {
2774
2887
  getMcpServerName() {
2775
2888
  return MCP_SERVER_NAME3;
2776
2889
  },
2890
+ getPassthroughMcpName() {
2891
+ return MCP_SERVER_NAME3;
2892
+ },
2777
2893
  getAllowedMcpTools() {
2778
2894
  return ALLOWED_MCP_TOOLS3;
2779
2895
  },
@@ -2795,116 +2911,6 @@ var init_passthrough2 = __esm(() => {
2795
2911
  };
2796
2912
  });
2797
2913
 
2798
- // src/proxy/adapters/claudecode.ts
2799
- function extractClaudeCodeClientCwd(body) {
2800
- let systemText = "";
2801
- if (typeof body.system === "string") {
2802
- systemText = body.system;
2803
- } else if (Array.isArray(body.system)) {
2804
- systemText = body.system.filter((b) => b.type === "text" && b.text).map((b) => b.text).join(`
2805
- `);
2806
- }
2807
- if (!systemText)
2808
- return;
2809
- const match2 = systemText.match(/Primary working directory:\s*([^\n<]+)/i);
2810
- return match2?.[1]?.trim() || undefined;
2811
- }
2812
- function extractClaudeCodeSessionIdentity(body) {
2813
- if (!body || typeof body !== "object")
2814
- return;
2815
- const metadata = body.metadata;
2816
- if (!metadata || typeof metadata !== "object")
2817
- return;
2818
- const rawUserId = metadata.user_id;
2819
- let userMetadata = rawUserId;
2820
- if (typeof rawUserId === "string") {
2821
- try {
2822
- userMetadata = JSON.parse(rawUserId);
2823
- } catch {
2824
- return;
2825
- }
2826
- }
2827
- if (!userMetadata || typeof userMetadata !== "object")
2828
- return;
2829
- const sessionId = userMetadata.session_id;
2830
- if (typeof sessionId !== "string" || sessionId.length === 0)
2831
- return;
2832
- const parentSessionId = userMetadata.parent_session_id;
2833
- const parent = typeof parentSessionId === "string" && parentSessionId.length > 0 && parentSessionId !== sessionId ? parentSessionId : undefined;
2834
- return parent ? { sessionId, parentSessionId: parent } : { sessionId };
2835
- }
2836
- function extractClaudeCodeSessionId(body) {
2837
- return extractClaudeCodeSessionIdentity(body)?.sessionId;
2838
- }
2839
- function extractClaudeCodeParentSessionId(body) {
2840
- return extractClaudeCodeSessionIdentity(body)?.parentSessionId;
2841
- }
2842
- var claudeCodeAdapter;
2843
- var init_claudecode = __esm(() => {
2844
- init_fileChanges();
2845
- init_messages();
2846
- init_tools();
2847
- init_env();
2848
- claudeCodeAdapter = {
2849
- name: "claude-code",
2850
- clientEnvironmentMayDifferFromProxy: true,
2851
- getSessionId(_c, body) {
2852
- return extractClaudeCodeSessionId(body);
2853
- },
2854
- getParentSessionId(_c, body) {
2855
- return extractClaudeCodeParentSessionId(body);
2856
- },
2857
- extractWorkingDirectory(_body) {
2858
- return;
2859
- },
2860
- extractClientWorkingDirectory(body) {
2861
- return extractClaudeCodeClientCwd(body);
2862
- },
2863
- normalizeContent(content) {
2864
- return normalizeContent(content);
2865
- },
2866
- getBlockedBuiltinTools() {
2867
- return BLOCKED_BUILTIN_TOOLS;
2868
- },
2869
- getAgentIncompatibleTools() {
2870
- return CLAUDE_CODE_ONLY_TOOLS;
2871
- },
2872
- getMcpServerName() {
2873
- return MCP_SERVER_NAME;
2874
- },
2875
- getAllowedMcpTools() {
2876
- return ALLOWED_MCP_TOOLS;
2877
- },
2878
- getCoreToolNames() {
2879
- return ["Read", "Write", "Edit", "Bash", "Glob", "Grep"];
2880
- },
2881
- usesPassthrough() {
2882
- return resolvePassthrough(true);
2883
- },
2884
- supportsThinking() {
2885
- return true;
2886
- },
2887
- shouldTrackFileChanges() {
2888
- return false;
2889
- },
2890
- extractFileChangesFromToolUse(toolName, toolInput) {
2891
- const input = toolInput;
2892
- const filePath = input?.file_path ?? input?.filePath ?? input?.path;
2893
- const lowerName = toolName.toLowerCase();
2894
- if (lowerName === "write" && filePath) {
2895
- return [{ operation: "wrote", path: String(filePath) }];
2896
- }
2897
- if ((lowerName === "edit" || lowerName === "multiedit") && filePath) {
2898
- return [{ operation: "edited", path: String(filePath) }];
2899
- }
2900
- if (lowerName === "bash" && input?.command) {
2901
- return extractFileChangesFromBash(String(input.command));
2902
- }
2903
- return [];
2904
- }
2905
- };
2906
- });
2907
-
2908
2914
  // src/proxy/transforms/pi.ts
2909
2915
  function resolvePiPassthrough() {
2910
2916
  return resolvePassthrough(true);
@@ -3332,8 +3338,95 @@ var init_cherry = __esm(() => {
3332
3338
  };
3333
3339
  });
3334
3340
 
3341
+ // src/proxy/transforms/polytoken.ts
3342
+ var polytokenTransforms;
3343
+ var init_polytoken = __esm(() => {
3344
+ polytokenTransforms = [
3345
+ {
3346
+ name: "polytoken-core",
3347
+ adapters: ["polytoken"],
3348
+ onRequest(ctx) {
3349
+ return {
3350
+ ...ctx,
3351
+ blockedTools: [],
3352
+ incompatibleTools: [],
3353
+ allowedMcpTools: [],
3354
+ coreToolNames: [],
3355
+ passthrough: true,
3356
+ sdkAgents: {},
3357
+ sdkHooks: undefined,
3358
+ systemContext: ctx.systemContext,
3359
+ supportsThinking: true,
3360
+ shouldTrackFileChanges: false,
3361
+ extractFileChangesFromToolUse: undefined
3362
+ };
3363
+ }
3364
+ }
3365
+ ];
3366
+ });
3367
+
3368
+ // src/proxy/adapters/polytoken.ts
3369
+ function normalizePolytokenSessionId(value) {
3370
+ const trimmed = value?.trim();
3371
+ return trimmed ? trimmed : undefined;
3372
+ }
3373
+ var POLYTOKEN_SESSION_HEADER = "x-polytoken-session", polytokenAdapter;
3374
+ var init_polytoken2 = __esm(() => {
3375
+ init_messages();
3376
+ init_polytoken();
3377
+ polytokenAdapter = {
3378
+ name: "polytoken",
3379
+ clientEnvironmentMayDifferFromProxy: true,
3380
+ getSessionId(c) {
3381
+ return normalizePolytokenSessionId(c.req.header(POLYTOKEN_SESSION_HEADER));
3382
+ },
3383
+ extractWorkingDirectory(_body) {
3384
+ return;
3385
+ },
3386
+ extractClientWorkingDirectory(_body) {
3387
+ return;
3388
+ },
3389
+ normalizeContent(content) {
3390
+ return normalizeContent(content);
3391
+ },
3392
+ getBlockedBuiltinTools() {
3393
+ return [];
3394
+ },
3395
+ getAgentIncompatibleTools() {
3396
+ return [];
3397
+ },
3398
+ getMcpServerName() {
3399
+ return "polytoken";
3400
+ },
3401
+ getAllowedMcpTools() {
3402
+ return [];
3403
+ },
3404
+ getCoreToolNames() {
3405
+ return [];
3406
+ },
3407
+ usesPassthrough() {
3408
+ return true;
3409
+ },
3410
+ supportsThinking() {
3411
+ return true;
3412
+ },
3413
+ shouldTrackFileChanges() {
3414
+ return false;
3415
+ },
3416
+ buildSdkAgents(_body, _mcpToolNames) {
3417
+ return {};
3418
+ },
3419
+ buildSdkHooks(_body, _sdkAgents) {
3420
+ return;
3421
+ },
3422
+ buildSystemContextAddendum(_body, _sdkAgents) {
3423
+ return "";
3424
+ }
3425
+ };
3426
+ });
3427
+
3335
3428
  // src/proxy/adapterInstances.ts
3336
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
3429
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
3337
3430
  import { join as join5 } from "node:path";
3338
3431
  import { homedir as homedir5 } from "node:os";
3339
3432
  function parseAdapterInstances(raw2) {
@@ -3379,7 +3472,7 @@ function loadAdapterInstances() {
3379
3472
  if (diskCacheAt > 0 && Date.now() - diskCacheAt < DISK_CACHE_TTL_MS)
3380
3473
  return diskCache;
3381
3474
  try {
3382
- diskCache = existsSync4(CONFIG_FILE) ? parseAdapterInstances(readFileSync3(CONFIG_FILE, "utf-8")) : {};
3475
+ diskCache = existsSync4(CONFIG_FILE) ? parseAdapterInstances(readFileSync4(CONFIG_FILE, "utf-8")) : {};
3383
3476
  } catch (err) {
3384
3477
  console.warn(`[meridian] Failed to read ${CONFIG_FILE}: ${err instanceof Error ? err.message : err}`);
3385
3478
  diskCache = {};
@@ -3423,6 +3516,10 @@ __export(exports_detect, {
3423
3516
  function listAdapterNames() {
3424
3517
  return [...new Set(Object.values(ADAPTER_MAP).map((a) => a.name))];
3425
3518
  }
3519
+ function resolveDefaultAdapter() {
3520
+ const current = (process.env.MERIDIAN_DEFAULT_AGENT || "").toLowerCase();
3521
+ return ADAPTER_MAP[current] ?? openCodeAdapter;
3522
+ }
3426
3523
  function isLiteLLMRequest(c) {
3427
3524
  if ((c.req.header("user-agent") || "").startsWith("litellm/"))
3428
3525
  return true;
@@ -3450,19 +3547,20 @@ function detectAdapter(c) {
3450
3547
  }
3451
3548
  const instances = loadAdapterInstances();
3452
3549
  const instanceNames = Object.keys(instances);
3453
- if (instanceNames.length > 0) {
3454
- if (agentOverride && instances[agentOverride]) {
3455
- const inst = makeInstanceAdapter(agentOverride, instances[agentOverride]);
3550
+ if (instanceNames.length > 0 && agentOverride && instances[agentOverride]) {
3551
+ const inst = makeInstanceAdapter(agentOverride, instances[agentOverride]);
3552
+ if (inst)
3553
+ return inst;
3554
+ }
3555
+ if (normalizePolytokenSessionId(c.req.header("x-polytoken-session"))) {
3556
+ return polytokenAdapter;
3557
+ }
3558
+ for (const name of instanceNames) {
3559
+ if (matchesInstance(instances[name], (h) => c.req.header(h))) {
3560
+ const inst = makeInstanceAdapter(name, instances[name]);
3456
3561
  if (inst)
3457
3562
  return inst;
3458
3563
  }
3459
- for (const name of instanceNames) {
3460
- if (matchesInstance(instances[name], (h) => c.req.header(h))) {
3461
- const inst = makeInstanceAdapter(name, instances[name]);
3462
- if (inst)
3463
- return inst;
3464
- }
3465
- }
3466
3564
  }
3467
3565
  if (c.req.header("x-opencode-session")) {
3468
3566
  return openCodeAdapter;
@@ -3480,6 +3578,9 @@ function detectAdapter(c) {
3480
3578
  if (userAgent.startsWith("Charm-Crush/")) {
3481
3579
  return crushAdapter;
3482
3580
  }
3581
+ if (/^Polytoken(?:[\s/]|$)/.test(userAgent)) {
3582
+ return polytokenAdapter;
3583
+ }
3483
3584
  if (c.req.header("x-session-affinity")) {
3484
3585
  return openCodeAdapter;
3485
3586
  }
@@ -3493,9 +3594,9 @@ function detectAdapter(c) {
3493
3594
  if (isLiteLLMRequest(c)) {
3494
3595
  return passthroughAdapter;
3495
3596
  }
3496
- return defaultAdapter;
3597
+ return resolveDefaultAdapter();
3497
3598
  }
3498
- var ADAPTER_MAP, envDefault, defaultAdapter;
3599
+ var ADAPTER_MAP, envDefault;
3499
3600
  var init_detect = __esm(() => {
3500
3601
  init_opencode2();
3501
3602
  init_droid2();
@@ -3509,6 +3610,7 @@ var init_detect = __esm(() => {
3509
3610
  init_jcode();
3510
3611
  init_codex();
3511
3612
  init_cherry();
3613
+ init_polytoken2();
3512
3614
  init_adapterInstances();
3513
3615
  ADAPTER_MAP = {
3514
3616
  opencode: openCodeAdapter,
@@ -3523,6 +3625,7 @@ var init_detect = __esm(() => {
3523
3625
  claudecode: claudeCodeAdapter,
3524
3626
  cherry: cherryAdapter,
3525
3627
  cherrystudio: cherryAdapter,
3628
+ polytoken: polytokenAdapter,
3526
3629
  openai: openAiAdapter,
3527
3630
  jcode: jcodeAdapter,
3528
3631
  codex: codexAdapter
@@ -3531,7 +3634,6 @@ var init_detect = __esm(() => {
3531
3634
  if (envDefault && !ADAPTER_MAP[envDefault]) {
3532
3635
  console.warn(`[meridian] Unknown MERIDIAN_DEFAULT_AGENT="${envDefault}". ` + `Valid values: ${Object.keys(ADAPTER_MAP).join(", ")}. Falling back to opencode.`);
3533
3636
  }
3534
- defaultAdapter = ADAPTER_MAP[envDefault] ?? openCodeAdapter;
3535
3637
  });
3536
3638
 
3537
3639
  // src/proxy/sdkFeatures.ts
@@ -3687,6 +3789,14 @@ var init_sdkFeatures = __esm(() => {
3687
3789
  },
3688
3790
  codex: {
3689
3791
  codeSystemPrompt: false
3792
+ },
3793
+ polytoken: {
3794
+ codeSystemPrompt: false,
3795
+ clientSystemPrompt: true,
3796
+ claudeMd: "off",
3797
+ memory: false,
3798
+ dreaming: false,
3799
+ sharedMemory: false
3690
3800
  }
3691
3801
  };
3692
3802
  VALID_CLAUDE_MD_VALUES = new Set(["off", "project", "full"]);
@@ -21704,6 +21814,9 @@ config(en_default());
21704
21814
  // src/proxy/passthroughTools.ts
21705
21815
  var PASSTHROUGH_MCP_NAME = "oc";
21706
21816
  var PASSTHROUGH_MCP_PREFIX = `mcp__${PASSTHROUGH_MCP_NAME}__`;
21817
+ function passthroughMcpPrefix(serverName = PASSTHROUGH_MCP_NAME) {
21818
+ return `mcp__${serverName}__`;
21819
+ }
21707
21820
  function repairTypeSlip(schema, value) {
21708
21821
  if (typeof value !== "string")
21709
21822
  return value;
@@ -21826,16 +21939,20 @@ function getAutoDeferThreshold() {
21826
21939
  return DEFAULT_DEFER_THRESHOLD;
21827
21940
  return parsed;
21828
21941
  }
21829
- function createPassthroughMcpServer(tools, coreToolNames) {
21942
+ function autoDeferDecision(threshold, coreToolNames, toolCount) {
21943
+ return !!(threshold > 0 && coreToolNames && coreToolNames.length > 0 && toolCount > threshold);
21944
+ }
21945
+ function createPassthroughMcpServer(tools, coreToolNames, serverName = PASSTHROUGH_MCP_NAME, pinnedAutoDefer) {
21830
21946
  const threshold = getAutoDeferThreshold();
21831
- const autoDefer = !!(threshold > 0 && coreToolNames && coreToolNames.length > 0 && tools.length > threshold);
21832
- const coreSet = autoDefer ? new Set(coreToolNames.map((n) => n.toLowerCase())) : undefined;
21947
+ const autoDefer = pinnedAutoDefer ?? autoDeferDecision(threshold, coreToolNames, tools.length);
21948
+ const coreSet = autoDefer && coreToolNames ? new Set(coreToolNames.map((n) => n.toLowerCase())) : undefined;
21833
21949
  const hasDeferredTools = tools.some((t) => t.defer_loading === true) || autoDefer;
21834
21950
  const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));
21951
+ const aliases = buildPassthroughToolAliases(sortedTools.map((tool) => tool.name), serverName);
21835
21952
  const definitions = sortedTools.map((passthroughTool) => {
21836
21953
  const alwaysLoad = hasDeferredTools && shouldAlwaysLoad(passthroughTool, coreSet);
21837
21954
  const defineTool = (shape) => ({
21838
- name: passthroughTool.name,
21955
+ name: aliases.aliasByClientName.get(passthroughTool.name) ?? passthroughTool.name,
21839
21956
  description: passthroughTool.description || passthroughTool.name,
21840
21957
  inputSchema: shape,
21841
21958
  handler: async () => ({ content: [{ type: "text", text: "passthrough" }] }),
@@ -21849,11 +21966,15 @@ function createPassthroughMcpServer(tools, coreToolNames) {
21849
21966
  return defineTool(fallbackShape);
21850
21967
  }
21851
21968
  });
21852
- const server = createSdkMcpServer({ name: PASSTHROUGH_MCP_NAME, tools: definitions });
21969
+ const server = createSdkMcpServer({ name: serverName, tools: definitions });
21970
+ const prefix = passthroughMcpPrefix(serverName);
21853
21971
  return {
21854
21972
  server,
21855
- toolNames: sortedTools.map((tool) => `${PASSTHROUGH_MCP_PREFIX}${tool.name}`),
21856
- hasDeferredTools
21973
+ serverName,
21974
+ prefix,
21975
+ toolNames: definitions.map((definition) => `${prefix}${definition.name}`),
21976
+ hasDeferredTools,
21977
+ clientNameByAlias: aliases.clientNameByAlias
21857
21978
  };
21858
21979
  }
21859
21980
  function shouldAlwaysLoad(tool, coreSet) {
@@ -21883,12 +22004,48 @@ function stableStringify(value) {
21883
22004
  function toolUseSignature(name, input) {
21884
22005
  return `${name}::${stableStringify(input ?? null)}`;
21885
22006
  }
21886
- function stripMcpPrefix(toolName) {
21887
- if (toolName.startsWith(PASSTHROUGH_MCP_PREFIX)) {
21888
- return toolName.slice(PASSTHROUGH_MCP_PREFIX.length);
22007
+ function stripMcpPrefix(toolName, serverName = PASSTHROUGH_MCP_NAME) {
22008
+ const prefix = passthroughMcpPrefix(serverName);
22009
+ if (toolName.startsWith(prefix)) {
22010
+ return toolName.slice(prefix.length);
21889
22011
  }
21890
22012
  return toolName;
21891
22013
  }
22014
+ function buildPassthroughToolAliases(names, serverName = PASSTHROUGH_MCP_NAME) {
22015
+ const PREFIX = passthroughMcpPrefix(serverName);
22016
+ const aliasByClientName = new Map;
22017
+ const clientNameByAlias = new Map;
22018
+ const ordered = [...names].sort((a, b) => a.localeCompare(b));
22019
+ for (const name of ordered) {
22020
+ if (name.startsWith(PREFIX))
22021
+ continue;
22022
+ aliasByClientName.set(name, name);
22023
+ clientNameByAlias.set(name, name);
22024
+ }
22025
+ for (const name of ordered) {
22026
+ if (!name.startsWith(PREFIX))
22027
+ continue;
22028
+ if (aliasByClientName.has(name))
22029
+ continue;
22030
+ let base = name;
22031
+ while (base.startsWith(PREFIX)) {
22032
+ base = base.slice(PREFIX.length);
22033
+ }
22034
+ if (!base)
22035
+ base = "tool";
22036
+ let alias = base;
22037
+ let attempt = 2;
22038
+ while (clientNameByAlias.has(alias))
22039
+ alias = `${base}_${attempt++}`;
22040
+ aliasByClientName.set(name, alias);
22041
+ clientNameByAlias.set(alias, name);
22042
+ }
22043
+ return { aliasByClientName, clientNameByAlias };
22044
+ }
22045
+ function resolveClientToolName(sdkToolName, clientNameByAlias, serverName = PASSTHROUGH_MCP_NAME) {
22046
+ const alias = stripMcpPrefix(sdkToolName, serverName);
22047
+ return clientNameByAlias?.get(alias) ?? alias;
22048
+ }
21892
22049
  function toCamelCase(s) {
21893
22050
  return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
21894
22051
  }
@@ -21922,6 +22079,313 @@ function normalizeToolInput(input, clientSchema) {
21922
22079
  return repairCapturedObject(normalized, clientSchema.properties);
21923
22080
  }
21924
22081
 
22082
+ // src/proxy/session/processIncarnation.ts
22083
+ import { spawnSync } from "node:child_process";
22084
+ import { createHash as createHash2 } from "node:crypto";
22085
+ import { readFileSync, readlinkSync } from "node:fs";
22086
+ var PROCESS_INCARNATION_VERSION = 1;
22087
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
22088
+ var SHA256_PATTERN = /^[0-9a-f]{64}$/;
22089
+ var LINUX_START_PATTERN = /^[1-9][0-9]{0,31}$/;
22090
+ var WINDOWS_START_PATTERN = /^[1-9][0-9]{0,31}$/;
22091
+ var DARWIN_START_PATTERN = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-6][0-9] [0-9]{4}$/;
22092
+ var PROBE_TIMEOUT_MS = 2000;
22093
+ var WINDOWS_PROBE_TIMEOUT_MS = 1e4;
22094
+ var cachedLocalBootIdentity;
22095
+ var cachedCurrentProcessIncarnation;
22096
+ function hashIdentity(value) {
22097
+ return createHash2("sha256").update(value).digest("hex");
22098
+ }
22099
+ function isPositivePid(value) {
22100
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
22101
+ }
22102
+ function validStartId(kind, value) {
22103
+ if (typeof value !== "string")
22104
+ return false;
22105
+ if (kind === "linux-proc-start-ticks")
22106
+ return LINUX_START_PATTERN.test(value);
22107
+ if (kind === "darwin-ps-lstart")
22108
+ return DARWIN_START_PATTERN.test(value);
22109
+ if (kind === "windows-start-ticks")
22110
+ return WINDOWS_START_PATTERN.test(value);
22111
+ return false;
22112
+ }
22113
+ function parseProcessIncarnation(value) {
22114
+ if (typeof value !== "object" || value === null || Array.isArray(value))
22115
+ return;
22116
+ const identity = value;
22117
+ if (identity.version !== PROCESS_INCARNATION_VERSION || !isPositivePid(identity.pid) || typeof identity.hostId !== "string" || !SHA256_PATTERN.test(identity.hostId) || typeof identity.bootId !== "string" || !UUID_PATTERN.test(identity.bootId) || typeof identity.startId !== "string" || !validStartId(identity.startIdKind, identity.startId))
22118
+ return;
22119
+ return {
22120
+ version: PROCESS_INCARNATION_VERSION,
22121
+ pid: identity.pid,
22122
+ hostId: identity.hostId,
22123
+ bootId: identity.bootId,
22124
+ startId: identity.startId,
22125
+ startIdKind: identity.startIdKind
22126
+ };
22127
+ }
22128
+ function evaluateProcessIncarnation(owner, localBoot, observedStart) {
22129
+ const parsedOwner = parseProcessIncarnation(owner);
22130
+ if (!parsedOwner || !localBoot || !SHA256_PATTERN.test(localBoot.hostId) || !UUID_PATTERN.test(localBoot.bootId) || parsedOwner.hostId !== localBoot.hostId)
22131
+ return "indeterminate";
22132
+ if (parsedOwner.bootId !== localBoot.bootId)
22133
+ return "dead";
22134
+ if (!observedStart || observedStart.status === "indeterminate")
22135
+ return "indeterminate";
22136
+ if (observedStart.status === "missing")
22137
+ return "dead";
22138
+ if (!validStartId(observedStart.startIdKind, observedStart.startId) || observedStart.startIdKind !== parsedOwner.startIdKind)
22139
+ return "indeterminate";
22140
+ if (observedStart.startId !== parsedOwner.startId)
22141
+ return "dead";
22142
+ return parsedOwner.startIdKind === "linux-proc-start-ticks" ? "alive" : "indeterminate";
22143
+ }
22144
+ function normalizeUuid(raw2) {
22145
+ const value = raw2.trim().toLowerCase();
22146
+ return UUID_PATTERN.test(value) ? value : undefined;
22147
+ }
22148
+ function readFirst(paths) {
22149
+ for (const path of paths) {
22150
+ try {
22151
+ const value = readFileSync(path, "utf8").trim();
22152
+ if (value)
22153
+ return value;
22154
+ } catch {}
22155
+ }
22156
+ return;
22157
+ }
22158
+ function linuxLocalBootIdentity() {
22159
+ const machineId = readFirst(["/etc/machine-id", "/var/lib/dbus/machine-id"]);
22160
+ const bootId = normalizeUuid(readFileSync("/proc/sys/kernel/random/boot_id", "utf8"));
22161
+ const pidNamespace = readlinkSync("/proc/self/ns/pid");
22162
+ if (!machineId || !/^[0-9a-fA-F]{32}$/.test(machineId) || !bootId || !/^pid:\[[0-9]+\]$/.test(pidNamespace)) {
22163
+ return;
22164
+ }
22165
+ return {
22166
+ hostId: hashIdentity(`linux:${machineId.toLowerCase()}:${pidNamespace}`),
22167
+ bootId
22168
+ };
22169
+ }
22170
+ function runDarwin(command, args) {
22171
+ const result = spawnSync(command, args, {
22172
+ encoding: "utf8",
22173
+ env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC0" },
22174
+ timeout: PROBE_TIMEOUT_MS,
22175
+ maxBuffer: 1024 * 1024
22176
+ });
22177
+ if (result.error || result.status !== 0 || typeof result.stdout !== "string")
22178
+ return;
22179
+ return result.stdout;
22180
+ }
22181
+ function darwinLocalBootIdentity() {
22182
+ const ioreg = runDarwin("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"]);
22183
+ const boot = runDarwin("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"]);
22184
+ const machineMatch = ioreg?.match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]+)"/);
22185
+ const machineId = machineMatch?.[1] ? normalizeUuid(machineMatch[1]) : undefined;
22186
+ const bootId = boot ? normalizeUuid(boot) : undefined;
22187
+ if (!machineId || !bootId)
22188
+ return;
22189
+ return {
22190
+ hostId: hashIdentity(`darwin:${machineId}`),
22191
+ bootId
22192
+ };
22193
+ }
22194
+ function uuidFromIdentity(value) {
22195
+ const hex3 = createHash2("sha256").update(value).digest("hex").slice(0, 32);
22196
+ return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
22197
+ }
22198
+ function runWindowsPowerShell(script) {
22199
+ const result = spawnSync("powershell.exe", [
22200
+ "-NoLogo",
22201
+ "-NoProfile",
22202
+ "-NonInteractive",
22203
+ "-ExecutionPolicy",
22204
+ "Bypass",
22205
+ "-Command",
22206
+ script
22207
+ ], {
22208
+ encoding: "utf8",
22209
+ windowsHide: true,
22210
+ timeout: WINDOWS_PROBE_TIMEOUT_MS,
22211
+ maxBuffer: 1024 * 1024
22212
+ });
22213
+ return {
22214
+ status: result.error ? null : result.status,
22215
+ ...typeof result.stdout === "string" ? { stdout: result.stdout } : {}
22216
+ };
22217
+ }
22218
+ function windowsLocalBootIdentity() {
22219
+ const result = runWindowsPowerShell(String.raw`
22220
+ $ErrorActionPreference = 'Stop'
22221
+ $machine = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Cryptography' -Name MachineGuid).MachineGuid
22222
+ try { $boot = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime }
22223
+ catch { $boot = (Get-WmiObject Win32_OperatingSystem).ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).LastBootUpTime) }
22224
+ Write-Output $machine
22225
+ Write-Output $boot.ToUniversalTime().Ticks
22226
+ `);
22227
+ if (result.status !== 0 || !result.stdout)
22228
+ return;
22229
+ const [machine, bootTicks] = result.stdout.trim().split(/\r?\n/).map((part) => part.trim());
22230
+ if (!machine || !bootTicks || !WINDOWS_START_PATTERN.test(bootTicks))
22231
+ return;
22232
+ return {
22233
+ hostId: hashIdentity(`windows:${machine.toLowerCase()}`),
22234
+ bootId: uuidFromIdentity(`windows-boot:${machine.toLowerCase()}:${bootTicks}`)
22235
+ };
22236
+ }
22237
+ function pinnedHostIdFor(pin) {
22238
+ const trimmed = pin?.trim();
22239
+ return trimmed ? hashIdentity(`pinned:${trimmed}`) : undefined;
22240
+ }
22241
+ function pinnedHostId() {
22242
+ return pinnedHostIdFor(process.env.MERIDIAN_HOST_ID);
22243
+ }
22244
+ function getLocalBootIdentity() {
22245
+ if (cachedLocalBootIdentity)
22246
+ return cachedLocalBootIdentity;
22247
+ try {
22248
+ const identity = process.platform === "linux" ? linuxLocalBootIdentity() : process.platform === "darwin" ? darwinLocalBootIdentity() : process.platform === "win32" ? windowsLocalBootIdentity() : undefined;
22249
+ const pinned = pinnedHostId();
22250
+ const resolved = identity && pinned ? { ...identity, hostId: pinned } : identity;
22251
+ if (resolved)
22252
+ cachedLocalBootIdentity = resolved;
22253
+ return resolved;
22254
+ } catch {
22255
+ return;
22256
+ }
22257
+ }
22258
+ function bootIdentityHint(platform) {
22259
+ if (platform === "linux") {
22260
+ return "no readable /etc/machine-id or /var/lib/dbus/machine-id, or /proc is not mounted. " + "Distroless, scratch, chroot and gVisor images commonly lack machine-id: " + "generate one (`dbus-uuidgen > /etc/machine-id`) or bind-mount the host's.";
22261
+ }
22262
+ if (platform === "darwin") {
22263
+ return "could not read the hardware UUID or boot time from the system profiler.";
22264
+ }
22265
+ if (platform === "win32") {
22266
+ return "could not read the machine GUID or boot time from the registry.";
22267
+ }
22268
+ return `unsupported platform "${platform}" — boot identity is implemented for linux, darwin and win32 only.`;
22269
+ }
22270
+ function describeLocalBootIdentity() {
22271
+ const platform = process.platform;
22272
+ if (getLocalBootIdentity())
22273
+ return { available: true, platform };
22274
+ return { available: false, platform, hint: bootIdentityHint(platform) };
22275
+ }
22276
+ function pidPresence(pid) {
22277
+ try {
22278
+ process.kill(pid, 0);
22279
+ return "present";
22280
+ } catch (error51) {
22281
+ const code = error51 instanceof Error && "code" in error51 ? error51.code : undefined;
22282
+ return code === "ESRCH" ? "missing" : "indeterminate";
22283
+ }
22284
+ }
22285
+ function parseLinuxProcStatStartId(raw2, expectedPid) {
22286
+ const prefix = `${expectedPid} (`;
22287
+ if (!raw2.startsWith(prefix))
22288
+ return;
22289
+ const commEnd = raw2.lastIndexOf(")");
22290
+ if (commEnd < prefix.length || raw2[commEnd + 1] !== " ")
22291
+ return;
22292
+ const fieldsFromState = raw2.slice(commEnd + 2).trim().split(/\s+/);
22293
+ const startId = fieldsFromState[19];
22294
+ return startId && LINUX_START_PATTERN.test(startId) ? startId : undefined;
22295
+ }
22296
+ function linuxProcessStart(pid) {
22297
+ let raw2;
22298
+ try {
22299
+ raw2 = readFileSync(`/proc/${pid}/stat`, "utf8");
22300
+ } catch (error51) {
22301
+ const code = error51 instanceof Error && "code" in error51 ? error51.code : undefined;
22302
+ if (code === "ENOENT" || code === "ESRCH")
22303
+ return { status: "missing" };
22304
+ return { status: "indeterminate" };
22305
+ }
22306
+ const startId = parseLinuxProcStatStartId(raw2, pid);
22307
+ if (startId)
22308
+ return { status: "found", startId, startIdKind: "linux-proc-start-ticks" };
22309
+ return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
22310
+ }
22311
+ function darwinProcessStart(pid) {
22312
+ const output = runDarwin("/bin/ps", ["-p", String(pid), "-o", "lstart="]);
22313
+ if (output !== undefined) {
22314
+ const startId = output.trimEnd().trimStart();
22315
+ if (DARWIN_START_PATTERN.test(startId)) {
22316
+ return { status: "found", startId, startIdKind: "darwin-ps-lstart" };
22317
+ }
22318
+ }
22319
+ return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
22320
+ }
22321
+ function windowsProcessStart(pid) {
22322
+ const result = runWindowsPowerShell(String.raw`
22323
+ $ErrorActionPreference = 'Stop'
22324
+ try {
22325
+ $process = Get-Process -Id ${pid} -ErrorAction Stop
22326
+ Write-Output $process.StartTime.ToUniversalTime().Ticks
22327
+ } catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
22328
+ exit 3
22329
+ } catch {
22330
+ exit 4
22331
+ }
22332
+ `);
22333
+ const startId = result.stdout?.trim();
22334
+ if (result.status === 0 && startId && WINDOWS_START_PATTERN.test(startId)) {
22335
+ return { status: "found", startId, startIdKind: "windows-start-ticks" };
22336
+ }
22337
+ if (result.status === 3)
22338
+ return { status: "missing" };
22339
+ return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
22340
+ }
22341
+ function observeProcessStart(pid) {
22342
+ if (process.platform === "linux")
22343
+ return linuxProcessStart(pid);
22344
+ if (process.platform === "darwin")
22345
+ return darwinProcessStart(pid);
22346
+ if (process.platform === "win32")
22347
+ return windowsProcessStart(pid);
22348
+ return { status: "indeterminate" };
22349
+ }
22350
+ function captureProcessIncarnation(pid = process.pid) {
22351
+ if (!isPositivePid(pid))
22352
+ return;
22353
+ if (pid === process.pid && cachedCurrentProcessIncarnation) {
22354
+ return { ...cachedCurrentProcessIncarnation };
22355
+ }
22356
+ const localBoot = getLocalBootIdentity();
22357
+ if (!localBoot)
22358
+ return;
22359
+ const start = observeProcessStart(pid);
22360
+ if (start.status !== "found")
22361
+ return;
22362
+ const identity = {
22363
+ version: PROCESS_INCARNATION_VERSION,
22364
+ pid,
22365
+ ...localBoot,
22366
+ startId: start.startId,
22367
+ startIdKind: start.startIdKind
22368
+ };
22369
+ if (pid === process.pid)
22370
+ cachedCurrentProcessIncarnation = identity;
22371
+ return { ...identity };
22372
+ }
22373
+ function probeProcessIncarnation(owner) {
22374
+ const parsed = parseProcessIncarnation(owner);
22375
+ if (!parsed)
22376
+ return "indeterminate";
22377
+ const localBoot = getLocalBootIdentity();
22378
+ if (!localBoot || parsed.hostId !== localBoot.hostId)
22379
+ return "indeterminate";
22380
+ if (parsed.bootId !== localBoot.bootId) {
22381
+ return evaluateProcessIncarnation(parsed, localBoot, undefined);
22382
+ }
22383
+ return evaluateProcessIncarnation(parsed, localBoot, observeProcessStart(parsed.pid));
22384
+ }
22385
+ function processIncarnationIsDead(owner) {
22386
+ return probeProcessIncarnation(owner) === "dead";
22387
+ }
22388
+
21925
22389
  // src/proxy/server.ts
21926
22390
  init_tools();
21927
22391
 
@@ -21931,7 +22395,7 @@ var INTERNAL_TOOLS = new Set(["ToolSearch", "StructuredOutput"]);
21931
22395
  function createEarlyStopTracker() {
21932
22396
  return { expected: new Set, resolved: new Set, fired: false };
21933
22397
  }
21934
- function isClientForwardedToolUse(block) {
22398
+ function isClientForwardedToolUse(block, clientToolPrefix = CLIENT_TOOL_PREFIX) {
21935
22399
  const b = block;
21936
22400
  if (!b || b.type !== "tool_use")
21937
22401
  return false;
@@ -21941,26 +22405,26 @@ function isClientForwardedToolUse(block) {
21941
22405
  return false;
21942
22406
  if (INTERNAL_TOOLS.has(b.name))
21943
22407
  return false;
21944
- if (b.name.startsWith("mcp__") && !b.name.startsWith(CLIENT_TOOL_PREFIX))
22408
+ if (b.name.startsWith("mcp__") && !b.name.startsWith(clientToolPrefix))
21945
22409
  return false;
21946
22410
  return true;
21947
22411
  }
21948
- function noteAssistantContent(tracker, content) {
22412
+ function noteAssistantContent(tracker, content, clientToolPrefix = CLIENT_TOOL_PREFIX) {
21949
22413
  if (!Array.isArray(content))
21950
22414
  return;
21951
22415
  for (const block of content) {
21952
- if (isClientForwardedToolUse(block)) {
22416
+ if (isClientForwardedToolUse(block, clientToolPrefix)) {
21953
22417
  tracker.expected.add(block.id);
21954
22418
  }
21955
22419
  }
21956
22420
  }
21957
- function noteAssistantMessage(tracker, message) {
22421
+ function noteAssistantMessage(tracker, message, clientToolPrefix = CLIENT_TOOL_PREFIX) {
21958
22422
  const m = message;
21959
22423
  if (m?.type !== "assistant")
21960
22424
  return;
21961
22425
  const content = m.message?.content;
21962
22426
  const before = tracker.expected.size;
21963
- noteAssistantContent(tracker, content);
22427
+ noteAssistantContent(tracker, content, clientToolPrefix);
21964
22428
  if (tracker.expected.size > before) {
21965
22429
  tracker.toolCallAssistantUuid = typeof m.uuid === "string" && m.uuid.length > 0 ? m.uuid : undefined;
21966
22430
  }
@@ -22342,7 +22806,7 @@ class MemoryDiagnosticLogStore {
22342
22806
  }
22343
22807
  var diagnosticLog = new MemoryDiagnosticLogStore;
22344
22808
  // src/telemetry/routes.ts
22345
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
22809
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
22346
22810
  import { resolve as resolve2, dirname as dirname2 } from "node:path";
22347
22811
  import { fileURLToPath } from "node:url";
22348
22812
 
@@ -22765,7 +23229,7 @@ timer = setInterval(refresh, 5000);
22765
23229
 
22766
23230
  // src/telemetry/routes.ts
22767
23231
  var _iconPath = resolve2(dirname2(fileURLToPath(import.meta.url)), "..", "..", "assets", "icon.svg");
22768
- var _iconSvg = existsSync3(_iconPath) ? readFileSync2(_iconPath, "utf-8") : null;
23232
+ var _iconSvg = existsSync3(_iconPath) ? readFileSync3(_iconPath, "utf-8") : null;
22769
23233
  function createTelemetryRoutes(deps = {}) {
22770
23234
  const routes = new Hono2;
22771
23235
  routes.get("/", (c) => {
@@ -23159,7 +23623,9 @@ function createStores() {
23159
23623
  const dbPath = env("TELEMETRY_DB") ?? getDefaultDbPath();
23160
23624
  const retention = envInt("TELEMETRY_RETENTION_DAYS", 7);
23161
23625
  const stores = createSqliteStores2(dbPath, retention);
23162
- console.error(`[telemetry] SQLite persistence enabled: ${dbPath} (${retention}d retention)`);
23626
+ if (!envBool("QUIET")) {
23627
+ console.error(`[telemetry] SQLite persistence enabled: ${dbPath} (${retention}d retention)`);
23628
+ }
23163
23629
  return { telemetry: stores.telemetry, diagnostics: stores.diagnostics };
23164
23630
  } catch {
23165
23631
  console.warn("[telemetry] MERIDIAN_TELEMETRY_PERSIST is set but libsql is not installed. Run: npm install libsql");
@@ -23201,9 +23667,14 @@ var BILLING_SIGNALS = [
23201
23667
  /^\s*(?:(?:error|api error|claude code returned an error result):\s*)*credit balance is too low[.!]?\s*$/m,
23202
23668
  /^\s*(?:(?:error|api error|claude code returned an error result|subprocess stderr):\s*)*your (?:group|organization|org)(?:'|’)s usage limit is set to \$\d/m
23203
23669
  ];
23670
+ var SUBSCRIPTION_ACCESS_DISABLED = /^\s*(?:(?:error|api error|claude code returned an error result|subprocess stderr):\s*|failed to authenticate\.\s*)*(?:\d{3} )?your (?:organization|org) has disabled claude subscription access/m;
23204
23671
  var HIT_YOUR_LIMIT = /hit your (?:[\w-]+ )?limit/;
23205
23672
  var HIT_YOUR_SPEND_LIMIT = /^\s*(?:(?:error|api error|claude code returned an error result|subprocess stderr):\s*)*you(?:'|’)ve hit your (?:[\w'’-]+ ){0,4}(?:spend|usage) limit/m;
23206
- var REACHED_YOUR_TIER_LIMIT = /^[ \t]*(?:(?:error|api error|claude code returned an error result|subprocess stderr):[ \t]*)*you(?:'|’)ve reached your (?:claude )?(?:fable|mythos|opus|sonnet|haiku)(?: \d+(?:\.\d+)*)? limit(?:(?:[.!][ \t]+|[ \t]+)(?:(?:run[ \t]+)?\/usage-credits(?:[ \t]+to[ \t]+continue)?(?:[ \t]+or[ \t]+switch[ \t]+models[ \t]+with[ \t]+\/model)?|\/model[ \t]+to[ \t]+switch[ \t]+models)\.?|[.!]?)[ \t\r]*$/m;
23673
+ var REACHED_YOUR_TIER_LIMIT = /^[ \t]*(?:(?:error|api error|claude code returned an error result|subprocess stderr):[ \t]*)*(?:\d{3}[ \t]+)?you(?:'|’)ve reached your (?:claude )?(?:fable|mythos|opus|sonnet|haiku)(?: \d+(?:\.\d+)*)? limit(?:(?:[.!][ \t]+|[ \t]+)(?:(?:run[ \t]+)?\/usage-credits(?:[ \t]+to[ \t]+continue)?(?:[ \t]+or[ \t]+switch[ \t]+models[ \t]+with[ \t]+\/model)?|\/model[ \t]+to[ \t]+switch[ \t]+models|switch[ \t]+to[ \t]+another[ \t]+model(?:[ \t]+to[ \t]+continue)?)\.?|[.!]?)[ \t\r]*$/m;
23674
+ var OUTPUT_TOKEN_MAXIMUM = /response exceeded the \d+ output token maximum/i;
23675
+ function isOutputTokenCapExceeded(message) {
23676
+ return typeof message === "string" && OUTPUT_TOKEN_MAXIMUM.test(message);
23677
+ }
23207
23678
  var OUT_OF_USAGE_CREDITS = /^\s*(?:(?:error|api error|claude code returned an error result):\s*)*you(?:'|’)re out of usage credits(?:[.!]\s*)?(?:\/model to switch models\.?)?\s*$/;
23208
23679
  var HTTP_401 = /(?:^|[^0-9a-f])401(?![0-9a-f]|:\d)/;
23209
23680
  var HTTP_429 = /(?:^|[^0-9a-f])429(?![0-9a-f]|:\d)/;
@@ -23225,6 +23696,13 @@ function classifyError(errMsg, model) {
23225
23696
  message: "Claude OAuth token has expired and could not be refreshed automatically. Run 'claude login' in your terminal to re-authenticate."
23226
23697
  };
23227
23698
  }
23699
+ if (SUBSCRIPTION_ACCESS_DISABLED.test(lower)) {
23700
+ return {
23701
+ status: 402,
23702
+ type: "billing_error",
23703
+ message: "This account's organization has disabled Claude subscription access for Claude Code. Ask the organization admin to re-enable it, or serve this request from an API-key profile — an identical retry on this account fails the same way."
23704
+ };
23705
+ }
23228
23706
  if (HTTP_401.test(lower) || lower.includes("authentication") || lower.includes("invalid auth") || lower.includes("credentials")) {
23229
23707
  return {
23230
23708
  status: 401,
@@ -24413,8 +24891,146 @@ function buildModelList(extendedContextIncluded, now = Math.floor(Date.now() / 1
24413
24891
 
24414
24892
  // src/proxy/server.ts
24415
24893
  init_jcode();
24894
+ init_claudecode();
24416
24895
 
24417
24896
  // src/proxy/openaiResponses.ts
24897
+ import { createHash as createHash4 } from "node:crypto";
24898
+ var PASSTHROUGH_PREFIX_LENGTH = "mcp__oc__".length;
24899
+ var RESPONSES_TOOL_ALIAS_MAX = 64 - PASSTHROUGH_PREFIX_LENGTH;
24900
+ function responsesToolAlias(namespace, name) {
24901
+ const raw2 = namespace ? `${namespace}__${name}` : name;
24902
+ const safe = raw2.replace(/[^A-Za-z0-9_-]/g, "_");
24903
+ if (safe.length <= RESPONSES_TOOL_ALIAS_MAX)
24904
+ return safe;
24905
+ const digest = createHash4("sha256").update(raw2).digest("hex").slice(0, 8);
24906
+ return `${safe.slice(0, RESPONSES_TOOL_ALIAS_MAX - digest.length - 1)}_${digest}`;
24907
+ }
24908
+ function buildResponsesToolAliases(tools) {
24909
+ const aliases = new Map;
24910
+ for (const tool of tools ?? []) {
24911
+ if (tool.type === "custom") {
24912
+ aliases.set(responsesToolAlias(undefined, tool.name), { name: tool.name, kind: "custom" });
24913
+ } else if (tool.type === "namespace") {
24914
+ for (const nested of tool.tools ?? []) {
24915
+ if (nested.type !== "function" && nested.type !== "custom")
24916
+ continue;
24917
+ aliases.set(responsesToolAlias(tool.name, nested.name), {
24918
+ namespace: tool.name,
24919
+ name: nested.name,
24920
+ kind: nested.type
24921
+ });
24922
+ }
24923
+ }
24924
+ }
24925
+ return aliases;
24926
+ }
24927
+ var CUSTOM_TOOL_INPUT_SCHEMA = {
24928
+ type: "object",
24929
+ properties: {
24930
+ input: { type: "string", description: "The complete freeform payload, exactly as the tool's format requires." }
24931
+ },
24932
+ required: ["input"],
24933
+ additionalProperties: false
24934
+ };
24935
+ function customToolDescription(tool) {
24936
+ const parts = [tool.description ?? "", "Freeform tool: put the entire payload in the `input` string; do not wrap it in JSON."];
24937
+ const format = tool.format && typeof tool.format === "object" ? tool.format : undefined;
24938
+ if (typeof format?.definition === "string") {
24939
+ parts.push(`Input grammar${typeof format.syntax === "string" ? ` (${format.syntax})` : ""}:
24940
+ ${format.definition}`);
24941
+ }
24942
+ return parts.filter((s) => s.length > 0).join(`
24943
+
24944
+ `);
24945
+ }
24946
+ function translateResponsesTools(tools) {
24947
+ const out = [];
24948
+ const push = (namespace, tool) => {
24949
+ if (tool.type === "function") {
24950
+ out.push({
24951
+ name: namespace ? responsesToolAlias(namespace, tool.name) : tool.name,
24952
+ description: namespace ? `[${namespace}] ${tool.description ?? ""}`.trimEnd() : tool.description ?? "",
24953
+ input_schema: tool.parameters ?? { type: "object", properties: {} }
24954
+ });
24955
+ } else if (tool.type === "custom") {
24956
+ out.push({
24957
+ name: responsesToolAlias(namespace, tool.name),
24958
+ description: customToolDescription(tool),
24959
+ input_schema: CUSTOM_TOOL_INPUT_SCHEMA
24960
+ });
24961
+ }
24962
+ };
24963
+ for (const tool of tools) {
24964
+ if (tool.type === "namespace") {
24965
+ for (const nested of tool.tools ?? [])
24966
+ push(tool.name, nested);
24967
+ } else {
24968
+ push(undefined, tool);
24969
+ }
24970
+ }
24971
+ return out;
24972
+ }
24973
+ function toolCallItem(ctx, id, callId, name, argsJson, status) {
24974
+ const alias = ctx.toolAliases?.get(name);
24975
+ const namespace = alias?.namespace ? { namespace: alias.namespace } : {};
24976
+ if (alias?.kind === "custom") {
24977
+ let input = argsJson;
24978
+ try {
24979
+ const parsed = JSON.parse(argsJson || "{}");
24980
+ if (parsed && typeof parsed === "object" && typeof parsed.input === "string") {
24981
+ input = parsed.input;
24982
+ } else if (argsJson === "" || argsJson === "{}") {
24983
+ input = "";
24984
+ }
24985
+ } catch {}
24986
+ return { type: "custom_tool_call", id, call_id: callId, name: alias.name, ...namespace, input, status };
24987
+ }
24988
+ return { type: "function_call", id, call_id: callId, name: alias?.name ?? name, ...namespace, arguments: argsJson, status };
24989
+ }
24990
+ var CODEX_TURN_METADATA = "x-codex-turn-metadata";
24991
+ var CODEX_THREAD_SOURCE_MAX = 24;
24992
+ var CODEX_TURN_KIND = "turn";
24993
+ function nonEmptyString(value) {
24994
+ return typeof value === "string" && value.length > 0 ? value : undefined;
24995
+ }
24996
+ function codexTag(value) {
24997
+ const tag = value.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, CODEX_THREAD_SOURCE_MAX);
24998
+ return tag.replace(/-/g, "") ? tag : undefined;
24999
+ }
25000
+ function parseCodexTurnMetadata(value) {
25001
+ if (value && typeof value === "object")
25002
+ return value;
25003
+ const raw2 = nonEmptyString(value);
25004
+ if (!raw2)
25005
+ return;
25006
+ try {
25007
+ const parsed = JSON.parse(raw2);
25008
+ return parsed && typeof parsed === "object" ? parsed : undefined;
25009
+ } catch {
25010
+ return;
25011
+ }
25012
+ }
25013
+ function codexTurnMetadataFromBody(body) {
25014
+ const metadata = body.client_metadata;
25015
+ if (!metadata || typeof metadata !== "object")
25016
+ return;
25017
+ return metadata[CODEX_TURN_METADATA];
25018
+ }
25019
+ function resolveCodexThreadIdentity(body, metadataHeader) {
25020
+ const metadata = parseCodexTurnMetadata(metadataHeader) ?? parseCodexTurnMetadata(codexTurnMetadataFromBody(body));
25021
+ const identity = {};
25022
+ const threadKey = nonEmptyString(metadata?.thread_id) ?? nonEmptyString(body.prompt_cache_key);
25023
+ const kind = nonEmptyString(metadata?.request_kind);
25024
+ const kindTag = kind && kind !== CODEX_TURN_KIND ? codexTag(kind) : undefined;
25025
+ if (threadKey)
25026
+ identity.sessionKey = kindTag ? `${threadKey}:${kindTag}` : threadKey;
25027
+ const threadSource = nonEmptyString(metadata?.thread_source);
25028
+ const sourceTag = threadSource && threadSource !== "user" ? codexTag(threadSource) : undefined;
25029
+ const flow = kindTag ?? sourceTag;
25030
+ if (flow)
25031
+ identity.requestSource = `fork-codex-${flow}`;
25032
+ return identity;
25033
+ }
24418
25034
  function itemDiscriminator(item) {
24419
25035
  if (typeof item !== "object" || item === null)
24420
25036
  return;
@@ -24449,6 +25065,28 @@ function partsToBlocks(content) {
24449
25065
  }
24450
25066
  return blocks;
24451
25067
  }
25068
+ function toolOutputToContent(output) {
25069
+ if (output === undefined || output === null)
25070
+ return "";
25071
+ if (typeof output === "string")
25072
+ return output;
25073
+ if (!Array.isArray(output))
25074
+ return typeof output === "object" ? JSON.stringify(output) : String(output);
25075
+ const blocks = [];
25076
+ for (const part of output) {
25077
+ if (!part || typeof part !== "object")
25078
+ continue;
25079
+ if (typeof part.text === "string") {
25080
+ blocks.push({ type: "text", text: part.text });
25081
+ } else if (part.type === "input_image") {
25082
+ const image = typeof part.image_url === "string" ? parseDataUrlImage(part.image_url) : null;
25083
+ blocks.push(image ?? { type: "text", text: "[Unsupported input_image omitted: only data URLs are currently supported]" });
25084
+ } else {
25085
+ blocks.push({ type: "text", text: `[Unsupported ${String(part.type)} tool output part omitted]` });
25086
+ }
25087
+ }
25088
+ return blocks.length > 0 ? blocks : "";
25089
+ }
24452
25090
  function mapToolChoice(tc) {
24453
25091
  if (tc === "auto")
24454
25092
  return { type: "auto" };
@@ -24476,21 +25114,36 @@ function translateResponsesToAnthropic(body) {
24476
25114
  const pushBlock = (role, block) => {
24477
25115
  const last = messages[messages.length - 1];
24478
25116
  if (last && last.role === role && Array.isArray(last.content)) {
24479
- last.content.push(block);
25117
+ if (block.type === "tool_result") {
25118
+ const firstText = last.content.findIndex((b) => b.type !== "tool_result");
25119
+ if (firstText === -1)
25120
+ last.content.push(block);
25121
+ else
25122
+ last.content.splice(firstText, 0, block);
25123
+ } else {
25124
+ last.content.push(block);
25125
+ }
24480
25126
  } else {
24481
25127
  messages.push({ role, content: [block] });
24482
25128
  }
24483
25129
  };
25130
+ let conversationStarted = false;
24484
25131
  for (const item of items) {
24485
25132
  switch (itemDiscriminator(item)) {
24486
25133
  case "message": {
24487
25134
  const msg = item;
24488
25135
  if (msg.role === "developer" || msg.role === "system") {
24489
25136
  const t = partsToText(msg.content);
24490
- if (t)
25137
+ if (!t)
25138
+ break;
25139
+ if (!conversationStarted) {
24491
25140
  systemParts.push(t);
25141
+ break;
25142
+ }
25143
+ pushBlock("user", { type: "text", text: t });
24492
25144
  break;
24493
25145
  }
25146
+ conversationStarted = true;
24494
25147
  const role = msg.role === "assistant" ? "assistant" : "user";
24495
25148
  const imageBlocks = partsToBlocks(msg.content);
24496
25149
  if (imageBlocks) {
@@ -24504,6 +25157,7 @@ function translateResponsesToAnthropic(body) {
24504
25157
  break;
24505
25158
  }
24506
25159
  case "function_call": {
25160
+ conversationStarted = true;
24507
25161
  const fc = item;
24508
25162
  let input = {};
24509
25163
  try {
@@ -24511,12 +25165,25 @@ function translateResponsesToAnthropic(body) {
24511
25165
  } catch {
24512
25166
  input = {};
24513
25167
  }
24514
- pushBlock("assistant", { type: "tool_use", id: fc.call_id, name: fc.name, input });
25168
+ const name = fc.namespace ? responsesToolAlias(fc.namespace, fc.name) : fc.name;
25169
+ pushBlock("assistant", { type: "tool_use", id: fc.call_id, name, input });
24515
25170
  break;
24516
25171
  }
24517
25172
  case "function_call_output": {
25173
+ conversationStarted = true;
24518
25174
  const fo = item;
24519
- pushBlock("user", { type: "tool_result", tool_use_id: fo.call_id, content: fo.output });
25175
+ pushBlock("user", { type: "tool_result", tool_use_id: fo.call_id, content: toolOutputToContent(fo.output) });
25176
+ break;
25177
+ }
25178
+ case "custom_tool_call": {
25179
+ const ct = item;
25180
+ const name = responsesToolAlias(ct.namespace, ct.name);
25181
+ pushBlock("assistant", { type: "tool_use", id: ct.call_id, name, input: { input: ct.input ?? "" } });
25182
+ break;
25183
+ }
25184
+ case "custom_tool_call_output": {
25185
+ const co = item;
25186
+ pushBlock("user", { type: "tool_result", tool_use_id: co.call_id, content: toolOutputToContent(co.output) });
24520
25187
  break;
24521
25188
  }
24522
25189
  case "reasoning":
@@ -24536,11 +25203,7 @@ function translateResponsesToAnthropic(body) {
24536
25203
 
24537
25204
  `);
24538
25205
  if (Array.isArray(body.tools) && body.tools.length > 0) {
24539
- result.tools = body.tools.filter((t) => t.type === "function").map((t) => ({
24540
- name: t.name,
24541
- description: t.description ?? "",
24542
- input_schema: t.parameters ?? { type: "object", properties: {} }
24543
- }));
25206
+ result.tools = translateResponsesTools(body.tools);
24544
25207
  }
24545
25208
  const tc = mapToolChoice(body.tool_choice);
24546
25209
  if (tc)
@@ -24582,14 +25245,8 @@ function translateAnthropicToResponses(res, ctx) {
24582
25245
  if (block.type === "text" && typeof block.text === "string") {
24583
25246
  textParts.push({ type: "output_text", text: block.text, annotations: [] });
24584
25247
  } else if (block.type === "tool_use") {
24585
- output.push({
24586
- type: "function_call",
24587
- id: `fc_${block.id}`,
24588
- call_id: block.id,
24589
- name: block.name,
24590
- arguments: JSON.stringify(block.input ?? {}),
24591
- status: "completed"
24592
- });
25248
+ const callId = String(block.id);
25249
+ output.push(toolCallItem(ctx, `fc_${callId}`, callId, String(block.name), JSON.stringify(block.input ?? {}), "completed"));
24593
25250
  }
24594
25251
  }
24595
25252
  if (textParts.length > 0) {
@@ -24686,10 +25343,13 @@ function createResponsesSseTranslator(ctx) {
24686
25343
  } else if (cb.type === "tool_use") {
24687
25344
  const oi = outputIndex++;
24688
25345
  const itemId = `fc_${cb.id}`;
24689
- blocks.set(idx, { kind: "tool", outputIndex: oi, itemId, text: "", args: "", callId: cb.id, name: cb.name });
25346
+ const callId = String(cb.id ?? "");
25347
+ const name = String(cb.name ?? "");
25348
+ const custom2 = ctx.toolAliases?.get(name)?.kind === "custom";
25349
+ blocks.set(idx, { kind: "tool", outputIndex: oi, itemId, text: "", args: "", callId, name, custom: custom2 });
24690
25350
  out.push(emit("response.output_item.added", {
24691
25351
  output_index: oi,
24692
- item: { type: "function_call", id: itemId, call_id: cb.id, name: cb.name, arguments: "", status: "in_progress" }
25352
+ item: toolCallItem(ctx, itemId, callId, name, "", "in_progress")
24693
25353
  }));
24694
25354
  } else {
24695
25355
  blocks.set(idx, { kind: "skip", outputIndex: -1, itemId: "", text: "", args: "" });
@@ -24711,11 +25371,13 @@ function createResponsesSseTranslator(ctx) {
24711
25371
  }));
24712
25372
  } else if (st.kind === "tool" && event.delta?.type === "input_json_delta" && typeof event.delta.partial_json === "string") {
24713
25373
  st.args += event.delta.partial_json;
24714
- out.push(emit("response.function_call_arguments.delta", {
24715
- item_id: st.itemId,
24716
- output_index: st.outputIndex,
24717
- delta: event.delta.partial_json
24718
- }));
25374
+ if (!st.custom) {
25375
+ out.push(emit("response.function_call_arguments.delta", {
25376
+ item_id: st.itemId,
25377
+ output_index: st.outputIndex,
25378
+ delta: event.delta.partial_json
25379
+ }));
25380
+ }
24719
25381
  }
24720
25382
  break;
24721
25383
  }
@@ -24747,19 +25409,14 @@ function createResponsesSseTranslator(ctx) {
24747
25409
  finalOutput.push(item);
24748
25410
  out.push(emit("response.output_item.done", { output_index: st.outputIndex, item }));
24749
25411
  } else if (st.kind === "tool") {
24750
- out.push(emit("response.function_call_arguments.done", {
24751
- item_id: st.itemId,
24752
- output_index: st.outputIndex,
24753
- arguments: st.args
24754
- }));
24755
- const item = {
24756
- type: "function_call",
24757
- id: st.itemId,
24758
- call_id: st.callId,
24759
- name: st.name,
24760
- arguments: st.args,
24761
- status: "completed"
24762
- };
25412
+ if (!st.custom) {
25413
+ out.push(emit("response.function_call_arguments.done", {
25414
+ item_id: st.itemId,
25415
+ output_index: st.outputIndex,
25416
+ arguments: st.args
25417
+ }));
25418
+ }
25419
+ const item = toolCallItem(ctx, st.itemId, st.callId ?? "", st.name ?? "", st.args, "completed");
24763
25420
  finalOutput.push(item);
24764
25421
  out.push(emit("response.output_item.done", { output_index: st.outputIndex, item }));
24765
25422
  }
@@ -27874,7 +28531,7 @@ class LRUCache {
27874
28531
  // node_modules/path-scurry/dist/esm/index.js
27875
28532
  import { posix, win32 } from "node:path";
27876
28533
  import { fileURLToPath as fileURLToPath2 } from "node:url";
27877
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
28534
+ import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync as readlinkSync2, realpathSync as rps } from "fs";
27878
28535
  import * as actualFS from "node:fs";
27879
28536
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
27880
28537
 
@@ -28545,7 +29202,7 @@ var defaultFS = {
28545
29202
  lstatSync,
28546
29203
  readdir: readdirCB,
28547
29204
  readdirSync,
28548
- readlinkSync,
29205
+ readlinkSync: readlinkSync2,
28549
29206
  realpathSync,
28550
29207
  promises: {
28551
29208
  lstat,
@@ -31119,6 +31776,7 @@ function buildQueryOptions(ctx, abortController) {
31119
31776
  dreaming,
31120
31777
  sharedMemory,
31121
31778
  maxBudgetUsd,
31779
+ maxOutputTokens,
31122
31780
  fallbackModel,
31123
31781
  sdkDebug,
31124
31782
  additionalDirectories
@@ -31146,7 +31804,7 @@ function buildQueryOptions(ctx, abortController) {
31146
31804
  disallowedTools: [...allBlockedTools],
31147
31805
  ...passthroughMcp ? {
31148
31806
  allowedTools: [...passthroughMcp.toolNames],
31149
- mcpServers: { [PASSTHROUGH_MCP_NAME]: passthroughMcp.server }
31807
+ mcpServers: { [passthroughMcp.serverName]: passthroughMcp.server }
31150
31808
  } : {}
31151
31809
  } : {
31152
31810
  disallowedTools: [...allBlockedTools],
@@ -31165,6 +31823,7 @@ function buildQueryOptions(ctx, abortController) {
31165
31823
  ...QUIET_SUBPROCESS_ENV,
31166
31824
  ...sharedMemory ? stripConfigDir(cleanEnv) : cleanEnv,
31167
31825
  ENABLE_TOOL_SEARCH: hasDeferredTools ? "true" : "false",
31826
+ ...maxOutputTokens && maxOutputTokens > 0 ? { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(Math.floor(maxOutputTokens)) } : {},
31168
31827
  ENABLE_CLAUDEAI_MCP_SERVERS: !passthrough && ctx.claudeAiConnectors === true ? "true" : "false",
31169
31828
  ...passthrough && process.env.MERIDIAN_SUPPRESS_SCRATCHPAD !== "0" ? { CLAUDE_CODE_SESSION_KIND: "bg" } : {},
31170
31829
  ...process.getuid?.() === 0 ? { IS_SANDBOX: "1" } : {},
@@ -31313,7 +31972,7 @@ var codexTransforms = [
31313
31972
  name: "codex-force-passthrough",
31314
31973
  adapters: ["codex"],
31315
31974
  onRequest(ctx) {
31316
- return { ...ctx, passthrough: true };
31975
+ return { ...ctx, passthrough: true, coreToolNames: undefined };
31317
31976
  }
31318
31977
  }
31319
31978
  ];
@@ -31358,6 +32017,7 @@ var claudeCodeTransforms = [
31358
32017
  ];
31359
32018
 
31360
32019
  // src/proxy/transforms/registry.ts
32020
+ init_polytoken();
31361
32021
  var ADAPTER_TRANSFORMS = {
31362
32022
  opencode: openCodeTransforms,
31363
32023
  crush: crushTransforms,
@@ -31370,14 +32030,15 @@ var ADAPTER_TRANSFORMS = {
31370
32030
  "claude-code": claudeCodeTransforms,
31371
32031
  openai: openCodeTransforms,
31372
32032
  jcode: openCodeTransforms,
31373
- codex: [...openCodeTransforms, ...codexTransforms]
32033
+ codex: [...openCodeTransforms, ...codexTransforms],
32034
+ polytoken: polytokenTransforms
31374
32035
  };
31375
32036
  function getAdapterTransforms(adapterName) {
31376
32037
  return ADAPTER_TRANSFORMS[adapterName] ?? [];
31377
32038
  }
31378
32039
 
31379
32040
  // src/proxy/plugins/loader.ts
31380
- import { readdirSync as readdirSync2, readFileSync as readFileSync4, existsSync as existsSync5 } from "fs";
32041
+ import { readdirSync as readdirSync2, readFileSync as readFileSync5, existsSync as existsSync5 } from "fs";
31381
32042
  import { join as join7, isAbsolute as isAbsolute3, extname } from "path";
31382
32043
  import { pathToFileURL } from "url";
31383
32044
 
@@ -31423,7 +32084,7 @@ function parsePluginConfig(configPath) {
31423
32084
  if (!existsSync5(configPath))
31424
32085
  return [];
31425
32086
  try {
31426
- const raw2 = readFileSync4(configPath, "utf-8");
32087
+ const raw2 = readFileSync5(configPath, "utf-8");
31427
32088
  const parsed = JSON.parse(raw2);
31428
32089
  return Array.isArray(parsed.plugins) ? parsed.plugins : [];
31429
32090
  } catch {
@@ -31658,7 +32319,7 @@ function formatUsageSummary(usage) {
31658
32319
 
31659
32320
  // src/proxy/session/lineage.ts
31660
32321
  init_messages();
31661
- import { createHash as createHash3 } from "crypto";
32322
+ import { createHash as createHash5 } from "crypto";
31662
32323
  function normalizeContextUsage(usage) {
31663
32324
  const lastIteration = usage.iterations?.at(-1);
31664
32325
  return lastIteration ?? usage;
@@ -31712,7 +32373,7 @@ function semanticContent(content) {
31712
32373
  return hashableContentBlocks(content).map(semanticBlock);
31713
32374
  }
31714
32375
  function lineageDigest(domain2, value) {
31715
- return createHash3("sha256").update(JSON.stringify(["meridian-lineage-v2", domain2, value])).digest("hex").slice(0, 32);
32376
+ return createHash5("sha256").update(JSON.stringify(["meridian-lineage-v2", domain2, value])).digest("hex").slice(0, 32);
31716
32377
  }
31717
32378
  function computeLineageHash(messages) {
31718
32379
  if (!messages || messages.length === 0)
@@ -31752,13 +32413,30 @@ function describeLineageMismatch(cached2, messages, precomputedIncomingHashes) {
31752
32413
  };
31753
32414
  if (index < 0)
31754
32415
  return base;
32416
+ const storedBlocks = cached2.messageBlockHashes?.[index];
32417
+ const incomingMessage = messages[index];
32418
+ const incomingBlocks = incomingMessage ? computeMessageBlockHashes([incomingMessage])[0] : undefined;
31755
32419
  return {
31756
32420
  ...base,
31757
32421
  storedDigest: storedHashes[index],
31758
32422
  incomingDigest: incomingHashes[index],
31759
- incomingShape: messages[index] ? describeShape(messages[index]) : undefined,
31760
- previousDigest: index > 0 ? storedHashes[index - 1] : undefined
31761
- };
32423
+ incomingShape: incomingMessage ? describeShape(incomingMessage) : undefined,
32424
+ previousDigest: index > 0 ? storedHashes[index - 1] : undefined,
32425
+ storedBlockCount: storedBlocks?.length,
32426
+ incomingBlockCount: incomingBlocks?.length,
32427
+ blockChange: classifyBlockChange(storedBlocks, incomingBlocks)
32428
+ };
32429
+ }
32430
+ function classifyBlockChange(stored, incoming) {
32431
+ if (!stored || !incoming)
32432
+ return "unknown";
32433
+ const isPrefix = (short, long) => short.every((hash2, i) => long[i] === hash2);
32434
+ if (incoming.length > stored.length)
32435
+ return isPrefix(stored, incoming) ? "appended" : "rewritten";
32436
+ if (incoming.length < stored.length)
32437
+ return isPrefix(incoming, stored) ? "dropped" : "rewritten";
32438
+ const same = [...stored].sort().join() === [...incoming].sort().join();
32439
+ return same ? "reordered" : "rewritten";
31762
32440
  }
31763
32441
  function formatLineageMismatch(mismatch) {
31764
32442
  if (mismatch.index < 0)
@@ -31766,7 +32444,24 @@ function formatLineageMismatch(mismatch) {
31766
32444
  const short = (digest) => digest ? digest.slice(0, 12) : "—";
31767
32445
  const trailing = mismatch.index === mismatch.storedCount - 1 ? " (trailing message only — the rest of the history matched)" : "";
31768
32446
  const shape = mismatch.incomingShape ? `${mismatch.incomingShape.role}[${mismatch.incomingShape.blocks}] ${mismatch.incomingShape.bytes}B` : "unknown";
31769
- return `first mismatch at index ${mismatch.index}${trailing}: ` + `stored=${short(mismatch.storedDigest)} incoming=${short(mismatch.incomingDigest)}, ` + `incoming now ${shape}`;
32447
+ const blocks = mismatch.storedBlockCount !== undefined && mismatch.incomingBlockCount !== undefined ? `, stored ${mismatch.storedBlockCount} blocks -> incoming ${mismatch.incomingBlockCount} blocks` + (mismatch.blockChange && mismatch.blockChange !== "unknown" ? ` (${mismatch.blockChange})` : "") : ", stored block hashes unavailable (session cached before 1.61.0)";
32448
+ return `first mismatch at index ${mismatch.index}${trailing}: ` + `stored=${short(mismatch.storedDigest)} incoming=${short(mismatch.incomingDigest)}, ` + `incoming now ${shape}${blocks}`;
32449
+ }
32450
+ function independentRequestCause(input) {
32451
+ if (!input.hasSessionKey && input.forkSource)
32452
+ return "fork-source";
32453
+ if (!input.hasSessionKey && input.isSubagent)
32454
+ return "subagent";
32455
+ if (input.clientDrivenLoop)
32456
+ return "headerless-tool-result";
32457
+ if (!input.hasDurableKey)
32458
+ return "no-cache-identity";
32459
+ return;
32460
+ }
32461
+ function formatDivergence(result, cause) {
32462
+ if (result.type !== "diverged")
32463
+ return;
32464
+ return result.reason === "independent-request" && cause ? `${result.reason}:${cause}` : result.reason;
31770
32465
  }
31771
32466
  function computeMessageHashes(messages) {
31772
32467
  if (!messages || messages.length === 0)
@@ -31941,7 +32636,7 @@ import {
31941
32636
  unlinkSync,
31942
32637
  writeFileSync as writeFileSync2
31943
32638
  } from "node:fs";
31944
- import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";
32639
+ import { createHash as createHash7, randomUUID as randomUUID2 } from "node:crypto";
31945
32640
  import { homedir as homedir7, hostname as hostname4 } from "node:os";
31946
32641
  import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join8 } from "node:path";
31947
32642
 
@@ -32007,290 +32702,8 @@ function directoryRenameWasBlockedSync(error51, destination) {
32007
32702
  }
32008
32703
 
32009
32704
  // src/proxy/session/recoveryClaim.ts
32010
- import { createHash as createHash5, randomUUID } from "node:crypto";
32705
+ import { createHash as createHash6, randomUUID } from "node:crypto";
32011
32706
  import { hostname as hostname3 } from "node:os";
32012
-
32013
- // src/proxy/session/processIncarnation.ts
32014
- import { spawnSync } from "node:child_process";
32015
- import { createHash as createHash4 } from "node:crypto";
32016
- import { readFileSync as readFileSync5, readlinkSync as readlinkSync2 } from "node:fs";
32017
- var PROCESS_INCARNATION_VERSION = 1;
32018
- var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
32019
- var SHA256_PATTERN = /^[0-9a-f]{64}$/;
32020
- var LINUX_START_PATTERN = /^[1-9][0-9]{0,31}$/;
32021
- var WINDOWS_START_PATTERN = /^[1-9][0-9]{0,31}$/;
32022
- var DARWIN_START_PATTERN = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-6][0-9] [0-9]{4}$/;
32023
- var PROBE_TIMEOUT_MS = 2000;
32024
- var WINDOWS_PROBE_TIMEOUT_MS = 1e4;
32025
- var cachedLocalBootIdentity;
32026
- var cachedCurrentProcessIncarnation;
32027
- function hashIdentity(value) {
32028
- return createHash4("sha256").update(value).digest("hex");
32029
- }
32030
- function isPositivePid(value) {
32031
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
32032
- }
32033
- function validStartId(kind, value) {
32034
- if (typeof value !== "string")
32035
- return false;
32036
- if (kind === "linux-proc-start-ticks")
32037
- return LINUX_START_PATTERN.test(value);
32038
- if (kind === "darwin-ps-lstart")
32039
- return DARWIN_START_PATTERN.test(value);
32040
- if (kind === "windows-start-ticks")
32041
- return WINDOWS_START_PATTERN.test(value);
32042
- return false;
32043
- }
32044
- function parseProcessIncarnation(value) {
32045
- if (typeof value !== "object" || value === null || Array.isArray(value))
32046
- return;
32047
- const identity = value;
32048
- if (identity.version !== PROCESS_INCARNATION_VERSION || !isPositivePid(identity.pid) || typeof identity.hostId !== "string" || !SHA256_PATTERN.test(identity.hostId) || typeof identity.bootId !== "string" || !UUID_PATTERN.test(identity.bootId) || typeof identity.startId !== "string" || !validStartId(identity.startIdKind, identity.startId))
32049
- return;
32050
- return {
32051
- version: PROCESS_INCARNATION_VERSION,
32052
- pid: identity.pid,
32053
- hostId: identity.hostId,
32054
- bootId: identity.bootId,
32055
- startId: identity.startId,
32056
- startIdKind: identity.startIdKind
32057
- };
32058
- }
32059
- function evaluateProcessIncarnation(owner, localBoot, observedStart) {
32060
- const parsedOwner = parseProcessIncarnation(owner);
32061
- if (!parsedOwner || !localBoot || !SHA256_PATTERN.test(localBoot.hostId) || !UUID_PATTERN.test(localBoot.bootId) || parsedOwner.hostId !== localBoot.hostId)
32062
- return "indeterminate";
32063
- if (parsedOwner.bootId !== localBoot.bootId)
32064
- return "dead";
32065
- if (!observedStart || observedStart.status === "indeterminate")
32066
- return "indeterminate";
32067
- if (observedStart.status === "missing")
32068
- return "dead";
32069
- if (!validStartId(observedStart.startIdKind, observedStart.startId) || observedStart.startIdKind !== parsedOwner.startIdKind)
32070
- return "indeterminate";
32071
- if (observedStart.startId !== parsedOwner.startId)
32072
- return "dead";
32073
- return parsedOwner.startIdKind === "linux-proc-start-ticks" ? "alive" : "indeterminate";
32074
- }
32075
- function normalizeUuid(raw2) {
32076
- const value = raw2.trim().toLowerCase();
32077
- return UUID_PATTERN.test(value) ? value : undefined;
32078
- }
32079
- function readFirst(paths) {
32080
- for (const path3 of paths) {
32081
- try {
32082
- const value = readFileSync5(path3, "utf8").trim();
32083
- if (value)
32084
- return value;
32085
- } catch {}
32086
- }
32087
- return;
32088
- }
32089
- function linuxLocalBootIdentity() {
32090
- const machineId = readFirst(["/etc/machine-id", "/var/lib/dbus/machine-id"]);
32091
- const bootId = normalizeUuid(readFileSync5("/proc/sys/kernel/random/boot_id", "utf8"));
32092
- const pidNamespace = readlinkSync2("/proc/self/ns/pid");
32093
- if (!machineId || !/^[0-9a-fA-F]{32}$/.test(machineId) || !bootId || !/^pid:\[[0-9]+\]$/.test(pidNamespace)) {
32094
- return;
32095
- }
32096
- return {
32097
- hostId: hashIdentity(`linux:${machineId.toLowerCase()}:${pidNamespace}`),
32098
- bootId
32099
- };
32100
- }
32101
- function runDarwin(command, args) {
32102
- const result = spawnSync(command, args, {
32103
- encoding: "utf8",
32104
- env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC0" },
32105
- timeout: PROBE_TIMEOUT_MS,
32106
- maxBuffer: 1024 * 1024
32107
- });
32108
- if (result.error || result.status !== 0 || typeof result.stdout !== "string")
32109
- return;
32110
- return result.stdout;
32111
- }
32112
- function darwinLocalBootIdentity() {
32113
- const ioreg = runDarwin("/usr/sbin/ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"]);
32114
- const boot = runDarwin("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"]);
32115
- const machineMatch = ioreg?.match(/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]+)"/);
32116
- const machineId = machineMatch?.[1] ? normalizeUuid(machineMatch[1]) : undefined;
32117
- const bootId = boot ? normalizeUuid(boot) : undefined;
32118
- if (!machineId || !bootId)
32119
- return;
32120
- return {
32121
- hostId: hashIdentity(`darwin:${machineId}`),
32122
- bootId
32123
- };
32124
- }
32125
- function uuidFromIdentity(value) {
32126
- const hex3 = createHash4("sha256").update(value).digest("hex").slice(0, 32);
32127
- return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
32128
- }
32129
- function runWindowsPowerShell(script) {
32130
- const result = spawnSync("powershell.exe", [
32131
- "-NoLogo",
32132
- "-NoProfile",
32133
- "-NonInteractive",
32134
- "-ExecutionPolicy",
32135
- "Bypass",
32136
- "-Command",
32137
- script
32138
- ], {
32139
- encoding: "utf8",
32140
- windowsHide: true,
32141
- timeout: WINDOWS_PROBE_TIMEOUT_MS,
32142
- maxBuffer: 1024 * 1024
32143
- });
32144
- return {
32145
- status: result.error ? null : result.status,
32146
- ...typeof result.stdout === "string" ? { stdout: result.stdout } : {}
32147
- };
32148
- }
32149
- function windowsLocalBootIdentity() {
32150
- const result = runWindowsPowerShell(String.raw`
32151
- $ErrorActionPreference = 'Stop'
32152
- $machine = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Cryptography' -Name MachineGuid).MachineGuid
32153
- try { $boot = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime }
32154
- catch { $boot = (Get-WmiObject Win32_OperatingSystem).ConvertToDateTime((Get-WmiObject Win32_OperatingSystem).LastBootUpTime) }
32155
- Write-Output $machine
32156
- Write-Output $boot.ToUniversalTime().Ticks
32157
- `);
32158
- if (result.status !== 0 || !result.stdout)
32159
- return;
32160
- const [machine, bootTicks] = result.stdout.trim().split(/\r?\n/).map((part) => part.trim());
32161
- if (!machine || !bootTicks || !WINDOWS_START_PATTERN.test(bootTicks))
32162
- return;
32163
- return {
32164
- hostId: hashIdentity(`windows:${machine.toLowerCase()}`),
32165
- bootId: uuidFromIdentity(`windows-boot:${machine.toLowerCase()}:${bootTicks}`)
32166
- };
32167
- }
32168
- function getLocalBootIdentity() {
32169
- if (cachedLocalBootIdentity)
32170
- return cachedLocalBootIdentity;
32171
- try {
32172
- const identity = process.platform === "linux" ? linuxLocalBootIdentity() : process.platform === "darwin" ? darwinLocalBootIdentity() : process.platform === "win32" ? windowsLocalBootIdentity() : undefined;
32173
- if (identity)
32174
- cachedLocalBootIdentity = identity;
32175
- return identity;
32176
- } catch {
32177
- return;
32178
- }
32179
- }
32180
- function pidPresence(pid) {
32181
- try {
32182
- process.kill(pid, 0);
32183
- return "present";
32184
- } catch (error51) {
32185
- const code = error51 instanceof Error && "code" in error51 ? error51.code : undefined;
32186
- return code === "ESRCH" ? "missing" : "indeterminate";
32187
- }
32188
- }
32189
- function parseLinuxProcStatStartId(raw2, expectedPid) {
32190
- const prefix = `${expectedPid} (`;
32191
- if (!raw2.startsWith(prefix))
32192
- return;
32193
- const commEnd = raw2.lastIndexOf(")");
32194
- if (commEnd < prefix.length || raw2[commEnd + 1] !== " ")
32195
- return;
32196
- const fieldsFromState = raw2.slice(commEnd + 2).trim().split(/\s+/);
32197
- const startId = fieldsFromState[19];
32198
- return startId && LINUX_START_PATTERN.test(startId) ? startId : undefined;
32199
- }
32200
- function linuxProcessStart(pid) {
32201
- let raw2;
32202
- try {
32203
- raw2 = readFileSync5(`/proc/${pid}/stat`, "utf8");
32204
- } catch (error51) {
32205
- const code = error51 instanceof Error && "code" in error51 ? error51.code : undefined;
32206
- if (code === "ENOENT" || code === "ESRCH")
32207
- return { status: "missing" };
32208
- return { status: "indeterminate" };
32209
- }
32210
- const startId = parseLinuxProcStatStartId(raw2, pid);
32211
- if (startId)
32212
- return { status: "found", startId, startIdKind: "linux-proc-start-ticks" };
32213
- return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
32214
- }
32215
- function darwinProcessStart(pid) {
32216
- const output = runDarwin("/bin/ps", ["-p", String(pid), "-o", "lstart="]);
32217
- if (output !== undefined) {
32218
- const startId = output.trimEnd().trimStart();
32219
- if (DARWIN_START_PATTERN.test(startId)) {
32220
- return { status: "found", startId, startIdKind: "darwin-ps-lstart" };
32221
- }
32222
- }
32223
- return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
32224
- }
32225
- function windowsProcessStart(pid) {
32226
- const result = runWindowsPowerShell(String.raw`
32227
- $ErrorActionPreference = 'Stop'
32228
- try {
32229
- $process = Get-Process -Id ${pid} -ErrorAction Stop
32230
- Write-Output $process.StartTime.ToUniversalTime().Ticks
32231
- } catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
32232
- exit 3
32233
- } catch {
32234
- exit 4
32235
- }
32236
- `);
32237
- const startId = result.stdout?.trim();
32238
- if (result.status === 0 && startId && WINDOWS_START_PATTERN.test(startId)) {
32239
- return { status: "found", startId, startIdKind: "windows-start-ticks" };
32240
- }
32241
- if (result.status === 3)
32242
- return { status: "missing" };
32243
- return pidPresence(pid) === "missing" ? { status: "missing" } : { status: "indeterminate" };
32244
- }
32245
- function observeProcessStart(pid) {
32246
- if (process.platform === "linux")
32247
- return linuxProcessStart(pid);
32248
- if (process.platform === "darwin")
32249
- return darwinProcessStart(pid);
32250
- if (process.platform === "win32")
32251
- return windowsProcessStart(pid);
32252
- return { status: "indeterminate" };
32253
- }
32254
- function captureProcessIncarnation(pid = process.pid) {
32255
- if (!isPositivePid(pid))
32256
- return;
32257
- if (pid === process.pid && cachedCurrentProcessIncarnation) {
32258
- return { ...cachedCurrentProcessIncarnation };
32259
- }
32260
- const localBoot = getLocalBootIdentity();
32261
- if (!localBoot)
32262
- return;
32263
- const start = observeProcessStart(pid);
32264
- if (start.status !== "found")
32265
- return;
32266
- const identity = {
32267
- version: PROCESS_INCARNATION_VERSION,
32268
- pid,
32269
- ...localBoot,
32270
- startId: start.startId,
32271
- startIdKind: start.startIdKind
32272
- };
32273
- if (pid === process.pid)
32274
- cachedCurrentProcessIncarnation = identity;
32275
- return { ...identity };
32276
- }
32277
- function probeProcessIncarnation(owner) {
32278
- const parsed = parseProcessIncarnation(owner);
32279
- if (!parsed)
32280
- return "indeterminate";
32281
- const localBoot = getLocalBootIdentity();
32282
- if (!localBoot || parsed.hostId !== localBoot.hostId)
32283
- return "indeterminate";
32284
- if (parsed.bootId !== localBoot.bootId) {
32285
- return evaluateProcessIncarnation(parsed, localBoot, undefined);
32286
- }
32287
- return evaluateProcessIncarnation(parsed, localBoot, observeProcessStart(parsed.pid));
32288
- }
32289
- function processIncarnationIsDead(owner) {
32290
- return probeProcessIncarnation(owner) === "dead";
32291
- }
32292
-
32293
- // src/proxy/session/recoveryClaim.ts
32294
32707
  var RECOVERY_CLAIM_VERSION = 2;
32295
32708
  function createRecoveryClaimOwner(generation) {
32296
32709
  if (!generation)
@@ -32336,11 +32749,11 @@ function recoveryClaimOwnerIsDead(owner, probe = processIncarnationIsDead) {
32336
32749
  return probe(owner.incarnation);
32337
32750
  }
32338
32751
  function getRecoveryClaimPath(lockPath, generation) {
32339
- const digest = createHash5("sha256").update(generation).digest("hex");
32752
+ const digest = createHash6("sha256").update(generation).digest("hex");
32340
32753
  return `${lockPath}.recover-${digest}`;
32341
32754
  }
32342
32755
  function getRecoveryClaimTombstonePath(claimPath, claimToken) {
32343
- const digest = createHash5("sha256").update(claimToken).digest("hex");
32756
+ const digest = createHash6("sha256").update(claimToken).digest("hex");
32344
32757
  return `${claimPath}.orphan-${digest}`;
32345
32758
  }
32346
32759
 
@@ -32349,7 +32762,7 @@ var STORE_META_KEY = "\x00meridian-session-store";
32349
32762
  var STORE_META_VERSION = 1;
32350
32763
  var PRIORITY_STORE_META_VERSION = 3;
32351
32764
  function keyDigest(key) {
32352
- return createHash6("sha256").update(key).digest("hex");
32765
+ return createHash7("sha256").update(key).digest("hex");
32353
32766
  }
32354
32767
  function keySlot(key) {
32355
32768
  return keyDigest(key).slice(0, 4);
@@ -32358,7 +32771,7 @@ function absenceGeneration(key, meta3) {
32358
32771
  return `a:${keyDigest(key)}:${meta3.slots[keySlot(key)] ?? 0}`;
32359
32772
  }
32360
32773
  function getStoredSessionGeneration(session, key) {
32361
- const generationId = session.generationId ?? `legacy-${createHash6("sha256").update(JSON.stringify(session)).digest("hex")}`;
32774
+ const generationId = session.generationId ?? `legacy-${createHash7("sha256").update(JSON.stringify(session)).digest("hex")}`;
32362
32775
  return `p:${keyDigest(key)}:${generationId}`;
32363
32776
  }
32364
32777
  function keyGeneration(key, session, meta3) {
@@ -33878,9 +34291,31 @@ function classifyLineage(state, messages, cacheKey2) {
33878
34291
  ${detail}` : "");
33879
34292
  console.error(`[PROXY] ${msg}`);
33880
34293
  diagnosticLog2.lineage(msg);
34294
+ } else if (result.type === "diverged") {
34295
+ const msg = `Session not resumable (key=${cacheKey2.slice(0, 8)}…): reason=${result.reason}, prefix overlap ${result.prefixOverlap || 0}/${state.messageCount}, incoming ${messages.length} msgs. Starting fresh replay.`;
34296
+ console.error(`[PROXY] ${msg}`);
34297
+ diagnosticLog2.lineage(msg);
33881
34298
  }
33882
34299
  return result;
33883
34300
  }
34301
+ var warnedDegradedFingerprint = false;
34302
+ function warnDegradedFingerprintOnce() {
34303
+ if (warnedDegradedFingerprint)
34304
+ return;
34305
+ warnedDegradedFingerprint = true;
34306
+ const msg = "[PROXY] Session fingerprint has no working directory, so it hashes only the opening " + "user message — two conversations in different directories that start with the same text " + "will share a session. The directory is read from the <env> block of the system prompt; a " + "plugin implementing experimental.chat.system.transform (for example opencode-scrub) may " + "have removed it. Send a session header (meridian setup) to key conversations explicitly.";
34307
+ console.warn(msg);
34308
+ diagnosticLog2.lineage(msg);
34309
+ }
34310
+ var warnedHeaderlessToolLoop = false;
34311
+ function warnHeaderlessToolLoopOnce(adapterName) {
34312
+ if (warnedHeaderlessToolLoop)
34313
+ return;
34314
+ warnedHeaderlessToolLoop = true;
34315
+ const msg = `[PROXY] Client-driven tool loop with no session identity (adapter=${adapterName}): ` + "the request ends in a tool_result and carries no session key, so this and every " + "following tool round starts a fresh SDK session. The conversation does not resume, " + "and the model sees none of its own earlier turns. This is correct for concurrent " + "headless workflow loops, which must not share one conversation fingerprint; an " + 'interactive client should send a session header instead — see "Session identity" ' + "in docs/configuration.md.";
34316
+ console.warn(msg);
34317
+ diagnosticLog2.lineage(msg);
34318
+ }
33884
34319
  function lookupSession(sessionId, messages, workingDirectory) {
33885
34320
  if (sessionId) {
33886
34321
  const shared = lookupSharedSessionResult(sessionId);
@@ -33901,6 +34336,8 @@ function lookupSession(sessionId, messages, workingDirectory) {
33901
34336
  }
33902
34337
  return result;
33903
34338
  }
34339
+ if (!workingDirectory)
34340
+ warnDegradedFingerprintOnce();
33904
34341
  const fp = getConversationFingerprint(messages, workingDirectory);
33905
34342
  if (fp) {
33906
34343
  const shared = lookupSharedSessionResult(fp);
@@ -34115,7 +34552,7 @@ class SessionTurnCoordinator {
34115
34552
  var processSessionTurns = new SessionTurnCoordinator;
34116
34553
 
34117
34554
  // src/proxy/session/crossProcessTurnCoordinator.ts
34118
- import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";
34555
+ import { createHash as createHash8, randomUUID as randomUUID3 } from "node:crypto";
34119
34556
  import { hostname as hostname5 } from "node:os";
34120
34557
  import { basename as basename2, dirname as dirname7, join as join9 } from "node:path";
34121
34558
  import {
@@ -34167,7 +34604,7 @@ function heartbeatName(token) {
34167
34604
  return `heartbeat-${token}`;
34168
34605
  }
34169
34606
  function lockName(key) {
34170
- return `${createHash7("sha256").update(key).digest("hex")}.lock`;
34607
+ return `${createHash8("sha256").update(key).digest("hex")}.lock`;
34171
34608
  }
34172
34609
  async function readOwner(lockPath) {
34173
34610
  let raw2;
@@ -34592,7 +35029,7 @@ class CrossProcessTurnCoordinator {
34592
35029
  }
34593
35030
 
34594
35031
  // src/proxy/sessionLifecycle.ts
34595
- import { createHash as createHash8, randomUUID as randomUUID4 } from "node:crypto";
35032
+ import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";
34596
35033
  import { spawn } from "node:child_process";
34597
35034
  import { realpathSync as realpathSync2 } from "node:fs";
34598
35035
  import {
@@ -34637,7 +35074,7 @@ class SessionLifecycleBacklogError extends SessionLifecycleError {
34637
35074
  }
34638
35075
  function getTranscriptResourceKey(locator) {
34639
35076
  validateLocator(locator);
34640
- return createHash8("sha256").update(locator.configDir).update("\x00").update(locator.sessionId).digest("hex");
35077
+ return createHash9("sha256").update(locator.configDir).update("\x00").update(locator.sessionId).digest("hex");
34641
35078
  }
34642
35079
  function physicalLocator(locator) {
34643
35080
  const { lifecycleGeneration: _generation, ...physical } = locator;
@@ -36400,6 +36837,7 @@ function createProxyServer(config2 = {}) {
36400
36837
  const sessionDiscoveredTools = new LRUMap(getMaxSessionsLimit());
36401
36838
  const sessionToolCache = new LRUMap(getMaxSessionsLimit());
36402
36839
  const sessionMcpCache = new LRUMap(getMaxSessionsLimit());
36840
+ const sessionDeferPin = new LRUMap(getMaxSessionsLimit());
36403
36841
  const idleStalls = new IdleStallTracker(UPSTREAM_IDLE_MAX_CONSECUTIVE, getMaxSessionsLimit());
36404
36842
  const RESUME_REFUSAL_MAX_RETRIES = 3;
36405
36843
  const RESUME_REFUSAL_RETRY_DELAY_MS = parseInt(process.env.MERIDIAN_BUSY_RETRY_DELAY_MS ?? "500", 10);
@@ -37033,6 +37471,8 @@ data: ${JSON.stringify(lastError)}
37033
37471
  return textPrompt;
37034
37472
  };
37035
37473
  const body = options.body;
37474
+ const rawMaxTokens = Number(body?.max_tokens);
37475
+ const clientMaxOutputTokens = envBool("ENFORCE_MAX_TOKENS") && Number.isFinite(rawMaxTokens) && rawMaxTokens > 0 ? Math.floor(rawMaxTokens) : undefined;
37036
37476
  const idleRequestKey = idleStallRequestKey(body);
37037
37477
  const markPriorityAttemptExposure = (reason) => {
37038
37478
  const exposure = options.priorityAttemptExposure;
@@ -37199,7 +37639,7 @@ data: ${JSON.stringify(lastError)}
37199
37639
  resolvedProfileId = profile.id;
37200
37640
  const authStatus = await getClaudeAuthStatusAsync(profile.id !== "default" ? profile.id : undefined, Object.keys(profile.env).length > 0 ? profile.env : undefined);
37201
37641
  const requestSource = c.req.header("x-meridian-source")?.slice(0, 64) || undefined;
37202
- const declaredAgentMode = adapter.getAgentMode?.(c, body) ?? c.req.header("x-opencode-agent-mode") ?? null;
37642
+ const declaredAgentMode = adapter.getAgentMode?.(c, body) ?? (adapter.baseName === "polytoken" || adapter.name === "polytoken" ? undefined : c.req.header("x-opencode-agent-mode")) ?? null;
37203
37643
  const isSubagentRequest = declaredAgentMode === "subagent" || requestSource?.startsWith("subagent-") === true;
37204
37644
  const agentMode = isSubagentRequest ? "subagent" : declaredAgentMode;
37205
37645
  const requestedModel = typeof body.model === "string" ? body.model : "sonnet";
@@ -37250,9 +37690,10 @@ data: ${JSON.stringify(lastError)}
37250
37690
  workingDirectory
37251
37691
  }), adapterBase);
37252
37692
  const stream3 = pipelineCtx.prefersStreaming !== undefined ? pipelineCtx.prefersStreaming : body.stream ?? false;
37253
- const effortHeader = c.req.header("x-opencode-effort");
37254
- const thinkingHeader = c.req.header("x-opencode-thinking");
37255
- const taskBudgetHeader = c.req.header("x-opencode-task-budget");
37693
+ const isPolytokenBase = adapterBase === "polytoken";
37694
+ const effortHeader = isPolytokenBase ? undefined : c.req.header("x-opencode-effort");
37695
+ const thinkingHeader = isPolytokenBase ? undefined : c.req.header("x-opencode-thinking");
37696
+ const taskBudgetHeader = isPolytokenBase ? undefined : c.req.header("x-opencode-task-budget");
37256
37697
  const rawBetaHeader = c.req.header("anthropic-beta");
37257
37698
  const betaFilter = filterBetasForProfile(rawBetaHeader, profile.type, getBetaPolicyFromEnv());
37258
37699
  if (betaFilter.stripped.length > 0) {
@@ -37361,11 +37802,19 @@ data: ${JSON.stringify(lastError)}
37361
37802
  const profileScopedCwd = profile.id !== "default" ? `${clientWorkingDirectory}::profile=${profile.id}` : clientWorkingDirectory;
37362
37803
  const lastMessage = Array.isArray(body.messages) ? body.messages[body.messages.length - 1] : undefined;
37363
37804
  const lastIsToolResult = Array.isArray(lastMessage?.content) && lastMessage.content.some((b) => b?.type === "tool_result");
37364
- const isClientDrivenLoop = adapterBase !== "claude-code" && !agentSessionId && lastIsToolResult;
37365
- let isIndependentSession = !agentSessionId && (requestSource?.startsWith("fork-") || isSubagentRequest) || isClientDrivenLoop || false;
37805
+ const ownsToolLoopWithResume = adapterBase === "claude-code" || isClaudeCodeClient(c);
37806
+ const isClientDrivenLoop = !ownsToolLoopWithResume && !agentSessionId && lastIsToolResult;
37366
37807
  const durableMappingKey = profileSessionId || getConversationFingerprint(lineageMessages, profileScopedCwd);
37367
- if (!durableMappingKey)
37368
- isIndependentSession = true;
37808
+ const independentCause = independentRequestCause({
37809
+ hasSessionKey: Boolean(agentSessionId),
37810
+ forkSource: Boolean(requestSource?.startsWith("fork-")),
37811
+ isSubagent: isSubagentRequest,
37812
+ clientDrivenLoop: isClientDrivenLoop,
37813
+ hasDurableKey: Boolean(durableMappingKey)
37814
+ });
37815
+ const isIndependentSession = independentCause !== undefined;
37816
+ if (independentCause === "headerless-tool-result")
37817
+ warnHeaderlessToolLoopOnce(adapter.name);
37369
37818
  const durableMappingAtTurn = durableMappingKey ? lookupSharedSessionResult(durableMappingKey) : { status: "missing" };
37370
37819
  if (durableMappingAtTurn.status === "error") {
37371
37820
  throw new Error(`Shared session store is unavailable: ${durableMappingAtTurn.error.message}`);
@@ -37399,7 +37848,7 @@ data: ${JSON.stringify(lastError)}
37399
37848
  const trailingSystemReminderOptions = adapterBase === "claude-code" ? { allowTrailingSystemReminder: true } : undefined;
37400
37849
  const durableCheckpointContinuation = durableCheckpointIds?.length && durableMappingAtTurn.status === "found" && matchesStoredLineagePrefix(durableMappingAtTurn.session, lineageMessages) ? coalesceCompleteToolResultContinuation((body.messages || []).slice(durableMappingAtTurn.session.messageCount), durableCheckpointIds, trailingSystemReminderOptions) : undefined;
37401
37850
  const advancesDurableCheckpoint = Boolean(durableCheckpointContinuation);
37402
- const passthrough = adapter.instancePassthrough !== undefined ? adapter.instancePassthrough : pipelineCtx.passthrough !== undefined ? pipelineCtx.passthrough : envBool("PASSTHROUGH");
37851
+ const passthrough = adapterBase === "polytoken" ? true : adapter.instancePassthrough !== undefined ? adapter.instancePassthrough : pipelineCtx.passthrough !== undefined ? pipelineCtx.passthrough : envBool("PASSTHROUGH");
37403
37852
  if (advancesDurableCheckpoint && lineageResult.type !== "continuation" && lineageResult.type !== "compaction" && durableMappingAtTurn.status === "found") {
37404
37853
  const checkpointSession = getSessionByClaudeId(durableMappingAtTurn.session.claudeSessionId);
37405
37854
  if (checkpointSession) {
@@ -37525,10 +37974,11 @@ data: ${JSON.stringify(lastError)}
37525
37974
  return `${m.role}[${contentTypes}]`;
37526
37975
  }).join(" → ");
37527
37976
  const lineageType = lineageResult.type === "diverged" && !cachedSession ? "new" : lineageResult.type;
37977
+ const divergedReason = formatDivergence(lineageResult, independentCause);
37528
37978
  const msgCount = Array.isArray(body.messages) ? body.messages.length : 0;
37529
37979
  const toolCount = body.tools?.length ?? 0;
37530
37980
  const sdkSnapshot = sdkSemaphore.snapshot;
37531
- const requestLogLine = `${requestMeta.requestId} adapter=${adapter.name}${requestSource ? ` source=${requestSource}` : ""}${profile.id !== "default" ? ` profile=${profile.id}${routingMode === "sticky" ? "(sticky)" : options.forcedProfileId ? "(priority)" : ""}` : ""} model=${model} stream=${stream3} tools=${toolCount} lineage=${lineageType} session=${resumeSessionId?.slice(0, 8) || "new"}${isUndo && undoRollbackUuid ? ` rollback=${undoRollbackUuid.slice(0, 8)}` : ""}${agentMode ? ` agent=${agentMode}` : ""} sdkActive=${sdkSnapshot.active}/${sdkSnapshot.limit} sdkQueued=${sdkSnapshot.queued} sessionWait=${requestMeta.sessionQueueWaitMs}ms msgCount=${msgCount}`;
37981
+ const requestLogLine = `${requestMeta.requestId} adapter=${adapter.name}${requestSource ? ` source=${requestSource}` : ""}${profile.id !== "default" ? ` profile=${profile.id}${routingMode === "sticky" ? "(sticky)" : options.forcedProfileId ? "(priority)" : ""}` : ""} model=${model} stream=${stream3} tools=${toolCount} lineage=${lineageType} session=${resumeSessionId?.slice(0, 8) || "new"}${isUndo && undoRollbackUuid ? ` rollback=${undoRollbackUuid.slice(0, 8)}` : ""}${divergedReason ? ` diverged=${divergedReason}` : ""}${agentMode ? ` agent=${agentMode}` : ""} sdkActive=${sdkSnapshot.active}/${sdkSnapshot.limit} sdkQueued=${sdkSnapshot.queued} sessionWait=${requestMeta.sessionQueueWaitMs}ms msgCount=${msgCount}`;
37532
37982
  plog(`[PROXY] ${requestLogLine} msgs=${msgSummary}`);
37533
37983
  diagnosticLog2.session(`${requestLogLine}`, requestMeta.requestId);
37534
37984
  if (lineageResult.type === "diverged" && profileSessionId && !isIndependentSession) {
@@ -37775,13 +38225,22 @@ data: ${JSON.stringify(lastError)}
37775
38225
  plog(`[PROXY] ${requestMeta.requestId} tools_restored: client sent 0 tools but continued branch had ${cached2.tools.length} — reusing cached tools to preserve prompt cache`);
37776
38226
  }
37777
38227
  }
38228
+ const passthroughMcpName = adapter.getPassthroughMcpName?.() ?? PASSTHROUGH_MCP_NAME;
38229
+ const clientToolPrefix = passthroughMcpPrefix(passthroughMcpName);
37778
38230
  if (passthrough && requestTools.length > 0) {
37779
38231
  const toolSetKey = computeToolSetKey(requestTools);
37780
38232
  const cachedMcp = profileSessionId ? sessionMcpCache.get(profileSessionId) : undefined;
38233
+ const coreNamesForDefer = pipelineCtx.coreToolNames ? [...pipelineCtx.coreToolNames] : undefined;
38234
+ const pinnedDefer = profileSessionId ? sessionDeferPin.get(profileSessionId) : undefined;
38235
+ const liveDefer = autoDeferDecision(getAutoDeferThreshold(), coreNamesForDefer, requestTools.length);
38236
+ if (pinnedDefer !== undefined && pinnedDefer !== liveDefer) {
38237
+ plog(`[PROXY] ${requestMeta.requestId} defer_flip suppressed: session pinned autoDefer=${pinnedDefer}, live tool count ${requestTools.length} would give ${liveDefer}`);
38238
+ claudeLog("passthrough.defer_flip_suppressed", { pinned: pinnedDefer, live: liveDefer, toolCount: requestTools.length });
38239
+ }
37781
38240
  if (cachedMcp && cachedMcp.key === toolSetKey) {
37782
38241
  passthroughMcp = cachedMcp.mcp;
37783
38242
  } else {
37784
- passthroughMcp = createPassthroughMcpServer(requestTools, pipelineCtx.coreToolNames ? [...pipelineCtx.coreToolNames] : undefined);
38243
+ passthroughMcp = createPassthroughMcpServer(requestTools, coreNamesForDefer, passthroughMcpName, pinnedDefer);
37785
38244
  if (profileSessionId) {
37786
38245
  sessionMcpCache.set(profileSessionId, { key: toolSetKey, mcp: passthroughMcp });
37787
38246
  if (cachedMcp) {
@@ -37789,6 +38248,9 @@ data: ${JSON.stringify(lastError)}
37789
38248
  }
37790
38249
  }
37791
38250
  }
38251
+ if (profileSessionId && !sessionDeferPin.has(profileSessionId)) {
38252
+ sessionDeferPin.set(profileSessionId, passthroughMcp.hasDeferredTools);
38253
+ }
37792
38254
  }
37793
38255
  const hasDeferredTools = passthroughMcp?.hasDeferredTools ?? false;
37794
38256
  const coreNames = pipelineCtx.coreToolNames ? [...pipelineCtx.coreToolNames] : undefined;
@@ -37821,13 +38283,13 @@ data: ${JSON.stringify(lastError)}
37821
38283
  return {};
37822
38284
  }
37823
38285
  markPriorityAttemptExposure("tool_use");
37824
- const toolName = stripMcpPrefix(input.tool_name);
38286
+ const toolName = resolveClientToolName(input.tool_name, passthroughMcp?.clientNameByAlias, passthroughMcpName);
37825
38287
  if (hasDeferredTools && coreSet && !coreSet.has(toolName.toLowerCase())) {
37826
38288
  discoveredTools.add(toolName);
37827
38289
  }
37828
38290
  const clientTool = requestTools.find((t) => t.name === toolName);
37829
38291
  let toolInput = normalizeToolInput(input.tool_input, clientTool?.input_schema);
37830
- if (toolName.toLowerCase() === "task" && toolInput?.subagent_type && typeof toolInput.subagent_type === "string") {
38292
+ if (adapterBase !== "polytoken" && toolName.toLowerCase() === "task" && toolInput?.subagent_type && typeof toolInput.subagent_type === "string") {
37831
38293
  toolInput = { ...toolInput, subagent_type: resolveAgentAlias(toolInput.subagent_type, validAgentNames) };
37832
38294
  }
37833
38295
  const signature = toolUseSignature(toolName, toolInput);
@@ -38003,6 +38465,7 @@ data: ${JSON.stringify(lastError)}
38003
38465
  webFetchPreflight: sdkFeatures.webFetchPreflight,
38004
38466
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
38005
38467
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
38468
+ maxOutputTokens: clientMaxOutputTokens,
38006
38469
  fallbackModel: sdkFeatures.fallbackModel,
38007
38470
  sdkDebug: sdkFeatures.sdkDebug,
38008
38471
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -38102,6 +38565,7 @@ data: ${JSON.stringify(lastError)}
38102
38565
  webFetchPreflight: sdkFeatures.webFetchPreflight,
38103
38566
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
38104
38567
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
38568
+ maxOutputTokens: clientMaxOutputTokens,
38105
38569
  fallbackModel: sdkFeatures.fallbackModel,
38106
38570
  sdkDebug: sdkFeatures.sdkDebug,
38107
38571
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -38180,6 +38644,7 @@ data: ${JSON.stringify(lastError)}
38180
38644
  webFetchPreflight: sdkFeatures.webFetchPreflight,
38181
38645
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
38182
38646
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
38647
+ maxOutputTokens: clientMaxOutputTokens,
38183
38648
  fallbackModel: sdkFeatures.fallbackModel,
38184
38649
  sdkDebug: sdkFeatures.sdkDebug,
38185
38650
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -38251,7 +38716,7 @@ data: ${JSON.stringify(lastError)}
38251
38716
  let assistantAddedForwardedCall = false;
38252
38717
  if (passthrough && message.type === "assistant" && !earlyStopFired) {
38253
38718
  const expectedBefore = earlyStop.expected.size;
38254
- noteAssistantMessage(earlyStop, message);
38719
+ noteAssistantMessage(earlyStop, message, clientToolPrefix);
38255
38720
  assistantAddedForwardedCall = earlyStop.expected.size > expectedBefore;
38256
38721
  } else if (passthrough && message.type === "user" && !earlyStopFired) {
38257
38722
  noteUserContent(earlyStop, message.message?.content);
@@ -38284,7 +38749,7 @@ data: ${JSON.stringify(lastError)}
38284
38749
  turnGenerating = true;
38285
38750
  } else if (passthrough && eventType === "content_block_start") {
38286
38751
  const block = event.content_block;
38287
- if (isClientForwardedToolUse(block))
38752
+ if (isClientForwardedToolUse(block, clientToolPrefix))
38288
38753
  streamedToolUseIds.add(block.id);
38289
38754
  }
38290
38755
  }
@@ -38330,7 +38795,7 @@ data: ${JSON.stringify(lastError)}
38330
38795
  continue;
38331
38796
  }
38332
38797
  if (passthrough && b.type === "tool_use" && typeof b.name === "string") {
38333
- b.name = stripMcpPrefix(b.name);
38798
+ b.name = resolveClientToolName(b.name, passthroughMcp?.clientNameByAlias, passthroughMcpName);
38334
38799
  }
38335
38800
  contentBlocks.push(b);
38336
38801
  }
@@ -38424,6 +38889,16 @@ Subprocess stderr: ${stderrOutput}`;
38424
38889
  });
38425
38890
  if (lastUsage)
38426
38891
  logUsage(requestMeta.requestId, lastUsage);
38892
+ } else if (clientMaxOutputTokens && isOutputTokenCapExceeded(error51 instanceof Error ? error51.message : String(error51 ?? ""))) {
38893
+ lastStopReason = "max_tokens";
38894
+ claudeLog("upstream.output_cap_truncated", {
38895
+ mode: "non_stream",
38896
+ cap: clientMaxOutputTokens,
38897
+ blocks: contentBlocks.length
38898
+ });
38899
+ plog(`[PROXY] ${requestMeta.requestId} output capped at client max_tokens=${clientMaxOutputTokens} — reporting stop_reason=max_tokens`);
38900
+ if (lastUsage)
38901
+ logUsage(requestMeta.requestId, lastUsage);
38427
38902
  } else if (passthrough && sdkTerm.reason === "max_turns" && hasTruncatableText(contentBlocks)) {
38428
38903
  lastStopReason = "max_tokens";
38429
38904
  claudeLog("passthrough.capped_turn_truncated", {
@@ -38726,7 +39201,7 @@ data: ${JSON.stringify({
38726
39201
  try {
38727
39202
  const clientTool = requestTools.find((tool2) => tool2.name === buffered.name);
38728
39203
  const parsed = normalizeToolInput(JSON.parse(buffered.json), clientTool?.input_schema);
38729
- if (buffered.name.toLowerCase() === "task" && typeof parsed?.subagent_type === "string") {
39204
+ if (adapterBase !== "polytoken" && buffered.name.toLowerCase() === "task" && typeof parsed?.subagent_type === "string") {
38730
39205
  parsed.subagent_type = resolveAgentAlias(parsed.subagent_type, validAgentNames);
38731
39206
  }
38732
39207
  fixed = JSON.stringify(parsed);
@@ -38831,6 +39306,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
38831
39306
  webFetchPreflight: sdkFeatures.webFetchPreflight,
38832
39307
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
38833
39308
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
39309
+ maxOutputTokens: clientMaxOutputTokens,
38834
39310
  fallbackModel: sdkFeatures.fallbackModel,
38835
39311
  sdkDebug: sdkFeatures.sdkDebug,
38836
39312
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -38929,6 +39405,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
38929
39405
  webFetchPreflight: sdkFeatures.webFetchPreflight,
38930
39406
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
38931
39407
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
39408
+ maxOutputTokens: clientMaxOutputTokens,
38932
39409
  fallbackModel: sdkFeatures.fallbackModel,
38933
39410
  sdkDebug: sdkFeatures.sdkDebug,
38934
39411
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -39007,6 +39484,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
39007
39484
  webFetchPreflight: sdkFeatures.webFetchPreflight,
39008
39485
  claudeAiConnectors: sdkFeatures.claudeAiConnectors,
39009
39486
  maxBudgetUsd: sdkFeatures.maxBudgetUsd,
39487
+ maxOutputTokens: clientMaxOutputTokens,
39010
39488
  fallbackModel: sdkFeatures.fallbackModel,
39011
39489
  sdkDebug: sdkFeatures.sdkDebug,
39012
39490
  additionalDirectories: sdkFeatures.additionalDirectories ? sdkFeatures.additionalDirectories.split(",").map((d) => d.trim()).filter(Boolean) : undefined,
@@ -39111,7 +39589,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
39111
39589
  let assistantAddedForwardedCall = false;
39112
39590
  if (earlyStopEnabled && message.type === "assistant" && !earlyStopFired) {
39113
39591
  const expectedBefore = earlyStop.expected.size;
39114
- noteAssistantMessage(earlyStop, message);
39592
+ noteAssistantMessage(earlyStop, message, clientToolPrefix);
39115
39593
  assistantAddedForwardedCall = earlyStop.expected.size > expectedBefore;
39116
39594
  } else if (earlyStopEnabled && message.type === "user" && !earlyStopFired) {
39117
39595
  noteUserContent(earlyStop, message.message?.content);
@@ -39227,8 +39705,8 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
39227
39705
  skipBlockIndices.add(eventIndex);
39228
39706
  continue;
39229
39707
  }
39230
- if (passthrough && block.name.startsWith(PASSTHROUGH_MCP_PREFIX)) {
39231
- block.name = stripMcpPrefix(block.name);
39708
+ if (passthrough && block.name.startsWith(clientToolPrefix)) {
39709
+ block.name = resolveClientToolName(block.name, passthroughMcp?.clientNameByAlias, passthroughMcpName);
39232
39710
  if (block.id)
39233
39711
  streamedToolUseIds.add(block.id);
39234
39712
  } else if (block.name.startsWith("mcp__")) {
@@ -39236,6 +39714,7 @@ data: ${JSON.stringify({ type: "content_block_stop", index: idx })}
39236
39714
  skipBlockIndices.add(eventIndex);
39237
39715
  continue;
39238
39716
  } else if (passthrough && block.id) {
39717
+ block.name = resolveClientToolName(block.name, passthroughMcp?.clientNameByAlias, passthroughMcpName);
39239
39718
  streamedToolUseIds.add(block.id);
39240
39719
  }
39241
39720
  if (passthrough && eventIndex !== undefined) {
@@ -39606,7 +40085,7 @@ data: ${JSON.stringify({
39606
40085
  recoverySessionId = recoveryMessage.session_id;
39607
40086
  }
39608
40087
  if (recoveryMessage.type === "assistant") {
39609
- noteAssistantMessage(recoveryEarlyStop, recoveryMessage);
40088
+ noteAssistantMessage(recoveryEarlyStop, recoveryMessage, clientToolPrefix);
39610
40089
  } else if (recoveryMessage.type === "user") {
39611
40090
  noteUserContent(recoveryEarlyStop, recoveryMessage.message?.content);
39612
40091
  }
@@ -39619,7 +40098,7 @@ data: ${JSON.stringify({
39619
40098
  releaseHeldDenies(`silent_recovery_${recoveryEvent.type}`);
39620
40099
  if (recoveryEvent.type === "message_start")
39621
40100
  turnGenerating = true;
39622
- if (recoveryEvent.type === "content_block_start" && isClientForwardedToolUse(recoveryEvent.content_block)) {
40101
+ if (recoveryEvent.type === "content_block_start" && isClientForwardedToolUse(recoveryEvent.content_block, clientToolPrefix)) {
39623
40102
  recoveryStreamedToolUseIds.add(recoveryEvent.content_block.id);
39624
40103
  }
39625
40104
  const lifted = recoveryLifter.lift(event.event);
@@ -40140,7 +40619,8 @@ data: {"type":"message_stop"}
40140
40619
  }
40141
40620
  return;
40142
40621
  }
40143
- if (passthrough && sdkTerm.reason === "max_turns" && capturedToolUses.length === 0 && streamedToolUseIds.size === 0 && messageStartEmitted && textCharsForwarded > 0) {
40622
+ const outputCapTruncated = Boolean(clientMaxOutputTokens) && isOutputTokenCapExceeded(errMsg);
40623
+ if ((passthrough && sdkTerm.reason === "max_turns" || outputCapTruncated) && capturedToolUses.length === 0 && streamedToolUseIds.size === 0 && messageStartEmitted && (outputCapTruncated || textCharsForwarded > 0)) {
40144
40624
  flushOpenClientBlocks("capped_turn");
40145
40625
  diagnosticLog2.session(`${requestMeta.requestId} sdk_termination_truncated ${formatSdkTermination(sdkTerm, {
40146
40626
  model,
@@ -40739,6 +41219,15 @@ data: ${JSON.stringify({
40739
41219
  message: "Meridian is shutting down; route new requests to another instance."
40740
41220
  }, 503);
40741
41221
  }
41222
+ const bootIdentity = describeLocalBootIdentity();
41223
+ if (!bootIdentity.available) {
41224
+ return c.json({
41225
+ status: "unhealthy",
41226
+ version: serverVersion,
41227
+ error: "Cannot capture a process incarnation, so no request that touches a session can be served.",
41228
+ bootIdentity
41229
+ }, 503);
41230
+ }
40742
41231
  try {
40743
41232
  const healthProfile = resolveProfile(finalConfig.profiles, finalConfig.defaultProfile);
40744
41233
  const profileEnvOverrides = Object.keys(healthProfile.env).length > 0 ? healthProfile.env : undefined;
@@ -41057,10 +41546,11 @@ data: ${JSON.stringify({
41057
41546
  "Content-Type": "application/json",
41058
41547
  "x-meridian-agent": "codex"
41059
41548
  };
41060
- const promptCacheKey = rawBody.prompt_cache_key;
41061
- if (typeof promptCacheKey === "string" && promptCacheKey.length > 0) {
41062
- internalHeaders["x-codex-session"] = promptCacheKey;
41063
- }
41549
+ const codexThread = resolveCodexThreadIdentity(rawBody, c.req.header("x-codex-turn-metadata"));
41550
+ if (codexThread.sessionKey)
41551
+ internalHeaders["x-codex-session"] = codexThread.sessionKey;
41552
+ if (codexThread.requestSource)
41553
+ internalHeaders["x-meridian-source"] = codexThread.requestSource;
41064
41554
  const xApiKey = c.req.header("x-api-key");
41065
41555
  if (xApiKey)
41066
41556
  internalHeaders["x-api-key"] = xApiKey;
@@ -41083,7 +41573,8 @@ data: ${JSON.stringify({
41083
41573
  const responseId = `resp_${randomUUID6().replace(/-/g, "")}`;
41084
41574
  const created = Math.floor(Date.now() / 1000);
41085
41575
  const model = typeof rawBody.model === "string" && rawBody.model ? rawBody.model : CANONICAL_SONNET_MODEL;
41086
- const ctx = { responseId, model, created, reasoningRequested: reasoningRequested(rawBody) };
41576
+ const toolAliases = buildResponsesToolAliases(rawBody.tools);
41577
+ const ctx = { responseId, model, created, reasoningRequested: reasoningRequested(rawBody), toolAliases };
41087
41578
  if (!anthropicBody.stream) {
41088
41579
  const anthropicRes = await internalRes.json();
41089
41580
  return c.json(translateAnthropicToResponses(anthropicRes, ctx));
@@ -41431,6 +41922,23 @@ function installProxyProcessErrorHandlers() {
41431
41922
  });
41432
41923
  }
41433
41924
  async function startProxyServer(config2 = {}) {
41925
+ let bootIdentity = describeLocalBootIdentity();
41926
+ for (let attempt = 1;!bootIdentity.available && attempt <= 3; attempt++) {
41927
+ await new Promise((resolve6) => setTimeout(resolve6, 250 * attempt));
41928
+ bootIdentity = describeLocalBootIdentity();
41929
+ if (bootIdentity.available) {
41930
+ console.error(`[PROXY] Boot identity captured on attempt ${attempt + 1} (the first probe failed).`);
41931
+ }
41932
+ }
41933
+ if (!bootIdentity.available && !envBool("ALLOW_MISSING_BOOT_IDENTITY")) {
41934
+ throw new Error("[PROXY] Refusing to start: cannot capture a process incarnation on this host, " + `so no request that touches a session could be served.
41935
+ ` + ` platform: ${bootIdentity.platform}
41936
+ ` + ` cause: ${bootIdentity.hint}
41937
+ ` + " Set MERIDIAN_ALLOW_MISSING_BOOT_IDENTITY=1 to start anyway (requests will still fail).");
41938
+ }
41939
+ if (!bootIdentity.available) {
41940
+ console.error("[PROXY] Starting WITHOUT a boot identity because MERIDIAN_ALLOW_MISSING_BOOT_IDENTITY is set. " + `Requests that touch a session will fail with 500. Cause: ${bootIdentity.hint}`);
41941
+ }
41434
41942
  claudeExecutable = await resolveClaudeExecutableAsync();
41435
41943
  const {
41436
41944
  app,