@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -28,13 +28,12 @@
28
28
  * depends only on verification facts.
29
29
  * - BAPI-1455: a required COMMAND (`bash_task`, `bash_bg`, `subagent_bash`)
30
30
  * that ended `failed` or `stopped` is resolved when the worker received
31
- * that command's OWN terminal result — today only its foreground
32
- * tool_result, bound by the exact tool_use_id. The recorded state stays the
33
- * real one and the envelope carries `result_delivered: true` beside it.
34
- * Delegates, monitors, denials, launch acknowledgements, and background
35
- * output reads never count: no background result shape has been measured
36
- * that binds to its task by structure rather than text, so background
37
- * commands stay unresolved exactly as before.
31
+ * that command's OWN terminal result: its foreground tool_result, bound by
32
+ * the exact tool_use_id, or its own `task_notification`, bound by the
33
+ * structural task id of an already-tracked run. The recorded state stays
34
+ * the real one and the envelope carries `result_delivered: true` beside it.
35
+ * Delegates, monitors, denials, launch acknowledgements, `task_updated`
36
+ * status patches, and background output reads never count.
38
37
  * - A denial links to an obligation only on the exact OPERATION and TARGET (for
39
38
  * example the prepared branch on `origin`), never on the effect class alone.
40
39
  *
@@ -43,7 +42,7 @@
43
42
  * retained prompt, command, argument, URL, or path. Tool inputs and denial
44
43
  * targets are kept only as SHA-256 digests.
45
44
  */
46
- import { DELIVERY_RESOLVABLE_KINDS, DELIVERY_RESOLVABLE_STATES, MAX_DENIALS, MAX_EVENT_BYTES, MAX_TASKS, boundEnvelope, boundedIdentifier, deriveCompletionCause, digestStructured, isTaskResolved, runtimeMatchesSupported, successRefusalReason, COMPLETION_CONTRACT_VERSION, COMPLETION_CONTRACT_VERSION_V2, } from "./completion-contract.js";
45
+ import { DELIVERY_RESOLVABLE_KINDS, DELIVERY_RESOLVABLE_STATES, MAX_DENIALS, MAX_EVENT_BYTES, MAX_IDENTIFIER_CHARS, MAX_STRUCTURAL_EVENT_BYTES, MAX_TASKS, boundEnvelope, boundedIdentifier, deriveCompletionCause, digestStructured, isTaskResolved, runtimeMatchesSupported, successRefusalReason, COMPLETION_CONTRACT_VERSION, COMPLETION_CONTRACT_VERSION_V2, } from "./completion-contract.js";
47
46
  import { requiredWorkKindTokens } from "./required-work-diagnostics.js";
48
47
  /**
49
48
  * A background command that fails this soon after its launch acknowledgement is
@@ -343,6 +342,808 @@ const TERMINAL_STATES = new Set([
343
342
  ]);
344
343
  const FAILED_TO_START_KINDS = new Set(["bash_bg", "bash_task", "subagent_bash"]);
345
344
  const KNOWN_TASK_STATUSES = new Set(["pending", "running", "completed", "failed", "stopped", "killed"]);
345
+ // ---------------------------------------------------------------------------
346
+ // Structural reading of an oversize stream-json line (BAPI-1586)
347
+ // ---------------------------------------------------------------------------
348
+ //
349
+ // A line larger than MAX_EVENT_BYTES is never held or parsed as one event. It is
350
+ // validated character by character in bounded memory, and only lifecycle
351
+ // metadata is kept. The projection is then judged once, at the end of the line:
352
+ // an event is *established* only when its reduced form carries its full ledger
353
+ // meaning. Everything else stays `stream_oversize` and applies nothing.
354
+ //
355
+ // Beginning or feeding a line never changes ledger state. Worker text (prompts,
356
+ // commands, arguments, paths, URLs, thinking, results) is never buffered: a
357
+ // dropped value contributes only a character count.
358
+ /** Deepest JSON nesting the structural reader accepts. */
359
+ export const MAX_OVERSIZE_JSON_DEPTH = 64;
360
+ /** A dropped value larger than this many characters is recorded as "large". */
361
+ export const MAX_OVERSIZE_SCALAR_CHARS = 128;
362
+ /** Content blocks retained across the whole projection. */
363
+ export const MAX_OVERSIZE_CONTENT_BLOCKS = 256;
364
+ /** Snapshot task entries retained across the whole projection. */
365
+ export const MAX_OVERSIZE_SNAPSHOT_TASK_IDS = MAX_TASKS * 2;
366
+ /** Large dropped values recorded across the whole projection. */
367
+ export const MAX_OVERSIZE_DROPPED_PATHS = 512;
368
+ /** Known-key duplicate bookkeeping entries across the whole projection. */
369
+ export const MAX_OVERSIZE_DUPLICATE_KEYS = 8192;
370
+ /** Total characters of small dropped values at unexplained positions. */
371
+ const MAX_OVERSIZE_UNEXPLAINED_CHARS = 4096;
372
+ const MAX_OVERSIZE_KEY_CHARS = 24;
373
+ const MAX_OVERSIZE_NUMBER_CHARS = 32;
374
+ const MAX_OVERSIZE_TOKEN_CHARS = 64;
375
+ const OVERSIZE_FEED_SLICE_CHARS = 64 * 1024;
376
+ /** A retained field whose value could not be read safely. */
377
+ const UNREADABLE = Symbol("unreadable");
378
+ const ROOT_KEYS = [
379
+ "type", "subtype", "session_id", "parent_tool_use_id", "message", "content",
380
+ "task_id", "tool_use_id", "status", "patch", "task_type", "is_backgrounded",
381
+ "owned_by_subagent", "tasks", "tool_use_result",
382
+ ];
383
+ const BLOCK_KEYS = [
384
+ "type", "id", "name", "tool_use_id", "is_error", "input", "text", "content",
385
+ "thinking", "signature", "data", "source",
386
+ ];
387
+ const KEY_TABLES = {
388
+ root: ROOT_KEYS,
389
+ message: ["content"],
390
+ block: BLOCK_KEYS,
391
+ patch: ["status", "is_backgrounded"],
392
+ task: ["task_id"],
393
+ };
394
+ const ID_FIELDS = new Set(["session_id", "parent_tool_use_id", "task_id", "tool_use_id"]);
395
+ const TOKEN_FIELDS = new Set(["type", "subtype", "status", "task_type"]);
396
+ const BOOL_FIELDS = new Set(["is_backgrounded", "owned_by_subagent"]);
397
+ const BLOCK_PAYLOAD_KEYS = new Set(["input", "text", "content", "thinking", "signature", "data", "source"]);
398
+ /** Tool names the ledger tracks or inspects: never reduced, whatever their input size. */
399
+ const STRUCTURAL_INSPECTED_TOOLS = new Set(["Agent", "Task", "Bash", "Monitor", "TaskStop"]);
400
+ /** Block type → the payload keys that may be large without changing its ledger meaning. */
401
+ const ASSISTANT_LARGE_KEYS = {
402
+ text: ["text"],
403
+ thinking: ["thinking", "signature"],
404
+ redacted_thinking: ["data"],
405
+ tool_use: ["input"],
406
+ };
407
+ const USER_LARGE_KEYS = {
408
+ tool_result: ["content", "text"],
409
+ text: ["text"],
410
+ image: ["source"],
411
+ };
412
+ /** The material-event membership `dispatch` and structural eligibility share. */
413
+ function isMaterialEvent(type, subtype) {
414
+ return (type === "assistant" ||
415
+ type === "user" ||
416
+ type === "result" ||
417
+ (type === "system" &&
418
+ (subtype === "init" ||
419
+ subtype === "task_started" ||
420
+ subtype === "task_notification" ||
421
+ subtype === "task_updated" ||
422
+ subtype === "background_tasks_changed")));
423
+ }
424
+ function newProjection() {
425
+ return {
426
+ root: {},
427
+ msgObj: false,
428
+ msg: { present: false, kind: null, blocks: [] },
429
+ flat: { present: false, kind: null, blocks: [] },
430
+ patch: { present: false, kind: null, fields: {} },
431
+ tasks: { present: false, kind: null, entries: [], bad: false },
432
+ large: [],
433
+ blockCount: 0,
434
+ invalidMeta: false,
435
+ largeOther: false,
436
+ };
437
+ }
438
+ /**
439
+ * Decide, from a completed projection, whether the event is established. The
440
+ * answer is always one of: ignore (a uniquely readable non-material event),
441
+ * dispatch a reduced event once, or reject. A rejected event applies nothing.
442
+ */
443
+ function decideProjection(p) {
444
+ const reject = { kind: "reject" };
445
+ const type = p.root["type"];
446
+ const subtype = p.root["subtype"];
447
+ if (typeof type !== "string")
448
+ return reject;
449
+ if (type === "system" && subtype !== undefined && typeof subtype !== "string")
450
+ return reject;
451
+ if (!isMaterialEvent(type, subtype))
452
+ return { kind: "ignored" };
453
+ if (p.invalidMeta || p.largeOther || type === "result")
454
+ return reject;
455
+ const event = { type };
456
+ for (const k of ["subtype", "session_id", "parent_tool_use_id"])
457
+ if (k in p.root)
458
+ event[k] = p.root[k];
459
+ if (type === "assistant" || type === "user") {
460
+ const useMsg = p.msgObj && p.msg.present;
461
+ // Both representations present: `contentOf` would pick one and the other
462
+ // could hide lifecycle meaning. Not established.
463
+ if (useMsg && p.flat.present)
464
+ return reject;
465
+ const rep = useMsg ? p.msg : p.flat;
466
+ const src = useMsg ? "msg" : "flat";
467
+ const table = type === "assistant" ? ASSISTANT_LARGE_KEYS : USER_LARGE_KEYS;
468
+ for (const rec of p.large) {
469
+ if (rec.w === "tur") {
470
+ if (type === "user")
471
+ continue;
472
+ return reject;
473
+ }
474
+ if (rec.w === "cont") {
475
+ if (rec.src !== src)
476
+ return reject;
477
+ continue;
478
+ }
479
+ if (rec.w !== "blk" || rec.src !== src)
480
+ return reject;
481
+ const blk = rep.blocks[rec.i];
482
+ const bt = blk?.fields["type"];
483
+ if (!blk || !blk.isObj || typeof bt !== "string")
484
+ return reject;
485
+ if (!(table[bt] ?? []).includes(rec.k))
486
+ return reject;
487
+ }
488
+ if (rep.present) {
489
+ let content;
490
+ if (rep.kind === "string")
491
+ content = "";
492
+ else if (rep.kind === "array") {
493
+ const blocks = [];
494
+ for (const b of rep.blocks) {
495
+ if (!b.isObj) {
496
+ blocks.push(0);
497
+ continue;
498
+ }
499
+ const f = b.fields;
500
+ if (type === "assistant" && f["type"] === "tool_use") {
501
+ if (boundedIdentifier(f["id"]) === null)
502
+ return reject;
503
+ if (typeof f["name"] !== "string" || STRUCTURAL_INSPECTED_TOOLS.has(f["name"]))
504
+ return reject;
505
+ }
506
+ else if (type === "user" && f["type"] === "tool_result") {
507
+ if (boundedIdentifier(f["tool_use_id"]) === null)
508
+ return reject;
509
+ // An error result may be a denial, which depends on its text.
510
+ if (f["is_error"] === true)
511
+ return reject;
512
+ }
513
+ const out = {};
514
+ for (const k of ["type", "id", "name", "tool_use_id", "is_error"])
515
+ if (k in f)
516
+ out[k] = f[k];
517
+ blocks.push(out);
518
+ }
519
+ content = blocks;
520
+ }
521
+ else
522
+ return reject;
523
+ if (useMsg)
524
+ event["message"] = { content };
525
+ else
526
+ event["content"] = content;
527
+ }
528
+ return { kind: "dispatch", event };
529
+ }
530
+ // Lifecycle system events: no discarded value may exist at all.
531
+ if (p.large.length > 0)
532
+ return reject;
533
+ for (const k of ["task_id", "tool_use_id", "status", "task_type", "is_backgrounded", "owned_by_subagent"]) {
534
+ if (k in p.root)
535
+ event[k] = p.root[k];
536
+ }
537
+ if (p.patch.present) {
538
+ if (p.patch.kind !== "object")
539
+ return reject;
540
+ event["patch"] = { ...p.patch.fields };
541
+ }
542
+ if (p.tasks.present) {
543
+ if (p.tasks.kind !== "array" || p.tasks.bad)
544
+ return reject;
545
+ event["tasks"] = p.tasks.entries.map((t) => ({ ...t }));
546
+ }
547
+ return { kind: "dispatch", event };
548
+ }
549
+ const LEX_NONE = 0;
550
+ const LEX_STR = 1;
551
+ const LEX_ESC = 2;
552
+ const LEX_UNI = 3;
553
+ const LEX_NUM = 4;
554
+ const LEX_LIT = 5;
555
+ const STR_KEY = 0;
556
+ const STR_DROPKEY = 1;
557
+ const STR_FIELD = 2;
558
+ const STR_DROP = 3;
559
+ const NO_REC = { w: "other", src: "", i: 0, k: "*" };
560
+ function createStructuralParser() {
561
+ let status = "active";
562
+ let proj = newProjection();
563
+ const stack = [];
564
+ let rootDone = false;
565
+ let bytes = 0;
566
+ let pendingHigh = false;
567
+ let lex = LEX_NONE;
568
+ let strKind = STR_DROP;
569
+ let keyBuf = "";
570
+ let keyOver = false;
571
+ let strBuf = "";
572
+ let strOver = false;
573
+ let curField = null;
574
+ let uniCount = 0;
575
+ let uniCode = 0;
576
+ let nState = 0;
577
+ let numBuf = "";
578
+ let numOver = false;
579
+ let litTarget = "";
580
+ let litPos = 0;
581
+ let dropActive = false;
582
+ let dropCount = 0;
583
+ let dropRec = NO_REC;
584
+ let dropExplained = false;
585
+ let dropBase = 0;
586
+ let unexplained = 0;
587
+ let dupMarks = 0;
588
+ /** Permanent rejection: release every retained structure and ignore the rest of the line. */
589
+ const reject = () => {
590
+ status = "rejected";
591
+ stack.length = 0;
592
+ proj = newProjection();
593
+ keyBuf = "";
594
+ strBuf = "";
595
+ numBuf = "";
596
+ curField = null;
597
+ dropActive = false;
598
+ lex = LEX_NONE;
599
+ };
600
+ const startDrop = (rec, explained) => {
601
+ if (dropActive)
602
+ return;
603
+ dropActive = true;
604
+ dropCount = 0;
605
+ dropRec = rec;
606
+ dropExplained = explained;
607
+ dropBase = stack.length;
608
+ };
609
+ const endDrop = () => {
610
+ dropActive = false;
611
+ // Bounded message metadata (usage, model, id) is charged to the unexplained budget only.
612
+ if (dropCount > MAX_OVERSIZE_SCALAR_CHARS && dropRec.w !== "meta") {
613
+ if (proj.large.length >= MAX_OVERSIZE_DROPPED_PATHS)
614
+ return reject();
615
+ proj.large.push(dropRec);
616
+ }
617
+ if (!dropExplained) {
618
+ unexplained += dropCount;
619
+ if (unexplained > MAX_OVERSIZE_UNEXPLAINED_CHARS)
620
+ proj.largeOther = true;
621
+ }
622
+ };
623
+ const mkFrame = (arr, role, fields, src, idx) => ({
624
+ arr, role, st: 0, seen: 0, keyName: "*", fields, src, idx,
625
+ });
626
+ const classify = (f) => {
627
+ const drop = (rec, explained) => ({ t: "drop", rec, explained });
628
+ if (f.role === "drop")
629
+ return drop(NO_REC, true);
630
+ if (f.arr) {
631
+ if (f.role === "content") {
632
+ if (proj.blockCount >= MAX_OVERSIZE_CONTENT_BLOCKS) {
633
+ reject();
634
+ return drop(NO_REC, true);
635
+ }
636
+ proj.blockCount++;
637
+ const rep = f.src === "msg" ? proj.msg : proj.flat;
638
+ const blk = { isObj: true, fields: {} };
639
+ rep.blocks.push(blk);
640
+ return { t: "cont", role: "block", src: f.src, idx: rep.blocks.length - 1, fields: blk.fields, blk };
641
+ }
642
+ if (proj.tasks.entries.length >= MAX_OVERSIZE_SNAPSHOT_TASK_IDS) {
643
+ reject();
644
+ return drop(NO_REC, true);
645
+ }
646
+ const fields = {};
647
+ proj.tasks.entries.push(fields);
648
+ return { t: "cont", role: "task", src: "", idx: 0, fields, blk: null };
649
+ }
650
+ const k = f.keyName;
651
+ const cont = (role, src) => ({
652
+ t: "cont", role, src, idx: 0, fields: null, blk: null,
653
+ });
654
+ switch (f.role) {
655
+ case "root":
656
+ if (ID_FIELDS.has(k))
657
+ return { t: "field", into: proj.root, key: k, cap: MAX_IDENTIFIER_CHARS };
658
+ if (TOKEN_FIELDS.has(k))
659
+ return { t: "field", into: proj.root, key: k, cap: MAX_OVERSIZE_TOKEN_CHARS };
660
+ if (BOOL_FIELDS.has(k))
661
+ return { t: "field", into: proj.root, key: k, cap: 16 };
662
+ if (k === "message")
663
+ return cont("message", "");
664
+ if (k === "content")
665
+ return cont("content", "flat");
666
+ if (k === "patch")
667
+ return cont("patch", "");
668
+ if (k === "tasks")
669
+ return cont("tasks", "");
670
+ // A user event's top-level copy of the tool output; only the block's ids carry meaning.
671
+ if (k === "tool_use_result")
672
+ return drop({ w: "tur", src: "", i: 0, k }, true);
673
+ return drop({ w: "top", src: "", i: 0, k }, false);
674
+ case "message":
675
+ if (k === "content")
676
+ return cont("content", "msg");
677
+ return drop({ w: "meta", src: "", i: 0, k: "msg:*" }, false);
678
+ case "block":
679
+ if (k === "type")
680
+ return { t: "field", into: f.fields, key: k, cap: MAX_OVERSIZE_TOKEN_CHARS };
681
+ if (k === "id" || k === "name" || k === "tool_use_id")
682
+ return { t: "field", into: f.fields, key: k, cap: MAX_IDENTIFIER_CHARS };
683
+ if (k === "is_error")
684
+ return { t: "field", into: f.fields, key: k, cap: 16 };
685
+ if (BLOCK_PAYLOAD_KEYS.has(k))
686
+ return drop({ w: "blk", src: f.src, i: f.idx, k }, true);
687
+ return drop({ w: "blk", src: f.src, i: f.idx, k: "*" }, false);
688
+ case "patch":
689
+ if (k === "status")
690
+ return { t: "field", into: f.fields, key: k, cap: MAX_OVERSIZE_TOKEN_CHARS };
691
+ if (k === "is_backgrounded")
692
+ return { t: "field", into: f.fields, key: k, cap: 16 };
693
+ return drop({ w: "top", src: "", i: 0, k: "patch:*" }, false);
694
+ case "task":
695
+ if (k === "task_id")
696
+ return { t: "field", into: f.fields, key: k, cap: MAX_IDENTIFIER_CHARS };
697
+ return drop({ w: "top", src: "", i: 0, k: "task:*" }, false);
698
+ default:
699
+ return drop(NO_REC, true);
700
+ }
701
+ };
702
+ /** The container role a `cont` slot descends into for this opening character, or null to drop the value. */
703
+ const contRole = (slot, ch) => {
704
+ switch (slot.role) {
705
+ case "message":
706
+ proj.msgObj = ch === "{";
707
+ return ch === "{" ? "message" : null;
708
+ case "content": {
709
+ const rep = slot.src === "msg" ? proj.msg : proj.flat;
710
+ rep.present = true;
711
+ if (ch === "[") {
712
+ rep.kind = "array";
713
+ return "content";
714
+ }
715
+ rep.kind = ch === '"' ? "string" : "other";
716
+ return null;
717
+ }
718
+ case "patch":
719
+ proj.patch.present = true;
720
+ proj.patch.kind = ch === "{" ? "object" : "other";
721
+ return ch === "{" ? "patch" : null;
722
+ case "tasks":
723
+ proj.tasks.present = true;
724
+ proj.tasks.kind = ch === "[" ? "array" : "other";
725
+ return ch === "[" ? "tasks" : null;
726
+ case "block":
727
+ if (ch === "{")
728
+ return "block";
729
+ if (slot.blk)
730
+ slot.blk.isObj = false;
731
+ return null;
732
+ case "task":
733
+ if (ch === "{")
734
+ return "task";
735
+ proj.tasks.bad = true;
736
+ return null;
737
+ }
738
+ };
739
+ const valueDone = () => {
740
+ if (dropActive && stack.length === dropBase) {
741
+ endDrop();
742
+ if (status !== "active")
743
+ return;
744
+ }
745
+ const f = stack[stack.length - 1];
746
+ if (f)
747
+ f.st = 4;
748
+ };
749
+ const finishScalar = (value) => {
750
+ if (curField) {
751
+ curField.into[curField.key] = value;
752
+ curField = null;
753
+ }
754
+ valueDone();
755
+ };
756
+ const closeContainer = (ch) => {
757
+ const f = stack[stack.length - 1];
758
+ if ((ch === "}") === f.arr)
759
+ return reject();
760
+ stack.pop();
761
+ if (dropActive && stack.length === dropBase) {
762
+ endDrop();
763
+ if (status !== "active")
764
+ return;
765
+ }
766
+ const parent = stack[stack.length - 1];
767
+ if (!parent) {
768
+ rootDone = true;
769
+ return;
770
+ }
771
+ parent.st = 4;
772
+ };
773
+ const beginValue = (ch) => {
774
+ const f = stack[stack.length - 1];
775
+ const slot = classify(f);
776
+ if (status !== "active")
777
+ return;
778
+ let role = null;
779
+ if (slot.t === "drop") {
780
+ startDrop(slot.rec, slot.explained);
781
+ }
782
+ else if (slot.t === "cont") {
783
+ role = contRole(slot, ch);
784
+ if (role === null) {
785
+ if (slot.role === "content" && ch === '"')
786
+ startDrop({ w: "cont", src: slot.src, i: 0, k: "content" }, true);
787
+ else
788
+ startDrop(NO_REC, false);
789
+ }
790
+ }
791
+ else if (ch === "{" || ch === "[") {
792
+ // A container where a scalar was required: unreadable, never harmless.
793
+ slot.into[slot.key] = UNREADABLE;
794
+ proj.invalidMeta = true;
795
+ startDrop(NO_REC, false);
796
+ }
797
+ if (ch === "{" || ch === "[") {
798
+ if (stack.length >= MAX_OVERSIZE_JSON_DEPTH)
799
+ return reject();
800
+ const fields = slot.t === "cont" ? slot.fields : null;
801
+ const src = slot.t === "cont" ? slot.src : "";
802
+ const idx = slot.t === "cont" ? slot.idx : 0;
803
+ const nextRole = role ?? "drop";
804
+ const nf = nextRole === "patch" ? proj.patch.fields : fields;
805
+ stack.push(mkFrame(ch === "[", nextRole, nf, src, idx));
806
+ return;
807
+ }
808
+ if (slot.t === "field") {
809
+ curField = { into: slot.into, key: slot.key, cap: slot.cap };
810
+ }
811
+ if (ch === '"') {
812
+ lex = LEX_STR;
813
+ strKind = slot.t === "field" ? STR_FIELD : STR_DROP;
814
+ strBuf = "";
815
+ strOver = false;
816
+ }
817
+ else if (ch === "-" || (ch >= "0" && ch <= "9")) {
818
+ lex = LEX_NUM;
819
+ nState = ch === "-" ? 1 : ch === "0" ? 2 : 3;
820
+ numBuf = ch;
821
+ numOver = false;
822
+ }
823
+ else if (ch === "t" || ch === "f" || ch === "n") {
824
+ lex = LEX_LIT;
825
+ litTarget = ch === "t" ? "true" : ch === "f" ? "false" : "null";
826
+ litPos = 1;
827
+ }
828
+ else {
829
+ reject();
830
+ }
831
+ };
832
+ const keyEnd = () => {
833
+ const f = stack[stack.length - 1];
834
+ const table = KEY_TABLES[f.role];
835
+ const id = keyOver || !table ? -1 : table.indexOf(keyBuf);
836
+ f.keyName = id >= 0 ? keyBuf : "*";
837
+ if (id >= 0) {
838
+ const bit = 1 << id;
839
+ // A repeated decoded key makes the value ambiguous: refuse the line.
840
+ if (f.seen & bit)
841
+ return reject();
842
+ f.seen |= bit;
843
+ if (++dupMarks > MAX_OVERSIZE_DUPLICATE_KEYS)
844
+ return reject();
845
+ }
846
+ f.st = 2;
847
+ };
848
+ const strAppend = (ch) => {
849
+ switch (strKind) {
850
+ case STR_KEY:
851
+ if (keyBuf.length < MAX_OVERSIZE_KEY_CHARS)
852
+ keyBuf += ch;
853
+ else
854
+ keyOver = true;
855
+ break;
856
+ case STR_FIELD:
857
+ if (strBuf.length < (curField?.cap ?? 0))
858
+ strBuf += ch;
859
+ else
860
+ strOver = true;
861
+ break;
862
+ default:
863
+ break; // dropped text is counted by the feed loop, never kept.
864
+ }
865
+ };
866
+ const endString = () => {
867
+ lex = LEX_NONE;
868
+ if (strKind === STR_KEY)
869
+ return keyEnd();
870
+ if (strKind === STR_DROPKEY) {
871
+ stack[stack.length - 1].st = 2;
872
+ return;
873
+ }
874
+ if (strKind === STR_FIELD) {
875
+ if (strOver) {
876
+ proj.invalidMeta = true;
877
+ strBuf = "";
878
+ return finishScalar(UNREADABLE);
879
+ }
880
+ const v = strBuf;
881
+ strBuf = "";
882
+ return finishScalar(v);
883
+ }
884
+ valueDone();
885
+ };
886
+ const endNumber = () => {
887
+ lex = LEX_NONE;
888
+ let value = UNREADABLE;
889
+ if (curField) {
890
+ if (numOver)
891
+ proj.invalidMeta = true;
892
+ else
893
+ value = Number(numBuf);
894
+ }
895
+ numBuf = "";
896
+ finishScalar(value);
897
+ };
898
+ const structural = (ch) => {
899
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r")
900
+ return;
901
+ const f = stack[stack.length - 1];
902
+ if (!f) {
903
+ // Exactly one root object, then only whitespace.
904
+ if (rootDone || ch !== "{")
905
+ return reject();
906
+ stack.push(mkFrame(false, "root", proj.root, "", 0));
907
+ return;
908
+ }
909
+ if (f.arr) {
910
+ if (f.st === 4) {
911
+ if (ch === ",")
912
+ f.st = 3;
913
+ else if (ch === "]")
914
+ closeContainer(ch);
915
+ else
916
+ reject();
917
+ }
918
+ else if (f.st === 0 && ch === "]")
919
+ closeContainer(ch);
920
+ else
921
+ beginValue(ch);
922
+ return;
923
+ }
924
+ switch (f.st) {
925
+ case 0:
926
+ case 1:
927
+ if (ch === '"') {
928
+ lex = LEX_STR;
929
+ strKind = f.role === "drop" ? STR_DROPKEY : STR_KEY;
930
+ keyBuf = "";
931
+ keyOver = false;
932
+ }
933
+ else if (f.st === 0 && ch === "}")
934
+ closeContainer(ch);
935
+ else
936
+ reject();
937
+ return;
938
+ case 2:
939
+ if (ch === ":")
940
+ f.st = 3;
941
+ else
942
+ reject();
943
+ return;
944
+ case 3:
945
+ beginValue(ch);
946
+ return;
947
+ default:
948
+ if (ch === ",")
949
+ f.st = 1;
950
+ else if (ch === "}")
951
+ closeContainer(ch);
952
+ else
953
+ reject();
954
+ }
955
+ };
956
+ const lexChar = (ch, code) => {
957
+ switch (lex) {
958
+ case LEX_STR:
959
+ if (ch === '"')
960
+ endString();
961
+ else if (ch === "\\")
962
+ lex = LEX_ESC;
963
+ else if (code < 0x20)
964
+ reject();
965
+ else
966
+ strAppend(ch);
967
+ return;
968
+ case LEX_ESC:
969
+ lex = LEX_STR;
970
+ switch (ch) {
971
+ case '"':
972
+ case "\\":
973
+ case "/":
974
+ strAppend(ch);
975
+ return;
976
+ case "b":
977
+ strAppend("\b");
978
+ return;
979
+ case "f":
980
+ strAppend("\f");
981
+ return;
982
+ case "n":
983
+ strAppend("\n");
984
+ return;
985
+ case "r":
986
+ strAppend("\r");
987
+ return;
988
+ case "t":
989
+ strAppend("\t");
990
+ return;
991
+ case "u":
992
+ lex = LEX_UNI;
993
+ uniCount = 0;
994
+ uniCode = 0;
995
+ return;
996
+ default:
997
+ reject();
998
+ return;
999
+ }
1000
+ case LEX_UNI: {
1001
+ const d = code >= 48 && code <= 57 ? code - 48 : code >= 97 && code <= 102 ? code - 87 : code >= 65 && code <= 70 ? code - 55 : -1;
1002
+ if (d < 0)
1003
+ return reject();
1004
+ uniCode = uniCode * 16 + d;
1005
+ if (++uniCount === 4) {
1006
+ lex = LEX_STR;
1007
+ strAppend(String.fromCharCode(uniCode));
1008
+ }
1009
+ return;
1010
+ }
1011
+ case LEX_NUM: {
1012
+ const digit = code >= 48 && code <= 57;
1013
+ const nonZero = digit && ch !== "0";
1014
+ let ok = true;
1015
+ let ended = false;
1016
+ switch (nState) {
1017
+ case 1:
1018
+ if (ch === "0")
1019
+ nState = 2;
1020
+ else if (nonZero)
1021
+ nState = 3;
1022
+ else
1023
+ ok = false;
1024
+ break;
1025
+ case 2:
1026
+ if (ch === ".")
1027
+ nState = 4;
1028
+ else if (ch === "e" || ch === "E")
1029
+ nState = 6;
1030
+ else
1031
+ ended = true;
1032
+ break;
1033
+ case 3:
1034
+ if (digit)
1035
+ break;
1036
+ if (ch === ".")
1037
+ nState = 4;
1038
+ else if (ch === "e" || ch === "E")
1039
+ nState = 6;
1040
+ else
1041
+ ended = true;
1042
+ break;
1043
+ case 4:
1044
+ if (digit)
1045
+ nState = 5;
1046
+ else
1047
+ ok = false;
1048
+ break;
1049
+ case 5:
1050
+ if (digit)
1051
+ break;
1052
+ if (ch === "e" || ch === "E")
1053
+ nState = 6;
1054
+ else
1055
+ ended = true;
1056
+ break;
1057
+ case 6:
1058
+ if (ch === "+" || ch === "-")
1059
+ nState = 7;
1060
+ else if (digit)
1061
+ nState = 8;
1062
+ else
1063
+ ok = false;
1064
+ break;
1065
+ case 7:
1066
+ if (digit)
1067
+ nState = 8;
1068
+ else
1069
+ ok = false;
1070
+ break;
1071
+ default: if (!digit)
1072
+ ended = true;
1073
+ }
1074
+ if (!ok)
1075
+ return reject();
1076
+ if (ended) {
1077
+ endNumber();
1078
+ if (status === "active")
1079
+ structural(ch);
1080
+ return;
1081
+ }
1082
+ if (numBuf.length < MAX_OVERSIZE_NUMBER_CHARS)
1083
+ numBuf += ch;
1084
+ else
1085
+ numOver = true;
1086
+ return;
1087
+ }
1088
+ case LEX_LIT:
1089
+ if (ch !== litTarget[litPos])
1090
+ return reject();
1091
+ if (++litPos === litTarget.length) {
1092
+ lex = LEX_NONE;
1093
+ finishScalar(litTarget === "true" ? true : litTarget === "false" ? false : null);
1094
+ }
1095
+ return;
1096
+ default:
1097
+ structural(ch);
1098
+ }
1099
+ };
1100
+ const feed = (chunk) => {
1101
+ if (status !== "active")
1102
+ return;
1103
+ for (let i = 0; i < chunk.length; i++) {
1104
+ const code = chunk.charCodeAt(i);
1105
+ // Incremental UTF-8 size, correct across a split surrogate pair.
1106
+ let counted = false;
1107
+ if (pendingHigh) {
1108
+ pendingHigh = false;
1109
+ if (code >= 0xdc00 && code <= 0xdfff) {
1110
+ bytes += 4;
1111
+ counted = true;
1112
+ }
1113
+ else
1114
+ bytes += 3;
1115
+ }
1116
+ if (!counted) {
1117
+ if (code < 0x80)
1118
+ bytes += 1;
1119
+ else if (code < 0x800)
1120
+ bytes += 2;
1121
+ else if (code >= 0xd800 && code <= 0xdbff)
1122
+ pendingHigh = true;
1123
+ else
1124
+ bytes += 3;
1125
+ }
1126
+ if (bytes + (pendingHigh ? 3 : 0) > MAX_STRUCTURAL_EVENT_BYTES)
1127
+ return reject();
1128
+ if (dropActive)
1129
+ dropCount++;
1130
+ lexChar(chunk[i], code);
1131
+ if (status !== "active")
1132
+ return;
1133
+ }
1134
+ };
1135
+ const finish = () => {
1136
+ if (status !== "active")
1137
+ return { kind: "reject" };
1138
+ if (pendingHigh)
1139
+ bytes += 3;
1140
+ const complete = rootDone && lex === LEX_NONE && stack.length === 0 && bytes <= MAX_STRUCTURAL_EVENT_BYTES;
1141
+ const p = proj;
1142
+ reject(); // release everything; the parser is single-use from here.
1143
+ return complete ? decideProjection(p) : { kind: "reject" };
1144
+ };
1145
+ return { feed, finish };
1146
+ }
346
1147
  export function createRequiredWorkLedger(init) {
347
1148
  const binding = { ...init.binding };
348
1149
  const lifecycleSupported = init.lifecycleSupported === true;
@@ -408,6 +1209,7 @@ export function createRequiredWorkLedger(init) {
408
1209
  launchedAt: null,
409
1210
  resultDelivered: false,
410
1211
  failedByResult: false,
1212
+ erroredBeforeLaunch: false,
411
1213
  ...spec,
412
1214
  required: spec.required ?? !isOptional(spec.kind, spec.inputDigest),
413
1215
  };
@@ -542,8 +1344,6 @@ export function createRequiredWorkLedger(init) {
542
1344
  // --- event handlers -------------------------------------------------------
543
1345
  const onTurnEvent = () => {
544
1346
  turnOpen = true;
545
- if (stdinClosed)
546
- insufficient.add("late_activity_after_close");
547
1347
  };
548
1348
  const handleInit = (e) => {
549
1349
  const sid = boundedIdentifier(e["session_id"]);
@@ -555,7 +1355,7 @@ export function createRequiredWorkLedger(init) {
555
1355
  sawInit = true;
556
1356
  return "applied";
557
1357
  };
558
- const handleAssistant = (e) => {
1358
+ const handleAssistant = (e, structural = false) => {
559
1359
  onTurnEvent();
560
1360
  const content = contentOf(e);
561
1361
  if (!Array.isArray(content)) {
@@ -576,8 +1376,10 @@ export function createRequiredWorkLedger(init) {
576
1376
  outcome = "unknown_shape";
577
1377
  continue;
578
1378
  }
579
- const input = b["input"];
580
- const inputDigest = obligationInputDigest(input);
1379
+ // A structurally read tool use has no input: it is admitted only for a tool
1380
+ // the ledger neither tracks nor inspects, so no digest is invented for it.
1381
+ const input = structural ? undefined : b["input"];
1382
+ const inputDigest = structural ? null : obligationInputDigest(input);
581
1383
  const bg = isRecord(input) && input["run_in_background"] === true;
582
1384
  // Bounded index; the input itself is dropped here, only digests remain.
583
1385
  if (!toolUses.has(id)) {
@@ -589,11 +1391,13 @@ export function createRequiredWorkLedger(init) {
589
1391
  toolUses.set(id, {
590
1392
  name,
591
1393
  inputDigest,
592
- denial: resolveDenialOperation(name, input),
1394
+ denial: structural ? { operation: "other", targetDigest: null, linkKeys: [] } : resolveDenialOperation(name, input),
593
1395
  background: bg,
594
1396
  foregroundResult: null,
595
1397
  });
596
1398
  }
1399
+ if (structural)
1400
+ continue;
597
1401
  if (name === "Agent" || name === "Task") {
598
1402
  track(id, { toolUseId: id, taskId: null, kind: bg ? "delegate_bg" : "delegate", inputDigest, background: bg, placeholder: false });
599
1403
  }
@@ -658,6 +1462,13 @@ export function createRequiredWorkLedger(init) {
658
1462
  // first named launch event for the startup window. No result text is read.
659
1463
  if (!isError)
660
1464
  recordLaunch(o);
1465
+ // The call itself errored before any launch and with no task id: it
1466
+ // never started (the denial rule, BAPI-1613 R3, for a plain error). An
1467
+ // error after a launch, or once a task id is bound, changes nothing.
1468
+ else if (o.state === "pending" && o.launchedAt === null && o.taskId === null) {
1469
+ applyTerminal(o, "failed");
1470
+ o.erroredBeforeLaunch = true;
1471
+ }
661
1472
  continue;
662
1473
  }
663
1474
  // A foreground result is the task's own terminal result, delivered to the
@@ -702,6 +1513,14 @@ export function createRequiredWorkLedger(init) {
702
1513
  insufficient.add("event_conflict");
703
1514
  return "conflict";
704
1515
  }
1516
+ // A start for a call whose own result said it never started contradicts
1517
+ // that result: conflict, never a silent resolution.
1518
+ if (o.erroredBeforeLaunch && o.taskId === null) {
1519
+ o.taskId = taskId;
1520
+ o.state = "conflict";
1521
+ insufficient.add("event_conflict");
1522
+ return "conflict";
1523
+ }
705
1524
  if (!repeatedStart && hasOtherLiveClaim(taskId, o.key)) {
706
1525
  o.taskId = taskId;
707
1526
  o.state = "conflict";
@@ -710,6 +1529,13 @@ export function createRequiredWorkLedger(init) {
710
1529
  }
711
1530
  o.taskId = taskId;
712
1531
  bindDeferredStop(o);
1532
+ // The trusted start says the run is backgrounded: an already-tracked
1533
+ // foreground delegate is corrected before its launch acknowledgement lands.
1534
+ if (e["is_backgrounded"] === true) {
1535
+ o.background = true;
1536
+ if (o.kind === "delegate")
1537
+ o.kind = "delegate_bg";
1538
+ }
713
1539
  // An orphan terminal recorded before this start had to guess a generic
714
1540
  // background `task`; the trusted start now names the real kind.
715
1541
  if (o.kind === "task") {
@@ -725,7 +1551,7 @@ export function createRequiredWorkLedger(init) {
725
1551
  return applyForegroundResult(o, entry.foregroundResult);
726
1552
  return merged;
727
1553
  };
728
- const handleTaskTerminal = (e, status) => {
1554
+ const handleTaskTerminal = (e, status, ownTaskNotification = false) => {
729
1555
  const taskId = boundedIdentifier(e["task_id"]);
730
1556
  if (!taskId || typeof status !== "string") {
731
1557
  insufficient.add("event_unknown");
@@ -745,11 +1571,15 @@ export function createRequiredWorkLedger(init) {
745
1571
  return "unknown_shape";
746
1572
  }
747
1573
  let o;
1574
+ // Whether this event found its obligation already tracked, before it could
1575
+ // create or merge one: only a known run can be resolved by its notification.
1576
+ let wasTracked = false;
748
1577
  if (toolUseId) {
749
1578
  // Exact keyed notices are authoritative for their own run, even after resume.
750
1579
  if (evicted.has(toolUseId))
751
1580
  return terminalOnEvicted(toolUseId, taskId, next);
752
1581
  o = obligations.get(toolUseId);
1582
+ wasTracked = o !== undefined;
753
1583
  if (o?.taskId !== null && o?.taskId !== undefined && o.taskId !== taskId) {
754
1584
  insufficient.add("event_conflict");
755
1585
  return "conflict";
@@ -784,6 +1614,7 @@ export function createRequiredWorkLedger(init) {
784
1614
  if (current && evicted.has(current.key))
785
1615
  return terminalOnEvicted(current.key, taskId, next);
786
1616
  o = current ? obligations.get(current.key) : undefined;
1617
+ wasTracked = o !== undefined;
787
1618
  if (!o) {
788
1619
  o = track(`t:${taskId}`, { toolUseId: taskId, taskId, kind: "task", inputDigest: null, background: true, placeholder: true, required: true });
789
1620
  if (!o)
@@ -805,6 +1636,17 @@ export function createRequiredWorkLedger(init) {
805
1636
  // must not refine it.
806
1637
  if (o.state === "failed")
807
1638
  o.failedByResult = false;
1639
+ // The command's own accepted notification delivered its result. A status
1640
+ // update (`task_updated`) never does, and neither does an unknown run.
1641
+ if (ownTaskNotification &&
1642
+ applied === "applied" &&
1643
+ wasTracked &&
1644
+ !o.placeholder &&
1645
+ o.kind !== "task" &&
1646
+ !denials.some((d) => d.toolUseId === o.toolUseId) &&
1647
+ DELIVERY_RESOLVABLE_KINDS.has(o.kind) &&
1648
+ DELIVERY_RESOLVABLE_STATES.has(o.state))
1649
+ o.resultDelivered = true;
808
1650
  return applied;
809
1651
  };
810
1652
  const handleSnapshot = (e) => {
@@ -861,18 +1703,10 @@ export function createRequiredWorkLedger(init) {
861
1703
  }
862
1704
  return outcome;
863
1705
  };
864
- const dispatch = (e) => {
1706
+ const dispatch = (e, structural = false) => {
865
1707
  const type = e["type"];
866
1708
  const subtype = e["subtype"];
867
- const material = type === "assistant" ||
868
- type === "user" ||
869
- type === "result" ||
870
- (type === "system" &&
871
- (subtype === "init" ||
872
- subtype === "task_started" ||
873
- subtype === "task_notification" ||
874
- subtype === "task_updated" ||
875
- subtype === "background_tasks_changed"));
1709
+ const material = isMaterialEvent(type, subtype);
876
1710
  if (!material)
877
1711
  return "not_material";
878
1712
  // Session binding: one session per attempt. A different session id is a
@@ -896,7 +1730,7 @@ export function createRequiredWorkLedger(init) {
896
1730
  if (type === "result")
897
1731
  return handleResult(e, seq);
898
1732
  if (type === "assistant")
899
- return handleAssistant(e);
1733
+ return handleAssistant(e, structural);
900
1734
  if (type === "user")
901
1735
  return handleUser(e, seq);
902
1736
  switch (subtype) {
@@ -905,7 +1739,7 @@ export function createRequiredWorkLedger(init) {
905
1739
  case "task_started":
906
1740
  return handleTaskStarted(e);
907
1741
  case "task_notification":
908
- return handleTaskTerminal(e, e["status"]);
1742
+ return handleTaskTerminal(e, e["status"], true);
909
1743
  case "task_updated": {
910
1744
  const patch = e["patch"];
911
1745
  if (!isRecord(patch)) {
@@ -913,9 +1747,21 @@ export function createRequiredWorkLedger(init) {
913
1747
  return "unknown_shape";
914
1748
  }
915
1749
  // A patch without a status (end_time, progress) is not a lifecycle change.
916
- if (patch["status"] === undefined)
1750
+ // A backgrounding patch only reclassifies the current run it names.
1751
+ if (patch["status"] === undefined) {
1752
+ if (patch["is_backgrounded"] === true) {
1753
+ const taskId = boundedIdentifier(e["task_id"]);
1754
+ const current = taskId ? findCurrentRunByTaskId(taskId) : undefined;
1755
+ const o = current ? obligations.get(current.key) : undefined;
1756
+ if (o) {
1757
+ o.background = true;
1758
+ if (o.kind === "bash_task")
1759
+ o.kind = "bash_bg";
1760
+ }
1761
+ }
917
1762
  return "applied";
918
- return handleTaskTerminal(e, patch["status"]);
1763
+ }
1764
+ return handleTaskTerminal(e, patch["status"], false);
919
1765
  }
920
1766
  case "background_tasks_changed":
921
1767
  return handleSnapshot(e);
@@ -958,23 +1804,70 @@ export function createRequiredWorkLedger(init) {
958
1804
  return false;
959
1805
  };
960
1806
  return all.map((o) => {
1807
+ // BAPI-1613 R3: a denied call that never got a task id never launched.
1808
+ // Its denial still stands in `denials`; only its task state changes. A
1809
+ // background call that errored before any launch is the same case.
1810
+ const neverLaunched = o.state === "failed" && o.taskId === null && (o.erroredBeforeLaunch || denials.some((d) => d.toolUseId === o.toolUseId));
1811
+ const own = neverLaunched ? "failed_to_start" : o.state;
961
1812
  // Only a terminal non-success is replaceable: live work is not superseded,
962
1813
  // and a `conflict` is contradictory evidence, not a failure to retry.
963
- const replaceable = o.state === "failed" || o.state === "failed_to_start" || o.state === "stopped" || o.state === "withdrawn";
964
- return { o, state: replaceable && succeededLater(o) ? "replaced" : o.state };
1814
+ const replaceable = own === "failed" || own === "failed_to_start" || own === "stopped" || own === "withdrawn";
1815
+ return { o, state: replaceable && succeededLater(o) ? "replaced" : own };
965
1816
  });
966
1817
  };
967
1818
  // --- public API -----------------------------------------------------------
1819
+ // --- oversize lines (BAPI-1586) -------------------------------------------
1820
+ let oversizeParser = null;
1821
+ /** Nothing about an unestablished line is applied; the refusal reason is the only consequence. */
1822
+ const refuseOversize = () => {
1823
+ insufficient.add("stream_oversize");
1824
+ latestIsResult = false;
1825
+ return "oversize";
1826
+ };
1827
+ const beginOversizeLine = () => {
1828
+ // A line still open when another begins can only have been cut off.
1829
+ if (oversizeParser !== null)
1830
+ endOversizeLine({ newlineTerminated: false });
1831
+ oversizeParser = createStructuralParser();
1832
+ };
1833
+ const feedOversizeLineChunk = (chunk) => {
1834
+ if (oversizeParser === null)
1835
+ return;
1836
+ oversizeParser.feed(chunk);
1837
+ };
1838
+ function endOversizeLine(options) {
1839
+ const parser = oversizeParser ?? createStructuralParser();
1840
+ oversizeParser = null;
1841
+ // One line is one unit of activity, however many chunks carried it.
1842
+ activitySeq++;
1843
+ const decision = parser.finish();
1844
+ if (decision.kind === "reject" || options.newlineTerminated !== true)
1845
+ return refuseOversize();
1846
+ if (decision.kind === "ignored")
1847
+ return "ignored";
1848
+ try {
1849
+ const r = dispatch(decision.event, true);
1850
+ return r === "not_material" ? "ignored" : r;
1851
+ }
1852
+ catch {
1853
+ insufficient.add("event_unknown");
1854
+ latestIsResult = false;
1855
+ return "unknown_shape";
1856
+ }
1857
+ }
968
1858
  const ingestLine = (line) => {
969
1859
  if (typeof line !== "string" || line.trim().length === 0)
970
1860
  return "blank";
971
- activitySeq++;
972
1861
  if (Buffer.byteLength(line, "utf8") > MAX_EVENT_BYTES) {
973
- // Never parsed: an event this large cannot be trusted to be complete.
974
- insufficient.add("stream_oversize");
975
- latestIsResult = false;
976
- return "oversize";
1862
+ // The argument is a complete logical line; read it through the same
1863
+ // structural path, in slices, without building another whole-event copy.
1864
+ beginOversizeLine();
1865
+ for (let i = 0; i < line.length; i += OVERSIZE_FEED_SLICE_CHARS) {
1866
+ feedOversizeLineChunk(line.slice(i, i + OVERSIZE_FEED_SLICE_CHARS));
1867
+ }
1868
+ return endOversizeLine({ newlineTerminated: true });
977
1869
  }
1870
+ activitySeq++;
978
1871
  let parsed;
979
1872
  try {
980
1873
  parsed = JSON.parse(line);
@@ -1171,11 +2064,16 @@ export function createRequiredWorkLedger(init) {
1171
2064
  };
1172
2065
  return {
1173
2066
  ingestLine,
2067
+ beginOversizeLine,
2068
+ feedOversizeLineChunk,
2069
+ endOversizeLine,
1174
2070
  closureState,
1175
2071
  recordStdinClosed: () => {
1176
2072
  stdinClosed = true;
1177
2073
  },
1178
2074
  recordStreamEnd: (outcome) => {
2075
+ if (oversizeParser !== null)
2076
+ endOversizeLine({ newlineTerminated: false });
1179
2077
  // The first non-clean outcome wins; a later clean EOF cannot repair a lost stream.
1180
2078
  if (streamEnd === null || (streamEnd === "eof" && outcome !== "eof"))
1181
2079
  streamEnd = outcome;
@@ -1213,8 +2111,8 @@ export const COMPLETION_WINDOW_MS = 30 * 60 * 1000;
1213
2111
  * Why the debounce: the first probe rule closed stdin the moment a result
1214
2112
  * arrived and cut off a notification-triggered turn that was about to start.
1215
2113
  * Every new activity resets the window, and closing is never the verdict: the
1216
- * caller drains to EOF and the ledger recomputes, so a late turn still
1217
- * invalidates the apparent closure (`late_activity_after_close`).
2114
+ * caller drains to EOF and the ledger recomputes, so a late turn is judged by
2115
+ * the work it leaves active or unfinished, not by the stdin close alone.
1218
2116
  *
1219
2117
  * The optional-watcher nudge: at most one, only when a turn ended while ONLY server-declared
1220
2118
  * optional watchers are live. It is never sent while required work is live and