@markus-global/cli 0.12.0-rc.3 → 0.12.1-rc.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 (88) hide show
  1. package/dist/commands/approval-card.d.ts +22 -1
  2. package/dist/commands/approval-card.d.ts.map +1 -1
  3. package/dist/commands/approval-card.js +25 -1
  4. package/dist/commands/approval-card.js.map +1 -1
  5. package/dist/commands/outbound.d.ts +8 -1
  6. package/dist/commands/outbound.d.ts.map +1 -1
  7. package/dist/commands/outbound.js +1 -0
  8. package/dist/commands/outbound.js.map +1 -1
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +93 -7
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +1906 -964
  13. package/dist/web-ui/assets/{AsyncState-Bn4fEZi_.js → AsyncState-BE4ycfHk.js} +1 -1
  14. package/dist/web-ui/assets/{CommentInput-K5GGyiKb.js → CommentInput-DQIh2AYB.js} +1 -1
  15. package/dist/web-ui/assets/{ContentRenderer-BfUE28DF.js → ContentRenderer-C0L1YkNl.js} +2 -2
  16. package/dist/web-ui/assets/{DeliverableShareModal-BA31hw63.js → DeliverableShareModal-KlLlP9Fe.js} +1 -1
  17. package/dist/web-ui/assets/{Deliverables-DTE21gMR.js → Deliverables-CiqT2Ipg.js} +1 -1
  18. package/dist/web-ui/assets/{Notifications-DrhzF29n.js → Notifications-82rU7lAf.js} +1 -1
  19. package/dist/web-ui/assets/{Search-B_FQwfHn.js → Search-CNNN3duL.js} +1 -1
  20. package/dist/web-ui/assets/SendToChat-EsNVdiYI.js +1 -0
  21. package/dist/web-ui/assets/Settings-COmJTMaX.js +8 -0
  22. package/dist/web-ui/assets/{Store-CvRIK-5v.js → Store-Cb-RBY68.js} +1 -1
  23. package/dist/web-ui/assets/{Switch-DBd7W9Pv.js → Switch-SqNs6-fd.js} +1 -1
  24. package/dist/web-ui/assets/{Team-Cre9JXT2.js → Team-DA5MQ-20.js} +31 -31
  25. package/dist/web-ui/assets/Work-D4noaLBo.js +142 -0
  26. package/dist/web-ui/assets/{arc-B8WSMmgB.js → arc-BOFJ1EJN.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-DE0fnpkU.js → architectureDiagram-3BPJPVTR-BQ0qr0Vl.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-BnEt7L8I.js → blockDiagram-GPEHLZMM-kSXlCE5q.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-0jt--EpH.js → c4Diagram-AAUBKEIU-kCxqEGe5.js} +1 -1
  30. package/dist/web-ui/assets/channel-MEPTI8rz.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-CLyqQEQo.js → chunk-2J33WTMH-BgMluOvE.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-mylnMthq.js → chunk-4BX2VUAB-tu9bzY5y.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-DtElV09S.js → chunk-55IACEB6-DK9D0I2N.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-BpRwLol3.js → chunk-727SXJPM-D_5Cdc0d.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-5yxNM2TB.js → chunk-AQP2D5EJ-BUmO_w99.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-no_NwFEB.js → chunk-FMBD7UC4-Ck9FWl7n.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-JvDwwYzS.js → chunk-ND2GUHAM-Mvxy6fm4.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-C-NPps0e.js → chunk-QZHKN3VN-C9xMd3WM.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C-iFEC5t.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C-iFEC5t.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-OUCdAUoH.js → cose-bilkent-S5V4N54A-CUTkidkC.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-BJNrdNyh.js → dagre-BM42HDAG-CGLda2Em.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-CXqfw0Vf.js → diagram-2AECGRRQ-DRl88ns2.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-Dhik8K7x.js → diagram-5GNKFQAL-rf4YhM9A.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-DzTqoIpG.js → diagram-KO2AKTUF-BD8mjYi6.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-CzPaYK-1.js → diagram-LMA3HP47-DiZICe4t.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-D3i9cNLV.js → diagram-OG6HWLK6-Dj0Mw95G.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-BE8zQneZ.js → docx-preview-DQSKxlsK.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-DZ6wi5nS.js → erDiagram-TEJ5UH35-BQq31SZZ.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-CEbBUrOM.js → flowDiagram-I6XJVG4X-Cc82cW20.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-lo_doOaC.js → ganttDiagram-6RSMTGT7-D1MzI2Uw.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-C3mdtDuF.js → gitGraphDiagram-PVQCEYII-D1v-40GN.js} +1 -1
  53. package/dist/web-ui/assets/index-B0GCqbye.css +1 -0
  54. package/dist/web-ui/assets/{index-DyYU0JDE.js → index-BXWHxoXp.js} +61 -61
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-6I0hh52X.js → infoDiagram-5YYISTIA-COPRgK1x.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BOk8zKdQ.js → ishikawaDiagram-YF4QCWOH-BmrWPE_9.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-C3KEoO7x.js → journeyDiagram-JHISSGLW-C7WKxQjK.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-DCT0_9gO.js → kanban-definition-UN3LZRKU-yNU5HtNI.js} +1 -1
  59. package/dist/web-ui/assets/{linear-D1g5s_fh.js → linear-BITZw-sC.js} +1 -1
  60. package/dist/web-ui/assets/{mermaid.core-BOX2l4yL.js → mermaid.core-B-JixiD0.js} +5 -5
  61. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-KkRXcsxC.js → mindmap-definition-RKZ34NQL-CIC2Ov1E.js} +1 -1
  62. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Crj5MjvX.js → pieDiagram-4H26LBE5-CJn4Ut9d.js} +1 -1
  63. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CKhlan97.js → quadrantDiagram-W4KKPZXB-DcRyVlzO.js} +1 -1
  64. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-B7OrOTSq.js → requirementDiagram-4Y6WPE33-DiNbCJGt.js} +1 -1
  65. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CzvhKY35.js → sankeyDiagram-5OEKKPKP-RHicfbUP.js} +1 -1
  66. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-CiNjJsfF.js → sequenceDiagram-3UESZ5HK-P1XTa1MM.js} +1 -1
  67. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DBsBa5mY.js → stateDiagram-AJRCARHV-Dbu2PX-0.js} +1 -1
  68. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-BVoD4Uz4.js +1 -0
  69. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-CL-8e5v_.js → timeline-definition-PNZ67QCA-DGJ5VfHk.js} +1 -1
  70. package/dist/web-ui/assets/{transform-CpIVI4vC.js → transform-BqqRT-Iy.js} +1 -1
  71. package/dist/web-ui/assets/{value-DIujSiJ7.js → value-wA6veExk.js} +1 -1
  72. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-CWgqoJu8.js → vennDiagram-CIIHVFJN-B9fLD2oz.js} +1 -1
  73. package/dist/web-ui/assets/{wardley-L42UT6IY-ZgIWnerm.js → wardley-L42UT6IY-CH2NYUlK.js} +1 -1
  74. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CBWa7zOH.js → wardleyDiagram-YWT4CUSO-efQZMvBj.js} +1 -1
  75. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-Du9MvrT6.js → xychartDiagram-2RQKCTM6-BNcrfIXF.js} +1 -1
  76. package/dist/web-ui/index.html +2 -2
  77. package/docs/analysis/2026-10-29-a2a-cache-hit-rate.md +347 -0
  78. package/docs/architecture/concurrent-processing.md +9 -1
  79. package/docs/architecture/notify-user-context-truth.md +91 -0
  80. package/package.json +1 -1
  81. package/dist/web-ui/assets/SendToChat-DjBI_C0Z.js +0 -1
  82. package/dist/web-ui/assets/Settings-BG3HtYuY.js +0 -8
  83. package/dist/web-ui/assets/Work-C77VUxw5.js +0 -12
  84. package/dist/web-ui/assets/channel-MmWww9CF.js +0 -1
  85. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-lROpDb6P.js +0 -1
  86. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-lROpDb6P.js +0 -1
  87. package/dist/web-ui/assets/index-D4zDaGe4.css +0 -1
  88. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DsfVE1eK.js +0 -1
package/dist/markus.mjs CHANGED
@@ -4368,15 +4368,69 @@ function validateWorkflowTemplate(template) {
4368
4368
  }
4369
4369
  }
4370
4370
  }
4371
+ const outputsByStep = /* @__PURE__ */ new Map();
4372
+ for (const step of steps) {
4373
+ const outs = step.outputs;
4374
+ if (outs === void 0)
4375
+ continue;
4376
+ if (!Array.isArray(outs)) {
4377
+ errors.push(`Step "${String(step.id)}": outputs must be an array`);
4378
+ continue;
4379
+ }
4380
+ const names = /* @__PURE__ */ new Set();
4381
+ for (const out of outs) {
4382
+ if (typeof out.name !== "string" || out.name.trim().length === 0) {
4383
+ errors.push(`Step "${String(step.id)}": outputs entries must have a non-empty "name"`);
4384
+ continue;
4385
+ }
4386
+ if (names.has(out.name)) {
4387
+ errors.push(`Step "${String(step.id)}": output "${out.name}" is declared twice`);
4388
+ }
4389
+ names.add(out.name);
4390
+ if (out.type !== void 0 && out.type !== "file" && out.type !== "directory") {
4391
+ errors.push(`Step "${String(step.id)}": output "${out.name}" type must be "file" or "directory" (got "${String(out.type)}")`);
4392
+ }
4393
+ if (out.required !== void 0 && typeof out.required !== "boolean") {
4394
+ errors.push(`Step "${String(step.id)}": output "${out.name}" required must be a boolean`);
4395
+ }
4396
+ }
4397
+ outputsByStep.set(String(step.id), names);
4398
+ }
4399
+ const dependencyClosure = (stepId) => {
4400
+ const seen = /* @__PURE__ */ new Set();
4401
+ const walk = (id) => {
4402
+ const s2 = steps.find((x) => x.id === id);
4403
+ const deps = s2?.depends_on ?? [];
4404
+ for (const dep of deps) {
4405
+ if (typeof dep !== "string" || seen.has(dep))
4406
+ continue;
4407
+ seen.add(dep);
4408
+ walk(dep);
4409
+ }
4410
+ };
4411
+ walk(stepId);
4412
+ return seen;
4413
+ };
4371
4414
  for (const step of steps) {
4372
4415
  const inputs = step.inputs;
4373
- if (Array.isArray(inputs)) {
4374
- for (const inp of inputs) {
4375
- if (typeof inp.from !== "string" || typeof inp.as !== "string") {
4376
- errors.push(`Step "${step.id}": inputs entries must have "from" and "as" string fields`);
4377
- } else if (!stepIds.has(inp.from)) {
4378
- errors.push(`Step "${step.id}": inputs.from references unknown step "${inp.from}"`);
4379
- }
4416
+ if (!Array.isArray(inputs))
4417
+ continue;
4418
+ const closure = dependencyClosure(String(step.id));
4419
+ for (const inp of inputs) {
4420
+ if (typeof inp.from !== "string" || typeof inp.as !== "string") {
4421
+ errors.push(`Step "${String(step.id)}": inputs entries must have "from" and "as" string fields`);
4422
+ continue;
4423
+ }
4424
+ if (!stepIds.has(inp.from)) {
4425
+ errors.push(`Step "${String(step.id)}": inputs.from references unknown step "${inp.from}"`);
4426
+ continue;
4427
+ }
4428
+ if (!closure.has(inp.from)) {
4429
+ errors.push(`Step "${String(step.id)}": inputs.from "${inp.from}" is not a declared dependency \u2014 it could run after this step`);
4430
+ }
4431
+ const upstreamOutputs = outputsByStep.get(inp.from);
4432
+ if (upstreamOutputs && upstreamOutputs.size > 0 && !upstreamOutputs.has(inp.as)) {
4433
+ errors.push(`Step "${String(step.id)}": inputs.as "${inp.as}" is not one of step "${inp.from}" outputs (${[...upstreamOutputs].join(", ")})`);
4380
4434
  }
4381
4435
  }
4382
4436
  }
@@ -8550,6 +8604,7 @@ function convertMessagesOpenAI(messages, opts) {
8550
8604
  const clean = sanitizeLLMMessages(messages);
8551
8605
  const backfillReasoning = !!opts?.backfillReasoning || clean.some((m) => !!m.reasoningContent);
8552
8606
  const splitSystemIntoSegments = !!opts?.systemCacheSegments && opts.systemCacheSegments.length >= 1;
8607
+ let segmentsEmitted = false;
8553
8608
  for (const m of clean) {
8554
8609
  if (m.role === "system")
8555
8610
  continue;
@@ -8560,7 +8615,8 @@ function convertMessagesOpenAI(messages, opts) {
8560
8615
  }
8561
8616
  }
8562
8617
  return clean.flatMap((m) => {
8563
- if (splitSystemIntoSegments && m.role === "system") {
8618
+ if (splitSystemIntoSegments && m.role === "system" && !segmentsEmitted) {
8619
+ segmentsEmitted = true;
8564
8620
  return opts.systemCacheSegments.filter((seg) => seg.content.length > 0).map((seg) => ({ role: "system", content: seg.content }));
8565
8621
  }
8566
8622
  if (m.role === "tool") {
@@ -8638,6 +8694,28 @@ function computeCacheHitRate(input) {
8638
8694
  return null;
8639
8695
  return Math.min(1, (input.cacheReadTokens ?? 0) / denom);
8640
8696
  }
8697
+ function aggregateCacheHitRate(agents) {
8698
+ let read = 0;
8699
+ let denom = 0;
8700
+ let samples = 0;
8701
+ for (const a of agents) {
8702
+ if (!Number.isFinite(a.cacheDenominatorTotal) || a.cacheDenominatorTotal <= 0)
8703
+ continue;
8704
+ read += Number.isFinite(a.cacheReadReported) ? a.cacheReadReported : 0;
8705
+ denom += a.cacheDenominatorTotal;
8706
+ samples++;
8707
+ }
8708
+ if (samples === 0 || denom <= 0)
8709
+ return { cacheHitRate: null, cacheHitSamples: 0 };
8710
+ return { cacheHitRate: Math.min(1, read / denom), cacheHitSamples: samples };
8711
+ }
8712
+ function computeReplayRatio(promptTokens, outputTokens) {
8713
+ if (!Number.isFinite(promptTokens) || !Number.isFinite(outputTokens) || outputTokens <= 0)
8714
+ return null;
8715
+ if (promptTokens <= 0)
8716
+ return null;
8717
+ return promptTokens / outputTokens;
8718
+ }
8641
8719
  function normalizeOpenAIUsage(raw) {
8642
8720
  const usage = {
8643
8721
  inputTokens: raw?.prompt_tokens ?? 0,
@@ -8962,6 +9040,82 @@ var init_context_slot = __esm({
8962
9040
  }
8963
9041
  });
8964
9042
 
9043
+ // ../core/dist/context-budget.js
9044
+ function estimateCompactionFractions(input) {
9045
+ const S = input.summaryTokens ?? COMPACTION_SUMMARY_TOKENS;
9046
+ if (!(input.totalChars > 0) || !(input.promptTokens > 0)) {
9047
+ return { fEst: 0, nEst: Math.max(1, Math.min(50, Math.round(input.callsThisTurn))) };
9048
+ }
9049
+ const keepRatio = input.recentChars / input.totalChars;
9050
+ const summaryRatio = S / input.promptTokens;
9051
+ const fEst = Math.max(0, Math.min(0.95, 1 - keepRatio - summaryRatio));
9052
+ const nEst = Math.max(1, Math.min(50, Math.round(input.callsThisTurn)));
9053
+ return { fEst, nEst };
9054
+ }
9055
+ function shouldEmitCompactionHint(input) {
9056
+ const rearm = input.rearmCalls ?? COMPACTION_REARM_CALLS;
9057
+ if (!input.previous || input.previous.verdict === void 0)
9058
+ return true;
9059
+ if (input.previous.verdict !== input.action)
9060
+ return true;
9061
+ return input.callIndex - input.previous.emittedAtCall >= rearm;
9062
+ }
9063
+ function compactionGuidance(input) {
9064
+ const { missPerToken: cMiss, hitPerToken: cHit, outputPerToken: cOut } = COMPACTION_PRICE;
9065
+ const P = input.promptTokens;
9066
+ const h = input.hitRate;
9067
+ const f = input.fEst;
9068
+ const n2 = input.nEst;
9069
+ if (!(P > 0) || !Number.isFinite(h) || !Number.isFinite(f) || !(n2 >= 1))
9070
+ return null;
9071
+ if (P < COMPACTION_MIN_PROMPT_TOKENS)
9072
+ return null;
9073
+ if (h < 0 || h > 1 || f <= 0 || f >= 1)
9074
+ return null;
9075
+ const S = input.summaryTokens ?? 3e3;
9076
+ const blend = h * cHit + (1 - h) * cMiss;
9077
+ if (!(blend > 0))
9078
+ return null;
9079
+ const pAfter = P * (1 - f);
9080
+ const oneTimePenaltyUsd = pAfter * cMiss - P * blend + S * cOut;
9081
+ const savingPerCallUsd = f * P * blend;
9082
+ const paybackCalls = savingPerCallUsd > 0 ? oneTimePenaltyUsd / savingPerCallUsd : null;
9083
+ const m = cMiss / blend;
9084
+ const fStar = (m - 1) / (n2 + m);
9085
+ const action = oneTimePenaltyUsd <= 0 || f > fStar || paybackCalls !== null && paybackCalls <= n2 ? "compact" : "hold";
9086
+ return {
9087
+ action,
9088
+ params: { hitRate: h, fEst: f, nEst: n2, fStar, paybackCalls, oneTimePenaltyUsd, savingPerCallUsd, blendedPerToken: blend }
9089
+ };
9090
+ }
9091
+ function compactionActionLine(action, opts) {
9092
+ if (action === "compact") {
9093
+ const reason = opts?.overflow ? "The next request may not fit in the window" : "Now is the cheapest time to compact \u2014 one call now makes every later call cheaper";
9094
+ return `[COMPACT] ${reason}. Use \`session\` operation:'compact' (optionally goal/done/next); operation:'pin' for the one fact you must not lose.`;
9095
+ }
9096
+ return "[COMPACT] Not worth it yet \u2014 keep going (a partial trim costs more than it saves).";
9097
+ }
9098
+ var COMPACTION_SUMMARY_TOKENS, DEFAULT_COMPACT_KEEP_LAST, COMPACT_KEEP_LAST_MIN, COMPACT_KEEP_LAST_MAX, COMPACTION_REARM_CALLS, COMPACTION_PRICE, COMPACTION_MIN_PROMPT_TOKENS;
9099
+ var init_context_budget = __esm({
9100
+ "../core/dist/context-budget.js"() {
9101
+ "use strict";
9102
+ COMPACTION_SUMMARY_TOKENS = 3e3;
9103
+ DEFAULT_COMPACT_KEEP_LAST = 40;
9104
+ COMPACT_KEEP_LAST_MIN = 5;
9105
+ COMPACT_KEEP_LAST_MAX = 200;
9106
+ COMPACTION_REARM_CALLS = 20;
9107
+ COMPACTION_PRICE = {
9108
+ /** `input_cost_per_token` (cache miss). */
9109
+ missPerToken: 2e-7,
9110
+ /** `cache_read_input_token_cost` (cache hit) — exactly 1/5 of a miss. */
9111
+ hitPerToken: 4e-8,
9112
+ /** `output_cost_per_token`. */
9113
+ outputPerToken: 4e-7
9114
+ };
9115
+ COMPACTION_MIN_PROMPT_TOKENS = 15e4;
9116
+ }
9117
+ });
9118
+
8965
9119
  // ../core/dist/memory/records.js
8966
9120
  function coerceEntry(raw) {
8967
9121
  if (!raw || typeof raw !== "object" || Array.isArray(raw))
@@ -9248,6 +9402,7 @@ var init_store = __esm({
9248
9402
  init_residue_repair();
9249
9403
  init_atomic_write();
9250
9404
  init_context_slot();
9405
+ init_context_budget();
9251
9406
  init_records();
9252
9407
  log8 = createLogger("memory-store");
9253
9408
  VALID_TYPES = /* @__PURE__ */ new Set(["conversation", "fact", "task_result", "note", "insight", "conversation_fragment"]);
@@ -10103,7 +10258,7 @@ ${truncatedContent}
10103
10258
  }
10104
10259
  return idx;
10105
10260
  }
10106
- compactSession(sessionId, keepLast = 20) {
10261
+ compactSession(sessionId, keepLast = DEFAULT_COMPACT_KEEP_LAST) {
10107
10262
  const session = this.sessions.get(sessionId) ?? this.getSession(sessionId);
10108
10263
  if (!session) {
10109
10264
  return { summary: "", flushedCount: 0, remaining: 0, found: false };
@@ -10220,7 +10375,7 @@ ${truncatedContent}
10220
10375
  * wrapper so downstream consumers (LLM, UI) treat it like any compaction.
10221
10376
  * Returns the number of flushed messages.
10222
10377
  */
10223
- compactSessionOnDemand(sessionId, keepLast = 40) {
10378
+ compactSessionOnDemand(sessionId, keepLast = DEFAULT_COMPACT_KEEP_LAST) {
10224
10379
  return this.compactSession(sessionId, keepLast);
10225
10380
  }
10226
10381
  // ─── ContextOS: session slots + fragment retrieval (agent-managed) ───────
@@ -11302,6 +11457,8 @@ var init_agent_metrics = __esm({
11302
11457
  cacheHitRateWindow: window3.cacheHitRateWindow,
11303
11458
  cacheHitRateSamples: window3.cacheHitRateSamples,
11304
11459
  promptTokensReported: c.promptTokensReported,
11460
+ cacheReadReported: c.cacheReadReported,
11461
+ cacheDenominatorTotal: c.cacheDenominatorTotal,
11305
11462
  requestCount: c.requestCount,
11306
11463
  toolCalls: c.toolCalls,
11307
11464
  tokensToday: c.tokensToday,
@@ -12001,27 +12158,6 @@ var init_capability_packs = __esm({
12001
12158
  }
12002
12159
  });
12003
12160
 
12004
- // ../core/dist/context-budget.js
12005
- function contextActionHint(opts) {
12006
- if (!opts.canCompact)
12007
- return void 0;
12008
- if (opts.usedPct >= CONTEXT_HINT_DIRECTIVE_PCT) {
12009
- return "ACT NOW: context is nearly full. Before your next big step, call the `session` tool with operation:'compact' (optionally goal/done/next) to collapse stale history into an anchor summary; use operation:'pin' for the one fact you must not lose. This costs one call now and makes every later call cheaper.";
12010
- }
12011
- if (opts.usedPct >= CONTEXT_HINT_ADVISORY_PCT) {
12012
- return "Context is getting heavy. If the earlier part of this session is no longer needed (finished sub-tasks, stale tool output), consider `session` operation:'compact' \u2014 it pages out old history and keeps an anchor summary.";
12013
- }
12014
- return void 0;
12015
- }
12016
- var CONTEXT_HINT_ADVISORY_PCT, CONTEXT_HINT_DIRECTIVE_PCT;
12017
- var init_context_budget = __esm({
12018
- "../core/dist/context-budget.js"() {
12019
- "use strict";
12020
- CONTEXT_HINT_ADVISORY_PCT = 70;
12021
- CONTEXT_HINT_DIRECTIVE_PCT = 85;
12022
- }
12023
- });
12024
-
12025
12161
  // ../core/dist/context-engine.js
12026
12162
  import { readFileSync as readFileSync10, existsSync as existsSync12 } from "node:fs";
12027
12163
  import { createHash } from "node:crypto";
@@ -12128,6 +12264,14 @@ var init_context_engine = __esm({
12128
12264
  * water level).
12129
12265
  */
12130
12266
  reportedInputBySession = /* @__PURE__ */ new Map();
12267
+ /**
12268
+ * Per-session compaction economics (see `compactionGuidance`).
12269
+ *
12270
+ * `verdict` exists so the agent is told the conclusion only when it FLIPS —
12271
+ * a banner that repeats the same advice every call gets trained out of the
12272
+ * agent's attention (we already made that mistake once).
12273
+ */
12274
+ compactionState = /* @__PURE__ */ new Map();
12131
12275
  /**
12132
12276
  * Durable cache of those readings, so a restart does not blind the gate.
12133
12277
  *
@@ -12415,6 +12559,8 @@ var init_context_engine = __esm({
12415
12559
  // ── SCOPE A (AGENT) head: persona + policies (see Tier 1 note above) ──
12416
12560
  ...agentPersona
12417
12561
  ];
12562
+ const teamDocsTail = [];
12563
+ const scenarioTail = [];
12418
12564
  semiStable.push(this.buildIdentitySection({
12419
12565
  agentId: opts.agentId,
12420
12566
  agentName: opts.agentName,
@@ -12431,7 +12577,7 @@ var init_context_engine = __esm({
12431
12577
  const body = raw.length > cap ? `${raw.slice(0, cap)}
12432
12578
 
12433
12579
  _[announcements truncated \u2014 read \`${opts.teamDataDir ?? "team"}/ANNOUNCEMENT.md\` for full text]_` : raw;
12434
- semiStable.push("\n## Team Announcements\n" + body);
12580
+ teamDocsTail.push("\n## Team Announcements\n" + body);
12435
12581
  }
12436
12582
  if (opts.teamNorms?.trim()) {
12437
12583
  const raw = opts.teamNorms.trim();
@@ -12439,7 +12585,7 @@ _[announcements truncated \u2014 read \`${opts.teamDataDir ?? "team"}/ANNOUNCEME
12439
12585
  const body = raw.length > cap ? `${raw.slice(0, cap)}
12440
12586
 
12441
12587
  _[norms truncated \u2014 read \`${opts.teamDataDir ?? "team"}/NORMS.md\` for full text]_` : raw;
12442
- semiStable.push("\n## Team Working Norms\n" + body);
12588
+ teamDocsTail.push("\n## Team Working Norms\n" + body);
12443
12589
  }
12444
12590
  if (opts.teamDataDir) {
12445
12591
  const lines = ["\n## Team Data Directory", `Path: \`${opts.teamDataDir}\``, "Files:", "- `ANNOUNCEMENT.md` \u2014 team announcements", "- `NORMS.md` \u2014 team working norms"];
@@ -12523,13 +12669,18 @@ _[norms truncated \u2014 read \`${opts.teamDataDir ?? "team"}/NORMS.md\` for ful
12523
12669
  const rawScenario = opts.scenario ?? "chat";
12524
12670
  const isGroupChannel = !!opts.channelKey && opts.channelKey.startsWith("group:");
12525
12671
  const scenario = rawScenario === "a2a" && isGroupChannel ? "group_chat" : rawScenario;
12526
- semiStable.push(this.buildScenarioSection(scenario, { a2aWaitForReply: opts.a2aWaitForReply, isManager: opts.isTeamManager, channelKey: opts.channelKey }));
12672
+ scenarioTail.push(this.buildScenarioSection(scenario, { a2aWaitForReply: opts.a2aWaitForReply, isManager: opts.isTeamManager, channelKey: opts.channelKey }));
12527
12673
  if (isExecuteLike) {
12528
12674
  const scenarioPolicies = this.buildScenarioPolicyBlocks(scenario);
12529
12675
  if (scenarioPolicies)
12530
12676
  semiStable.push(scenarioPolicies);
12531
12677
  }
12532
- const volatile = [];
12678
+ const volatile = [
12679
+ // Interaction mode first (behavioural instructions), then agent-writable
12680
+ // team docs. Both are tail-bound — see the placement notes above.
12681
+ ...scenarioTail,
12682
+ ...teamDocsTail
12683
+ ];
12533
12684
  const dynamic = volatile;
12534
12685
  const knowledgeTokCap = isReflex ? KNOWLEDGE_PROMPT_MAX_TOKENS_REFLEX : isConverse ? KNOWLEDGE_PROMPT_MAX_TOKENS_CONVERSE : KNOWLEDGE_PROMPT_MAX_TOKENS;
12535
12686
  if (knowledgeTokCap > 0) {
@@ -13491,6 +13642,7 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
13491
13642
  const outputReserve = maxOutput;
13492
13643
  let messages = opts.sessionMessages;
13493
13644
  messages = this.shrinkOversizedMessages(messages, CONTEXT_ABSURD_MESSAGE_CHARS);
13645
+ messages = this.collapseStateCheckpoints(messages);
13494
13646
  messages = this.sanitizeMessageSequence(messages);
13495
13647
  messages = this.dedupeTransientPrompts(messages);
13496
13648
  const variableChars = messages.reduce((n2, m) => n2 + getTextContent(m.content).length + (m.toolCalls?.length ? JSON.stringify(m.toolCalls).length : 0), 0);
@@ -13520,16 +13672,53 @@ ${ctx.mergedContent.slice(0, SYSTEM_MAILBOX_MERGED_CHARS)}`);
13520
13672
  const metrics = `window ${Math.round(contextWindow / 1e3)}k \xB7 messages ${messages.length} \xB7 chars ${variableChars} \xB7 output reserve ${outputReserve}`;
13521
13673
  let hintLines = usedPct === void 0 ? `[CONTEXT pending \u2014 no provider measurement for this session yet \xB7 ${metrics}]` : `[CONTEXT ${usedPct}% used \u2014 src=reported \xB7 ${metrics}]`;
13522
13674
  const canCompact = opts.scenario !== "memory_consolidation" && opts.scenario !== "distillation";
13523
- const actionHint = contextActionHint({ usedPct: usedPct ?? 0, canCompact });
13524
- if (actionHint)
13525
- hintLines += `
13526
- ${actionHint}`;
13527
- if (usedPct !== void 0 && usedPct >= CONTEXT_CRIT_RATIO * 100) {
13528
- hintLines += `
13529
- [CONTEXT CRIT] at ${usedPct}%: the next request may not fit. Run session_compact now, and session_pin a goal/done/next anchor to keep your position.`;
13530
- } else if (usedPct !== void 0 && usedPct >= CONTEXT_WARN_RATIO * 100) {
13531
- hintLines += `
13532
- [CONTEXT WARN] at ${usedPct}% \u2192 compress now (session_compact) or pin an anchor (session_pin).`;
13675
+ const overflow = usedPct !== void 0 && usedPct >= CONTEXT_CRIT_RATIO * 100;
13676
+ if (canCompact && opts.sessionId && reportedInputTokens && opts.cacheHitRate !== void 0) {
13677
+ const sid = opts.sessionId;
13678
+ const prev = this.compactionState.get(sid);
13679
+ const calls = (prev?.calls ?? 0) + 1;
13680
+ const totalChars = messages.reduce((n2, m) => n2 + getTextContent(m.content).length, 0);
13681
+ const recentChars = messages.slice(-DEFAULT_COMPACT_KEEP_LAST).reduce((n2, m) => n2 + getTextContent(m.content).length, 0);
13682
+ const turnStartForEst = this.findCurrentTurnStart(messages);
13683
+ const callsThisTurn = messages.slice(turnStartForEst + 1).filter((m) => m.role === "assistant").length;
13684
+ const { fEst, nEst } = estimateCompactionFractions({
13685
+ promptTokens: reportedInputTokens,
13686
+ totalChars,
13687
+ recentChars,
13688
+ callsThisTurn
13689
+ });
13690
+ const g = compactionGuidance({
13691
+ promptTokens: reportedInputTokens,
13692
+ hitRate: opts.cacheHitRate,
13693
+ fEst,
13694
+ nEst,
13695
+ summaryTokens: COMPACTION_SUMMARY_TOKENS
13696
+ });
13697
+ if (g) {
13698
+ const action = overflow ? "compact" : g.action;
13699
+ const emit = action === "compact" && (overflow || shouldEmitCompactionHint({ previous: prev, action, callIndex: calls }));
13700
+ if (emit)
13701
+ hintLines += `
13702
+ ${compactionActionLine(action, { overflow })}`;
13703
+ this.compactionState.set(sid, {
13704
+ verdict: action,
13705
+ calls,
13706
+ emittedAtCall: emit ? calls : prev?.emittedAtCall ?? 0
13707
+ });
13708
+ log10.info("Compaction economics", { agentId: opts.agentId, sessionId: sid, action, emit, overflow, ...g.params });
13709
+ } else {
13710
+ this.compactionState.set(sid, {
13711
+ verdict: prev?.verdict,
13712
+ calls,
13713
+ emittedAtCall: prev?.emittedAtCall ?? 0
13714
+ });
13715
+ }
13716
+ while (this.compactionState.size > 256) {
13717
+ const oldest = this.compactionState.keys().next().value;
13718
+ if (oldest === void 0)
13719
+ break;
13720
+ this.compactionState.delete(oldest);
13721
+ }
13533
13722
  }
13534
13723
  const contextHint = hintLines;
13535
13724
  log10.info("Context assembled", {
@@ -13562,12 +13751,13 @@ ${actionHint}`;
13562
13751
  for (const sec of sections) {
13563
13752
  const h = _ContextEngine.hashSection(sec.body);
13564
13753
  nextHashes.set(sec.key, h);
13754
+ const alwaysFresh = _ContextEngine.ALWAYS_FRESH_VOLATILE_SECTIONS.has(sec.key);
13565
13755
  const changed = !prevSnapshot || prevSnapshot.hashes.get(sec.key) !== h;
13566
- if (changed) {
13756
+ if (changed && !alwaysFresh) {
13567
13757
  anyChanged = true;
13568
13758
  changedBodies.push(sec.body);
13569
13759
  }
13570
- if (forceFull || changed)
13760
+ if (forceFull || changed || alwaysFresh)
13571
13761
  freshBodies.push(sec.body);
13572
13762
  else
13573
13763
  omitted.push(sec.key);
@@ -13745,6 +13935,21 @@ ${tail}`
13745
13935
  * counts as a user turn.
13746
13936
  */
13747
13937
  static STATE_CHECKPOINT_PREFIX = "[SYSTEM] [State checkpoint]";
13938
+ /**
13939
+ * Volatile-tail sections that must be delivered IN FULL on every call.
13940
+ *
13941
+ * The tail is change-gated to stop it working as a stream of "new" user
13942
+ * statements (see the ContextOS v2 note in `prepareMessages`). That gating is
13943
+ * right for *state* (Task Board, Team Status, Knowledge) and wrong for
13944
+ * *instructions*: an omitted instruction is genuinely gone from the model's
13945
+ * context until the next re-arm.
13946
+ *
13947
+ * `## Current Interaction Mode` says which KIND of turn this is ("human chat"
13948
+ * vs "A2A — humans do not see this"). It must never be gated away.
13949
+ */
13950
+ static ALWAYS_FRESH_VOLATILE_SECTIONS = /* @__PURE__ */ new Set([
13951
+ "Current Interaction Mode"
13952
+ ]);
13748
13953
  static hashSection(body) {
13749
13954
  return createHash("sha1").update(_ContextEngine.normalizeSectionForHash(body)).digest("hex").slice(0, 8);
13750
13955
  }
@@ -13787,6 +13992,89 @@ ${tail}`
13787
13992
  flush();
13788
13993
  return out;
13789
13994
  }
13995
+ /**
13996
+ * Collapse accumulated `[SYSTEM] [State checkpoint]` messages into ONE.
13997
+ *
13998
+ * A checkpoint is appended to durable history every time the volatile state
13999
+ * changes (see the completeness guarantee in `prepareMessages`), and it is
14000
+ * never rewritten in place — measured 2026-10-29: at a fixed index, 0 hash
14001
+ * changes across 861 adjacent-call pairs. So they do not *thrash* the prefix;
14002
+ * they simply PILE UP, and every request replays all of them:
14003
+ *
14004
+ * 247 checkpoints / 3.4M chars across 26 sessions in one 35-minute window.
14005
+ * Worst session: 26 checkpoints / 474 695 chars, of which only ~19k was the
14006
+ * newest — i.e. ~96% of that session's state payload was superseded copies
14007
+ * of facts already stated again later.
14008
+ *
14009
+ * "Keep only the newest" would be LOSSY and is wrong: a checkpoint writes
14010
+ * only the sections that CHANGED, so the newest one legitimately lacks
14011
+ * sections written earlier (measured: `## Team Status` and `## Notebook`
14012
+ * existed only in older checkpoints). Dropping them would silently remove
14013
+ * state the agent still needs.
14014
+ *
14015
+ * Lossless collapse instead: parse every checkpoint into `## Section` bodies
14016
+ * and keep the NEWEST body per section. Legal precisely because the writer's
14017
+ * own invariant is "each section body is the complete current body of that
14018
+ * section" — so the newest occurrence is authoritative for that section.
14019
+ *
14020
+ * Placement: at the LAST checkpoint's position, so the fewest already-replayed
14021
+ * messages sit behind a block that changes on every state transition.
14022
+ *
14023
+ * Pure and deterministic (same history ⇒ same bytes), and never mutates the
14024
+ * caller's stored messages — a mutation here would poison the session the
14025
+ * same way the old user-message merge did.
14026
+ */
14027
+ collapseStateCheckpoints(messages) {
14028
+ const PREFIX = _ContextEngine.STATE_CHECKPOINT_PREFIX;
14029
+ const isCheckpoint = (m) => m.role === "user" && getTextContent(m.content).trimStart().startsWith(PREFIX);
14030
+ const indices = [];
14031
+ messages.forEach((m, i) => {
14032
+ if (isCheckpoint(m))
14033
+ indices.push(i);
14034
+ });
14035
+ if (indices.length < 2)
14036
+ return messages;
14037
+ const latestBody = /* @__PURE__ */ new Map();
14038
+ const order = [];
14039
+ let preamble = "";
14040
+ const absorb = (content) => {
14041
+ const body = content.trimStart().slice(PREFIX.length);
14042
+ const parts = body.split(/\n(?=##\s)/);
14043
+ for (const part of parts) {
14044
+ const firstLine2 = part.split("\n", 1)[0] ?? "";
14045
+ const m = /^##\s+(.+?)\s*$/.exec(firstLine2);
14046
+ if (!m) {
14047
+ const trimmed2 = part.trim();
14048
+ if (trimmed2)
14049
+ preamble = trimmed2;
14050
+ continue;
14051
+ }
14052
+ const name = m[1];
14053
+ if (!latestBody.has(name))
14054
+ order.push(name);
14055
+ latestBody.set(name, part.trim());
14056
+ }
14057
+ };
14058
+ for (const i of indices)
14059
+ absorb(getTextContent(messages[i].content));
14060
+ const collapsed = [
14061
+ PREFIX,
14062
+ ...preamble ? [preamble] : [],
14063
+ ...order.map((name) => latestBody.get(name))
14064
+ ].join("\n");
14065
+ const lastIdx = indices[indices.length - 1];
14066
+ const dropSet = new Set(indices);
14067
+ const out = [];
14068
+ for (let i = 0; i < messages.length; i++) {
14069
+ if (dropSet.has(i)) {
14070
+ if (i === lastIdx)
14071
+ out.push({ ...messages[i], content: collapsed });
14072
+ continue;
14073
+ }
14074
+ out.push(messages[i]);
14075
+ }
14076
+ return out;
14077
+ }
13790
14078
  /**
13791
14079
  * Collapse duplicate *transient* harness prompts.
13792
14080
  *
@@ -13899,7 +14187,7 @@ ${tail}`
13899
14187
  const prevText = prev ? typeof prev.content === "string" ? prev.content : "" : "";
13900
14188
  const isSystemInjected = (t) => t.startsWith("[SYSTEM]") || t.startsWith("[Conversation history summary");
13901
14189
  if (prev && prev.role === msg.role && msg.role === "user" && !isSystemInjected(msgText) && !isSystemInjected(prevText)) {
13902
- prev.content = prev.content + "\n\n" + msg.content;
14190
+ result[result.length - 1] = { ...prev, content: prevText + "\n\n" + msgText };
13903
14191
  } else {
13904
14192
  result.push(msg);
13905
14193
  }
@@ -14875,7 +15163,7 @@ var init_tool_selector = __esm({
14875
15163
  };
14876
15164
  pushUnique({
14877
15165
  name: "notify_user",
14878
- description: 'Send a ONE-WAY notification to a human team member (appears in the agent chat + notification bell). SEMANTICS: notify = inform, do NOT expect a reply. Use it for status updates, reports, alerts and findings \u2014 the user reads it whenever they get to it, and you must NOT wait for it.\nIf you need an answer or a decision before you can continue (an authorization, a scope call, a choice, "I am blocked until someone signs off"), do NOT use this tool \u2014 use `request_user_input`, which blocks and returns the answer.\nDo NOT repeat a notification you already sent: a second copy of the same message adds no information and does not make an answer arrive sooner. If you are waiting on a reply, the right move is `request_user_input`, not another notification.',
15166
+ description: 'Send a ONE-WAY notification to a human team member (appears in the agent chat + notification bell). SEMANTICS: notify = inform, do NOT expect a reply. Use it for status updates, reports, alerts and findings \u2014 the user reads it whenever they get to it, and you must NOT wait for it.\nIf you need an answer or a decision before you can continue (an authorization, a scope call, a choice, "I am blocked until someone signs off"), do NOT use this tool \u2014 use `request_user_input`, which blocks and returns the answer.\nDo NOT repeat a notification you already sent: a second copy of the same message adds no information and does not make an answer arrive sooner. If you are waiting on a reply, the right move is `request_user_input`, not another notification.\nThe tool result carries a `notification.id` \u2014 that id IS the proof of delivery. If your history already holds one for the same content, it was delivered: do not send it again, and never re-derive "I only wrote text, it was not actually sent" when a receipt is present.',
14879
15167
  inputSchema: {
14880
15168
  type: "object",
14881
15169
  properties: {
@@ -14940,7 +15228,11 @@ var init_tool_selector = __esm({
14940
15228
  properties: {
14941
15229
  id: { type: "string" },
14942
15230
  label: { type: "string" },
14943
- description: { type: "string" }
15231
+ description: { type: "string" },
15232
+ requires_freeform: {
15233
+ type: "boolean",
15234
+ description: 'Set true when picking this option is NOT yet an answer \u2014 the user must also type something (e.g. "give you the numbers" requires `3 / 1 / 1`). Channels that cannot collect text will not offer it as a one-tap button, and a selection without the typed value is refused rather than silently accepted.'
15235
+ }
14944
15236
  },
14945
15237
  required: ["label"]
14946
15238
  }
@@ -58038,6 +58330,16 @@ ${turnContentOf(item)}` + batchSuffix;
58038
58330
  const provider = this.getEffectiveProvider();
58039
58331
  const effectiveModel = this.getEffectiveModel();
58040
58332
  return {
58333
+ // Feeds `compactionGuidance` (context-budget.ts): the economics of
58334
+ // compacting depend on what a cached vs uncached token actually costs.
58335
+ //
58336
+ // Prefer the per-session window (it reflects THIS conversation), but fall
58337
+ // back to the cumulative rate: the window needs `sessionId` on every
58338
+ // metrics event, and before that was wired it was structurally null — a
58339
+ // silent, "no measurement" that made this whole signal never fire. A
58340
+ // slightly stale number beats a dead signal here, because the decision
58341
+ // it drives is a coarse two-way choice (compact / don't), not a price.
58342
+ cacheHitRate: this.metricsCollector.getUsageStats().cacheHitRateWindow ?? this.metricsCollector.getUsageStats().cacheHitRate ?? void 0,
58041
58343
  // P1-8: window must be resolved for the model actually used this request,
58042
58344
  // not the provider's configured default (which the session may override).
58043
58345
  modelContextWindow: this.llmRouter.getModelContextWindow(provider, effectiveModel),
@@ -59066,6 +59368,9 @@ _[truncated \u2014 full text in NOTEBOOK.md]
59066
59368
  this.emitAudit({
59067
59369
  type: "llm_request",
59068
59370
  action,
59371
+ // Per-session window needs this (see emitAudit's note). Without it the
59372
+ // windowed cache-hit metric is always null.
59373
+ sessionId: this.currentSessionId,
59069
59374
  tokensUsed: tokensUsed ?? response.usage.inputTokens + response.usage.outputTokens,
59070
59375
  inputTokens: response.usage.inputTokens,
59071
59376
  outputTokens: response.usage.outputTokens,
@@ -62452,8 +62757,6 @@ ${d.text}
62452
62757
  notebook_clear: { domain: AGENT_MEMORY_RESOURCE_DOMAIN, resource: "notebook" },
62453
62758
  // 会话自我管理:compact / pin / unpin / purge 都是会话状态变更
62454
62759
  session: { domain: "session", arg: ["session_id", "sessionId"] },
62455
- // discover_tools 会写入「本会话已激活工具」集合 —— 共享可变状态
62456
- discover_tools: { domain: "session-tools" },
62457
62760
  // ── 全局配置
62458
62761
  llm_switch_model: { domain: "llm-config" },
62459
62762
  llm_set_capability_routing: { domain: "llm-config" },
@@ -62622,6 +62925,15 @@ ${d.text}
62622
62925
  "get_network_request",
62623
62926
  "lighthouse_audit",
62624
62927
  "speech_to_text",
62928
+ // ── 纯本地元工具:只动本 Agent 内存里的「工具可见性」集合并即时返回。
62929
+ // 必须免锁:`discover_tools` 命中工具名时是几次 Set/Map 查询(历史 800 次
62930
+ // 调用耗时 0–4ms),被默认判为写工具后却要排 `shell_execute` 的 `'*'`
62931
+ // 全局独占锁 —— 实测一次 112.4s 的「工具耗时」里 112.4s 全是在等锁,
62932
+ // 真正的执行只用了 3ms(2026-10-29 incident)。它的其余副作用各自已有
62933
+ // 串行化:MCP 连接按 server 名持 startup lock(mcp-client.withStartupLock),
62934
+ // `Set.add` / `Map.set` 本身在 JS 单线程内原子。
62935
+ // 回归守卫:test/agent-write-lock.test.ts「discover_tools 不得排队等全局写锁」。
62936
+ "discover_tools",
62625
62937
  // ── HITL 阻塞 / 长时任务:绝不能持锁(见上方说明)
62626
62938
  "request_user_input",
62627
62939
  "request_user_approval",
@@ -62791,28 +63103,6 @@ ${d.text}
62791
63103
  const taskId2 = explicitTaskId ?? this.getCurrentTaskId();
62792
63104
  const requirementId2 = this.getCurrentRequirementId();
62793
63105
  const explicitTargetUser = toolCall.arguments.target_user_id;
62794
- const contextParts = [];
62795
- if (taskId2)
62796
- contextParts.push(`task_id=${taskId2}`);
62797
- if (requirementId2)
62798
- contextParts.push(`requirement_id=${requirementId2}`);
62799
- if (priority && priority !== "normal")
62800
- contextParts.push(`priority=${priority}`);
62801
- const contextSuffix = contextParts.length > 0 ? `
62802
-
62803
- <!-- notify_context: ${contextParts.join(", ")} -->` : "";
62804
- const formattedMsg = `**${title}**
62805
-
62806
- ${body}${contextSuffix}`;
62807
- if (this.currentSessionId) {
62808
- try {
62809
- this.memory.appendMessage(this.currentSessionId, {
62810
- role: "assistant",
62811
- content: formattedMsg
62812
- });
62813
- } catch {
62814
- }
62815
- }
62816
63106
  this.recentActivityRing.push(`[notify_user] ${title}`);
62817
63107
  if (this.recentActivityRing.length > _Agent.ACTIVITY_RING_SIZE) {
62818
63108
  this.recentActivityRing.shift();
@@ -62828,8 +63118,22 @@ ${body}${contextSuffix}`;
62828
63118
  taskId: taskId2,
62829
63119
  requirementId: requirementId2
62830
63120
  });
62831
- log20.info("User notification sent", { agentId: this.id, title });
62832
- return JSON.stringify({ status: "ok", message: "Notification sent to user." });
63121
+ const deliveredAt = (/* @__PURE__ */ new Date()).toISOString();
63122
+ const notificationId = `ntf_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
63123
+ log20.info("User notification sent", { agentId: this.id, title, notificationId });
63124
+ return JSON.stringify({
63125
+ status: "ok",
63126
+ message: "Notification delivered to the user.",
63127
+ notification: {
63128
+ id: notificationId,
63129
+ title,
63130
+ priority,
63131
+ to: explicitTargetUser ?? this.currentInteractingUserId ?? "owner",
63132
+ deliveredAt,
63133
+ ...taskId2 ? { taskId: taskId2 } : {},
63134
+ ...requirementId2 ? { requirementId: requirementId2 } : {}
63135
+ }
63136
+ });
62833
63137
  } catch (err) {
62834
63138
  return JSON.stringify({ status: "error", message: `Failed to send notification: ${String(err)}` });
62835
63139
  }
@@ -62901,7 +63205,12 @@ ${body}${contextSuffix}`;
62901
63205
  const description = toolCall.arguments.description ?? "";
62902
63206
  const rawQuestions = toolCall.arguments.questions;
62903
63207
  const rawOptions = toolCall.arguments.options;
62904
- const normalizeOptions = (opts) => opts?.map((o, i) => ({ id: o.id ?? `opt_${i + 1}`, label: o.label, description: o.description }));
63208
+ const normalizeOptions = (opts) => opts?.map((o, i) => ({
63209
+ id: o.id ?? `opt_${i + 1}`,
63210
+ label: o.label,
63211
+ description: o.description,
63212
+ ...o.requires_freeform === true ? { requiresFreeform: true } : {}
63213
+ }));
62905
63214
  const missingIntent = [];
62906
63215
  let questions;
62907
63216
  if (rawQuestions && rawQuestions.length > 0) {
@@ -62970,7 +63279,10 @@ ${body}${contextSuffix}`;
62970
63279
  const resp = {
62971
63280
  status: "ok",
62972
63281
  approved: result.approved,
62973
- selected_option: result.selectedOption ?? (result.approved ? "approve" : "reject"),
63282
+ // 不要编造 selected_option。以前没有选中项时也会填 'approve',于是模型
63283
+ // 分不清「我的选项被选了」和「人被别的路径批准了」——2026-10-28:它把
63284
+ // 'approve' 读成了同意,而它要的数字一个都没拿到。
63285
+ ...result.selectedOption ? { selected_option: result.selectedOption } : {},
62974
63286
  comment: result.comment ?? ""
62975
63287
  };
62976
63288
  if (result.answers && result.answers.length > 0)
@@ -315738,7 +316050,10 @@ var init_cards = __esm({
315738
316050
  approved: { icon: "\u2705", label: "\u5DF2\u6279\u51C6", template: "green" },
315739
316051
  rejected: { icon: "\u274C", label: "\u5DF2\u9A73\u56DE", template: "red" },
315740
316052
  cancelled: { icon: "\u26AA", label: "\u5DF2\u53D6\u6D88", template: "grey" },
315741
- expired: { icon: "\u23F0", label: "\u5DF2\u8D85\u65F6", template: "grey" }
316053
+ expired: { icon: "\u23F0", label: "\u5DF2\u8D85\u65F6", template: "grey" },
316054
+ // 点击没有落账(例如需要到应用内回答的表单)——**不是超时**。把「还没记录」
316055
+ // 画成「已超时」是另一种谎:人会以为请求失效了,于是重发一份。
316056
+ pending: { icon: "\u23F3", label: "\u672A\u8BB0\u5F55 \xB7 \u8BF7\u5230 Markus \u5E94\u7528\u5185\u56DE\u7B54", template: "orange" }
315742
316057
  };
315743
316058
  }
315744
316059
  });
@@ -320054,9 +320369,10 @@ function plainText(msg, body, actions, origin) {
320054
320369
  }
320055
320370
  function renderOutbound(msg, caps = {}) {
320056
320371
  const declared = msg.actions ?? [];
320057
- const withheld = caps.approvalComment ? [] : declared.filter((a) => a.requiresComment);
320058
- const actions = withheld.length > 0 ? declared.filter((a) => !a.requiresComment) : declared;
320059
- const note = withheld.length > 0 ? msg.commentRequiredNote?.trim() : void 0;
320372
+ const lacksFreeText = !caps.approvalComment;
320373
+ const withheld = lacksFreeText ? declared.filter((a) => a.requiresComment || a.requiresFreeform) : [];
320374
+ const actions = withheld.length > 0 ? declared.filter((a) => !withheld.includes(a)) : declared;
320375
+ const note = withheld.length > 0 ? (withheld.some((a) => a.requiresFreeform) ? msg.freeformRequiredNote ?? msg.commentRequiredNote : msg.commentRequiredNote)?.trim() : void 0;
320060
320376
  const body = note ? `${msg.body}
320061
320377
 
320062
320378
  ${note}` : msg.body;
@@ -320187,6 +320503,12 @@ function resolveEnumParams(params, locale) {
320187
320503
  }
320188
320504
  return out;
320189
320505
  }
320506
+ function approvalFreeformNote(locale) {
320507
+ return locale?.toLowerCase().startsWith("zh") ? "\u5176\u4E2D\u9700\u8981\u586B\u5199\u5185\u5BB9\u7684\u9009\u9879\u65E0\u6CD5\u5728\u8FD9\u91CC\u5B8C\u6210\u2014\u2014\u8BF7\u5230 Markus \u5E94\u7528\u5185\u56DE\u7B54\u3002" : "A choice that needs typed input cannot be completed here \u2014 answer inside the Markus app.";
320508
+ }
320509
+ function approvalFormNote(locale) {
320510
+ return locale?.toLowerCase().startsWith("zh") ? "\u2192 \u8FD9\u4E2A\u95EE\u9898\u9700\u8981\u5B8C\u6574\u586B\u5199\uFF08\u591A\u9879/\u9700\u8981\u6587\u5B57\uFF09\uFF0C\u8BF7\u5728 Markus \u5E94\u7528\u5185\u56DE\u7B54\u3002" : "\u2192 This request needs a full answer (several questions / typed input) \u2014 answer inside the Markus app.";
320511
+ }
320190
320512
  function notificationToOutbound(n2, actionSecret, locale) {
320191
320513
  const metadata = n2.metadata ?? {};
320192
320514
  const origin = {};
@@ -320205,7 +320527,13 @@ function notificationToOutbound(n2, actionSecret, locale) {
320205
320527
  origin: Object.keys(origin).length > 0 ? origin : void 0
320206
320528
  };
320207
320529
  const approvalId = typeof metadata["approvalId"] === "string" ? metadata["approvalId"] : void 0;
320208
- if (approvalId) {
320530
+ const formOnly = metadata["formOnly"] === true;
320531
+ if (approvalId && formOnly) {
320532
+ msg.body = `${body}
320533
+
320534
+ ${approvalFormNote(locale)}`;
320535
+ }
320536
+ if (approvalId && !formOnly) {
320209
320537
  const refFor = (action, explicit) => {
320210
320538
  if (typeof explicit === "string")
320211
320539
  return explicit;
@@ -320227,6 +320555,9 @@ function notificationToOutbound(n2, actionSecret, locale) {
320227
320555
  // A choice that needs a written reason says so; the renderer withholds
320228
320556
  // it on a channel that cannot collect free text.
320229
320557
  ...opt["requiresComment"] === true ? { requiresComment: true } : {},
320558
+ // A choice that is only an answer together with typed input says so;
320559
+ // the renderer withholds it on a channel that cannot collect text.
320560
+ ...opt["requiresFreeform"] === true ? { requiresFreeform: true } : {},
320230
320561
  ref: refFor(id)
320231
320562
  };
320232
320563
  }) : [
@@ -320236,6 +320567,9 @@ function notificationToOutbound(n2, actionSecret, locale) {
320236
320567
  if (msg.actions.some((a) => a.requiresComment)) {
320237
320568
  msg.commentRequiredNote = approvalCommentNote(locale);
320238
320569
  }
320570
+ if (msg.actions.some((a) => a.requiresFreeform)) {
320571
+ msg.freeformRequiredNote = approvalFreeformNote(locale);
320572
+ }
320239
320573
  }
320240
320574
  return msg;
320241
320575
  }
@@ -320286,6 +320620,7 @@ var init_dispatcher = __esm({
320286
320620
  agentName;
320287
320621
  agentTeamName;
320288
320622
  locale;
320623
+ onDelivered;
320289
320624
  /**
320290
320625
  * `info` messages waiting for a digest, each paired with the destination it
320291
320626
  * already passed eligibility for. Pairing is load-bearing: re-resolving at
@@ -320304,6 +320639,7 @@ var init_dispatcher = __esm({
320304
320639
  this.agentName = opts.agentName;
320305
320640
  this.agentTeamName = opts.agentTeamName;
320306
320641
  this.locale = opts.locale;
320642
+ this.onDelivered = opts.onDelivered;
320307
320643
  }
320308
320644
  /**
320309
320645
  * Deliver one message. `action_required` is pushed immediately; `info` is
@@ -320430,7 +320766,13 @@ var init_dispatcher = __esm({
320430
320766
  */
320431
320767
  attachNotifications(source) {
320432
320768
  return source.onChannelNotification((n2) => {
320433
- void this.dispatch(notificationToOutbound(n2, this.actionSecret, this.locale?.())).catch((err) => {
320769
+ void this.dispatch(notificationToOutbound(n2, this.actionSecret, this.locale?.())).then((outcome) => {
320770
+ try {
320771
+ this.onDelivered?.(n2, outcome);
320772
+ } catch (err) {
320773
+ log43.warn("onDelivered hook failed", { error: String(err) });
320774
+ }
320775
+ }).catch((err) => {
320434
320776
  log43.error("Failed to dispatch notification", { error: String(err) });
320435
320777
  });
320436
320778
  });
@@ -321498,13 +321840,13 @@ function createSessionTool(ctx) {
321498
321840
  if (!n2.sessionId) {
321499
321841
  return JSON.stringify({
321500
321842
  status: "error",
321501
- message: 'Compacting needs session_id. Example: { "operation": "compact", "session_id": "sess_...", "keep_last": 40 }.'
321843
+ message: `Compacting needs session_id. Example: { "operation": "compact", "session_id": "sess_...", "keep_last": ${DEFAULT_COMPACT_KEEP_LAST} }.`
321502
321844
  });
321503
321845
  }
321504
321846
  const own = checkOwnership(repo, n2.sessionId, ctx.agentId);
321505
321847
  if (own.error)
321506
321848
  return own.error;
321507
- const keepLast = Math.max(5, Math.min(200, Math.trunc(Number(n2.keepLast) || 40) || 40));
321849
+ const keepLast = Math.max(COMPACT_KEEP_LAST_MIN, Math.min(COMPACT_KEEP_LAST_MAX, Math.trunc(Number(n2.keepLast) || DEFAULT_COMPACT_KEEP_LAST) || DEFAULT_COMPACT_KEEP_LAST));
321508
321850
  try {
321509
321851
  const hasAnchor = n2.goal || n2.done || n2.next;
321510
321852
  let res;
@@ -321768,8 +322110,8 @@ function createSessionTool(ctx) {
321768
322110
  "\u2022 session_get \u2014 get one session + its messages. Args: session_id, since/until, page, page_size. Returns { status, sessionId, messages: [{role, content}], total, page }.",
321769
322111
  ' Example: { "operation": "get", "session_id": "sess_...", "page_size": 50 }',
321770
322112
  '\u2022 session_compact \u2014 collapse stale history into an anchor summary so future turns stop re-reading it. Atomic: an assistant tool-call and its tool results are NEVER split. Optionally pass goal/done/next to anchor your position. Use when earlier tool results are obsolete or context feels bloated. Returns { status, flushedCount, remaining, summary } \u2014 flushedCount = messages paged out (0 means nothing was compacted), remaining = messages kept, summary = a [SYSTEM]-prefixed anchor injected into the session; the raw flushed messages are archived and recoverable via session_retrieve. If the session already fits within keep_last you get flushedCount:0, skipped:true, reason:"within_keep_last" (a valid no-op, NOT a failure); an unknown session_id returns status:"error".',
321771
- " Args: session_id (required), keep_last (5-200, default 40), goal/done/next (optional anchors).",
321772
- ' Example: { "operation": "compact", "session_id": "sess_...", "keep_last": 40 }',
322113
+ ` Args: session_id (required), keep_last (5-200, default ${DEFAULT_COMPACT_KEEP_LAST}), goal/done/next (optional anchors).`,
322114
+ ` Example: { "operation": "compact", "session_id": "sess_...", "keep_last": ${DEFAULT_COMPACT_KEEP_LAST} }`,
321773
322115
  "\u2022 session_pin \u2014 write a durable slot into the fixed [SLOTS] segment: persisted per session and injected every turn, NEVER compacted until you unpin it. Best for your current goal / what is done / what is next (use key=goal/done/next). Returns { status, pinned: {key: content} }.",
321774
322116
  ' Args: session_id, key, content. Example: { "operation": "pin", "session_id": "sess_...", "key": "goal", "content": "..." }',
321775
322117
  "\u2022 session_unpin \u2014 remove a pinned slot. Args: session_id, key. Returns { status, unpinned: key }.",
@@ -321797,7 +322139,7 @@ function createSessionTool(ctx) {
321797
322139
  until: { type: "string", description: "ISO timestamp \u2014 filter sessions/messages with timestamp <= until." },
321798
322140
  page: { type: "number", description: "1-based page number (default 1)." },
321799
322141
  page_size: { type: "number", description: "Page size (list default 20 max 50; get default 50 max 100)." },
321800
- keep_last: { type: "number", description: "For compact: how many most-recent messages to keep verbatim (default 40, range 5-200)." },
322142
+ keep_last: { type: "number", description: `For compact: how many most-recent messages to keep verbatim (default ${DEFAULT_COMPACT_KEEP_LAST}, range ${COMPACT_KEEP_LAST_MIN}-${COMPACT_KEEP_LAST_MAX}).` },
321801
322143
  key: { type: "string", description: "For pin/unpin: the slot key (e.g. goal, done, next)." },
321802
322144
  content: { type: "string", description: "For pin: the fact/anchor text to pin (> up to 1200 chars)." },
321803
322145
  query: { type: "string", description: "For retrieve: keyword(s) to search archived fragments." },
@@ -321864,6 +322206,7 @@ var init_session = __esm({
321864
322206
  "use strict";
321865
322207
  init_dist();
321866
322208
  init_file();
322209
+ init_context_budget();
321867
322210
  log46 = createLogger("session-tools");
321868
322211
  OP_ALIASES2 = /* @__PURE__ */ new Set([
321869
322212
  "list",
@@ -328323,6 +328666,9 @@ function mergeConsecutiveToolResults(messages) {
328323
328666
  }
328324
328667
  return out;
328325
328668
  }
328669
+ function collectSystemText(messages) {
328670
+ return messages.filter((m) => m.role === "system").map((m) => getTextContent(m.content)).filter((text) => text.length > 0).join("\n\n");
328671
+ }
328326
328672
  var AnthropicProvider;
328327
328673
  var init_anthropic = __esm({
328328
328674
  "../core/dist/llm/anthropic.js"() {
@@ -328364,7 +328710,7 @@ var init_anthropic = __esm({
328364
328710
  this.streamTimeoutMs = config.streamTimeoutMs;
328365
328711
  }
328366
328712
  async chat(request) {
328367
- const systemMsg = request.messages.find((m) => m.role === "system");
328713
+ const systemText = collectSystemText(request.messages);
328368
328714
  const messages = this.convertMessages(request.messages.filter((m) => m.role !== "system"));
328369
328715
  const useCompaction = request.compaction && this.isCompactionSupported();
328370
328716
  const body = {
@@ -328372,8 +328718,8 @@ var init_anthropic = __esm({
328372
328718
  max_tokens: request.maxTokens ?? this.maxTokens,
328373
328719
  messages
328374
328720
  };
328375
- if (systemMsg) {
328376
- body["system"] = this.buildSystemContent(sanitizeForLLM(getTextContent(systemMsg.content)), request.systemCacheSegments);
328721
+ if (systemText) {
328722
+ body["system"] = this.buildSystemContent(sanitizeForLLM(systemText), request.systemCacheSegments);
328377
328723
  }
328378
328724
  if (request.temperature !== void 0)
328379
328725
  body["temperature"] = request.temperature;
@@ -328419,7 +328765,7 @@ var init_anthropic = __esm({
328419
328765
  return this.convertResponse(data);
328420
328766
  }
328421
328767
  async chatStream(request, onEvent, signal) {
328422
- const systemMsg = request.messages.find((m) => m.role === "system");
328768
+ const systemText = collectSystemText(request.messages);
328423
328769
  const messages = this.convertMessages(request.messages.filter((m) => m.role !== "system"));
328424
328770
  const useCompaction = request.compaction && this.isCompactionSupported();
328425
328771
  const body = {
@@ -328428,8 +328774,8 @@ var init_anthropic = __esm({
328428
328774
  messages,
328429
328775
  stream: true
328430
328776
  };
328431
- if (systemMsg) {
328432
- body["system"] = this.buildSystemContent(sanitizeForLLM(getTextContent(systemMsg.content)), request.systemCacheSegments);
328777
+ if (systemText) {
328778
+ body["system"] = this.buildSystemContent(sanitizeForLLM(systemText), request.systemCacheSegments);
328433
328779
  }
328434
328780
  if (request.temperature !== void 0)
328435
328781
  body["temperature"] = request.temperature;
@@ -341385,6 +341731,7 @@ __export(dist_exports3, {
341385
341731
  WebFetchTool: () => WebFetchTool,
341386
341732
  WebSearchTool: () => WebSearchTool,
341387
341733
  WorkflowEngine: () => WorkflowEngine,
341734
+ aggregateCacheHitRate: () => aggregateCacheHitRate,
341388
341735
  applyFanoutDailyCap: () => applyFanoutDailyCap,
341389
341736
  applyHubRecommendedRouting: () => applyHubRecommendedRouting,
341390
341737
  applyToolPolicy: () => applyToolPolicy,
@@ -341399,7 +341746,9 @@ __export(dist_exports3, {
341399
341746
  clearEnvironmentCache: () => clearEnvironmentCache,
341400
341747
  clearMarkusModelListCache: () => clearMarkusModelListCache,
341401
341748
  clickChromeAllowDialog: () => clickChromeAllowDialog,
341749
+ computeCacheHitRate: () => computeCacheHitRate,
341402
341750
  computeEvolutionMetrics: () => computeEvolutionMetrics,
341751
+ computeReplayRatio: () => computeReplayRatio,
341403
341752
  convertFilesToText: () => convertFilesToText,
341404
341753
  costTierFromPrice: () => costTierFromPrice,
341405
341754
  createA2ATools: () => createA2ATools,
@@ -341551,6 +341900,7 @@ var init_dist7 = __esm({
341551
341900
  init_model_catalog2();
341552
341901
  init_model_discovery();
341553
341902
  init_router2();
341903
+ init_provider_helpers();
341554
341904
  init_store();
341555
341905
  init_pending_callback();
341556
341906
  init_semantic_search();
@@ -353729,7 +354079,9 @@ ${c.content}`;
353729
354079
  approvedVia: request.approvedVia,
353730
354080
  planReportId: request.planReportId,
353731
354081
  taskType: request.taskType ?? "standard",
353732
- scheduleConfig
354082
+ scheduleConfig,
354083
+ workflowRunId: request.workflowRunId,
354084
+ workflowStepId: request.workflowStepId
353733
354085
  };
353734
354086
  this.tasks.set(task.id, task);
353735
354087
  if (this.taskRepo) {
@@ -353749,7 +354101,9 @@ ${c.content}`;
353749
354101
  blockedBy: task.blockedBy,
353750
354102
  dueAt: task.dueAt ? new Date(task.dueAt) : void 0,
353751
354103
  taskType: task.taskType,
353752
- scheduleConfig: task.scheduleConfig
354104
+ scheduleConfig: task.scheduleConfig,
354105
+ workflowRunId: task.workflowRunId,
354106
+ workflowStepId: task.workflowStepId
353753
354107
  }).catch((err) => log78.warn("Failed to persist task to DB", { error: String(err) }));
353754
354108
  }
353755
354109
  if (task.requirementId && this.requirementService) {
@@ -353935,6 +354289,51 @@ ${c.content}`;
353935
354289
  const targetStatus = hasBlockers ? "blocked" : "in_progress";
353936
354290
  return this.updateTaskStatus(taskIdStr, targetStatus, userId2, true, false, "human", "Approved");
353937
354291
  }
354292
+ /**
354293
+ * Approve every approvable task under a requirement — **as a loop over the
354294
+ * single writer** (`approveTask`), never as a second approval path.
354295
+ *
354296
+ * Consequences that matter:
354297
+ * - each task still passes the `pending` guard, the HITL settlement and the
354298
+ * gate-aware apply, so bulk cannot bypass a gate or "force" a status;
354299
+ * - ineligible tasks are *skipped with a reason* instead of silently ignored;
354300
+ * - per-task failures are reported per task (a partial run must never look
354301
+ * like a clean one);
354302
+ * - `dryRun` returns exactly what would happen, with no side effects — the
354303
+ * confirmation dialog shows real numbers, not client-side guesses;
354304
+ * - approval starts execution (standard tasks have no "approved but idle"
354305
+ * state), so callers pass `runNow` and the dialog says so out loud.
354306
+ */
354307
+ approveRequirementTasks(requirementId2, opts = {}) {
354308
+ const requirement = this.requirementService?.getRequirement(requirementId2);
354309
+ if (!requirement)
354310
+ throw new Error(`Requirement not found: ${requirementId2}`);
354311
+ const approved = [];
354312
+ const skipped = [];
354313
+ const failed = [];
354314
+ for (const taskId2 of requirement.taskIds ?? []) {
354315
+ const task = this.tasks.get(taskId2);
354316
+ if (!task) {
354317
+ skipped.push({ id: taskId2, title: "", reason: "task not found" });
354318
+ continue;
354319
+ }
354320
+ if (task.status !== "pending") {
354321
+ skipped.push({ id: task.id, title: task.title, reason: `status is ${task.status}` });
354322
+ continue;
354323
+ }
354324
+ if (opts.dryRun) {
354325
+ approved.push({ id: task.id, title: task.title });
354326
+ continue;
354327
+ }
354328
+ try {
354329
+ this.approveTask(task.id, opts.actorId, opts.runNow !== false);
354330
+ approved.push({ id: task.id, title: task.title });
354331
+ } catch (err) {
354332
+ failed.push({ id: task.id, title: task.title, error: err instanceof Error ? err.message : String(err) });
354333
+ }
354334
+ }
354335
+ return { approved, skipped, failed };
354336
+ }
353938
354337
  rejectTask(taskIdStr, userId2) {
353939
354338
  const task = this.tasks.get(taskIdStr);
353940
354339
  if (!task)
@@ -357837,6 +358236,701 @@ var init_builder_service = __esm({
357837
358236
  }
357838
358237
  });
357839
358238
 
358239
+ // ../org-manager/dist/hitl-service.js
358240
+ function normalizeIntentToken(raw) {
358241
+ return raw.trim().toLowerCase().replace(/[\s-]+/g, "_");
358242
+ }
358243
+ function intentToApprovalStatus(intent) {
358244
+ if (intent === "approve")
358245
+ return "approved";
358246
+ if (intent === "reject")
358247
+ return "rejected";
358248
+ return "changes_requested";
358249
+ }
358250
+ function resolveApprovalIntent(input) {
358251
+ const raw = input.selectedOption?.trim();
358252
+ if (raw) {
358253
+ const token = normalizeIntentToken(raw);
358254
+ const gate = input.subType ? GATE_OPTION_ALIASES[input.subType] : void 0;
358255
+ const gateAlias = gate?.[token];
358256
+ if (gateAlias)
358257
+ return { intent: gateAlias };
358258
+ const intent = GLOBAL_INTENT_TOKENS[token];
358259
+ if (intent)
358260
+ return { intent };
358261
+ return gate ? { intent: input.approved ? "approve" : "reject", unknownOption: raw } : { intent: input.approved ? "approve" : "reject" };
358262
+ }
358263
+ return { intent: input.approved ? "approve" : "reject" };
358264
+ }
358265
+ function genId(prefix) {
358266
+ return `${prefix}_${Date.now().toString(36)}_${(++idCounter).toString(36)}`;
358267
+ }
358268
+ function answersFromTap(approval, selectedOption, comment) {
358269
+ const questions = approval.questions ?? [];
358270
+ if (questions.length !== 1)
358271
+ return void 0;
358272
+ const question = questions[0];
358273
+ if (question.inputType !== "choice" || question.allowMultiple === true)
358274
+ return void 0;
358275
+ if (!selectedOption)
358276
+ return void 0;
358277
+ const ids = (question.options ?? []).map((o) => o.id);
358278
+ if (!ids.includes(selectedOption))
358279
+ return void 0;
358280
+ const text = (comment ?? "").trim();
358281
+ return [
358282
+ {
358283
+ questionId: question.id,
358284
+ selectedOptionIds: [selectedOption],
358285
+ ...text ? { text } : {}
358286
+ }
358287
+ ];
358288
+ }
358289
+ function isAnswerableByTap(questions, options) {
358290
+ if (!questions || questions.length === 0) {
358291
+ return !options || options.every((o) => o.requiresFreeform !== true);
358292
+ }
358293
+ if (questions.length > 1)
358294
+ return false;
358295
+ const q = questions[0];
358296
+ if (q.inputType !== "choice")
358297
+ return false;
358298
+ if (q.allowMultiple === true)
358299
+ return false;
358300
+ return (q.options ?? []).every((o) => o.requiresFreeform !== true);
358301
+ }
358302
+ function assessResponseCompleteness(approval, selectedOption, comment, answers) {
358303
+ const commentText = (comment ?? "").trim();
358304
+ const missing = [];
358305
+ const selected = selectedOption ? approval.options?.find((o) => o.id === selectedOption) : void 0;
358306
+ if (selected?.requiresFreeform && commentText.length === 0) {
358307
+ missing.push(`option:${selected.id}`);
358308
+ }
358309
+ const byQuestion = new Map((answers ?? []).map((a) => [a.questionId, a]));
358310
+ for (const question of approval.questions ?? []) {
358311
+ const answer = byQuestion.get(question.id);
358312
+ const picked = answer?.selectedOptionIds ?? [];
358313
+ const text = (answer?.text ?? "").trim();
358314
+ if (question.inputType === "text") {
358315
+ if (text.length === 0)
358316
+ missing.push(`question:${question.id}:text`);
358317
+ continue;
358318
+ }
358319
+ if (picked.length === 0 && text.length === 0) {
358320
+ missing.push(`question:${question.id}:unanswered`);
358321
+ continue;
358322
+ }
358323
+ for (const id of picked) {
358324
+ const opt = question.options?.find((o) => o.id === id);
358325
+ if (opt?.requiresFreeform && text.length === 0) {
358326
+ missing.push(`question:${question.id}:option:${opt.id}:text`);
358327
+ }
358328
+ }
358329
+ }
358330
+ return missing.length > 0 ? { incomplete: true, missing } : void 0;
358331
+ }
358332
+ var log81, GLOBAL_INTENT_TOKENS, GATE_OPTION_ALIASES, APPROVALS_IN_MEMORY_CAP, idCounter, HITLService;
358333
+ var init_hitl_service = __esm({
358334
+ "../org-manager/dist/hitl-service.js"() {
358335
+ "use strict";
358336
+ init_dist();
358337
+ log81 = createLogger("hitl");
358338
+ GLOBAL_INTENT_TOKENS = {
358339
+ approve: "approve",
358340
+ approved: "approve",
358341
+ request_changes: "request_changes",
358342
+ requestchanges: "request_changes",
358343
+ changes_requested: "request_changes",
358344
+ revision: "request_changes",
358345
+ needs_adjustment: "needs_adjustment",
358346
+ needsadjustment: "needs_adjustment",
358347
+ reject: "reject",
358348
+ rejected: "reject"
358349
+ };
358350
+ GATE_OPTION_ALIASES = {
358351
+ task_review: { reject: "request_changes" }
358352
+ };
358353
+ APPROVALS_IN_MEMORY_CAP = 200;
358354
+ idCounter = 0;
358355
+ HITLService = class {
358356
+ approvals = /* @__PURE__ */ new Map();
358357
+ pendingResolvers = /* @__PURE__ */ new Map();
358358
+ /**
358359
+ * The router that drives a **recorded decision** to its gate.
358360
+ *
358361
+ * Set once by the composition root. Deliberately owned by this service rather
358362
+ * than by any inbound surface: recording a decision and applying it must not be
358363
+ * two independent obligations, because a surface that honours only the first
358364
+ * one fails **silently** — the 2026-10-16 Feishu card tap that recorded
358365
+ * "approved" while the task stayed `pending`, because the only thing that knew
358366
+ * how to apply it was an in-memory promise that had died with the last restart.
358367
+ * Routing at the single point where a decision is written makes that omission
358368
+ * unrepresentable for every surface, present and future.
358369
+ */
358370
+ decisionRouter;
358371
+ notificationHandlers = [];
358372
+ /**
358373
+ * Channel-level consumers — the outbound gateway. Deliberately a **separate**
358374
+ * list from {@link notificationHandlers}: the two answer different questions.
358375
+ * "Who should see this in their bell" is per *person* (N emissions for
358376
+ * `targetUserId:'all'`); "one channel message per logical notification" is per
358377
+ * *channel* (exactly one). Sharing one list is the granularity confusion that
358378
+ * made a single notification reach a Feishu group N times (req_d25dc9b9).
358379
+ */
358380
+ channelNotificationHandlers = [];
358381
+ /**
358382
+ * Approval-lifecycle consumers. A terminal transition (approved / rejected /
358383
+ * cancelled / expired) is a change to authoritative state that **every**
358384
+ * derived surface must observe — the in-app chat banner, the bell, any other
358385
+ * client. Deliberately separate from the notification streams: notifications
358386
+ * answer "tell this person", this one answers "the state changed".
358387
+ *
358388
+ * The emission lives at the transition itself (not at each call site) because
358389
+ * a decision can be written from ≥3 places — the HTTP API, the in-process
358390
+ * platform-action path, and the expiry timer. Wiring only the HTTP path is
358391
+ * exactly how the chat banner used to linger forever after an approval was
358392
+ * settled from Feishu (the resolving surface was not the one polling).
358393
+ */
358394
+ approvalChangeHandlers = [];
358395
+ notificationRepo;
358396
+ approvalRepo;
358397
+ orgService;
358398
+ setOrgService(service) {
358399
+ this.orgService = service;
358400
+ }
358401
+ setNotificationRepo(repo) {
358402
+ this.notificationRepo = repo;
358403
+ try {
358404
+ const healed = repo.reconcileResolvedApprovalNotifications?.() ?? 0;
358405
+ if (healed > 0)
358406
+ log81.info(`Reconciled ${healed} stale unread approval notification(s)`);
358407
+ } catch (err) {
358408
+ log81.warn("Failed to reconcile stale approval notifications", { error: String(err) });
358409
+ }
358410
+ }
358411
+ /**
358412
+ * Wire the router that applies a recorded decision to its gate. Called once by
358413
+ * the composition root; see {@link decisionRouter} for why it lives here.
358414
+ */
358415
+ setDecisionRouter(router) {
358416
+ this.decisionRouter = router;
358417
+ }
358418
+ setApprovalRepo(repo) {
358419
+ this.approvalRepo = repo;
358420
+ try {
358421
+ const rows = repo.list({ limit: APPROVALS_IN_MEMORY_CAP });
358422
+ for (const row of rows) {
358423
+ if (!this.approvals.has(row.id))
358424
+ this.approvals.set(row.id, this.rowToApproval(row));
358425
+ }
358426
+ log81.info(`Restored ${rows.length} approvals from storage`);
358427
+ } catch (err) {
358428
+ log81.warn("Failed to restore approvals from storage", { error: String(err) });
358429
+ }
358430
+ }
358431
+ /**
358432
+ * Paged, time-ordered approval read — the ONE read path for the list API.
358433
+ *
358434
+ * Two defects this replaces (owner report 2026-10-18 "审批似乎没法加载历史"):
358435
+ * - The map only mirrors the newest {@link APPROVALS_IN_MEMORY_CAP} rows, so
358436
+ * slicing the map could never reach real history.
358437
+ * - `slice(offset, offset+limit)` over the map followed INSERTION order, and
358438
+ * the restore inserts the startup snapshot first — every approval requested
358439
+ * after startup landed at the END of the map and never appeared on page 1.
358440
+ * The pending approvals were literally invisible in the bell.
358441
+ */
358442
+ listApprovalsPage(opts) {
358443
+ const { status, limit, offset: offset2 } = opts;
358444
+ if (this.approvalRepo) {
358445
+ try {
358446
+ const rows = this.approvalRepo.list({ status, limit, offset: offset2 });
358447
+ const total = this.approvalRepo.count ? this.approvalRepo.count(status) : rows.length;
358448
+ return { approvals: rows.map((r) => this.rowToApproval(r)), total };
358449
+ } catch (err) {
358450
+ log81.warn("Approval repo paging failed \u2014 falling back to memory", { error: String(err) });
358451
+ }
358452
+ }
358453
+ const all = [...this.approvals.values()].filter((a) => !status || a.status === status).sort((a, b) => new Date(b.requestedAt).getTime() - new Date(a.requestedAt).getTime());
358454
+ return { approvals: all.slice(offset2, offset2 + limit), total: all.length };
358455
+ }
358456
+ /** Single mapping from persisted row → domain object (restore + paging share it). */
358457
+ rowToApproval(row) {
358458
+ return {
358459
+ id: row.id,
358460
+ agentId: row.agentId,
358461
+ agentName: row.agentName,
358462
+ type: row.type,
358463
+ title: row.title,
358464
+ description: row.description,
358465
+ details: row.details,
358466
+ status: row.status,
358467
+ requestedAt: row.requestedAt,
358468
+ respondedAt: row.respondedAt,
358469
+ respondedBy: row.respondedBy,
358470
+ responseComment: row.responseComment,
358471
+ expiresAt: row.expiresAt,
358472
+ options: row.options,
358473
+ allowFreeform: row.allowFreeform,
358474
+ selectedOption: row.selectedOption,
358475
+ appliedAt: row.appliedAt,
358476
+ appliedIntent: row.appliedIntent,
358477
+ questions: row.questions,
358478
+ answers: row.answers,
358479
+ approverUserIds: row.approverUserIds,
358480
+ targetUserId: row.targetUserId
358481
+ };
358482
+ }
358483
+ /**
358484
+ * Per-person stream. Fires **once per human recipient** — `targetUserId:'all'`
358485
+ * fans out to N emissions by design (the in-app bell / WS push is per person).
358486
+ * Consumers that address a concrete user subscribe here.
358487
+ */
358488
+ onNotification(handler4) {
358489
+ this.notificationHandlers.push(handler4);
358490
+ return () => {
358491
+ const idx = this.notificationHandlers.indexOf(handler4);
358492
+ if (idx >= 0)
358493
+ this.notificationHandlers.splice(idx, 1);
358494
+ };
358495
+ }
358496
+ /**
358497
+ * Channel-level stream — the single granularity the outbound gateway needs:
358498
+ * fires **exactly once per `notify()` call**, no matter how many humans the
358499
+ * notification fans out to. This is what structurally guarantees "one logical
358500
+ * notification ⇒ one channel message", instead of leaving the dispatcher to
358501
+ * de-duplicate N per-person emissions (req_d25dc9b9).
358502
+ */
358503
+ onChannelNotification(handler4) {
358504
+ this.channelNotificationHandlers.push(handler4);
358505
+ return () => {
358506
+ const idx = this.channelNotificationHandlers.indexOf(handler4);
358507
+ if (idx >= 0)
358508
+ this.channelNotificationHandlers.splice(idx, 1);
358509
+ };
358510
+ }
358511
+ /**
358512
+ * Approval-lifecycle stream. Fires exactly once per terminal transition,
358513
+ * whichever surface caused it (in-app modal, Feishu card tap, expiry timer).
358514
+ * Consumers invalidate their derived views from this — that is what makes an
358515
+ * approval decided in an external IM disappear from the in-app banner too.
358516
+ */
358517
+ onApprovalChanged(handler4) {
358518
+ this.approvalChangeHandlers.push(handler4);
358519
+ return () => {
358520
+ const idx = this.approvalChangeHandlers.indexOf(handler4);
358521
+ if (idx >= 0)
358522
+ this.approvalChangeHandlers.splice(idx, 1);
358523
+ };
358524
+ }
358525
+ emit(n2) {
358526
+ for (const h of this.notificationHandlers) {
358527
+ try {
358528
+ h(n2);
358529
+ } catch {
358530
+ }
358531
+ }
358532
+ }
358533
+ emitChannel(n2) {
358534
+ for (const h of this.channelNotificationHandlers) {
358535
+ try {
358536
+ h(n2);
358537
+ } catch {
358538
+ }
358539
+ }
358540
+ }
358541
+ emitApprovalChanged(approval) {
358542
+ for (const h of this.approvalChangeHandlers) {
358543
+ try {
358544
+ h(approval);
358545
+ } catch {
358546
+ }
358547
+ }
358548
+ }
358549
+ requestApproval(opts) {
358550
+ const id = genId("apr");
358551
+ const now3 = (/* @__PURE__ */ new Date()).toISOString();
358552
+ const approval = {
358553
+ id,
358554
+ agentId: opts.agentId,
358555
+ agentName: opts.agentName,
358556
+ type: opts.type,
358557
+ title: opts.title,
358558
+ description: opts.description,
358559
+ details: opts.details ?? {},
358560
+ status: "pending",
358561
+ requestedAt: now3,
358562
+ expiresAt: opts.expiresInMs ? new Date(Date.now() + opts.expiresInMs).toISOString() : void 0,
358563
+ options: opts.options,
358564
+ allowFreeform: opts.allowFreeform,
358565
+ questions: opts.questions,
358566
+ approverUserIds: opts.approverUserIds,
358567
+ targetUserId: opts.targetUserId
358568
+ };
358569
+ this.approvals.set(id, approval);
358570
+ this.persistApproval(approval);
358571
+ log81.info(`Approval requested: ${id} by ${opts.agentName}`);
358572
+ this.notify({
358573
+ targetUserId: opts.targetUserId ?? "all",
358574
+ type: "approval_request",
358575
+ title: opts.title,
358576
+ body: opts.description,
358577
+ priority: "high",
358578
+ actionType: "navigate",
358579
+ actionTarget: JSON.stringify({ path: `/approvals/${id}` }),
358580
+ // `agentId` travels with the notification so the outbound gateway can route
358581
+ // it to the producing agent's own channel before falling back to the global
358582
+ // default (G4, design §7.3).
358583
+ // `formOnly`:这张单子**一次点击答不完**(多问题 / 多选 / 文本题 / 需填字的选项)。
358584
+ // 渠道收到它就不得把「同意/拒绝」当答案按钮发出去,改说“请到应用内回答”。
358585
+ // 判定与校验同源(`isAnswerableByTap`),所以不存在“卡片能点、服务端却拒收”。
358586
+ metadata: {
358587
+ approvalId: id,
358588
+ agentId: opts.agentId,
358589
+ options: opts.options,
358590
+ i18n: opts.i18n,
358591
+ ...isAnswerableByTap(opts.questions, opts.options) ? {} : { formOnly: true }
358592
+ }
358593
+ });
358594
+ return approval;
358595
+ }
358596
+ async requestApprovalAndWait(opts) {
358597
+ const approval = this.requestApproval(opts);
358598
+ return new Promise((resolve27) => {
358599
+ this.pendingResolvers.set(approval.id, resolve27);
358600
+ if (opts.expiresInMs) {
358601
+ setTimeout(() => {
358602
+ if (this.pendingResolvers.has(approval.id)) {
358603
+ this.pendingResolvers.delete(approval.id);
358604
+ const a = this.approvals.get(approval.id);
358605
+ if (a && a.status === "pending") {
358606
+ a.status = "expired";
358607
+ a.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
358608
+ a.responseComment = "Approval timed out";
358609
+ this.persistApproval(a);
358610
+ this.markApprovalNotificationsRead(a.id);
358611
+ this.emitApprovalChanged(a);
358612
+ }
358613
+ resolve27({ approved: false, intent: "reject", approvalId: approval.id, comment: "Approval timed out" });
358614
+ }
358615
+ }, opts.expiresInMs);
358616
+ }
358617
+ });
358618
+ }
358619
+ respondToApproval(id, approved, respondedBy, comment, selectedOption, answers) {
358620
+ const approval = this.approvals.get(id);
358621
+ if (!approval || approval.status !== "pending")
358622
+ return void 0;
358623
+ const resolvedAnswers = answers ?? answersFromTap(approval, selectedOption, comment);
358624
+ const incompleteResponse = assessResponseCompleteness(approval, selectedOption, comment, resolvedAnswers);
358625
+ if (incompleteResponse) {
358626
+ log81.warn("Refused an incomplete approval response \u2014 the chosen option needs typed input", {
358627
+ approvalId: id,
358628
+ selectedOption,
358629
+ missing: incompleteResponse.missing
358630
+ });
358631
+ return void 0;
358632
+ }
358633
+ const subType = approval.details["subType"];
358634
+ const decision = resolveApprovalIntent({ subType, selectedOption, approved });
358635
+ approval.status = intentToApprovalStatus(decision.intent);
358636
+ approval.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
358637
+ approval.respondedBy = respondedBy;
358638
+ if (comment)
358639
+ approval.responseComment = comment;
358640
+ if (selectedOption)
358641
+ approval.selectedOption = selectedOption;
358642
+ if (resolvedAnswers && resolvedAnswers.length > 0)
358643
+ approval.answers = resolvedAnswers;
358644
+ if (decision.unknownOption)
358645
+ approval.details["unknownOption"] = decision.unknownOption;
358646
+ this.persistApproval(approval);
358647
+ log81.info(`Approval ${id} ${approval.status} (intent=${decision.intent}) by ${respondedBy}`, {
358648
+ comment,
358649
+ selectedOption,
358650
+ unknownOption: decision.unknownOption,
358651
+ answerCount: resolvedAnswers?.length ?? 0
358652
+ });
358653
+ this.markApprovalNotificationsRead(id);
358654
+ this.emitApprovalChanged(approval);
358655
+ const resolve27 = this.pendingResolvers.get(id);
358656
+ if (resolve27) {
358657
+ this.pendingResolvers.delete(id);
358658
+ resolve27({
358659
+ approved: decision.intent === "approve",
358660
+ intent: decision.intent,
358661
+ approvalId: approval.id,
358662
+ comment,
358663
+ selectedOption,
358664
+ answers: resolvedAnswers,
358665
+ respondedBy,
358666
+ ...decision.unknownOption ? { unknownOption: decision.unknownOption } : {}
358667
+ });
358668
+ }
358669
+ const response = { approval, decision };
358670
+ if (this.decisionRouter) {
358671
+ queueMicrotask(() => this.decisionRouter?.(response));
358672
+ }
358673
+ return response;
358674
+ }
358675
+ /**
358676
+ * Synchronous, check-and-set claim for "apply this approval decision to its
358677
+ * target". Both consumers (the promise chain and the API fallback) call this
358678
+ * before doing anything observable; only the winner may act.
358679
+ *
358680
+ * Deliberately keyed on the **approval entity** (persisted `appliedAt`):
358681
+ * · target state is unusable — two of the three gates intentionally perform
358682
+ * zero state transition, so a state-based guard would never fire;
358683
+ * · `approval.status` is unusable — {@link respondToApproval} flips it first,
358684
+ * which would make the *first* apply look like a duplicate.
358685
+ *
358686
+ * Synchronous by contract: no `await` between read and write, so the guard and
358687
+ * the microtask that follows a resolved promise can never interleave.
358688
+ */
358689
+ claimApply(id, intent) {
358690
+ const approval = this.approvals.get(id);
358691
+ if (!approval)
358692
+ return false;
358693
+ if (approval.appliedAt)
358694
+ return false;
358695
+ approval.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
358696
+ approval.appliedIntent = intent;
358697
+ this.persistApproval(approval);
358698
+ log81.info("Approval decision claimed for apply", { id, intent });
358699
+ return true;
358700
+ }
358701
+ cancelApproval(id, cancelledBy, comment) {
358702
+ const approval = this.approvals.get(id);
358703
+ if (!approval || approval.status !== "pending")
358704
+ return void 0;
358705
+ approval.status = "cancelled";
358706
+ approval.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
358707
+ approval.respondedBy = cancelledBy;
358708
+ if (comment)
358709
+ approval.responseComment = comment;
358710
+ this.persistApproval(approval);
358711
+ log81.info(`Approval ${id} cancelled by ${cancelledBy}`, { comment });
358712
+ this.markApprovalNotificationsRead(id);
358713
+ this.emitApprovalChanged(approval);
358714
+ const resolve27 = this.pendingResolvers.get(id);
358715
+ if (resolve27) {
358716
+ this.pendingResolvers.delete(id);
358717
+ resolve27({
358718
+ approved: false,
358719
+ intent: "reject",
358720
+ approvalId: approval.id,
358721
+ comment: comment ?? "Approval cancelled"
358722
+ });
358723
+ }
358724
+ return approval;
358725
+ }
358726
+ cancelApprovalsByDetail(key2, value, cancelledBy, comment) {
358727
+ let count = 0;
358728
+ for (const approval of this.approvals.values()) {
358729
+ if (approval.status === "pending" && approval.details[key2] === value) {
358730
+ this.cancelApproval(approval.id, cancelledBy, comment);
358731
+ count++;
358732
+ }
358733
+ }
358734
+ return count;
358735
+ }
358736
+ persistApproval(approval) {
358737
+ if (!this.approvalRepo)
358738
+ return;
358739
+ try {
358740
+ this.approvalRepo.upsert({
358741
+ id: approval.id,
358742
+ agentId: approval.agentId,
358743
+ agentName: approval.agentName,
358744
+ type: approval.type,
358745
+ title: approval.title,
358746
+ description: approval.description,
358747
+ details: approval.details,
358748
+ status: approval.status,
358749
+ requestedAt: approval.requestedAt,
358750
+ respondedAt: approval.respondedAt,
358751
+ respondedBy: approval.respondedBy,
358752
+ responseComment: approval.responseComment,
358753
+ expiresAt: approval.expiresAt,
358754
+ options: approval.options,
358755
+ allowFreeform: approval.allowFreeform,
358756
+ selectedOption: approval.selectedOption,
358757
+ appliedAt: approval.appliedAt,
358758
+ appliedIntent: approval.appliedIntent,
358759
+ questions: approval.questions,
358760
+ answers: approval.answers,
358761
+ approverUserIds: approval.approverUserIds,
358762
+ targetUserId: approval.targetUserId
358763
+ });
358764
+ } catch (err) {
358765
+ log81.warn("Failed to persist approval", { id: approval.id, error: String(err) });
358766
+ }
358767
+ }
358768
+ listApprovals(status) {
358769
+ const all = [...this.approvals.values()];
358770
+ return status ? all.filter((a) => a.status === status) : all;
358771
+ }
358772
+ getApproval(id) {
358773
+ return this.approvals.get(id);
358774
+ }
358775
+ listNotifications(userId2, unreadOnly = false, opts) {
358776
+ if (this.notificationRepo && userId2) {
358777
+ const rows = this.notificationRepo.list(userId2, {
358778
+ unreadOnly,
358779
+ limit: opts?.limit,
358780
+ offset: opts?.offset,
358781
+ type: opts?.type
358782
+ });
358783
+ return rows.map((r) => this.rowToNotification(r));
358784
+ }
358785
+ return [];
358786
+ }
358787
+ countNotifications(userId2, unreadOnly = false) {
358788
+ if (this.notificationRepo) {
358789
+ return {
358790
+ total: this.notificationRepo.count(userId2, false),
358791
+ unread: this.notificationRepo.count(userId2, true)
358792
+ };
358793
+ }
358794
+ return { total: 0, unread: 0 };
358795
+ }
358796
+ markNotificationRead(id) {
358797
+ if (this.notificationRepo) {
358798
+ return this.notificationRepo.markRead(id);
358799
+ }
358800
+ return false;
358801
+ }
358802
+ markAllNotificationsRead(userId2) {
358803
+ if (this.notificationRepo) {
358804
+ return this.notificationRepo.markAllRead(userId2);
358805
+ }
358806
+ return 0;
358807
+ }
358808
+ notify(opts) {
358809
+ let targetUserIds;
358810
+ if (opts.targetUserId === "all") {
358811
+ if (this.orgService) {
358812
+ const humans = this.orgService.listHumanUsers("default");
358813
+ targetUserIds = humans.map((h) => h.id);
358814
+ if (targetUserIds.length === 0)
358815
+ targetUserIds = ["all"];
358816
+ } else {
358817
+ targetUserIds = ["all"];
358818
+ }
358819
+ } else {
358820
+ targetUserIds = [opts.targetUserId];
358821
+ }
358822
+ if (opts.excludeUserIds?.length) {
358823
+ const skip = new Set(opts.excludeUserIds);
358824
+ targetUserIds = targetUserIds.filter((id) => !skip.has(id));
358825
+ }
358826
+ if (targetUserIds.length === 0) {
358827
+ const n2 = this.buildNotification({ ...opts });
358828
+ this.emitChannel(n2);
358829
+ return n2;
358830
+ }
358831
+ let first;
358832
+ for (const targetUserId of targetUserIds) {
358833
+ const n2 = this.notifySingle({ ...opts, targetUserId });
358834
+ first ??= n2;
358835
+ }
358836
+ this.emitChannel(this.buildNotification({ ...opts }));
358837
+ return first;
358838
+ }
358839
+ /**
358840
+ * Assemble the notification shape — the **single** place the fields are built,
358841
+ * shared by the persisted per-person row and the logical channel event.
358842
+ */
358843
+ buildNotification(opts) {
358844
+ return {
358845
+ id: genId("ntf"),
358846
+ targetUserId: opts.targetUserId,
358847
+ type: opts.type,
358848
+ title: opts.title,
358849
+ body: opts.body,
358850
+ priority: opts.priority ?? "normal",
358851
+ read: false,
358852
+ actionType: opts.actionType ?? "none",
358853
+ actionTarget: opts.actionTarget,
358854
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
358855
+ metadata: opts.metadata
358856
+ };
358857
+ }
358858
+ notifySingle(opts) {
358859
+ const notification = this.buildNotification(opts);
358860
+ if (this.notificationRepo) {
358861
+ try {
358862
+ this.notificationRepo.insert({
358863
+ id: notification.id,
358864
+ userId: notification.targetUserId,
358865
+ type: notification.type,
358866
+ title: notification.title,
358867
+ body: notification.body,
358868
+ priority: notification.priority,
358869
+ read: false,
358870
+ actionType: notification.actionType,
358871
+ actionTarget: notification.actionTarget ?? null,
358872
+ metadata: notification.metadata ?? null,
358873
+ createdAt: notification.createdAt
358874
+ });
358875
+ } catch (err) {
358876
+ log81.warn("Failed to persist notification", { error: String(err) });
358877
+ }
358878
+ }
358879
+ this.emit(notification);
358880
+ return notification;
358881
+ }
358882
+ /** Mark unread approval_request rows for this approval read, across every user_id. */
358883
+ markApprovalNotificationsRead(approvalId) {
358884
+ if (!this.notificationRepo)
358885
+ return;
358886
+ if (this.notificationRepo.markReadByApprovalId) {
358887
+ try {
358888
+ this.notificationRepo.markReadByApprovalId(approvalId);
358889
+ return;
358890
+ } catch (err) {
358891
+ log81.warn("Failed to mark approval notifications read by approvalId", {
358892
+ approvalId,
358893
+ error: String(err)
358894
+ });
358895
+ }
358896
+ }
358897
+ const userIds = /* @__PURE__ */ new Set(["all"]);
358898
+ if (this.orgService) {
358899
+ for (const h of this.orgService.listHumanUsers("default")) {
358900
+ userIds.add(h.id);
358901
+ }
358902
+ }
358903
+ for (const userId2 of userIds) {
358904
+ try {
358905
+ const rows = this.notificationRepo.list(userId2, { type: "approval_request", limit: 200 });
358906
+ for (const row of rows) {
358907
+ if (row.metadata && row.metadata.approvalId === approvalId && !row.read) {
358908
+ this.notificationRepo.markRead(row.id);
358909
+ }
358910
+ }
358911
+ } catch {
358912
+ }
358913
+ }
358914
+ }
358915
+ rowToNotification(r) {
358916
+ return {
358917
+ id: r.id,
358918
+ targetUserId: r.userId,
358919
+ type: r.type,
358920
+ title: r.title,
358921
+ body: r.body,
358922
+ priority: r.priority,
358923
+ read: r.read,
358924
+ actionType: r.actionType,
358925
+ actionTarget: r.actionTarget ?? void 0,
358926
+ createdAt: r.createdAt,
358927
+ metadata: r.metadata ?? void 0
358928
+ };
358929
+ }
358930
+ };
358931
+ }
358932
+ });
358933
+
357840
358934
  // ../org-manager/dist/approval-apply.js
357841
358935
  function targetOfApproval(details) {
357842
358936
  const d = details ?? {};
@@ -357853,19 +358947,19 @@ function routeRecordedDecision(applier, approval, decision, opts) {
357853
358947
  intent: decision.intent,
357854
358948
  actorId: opts?.actorId ?? approval.respondedBy,
357855
358949
  comment: opts?.comment ?? approval.responseComment
357856
- }).catch((err) => log81.error("Routing a recorded approval decision threw unexpectedly", {
358950
+ }).catch((err) => log82.error("Routing a recorded approval decision threw unexpectedly", {
357857
358951
  approvalId: approval.id,
357858
358952
  subType,
357859
358953
  targetId,
357860
358954
  error: String(err)
357861
358955
  }));
357862
358956
  }
357863
- var log81, APPROVAL_GATE_SUB_TYPES, ApprovalApplier;
358957
+ var log82, APPROVAL_GATE_SUB_TYPES, ApprovalApplier;
357864
358958
  var init_approval_apply = __esm({
357865
358959
  "../org-manager/dist/approval-apply.js"() {
357866
358960
  "use strict";
357867
358961
  init_dist();
357868
- log81 = createLogger("approval-apply");
358962
+ log82 = createLogger("approval-apply");
357869
358963
  APPROVAL_GATE_SUB_TYPES = ["task", "task_review", "requirement", "requirement_resubmit"];
357870
358964
  ApprovalApplier = class {
357871
358965
  hitlService;
@@ -357877,7 +358971,7 @@ var init_approval_apply = __esm({
357877
358971
  for (const subType of port.approvalGateSubTypes) {
357878
358972
  const existing = this.ports.get(subType);
357879
358973
  if (existing && existing !== port) {
357880
- log81.warn("Overriding approval gate port", { subType });
358974
+ log82.warn("Overriding approval gate port", { subType });
357881
358975
  }
357882
358976
  this.ports.set(subType, port);
357883
358977
  }
@@ -357896,7 +358990,7 @@ var init_approval_apply = __esm({
357896
358990
  const base = { approvalId, subType, intent, targetId };
357897
358991
  const port = this.ports.get(subType);
357898
358992
  if (!port || !targetId) {
357899
- log81.warn("Approval decision has no routable gate \u2014 ignoring", { approvalId, subType, targetId, intent });
358993
+ log82.warn("Approval decision has no routable gate \u2014 ignoring", { approvalId, subType, targetId, intent });
357900
358994
  return { ...base, applied: false, reason: "unrouted" };
357901
358995
  }
357902
358996
  if (!port.canApplyApproval(subType, targetId)) {
@@ -357909,7 +359003,7 @@ var init_approval_apply = __esm({
357909
359003
  await port.applyApprovalDecision(input);
357910
359004
  return { ...base, applied: true, reason: "applied" };
357911
359005
  } catch (err) {
357912
- log81.error("Approval decision apply failed after routing", {
359006
+ log82.error("Approval decision apply failed after routing", {
357913
359007
  approvalId,
357914
359008
  subType,
357915
359009
  targetId,
@@ -358058,12 +359152,12 @@ var init_session_title = __esm({
358058
359152
 
358059
359153
  // ../org-manager/dist/ws-server.js
358060
359154
  import { WebSocketServer as WebSocketServer2, WebSocket as WebSocket2 } from "ws";
358061
- var log82, COALESCE_INTERVAL_MS, COALESCE_EVENT_TYPES, WSBroadcaster;
359155
+ var log83, COALESCE_INTERVAL_MS, COALESCE_EVENT_TYPES, WSBroadcaster;
358062
359156
  var init_ws_server = __esm({
358063
359157
  "../org-manager/dist/ws-server.js"() {
358064
359158
  "use strict";
358065
359159
  init_dist();
358066
- log82 = createLogger("ws-server");
359160
+ log83 = createLogger("ws-server");
358067
359161
  COALESCE_INTERVAL_MS = 200;
358068
359162
  COALESCE_EVENT_TYPES = /* @__PURE__ */ new Set([
358069
359163
  "agent:update",
@@ -358101,7 +359195,7 @@ var init_ws_server = __esm({
358101
359195
  }
358102
359196
  } catch {
358103
359197
  }
358104
- log82.info("WebSocket client connected", {
359198
+ log83.info("WebSocket client connected", {
358105
359199
  clients: this.clients.size,
358106
359200
  userScoped: !!trackedUserId
358107
359201
  });
@@ -358118,10 +359212,10 @@ var init_ws_server = __esm({
358118
359212
  ws.on("close", () => {
358119
359213
  this.clients.delete(ws);
358120
359214
  detachUser();
358121
- log82.debug("WebSocket client disconnected", { clients: this.clients.size });
359215
+ log83.debug("WebSocket client disconnected", { clients: this.clients.size });
358122
359216
  });
358123
359217
  ws.on("error", (err) => {
358124
- log82.error("WebSocket client error", { error: String(err) });
359218
+ log83.error("WebSocket client error", { error: String(err) });
358125
359219
  this.clients.delete(ws);
358126
359220
  detachUser();
358127
359221
  });
@@ -358131,7 +359225,7 @@ var init_ws_server = __esm({
358131
359225
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
358132
359226
  }));
358133
359227
  });
358134
- log82.info("WebSocket server attached");
359228
+ log83.info("WebSocket server attached");
358135
359229
  }
358136
359230
  sendToUser(userId2, event) {
358137
359231
  this.sendToUsers([userId2], event);
@@ -358276,12 +359370,12 @@ var init_ws_server = __esm({
358276
359370
  });
358277
359371
 
358278
359372
  // ../org-manager/dist/sse-buffer.js
358279
- var log83, SSEBuffer;
359373
+ var log84, SSEBuffer;
358280
359374
  var init_sse_buffer = __esm({
358281
359375
  "../org-manager/dist/sse-buffer.js"() {
358282
359376
  "use strict";
358283
359377
  init_dist();
358284
- log83 = createLogger("sse-buffer");
359378
+ log84 = createLogger("sse-buffer");
358285
359379
  SSEBuffer = class {
358286
359380
  response;
358287
359381
  buffer = [];
@@ -358327,7 +359421,7 @@ var init_sse_buffer = __esm({
358327
359421
  this.close();
358328
359422
  });
358329
359423
  this.response.on("error", (err) => {
358330
- log83.error("SSE response error", { error: String(err) });
359424
+ log84.error("SSE response error", { error: String(err) });
358331
359425
  this.close();
358332
359426
  });
358333
359427
  }
@@ -358346,7 +359440,7 @@ var init_sse_buffer = __esm({
358346
359440
  this.droppedAfterClose++;
358347
359441
  if (!this.closedWarnLogged) {
358348
359442
  this.closedWarnLogged = true;
358349
- log83.warn("SSE connection closed \u2014 further messages will be silently dropped");
359443
+ log84.warn("SSE connection closed \u2014 further messages will be silently dropped");
358350
359444
  }
358351
359445
  return;
358352
359446
  }
@@ -358375,7 +359469,7 @@ var init_sse_buffer = __esm({
358375
359469
  this.stats.messagesSent++;
358376
359470
  this.stats.bytesSent += Buffer.byteLength(eventStr, "utf8");
358377
359471
  } catch (err) {
358378
- log83.error("Failed to send immediate SSE message", { error: String(err) });
359472
+ log84.error("Failed to send immediate SSE message", { error: String(err) });
358379
359473
  this.stats.errors++;
358380
359474
  }
358381
359475
  }
@@ -358429,7 +359523,7 @@ var init_sse_buffer = __esm({
358429
359523
  this.flushTimer = null;
358430
359524
  }
358431
359525
  } catch (err) {
358432
- log83.error("Failed to flush SSE buffer", { error: String(err) });
359526
+ log84.error("Failed to flush SSE buffer", { error: String(err) });
358433
359527
  this.stats.errors++;
358434
359528
  this.close();
358435
359529
  }
@@ -358448,7 +359542,7 @@ var init_sse_buffer = __esm({
358448
359542
  try {
358449
359543
  this.sendImmediate({ type: "heartbeat", timestamp: Date.now() });
358450
359544
  } catch (err) {
358451
- log83.warn("Heartbeat failed", { error: String(err) });
359545
+ log84.warn("Heartbeat failed", { error: String(err) });
358452
359546
  this.stopHeartbeat();
358453
359547
  this.close();
358454
359548
  }
@@ -358486,14 +359580,14 @@ var init_sse_buffer = __esm({
358486
359580
  this.response.end();
358487
359581
  }
358488
359582
  } catch (err) {
358489
- log83.debug("Error closing SSE connection", { error: String(err) });
359583
+ log84.debug("Error closing SSE connection", { error: String(err) });
358490
359584
  }
358491
359585
  if (this.droppedAfterClose > 0) {
358492
- log83.warn("SSE connection closed after dropping messages", {
359586
+ log84.warn("SSE connection closed after dropping messages", {
358493
359587
  droppedAfterClose: this.droppedAfterClose
358494
359588
  });
358495
359589
  }
358496
- log83.debug("SSE connection closed", { stats: this.stats });
359590
+ log84.debug("SSE connection closed", { stats: this.stats });
358497
359591
  if (this.onCloseCallback) {
358498
359592
  try {
358499
359593
  this.onCloseCallback();
@@ -358519,13 +359613,13 @@ var init_sse_buffer = __esm({
358519
359613
 
358520
359614
  // ../org-manager/dist/sse-handler.js
358521
359615
  import { randomUUID as randomUUID2 } from "node:crypto";
358522
- var log84, SSEHandler;
359616
+ var log85, SSEHandler;
358523
359617
  var init_sse_handler = __esm({
358524
359618
  "../org-manager/dist/sse-handler.js"() {
358525
359619
  "use strict";
358526
359620
  init_dist();
358527
359621
  init_sse_buffer();
358528
- log84 = createLogger("sse-handler");
359622
+ log85 = createLogger("sse-handler");
358529
359623
  SSEHandler = class {
358530
359624
  options;
358531
359625
  sseBuffer = null;
@@ -358585,7 +359679,7 @@ var init_sse_handler = __esm({
358585
359679
  this.sseBuffer.onClose(() => {
358586
359680
  if (!this.isComplete) {
358587
359681
  this.sseDisconnected = true;
358588
- log84.info("SSE client disconnected \u2014 detaching (agent continues)", {
359682
+ log85.info("SSE client disconnected \u2014 detaching (agent continues)", {
358589
359683
  agentId: this.options.agentId,
358590
359684
  streamId: this.streamId
358591
359685
  });
@@ -358607,7 +359701,7 @@ var init_sse_handler = __esm({
358607
359701
  if (this.forceStopTimer)
358608
359702
  clearInterval(this.forceStopTimer);
358609
359703
  this.forceStopTimer = null;
358610
- log84.warn("Force-stopping detached agent after SSE disconnect inactivity window", {
359704
+ log85.warn("Force-stopping detached agent after SSE disconnect inactivity window", {
358611
359705
  agentId: this.options.agentId,
358612
359706
  inactiveMs: silentFor,
358613
359707
  windowMs: disconnectWindowMs
@@ -358669,14 +359763,14 @@ var init_sse_handler = __esm({
358669
359763
  ...this.sessionId ? { sessionId: this.sessionId } : {}
358670
359764
  });
358671
359765
  if (reply === "[merged]") {
358672
- log84.info("Message was merged into active processing \u2014 closing SSE without persisting assistant", {
359766
+ log85.info("Message was merged into active processing \u2014 closing SSE without persisting assistant", {
358673
359767
  agentId: this.options.agentId
358674
359768
  });
358675
359769
  if (persistedUserMessageId && this.options.deleteUserMessage) {
358676
359770
  try {
358677
359771
  this.options.deleteUserMessage(persistedUserMessageId);
358678
359772
  } catch (err) {
358679
- log84.warn("Failed to delete merged user message", { error: String(err) });
359773
+ log85.warn("Failed to delete merged user message", { error: String(err) });
358680
359774
  }
358681
359775
  }
358682
359776
  const mergedDone = {
@@ -358742,7 +359836,7 @@ var init_sse_handler = __esm({
358742
359836
  };
358743
359837
  if (this.sseDisconnected) {
358744
359838
  if (persistReply && !isCancelledReply && !this.activeStream) {
358745
- log84.info("Agent finished but SSE was disconnected \u2014 delivering reply via WebSocket fallback", {
359839
+ log85.info("Agent finished but SSE was disconnected \u2014 delivering reply via WebSocket fallback", {
358746
359840
  agentId: this.options.agentId,
358747
359841
  replyLength: persistReply.length
358748
359842
  });
@@ -358786,7 +359880,7 @@ var init_sse_handler = __esm({
358786
359880
  try {
358787
359881
  await this.options.persistAssistantMessage(this.sessionId, this.options.agentId, storedContent, this.options.agent.getState().tokensUsedToday, msgMeta);
358788
359882
  } catch (e) {
358789
- log84.error("Failed to persist assistant message", { agentId: this.options.agentId, error: String(e) });
359883
+ log85.error("Failed to persist assistant message", { agentId: this.options.agentId, error: String(e) });
358790
359884
  }
358791
359885
  }
358792
359886
  if (this.options.onComplete) {
@@ -358806,7 +359900,7 @@ var init_sse_handler = __esm({
358806
359900
  }, 100);
358807
359901
  }
358808
359902
  } catch (error) {
358809
- log84.error("SSE handler error", {
359903
+ log85.error("SSE handler error", {
358810
359904
  agentId: this.options.agentId,
358811
359905
  error: String(error)
358812
359906
  });
@@ -358827,7 +359921,7 @@ var init_sse_handler = __esm({
358827
359921
  try {
358828
359922
  await this.options.persistAssistantMessage(this.sessionId, this.options.agentId, errReply, 0, errMeta);
358829
359923
  } catch (e) {
358830
- log84.error("Failed to persist error message", { agentId: this.options.agentId, error: String(e) });
359924
+ log85.error("Failed to persist error message", { agentId: this.options.agentId, error: String(e) });
358831
359925
  }
358832
359926
  }
358833
359927
  this.activeStream?.complete({
@@ -358837,7 +359931,7 @@ var init_sse_handler = __esm({
358837
359931
  streamId: this.streamId
358838
359932
  });
358839
359933
  if (this.options.onError) {
358840
- void this.options.onError(error, this.msgSegments).catch((e) => log84.warn("onError callback failed", { error: String(e) }));
359934
+ void this.options.onError(error, this.msgSegments).catch((e) => log85.warn("onError callback failed", { error: String(e) }));
358841
359935
  }
358842
359936
  } finally {
358843
359937
  this.isProcessing = false;
@@ -358928,7 +360022,7 @@ var init_sse_handler = __esm({
358928
360022
  }
358929
360023
  }
358930
360024
  } catch (err) {
358931
- log84.warn("Failed to persist chat segments to execution stream", { messageId, error: String(err) });
360025
+ log85.warn("Failed to persist chat segments to execution stream", { messageId, error: String(err) });
358932
360026
  }
358933
360027
  }
358934
360028
  /**
@@ -358972,13 +360066,13 @@ var init_sse_handler = __esm({
358972
360066
  return;
358973
360067
  try {
358974
360068
  await this.options.persistAssistantMessage(this.sessionId, this.options.agentId, partialText, 0, meta);
358975
- log84.info("Persisted partial streaming content on SSE disconnect", {
360069
+ log85.info("Persisted partial streaming content on SSE disconnect", {
358976
360070
  agentId: this.options.agentId,
358977
360071
  segmentCount: segments.length,
358978
360072
  textLength: partialText.length
358979
360073
  });
358980
360074
  } catch (e) {
358981
- log84.error("Failed to persist partial content on disconnect", {
360075
+ log85.error("Failed to persist partial content on disconnect", {
358982
360076
  agentId: this.options.agentId,
358983
360077
  error: String(e)
358984
360078
  });
@@ -359142,7 +360236,7 @@ var init_sse_handler = __esm({
359142
360236
  res.end();
359143
360237
  }
359144
360238
  } catch (e) {
359145
- log84.error("Error handling SSE error", { error: String(e) });
360239
+ log85.error("Error handling SSE error", { error: String(e) });
359146
360240
  }
359147
360241
  }
359148
360242
  /**
@@ -359184,12 +360278,12 @@ var init_sse_handler = __esm({
359184
360278
  });
359185
360279
 
359186
360280
  // ../org-manager/dist/active-stream-registry.js
359187
- var log85, RING_CAP, DONE_TTL_MS, STREAM_ATTACH_HEARTBEAT_MS, ActiveStreamSession, ActiveStreamRegistry;
360281
+ var log86, RING_CAP, DONE_TTL_MS, STREAM_ATTACH_HEARTBEAT_MS, ActiveStreamSession, ActiveStreamRegistry;
359188
360282
  var init_active_stream_registry = __esm({
359189
360283
  "../org-manager/dist/active-stream-registry.js"() {
359190
360284
  "use strict";
359191
360285
  init_dist();
359192
- log85 = createLogger("active-stream");
360286
+ log86 = createLogger("active-stream");
359193
360287
  RING_CAP = 2500;
359194
360288
  DONE_TTL_MS = 9e4;
359195
360289
  STREAM_ATTACH_HEARTBEAT_MS = 15e3;
@@ -359247,7 +360341,7 @@ var init_active_stream_registry = __esm({
359247
360341
  try {
359248
360342
  sub(wrapped);
359249
360343
  } catch (err) {
359250
- log85.warn("Active stream subscriber failed", { error: String(err) });
360344
+ log86.warn("Active stream subscriber failed", { error: String(err) });
359251
360345
  }
359252
360346
  }
359253
360347
  return wrapped;
@@ -359287,7 +360381,7 @@ var init_active_stream_registry = __esm({
359287
360381
  */
359288
360382
  attach(res, afterSeq = 0) {
359289
360383
  if (res.headersSent) {
359290
- log85.warn("Cannot attach active stream \u2014 headers already sent", {
360384
+ log86.warn("Cannot attach active stream \u2014 headers already sent", {
359291
360385
  streamId: this.streamId
359292
360386
  });
359293
360387
  return;
@@ -359307,7 +360401,7 @@ var init_active_stream_registry = __esm({
359307
360401
 
359308
360402
  `);
359309
360403
  } catch (err) {
359310
- log85.warn("Failed writing reattach SSE event", { error: String(err) });
360404
+ log86.warn("Failed writing reattach SSE event", { error: String(err) });
359311
360405
  }
359312
360406
  };
359313
360407
  write({
@@ -359418,7 +360512,7 @@ var init_active_stream_registry = __esm({
359418
360512
  });
359419
360513
  this.bySession.set(this.key(opts.agentId, opts.sessionId), session);
359420
360514
  this.byStreamId.set(opts.streamId, session);
359421
- log85.info("Registered active stream", {
360515
+ log86.info("Registered active stream", {
359422
360516
  streamId: opts.streamId,
359423
360517
  agentId: opts.agentId,
359424
360518
  sessionId: opts.sessionId
@@ -360974,7 +362068,7 @@ async function importSkillFromDirectory(srcDir, opts = {}, skillRegistry) {
360974
362068
  skillRegistry.register({ manifest: discovered.manifest });
360975
362069
  }
360976
362070
  } catch (regErr) {
360977
- log86.warn("Failed to register imported skill into runtime registry", { error: String(regErr) });
362071
+ log87.warn("Failed to register imported skill into runtime registry", { error: String(regErr) });
360978
362072
  }
360979
362073
  }
360980
362074
  return {
@@ -361024,7 +362118,7 @@ async function installSkill(request, skillRegistry) {
361024
362118
  installed3 = true;
361025
362119
  installMethod = "clawhub-zip";
361026
362120
  } catch {
361027
- log86.warn("unzip failed for skill", { skillName });
362121
+ log87.warn("unzip failed for skill", { skillName });
361028
362122
  }
361029
362123
  try {
361030
362124
  execSync5(`rm -f "${tmpZip}"`);
@@ -361032,7 +362126,7 @@ async function installSkill(request, skillRegistry) {
361032
362126
  }
361033
362127
  }
361034
362128
  } catch (err) {
361035
- log86.warn(`ClawHub download failed for ${slug}`, { error: String(err) });
362129
+ log87.warn(`ClawHub download failed for ${slug}`, { error: String(err) });
361036
362130
  }
361037
362131
  }
361038
362132
  if (!installed3 && source === "skillssh" && githubRepo) {
@@ -361048,7 +362142,7 @@ async function installSkill(request, skillRegistry) {
361048
362142
  installMethod = "github-skillmd";
361049
362143
  }
361050
362144
  } catch (err) {
361051
- log86.warn(`GitHub SKILL.md download failed`, { error: String(err) });
362145
+ log87.warn(`GitHub SKILL.md download failed`, { error: String(err) });
361052
362146
  }
361053
362147
  if (!installed3) {
361054
362148
  try {
@@ -361080,7 +362174,7 @@ async function installSkill(request, skillRegistry) {
361080
362174
  installed3 = true;
361081
362175
  installMethod = "clawhub-zip-fallback";
361082
362176
  } catch {
361083
- log86.warn("unzip failed (fallback)", { skillName });
362177
+ log87.warn("unzip failed (fallback)", { skillName });
361084
362178
  }
361085
362179
  try {
361086
362180
  execSync5(`rm -f "${tmpZip}"`);
@@ -361088,7 +362182,7 @@ async function installSkill(request, skillRegistry) {
361088
362182
  }
361089
362183
  }
361090
362184
  } catch {
361091
- log86.warn(`ClawHub fallback failed for ${trySlug}`);
362185
+ log87.warn(`ClawHub fallback failed for ${trySlug}`);
361092
362186
  }
361093
362187
  }
361094
362188
  if (!installed3) {
@@ -361124,18 +362218,18 @@ async function installSkill(request, skillRegistry) {
361124
362218
  skillRegistry.register({ manifest: discovered.manifest });
361125
362219
  }
361126
362220
  } catch (regErr) {
361127
- log86.warn("Failed to register installed skill into runtime registry", { error: String(regErr) });
362221
+ log87.warn("Failed to register installed skill into runtime registry", { error: String(regErr) });
361128
362222
  }
361129
362223
  }
361130
362224
  return { installed: true, name: skillName, path: targetDir, method: installMethod };
361131
362225
  }
361132
- var log86, cache, CACHE_TTL_MS2, SKILLHUB_CACHE_TTL_MS;
362226
+ var log87, cache, CACHE_TTL_MS2, SKILLHUB_CACHE_TTL_MS;
361133
362227
  var init_skill_service = __esm({
361134
362228
  "../org-manager/dist/skill-service.js"() {
361135
362229
  "use strict";
361136
362230
  init_dist();
361137
362231
  init_dist7();
361138
- log86 = createLogger("skill-service");
362232
+ log87 = createLogger("skill-service");
361139
362233
  cache = /* @__PURE__ */ new Map();
361140
362234
  CACHE_TTL_MS2 = 6e5;
361141
362235
  SKILLHUB_CACHE_TTL_MS = 36e5;
@@ -361200,7 +362294,7 @@ function syncSkillFrontmatterName(artDir, newSlug) {
361200
362294
  if (updatedFm !== fm)
361201
362295
  writeFileSync32(skillMd, updatedFm + body, "utf-8");
361202
362296
  } catch (err) {
361203
- log87.warn("Failed to sync SKILL.md frontmatter name", { error: String(err) });
362297
+ log88.warn("Failed to sync SKILL.md frontmatter name", { error: String(err) });
361204
362298
  }
361205
362299
  }
361206
362300
  async function handleSkillsRoutes(server, req, res, path, url) {
@@ -361464,7 +362558,7 @@ async function handleSkillsRoutes(server, req, res, path, url) {
361464
362558
  try {
361465
362559
  await server.storage.agentRepo.updateConfig(agentInfo.id, { skills: agent.config.skills });
361466
362560
  } catch (e) {
361467
- log87.warn("Failed to persist skill removal from agent after uninstall", { agentId: agentInfo.id, error: String(e) });
362561
+ log88.warn("Failed to persist skill removal from agent after uninstall", { agentId: agentInfo.id, error: String(e) });
361468
362562
  }
361469
362563
  }
361470
362564
  }
@@ -361672,7 +362766,7 @@ async function handleSkillsRoutes(server, req, res, path, url) {
361672
362766
  artifactType: mode,
361673
362767
  artifactData: artifact,
361674
362768
  tags: ["builder", mode]
361675
- }).catch((err) => log87.warn("Failed to create deliverable for builder artifact", { error: String(err) }));
362769
+ }).catch((err) => log88.warn("Failed to create deliverable for builder artifact", { error: String(err) }));
361676
362770
  }
361677
362771
  server.json(res, 201, { type: mode, name: manifest.name, path: artDir });
361678
362772
  } catch (err) {
@@ -361890,7 +362984,7 @@ async function handleSkillsRoutes(server, req, res, path, url) {
361890
362984
  renameSync4(artDir, dest);
361891
362985
  finalDir = dest;
361892
362986
  }
361893
- log87.info(`Converted artifact slug ${type}/${name} \u2192 ${newSlug}`);
362987
+ log88.info(`Converted artifact slug ${type}/${name} \u2192 ${newSlug}`);
361894
362988
  server.json(res, 200, {
361895
362989
  converted: true,
361896
362990
  type,
@@ -362255,14 +363349,14 @@ async function handleSkillsRoutes(server, req, res, path, url) {
362255
363349
  }
362256
363350
  return false;
362257
363351
  }
362258
- var log87;
363352
+ var log88;
362259
363353
  var init_skills2 = __esm({
362260
363354
  "../org-manager/dist/routes/skills.js"() {
362261
363355
  "use strict";
362262
363356
  init_dist7();
362263
363357
  init_dist();
362264
363358
  init_skill_service();
362265
- log87 = createLogger("routes/skills");
363359
+ log88 = createLogger("routes/skills");
362266
363360
  }
362267
363361
  });
362268
363362
 
@@ -362270,12 +363364,12 @@ var init_skills2 = __esm({
362270
363364
  function newChainId() {
362271
363365
  return `chain_${Date.now().toString(36)}_${(++deliverySeq).toString(36)}`;
362272
363366
  }
362273
- var log88, deliverySeq, AgentDelivery;
363367
+ var log89, deliverySeq, AgentDelivery;
362274
363368
  var init_agent_delivery = __esm({
362275
363369
  "../org-manager/dist/agent-delivery.js"() {
362276
363370
  "use strict";
362277
363371
  init_dist();
362278
- log88 = createLogger("agent-delivery");
363372
+ log89 = createLogger("agent-delivery");
362279
363373
  deliverySeq = 0;
362280
363374
  AgentDelivery = class {
362281
363375
  deps;
@@ -362297,7 +363391,7 @@ var init_agent_delivery = __esm({
362297
363391
  continue;
362298
363392
  const agent = this.deps.getAgent(targetId);
362299
363393
  if (!agent) {
362300
- log88.warn("A2A delivery skipped \u2014 target agent not available", {
363394
+ log89.warn("A2A delivery skipped \u2014 target agent not available", {
362301
363395
  deliveryId,
362302
363396
  targetId,
362303
363397
  channelKey: req.channelKey,
@@ -362351,7 +363445,7 @@ var init_agent_delivery = __esm({
362351
363445
  });
362352
363446
  deliveredTo.push(targetId);
362353
363447
  } catch (err) {
362354
- log88.error("A2A delivery failed \u2014 enqueue threw", {
363448
+ log89.error("A2A delivery failed \u2014 enqueue threw", {
362355
363449
  deliveryId,
362356
363450
  targetId,
362357
363451
  channelKey: req.channelKey,
@@ -362361,7 +363455,7 @@ var init_agent_delivery = __esm({
362361
363455
  throw err;
362362
363456
  }
362363
363457
  }
362364
- log88.info("A2A delivered to mailbox", {
363458
+ log89.info("A2A delivered to mailbox", {
362365
363459
  deliveryId,
362366
363460
  channelKey: req.channelKey,
362367
363461
  from: req.fromAgentId,
@@ -362409,7 +363503,7 @@ var init_agent_delivery = __esm({
362409
363503
  replyToId: args.replyToMsgId
362410
363504
  });
362411
363505
  } catch (err) {
362412
- log88.warn("Failed to persist A2A reply", { channelKey: args.channelKey, error: String(err) });
363506
+ log89.warn("Failed to persist A2A reply", { channelKey: args.channelKey, error: String(err) });
362413
363507
  }
362414
363508
  }
362415
363509
  try {
@@ -362421,7 +363515,7 @@ var init_agent_delivery = __esm({
362421
363515
  messageId
362422
363516
  });
362423
363517
  } catch (err) {
362424
- log88.warn("Failed to broadcast A2A reply", { channelKey: args.channelKey, error: String(err) });
363518
+ log89.warn("Failed to broadcast A2A reply", { channelKey: args.channelKey, error: String(err) });
362425
363519
  }
362426
363520
  return { messageId };
362427
363521
  }
@@ -362814,13 +363908,13 @@ function exponentialBackoffMs(attemptOrdinal, cfg) {
362814
363908
  const limit = Math.min(exponent, 24);
362815
363909
  return Math.min(cfg.retryBaseMs * Math.pow(2, limit), cfg.backoffMaxMs);
362816
363910
  }
362817
- var log89, CONSERVATOR_RETRY_AFTER_MS, CONSERVATOR_MAX_WAKE_ATTEMPTS, CONSERVATOR_MAX_RECONCILE_ATTEMPTS, CONSERVATOR_MAX_TOTAL_ATTEMPTS, CONSERVATOR_BACKOFF_MAX_MS, DEFAULT_DIRTY_CONFIG, DEFAULT_STALL_CONFIG, DEAD_DEP_STATUSES, ACTIVITY_PHASES, DEFAULT_CONSERVATOR_CONFIG, LIVE_TASK_STATUSES, AgentConservator;
363911
+ var log90, CONSERVATOR_RETRY_AFTER_MS, CONSERVATOR_MAX_WAKE_ATTEMPTS, CONSERVATOR_MAX_RECONCILE_ATTEMPTS, CONSERVATOR_MAX_TOTAL_ATTEMPTS, CONSERVATOR_BACKOFF_MAX_MS, DEFAULT_DIRTY_CONFIG, DEFAULT_STALL_CONFIG, DEAD_DEP_STATUSES, ACTIVITY_PHASES, DEFAULT_CONSERVATOR_CONFIG, LIVE_TASK_STATUSES, AgentConservator;
362818
363912
  var init_agent_conservator = __esm({
362819
363913
  "../org-manager/dist/agent-conservator.js"() {
362820
363914
  "use strict";
362821
363915
  init_dist();
362822
363916
  init_agent_runtime();
362823
- log89 = createLogger("agent-conservator");
363917
+ log90 = createLogger("agent-conservator");
362824
363918
  CONSERVATOR_RETRY_AFTER_MS = 5 * 6e4;
362825
363919
  CONSERVATOR_MAX_WAKE_ATTEMPTS = 3;
362826
363920
  CONSERVATOR_MAX_RECONCILE_ATTEMPTS = 2;
@@ -362907,7 +364001,7 @@ var init_agent_conservator = __esm({
362907
364001
  if (this.opts.onNeedsHuman)
362908
364002
  void this.opts.onNeedsHuman(v);
362909
364003
  else
362910
- log89.warn("Conservator: agent needs human review", { agentId: a.agentId, verdict: v });
364004
+ log90.warn("Conservator: agent needs human review", { agentId: a.agentId, verdict: v });
362911
364005
  }
362912
364006
  continue;
362913
364007
  }
@@ -362965,7 +364059,7 @@ var init_agent_conservator = __esm({
362965
364059
  if (this.opts.onNeedsHuman)
362966
364060
  void this.opts.onNeedsHuman(effective);
362967
364061
  else
362968
- log89.warn("Conservator: agent needs human review", { agentId: a.agentId, verdict: effective });
364062
+ log90.warn("Conservator: agent needs human review", { agentId: a.agentId, verdict: effective });
362969
364063
  }
362970
364064
  } else if (this.opts.recover) {
362971
364065
  await this.opts.recover(effective);
@@ -362990,18 +364084,18 @@ var init_agent_conservator = __esm({
362990
364084
  try {
362991
364085
  list = getAgents();
362992
364086
  } catch (err) {
362993
- log89.warn("conservator scan: getAgents failed", { error: String(err) });
364087
+ log90.warn("conservator scan: getAgents failed", { error: String(err) });
362994
364088
  return;
362995
364089
  }
362996
364090
  this.scan(list).then((handled) => {
362997
364091
  if (handled.length > 0) {
362998
- log89.info(`Conservator handled ${handled.length} agent(s)`, {
364092
+ log90.info(`Conservator handled ${handled.length} agent(s)`, {
362999
364093
  handled: handled.map((v) => `${v.agentId}:${v.action}`)
363000
364094
  });
363001
364095
  }
363002
- }).catch((err) => log89.warn("conservator scan failed", { error: String(err) }));
364096
+ }).catch((err) => log90.warn("conservator scan failed", { error: String(err) }));
363003
364097
  }, intervalMs);
363004
- log89.info("Agent Conservator started", { intervalMs, enabled: this.cfg.enabled });
364098
+ log90.info("Agent Conservator started", { intervalMs, enabled: this.cfg.enabled });
363005
364099
  }
363006
364100
  stop() {
363007
364101
  if (this.timer) {
@@ -363027,7 +364121,7 @@ var init_agent_conservator = __esm({
363027
364121
  try {
363028
364122
  void this.opts.appendExecution(entry);
363029
364123
  } catch (err) {
363030
- log89.debug("appendExecution failed (best-effort)", { error: String(err) });
364124
+ log90.debug("appendExecution failed (best-effort)", { error: String(err) });
363031
364125
  }
363032
364126
  }
363033
364127
  };
@@ -363039,13 +364133,13 @@ var feishu_api_client_exports = {};
363039
364133
  __export(feishu_api_client_exports, {
363040
364134
  FeishuApiClient: () => FeishuApiClient
363041
364135
  });
363042
- var Lark2, log90, FeishuApiClient;
364136
+ var Lark2, log91, FeishuApiClient;
363043
364137
  var init_feishu_api_client = __esm({
363044
364138
  "../org-manager/dist/feishu-api-client.js"() {
363045
364139
  "use strict";
363046
364140
  Lark2 = __toESM(require_lib9(), 1);
363047
364141
  init_dist();
363048
- log90 = createLogger("feishu-api-client");
364142
+ log91 = createLogger("feishu-api-client");
363049
364143
  FeishuApiClient = class {
363050
364144
  client;
363051
364145
  wsClient = null;
@@ -363072,7 +364166,7 @@ var init_feishu_api_client = __esm({
363072
364166
  */
363073
364167
  async startWSClient(eventDispatcher) {
363074
364168
  if (this.wsClient) {
363075
- log90.warn("WSClient already running, stopping existing one");
364169
+ log91.warn("WSClient already running, stopping existing one");
363076
364170
  this.stopWSClient();
363077
364171
  }
363078
364172
  this.wsClient = new Lark2.WSClient({
@@ -363081,20 +364175,20 @@ var init_feishu_api_client = __esm({
363081
364175
  domain: this.domain,
363082
364176
  loggerLevel: Lark2.LoggerLevel.debug,
363083
364177
  onReady: () => {
363084
- log90.info("Feishu WSClient onReady callback fired \u2014 connection is live");
364178
+ log91.info("Feishu WSClient onReady callback fired \u2014 connection is live");
363085
364179
  },
363086
364180
  onError: (err) => {
363087
- log90.error("Feishu WSClient onError callback", { error: err.message });
364181
+ log91.error("Feishu WSClient onError callback", { error: err.message });
363088
364182
  }
363089
364183
  });
363090
364184
  await this.wsClient.start({ eventDispatcher });
363091
- log90.info("Feishu WSClient started (long connection mode)");
364185
+ log91.info("Feishu WSClient started (long connection mode)");
363092
364186
  return this.wsClient;
363093
364187
  }
363094
364188
  /** Stop the WebSocket client. */
363095
364189
  stopWSClient() {
363096
364190
  this.wsClient = null;
363097
- log90.info("Feishu WSClient stopped");
364191
+ log91.info("Feishu WSClient stopped");
363098
364192
  }
363099
364193
  /** Send a text message to a Feishu chat by chat_id. */
363100
364194
  async sendText(chatId, text) {
@@ -363108,7 +364202,7 @@ var init_feishu_api_client = __esm({
363108
364202
  }
363109
364203
  });
363110
364204
  } catch (err) {
363111
- log90.error("Feishu sendText failed", { chatId, error: String(err) });
364205
+ log91.error("Feishu sendText failed", { chatId, error: String(err) });
363112
364206
  throw err;
363113
364207
  }
363114
364208
  }
@@ -363124,7 +364218,7 @@ var init_feishu_api_client = __esm({
363124
364218
  }
363125
364219
  });
363126
364220
  } catch (err) {
363127
- log90.error("Feishu sendTextToUser failed", { openId, error: String(err) });
364221
+ log91.error("Feishu sendTextToUser failed", { openId, error: String(err) });
363128
364222
  throw err;
363129
364223
  }
363130
364224
  }
@@ -363141,7 +364235,7 @@ var init_feishu_api_client = __esm({
363141
364235
  });
363142
364236
  return resp?.data?.message_id ?? void 0;
363143
364237
  } catch (err) {
363144
- log90.error("Feishu sendCardToUser failed", { openId, error: String(err) });
364238
+ log91.error("Feishu sendCardToUser failed", { openId, error: String(err) });
363145
364239
  throw err;
363146
364240
  }
363147
364241
  }
@@ -363158,7 +364252,7 @@ var init_feishu_api_client = __esm({
363158
364252
  });
363159
364253
  return resp?.data?.message_id ?? void 0;
363160
364254
  } catch (err) {
363161
- log90.error("Feishu sendCard failed", { chatId, error: String(err) });
364255
+ log91.error("Feishu sendCard failed", { chatId, error: String(err) });
363162
364256
  throw err;
363163
364257
  }
363164
364258
  }
@@ -363187,7 +364281,7 @@ var init_feishu_api_client = __esm({
363187
364281
  pageToken = resp?.data?.page_token;
363188
364282
  } while (pageToken);
363189
364283
  } catch (err) {
363190
- log90.error("Feishu listBotChats failed", { error: String(err) });
364284
+ log91.error("Feishu listBotChats failed", { error: String(err) });
363191
364285
  throw err;
363192
364286
  }
363193
364287
  return results;
@@ -363200,10 +364294,10 @@ var init_feishu_api_client = __esm({
363200
364294
  data: { reaction_type: { emoji_type: emojiType } }
363201
364295
  });
363202
364296
  const reactionId = resp?.data?.reaction_id;
363203
- log90.info("Feishu reaction added", { messageId, emojiType, reactionId });
364297
+ log91.info("Feishu reaction added", { messageId, emojiType, reactionId });
363204
364298
  return reactionId;
363205
364299
  } catch (err) {
363206
- log90.error("Feishu addReaction failed", { messageId, emojiType, error: String(err) });
364300
+ log91.error("Feishu addReaction failed", { messageId, emojiType, error: String(err) });
363207
364301
  return void 0;
363208
364302
  }
363209
364303
  }
@@ -363213,9 +364307,9 @@ var init_feishu_api_client = __esm({
363213
364307
  await this.client.im.v1.messageReaction.delete({
363214
364308
  path: { message_id: messageId, reaction_id: reactionId }
363215
364309
  });
363216
- log90.info("Feishu reaction deleted", { messageId, reactionId });
364310
+ log91.info("Feishu reaction deleted", { messageId, reactionId });
363217
364311
  } catch (err) {
363218
- log90.error("Feishu deleteReaction failed", { messageId, reactionId, error: String(err) });
364312
+ log91.error("Feishu deleteReaction failed", { messageId, reactionId, error: String(err) });
363219
364313
  }
363220
364314
  }
363221
364315
  /** Update an interactive card message in place. */
@@ -363227,12 +364321,12 @@ var init_feishu_api_client = __esm({
363227
364321
  content: JSON.stringify(card)
363228
364322
  }
363229
364323
  });
363230
- log90.info("Feishu card updated", { messageId });
364324
+ log91.info("Feishu card updated", { messageId });
363231
364325
  } catch (err) {
363232
364326
  const respData = err?.response?.data;
363233
364327
  const errCode = respData?.code;
363234
364328
  const errMsg = respData?.msg;
363235
- log90.error("Feishu updateCard failed", {
364329
+ log91.error("Feishu updateCard failed", {
363236
364330
  messageId,
363237
364331
  error: String(err),
363238
364332
  code: errCode,
@@ -363315,7 +364409,7 @@ function buildNonStreamingSegments(params) {
363315
364409
  function stripHtmlTags(value) {
363316
364410
  return value.replace(/<[^>]*>/g, "");
363317
364411
  }
363318
- var log91, COMPRESS_MIN_BYTES, STORAGE_SCAN_TTL_MS, storageScanCache, EMPTY_REMOTE_STATUS, APIServer;
364412
+ var log92, COMPRESS_MIN_BYTES, STORAGE_SCAN_TTL_MS, storageScanCache, EMPTY_REMOTE_STATUS, APIServer;
363319
364413
  var init_api_server = __esm({
363320
364414
  "../org-manager/dist/api-server.js"() {
363321
364415
  "use strict";
@@ -363327,6 +364421,7 @@ var init_api_server = __esm({
363327
364421
  init_instance_integrations();
363328
364422
  init_storage_usage();
363329
364423
  init_builder_service();
364424
+ init_hitl_service();
363330
364425
  init_approval_apply();
363331
364426
  init_message_lean();
363332
364427
  init_session_title();
@@ -363341,7 +364436,7 @@ var init_api_server = __esm({
363341
364436
  init_agent_delivery();
363342
364437
  init_agent_runtime();
363343
364438
  init_agent_conservator();
363344
- log91 = createLogger("api-server");
364439
+ log92 = createLogger("api-server");
363345
364440
  COMPRESS_MIN_BYTES = 1024;
363346
364441
  STORAGE_SCAN_TTL_MS = 3e4;
363347
364442
  storageScanCache = null;
@@ -363608,9 +364703,9 @@ var init_api_server = __esm({
363608
364703
  if (payload.providers.length === 0)
363609
364704
  return;
363610
364705
  this.routingCandidatesCache = { data: payload, expireAt: Date.now() + _APIServer.ROUTING_CACHE_TTL_MS };
363611
- log91.info("Warmed routing-candidates cache", { providers: payload.providers.length });
364706
+ log92.info("Warmed routing-candidates cache", { providers: payload.providers.length });
363612
364707
  } catch (err) {
363613
- log91.warn("Routing candidates warm-up failed; will build on first request", { error: String(err) });
364708
+ log92.warn("Routing candidates warm-up failed; will build on first request", { error: String(err) });
363614
364709
  }
363615
364710
  }
363616
364711
  /**
@@ -363672,7 +364767,7 @@ var init_api_server = __esm({
363672
364767
  if (mu.host !== hu.host) {
363673
364768
  modelsUrl = markusCatalogUrlFromHub(hubBase);
363674
364769
  changed = true;
363675
- log91.info("Markus modelsUrl host mismatch \u2014 retargeted to config hub.url", {
364770
+ log92.info("Markus modelsUrl host mismatch \u2014 retargeted to config hub.url", {
363676
364771
  from: markus.modelsUrl,
363677
364772
  to: modelsUrl
363678
364773
  });
@@ -363716,7 +364811,7 @@ var init_api_server = __esm({
363716
364811
  ...modelsUrl ? { modelsUrl } : {}
363717
364812
  });
363718
364813
  }
363719
- log91.info("Normalized Markus OpenRouter-only provider config", {
364814
+ log92.info("Normalized Markus OpenRouter-only provider config", {
363720
364815
  modelsUrl,
363721
364816
  baseUrl,
363722
364817
  hasOrKey: !!apiKey,
@@ -363742,7 +364837,7 @@ var init_api_server = __esm({
363742
364837
  process.env["MARKUS_MODELS_URL"] = modelsUrl;
363743
364838
  return modelsUrl || void 0;
363744
364839
  } catch (err) {
363745
- log91.warn("ensureMarkusDirectConfig failed", { error: String(err) });
364840
+ log92.warn("ensureMarkusDirectConfig failed", { error: String(err) });
363746
364841
  return void 0;
363747
364842
  }
363748
364843
  }
@@ -363770,12 +364865,12 @@ var init_api_server = __esm({
363770
364865
  updates.providers = { markus: { ...diskMarkus, model: active } };
363771
364866
  }
363772
364867
  saveConfig({ llm: updates }, this.markusConfigPath);
363773
- log91.info("Persisted healed Markus routing after catalog filter", {
364868
+ log92.info("Persisted healed Markus routing after catalog filter", {
363774
364869
  model: active,
363775
364870
  routingDefaultModel: rdm
363776
364871
  });
363777
364872
  } catch (err) {
363778
- log91.warn("Failed to persist healed Markus routing", { error: String(err) });
364873
+ log92.warn("Failed to persist healed Markus routing", { error: String(err) });
363779
364874
  }
363780
364875
  }
363781
364876
  /**
@@ -363920,7 +365015,7 @@ var init_api_server = __esm({
363920
365015
  await this.llmRouter.refreshMarkusCatalog().catch(() => 0);
363921
365016
  this.invalidateRoutingCache();
363922
365017
  }
363923
- log91.info("Synced OpenRouter member key from Hub", {
365018
+ log92.info("Synced OpenRouter member key from Hub", {
363924
365019
  keyPrefix: or2.keyPrefix ?? or2.key.slice(0, 12),
363925
365020
  modelsUrl,
363926
365021
  rotated: !!opts?.rotate
@@ -363972,7 +365067,7 @@ var init_api_server = __esm({
363972
365067
  this.llmRouter.setDefaultProvider("markus");
363973
365068
  configUpdates.defaultProvider = "markus";
363974
365069
  } catch (err) {
363975
- log91.warn("Could not set defaultProvider=markus", { error: String(err) });
365070
+ log92.warn("Could not set defaultProvider=markus", { error: String(err) });
363976
365071
  }
363977
365072
  }
363978
365073
  if (applied.markusActiveModel) {
@@ -363988,7 +365083,7 @@ var init_api_server = __esm({
363988
365083
  }
363989
365084
  saveConfig({ llm: configUpdates });
363990
365085
  this.invalidateRoutingCache();
363991
- log91.info("Applied Hub recommended routing", {
365086
+ log92.info("Applied Hub recommended routing", {
363992
365087
  force: opts.force,
363993
365088
  greenfield,
363994
365089
  defaultProvider: applied.defaultProvider,
@@ -364434,7 +365529,7 @@ ${cleanText}`,
364434
365529
  mf.icon = `images/${iconFilename}`;
364435
365530
  }
364436
365531
  } catch (iconErr) {
364437
- log91.warn("Failed to download Hub icon, keeping remote URL", { icon: mfIcon, error: String(iconErr) });
365532
+ log92.warn("Failed to download Hub icon, keeping remote URL", { icon: mfIcon, error: String(iconErr) });
364438
365533
  }
364439
365534
  }
364440
365535
  writeFileSync33(mfPath, JSON.stringify(mf, null, 2), "utf-8");
@@ -364485,7 +365580,7 @@ ${cleanText}`,
364485
365580
  body: JSON.stringify({ name: preferred })
364486
365581
  });
364487
365582
  if (!renameRes.ok) {
364488
- log91.warn("Hub org rename rejected", { status: renameRes.status, orgId: owned.id });
365583
+ log92.warn("Hub org rename rejected", { status: renameRes.status, orgId: owned.id });
364489
365584
  }
364490
365585
  }
364491
365586
  setBillingService(service) {
@@ -364616,7 +365711,7 @@ ${cleanText}`,
364616
365711
  try {
364617
365712
  await this.platformRuntimeSyncInstance?.(instanceId);
364618
365713
  } catch (error) {
364619
- log91.warn("Runtime instance reconcile failed", { instanceId, error: String(error) });
365714
+ log92.warn("Runtime instance reconcile failed", { instanceId, error: String(error) });
364620
365715
  }
364621
365716
  }
364622
365717
  /**
@@ -364747,7 +365842,7 @@ ${cleanText}`,
364747
365842
  try {
364748
365843
  saveConfig({ remote: { enabled: true, mode } }, this.markusConfigPath);
364749
365844
  } catch (err) {
364750
- log91.warn("persistRemoteIntent failed", { error: String(err) });
365845
+ log92.warn("persistRemoteIntent failed", { error: String(err) });
364751
365846
  }
364752
365847
  }
364753
365848
  /** Candidate recipient Agents for the Path-B picker, plus a sensible default. */
@@ -364763,7 +365858,7 @@ ${cleanText}`,
364763
365858
  };
364764
365859
  }).filter((a) => a.id);
364765
365860
  } catch (err) {
364766
- log91.warn("remoteSetupTargets: listAgents failed", { error: String(err) });
365861
+ log92.warn("remoteSetupTargets: listAgents failed", { error: String(err) });
364767
365862
  }
364768
365863
  let secretaryId = null;
364769
365864
  try {
@@ -364961,7 +366056,7 @@ ${cleanText}`,
364961
366056
  if (existingOwner.id === "default") {
364962
366057
  const newId = userId();
364963
366058
  this.storage.userRepo.migrateDefaultId(newId);
364964
- log91.info("Migrated legacy owner id='default'", { newId });
366059
+ log92.info("Migrated legacy owner id='default'", { newId });
364965
366060
  return newId;
364966
366061
  }
364967
366062
  return existingOwner.id;
@@ -364978,11 +366073,11 @@ ${cleanText}`,
364978
366073
  passwordHash: hash
364979
366074
  });
364980
366075
  if (generated) {
364981
- log91.warn("Created admin user (admin@markus.local) with a randomly generated initial password.");
364982
- log91.warn(`Initial admin password: ${adminPassword}`);
364983
- log91.warn(`(also saved to ${initialAdminPasswordFile()}, mode 0600 \u2014 complete onboarding to set your own credentials)`);
366076
+ log92.warn("Created admin user (admin@markus.local) with a randomly generated initial password.");
366077
+ log92.warn(`Initial admin password: ${adminPassword}`);
366078
+ log92.warn(`(also saved to ${initialAdminPasswordFile()}, mode 0600 \u2014 complete onboarding to set your own credentials)`);
364984
366079
  } else {
364985
- log91.info("Created admin user (admin@markus.local)", { userId: ownerId });
366080
+ log92.info("Created admin user (admin@markus.local)", { userId: ownerId });
364986
366081
  }
364987
366082
  return ownerId;
364988
366083
  }
@@ -365030,7 +366125,7 @@ ${cleanText}`,
365030
366125
  if (title)
365031
366126
  await this.storage.chatSessionRepo.updateLastMessage(session.id, title);
365032
366127
  } catch (err) {
365033
- log91.warn("Failed to persist chat turn", { error: String(err) });
366128
+ log92.warn("Failed to persist chat turn", { error: String(err) });
365034
366129
  }
365035
366130
  }
365036
366131
  // ── Agent-to-agent reply storm prevention ───────────────────────────────────
@@ -365206,7 +366301,7 @@ ${cleanText}`,
365206
366301
  return;
365207
366302
  this.storage.chatSessionRepo.updateSessionMetadata(dbSessionId, { ...existing, memorySessionId });
365208
366303
  } catch (err) {
365209
- log91.debug("Failed to persist memory-session binding", { dbSessionId, error: String(err) });
366304
+ log92.debug("Failed to persist memory-session binding", { dbSessionId, error: String(err) });
365210
366305
  }
365211
366306
  }
365212
366307
  /**
@@ -365265,7 +366360,7 @@ ${cleanText}`,
365265
366360
  await this.storage.chatSessionRepo.updateLastMessage(session.id, title);
365266
366361
  return { sessionId: session.id, messageId: saved.id };
365267
366362
  } catch (err) {
365268
- log91.warn("Failed to persist user message", { error: String(err) });
366363
+ log92.warn("Failed to persist user message", { error: String(err) });
365269
366364
  return null;
365270
366365
  }
365271
366366
  }
@@ -365282,7 +366377,7 @@ ${cleanText}`,
365282
366377
  this.ws.broadcastUnreadUpdate(`session:${sessionId}`, msg.id);
365283
366378
  }
365284
366379
  } catch (err) {
365285
- log91.warn("Failed to persist assistant message", { error: String(err) });
366380
+ log92.warn("Failed to persist assistant message", { error: String(err) });
365286
366381
  }
365287
366382
  }
365288
366383
  /**
@@ -365315,7 +366410,7 @@ ${cleanText}`,
365315
366410
  isFirstConversation: true
365316
366411
  }, { sourceType: "human_chat", scenario: "chat" });
365317
366412
  } catch (err) {
365318
- log91.warn("Failed to trigger secretary welcome for new user", { userId: userId2, error: String(err) });
366413
+ log92.warn("Failed to trigger secretary welcome for new user", { userId: userId2, error: String(err) });
365319
366414
  }
365320
366415
  }
365321
366416
  start() {
@@ -365326,7 +366421,7 @@ ${cleanText}`,
365326
366421
  reject(err);
365327
366422
  });
365328
366423
  this.server.listen(this.port, "0.0.0.0", () => {
365329
- log91.info(`API server listening on 0.0.0.0:${this.port} (HTTP + WebSocket)`);
366424
+ log92.info(`API server listening on 0.0.0.0:${this.port} (HTTP + WebSocket)`);
365330
366425
  resolve27();
365331
366426
  void this.warmRoutingCandidates();
365332
366427
  });
@@ -365346,7 +366441,7 @@ ${cleanText}`,
365346
366441
  if (this._conservator)
365347
366442
  return;
365348
366443
  if (!this.storage || !this.taskService || !this.orgService) {
365349
- log91.info("Conservator deferred \u2014 deps not ready");
366444
+ log92.info("Conservator deferred \u2014 deps not ready");
365350
366445
  return;
365351
366446
  }
365352
366447
  try {
@@ -365376,9 +366471,9 @@ ${cleanText}`,
365376
366471
  recovered = agentManager.triggerAgentHeartbeat(v.agentId);
365377
366472
  }
365378
366473
  } catch (err) {
365379
- log91.warn("Conservator recover failed", { agentId: v.agentId, action: v.action, error: String(err) });
366474
+ log92.warn("Conservator recover failed", { agentId: v.agentId, action: v.action, error: String(err) });
365380
366475
  }
365381
- log91.info("Conservator recovering agent", {
366476
+ log92.info("Conservator recovering agent", {
365382
366477
  agentId: v.agentId,
365383
366478
  action: v.action,
365384
366479
  recovered,
@@ -365391,7 +366486,7 @@ ${cleanText}`,
365391
366486
  });
365392
366487
  },
365393
366488
  onNeedsHuman: (v) => {
365394
- log91.warn("Agent needs human review (Conservator)", { agentId: v.agentId, reason: v.reason, suggestions: v.suggestions });
366489
+ log92.warn("Agent needs human review (Conservator)", { agentId: v.agentId, reason: v.reason, suggestions: v.suggestions });
365395
366490
  this.ws?.broadcast?.({
365396
366491
  type: "agent:dirty-human-review",
365397
366492
  payload: { agentId: v.agentId, reason: v.reason, suggestions: v.suggestions },
@@ -365415,9 +366510,9 @@ ${cleanText}`,
365415
366510
  tokensUsedToday: a.tokensUsedToday
365416
366511
  }));
365417
366512
  }, 3e4);
365418
- log91.info("Agent Conservator started");
366513
+ log92.info("Agent Conservator started");
365419
366514
  } catch (err) {
365420
- log91.warn("Failed to init Conservator", { error: String(err) });
366515
+ log92.warn("Failed to init Conservator", { error: String(err) });
365421
366516
  }
365422
366517
  }
365423
366518
  getWSBroadcaster() {
@@ -365448,12 +366543,12 @@ ${cleanText}`,
365448
366543
  if (this.remoteVerifyHandler(req, res))
365449
366544
  return;
365450
366545
  } catch (err) {
365451
- log91.warn("remote verify handler threw", { error: String(err) });
366546
+ log92.warn("remote verify handler threw", { error: String(err) });
365452
366547
  }
365453
366548
  }
365454
366549
  this.route(req, res, path, url).catch((error) => {
365455
366550
  const msg = error instanceof Error ? error.message : String(error);
365456
- log91.error("Request handler error", { error: msg, path });
366551
+ log92.error("Request handler error", { error: msg, path });
365457
366552
  if (res.headersSent) {
365458
366553
  try {
365459
366554
  res.write(`data: ${JSON.stringify({ type: "error", message: msg })}
@@ -365626,13 +366721,13 @@ ${cleanText}`,
365626
366721
  if (verifyData.user && verifyData.user.id === hubUser.id) {
365627
366722
  verifiedUser = verifyData.user;
365628
366723
  } else {
365629
- log91.warn("Hub token user mismatch", { expected: hubUser.id, got: verifyData.user?.id });
366724
+ log92.warn("Hub token user mismatch", { expected: hubUser.id, got: verifyData.user?.id });
365630
366725
  }
365631
366726
  } else {
365632
- log91.warn("Hub /api/auth/me returned non-OK", { status: verifyRes.status, hubUrl: this.hubUrl });
366727
+ log92.warn("Hub /api/auth/me returned non-OK", { status: verifyRes.status, hubUrl: this.hubUrl });
365633
366728
  }
365634
366729
  } catch (e) {
365635
- log91.warn("Hub token verification failed", { error: e.message, hubUrl: this.hubUrl });
366730
+ log92.warn("Hub token verification failed", { error: e.message, hubUrl: this.hubUrl });
365636
366731
  }
365637
366732
  if (!verifiedUser) {
365638
366733
  this.json(res, 401, { error: "Hub token verification failed. Please sign in to Markus Hub again.", code: "HUB_VERIFY_FAILED" });
@@ -365683,7 +366778,7 @@ ${cleanText}`,
365683
366778
  this.storage.userRepo.updateProfile(existingOwner.id, { name: existingOwner.name, email: email || existingOwner.email, avatarUrl: avatarUrl ?? existingOwner.avatarUrl });
365684
366779
  this.storage.userRepo.updateHubUserId(existingOwner.id, hubUser.id, hubUser.username);
365685
366780
  userRow = this.storage.userRepo.findById(existingOwner.id);
365686
- log91.info("Hub login: adopted existing owner", { ownerId: existingOwner.id, hubUserId: hubUser.id });
366781
+ log92.info("Hub login: adopted existing owner", { ownerId: existingOwner.id, hubUserId: hubUser.id });
365687
366782
  } else if (this.licenseService?.canUse("multi_user") ?? false) {
365688
366783
  const userId2 = userId();
365689
366784
  this.storage.userRepo.create({
@@ -365698,7 +366793,7 @@ ${cleanText}`,
365698
366793
  this.storage.userRepo.updateHubUserId(userId2, hubUser.id, hubUser.username);
365699
366794
  userRow = this.storage.userRepo.findById(userId2);
365700
366795
  isFirstLogin = true;
365701
- log91.info("Hub login: created member user for additional Hub user", { userId: userId2, hubUserId: hubUser.id });
366796
+ log92.info("Hub login: created member user for additional Hub user", { userId: userId2, hubUserId: hubUser.id });
365702
366797
  } else {
365703
366798
  this.json(res, 403, {
365704
366799
  error: "This instance already has an owner. Multi-user requires Enterprise license.",
@@ -365740,7 +366835,7 @@ ${cleanText}`,
365740
366835
  try {
365741
366836
  await this.applyPreferredOrgNameToHub(hubToken);
365742
366837
  } catch (err) {
365743
- log91.warn("Failed to sync preferred org name to Hub", { error: err.message });
366838
+ log92.warn("Failed to sync preferred org name to Hub", { error: err.message });
365744
366839
  }
365745
366840
  let cloudAiReady = false;
365746
366841
  let cloudAiError;
@@ -365749,15 +366844,15 @@ ${cleanText}`,
365749
366844
  if (sync.ok) {
365750
366845
  cloudAiReady = true;
365751
366846
  await this.applyHubRecommendationsAfterConnect(sync.modelsUrl, { force: false }).catch((err) => {
365752
- log91.warn("hub-login: apply recommendations failed", { error: err.message });
366847
+ log92.warn("hub-login: apply recommendations failed", { error: err.message });
365753
366848
  });
365754
366849
  } else {
365755
366850
  cloudAiError = sync.error ?? "OpenRouter sync failed";
365756
- log91.warn("hub-login: OpenRouter sync failed", { error: cloudAiError });
366851
+ log92.warn("hub-login: OpenRouter sync failed", { error: cloudAiError });
365757
366852
  }
365758
366853
  } catch (err) {
365759
366854
  cloudAiError = err instanceof Error ? err.message : String(err);
365760
- log91.warn("hub-login: OpenRouter sync threw", { error: cloudAiError });
366855
+ log92.warn("hub-login: OpenRouter sync threw", { error: cloudAiError });
365761
366856
  }
365762
366857
  const finalUser = userRow;
365763
366858
  await this.storage.userRepo.updateLastLogin(finalUser.id);
@@ -366568,7 +367663,7 @@ ${cleanText}`,
366568
367663
  mentions: []
366569
367664
  });
366570
367665
  } catch (e) {
366571
- log91.warn("Failed to persist channel error message", { error: String(e) });
367666
+ log92.warn("Failed to persist channel error message", { error: String(e) });
366572
367667
  }
366573
367668
  }
366574
367669
  const statusCode = raw.includes("402") ? 402 : raw.includes("401") ? 401 : raw.includes("429") ? 429 : 502;
@@ -366730,7 +367825,7 @@ ${cleanText}`,
366730
367825
  const orgId2 = body["orgId"] ?? "default";
366731
367826
  const sanitizedName = stripHtmlTags(agentName);
366732
367827
  if (sanitizedName !== agentName) {
366733
- log91.warn("XSS sanitization applied to agent name", { original: agentName, sanitized: sanitizedName });
367828
+ log92.warn("XSS sanitization applied to agent name", { original: agentName, sanitized: sanitizedName });
366734
367829
  }
366735
367830
  const agent = await this.orgService.hireAgent({
366736
367831
  name: sanitizedName,
@@ -366943,7 +368038,7 @@ ${cleanText}`,
366943
368038
  preferredMemorySessionId: this.readMemorySessionBinding(sessionId)
366944
368039
  };
366945
368040
  } catch (err) {
366946
- log91.warn("Failed to load session history \u2014 keeping current session identity", { sessionId, error: String(err) });
368041
+ log92.warn("Failed to load session history \u2014 keeping current session identity", { sessionId, error: String(err) });
366947
368042
  sessionRestoreData = void 0;
366948
368043
  }
366949
368044
  } else {
@@ -367934,7 +369029,7 @@ ${userText}` : userText;
367934
369029
  profile: titleProvided ? cfg.profile : void 0
367935
369030
  });
367936
369031
  } catch (persistErr) {
367937
- log91.warn("Failed to persist agent config to DB", { agentId: agentId2, error: String(persistErr) });
369032
+ log92.warn("Failed to persist agent config to DB", { agentId: agentId2, error: String(persistErr) });
367938
369033
  }
367939
369034
  }
367940
369035
  this.json(res, 200, { ok: true, config: agent.config });
@@ -368270,7 +369365,7 @@ EXPLANATION_END`;
368270
369365
  try {
368271
369366
  await this.storage.agentRepo.updateConfig(agentId2, { skills: agent.config.skills });
368272
369367
  } catch (e) {
368273
- log91.warn("Failed to persist skill assignment", { agentId: agentId2, error: String(e) });
369368
+ log92.warn("Failed to persist skill assignment", { agentId: agentId2, error: String(e) });
368274
369369
  }
368275
369370
  }
368276
369371
  this.json(res, 200, { ok: true, skills: agent.getActiveSkillNames() });
@@ -368294,7 +369389,7 @@ EXPLANATION_END`;
368294
369389
  try {
368295
369390
  await this.storage.agentRepo.updateConfig(agentId2, { skills: agent.config.skills });
368296
369391
  } catch (e) {
368297
- log91.warn("Failed to persist skill removal", { agentId: agentId2, error: String(e) });
369392
+ log92.warn("Failed to persist skill removal", { agentId: agentId2, error: String(e) });
368298
369393
  }
368299
369394
  }
368300
369395
  this.json(res, 200, { ok: true, skills: agent.getActiveSkillNames() });
@@ -368985,7 +370080,7 @@ EXPLANATION_END`;
368985
370080
  heartbeatIntervalMs: agent.config.heartbeatIntervalMs
368986
370081
  });
368987
370082
  } catch (persistErr) {
368988
- log91.warn("Failed to persist instantiated agent to DB", { error: String(persistErr) });
370083
+ log92.warn("Failed to persist instantiated agent to DB", { error: String(persistErr) });
368989
370084
  }
368990
370085
  }
368991
370086
  await agentManager.startAgent(agent.id);
@@ -369150,6 +370245,14 @@ EXPLANATION_END`;
369150
370245
  const comment = body["comment"];
369151
370246
  const selectedOption = body["selectedOption"];
369152
370247
  const answers = body["answers"];
370248
+ const incomplete = assessResponseCompleteness(pending, selectedOption, comment, answers);
370249
+ if (incomplete) {
370250
+ this.json(res, 400, {
370251
+ error: "This choice needs the text it asks for before it counts as an answer",
370252
+ missing: incomplete.missing
370253
+ });
370254
+ return;
370255
+ }
369153
370256
  const response = this.hitlService.respondToApproval(approvalId, approved, respondedBy, comment, selectedOption, answers);
369154
370257
  if (!response) {
369155
370258
  this.json(res, 404, { error: "Approval not found or not pending" });
@@ -369171,7 +370274,7 @@ EXPLANATION_END`;
369171
370274
  comment
369172
370275
  }) : void 0;
369173
370276
  if (!applier) {
369174
- log91.error("Approval applier unavailable \u2014 decision was NOT applied to its target", {
370277
+ log92.error("Approval applier unavailable \u2014 decision was NOT applied to its target", {
369175
370278
  approvalId,
369176
370279
  subType,
369177
370280
  taskId: taskId2,
@@ -369433,7 +370536,9 @@ EXPLANATION_END`;
369433
370536
  let messages = 0;
369434
370537
  let cacheReadTokens = 0;
369435
370538
  let cacheWriteTokens = 0;
369436
- let cacheHitRate = 0;
370539
+ const cacheSamples = [];
370540
+ let promptTokensReported = 0;
370541
+ let outputTokensReported = 0;
369437
370542
  for (const a of allAgents) {
369438
370543
  try {
369439
370544
  const agent = agentManager.getAgent(a.id);
@@ -369443,10 +370548,17 @@ EXPLANATION_END`;
369443
370548
  messages += stats.requestsToday;
369444
370549
  cacheReadTokens += stats.cacheReadTokens;
369445
370550
  cacheWriteTokens += stats.cacheWriteTokens;
369446
- cacheHitRate += stats.cacheHitRate;
370551
+ cacheSamples.push({
370552
+ cacheReadReported: stats.cacheReadReported ?? 0,
370553
+ cacheDenominatorTotal: stats.cacheDenominatorTotal ?? 0
370554
+ });
370555
+ promptTokensReported += stats.cacheDenominatorTotal ?? 0;
370556
+ outputTokensReported += stats.completionTokens;
369447
370557
  } catch {
369448
370558
  }
369449
370559
  }
370560
+ const agg = aggregateCacheHitRate(cacheSamples);
370561
+ const replayRatio = computeReplayRatio(promptTokensReported, outputTokensReported);
369450
370562
  this.json(res, 200, {
369451
370563
  usage: {
369452
370564
  orgId: orgId2,
@@ -369456,7 +370568,13 @@ EXPLANATION_END`;
369456
370568
  messages,
369457
370569
  cacheReadTokens,
369458
370570
  cacheWriteTokens,
369459
- cacheHitRate: allAgents.length > 0 ? Math.round(cacheHitRate / allAgents.length * 1e3) / 1e3 : 0,
370571
+ // null ⇒ nothing measured. Callers must render "unknown", not 0%.
370572
+ cacheHitRate: agg.cacheHitRate === null ? 0 : Math.round(agg.cacheHitRate * 1e3) / 1e3,
370573
+ cacheHitRateUnknown: agg.cacheHitRate === null,
370574
+ cacheHitSamples: agg.cacheHitSamples,
370575
+ // Prompt tokens re-sent per output token produced. A 96% hit rate can
370576
+ // still be pathological; this number is the cost itself.
370577
+ replayRatio: replayRatio === null ? null : Math.round(replayRatio * 10) / 10,
369460
370578
  storageBytes: this.billingService?.getUsageSummary(orgId2)?.storageBytes ?? 0
369461
370579
  },
369462
370580
  plan
@@ -369951,9 +371069,9 @@ EXPLANATION_END`;
369951
371069
  this.llmRouter?.setMarkusHubRemainingHint(null);
369952
371070
  }
369953
371071
  }
369954
- log91.info(`Hub token saved per-user for ${authUser.userId}${authUser.role === "owner" ? " (+ owner global file)" : ""}`);
371072
+ log92.info(`Hub token saved per-user for ${authUser.userId}${authUser.role === "owner" ? " (+ owner global file)" : ""}`);
369955
371073
  } catch (err) {
369956
- log91.error("Failed to write hub token", { error: String(err) });
371074
+ log92.error("Failed to write hub token", { error: String(err) });
369957
371075
  }
369958
371076
  this.auditService?.record({
369959
371077
  orgId: "system",
@@ -369996,7 +371114,7 @@ EXPLANATION_END`;
369996
371114
  markusConfig.model = existing.model;
369997
371115
  if (Object.keys(markusConfig).length > 0) {
369998
371116
  saveConfig2({ llm: { providers: { markus: markusConfig } } });
369999
- log91.info("Markus OpenRouter credentials saved", {
371117
+ log92.info("Markus OpenRouter credentials saved", {
370000
371118
  hasOr: savedOpenRouter,
370001
371119
  hasModelsUrl: !!markusConfig.modelsUrl
370002
371120
  });
@@ -370026,10 +371144,10 @@ EXPLANATION_END`;
370026
371144
  this.invalidateRoutingCache();
370027
371145
  }
370028
371146
  } catch (err) {
370029
- log91.warn("Failed to hot-reload Markus provider after Hub connect", { error: String(err) });
371147
+ log92.warn("Failed to hot-reload Markus provider after Hub connect", { error: String(err) });
370030
371148
  }
370031
371149
  } catch (err) {
370032
- log91.error("Failed to save openrouter key", { error: String(err) });
371150
+ log92.error("Failed to save openrouter key", { error: String(err) });
370033
371151
  }
370034
371152
  this.auditService?.record({
370035
371153
  orgId: "system",
@@ -370340,7 +371458,7 @@ EXPLANATION_END`;
370340
371458
  if (this.isLegacyMarkusSubscriptionKey(markusKey)) {
370341
371459
  const sync = await this.syncOpenRouterCredentialsFromHub({ force: true });
370342
371460
  if (!sync.ok) {
370343
- log91.warn("Legacy Markus key present but OpenRouter sync failed", { error: sync.error });
371461
+ log92.warn("Legacy Markus key present but OpenRouter sync failed", { error: sync.error });
370344
371462
  }
370345
371463
  }
370346
371464
  const preview = this.llmRouter.getEnhancedSettings();
@@ -370434,7 +371552,7 @@ EXPLANATION_END`;
370434
371552
  try {
370435
371553
  saveConfig({ llm: configUpdates }, this.markusConfigPath);
370436
371554
  } catch (e) {
370437
- log91.warn("Failed to persist LLM settings to config file", { error: String(e) });
371555
+ log92.warn("Failed to persist LLM settings to config file", { error: String(e) });
370438
371556
  }
370439
371557
  this.auditService?.record({
370440
371558
  orgId: "system",
@@ -370649,7 +371767,7 @@ EXPLANATION_END`;
370649
371767
  }
370650
371768
  }, this.markusConfigPath);
370651
371769
  } catch (e) {
370652
- log91.warn("Failed to persist agent settings to config file", { error: String(e) });
371770
+ log92.warn("Failed to persist agent settings to config file", { error: String(e) });
370653
371771
  }
370654
371772
  for (const info2 of am.listAgents()) {
370655
371773
  const agent = am.getAgent(info2.id);
@@ -370758,7 +371876,7 @@ EXPLANATION_END`;
370758
371876
  am.setBrowserAutoClickAllowDialog(updates.autoClickAllowDialog);
370759
371877
  }
370760
371878
  } catch (e) {
370761
- log91.warn("Failed to persist browser settings", { error: String(e) });
371879
+ log92.warn("Failed to persist browser settings", { error: String(e) });
370762
371880
  }
370763
371881
  if (Object.keys(updates).length > 0) {
370764
371882
  this.auditService?.record({
@@ -371049,7 +372167,7 @@ data: ${JSON.stringify({ error: msg })}
371049
372167
  try {
371050
372168
  saveConfig({ integrations: { search: searchUpdates } }, this.markusConfigPath);
371051
372169
  } catch (e) {
371052
- log91.warn("Failed to persist search settings", { error: String(e) });
372170
+ log92.warn("Failed to persist search settings", { error: String(e) });
371053
372171
  }
371054
372172
  try {
371055
372173
  const { loadConfig: reload } = await Promise.resolve().then(() => (init_dist(), dist_exports));
@@ -371332,7 +372450,7 @@ data: ${JSON.stringify({ error: msg })}
371332
372450
  const am = this.orgService.getAgentManager();
371333
372451
  am.setCodingToolsConfig(updates);
371334
372452
  } catch (e) {
371335
- log91.warn("Failed to persist coding tools settings", { error: String(e) });
372453
+ log92.warn("Failed to persist coding tools settings", { error: String(e) });
371336
372454
  this.json(res, 500, { error: `Failed to save coding tools settings: ${e}` });
371337
372455
  return;
371338
372456
  }
@@ -371395,7 +372513,7 @@ data: ${JSON.stringify({ error: msg })}
371395
372513
  }
371396
372514
  this.json(res, 200, { tool: toolName, models: result.models, source: result.source, hint: result.hint });
371397
372515
  } catch (err) {
371398
- log91.error(`Failed to list models for ${toolName}`, { error: err instanceof Error ? err.message : String(err) });
372516
+ log92.error(`Failed to list models for ${toolName}`, { error: err instanceof Error ? err.message : String(err) });
371399
372517
  this.json(res, 200, { tool: toolName, models: [], source: "cli", error: err instanceof Error ? err.message : "Unknown error" });
371400
372518
  }
371401
372519
  return;
@@ -371547,7 +372665,7 @@ data: ${JSON.stringify({ error: msg })}
371547
372665
  this.invalidateRoutingCache();
371548
372666
  if (!this.llmRouter.routingDefaultModel && enabled !== false) {
371549
372667
  this.llmRouter.setRoutingDefaultModel({ provider: name, model });
371550
- log91.info("Auto-set routing default model for first provider", { provider: name, model });
372668
+ log92.info("Auto-set routing default model for first provider", { provider: name, model });
371551
372669
  }
371552
372670
  try {
371553
372671
  const { loadConfig: loadCfg } = await Promise.resolve().then(() => (init_dist(), dist_exports));
@@ -371571,7 +372689,7 @@ data: ${JSON.stringify({ error: msg })}
371571
372689
  }
371572
372690
  saveConfig({ llm: configUpdates }, this.markusConfigPath);
371573
372691
  } catch (e) {
371574
- log91.warn("Failed to persist new provider", { error: String(e) });
372692
+ log92.warn("Failed to persist new provider", { error: String(e) });
371575
372693
  }
371576
372694
  this.auditService?.record({
371577
372695
  orgId: "system",
@@ -371655,7 +372773,7 @@ data: ${JSON.stringify({ error: msg })}
371655
372773
  providers[providerName] = next;
371656
372774
  saveConfig({ llm: { providers } }, this.markusConfigPath);
371657
372775
  } catch (e) {
371658
- log91.warn("Failed to persist provider update", { error: String(e) });
372776
+ log92.warn("Failed to persist provider update", { error: String(e) });
371659
372777
  }
371660
372778
  this.auditService?.record({
371661
372779
  orgId: "system",
@@ -371696,7 +372814,7 @@ data: ${JSON.stringify({ error: msg })}
371696
372814
  }
371697
372815
  saveConfig(configUpdates, this.markusConfigPath);
371698
372816
  } catch (e) {
371699
- log91.warn("Failed to persist provider deletion", { error: String(e) });
372817
+ log92.warn("Failed to persist provider deletion", { error: String(e) });
371700
372818
  }
371701
372819
  this.auditService?.record({
371702
372820
  orgId: "system",
@@ -371749,7 +372867,7 @@ data: ${JSON.stringify({ error: msg })}
371749
372867
  customModels[providerName] = [...existing.filter((m) => m.id !== id), modelDef];
371750
372868
  saveConfig({ llm: { customModels } }, this.markusConfigPath);
371751
372869
  } catch (e) {
371752
- log91.warn("Failed to persist custom model", { error: String(e) });
372870
+ log92.warn("Failed to persist custom model", { error: String(e) });
371753
372871
  }
371754
372872
  this.auditService?.record({
371755
372873
  orgId: "system",
@@ -371789,7 +372907,7 @@ data: ${JSON.stringify({ error: msg })}
371789
372907
  };
371790
372908
  saveConfig({ llm: { customModels: customModelsUpdate } }, this.markusConfigPath);
371791
372909
  } catch (e) {
371792
- log91.warn("Failed to persist custom model removal", { error: String(e) });
372910
+ log92.warn("Failed to persist custom model removal", { error: String(e) });
371793
372911
  }
371794
372912
  this.auditService?.record({
371795
372913
  orgId: "system",
@@ -371830,7 +372948,7 @@ data: ${JSON.stringify({ error: msg })}
371830
372948
  providers[providerName] = { ...providers[providerName], model };
371831
372949
  saveConfig({ llm: { providers } }, this.markusConfigPath);
371832
372950
  } catch (e) {
371833
- log91.warn("Failed to persist provider model change", { error: String(e) });
372951
+ log92.warn("Failed to persist provider model change", { error: String(e) });
371834
372952
  }
371835
372953
  this.auditService?.record({
371836
372954
  orgId: "system",
@@ -371882,7 +373000,7 @@ data: ${JSON.stringify({ error: msg })}
371882
373000
  }
371883
373001
  saveConfig(configUpdates, this.markusConfigPath);
371884
373002
  } catch (e) {
371885
- log91.warn("Failed to persist provider enabled state", { error: String(e) });
373003
+ log92.warn("Failed to persist provider enabled state", { error: String(e) });
371886
373004
  }
371887
373005
  this.auditService?.record({
371888
373006
  orgId: "system",
@@ -372162,7 +373280,7 @@ data: ${JSON.stringify({ error: msg })}
372162
373280
  baseUrl: cfg?.baseUrl
372163
373281
  });
372164
373282
  } catch (e) {
372165
- log91.warn(`Failed to hot-register provider ${provName}`, { error: String(e) });
373283
+ log92.warn(`Failed to hot-register provider ${provName}`, { error: String(e) });
372166
373284
  }
372167
373285
  }
372168
373286
  }
@@ -372173,7 +373291,7 @@ data: ${JSON.stringify({ error: msg })}
372173
373291
  if (first) {
372174
373292
  this.llmRouter.setRoutingDefaultModel({ provider: first.provider, model: first.model });
372175
373293
  saveConfig({ llm: { routingDefaultModel: { provider: first.provider, model: first.model } } }, this.markusConfigPath);
372176
- log91.info("Auto-set routing default model from env detection", { provider: first.provider, model: first.model });
373294
+ log92.info("Auto-set routing default model from env detection", { provider: first.provider, model: first.model });
372177
373295
  }
372178
373296
  }
372179
373297
  }
@@ -372236,18 +373354,18 @@ data: ${JSON.stringify({ error: msg })}
372236
373354
  try {
372237
373355
  const { authorizeUrl, promise } = await this.llmRouter.oauthManager.startLogin(provider);
372238
373356
  promise.then((profile) => {
372239
- log91.info(`OAuth login completed for ${provider}`, { profileId: profile.id });
373357
+ log92.info(`OAuth login completed for ${provider}`, { profileId: profile.id });
372240
373358
  if (this.llmRouter && !this.llmRouter.getProvider(provider)) {
372241
373359
  try {
372242
373360
  this.llmRouter.registerOAuthProvider(provider, profile, {
372243
373361
  model: provider === "openai-codex" ? "gpt-5.5" : void 0
372244
373362
  });
372245
373363
  } catch (err) {
372246
- log91.warn(`Failed to auto-register OAuth provider after login`, { error: String(err) });
373364
+ log92.warn(`Failed to auto-register OAuth provider after login`, { error: String(err) });
372247
373365
  }
372248
373366
  }
372249
373367
  }).catch((err) => {
372250
- log91.warn(`OAuth login failed for ${provider}`, { error: String(err) });
373368
+ log92.warn(`OAuth login failed for ${provider}`, { error: String(err) });
372251
373369
  });
372252
373370
  this.json(res, 200, { authorizeUrl, provider });
372253
373371
  } catch (err) {
@@ -372272,18 +373390,18 @@ data: ${JSON.stringify({ error: msg })}
372272
373390
  try {
372273
373391
  const { userCode, verificationUri, promise } = await this.llmRouter.oauthManager.startDeviceCodeLogin(provider);
372274
373392
  promise.then((profile) => {
372275
- log91.info(`Device code OAuth login completed for ${provider}`, { profileId: profile.id });
373393
+ log92.info(`Device code OAuth login completed for ${provider}`, { profileId: profile.id });
372276
373394
  if (this.llmRouter && !this.llmRouter.getProvider(provider)) {
372277
373395
  try {
372278
373396
  this.llmRouter.registerOAuthProvider(provider, profile, {
372279
373397
  model: provider === "openai-codex" ? "gpt-5.5" : void 0
372280
373398
  });
372281
373399
  } catch (err) {
372282
- log91.warn(`Failed to auto-register OAuth provider after device code login`, { error: String(err) });
373400
+ log92.warn(`Failed to auto-register OAuth provider after device code login`, { error: String(err) });
372283
373401
  }
372284
373402
  }
372285
373403
  }).catch((err) => {
372286
- log91.warn(`Device code OAuth login failed for ${provider}`, { error: String(err) });
373404
+ log92.warn(`Device code OAuth login failed for ${provider}`, { error: String(err) });
372287
373405
  });
372288
373406
  this.json(res, 200, { userCode, verificationUri, provider });
372289
373407
  } catch (err) {
@@ -372459,7 +373577,7 @@ data: ${JSON.stringify({ error: msg })}
372459
373577
  try {
372460
373578
  this.json(res, 200, { instances: listInstanceStatuses(instanceStore(auth.orgId)) });
372461
373579
  } catch (e) {
372462
- log91.error("Failed to list bot instances", { error: String(e) });
373580
+ log92.error("Failed to list bot instances", { error: String(e) });
372463
373581
  this.json(res, 500, { error: "Failed to list bot instances" });
372464
373582
  }
372465
373583
  return;
@@ -372502,7 +373620,7 @@ data: ${JSON.stringify({ error: msg })}
372502
373620
  this.json(res, 409, { error: message });
372503
373621
  return;
372504
373622
  }
372505
- log91.error("Failed to create bot instance", { platform: platform11, error: message });
373623
+ log92.error("Failed to create bot instance", { platform: platform11, error: message });
372506
373624
  this.json(res, 500, { error: "Failed to create bot instance" });
372507
373625
  }
372508
373626
  return;
@@ -372562,7 +373680,7 @@ data: ${JSON.stringify({ error: msg })}
372562
373680
  this.json(res, 400, { error: e.message, missing: e.missing });
372563
373681
  return;
372564
373682
  }
372565
- log91.error("Failed to save bot instance", { id, error: String(e) });
373683
+ log92.error("Failed to save bot instance", { id, error: String(e) });
372566
373684
  this.json(res, 500, { error: "Failed to save bot instance" });
372567
373685
  }
372568
373686
  return;
@@ -372593,7 +373711,7 @@ data: ${JSON.stringify({ error: msg })}
372593
373711
  });
372594
373712
  this.json(res, 200, { success: true });
372595
373713
  } catch (e) {
372596
- log91.error("Failed to delete bot instance", { id, error: String(e) });
373714
+ log92.error("Failed to delete bot instance", { id, error: String(e) });
372597
373715
  this.json(res, 500, { error: "Failed to delete bot instance" });
372598
373716
  }
372599
373717
  return;
@@ -372632,7 +373750,7 @@ data: ${JSON.stringify({ error: msg })}
372632
373750
  message: result.ok ? "Credentials verified successfully" : result.error ?? "Authentication failed"
372633
373751
  });
372634
373752
  } catch (e) {
372635
- log91.error("Bot instance credential test failed", { id, platform: existing.platform, error: String(e) });
373753
+ log92.error("Bot instance credential test failed", { id, platform: existing.platform, error: String(e) });
372636
373754
  this.json(res, 200, { ok: false, success: false, message: `Connection failed: ${String(e)}` });
372637
373755
  }
372638
373756
  return;
@@ -372677,7 +373795,7 @@ data: ${JSON.stringify({ error: msg })}
372677
373795
  });
372678
373796
  this.json(res, 200, { test });
372679
373797
  } catch (e) {
372680
- log91.error("Failed to start bot instance connection test", { id, error: String(e) });
373798
+ log92.error("Failed to start bot instance connection test", { id, error: String(e) });
372681
373799
  this.json(res, 500, { error: "Failed to start connection test" });
372682
373800
  }
372683
373801
  return;
@@ -372731,7 +373849,7 @@ data: ${JSON.stringify({ error: msg })}
372731
373849
  const channels = await manifest.listChannels(config);
372732
373850
  this.json(res, 200, { supported: true, channels });
372733
373851
  } catch (e) {
372734
- log91.warn("Failed to list platform channels", {
373852
+ log92.warn("Failed to list platform channels", {
372735
373853
  instanceId: id,
372736
373854
  platform: instance.platform,
372737
373855
  error: String(e)
@@ -372784,7 +373902,7 @@ data: ${JSON.stringify({ error: msg })}
372784
373902
  });
372785
373903
  this.json(res, 200, { instance });
372786
373904
  } catch (e) {
372787
- log91.error("Failed to save bot instance channels", { id, error: String(e) });
373905
+ log92.error("Failed to save bot instance channels", { id, error: String(e) });
372788
373906
  this.json(res, 500, { error: "Failed to save bot instance channels" });
372789
373907
  }
372790
373908
  return;
@@ -372798,7 +373916,7 @@ data: ${JSON.stringify({ error: msg })}
372798
373916
  try {
372799
373917
  this.json(res, 200, { platforms: listPlatformStatuses(platformStore(auth.orgId)) });
372800
373918
  } catch (e) {
372801
- log91.error("Failed to list integrations", { error: String(e) });
373919
+ log92.error("Failed to list integrations", { error: String(e) });
372802
373920
  this.json(res, 500, { error: "Failed to list integrations" });
372803
373921
  }
372804
373922
  return;
@@ -372828,7 +373946,7 @@ data: ${JSON.stringify({ error: msg })}
372828
373946
  message: result.ok ? "Credentials verified successfully" : result.error ?? "Authentication failed"
372829
373947
  });
372830
373948
  } catch (e) {
372831
- log91.error("Integration credential test failed", { platform: platform11, error: String(e) });
373949
+ log92.error("Integration credential test failed", { platform: platform11, error: String(e) });
372832
373950
  this.json(res, 200, { ok: false, success: false, message: `Connection failed: ${String(e)}` });
372833
373951
  }
372834
373952
  return;
@@ -372876,7 +373994,7 @@ data: ${JSON.stringify({ error: msg })}
372876
373994
  });
372877
373995
  this.json(res, 200, { success: true, ...flattenStatus(status) });
372878
373996
  } catch (e) {
372879
- log91.error("Failed to save integration config", { platform: platform11, error: String(e) });
373997
+ log92.error("Failed to save integration config", { platform: platform11, error: String(e) });
372880
373998
  this.json(res, 500, { error: "Failed to save integration config" });
372881
373999
  }
372882
374000
  return;
@@ -372903,7 +374021,7 @@ data: ${JSON.stringify({ error: msg })}
372903
374021
  });
372904
374022
  this.json(res, 200, { success: true });
372905
374023
  } catch (e) {
372906
- log91.error("Failed to delete integration config", { platform: platform11, error: String(e) });
374024
+ log92.error("Failed to delete integration config", { platform: platform11, error: String(e) });
372907
374025
  this.json(res, 500, { error: "Failed to delete integration config" });
372908
374026
  }
372909
374027
  return;
@@ -372925,7 +374043,7 @@ data: ${JSON.stringify({ error: msg })}
372925
374043
  const chats = await client.listBotChats();
372926
374044
  this.json(res, 200, { chats });
372927
374045
  } catch (e) {
372928
- log91.error("Failed to list Feishu bot chats", { error: String(e) });
374046
+ log92.error("Failed to list Feishu bot chats", { error: String(e) });
372929
374047
  this.json(res, 200, { chats: [], error: String(e) });
372930
374048
  }
372931
374049
  return;
@@ -372974,7 +374092,7 @@ data: ${JSON.stringify({ error: msg })}
372974
374092
  await client.sendCard(chatId, card);
372975
374093
  this.json(res, 200, { success: true, message: "Test message sent" });
372976
374094
  } catch (e) {
372977
- log91.error("Feishu test message failed", { error: String(e) });
374095
+ log92.error("Feishu test message failed", { error: String(e) });
372978
374096
  this.json(res, 200, { success: false, message: `Send failed: ${String(e)}` });
372979
374097
  }
372980
374098
  return;
@@ -373032,7 +374150,7 @@ data: ${JSON.stringify({ error: msg })}
373032
374150
  notifyPriority: ["normal", "high", "urgent"]
373033
374151
  });
373034
374152
  await this.reconcileInstanceRuntime(instance.id);
373035
- log91.info("Feishu app registered via QR scan", {
374153
+ log92.info("Feishu app registered via QR scan", {
373036
374154
  orgId: auth.orgId,
373037
374155
  appId,
373038
374156
  instanceId: instance.id
@@ -373129,9 +374247,9 @@ You can now:
373129
374247
  };
373130
374248
  await welcomeClient.sendCardToUser(openId, card);
373131
374249
  }
373132
- log91.info("Welcome message sent to user", { openId, locale });
374250
+ log92.info("Welcome message sent to user", { openId, locale });
373133
374251
  } catch (welcomeErr) {
373134
- log91.warn("Failed to send welcome message", { error: String(welcomeErr) });
374252
+ log92.warn("Failed to send welcome message", { error: String(welcomeErr) });
373135
374253
  }
373136
374254
  }
373137
374255
  this.json(res, 200, {
@@ -373151,7 +374269,7 @@ You can now:
373151
374269
  } else if (err.code === "expired_token" || err.code === "abort") {
373152
374270
  this.json(res, 200, { success: false, error: "expired", message: "\u4E8C\u7EF4\u7801\u5DF2\u8FC7\u671F\u6216\u8D85\u65F6" });
373153
374271
  } else {
373154
- log91.error("Feishu register app failed", { error: String(e) });
374272
+ log92.error("Feishu register app failed", { error: String(e) });
373155
374273
  this.json(res, 200, { success: false, error: "unknown", message: String(err.message || err.description || e) });
373156
374274
  }
373157
374275
  }
@@ -373184,7 +374302,7 @@ You can now:
373184
374302
  const rules = row?.["forwardRules"];
373185
374303
  this.json(res, 200, { rules: rules ?? [] });
373186
374304
  } catch (e) {
373187
- log91.error("Failed to read notification rules", { error: String(e) });
374305
+ log92.error("Failed to read notification rules", { error: String(e) });
373188
374306
  this.json(res, 500, { error: "Failed to read notification rules" });
373189
374307
  }
373190
374308
  return;
@@ -373212,7 +374330,7 @@ You can now:
373212
374330
  lastVerifiedAt: row["lastVerifiedAt"] ?? null,
373213
374331
  lastError: row["lastError"] ?? null
373214
374332
  });
373215
- log91.info("Feishu notification rules updated", { orgId: auth.orgId, ruleCount: rules.length });
374333
+ log92.info("Feishu notification rules updated", { orgId: auth.orgId, ruleCount: rules.length });
373216
374334
  this.auditService?.record({
373217
374335
  orgId: auth.orgId,
373218
374336
  type: "settings_changed",
@@ -373226,7 +374344,7 @@ You can now:
373226
374344
  this.json(res, 404, { error: "Feishu integration not configured" });
373227
374345
  }
373228
374346
  } catch (e) {
373229
- log91.error("Failed to update notification rules", { error: String(e) });
374347
+ log92.error("Failed to update notification rules", { error: String(e) });
373230
374348
  this.json(res, 500, { error: "Failed to update notification rules" });
373231
374349
  }
373232
374350
  return;
@@ -373432,7 +374550,7 @@ You can now:
373432
374550
  this.json(res, 404, { error: `Workflow "${wfName}" not found` });
373433
374551
  return;
373434
374552
  }
373435
- this.json(res, 200, { template });
374553
+ this.json(res, 200, { template, yaml: this.workflowService.getWorkflowYaml(teamId, wfName) ?? void 0 });
373436
374554
  return;
373437
374555
  }
373438
374556
  if (wfName && !wfSub && req.method === "PUT") {
@@ -374390,7 +375508,7 @@ You can now:
374390
375508
  }
374391
375509
  exec2(cmd, (err) => {
374392
375510
  if (err) {
374393
- log91.warn("Failed to reveal file in system browser", { path: resolved, error: String(err) });
375511
+ log92.warn("Failed to reveal file in system browser", { path: resolved, error: String(err) });
374394
375512
  }
374395
375513
  });
374396
375514
  this.json(res, 200, { ok: true, path: resolved });
@@ -374579,6 +375697,29 @@ You can now:
374579
375697
  }
374580
375698
  return;
374581
375699
  }
375700
+ if (path.match(/^\/api\/requirements\/[^/]+\/tasks\/approve-bulk$/) && req.method === "POST") {
375701
+ const authUser = await this.requireAuth(req, res);
375702
+ if (!authUser)
375703
+ return;
375704
+ const reqId = path.split("/")[3];
375705
+ if (!this.taskService) {
375706
+ this.json(res, 503, { error: "Task service not available" });
375707
+ return;
375708
+ }
375709
+ const body = await this.readBody(req);
375710
+ const dryRun = body["dryRun"] === true;
375711
+ try {
375712
+ const result = this.taskService.approveRequirementTasks(reqId, {
375713
+ dryRun,
375714
+ runNow: body["runNow"] !== false,
375715
+ actorId: authUser.userId
375716
+ });
375717
+ this.json(res, 200, { ...result, dryRun });
375718
+ } catch (e) {
375719
+ this.json(res, 400, { error: String(e) });
375720
+ }
375721
+ return;
375722
+ }
374582
375723
  if (path.match(/^\/api\/requirements\/[^/]+\/reject$/) && req.method === "POST") {
374583
375724
  const authUser = await this.requireAuth(req, res);
374584
375725
  if (!authUser)
@@ -375318,6 +376459,7 @@ You can now:
375318
376459
  regex(/^\/api\/requirements\/[^/]+$/, "GET", "PUT", "DELETE"),
375319
376460
  regex(/^\/api\/requirements\/[^/]+\/status$/, "POST"),
375320
376461
  regex(/^\/api\/requirements\/[^/]+\/approve$/, "POST"),
376462
+ regex(/^\/api\/requirements\/[^/]+\/tasks\/approve-bulk$/, "POST"),
375321
376463
  regex(/^\/api\/requirements\/[^/]+\/reject$/, "POST"),
375322
376464
  regex(/^\/api\/requirements\/[^/]+\/cancel$/, "POST"),
375323
376465
  regex(/^\/api\/requirements\/[^/]+\/request-approval$/, "POST"),
@@ -376284,617 +377426,6 @@ You can now:
376284
377426
  }
376285
377427
  });
376286
377428
 
376287
- // ../org-manager/dist/hitl-service.js
376288
- function normalizeIntentToken(raw) {
376289
- return raw.trim().toLowerCase().replace(/[\s-]+/g, "_");
376290
- }
376291
- function intentToApprovalStatus(intent) {
376292
- if (intent === "approve")
376293
- return "approved";
376294
- if (intent === "reject")
376295
- return "rejected";
376296
- return "changes_requested";
376297
- }
376298
- function resolveApprovalIntent(input) {
376299
- const raw = input.selectedOption?.trim();
376300
- if (raw) {
376301
- const token = normalizeIntentToken(raw);
376302
- const gateAlias = input.subType ? GATE_OPTION_ALIASES[input.subType]?.[token] : void 0;
376303
- if (gateAlias)
376304
- return { intent: gateAlias };
376305
- const intent = GLOBAL_INTENT_TOKENS[token];
376306
- if (intent)
376307
- return { intent };
376308
- return { intent: input.approved ? "approve" : "reject", unknownOption: raw };
376309
- }
376310
- return { intent: input.approved ? "approve" : "reject" };
376311
- }
376312
- function genId(prefix) {
376313
- return `${prefix}_${Date.now().toString(36)}_${(++idCounter).toString(36)}`;
376314
- }
376315
- var log92, GLOBAL_INTENT_TOKENS, GATE_OPTION_ALIASES, APPROVALS_IN_MEMORY_CAP, idCounter, HITLService;
376316
- var init_hitl_service = __esm({
376317
- "../org-manager/dist/hitl-service.js"() {
376318
- "use strict";
376319
- init_dist();
376320
- log92 = createLogger("hitl");
376321
- GLOBAL_INTENT_TOKENS = {
376322
- approve: "approve",
376323
- approved: "approve",
376324
- request_changes: "request_changes",
376325
- requestchanges: "request_changes",
376326
- changes_requested: "request_changes",
376327
- revision: "request_changes",
376328
- needs_adjustment: "needs_adjustment",
376329
- needsadjustment: "needs_adjustment",
376330
- reject: "reject",
376331
- rejected: "reject"
376332
- };
376333
- GATE_OPTION_ALIASES = {
376334
- task_review: { reject: "request_changes" }
376335
- };
376336
- APPROVALS_IN_MEMORY_CAP = 200;
376337
- idCounter = 0;
376338
- HITLService = class {
376339
- approvals = /* @__PURE__ */ new Map();
376340
- pendingResolvers = /* @__PURE__ */ new Map();
376341
- /**
376342
- * The router that drives a **recorded decision** to its gate.
376343
- *
376344
- * Set once by the composition root. Deliberately owned by this service rather
376345
- * than by any inbound surface: recording a decision and applying it must not be
376346
- * two independent obligations, because a surface that honours only the first
376347
- * one fails **silently** — the 2026-10-16 Feishu card tap that recorded
376348
- * "approved" while the task stayed `pending`, because the only thing that knew
376349
- * how to apply it was an in-memory promise that had died with the last restart.
376350
- * Routing at the single point where a decision is written makes that omission
376351
- * unrepresentable for every surface, present and future.
376352
- */
376353
- decisionRouter;
376354
- notificationHandlers = [];
376355
- /**
376356
- * Channel-level consumers — the outbound gateway. Deliberately a **separate**
376357
- * list from {@link notificationHandlers}: the two answer different questions.
376358
- * "Who should see this in their bell" is per *person* (N emissions for
376359
- * `targetUserId:'all'`); "one channel message per logical notification" is per
376360
- * *channel* (exactly one). Sharing one list is the granularity confusion that
376361
- * made a single notification reach a Feishu group N times (req_d25dc9b9).
376362
- */
376363
- channelNotificationHandlers = [];
376364
- /**
376365
- * Approval-lifecycle consumers. A terminal transition (approved / rejected /
376366
- * cancelled / expired) is a change to authoritative state that **every**
376367
- * derived surface must observe — the in-app chat banner, the bell, any other
376368
- * client. Deliberately separate from the notification streams: notifications
376369
- * answer "tell this person", this one answers "the state changed".
376370
- *
376371
- * The emission lives at the transition itself (not at each call site) because
376372
- * a decision can be written from ≥3 places — the HTTP API, the in-process
376373
- * platform-action path, and the expiry timer. Wiring only the HTTP path is
376374
- * exactly how the chat banner used to linger forever after an approval was
376375
- * settled from Feishu (the resolving surface was not the one polling).
376376
- */
376377
- approvalChangeHandlers = [];
376378
- notificationRepo;
376379
- approvalRepo;
376380
- orgService;
376381
- setOrgService(service) {
376382
- this.orgService = service;
376383
- }
376384
- setNotificationRepo(repo) {
376385
- this.notificationRepo = repo;
376386
- try {
376387
- const healed = repo.reconcileResolvedApprovalNotifications?.() ?? 0;
376388
- if (healed > 0)
376389
- log92.info(`Reconciled ${healed} stale unread approval notification(s)`);
376390
- } catch (err) {
376391
- log92.warn("Failed to reconcile stale approval notifications", { error: String(err) });
376392
- }
376393
- }
376394
- /**
376395
- * Wire the router that applies a recorded decision to its gate. Called once by
376396
- * the composition root; see {@link decisionRouter} for why it lives here.
376397
- */
376398
- setDecisionRouter(router) {
376399
- this.decisionRouter = router;
376400
- }
376401
- setApprovalRepo(repo) {
376402
- this.approvalRepo = repo;
376403
- try {
376404
- const rows = repo.list({ limit: APPROVALS_IN_MEMORY_CAP });
376405
- for (const row of rows) {
376406
- if (!this.approvals.has(row.id))
376407
- this.approvals.set(row.id, this.rowToApproval(row));
376408
- }
376409
- log92.info(`Restored ${rows.length} approvals from storage`);
376410
- } catch (err) {
376411
- log92.warn("Failed to restore approvals from storage", { error: String(err) });
376412
- }
376413
- }
376414
- /**
376415
- * Paged, time-ordered approval read — the ONE read path for the list API.
376416
- *
376417
- * Two defects this replaces (owner report 2026-10-18 "审批似乎没法加载历史"):
376418
- * - The map only mirrors the newest {@link APPROVALS_IN_MEMORY_CAP} rows, so
376419
- * slicing the map could never reach real history.
376420
- * - `slice(offset, offset+limit)` over the map followed INSERTION order, and
376421
- * the restore inserts the startup snapshot first — every approval requested
376422
- * after startup landed at the END of the map and never appeared on page 1.
376423
- * The pending approvals were literally invisible in the bell.
376424
- */
376425
- listApprovalsPage(opts) {
376426
- const { status, limit, offset: offset2 } = opts;
376427
- if (this.approvalRepo) {
376428
- try {
376429
- const rows = this.approvalRepo.list({ status, limit, offset: offset2 });
376430
- const total = this.approvalRepo.count ? this.approvalRepo.count(status) : rows.length;
376431
- return { approvals: rows.map((r) => this.rowToApproval(r)), total };
376432
- } catch (err) {
376433
- log92.warn("Approval repo paging failed \u2014 falling back to memory", { error: String(err) });
376434
- }
376435
- }
376436
- const all = [...this.approvals.values()].filter((a) => !status || a.status === status).sort((a, b) => new Date(b.requestedAt).getTime() - new Date(a.requestedAt).getTime());
376437
- return { approvals: all.slice(offset2, offset2 + limit), total: all.length };
376438
- }
376439
- /** Single mapping from persisted row → domain object (restore + paging share it). */
376440
- rowToApproval(row) {
376441
- return {
376442
- id: row.id,
376443
- agentId: row.agentId,
376444
- agentName: row.agentName,
376445
- type: row.type,
376446
- title: row.title,
376447
- description: row.description,
376448
- details: row.details,
376449
- status: row.status,
376450
- requestedAt: row.requestedAt,
376451
- respondedAt: row.respondedAt,
376452
- respondedBy: row.respondedBy,
376453
- responseComment: row.responseComment,
376454
- expiresAt: row.expiresAt,
376455
- options: row.options,
376456
- allowFreeform: row.allowFreeform,
376457
- selectedOption: row.selectedOption,
376458
- appliedAt: row.appliedAt,
376459
- appliedIntent: row.appliedIntent,
376460
- questions: row.questions,
376461
- answers: row.answers,
376462
- approverUserIds: row.approverUserIds,
376463
- targetUserId: row.targetUserId
376464
- };
376465
- }
376466
- /**
376467
- * Per-person stream. Fires **once per human recipient** — `targetUserId:'all'`
376468
- * fans out to N emissions by design (the in-app bell / WS push is per person).
376469
- * Consumers that address a concrete user subscribe here.
376470
- */
376471
- onNotification(handler4) {
376472
- this.notificationHandlers.push(handler4);
376473
- return () => {
376474
- const idx = this.notificationHandlers.indexOf(handler4);
376475
- if (idx >= 0)
376476
- this.notificationHandlers.splice(idx, 1);
376477
- };
376478
- }
376479
- /**
376480
- * Channel-level stream — the single granularity the outbound gateway needs:
376481
- * fires **exactly once per `notify()` call**, no matter how many humans the
376482
- * notification fans out to. This is what structurally guarantees "one logical
376483
- * notification ⇒ one channel message", instead of leaving the dispatcher to
376484
- * de-duplicate N per-person emissions (req_d25dc9b9).
376485
- */
376486
- onChannelNotification(handler4) {
376487
- this.channelNotificationHandlers.push(handler4);
376488
- return () => {
376489
- const idx = this.channelNotificationHandlers.indexOf(handler4);
376490
- if (idx >= 0)
376491
- this.channelNotificationHandlers.splice(idx, 1);
376492
- };
376493
- }
376494
- /**
376495
- * Approval-lifecycle stream. Fires exactly once per terminal transition,
376496
- * whichever surface caused it (in-app modal, Feishu card tap, expiry timer).
376497
- * Consumers invalidate their derived views from this — that is what makes an
376498
- * approval decided in an external IM disappear from the in-app banner too.
376499
- */
376500
- onApprovalChanged(handler4) {
376501
- this.approvalChangeHandlers.push(handler4);
376502
- return () => {
376503
- const idx = this.approvalChangeHandlers.indexOf(handler4);
376504
- if (idx >= 0)
376505
- this.approvalChangeHandlers.splice(idx, 1);
376506
- };
376507
- }
376508
- emit(n2) {
376509
- for (const h of this.notificationHandlers) {
376510
- try {
376511
- h(n2);
376512
- } catch {
376513
- }
376514
- }
376515
- }
376516
- emitChannel(n2) {
376517
- for (const h of this.channelNotificationHandlers) {
376518
- try {
376519
- h(n2);
376520
- } catch {
376521
- }
376522
- }
376523
- }
376524
- emitApprovalChanged(approval) {
376525
- for (const h of this.approvalChangeHandlers) {
376526
- try {
376527
- h(approval);
376528
- } catch {
376529
- }
376530
- }
376531
- }
376532
- requestApproval(opts) {
376533
- const id = genId("apr");
376534
- const now3 = (/* @__PURE__ */ new Date()).toISOString();
376535
- const approval = {
376536
- id,
376537
- agentId: opts.agentId,
376538
- agentName: opts.agentName,
376539
- type: opts.type,
376540
- title: opts.title,
376541
- description: opts.description,
376542
- details: opts.details ?? {},
376543
- status: "pending",
376544
- requestedAt: now3,
376545
- expiresAt: opts.expiresInMs ? new Date(Date.now() + opts.expiresInMs).toISOString() : void 0,
376546
- options: opts.options,
376547
- allowFreeform: opts.allowFreeform,
376548
- questions: opts.questions,
376549
- approverUserIds: opts.approverUserIds,
376550
- targetUserId: opts.targetUserId
376551
- };
376552
- this.approvals.set(id, approval);
376553
- this.persistApproval(approval);
376554
- log92.info(`Approval requested: ${id} by ${opts.agentName}`);
376555
- this.notify({
376556
- targetUserId: opts.targetUserId ?? "all",
376557
- type: "approval_request",
376558
- title: opts.title,
376559
- body: opts.description,
376560
- priority: "high",
376561
- actionType: "navigate",
376562
- actionTarget: JSON.stringify({ path: `/approvals/${id}` }),
376563
- // `agentId` travels with the notification so the outbound gateway can route
376564
- // it to the producing agent's own channel before falling back to the global
376565
- // default (G4, design §7.3).
376566
- metadata: { approvalId: id, agentId: opts.agentId, options: opts.options, i18n: opts.i18n }
376567
- });
376568
- return approval;
376569
- }
376570
- async requestApprovalAndWait(opts) {
376571
- const approval = this.requestApproval(opts);
376572
- return new Promise((resolve27) => {
376573
- this.pendingResolvers.set(approval.id, resolve27);
376574
- if (opts.expiresInMs) {
376575
- setTimeout(() => {
376576
- if (this.pendingResolvers.has(approval.id)) {
376577
- this.pendingResolvers.delete(approval.id);
376578
- const a = this.approvals.get(approval.id);
376579
- if (a && a.status === "pending") {
376580
- a.status = "expired";
376581
- a.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
376582
- a.responseComment = "Approval timed out";
376583
- this.persistApproval(a);
376584
- this.markApprovalNotificationsRead(a.id);
376585
- this.emitApprovalChanged(a);
376586
- }
376587
- resolve27({ approved: false, intent: "reject", approvalId: approval.id, comment: "Approval timed out" });
376588
- }
376589
- }, opts.expiresInMs);
376590
- }
376591
- });
376592
- }
376593
- respondToApproval(id, approved, respondedBy, comment, selectedOption, answers) {
376594
- const approval = this.approvals.get(id);
376595
- if (!approval || approval.status !== "pending")
376596
- return void 0;
376597
- const subType = approval.details["subType"];
376598
- const decision = resolveApprovalIntent({ subType, selectedOption, approved });
376599
- approval.status = intentToApprovalStatus(decision.intent);
376600
- approval.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
376601
- approval.respondedBy = respondedBy;
376602
- if (comment)
376603
- approval.responseComment = comment;
376604
- if (selectedOption)
376605
- approval.selectedOption = selectedOption;
376606
- if (answers && answers.length > 0)
376607
- approval.answers = answers;
376608
- if (decision.unknownOption)
376609
- approval.details["unknownOption"] = decision.unknownOption;
376610
- this.persistApproval(approval);
376611
- log92.info(`Approval ${id} ${approval.status} (intent=${decision.intent}) by ${respondedBy}`, {
376612
- comment,
376613
- selectedOption,
376614
- unknownOption: decision.unknownOption,
376615
- answerCount: answers?.length ?? 0
376616
- });
376617
- this.markApprovalNotificationsRead(id);
376618
- this.emitApprovalChanged(approval);
376619
- const resolve27 = this.pendingResolvers.get(id);
376620
- if (resolve27) {
376621
- this.pendingResolvers.delete(id);
376622
- resolve27({
376623
- approved: decision.intent === "approve",
376624
- intent: decision.intent,
376625
- approvalId: approval.id,
376626
- comment,
376627
- selectedOption,
376628
- answers,
376629
- respondedBy,
376630
- ...decision.unknownOption ? { unknownOption: decision.unknownOption } : {}
376631
- });
376632
- }
376633
- const response = { approval, decision };
376634
- if (this.decisionRouter) {
376635
- queueMicrotask(() => this.decisionRouter?.(response));
376636
- }
376637
- return response;
376638
- }
376639
- /**
376640
- * Synchronous, check-and-set claim for "apply this approval decision to its
376641
- * target". Both consumers (the promise chain and the API fallback) call this
376642
- * before doing anything observable; only the winner may act.
376643
- *
376644
- * Deliberately keyed on the **approval entity** (persisted `appliedAt`):
376645
- * · target state is unusable — two of the three gates intentionally perform
376646
- * zero state transition, so a state-based guard would never fire;
376647
- * · `approval.status` is unusable — {@link respondToApproval} flips it first,
376648
- * which would make the *first* apply look like a duplicate.
376649
- *
376650
- * Synchronous by contract: no `await` between read and write, so the guard and
376651
- * the microtask that follows a resolved promise can never interleave.
376652
- */
376653
- claimApply(id, intent) {
376654
- const approval = this.approvals.get(id);
376655
- if (!approval)
376656
- return false;
376657
- if (approval.appliedAt)
376658
- return false;
376659
- approval.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
376660
- approval.appliedIntent = intent;
376661
- this.persistApproval(approval);
376662
- log92.info("Approval decision claimed for apply", { id, intent });
376663
- return true;
376664
- }
376665
- cancelApproval(id, cancelledBy, comment) {
376666
- const approval = this.approvals.get(id);
376667
- if (!approval || approval.status !== "pending")
376668
- return void 0;
376669
- approval.status = "cancelled";
376670
- approval.respondedAt = (/* @__PURE__ */ new Date()).toISOString();
376671
- approval.respondedBy = cancelledBy;
376672
- if (comment)
376673
- approval.responseComment = comment;
376674
- this.persistApproval(approval);
376675
- log92.info(`Approval ${id} cancelled by ${cancelledBy}`, { comment });
376676
- this.markApprovalNotificationsRead(id);
376677
- this.emitApprovalChanged(approval);
376678
- const resolve27 = this.pendingResolvers.get(id);
376679
- if (resolve27) {
376680
- this.pendingResolvers.delete(id);
376681
- resolve27({
376682
- approved: false,
376683
- intent: "reject",
376684
- approvalId: approval.id,
376685
- comment: comment ?? "Approval cancelled"
376686
- });
376687
- }
376688
- return approval;
376689
- }
376690
- cancelApprovalsByDetail(key2, value, cancelledBy, comment) {
376691
- let count = 0;
376692
- for (const approval of this.approvals.values()) {
376693
- if (approval.status === "pending" && approval.details[key2] === value) {
376694
- this.cancelApproval(approval.id, cancelledBy, comment);
376695
- count++;
376696
- }
376697
- }
376698
- return count;
376699
- }
376700
- persistApproval(approval) {
376701
- if (!this.approvalRepo)
376702
- return;
376703
- try {
376704
- this.approvalRepo.upsert({
376705
- id: approval.id,
376706
- agentId: approval.agentId,
376707
- agentName: approval.agentName,
376708
- type: approval.type,
376709
- title: approval.title,
376710
- description: approval.description,
376711
- details: approval.details,
376712
- status: approval.status,
376713
- requestedAt: approval.requestedAt,
376714
- respondedAt: approval.respondedAt,
376715
- respondedBy: approval.respondedBy,
376716
- responseComment: approval.responseComment,
376717
- expiresAt: approval.expiresAt,
376718
- options: approval.options,
376719
- allowFreeform: approval.allowFreeform,
376720
- selectedOption: approval.selectedOption,
376721
- appliedAt: approval.appliedAt,
376722
- appliedIntent: approval.appliedIntent,
376723
- questions: approval.questions,
376724
- answers: approval.answers,
376725
- approverUserIds: approval.approverUserIds,
376726
- targetUserId: approval.targetUserId
376727
- });
376728
- } catch (err) {
376729
- log92.warn("Failed to persist approval", { id: approval.id, error: String(err) });
376730
- }
376731
- }
376732
- listApprovals(status) {
376733
- const all = [...this.approvals.values()];
376734
- return status ? all.filter((a) => a.status === status) : all;
376735
- }
376736
- getApproval(id) {
376737
- return this.approvals.get(id);
376738
- }
376739
- listNotifications(userId2, unreadOnly = false, opts) {
376740
- if (this.notificationRepo && userId2) {
376741
- const rows = this.notificationRepo.list(userId2, {
376742
- unreadOnly,
376743
- limit: opts?.limit,
376744
- offset: opts?.offset,
376745
- type: opts?.type
376746
- });
376747
- return rows.map((r) => this.rowToNotification(r));
376748
- }
376749
- return [];
376750
- }
376751
- countNotifications(userId2, unreadOnly = false) {
376752
- if (this.notificationRepo) {
376753
- return {
376754
- total: this.notificationRepo.count(userId2, false),
376755
- unread: this.notificationRepo.count(userId2, true)
376756
- };
376757
- }
376758
- return { total: 0, unread: 0 };
376759
- }
376760
- markNotificationRead(id) {
376761
- if (this.notificationRepo) {
376762
- return this.notificationRepo.markRead(id);
376763
- }
376764
- return false;
376765
- }
376766
- markAllNotificationsRead(userId2) {
376767
- if (this.notificationRepo) {
376768
- return this.notificationRepo.markAllRead(userId2);
376769
- }
376770
- return 0;
376771
- }
376772
- notify(opts) {
376773
- let targetUserIds;
376774
- if (opts.targetUserId === "all") {
376775
- if (this.orgService) {
376776
- const humans = this.orgService.listHumanUsers("default");
376777
- targetUserIds = humans.map((h) => h.id);
376778
- if (targetUserIds.length === 0)
376779
- targetUserIds = ["all"];
376780
- } else {
376781
- targetUserIds = ["all"];
376782
- }
376783
- } else {
376784
- targetUserIds = [opts.targetUserId];
376785
- }
376786
- if (opts.excludeUserIds?.length) {
376787
- const skip = new Set(opts.excludeUserIds);
376788
- targetUserIds = targetUserIds.filter((id) => !skip.has(id));
376789
- }
376790
- if (targetUserIds.length === 0) {
376791
- const n2 = this.buildNotification({ ...opts });
376792
- this.emitChannel(n2);
376793
- return n2;
376794
- }
376795
- let first;
376796
- for (const targetUserId of targetUserIds) {
376797
- const n2 = this.notifySingle({ ...opts, targetUserId });
376798
- first ??= n2;
376799
- }
376800
- this.emitChannel(this.buildNotification({ ...opts }));
376801
- return first;
376802
- }
376803
- /**
376804
- * Assemble the notification shape — the **single** place the fields are built,
376805
- * shared by the persisted per-person row and the logical channel event.
376806
- */
376807
- buildNotification(opts) {
376808
- return {
376809
- id: genId("ntf"),
376810
- targetUserId: opts.targetUserId,
376811
- type: opts.type,
376812
- title: opts.title,
376813
- body: opts.body,
376814
- priority: opts.priority ?? "normal",
376815
- read: false,
376816
- actionType: opts.actionType ?? "none",
376817
- actionTarget: opts.actionTarget,
376818
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
376819
- metadata: opts.metadata
376820
- };
376821
- }
376822
- notifySingle(opts) {
376823
- const notification = this.buildNotification(opts);
376824
- if (this.notificationRepo) {
376825
- try {
376826
- this.notificationRepo.insert({
376827
- id: notification.id,
376828
- userId: notification.targetUserId,
376829
- type: notification.type,
376830
- title: notification.title,
376831
- body: notification.body,
376832
- priority: notification.priority,
376833
- read: false,
376834
- actionType: notification.actionType,
376835
- actionTarget: notification.actionTarget ?? null,
376836
- metadata: notification.metadata ?? null,
376837
- createdAt: notification.createdAt
376838
- });
376839
- } catch (err) {
376840
- log92.warn("Failed to persist notification", { error: String(err) });
376841
- }
376842
- }
376843
- this.emit(notification);
376844
- return notification;
376845
- }
376846
- /** Mark unread approval_request rows for this approval read, across every user_id. */
376847
- markApprovalNotificationsRead(approvalId) {
376848
- if (!this.notificationRepo)
376849
- return;
376850
- if (this.notificationRepo.markReadByApprovalId) {
376851
- try {
376852
- this.notificationRepo.markReadByApprovalId(approvalId);
376853
- return;
376854
- } catch (err) {
376855
- log92.warn("Failed to mark approval notifications read by approvalId", {
376856
- approvalId,
376857
- error: String(err)
376858
- });
376859
- }
376860
- }
376861
- const userIds = /* @__PURE__ */ new Set(["all"]);
376862
- if (this.orgService) {
376863
- for (const h of this.orgService.listHumanUsers("default")) {
376864
- userIds.add(h.id);
376865
- }
376866
- }
376867
- for (const userId2 of userIds) {
376868
- try {
376869
- const rows = this.notificationRepo.list(userId2, { type: "approval_request", limit: 200 });
376870
- for (const row of rows) {
376871
- if (row.metadata && row.metadata.approvalId === approvalId && !row.read) {
376872
- this.notificationRepo.markRead(row.id);
376873
- }
376874
- }
376875
- } catch {
376876
- }
376877
- }
376878
- }
376879
- rowToNotification(r) {
376880
- return {
376881
- id: r.id,
376882
- targetUserId: r.userId,
376883
- type: r.type,
376884
- title: r.title,
376885
- body: r.body,
376886
- priority: r.priority,
376887
- read: r.read,
376888
- actionType: r.actionType,
376889
- actionTarget: r.actionTarget ?? void 0,
376890
- createdAt: r.createdAt,
376891
- metadata: r.metadata ?? void 0
376892
- };
376893
- }
376894
- };
376895
- }
376896
- });
376897
-
376898
377429
  // ../org-manager/dist/billing-service.js
376899
377430
  import { randomBytes as randomBytes6 } from "node:crypto";
376900
377431
  var log93, keyCounter, BillingService;
@@ -380780,6 +381311,16 @@ function openSqlite(dbPath) {
380780
381311
  { table: "tasks", column: "due_at", sql: "ALTER TABLE tasks ADD COLUMN due_at TEXT" },
380781
381312
  { table: "tasks", column: "open_question", sql: "ALTER TABLE tasks ADD COLUMN open_question TEXT" },
380782
381313
  { table: "tasks", column: "decisions", sql: "ALTER TABLE tasks ADD COLUMN decisions TEXT DEFAULT '[]'" },
381314
+ // Workflow identity (2026-10-27): a workflow task belongs to exactly one
381315
+ // (run, step). Structural columns replace the old `step: <id>` marker in
381316
+ // notes; `migrateWorkflowTaskIdentity` backfills existing rows once.
381317
+ { table: "tasks", column: "workflow_run_id", sql: "ALTER TABLE tasks ADD COLUMN workflow_run_id TEXT" },
381318
+ { table: "tasks", column: "workflow_step_id", sql: "ALTER TABLE tasks ADD COLUMN workflow_step_id TEXT" },
381319
+ // Run-time template snapshot (2026-10-27): a run must render with the
381320
+ // template it started with, not whatever the file says today.
381321
+ { table: "workflow_runs", column: "template_version", sql: "ALTER TABLE workflow_runs ADD COLUMN template_version TEXT" },
381322
+ { table: "workflow_runs", column: "template_hash", sql: "ALTER TABLE workflow_runs ADD COLUMN template_hash TEXT" },
381323
+ { table: "workflow_runs", column: "template_snapshot", sql: "ALTER TABLE workflow_runs ADD COLUMN template_snapshot TEXT" },
380783
381324
  { table: "channel_messages", column: "metadata", sql: "ALTER TABLE channel_messages ADD COLUMN metadata TEXT DEFAULT '{}'" },
380784
381325
  { table: "task_logs", column: "execution_round", sql: "ALTER TABLE task_logs ADD COLUMN execution_round INTEGER NOT NULL DEFAULT 1" },
380785
381326
  { table: "tasks", column: "execution_round", sql: "ALTER TABLE tasks ADD COLUMN execution_round INTEGER NOT NULL DEFAULT 1" },
@@ -381207,6 +381748,8 @@ CREATE TABLE IF NOT EXISTS tasks (
381207
381748
  subtasks TEXT DEFAULT '[]',
381208
381749
  requirement_id TEXT,
381209
381750
  blocked_by TEXT DEFAULT '[]',
381751
+ workflow_run_id TEXT,
381752
+ workflow_step_id TEXT,
381210
381753
  result TEXT,
381211
381754
  deliverables TEXT,
381212
381755
  notes TEXT DEFAULT '[]',
@@ -381761,7 +382304,11 @@ CREATE TABLE IF NOT EXISTS workflow_runs (
381761
382304
  triggered_by TEXT NOT NULL DEFAULT 'manual',
381762
382305
  project_id TEXT,
381763
382306
  started_at TEXT NOT NULL DEFAULT (datetime('now')),
381764
- completed_at TEXT
382307
+ completed_at TEXT,
382308
+ -- Template at run start \u2014 the run renders from here, never from today's file
382309
+ template_version TEXT,
382310
+ template_hash TEXT,
382311
+ template_snapshot TEXT
381765
382312
  );
381766
382313
  CREATE INDEX IF NOT EXISTS idx_workflow_runs_team ON workflow_runs(team_id, workflow_name);
381767
382314
  CREATE INDEX IF NOT EXISTS idx_workflow_runs_req ON workflow_runs(requirement_id);
@@ -382008,8 +382555,8 @@ CREATE INDEX IF NOT EXISTS idx_pending_callbacks_agent ON pending_callbacks(agen
382008
382555
  }
382009
382556
  async create(data) {
382010
382557
  const ts = now2();
382011
- this.db.prepare(`INSERT INTO tasks (id, org_id, title, description, status, priority, execution_mode, assigned_agent_id, reviewer_agent_id, reviewer_type, execution_round, subtasks, requirement_id, blocked_by, project_id, created_by, due_at, task_type, schedule_config, created_at, updated_at)
382012
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(data.id, data.orgId, data.title, data.description ?? "", data.status ?? "pending", data.priority ?? "medium", data.executionMode ?? null, data.assignedAgentId, data.reviewerId, data.reviewerType ?? "agent", data.executionRound ?? 1, toJson2(data.subtasks ?? []), data.requirementId ?? null, toJson2(data.blockedBy ?? []), data.projectId ?? null, data.createdBy ?? null, data.dueAt?.toISOString() ?? null, data.taskType ?? "standard", data.scheduleConfig ? toJson2(data.scheduleConfig) : null, ts, ts);
382558
+ this.db.prepare(`INSERT INTO tasks (id, org_id, title, description, status, priority, execution_mode, assigned_agent_id, reviewer_agent_id, reviewer_type, execution_round, subtasks, requirement_id, blocked_by, project_id, created_by, due_at, task_type, schedule_config, created_at, updated_at, workflow_run_id, workflow_step_id)
382559
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(data.id, data.orgId, data.title, data.description ?? "", data.status ?? "pending", data.priority ?? "medium", data.executionMode ?? null, data.assignedAgentId, data.reviewerId, data.reviewerType ?? "agent", data.executionRound ?? 1, toJson2(data.subtasks ?? []), data.requirementId ?? null, toJson2(data.blockedBy ?? []), data.projectId ?? null, data.createdBy ?? null, data.dueAt?.toISOString() ?? null, data.taskType ?? "standard", data.scheduleConfig ? toJson2(data.scheduleConfig) : null, ts, ts, data.workflowRunId ?? null, data.workflowStepId ?? null);
382013
382560
  return this.findById(data.id);
382014
382561
  }
382015
382562
  findById(id) {
@@ -382144,14 +382691,14 @@ CREATE INDEX IF NOT EXISTS idx_pending_callbacks_agent ON pending_callbacks(agen
382144
382691
  }
382145
382692
  async ensureExists(data) {
382146
382693
  const ts = now2();
382147
- this.db.prepare(`INSERT INTO tasks (id, org_id, title, description, status, priority, assigned_agent_id, reviewer_agent_id, reviewer_type, execution_round, subtasks, requirement_id, blocked_by, project_id, created_by, due_at, task_type, schedule_config, created_at, updated_at)
382148
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
382694
+ this.db.prepare(`INSERT INTO tasks (id, org_id, title, description, status, priority, assigned_agent_id, reviewer_agent_id, reviewer_type, execution_round, subtasks, requirement_id, blocked_by, project_id, created_by, due_at, task_type, schedule_config, created_at, updated_at, workflow_run_id, workflow_step_id)
382695
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
382149
382696
  ON CONFLICT(id) DO UPDATE SET
382150
382697
  title = excluded.title,
382151
382698
  status = excluded.status,
382152
382699
  assigned_agent_id = excluded.assigned_agent_id,
382153
382700
  execution_round = excluded.execution_round,
382154
- updated_at = excluded.updated_at`).run(data.id, data.orgId, data.title, data.description ?? "", data.status ?? "pending", data.priority ?? "medium", data.assignedAgentId, data.reviewerId, data.reviewerType ?? "agent", data.executionRound ?? 1, toJson2(data.subtasks ?? []), data.requirementId ?? null, toJson2(data.blockedBy ?? []), data.projectId ?? null, data.createdBy ?? null, data.dueAt?.toISOString() ?? null, data.taskType ?? "standard", data.scheduleConfig ? toJson2(data.scheduleConfig) : null, ts, ts);
382701
+ updated_at = excluded.updated_at`).run(data.id, data.orgId, data.title, data.description ?? "", data.status ?? "pending", data.priority ?? "medium", data.assignedAgentId, data.reviewerId, data.reviewerType ?? "agent", data.executionRound ?? 1, toJson2(data.subtasks ?? []), data.requirementId ?? null, toJson2(data.blockedBy ?? []), data.projectId ?? null, data.createdBy ?? null, data.dueAt?.toISOString() ?? null, data.taskType ?? "standard", data.scheduleConfig ? toJson2(data.scheduleConfig) : null, ts, ts, data.workflowRunId ?? null, data.workflowStepId ?? null);
382155
382702
  }
382156
382703
  async delete(id) {
382157
382704
  this.db.prepare("DELETE FROM tasks WHERE id = ?").run(id);
@@ -382172,6 +382719,8 @@ CREATE INDEX IF NOT EXISTS idx_pending_callbacks_agent ON pending_callbacks(agen
382172
382719
  subtasks: fromJson(r["subtasks"]) ?? [],
382173
382720
  requirementId: r["requirement_id"],
382174
382721
  blockedBy: fromJson(r["blocked_by"]) ?? [],
382722
+ workflowRunId: r["workflow_run_id"] ?? void 0,
382723
+ workflowStepId: r["workflow_step_id"] ?? void 0,
382175
382724
  result: fromJson(r["result"]),
382176
382725
  deliverables: fromJson(r["deliverables"]),
382177
382726
  notes: fromJson(r["notes"]),
@@ -385254,8 +385803,8 @@ CREATE INDEX IF NOT EXISTS idx_pending_callbacks_agent ON pending_callbacks(agen
385254
385803
  this.db = db;
385255
385804
  }
385256
385805
  async create(row) {
385257
- this.db.prepare(`INSERT INTO workflow_runs (id, team_id, workflow_name, run_number, requirement_id, task_ids, params, role_mapping, status, triggered_by, project_id, started_at, completed_at)
385258
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.id, row.team_id, row.workflow_name, row.run_number, row.requirement_id, row.task_ids, row.params, row.role_mapping, row.status, row.triggered_by, row.project_id, row.started_at, row.completed_at);
385806
+ this.db.prepare(`INSERT INTO workflow_runs (id, team_id, workflow_name, run_number, requirement_id, task_ids, params, role_mapping, status, triggered_by, project_id, started_at, completed_at, template_version, template_hash, template_snapshot)
385807
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.id, row.team_id, row.workflow_name, row.run_number, row.requirement_id, row.task_ids, row.params, row.role_mapping, row.status, row.triggered_by, row.project_id, row.started_at, row.completed_at, row.template_version ?? null, row.template_hash ?? null, row.template_snapshot ?? null);
385259
385808
  }
385260
385809
  async findById(id) {
385261
385810
  const r = this.db.prepare("SELECT * FROM workflow_runs WHERE id = ?").get(id);
@@ -385299,7 +385848,10 @@ CREATE INDEX IF NOT EXISTS idx_pending_callbacks_agent ON pending_callbacks(agen
385299
385848
  triggered_by: r["triggered_by"],
385300
385849
  project_id: r["project_id"] ?? null,
385301
385850
  started_at: r["started_at"],
385302
- completed_at: r["completed_at"] ?? null
385851
+ completed_at: r["completed_at"] ?? null,
385852
+ template_version: r["template_version"] ?? null,
385853
+ template_hash: r["template_hash"] ?? null,
385854
+ template_snapshot: r["template_snapshot"] ?? null
385303
385855
  };
385304
385856
  }
385305
385857
  };
@@ -385531,7 +386083,7 @@ function encodeCursor(tableIdx, rowid) {
385531
386083
  function decodeCursor(cursor) {
385532
386084
  return { tableIdx: Math.floor(cursor / TABLE_STRIDE), rowid: cursor % TABLE_STRIDE };
385533
386085
  }
385534
- var TABLE_STRIDE, IMAGE_TABLES, migrateImagesToAttachments, PAYLOAD_TARGETS, LARGE_THRESHOLD_BYTES, migrateLargePayloadsToBlobs, DEFAULT_MIGRATIONS, MigrationRunner;
386086
+ var TABLE_STRIDE, IMAGE_TABLES, migrateImagesToAttachments, PAYLOAD_TARGETS, LARGE_THRESHOLD_BYTES, migrateLargePayloadsToBlobs, migrateWorkflowTaskIdentity, DEFAULT_MIGRATIONS, MigrationRunner;
385535
386087
  var init_migration_runner = __esm({
385536
386088
  "../storage/dist/migration-runner.js"() {
385537
386089
  "use strict";
@@ -385660,7 +386212,58 @@ var init_migration_runner = __esm({
385660
386212
  return { processed, nextCursor: encodeCursor(PAYLOAD_TARGETS.length, 0), done: true, errors };
385661
386213
  }
385662
386214
  };
385663
- DEFAULT_MIGRATIONS = [migrateImagesToAttachments, migrateLargePayloadsToBlobs];
386215
+ migrateWorkflowTaskIdentity = {
386216
+ id: "003-workflow-task-identity",
386217
+ title: "\u5386\u53F2\u5DE5\u4F5C\u6D41\u4EFB\u52A1\u8865\u9F50 workflow_run_id / workflow_step_id",
386218
+ run({ db, cursor, batchSize }) {
386219
+ const errors = [];
386220
+ let processed = 0;
386221
+ const hasRuns = db.prepare("SELECT 1 AS one FROM sqlite_master WHERE type='table' AND name='workflow_runs'").get();
386222
+ if (!hasRuns)
386223
+ return { processed: 0, nextCursor: cursor, done: true, errors };
386224
+ const runs = db.prepare("SELECT rowid AS rid, id AS run_id, task_ids FROM workflow_runs WHERE rowid > ? ORDER BY rowid ASC LIMIT ?").all(cursor, batchSize);
386225
+ if (runs.length === 0)
386226
+ return { processed: 0, nextCursor: cursor, done: true, errors };
386227
+ const getTask = db.prepare("SELECT notes FROM tasks WHERE id = ?");
386228
+ const update2 = db.prepare("UPDATE tasks SET workflow_run_id = COALESCE(workflow_run_id, ?), workflow_step_id = COALESCE(workflow_step_id, ?) WHERE id = ?");
386229
+ let lastRowid = cursor;
386230
+ for (const run of runs) {
386231
+ lastRowid = run.rid;
386232
+ try {
386233
+ const taskIds = JSON.parse(run.task_ids);
386234
+ for (const taskId2 of taskIds) {
386235
+ const task = getTask.get(taskId2);
386236
+ if (!task)
386237
+ continue;
386238
+ let stepId = null;
386239
+ try {
386240
+ const notes = JSON.parse(task.notes ?? "[]");
386241
+ if (Array.isArray(notes)) {
386242
+ for (const note of notes) {
386243
+ const match2 = /step:\s*([A-Za-z0-9_.-]+)/.exec(String(note));
386244
+ if (match2) {
386245
+ stepId = match2[1];
386246
+ break;
386247
+ }
386248
+ }
386249
+ }
386250
+ } catch {
386251
+ }
386252
+ update2.run(run.run_id, stepId, taskId2);
386253
+ processed += 1;
386254
+ }
386255
+ } catch (err) {
386256
+ errors.push(`run ${run.run_id}: ${String(err)}`);
386257
+ }
386258
+ }
386259
+ return { processed, nextCursor: lastRowid, done: false, errors };
386260
+ }
386261
+ };
386262
+ DEFAULT_MIGRATIONS = [
386263
+ migrateImagesToAttachments,
386264
+ migrateLargePayloadsToBlobs,
386265
+ migrateWorkflowTaskIdentity
386266
+ ];
385664
386267
  MigrationRunner = class {
385665
386268
  db;
385666
386269
  attachments;
@@ -394374,6 +394977,26 @@ var init_workflow_service = __esm({
394374
394977
  return null;
394375
394978
  }
394376
394979
  }
394980
+ /**
394981
+ * Raw template YAML.
394982
+ *
394983
+ * The parsed `WorkflowTemplate` is lossy (comments, ordering, formatting), so
394984
+ * an editor that round-trips must read the file itself. This is the single
394985
+ * reader for that — the API exposes it as `yaml` on `GET .../workflows/:name`
394986
+ * so the Web UI can edit/duplicate without inventing a second serializer.
394987
+ */
394988
+ getWorkflowYaml(teamId, name) {
394989
+ const dir = this.getWorkflowsDir(teamId);
394990
+ const filePath = this.resolveWorkflowFile(dir, name);
394991
+ if (!filePath)
394992
+ return null;
394993
+ try {
394994
+ return readFileSync44(filePath, "utf-8");
394995
+ } catch (err) {
394996
+ log110.warn("Failed to read workflow template YAML", { name, error: String(err) });
394997
+ return null;
394998
+ }
394999
+ }
394377
395000
  addWorkflow(teamId, name, yamlContent) {
394378
395001
  const parsed = (0, import_yaml.parse)(yamlContent);
394379
395002
  const errors = validateWorkflowTemplate(parsed);
@@ -394381,6 +395004,9 @@ var init_workflow_service = __esm({
394381
395004
  throw new Error(`Invalid workflow template: ${errors.join("; ")}`);
394382
395005
  }
394383
395006
  const template = parsed;
395007
+ if (template.name !== name) {
395008
+ throw new Error(`Workflow name mismatch: file name "${name}" but the YAML says name: "${template.name}". Set the template's \`name\` field to "${name}" (or change the requested name) so the file and the template agree.`);
395009
+ }
394384
395010
  const dir = this.ensureWorkflowsDir(teamId);
394385
395011
  const fileName = `${name}.yaml`;
394386
395012
  const filePath = join49(dir, fileName);
@@ -394403,6 +395029,9 @@ var init_workflow_service = __esm({
394403
395029
  if (!filePath) {
394404
395030
  throw new Error(`Workflow "${name}" not found`);
394405
395031
  }
395032
+ if (template.name !== name) {
395033
+ throw new Error(`Workflow name mismatch: file name "${name}" but the YAML says name: "${template.name}". Rename the file with a copy instead of editing \`name\` here.`);
395034
+ }
394406
395035
  writeFileSync40(filePath, yamlContent, "utf-8");
394407
395036
  log110.info("Workflow template updated", { teamId, name });
394408
395037
  return template;
@@ -394551,6 +395180,7 @@ var init_workflow_service = __esm({
394551
395180
  });
394552
395181
 
394553
395182
  // ../org-manager/dist/workflow-runner.js
395183
+ import { createHash as createHash8 } from "node:crypto";
394554
395184
  function rowToRun(row) {
394555
395185
  return {
394556
395186
  id: row.id,
@@ -394565,7 +395195,10 @@ function rowToRun(row) {
394565
395195
  triggeredBy: row.triggered_by,
394566
395196
  projectId: row.project_id ?? void 0,
394567
395197
  startedAt: row.started_at,
394568
- completedAt: row.completed_at ?? void 0
395198
+ completedAt: row.completed_at ?? void 0,
395199
+ templateVersion: row.template_version ?? void 0,
395200
+ templateHash: row.template_hash ?? void 0,
395201
+ templateSnapshot: row.template_snapshot ? JSON.parse(row.template_snapshot) : void 0
394569
395202
  };
394570
395203
  }
394571
395204
  function runToRow(run) {
@@ -394582,21 +395215,64 @@ function runToRow(run) {
394582
395215
  triggered_by: run.triggeredBy,
394583
395216
  project_id: run.projectId ?? null,
394584
395217
  started_at: run.startedAt,
395218
+ template_version: run.templateVersion ?? null,
395219
+ template_hash: run.templateHash ?? null,
395220
+ template_snapshot: run.templateSnapshot ? JSON.stringify(run.templateSnapshot) : null,
394585
395221
  completed_at: run.completedAt ?? null
394586
395222
  };
394587
395223
  }
394588
- var log111, WorkflowRunner;
395224
+ function parseDurationMs(value) {
395225
+ if (value === void 0 || value === null)
395226
+ return null;
395227
+ if (typeof value === "number")
395228
+ return Number.isFinite(value) && value > 0 ? value : null;
395229
+ const match2 = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?\s*$/i.exec(value);
395230
+ if (!match2)
395231
+ return null;
395232
+ const amount = Number(match2[1]);
395233
+ const unit = (match2[2] ?? "ms").toLowerCase();
395234
+ const factor = unit === "d" ? 864e5 : unit === "h" ? 36e5 : unit === "m" ? 6e4 : unit === "s" ? 1e3 : 1;
395235
+ const ms = amount * factor;
395236
+ return Number.isFinite(ms) && ms > 0 ? ms : null;
395237
+ }
395238
+ var log111, WorkflowConcurrencyError, WorkflowRunner;
394589
395239
  var init_workflow_runner = __esm({
394590
395240
  "../org-manager/dist/workflow-runner.js"() {
394591
395241
  "use strict";
394592
395242
  init_dist();
394593
395243
  log111 = createLogger("workflow-runner");
395244
+ WorkflowConcurrencyError = class extends Error {
395245
+ constructor(message) {
395246
+ super(message);
395247
+ this.name = "WorkflowConcurrencyError";
395248
+ }
395249
+ };
394594
395250
  WorkflowRunner = class {
394595
395251
  runRepo;
394596
395252
  requirementService;
394597
395253
  taskService;
394598
395254
  orgService;
394599
395255
  ws;
395256
+ /**
395257
+ * Team-level admission control. Without it a cron glitch (or an eager agent)
395258
+ * could start unlimited runs for one team — every one of them a real
395259
+ * requirement, real tasks and real token spend.
395260
+ *
395261
+ * Source of truth: `MARKUS_WORKFLOW_MAX_CONCURRENT` (process-wide policy), with
395262
+ * a conservative default. `setMaxConcurrentRunsPerTeam` exists for tests and for
395263
+ * a future per-team override; nothing else may write this value.
395264
+ */
395265
+ maxConcurrentRunsPerTeam = (() => {
395266
+ const raw = Number(process.env["MARKUS_WORKFLOW_MAX_CONCURRENT"]);
395267
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 3;
395268
+ })();
395269
+ setMaxConcurrentRunsPerTeam(limit) {
395270
+ if (Number.isFinite(limit) && limit > 0)
395271
+ this.maxConcurrentRunsPerTeam = Math.floor(limit);
395272
+ }
395273
+ getMaxConcurrentRunsPerTeam() {
395274
+ return this.maxConcurrentRunsPerTeam;
395275
+ }
394600
395276
  // In-memory cache for fast lookup
394601
395277
  runs = /* @__PURE__ */ new Map();
394602
395278
  reqToRun = /* @__PURE__ */ new Map();
@@ -394615,6 +395291,12 @@ var init_workflow_runner = __esm({
394615
395291
  const team = this.orgService.getTeam(teamId);
394616
395292
  if (!team)
394617
395293
  throw new Error(`Team not found: ${teamId}`);
395294
+ const active = this.getActiveRuns(teamId).filter((r) => r.status === "running");
395295
+ if (active.length >= this.maxConcurrentRunsPerTeam) {
395296
+ throw new WorkflowConcurrencyError(`Team already has ${active.length} running workflow(s) (limit ${this.maxConcurrentRunsPerTeam}). Wait for one to finish, or raise workflow.maxConcurrentRunsPerTeam.`);
395297
+ }
395298
+ const runId = generateId("wfr");
395299
+ const templateHash = createHash8("sha256").update(JSON.stringify(template)).digest("hex").slice(0, 16);
394618
395300
  for (const p of template.params ?? []) {
394619
395301
  if (p.required && !params[p.name]) {
394620
395302
  throw new Error(`Required parameter "${p.name}" is missing`);
@@ -394640,7 +395322,7 @@ Params: ${JSON.stringify(params)}`,
394640
395322
  try {
394641
395323
  for (const step of sortedSteps) {
394642
395324
  const description = renderStepPrompt(step, params, runNumber);
394643
- const workflowContext = this.buildWorkflowContext(step, template, params, runNumber, sortedSteps);
395325
+ const workflowContext = this.buildWorkflowContext(step, template, params, runNumber, taskIdMap);
394644
395326
  const assignedAgentId = roleMapping[step.role];
394645
395327
  if (!assignedAgentId) {
394646
395328
  throw new Error(`No agent mapped for role "${step.role}" in workflow "${template.name}"`);
@@ -394663,7 +395345,13 @@ ${description}`,
394663
395345
  createdBy: createdBy || team.managerId || "system",
394664
395346
  creatorRole: "worker",
394665
395347
  approvedVia: "workflow",
394666
- notes: `[Workflow] ${template.name} run #${runNumber}, step: ${step.id}`
395348
+ // No `notes:` here on purpose. `CreateTaskRequest.notes` is a `string`
395349
+ // while `Task.notes` is `string[]`, so this used to be silently dropped
395350
+ // at creation — a dead parameter that made the old UI's "step: <id>"
395351
+ // guess and the P0 backfill impossible. Provenance now lives in the
395352
+ // structural columns below.
395353
+ workflowRunId: runId,
395354
+ workflowStepId: step.id
394667
395355
  });
394668
395356
  taskIdMap.set(step.id, task.id);
394669
395357
  createdTaskIds.push(task.id);
@@ -394685,7 +395373,7 @@ ${description}`,
394685
395373
  retriesUsed: 0
394686
395374
  }));
394687
395375
  const run = {
394688
- id: generateId("wfr"),
395376
+ id: runId,
394689
395377
  teamId,
394690
395378
  workflowName: template.name,
394691
395379
  runNumber,
@@ -394697,7 +395385,10 @@ ${description}`,
394697
395385
  status: "running",
394698
395386
  triggeredBy,
394699
395387
  projectId,
394700
- startedAt: (/* @__PURE__ */ new Date()).toISOString()
395388
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
395389
+ templateVersion: template.version,
395390
+ templateHash,
395391
+ templateSnapshot: template
394701
395392
  };
394702
395393
  this.runs.set(run.id, run);
394703
395394
  this.reqToRun.set(requirement.id, run.id);
@@ -394840,11 +395531,8 @@ ${description}`,
394840
395531
  return void 0;
394841
395532
  }
394842
395533
  async listRuns(teamId, workflowName, limit = 20) {
394843
- if (this.runRepo) {
394844
- const rows = await this.runRepo.findByTeamAndWorkflow(teamId, workflowName, limit);
394845
- return rows.map(rowToRun);
394846
- }
394847
- return [...this.runs.values()].filter((r) => r.teamId === teamId && r.workflowName === workflowName).sort((a, b) => b.runNumber - a.runNumber).slice(0, limit);
395534
+ const runs = this.runRepo ? (await this.runRepo.findByTeamAndWorkflow(teamId, workflowName, limit)).map(rowToRun) : [...this.runs.values()].filter((r) => r.teamId === teamId && r.workflowName === workflowName).sort((a, b) => b.runNumber - a.runNumber).slice(0, limit);
395535
+ return this.reconcileRunStatuses(runs);
394848
395536
  }
394849
395537
  getActiveRuns(teamId) {
394850
395538
  return [...this.runs.values()].filter((r) => r.teamId === teamId && r.status === "running");
@@ -394855,12 +395543,36 @@ ${description}`,
394855
395543
  */
394856
395544
  async onTaskStatusChange(task) {
394857
395545
  const run = this.findRunForTask(task.id);
394858
- if (!run || run.status !== "running")
395546
+ if (!run)
395547
+ return;
395548
+ if (run.status === "paused" || run.status === "cancelled")
394859
395549
  return;
395550
+ if (task.status === "completed") {
395551
+ const missing = this.missingOutputs(run, task);
395552
+ if (missing.length > 0) {
395553
+ const reason = `Workflow output contract not met: missing ${missing.join(", ")}`;
395554
+ try {
395555
+ this.taskService.updateTaskStatus(task.id, "failed", "system", false, false, "system", reason);
395556
+ } catch (err) {
395557
+ log111.warn("Failed to fail a step that missed its declared outputs", { taskId: task.id, error: String(err) });
395558
+ }
395559
+ this.notifyManager(run.teamId, "step_failed", {
395560
+ workflowName: run.workflowName,
395561
+ runId: run.id,
395562
+ runNumber: run.runNumber,
395563
+ taskId: task.id,
395564
+ taskTitle: task.title,
395565
+ reason: "output_contract",
395566
+ missing,
395567
+ actionRequired: true
395568
+ });
395569
+ return;
395570
+ }
395571
+ }
394860
395572
  const allTasks = run.taskIds.map((id) => this.taskService.getTask(id)).filter(Boolean);
394861
395573
  const newStatus = this.deriveRunStatus(allTasks);
394862
- if (newStatus === "running") {
394863
- if (task.status === "failed") {
395574
+ if (newStatus === run.status) {
395575
+ if (newStatus === "running" && task.status === "failed") {
394864
395576
  const retried = this.attemptStepRetry(run, task);
394865
395577
  if (!retried) {
394866
395578
  this.notifyManager(run.teamId, "step_failed", {
@@ -394875,29 +395587,105 @@ ${description}`,
394875
395587
  }
394876
395588
  return;
394877
395589
  }
395590
+ await this.applyRunStatus(run, newStatus, { task });
395591
+ }
395592
+ /**
395593
+ * Enforce `steps[].timeout`.
395594
+ *
395595
+ * The template has always *accepted* a timeout and stored it in
395596
+ * `stepConfigs` — nothing ever read it, so a wedged step kept its run
395597
+ * `running` forever and the config was a lie. Sweeping from the scheduler tick
395598
+ * (rather than per-task timers) means the guarantee survives a restart: the
395599
+ * deadline is recomputed from the task's own `startedAt`.
395600
+ *
395601
+ * Failure policy is shared with the normal failure path: retry if the step has
395602
+ * retries left, otherwise fail the task with an explicit reason so the run
395603
+ * status derives to `failed`.
395604
+ */
395605
+ async enforceTimeouts(now3 = Date.now()) {
395606
+ let enforced = 0;
395607
+ for (const run of [...this.runs.values()]) {
395608
+ if (run.status !== "running")
395609
+ continue;
395610
+ for (const cfg of run.stepConfigs ?? []) {
395611
+ const limitMs = parseDurationMs(cfg.timeout);
395612
+ if (!limitMs)
395613
+ continue;
395614
+ const task = this.taskService.getTask(cfg.taskId);
395615
+ if (!task || TERMINAL_STATUSES.has(task.status))
395616
+ continue;
395617
+ const startedAtMs = new Date(task.startedAt ?? task.createdAt).getTime();
395618
+ if (!Number.isFinite(startedAtMs))
395619
+ continue;
395620
+ if (now3 - startedAtMs < limitMs)
395621
+ continue;
395622
+ enforced += 1;
395623
+ const retried = this.attemptStepRetry(run, task);
395624
+ if (!retried) {
395625
+ try {
395626
+ this.taskService.updateTaskStatus(task.id, "failed", "system", false, false, "system", `Step timed out after ${cfg.timeout} (limit ${Math.round(limitMs / 1e3)}s)`);
395627
+ } catch (err) {
395628
+ log111.warn("Failed to fail timed-out workflow step", { taskId: task.id, error: String(err) });
395629
+ }
395630
+ this.notifyManager(run.teamId, "step_failed", {
395631
+ workflowName: run.workflowName,
395632
+ runId: run.id,
395633
+ runNumber: run.runNumber,
395634
+ taskId: task.id,
395635
+ taskTitle: task.title,
395636
+ reason: "timeout",
395637
+ actionRequired: true
395638
+ });
395639
+ }
395640
+ log111.info("Workflow step timeout enforced", {
395641
+ runId: run.id,
395642
+ taskId: task.id,
395643
+ timeout: cfg.timeout,
395644
+ retried
395645
+ });
395646
+ }
395647
+ }
395648
+ return enforced;
395649
+ }
395650
+ /**
395651
+ * The single writer for a *derived* run status.
395652
+ *
395653
+ * Callers: `onTaskStatusChange` (live) and `reconcileRunStatuses` (read-time
395654
+ * healing of historical drift). Keeping it in one place is what stops the two
395655
+ * paths from disagreeing about notifications or `completedAt`.
395656
+ */
395657
+ async applyRunStatus(run, newStatus, ctx = {}) {
395658
+ const previous = run.status;
395659
+ const notify = ctx.notify ?? true;
394878
395660
  run.status = newStatus;
394879
- run.completedAt = (/* @__PURE__ */ new Date()).toISOString();
395661
+ if (newStatus === "running") {
395662
+ run.completedAt = void 0;
395663
+ } else {
395664
+ run.completedAt = run.completedAt ?? (/* @__PURE__ */ new Date()).toISOString();
395665
+ }
394880
395666
  this.runs.set(run.id, run);
394881
395667
  if (this.runRepo) {
394882
395668
  await this.runRepo.updateStatus(run.id, newStatus, run.completedAt).catch((err) => log111.warn("Failed to update workflow run status", { error: String(err) }));
394883
395669
  }
394884
- if (newStatus === "completed") {
394885
- this.notifyManager(run.teamId, "run_completed", {
394886
- workflowName: run.workflowName,
394887
- runId: run.id,
394888
- runNumber: run.runNumber,
394889
- taskCount: run.taskIds.length,
394890
- actionRequired: true
394891
- });
394892
- } else if (newStatus === "failed") {
394893
- this.notifyManager(run.teamId, "run_failed", {
394894
- workflowName: run.workflowName,
394895
- runId: run.id,
394896
- runNumber: run.runNumber,
394897
- failedTaskId: task.id,
394898
- failedTaskTitle: task.title,
394899
- actionRequired: true
394900
- });
395670
+ if (notify && previous === "running") {
395671
+ if (newStatus === "completed") {
395672
+ this.notifyManager(run.teamId, "run_completed", {
395673
+ workflowName: run.workflowName,
395674
+ runId: run.id,
395675
+ runNumber: run.runNumber,
395676
+ taskCount: run.taskIds.length,
395677
+ actionRequired: true
395678
+ });
395679
+ } else if (newStatus === "failed") {
395680
+ this.notifyManager(run.teamId, "run_failed", {
395681
+ workflowName: run.workflowName,
395682
+ runId: run.id,
395683
+ runNumber: run.runNumber,
395684
+ failedTaskId: ctx.task?.id ?? "",
395685
+ failedTaskTitle: ctx.task?.title ?? "",
395686
+ actionRequired: true
395687
+ });
395688
+ }
394901
395689
  }
394902
395690
  this.ws?.broadcast?.({
394903
395691
  type: `workflow:run_${newStatus}`,
@@ -394907,10 +395695,35 @@ ${description}`,
394907
395695
  log111.info("Workflow run status changed", {
394908
395696
  runId: run.id,
394909
395697
  workflow: run.workflowName,
395698
+ previousStatus: previous,
394910
395699
  newStatus,
394911
- taskId: task.id
395700
+ taskId: ctx.task?.id
394912
395701
  });
394913
395702
  }
395703
+ /**
395704
+ * Tasks are the authority; a run's terminal status is a projection of them.
395705
+ * Rows written before the fix above are healed here, on read.
395706
+ */
395707
+ async reconcileRunStatuses(runs) {
395708
+ const healed = [];
395709
+ for (const run of runs) {
395710
+ if (run.status === "paused" || run.status === "cancelled") {
395711
+ healed.push(run);
395712
+ continue;
395713
+ }
395714
+ const tasks = run.taskIds.map((id) => this.taskService.getTask(id)).filter(Boolean);
395715
+ if (tasks.length === 0) {
395716
+ healed.push(run);
395717
+ continue;
395718
+ }
395719
+ const derived = this.deriveRunStatus(tasks);
395720
+ if (derived !== run.status) {
395721
+ await this.applyRunStatus(run, derived, { notify: false });
395722
+ }
395723
+ healed.push(run);
395724
+ }
395725
+ return healed;
395726
+ }
394914
395727
  async loadFromDB() {
394915
395728
  if (!this.runRepo)
394916
395729
  return;
@@ -394929,6 +395742,33 @@ ${description}`,
394929
395742
  }
394930
395743
  }
394931
395744
  // ─── Private helpers ───────────────────────────────────────────────────────
395745
+ /**
395746
+ * Which of the step's *required* declared outputs are missing from the task.
395747
+ *
395748
+ * The check is deliberately narrow and mechanical:
395749
+ * - `outputs[].type` is compared against `TaskDeliverable.type` (a real
395750
+ * structured field — never free text);
395751
+ * - an output declared without a `type` can only be checked as "produced at
395752
+ * least one deliverable", which is what it says on the tin;
395753
+ * - `required: false` opts an output out entirely;
395754
+ * - runs without a template snapshot (pre-2026-10) have no contract to
395755
+ * enforce and are left alone rather than retro-failed.
395756
+ */
395757
+ missingOutputs(run, task) {
395758
+ const stepId = task.workflowStepId;
395759
+ if (!stepId)
395760
+ return [];
395761
+ const template = run.templateSnapshot;
395762
+ if (!template)
395763
+ return [];
395764
+ const step = template.steps.find((s2) => s2.id === stepId);
395765
+ const required = (step?.outputs ?? []).filter((o) => o.required !== false);
395766
+ if (required.length === 0)
395767
+ return [];
395768
+ const deliverables = task.deliverables ?? [];
395769
+ const types = new Set(deliverables.map((d) => d.type).filter((t) => !!t));
395770
+ return required.filter((output) => output.type ? !types.has(output.type) : deliverables.length === 0).map((output) => output.type ? `${output.name}(${output.type})` : output.name);
395771
+ }
394932
395772
  deriveRunStatus(tasks) {
394933
395773
  if (tasks.length === 0)
394934
395774
  return "running";
@@ -395000,7 +395840,22 @@ ${description}`,
395000
395840
  return void 0;
395001
395841
  }
395002
395842
  }
395003
- buildWorkflowContext(step, template, params, runNumber, _sortedSteps) {
395843
+ /**
395844
+ * The prompt preamble a step's task starts with.
395845
+ *
395846
+ * Upstream outputs *are* the data channel in this design: the runner creates
395847
+ * every task up front, `blockedBy` orders them, and `task_get` returns an
395848
+ * upstream task's `deliverables`. What used to be broken was the **pointer**:
395849
+ * this text listed upstream *step* ids (`step-1-research`) while the tool it
395850
+ * named (`task_get`) needs a *task* id (`tsk_…`), so the instruction failed
395851
+ * verbatim ("Task not found") and a diligent agent had to rediscover the route
395852
+ * through `blockedBy` on its own task.
395853
+ *
395854
+ * Now the upstream task id is written out explicitly. Tasks are created in
395855
+ * topological order, so every dependency already has its id by the time a
395856
+ * downstream step is rendered.
395857
+ */
395858
+ buildWorkflowContext(step, template, params, runNumber, taskIdMap) {
395004
395859
  const displayName = template.displayName || template.name;
395005
395860
  const lines = [
395006
395861
  `## Workflow Context`,
@@ -395011,12 +395866,34 @@ ${description}`,
395011
395866
  lines.push(`Parameters: ${paramEntries.map(([k, v]) => `${k}="${v}"`).join(", ")}`);
395012
395867
  }
395013
395868
  lines.push(`Your role in this workflow: ${step.role}`);
395869
+ const declaredInputs = step.inputs ?? [];
395870
+ if (declaredInputs.length > 0) {
395871
+ lines.push("");
395872
+ lines.push("Inputs you must consume (declared by this workflow):");
395873
+ for (const input of declaredInputs) {
395874
+ const fromStep = template.steps.find((s2) => s2.id === input.from);
395875
+ const fromTaskId = taskIdMap.get(input.from);
395876
+ const declared = fromStep?.outputs?.find((o) => o.name === input.as);
395877
+ const typeHint = declared?.type ? ` of type "${declared.type}"` : "";
395878
+ if (fromTaskId) {
395879
+ lines.push(`- \`${input.as}\`${typeHint} from step "${fromStep?.name || input.from}" \u2192 task \`${fromTaskId}\` (call \`task_get\` with task_id="${fromTaskId}" and read the deliverable${declared?.type ? ` whose type is "${declared.type}"` : ""})`);
395880
+ } else {
395881
+ lines.push(`- \`${input.as}\` from step "${fromStep?.name || input.from}" \u2014 its task has not been created yet`);
395882
+ }
395883
+ }
395884
+ }
395014
395885
  if (step.depends_on && step.depends_on.length > 0) {
395015
395886
  lines.push("");
395016
- lines.push("Step dependencies (review their outputs using `task_get`):");
395887
+ lines.push("Upstream steps \u2014 read their deliverables before you start:");
395017
395888
  for (const depId of step.depends_on) {
395018
395889
  const depStep = template.steps.find((s2) => s2.id === depId);
395019
- lines.push(`- "${depStep?.name || depId}" (${depId})`);
395890
+ const depTaskId = taskIdMap.get(depId);
395891
+ const name = depStep?.name || depId;
395892
+ if (depTaskId) {
395893
+ lines.push(`- "${name}" \u2192 task \`${depTaskId}\` \u2014 call \`task_get\` with task_id="${depTaskId}" and use its deliverables as your input`);
395894
+ } else {
395895
+ lines.push(`- "${name}" (${depId}) \u2014 its task has not been created yet (upstream step failed to materialize)`);
395896
+ }
395020
395897
  }
395021
395898
  } else {
395022
395899
  lines.push("");
@@ -395276,6 +396153,11 @@ var init_workflow_scheduler = __esm({
395276
396153
  }
395277
396154
  async tick() {
395278
396155
  this.refreshScheduleStates();
396156
+ try {
396157
+ await this.workflowRunner.enforceTimeouts();
396158
+ } catch (err) {
396159
+ log112.warn("Workflow step-timeout sweep failed", { error: String(err) });
396160
+ }
395279
396161
  const now3 = Date.now();
395280
396162
  for (const [key2, state] of this.scheduleStates) {
395281
396163
  if (state.paused)
@@ -395433,11 +396315,13 @@ __export(dist_exports5, {
395433
396315
  WorkflowRunner: () => WorkflowRunner,
395434
396316
  WorkflowScheduler: () => WorkflowScheduler,
395435
396317
  WorkflowService: () => WorkflowService,
396318
+ assessResponseCompleteness: () => assessResponseCompleteness,
395436
396319
  evaluateConservator: () => evaluateConservator,
395437
396320
  exportSkillToFormat: () => exportSkillToFormat,
395438
396321
  importSkillFromDirectory: () => importSkillFromDirectory,
395439
396322
  initStorage: () => initStorage,
395440
396323
  installSkill: () => installSkill,
396324
+ isAnswerableByTap: () => isAnswerableByTap,
395441
396325
  loadPlatformBindings: () => loadPlatformBindings,
395442
396326
  readStoredPlatformConfig: () => readStoredPlatformConfig,
395443
396327
  recordInstanceVerification: () => recordInstanceVerification,
@@ -395512,7 +396396,8 @@ function setupOutboundDispatch(opts) {
395512
396396
  actionSecret: opts.actionSecret,
395513
396397
  agentName: opts.agentName,
395514
396398
  agentTeamName: opts.agentTeamName,
395515
- locale: opts.locale
396399
+ locale: opts.locale,
396400
+ onDelivered: opts.onDelivered
395516
396401
  });
395517
396402
  const detachers = [];
395518
396403
  if (opts.notificationSource) {
@@ -395549,7 +396434,7 @@ var init_outbound2 = __esm({
395549
396434
  // src/commands/approval-card.ts
395550
396435
  function buildApprovalCardResolution(approval, tap) {
395551
396436
  return {
395552
- status: TERMINAL_STATUSES3.has(approval.status) ? approval.status : "expired",
396437
+ status: TERMINAL_STATUSES3.has(approval.status) ? approval.status : "pending",
395553
396438
  title: approval.title,
395554
396439
  body: approval.description,
395555
396440
  actorId: approval.respondedBy ?? tap.actorId,
@@ -395559,6 +396444,13 @@ function buildApprovalCardResolution(approval, tap) {
395559
396444
  at: approval.respondedAt
395560
396445
  };
395561
396446
  }
396447
+ function cardActorFields(opts) {
396448
+ if (opts.platformName && opts.respondedBy) {
396449
+ return { actorId: opts.respondedBy, actorName: opts.platformName };
396450
+ }
396451
+ const name = opts.humanName?.trim();
396452
+ return name && !/[<>]/.test(name) ? { actorName: name } : {};
396453
+ }
395562
396454
  function scheduleCardRewrite(rewrite, onError) {
395563
396455
  return new Promise((resolve27) => {
395564
396456
  const timer = setTimeout(() => {
@@ -398480,7 +399372,7 @@ var init_remote_secrets = __esm({
398480
399372
  });
398481
399373
 
398482
399374
  // ../remote/dist/registry-client.js
398483
- import { createHash as createHash8, createHmac as createHmac6, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
399375
+ import { createHash as createHash9, createHmac as createHmac6, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
398484
399376
  function resolveHubBaseUrl(explicit) {
398485
399377
  const raw = explicit?.trim() || process.env["MARKUS_HUB_URL"]?.trim() || DEFAULT_HUB_URL;
398486
399378
  return raw.replace(/\/+$/, "");
@@ -398489,7 +399381,7 @@ function endpointPath(endpointId) {
398489
399381
  return `${ENDPOINTS_PATH}/${encodeURIComponent(endpointId)}`;
398490
399382
  }
398491
399383
  function sha256Hex(input) {
398492
- return createHash8("sha256").update(input, "utf-8").digest("hex");
399384
+ return createHash9("sha256").update(input, "utf-8").digest("hex");
398493
399385
  }
398494
399386
  function generateNonce() {
398495
399387
  return randomBytes7(24).toString("base64url");
@@ -400063,6 +400955,12 @@ async function startServerCore(config, values, opts) {
400063
400955
  });
400064
400956
  agentManager.setUserApprovalRequester(async (opts2) => {
400065
400957
  const taskTitle = opts2.relatedTaskId ? taskService.getTask(opts2.relatedTaskId)?.title : void 0;
400958
+ const channelOptions = opts2.options && opts2.options.length > 0 ? opts2.options : isAnswerableByTap(opts2.questions, opts2.options) ? (opts2.questions?.[0]?.options ?? []).map((o) => ({
400959
+ id: o.id,
400960
+ label: o.label,
400961
+ description: o.description,
400962
+ ...o.requiresFreeform ? { requiresFreeform: true } : {}
400963
+ })) : void 0;
400066
400964
  return hitlService.requestApprovalAndWait({
400067
400965
  agentId: opts2.agentId,
400068
400966
  agentName: opts2.agentName,
@@ -400070,7 +400968,7 @@ async function startServerCore(config, values, opts) {
400070
400968
  title: opts2.title,
400071
400969
  description: opts2.description,
400072
400970
  targetUserId: ownerUserId,
400073
- options: opts2.options,
400971
+ options: channelOptions,
400074
400972
  allowFreeform: opts2.allowFreeform,
400075
400973
  questions: opts2.questions,
400076
400974
  details: { priority: opts2.priority, taskId: opts2.relatedTaskId, taskTitle }
@@ -401065,11 +401963,12 @@ ${reason}`;
401065
401963
  return;
401066
401964
  }
401067
401965
  const tapped = hitlService.getApproval(approvalId)?.options?.find((o) => o.id === command);
401068
- if (tapped?.requiresComment) {
401069
- log116.warn("Refused a platform approval action that needs an unwritable comment", {
401966
+ if (tapped?.requiresComment || tapped?.requiresFreeform) {
401967
+ log116.warn("Refused a platform approval action that needs input this surface cannot collect", {
401070
401968
  approvalId,
401071
401969
  command,
401072
- platform: action.platform
401970
+ platform: action.platform,
401971
+ needs: tapped?.requiresFreeform ? "freeform" : "comment"
401073
401972
  });
401074
401973
  return;
401075
401974
  }
@@ -401081,10 +401980,19 @@ ${reason}`;
401081
401980
  void 0,
401082
401981
  command
401083
401982
  );
401084
- log116.info("Platform action resolved", { approvalId, command, platform: action.platform });
401983
+ if (resolved) {
401984
+ log116.info("Platform action resolved", { approvalId, command, platform: action.platform });
401985
+ } else {
401986
+ log116.warn("Platform action was NOT recorded \u2014 the request is still waiting for a full answer", {
401987
+ approvalId,
401988
+ command,
401989
+ platform: action.platform
401990
+ });
401991
+ }
401085
401992
  const approval = resolved?.approval ?? hitlService.getApproval(approvalId);
401086
401993
  const messageId = action.messageId;
401087
- if (approval && messageId) {
401994
+ const hasRecordedCards = (deliveredCards.get(approvalId)?.length ?? 0) > 0;
401995
+ if (approval && messageId && (!resolved || !hasRecordedCards)) {
401088
401996
  void scheduleCardRewrite(async () => {
401089
401997
  const actorName = action.actorId ? await messageRouter.resolveActorName(action.platform, action.instanceId, action.actorId) : null;
401090
401998
  const updated = await messageRouter.updateResolvedCard(
@@ -401214,6 +402122,28 @@ ${reason}`;
401214
402122
  const failedLabels = platformResults.filter((r) => !r.connected).map((r) => r.label);
401215
402123
  const gatewayDetail = connectedLabels.length > 0 ? `webhook adapters: ${connectedLabels.join(" + ")}` : "webhook adapters: none";
401216
402124
  progress?.complete(5, failedLabels.length > 0 ? `${gatewayDetail} (${failedLabels.join(", ")} failed)` : gatewayDetail);
402125
+ const deliveredCards = /* @__PURE__ */ new Map();
402126
+ hitlService.onApprovalChanged((changed) => {
402127
+ for (const ref of deliveredCards.get(changed.id) ?? []) {
402128
+ void scheduleCardRewrite(async () => {
402129
+ const platformName = changed.respondedBy ? await messageRouter.resolveActorName(ref.platform, ref.instanceId, changed.respondedBy) : null;
402130
+ const humanName = changed.respondedBy ? orgService.resolveHumanIdentity(changed.respondedBy)?.name : void 0;
402131
+ const actorFields = cardActorFields({ platformName, respondedBy: changed.respondedBy, humanName });
402132
+ const updated = await messageRouter.updateResolvedCard(
402133
+ ref.platform,
402134
+ ref.instanceId,
402135
+ ref.messageId,
402136
+ buildApprovalCardResolution(changed, actorFields)
402137
+ );
402138
+ if (!updated) {
402139
+ log116.info("Approval card left as-is \u2014 platform cannot edit a sent message", {
402140
+ approvalId: changed.id,
402141
+ platform: ref.platform
402142
+ });
402143
+ }
402144
+ }, (err) => log116.warn("Approval card rewrite failed", { approvalId: changed.id, error: String(err) }));
402145
+ }
402146
+ });
401217
402147
  const outbound = setupOutboundDispatch({
401218
402148
  router: messageRouter,
401219
402149
  bindingRepo: storage?.channelBindingRepo,
@@ -401224,6 +402154,18 @@ ${reason}`;
401224
402154
  orgId: "default",
401225
402155
  digestInfo: false,
401226
402156
  actionSecret: resolveActionSecret(),
402157
+ // 记住“哪张卡片对应哪个审批”:后续任何一面做出决定,都靠这个 ref 把卡片收敛。
402158
+ onDelivered: (notification, outcome) => {
402159
+ const approvalId = notification.metadata?.["approvalId"];
402160
+ const { messageId } = outcome;
402161
+ const platform11 = outcome.target?.platform;
402162
+ if (typeof approvalId !== "string" || !messageId || !platform11) return;
402163
+ const list = deliveredCards.get(approvalId) ?? [];
402164
+ if (!list.some((r) => r.platform === platform11 && r.messageId === messageId)) {
402165
+ list.push({ platform: platform11, instanceId: outcome.target?.instanceId, messageId });
402166
+ deliveredCards.set(approvalId, list);
402167
+ }
402168
+ },
401227
402169
  // Resolve the origin agent's display name so a notification landing in a
401228
402170
  // shared group says which agent sent it. A lookup failure must never hold
401229
402171
  // back a delivery — an unknown agent simply goes out unattributed.