@bridge_gpt/mcp-server 0.2.71 → 0.2.73

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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -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/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. 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,8 @@
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";
46
+ import { requiredWorkKindTokens } from "./required-work-diagnostics.js";
47
47
  /**
48
48
  * A background command that fails this soon after its launch acknowledgement is
49
49
  * classified `failed_to_start` and resolves execution of a required task.
@@ -342,6 +342,808 @@ const TERMINAL_STATES = new Set([
342
342
  ]);
343
343
  const FAILED_TO_START_KINDS = new Set(["bash_bg", "bash_task", "subagent_bash"]);
344
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
+ }
345
1147
  export function createRequiredWorkLedger(init) {
346
1148
  const binding = { ...init.binding };
347
1149
  const lifecycleSupported = init.lifecycleSupported === true;
@@ -407,6 +1209,7 @@ export function createRequiredWorkLedger(init) {
407
1209
  launchedAt: null,
408
1210
  resultDelivered: false,
409
1211
  failedByResult: false,
1212
+ erroredBeforeLaunch: false,
410
1213
  ...spec,
411
1214
  required: spec.required ?? !isOptional(spec.kind, spec.inputDigest),
412
1215
  };
@@ -541,8 +1344,6 @@ export function createRequiredWorkLedger(init) {
541
1344
  // --- event handlers -------------------------------------------------------
542
1345
  const onTurnEvent = () => {
543
1346
  turnOpen = true;
544
- if (stdinClosed)
545
- insufficient.add("late_activity_after_close");
546
1347
  };
547
1348
  const handleInit = (e) => {
548
1349
  const sid = boundedIdentifier(e["session_id"]);
@@ -554,7 +1355,7 @@ export function createRequiredWorkLedger(init) {
554
1355
  sawInit = true;
555
1356
  return "applied";
556
1357
  };
557
- const handleAssistant = (e) => {
1358
+ const handleAssistant = (e, structural = false) => {
558
1359
  onTurnEvent();
559
1360
  const content = contentOf(e);
560
1361
  if (!Array.isArray(content)) {
@@ -575,8 +1376,10 @@ export function createRequiredWorkLedger(init) {
575
1376
  outcome = "unknown_shape";
576
1377
  continue;
577
1378
  }
578
- const input = b["input"];
579
- 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);
580
1383
  const bg = isRecord(input) && input["run_in_background"] === true;
581
1384
  // Bounded index; the input itself is dropped here, only digests remain.
582
1385
  if (!toolUses.has(id)) {
@@ -588,11 +1391,13 @@ export function createRequiredWorkLedger(init) {
588
1391
  toolUses.set(id, {
589
1392
  name,
590
1393
  inputDigest,
591
- denial: resolveDenialOperation(name, input),
1394
+ denial: structural ? { operation: "other", targetDigest: null, linkKeys: [] } : resolveDenialOperation(name, input),
592
1395
  background: bg,
593
1396
  foregroundResult: null,
594
1397
  });
595
1398
  }
1399
+ if (structural)
1400
+ continue;
596
1401
  if (name === "Agent" || name === "Task") {
597
1402
  track(id, { toolUseId: id, taskId: null, kind: bg ? "delegate_bg" : "delegate", inputDigest, background: bg, placeholder: false });
598
1403
  }
@@ -657,6 +1462,13 @@ export function createRequiredWorkLedger(init) {
657
1462
  // first named launch event for the startup window. No result text is read.
658
1463
  if (!isError)
659
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
+ }
660
1472
  continue;
661
1473
  }
662
1474
  // A foreground result is the task's own terminal result, delivered to the
@@ -701,6 +1513,14 @@ export function createRequiredWorkLedger(init) {
701
1513
  insufficient.add("event_conflict");
702
1514
  return "conflict";
703
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
+ }
704
1524
  if (!repeatedStart && hasOtherLiveClaim(taskId, o.key)) {
705
1525
  o.taskId = taskId;
706
1526
  o.state = "conflict";
@@ -709,6 +1529,13 @@ export function createRequiredWorkLedger(init) {
709
1529
  }
710
1530
  o.taskId = taskId;
711
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
+ }
712
1539
  // An orphan terminal recorded before this start had to guess a generic
713
1540
  // background `task`; the trusted start now names the real kind.
714
1541
  if (o.kind === "task") {
@@ -724,7 +1551,7 @@ export function createRequiredWorkLedger(init) {
724
1551
  return applyForegroundResult(o, entry.foregroundResult);
725
1552
  return merged;
726
1553
  };
727
- const handleTaskTerminal = (e, status) => {
1554
+ const handleTaskTerminal = (e, status, ownTaskNotification = false) => {
728
1555
  const taskId = boundedIdentifier(e["task_id"]);
729
1556
  if (!taskId || typeof status !== "string") {
730
1557
  insufficient.add("event_unknown");
@@ -744,11 +1571,15 @@ export function createRequiredWorkLedger(init) {
744
1571
  return "unknown_shape";
745
1572
  }
746
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;
747
1577
  if (toolUseId) {
748
1578
  // Exact keyed notices are authoritative for their own run, even after resume.
749
1579
  if (evicted.has(toolUseId))
750
1580
  return terminalOnEvicted(toolUseId, taskId, next);
751
1581
  o = obligations.get(toolUseId);
1582
+ wasTracked = o !== undefined;
752
1583
  if (o?.taskId !== null && o?.taskId !== undefined && o.taskId !== taskId) {
753
1584
  insufficient.add("event_conflict");
754
1585
  return "conflict";
@@ -783,6 +1614,7 @@ export function createRequiredWorkLedger(init) {
783
1614
  if (current && evicted.has(current.key))
784
1615
  return terminalOnEvicted(current.key, taskId, next);
785
1616
  o = current ? obligations.get(current.key) : undefined;
1617
+ wasTracked = o !== undefined;
786
1618
  if (!o) {
787
1619
  o = track(`t:${taskId}`, { toolUseId: taskId, taskId, kind: "task", inputDigest: null, background: true, placeholder: true, required: true });
788
1620
  if (!o)
@@ -804,6 +1636,17 @@ export function createRequiredWorkLedger(init) {
804
1636
  // must not refine it.
805
1637
  if (o.state === "failed")
806
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;
807
1650
  return applied;
808
1651
  };
809
1652
  const handleSnapshot = (e) => {
@@ -860,18 +1703,10 @@ export function createRequiredWorkLedger(init) {
860
1703
  }
861
1704
  return outcome;
862
1705
  };
863
- const dispatch = (e) => {
1706
+ const dispatch = (e, structural = false) => {
864
1707
  const type = e["type"];
865
1708
  const subtype = e["subtype"];
866
- const material = type === "assistant" ||
867
- type === "user" ||
868
- type === "result" ||
869
- (type === "system" &&
870
- (subtype === "init" ||
871
- subtype === "task_started" ||
872
- subtype === "task_notification" ||
873
- subtype === "task_updated" ||
874
- subtype === "background_tasks_changed"));
1709
+ const material = isMaterialEvent(type, subtype);
875
1710
  if (!material)
876
1711
  return "not_material";
877
1712
  // Session binding: one session per attempt. A different session id is a
@@ -895,7 +1730,7 @@ export function createRequiredWorkLedger(init) {
895
1730
  if (type === "result")
896
1731
  return handleResult(e, seq);
897
1732
  if (type === "assistant")
898
- return handleAssistant(e);
1733
+ return handleAssistant(e, structural);
899
1734
  if (type === "user")
900
1735
  return handleUser(e, seq);
901
1736
  switch (subtype) {
@@ -904,7 +1739,7 @@ export function createRequiredWorkLedger(init) {
904
1739
  case "task_started":
905
1740
  return handleTaskStarted(e);
906
1741
  case "task_notification":
907
- return handleTaskTerminal(e, e["status"]);
1742
+ return handleTaskTerminal(e, e["status"], true);
908
1743
  case "task_updated": {
909
1744
  const patch = e["patch"];
910
1745
  if (!isRecord(patch)) {
@@ -912,9 +1747,21 @@ export function createRequiredWorkLedger(init) {
912
1747
  return "unknown_shape";
913
1748
  }
914
1749
  // A patch without a status (end_time, progress) is not a lifecycle change.
915
- 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
+ }
916
1762
  return "applied";
917
- return handleTaskTerminal(e, patch["status"]);
1763
+ }
1764
+ return handleTaskTerminal(e, patch["status"], false);
918
1765
  }
919
1766
  case "background_tasks_changed":
920
1767
  return handleSnapshot(e);
@@ -957,23 +1804,70 @@ export function createRequiredWorkLedger(init) {
957
1804
  return false;
958
1805
  };
959
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;
960
1812
  // Only a terminal non-success is replaceable: live work is not superseded,
961
1813
  // and a `conflict` is contradictory evidence, not a failure to retry.
962
- const replaceable = o.state === "failed" || o.state === "failed_to_start" || o.state === "stopped" || o.state === "withdrawn";
963
- 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 };
964
1816
  });
965
1817
  };
966
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
+ }
967
1858
  const ingestLine = (line) => {
968
1859
  if (typeof line !== "string" || line.trim().length === 0)
969
1860
  return "blank";
970
- activitySeq++;
971
1861
  if (Buffer.byteLength(line, "utf8") > MAX_EVENT_BYTES) {
972
- // Never parsed: an event this large cannot be trusted to be complete.
973
- insufficient.add("stream_oversize");
974
- latestIsResult = false;
975
- 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 });
976
1869
  }
1870
+ activitySeq++;
977
1871
  let parsed;
978
1872
  try {
979
1873
  parsed = JSON.parse(line);
@@ -1037,6 +1931,19 @@ export function createRequiredWorkLedger(init) {
1037
1931
  else if (!bashBgIds.includes(o.taskId ?? o.key))
1038
1932
  bashBgIds.push(o.taskId ?? o.key);
1039
1933
  }
1934
+ const liveRequiredKinds = [];
1935
+ for (const o of obligations.values()) {
1936
+ if (isLive(o) && o.required)
1937
+ liveRequiredKinds.push(o.kind);
1938
+ }
1939
+ for (const tid of snap.required) {
1940
+ const o = findCurrentRunByTaskId(tid);
1941
+ // A task the obligations map already holds was counted above.
1942
+ if (!o)
1943
+ liveRequiredKinds.push("task");
1944
+ else if (!obligations.has(o.key))
1945
+ liveRequiredKinds.push(o.kind);
1946
+ }
1040
1947
  return {
1041
1948
  readyToClose,
1042
1949
  liveRequired,
@@ -1052,6 +1959,7 @@ export function createRequiredWorkLedger(init) {
1052
1959
  ...snap.required,
1053
1960
  ])]
1054
1961
  : [],
1962
+ liveRequiredKinds,
1055
1963
  };
1056
1964
  };
1057
1965
  // One predicate for "a required task is still pending", shared by the envelope
@@ -1156,11 +2064,16 @@ export function createRequiredWorkLedger(init) {
1156
2064
  };
1157
2065
  return {
1158
2066
  ingestLine,
2067
+ beginOversizeLine,
2068
+ feedOversizeLineChunk,
2069
+ endOversizeLine,
1159
2070
  closureState,
1160
2071
  recordStdinClosed: () => {
1161
2072
  stdinClosed = true;
1162
2073
  },
1163
2074
  recordStreamEnd: (outcome) => {
2075
+ if (oversizeParser !== null)
2076
+ endOversizeLine({ newlineTerminated: false });
1164
2077
  // The first non-clean outcome wins; a later clean EOF cannot repair a lost stream.
1165
2078
  if (streamEnd === null || (streamEnd === "eof" && outcome !== "eof"))
1166
2079
  streamEnd = outcome;
@@ -1198,8 +2111,8 @@ export const COMPLETION_WINDOW_MS = 30 * 60 * 1000;
1198
2111
  * Why the debounce: the first probe rule closed stdin the moment a result
1199
2112
  * arrived and cut off a notification-triggered turn that was about to start.
1200
2113
  * Every new activity resets the window, and closing is never the verdict: the
1201
- * caller drains to EOF and the ledger recomputes, so a late turn still
1202
- * 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.
1203
2116
  *
1204
2117
  * The optional-watcher nudge: at most one, only when a turn ended while ONLY server-declared
1205
2118
  * optional watchers are live. It is never sent while required work is live and
@@ -1241,6 +2154,9 @@ export function createClosureSupervisor(opts) {
1241
2154
  const close = (reason) => {
1242
2155
  if (closed || disposed)
1243
2156
  return;
2157
+ // BAPI-1554: capture what was running BEFORE anything below can change the
2158
+ // ledger, and freeze it so the later log and failure text cannot drift.
2159
+ const windowLiveKinds = Object.freeze(reason === "window" ? requiredWorkKindTokens(ledger.closureState().liveRequiredKinds) : []);
1244
2160
  closed = true;
1245
2161
  closedReason = reason;
1246
2162
  clearDebounce();
@@ -1260,7 +2176,7 @@ export function createClosureSupervisor(opts) {
1260
2176
  });
1261
2177
  if (reason === "window") {
1262
2178
  try {
1263
- opts.onWindowExpiry?.();
2179
+ opts.onWindowExpiry?.(windowLiveKinds);
1264
2180
  }
1265
2181
  catch {
1266
2182
  /* the caller's termination scheduling must never break closure */