@corca-org/ceal-host-win32-x64 1.0.23 → 1.0.24

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.
@@ -139,7 +139,7 @@ var client_wire_contract_default = {
139
139
  },
140
140
  command_request: {
141
141
  schema_name: "ceal.command_request",
142
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
142
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
143
143
  absolute_transport_max_bytes: 65536
144
144
  },
145
145
  command_resolution: {
@@ -185,7 +185,7 @@ var client_wire_contract_default = {
185
185
  },
186
186
  command_response: {
187
187
  schema_name: "ceal.command_response",
188
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
188
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
189
189
  descriptor_field: "verified_artifact",
190
190
  request_context_field: "request_context",
191
191
  required_fields: [
@@ -198,7 +198,8 @@ var client_wire_contract_default = {
198
198
  "visible_output_max_bytes",
199
199
  "local_delivery",
200
200
  "verified_artifact",
201
- "request_context"
201
+ "request_context",
202
+ "result_file"
202
203
  ],
203
204
  bare_document_fields: [
204
205
  "invocation",
@@ -467,6 +468,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
467
468
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
468
469
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
469
470
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
471
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
472
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
473
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
470
474
  var CEAL_GATEWAY_READ_REUSE_DISPOSITIONS = vocabulary(["response_cache_hit", "corpus_hit", "corpus_hit_after_revalidation", "corpus_partial_provider_supplement", "provider_direct", "provider_continuation", "reuse_unavailable"]);
471
475
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
472
476
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -507,6 +511,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
507
511
  ]);
508
512
 
509
513
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
514
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
515
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
516
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
517
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
518
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
519
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
520
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
521
+ function escapePathPattern(value) {
522
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
523
+ }
524
+ function machineHomePathPatterns(flags) {
525
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
526
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
527
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
528
+ }
510
529
  var CealProtocolValidationError = class extends Error {
511
530
  name = "CealProtocolValidationError";
512
531
  code;
@@ -862,6 +881,7 @@ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Rel
862
881
  var HOST_INSTALL_REPAIR = "The local Host or Relay is missing, stale, or unavailable. Run `ceal-host install`, then `ceal-host discovery sync`, and retry from a new producer conversation.";
863
882
  var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn; reason uncertain. Host mode is unavailable in an ephemeral side conversation. When you know you are in one, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions, without Host session/turn correlation or Host usage attribution. Unknown-outcome `repeat_request` needs the same Host turn or explicit `--request-context`. Otherwise return to the original regular conversation. Host refusal never switches modes; report intended Host calls as a gap.";
864
883
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
884
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
865
885
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
866
886
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
867
887
  }
@@ -882,13 +902,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
882
902
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
883
903
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
884
904
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
885
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
886
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
887
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
888
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
889
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
890
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
891
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
905
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
906
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
907
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
908
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
909
+ person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Person, then retry this same session refresh.", "ask_admin", 403),
910
+ principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family. Ask an Admin to reactivate the Principal, then retry this same session refresh.", "ask_admin", 403),
911
+ authority_replaced: guidance("The Gateway authority has been replaced; this session is no longer valid here. Run `ceal session adopt --gateway <origin> --email <email>` against the current Gateway to complete mailbox-confirmed recovery.", "repair_or_adopt_session", 409),
912
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
913
+ refresh_recovery_unavailable: guidance("The Gateway's durable refresh-recovery key is unavailable. Retry the same refresh attempt after the key is available.", "retry", 503, true),
914
+ refresh_recovery_outcome_unavailable: guidance("The Gateway could not safely recover the outcome of a prior refresh. Ask an administrator to inspect the Gateway session state before retrying or adopting this session.", "ask_admin", 503),
915
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
916
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
892
917
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
893
918
  session_store_unwritable: guidance("The Ceal client could not write its local session store; the operating system refused the write (EACCES, EPERM, or EROFS). rerun_outside_agent_sandbox reruns it with escalated execution.", "rerun_outside_agent_sandbox", 500),
894
919
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -903,10 +928,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
903
928
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
904
929
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
905
930
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
906
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
907
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
908
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
909
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
931
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
932
+ [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance("The Gateway is still starting; the refresh was not attempted and the refresh token was not consumed. Retry the same refresh attempt after the Gateway is serving.", "retry", 503, true),
910
933
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
911
934
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
912
935
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -918,6 +941,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
918
941
  // The safe move varies by request. Keep the sentence conditional on the
919
942
  // same `retryable` and `next_action` facts the response exposes.
920
943
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
944
+ // A provider write the Gateway command deadline cut after its dispatch: the write left and its receipt is still settling, so the caller reads the receipt instead of repeating the write.
945
+ write_in_progress: guidance("The provider write was dispatched but the Gateway command deadline cut the wait before its outcome settled. Do not repeat the write; read the durable receipt named by write_request_ref with write_receipt.get.", "write_receipt.get", 500),
921
946
  // Restored verbatim from the retired `localFailureText`
922
947
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
923
948
  // session context unavailable, so the caller repairs or adopts the
@@ -1567,6 +1592,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1567
1592
  "review_submitted",
1568
1593
  "comment_created",
1569
1594
  "reaction_created",
1595
+ "pull_request_merged",
1596
+ "release_published",
1570
1597
  "ceal_write_completed",
1571
1598
  "event_start",
1572
1599
  "all_day_start",
@@ -1578,7 +1605,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
1578
1605
  "page_last_edited",
1579
1606
  "resource_modified"
1580
1607
  ]);
1581
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
1608
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
1582
1609
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
1583
1610
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
1584
1611
  "provider_page_budget",
@@ -1599,6 +1626,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1599
1626
  "github.pull_request.opened",
1600
1627
  "github.issue.edited",
1601
1628
  "github.pull_request.edited",
1629
+ "github.pull_request.merged",
1630
+ "github.release.published",
1602
1631
  "github.review.submitted",
1603
1632
  "github.issue_comment.created",
1604
1633
  "github.review_comment.created",
@@ -1612,6 +1641,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
1612
1641
  "drive.file.created",
1613
1642
  "drive.file.modified",
1614
1643
  "drive.file.viewed",
1644
+ "mail.sent",
1615
1645
  "notion.page.created",
1616
1646
  "notion.page.edited"
1617
1647
  ]);
@@ -1625,6 +1655,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1625
1655
  "github.review_comment.created": "comment_created",
1626
1656
  "github.issue.opened": "resource_created",
1627
1657
  "github.pull_request.opened": "resource_created",
1658
+ "github.pull_request.merged": "pull_request_merged",
1659
+ "github.release.published": "release_published",
1628
1660
  "github.issue.edited": "resource_modified",
1629
1661
  "github.pull_request.edited": "resource_modified",
1630
1662
  "github.reaction.created": "reaction_created",
@@ -1635,6 +1667,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
1635
1667
  "drive.file.created": "file_created",
1636
1668
  "drive.file.modified": "file_modified_by_me",
1637
1669
  "drive.file.viewed": "file_viewed_by_me",
1670
+ "mail.sent": "message_created",
1638
1671
  "notion.page.created": "page_created",
1639
1672
  "notion.page.edited": "page_last_edited"
1640
1673
  });
@@ -1745,6 +1778,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
1745
1778
  "principal_inactive",
1746
1779
  "authority_replaced",
1747
1780
  "refresh_recovery_unavailable",
1781
+ "refresh_recovery_outcome_unavailable",
1782
+ "refresh_state_unavailable",
1748
1783
  "refresh_recovery_expired",
1749
1784
  // The serving gate answers this while the Gateway is still starting and the
1750
1785
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -2503,6 +2538,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
2503
2538
  maximum: CEAL_PROTOCOL_VERSION
2504
2539
  });
2505
2540
 
2541
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
2542
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
2543
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
2544
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
2545
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
2546
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
2547
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
2548
+ function redactOperatorDiagnosticSecrets(value) {
2549
+ return value.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [redacted]").replace(/(["']?(?:authorization|[A-Za-z0-9_-]*(?:token|secret|credential|password|key))["']?\s*[:=]\s*)(?!(?:"unknown"|'unknown'|unknown\b))(?:"[^"]*"|'[^']*'|[^\s,;}]+)/giu, "$1[redacted]");
2550
+ }
2551
+ function redactOperatorDiagnosticText(value) {
2552
+ const normalized = normalizeCealSingleLineText(value);
2553
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
2554
+ }
2555
+ function renderOperatorDiagnostic(value) {
2556
+ const state = collectDiagnosticState(value);
2557
+ const fields = [
2558
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
2559
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
2560
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
2561
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
2562
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
2563
+ ].filter((field) => field !== void 0);
2564
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
2565
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
2566
+ }
2567
+ function collectDiagnosticState(value) {
2568
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
2569
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
2570
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
2571
+ const current = pending.shift();
2572
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
2573
+ }
2574
+ return state;
2575
+ }
2576
+ function visitDiagnosticNode(current, state, pending, visited) {
2577
+ if (isObject(current)) {
2578
+ if (visited.has(current)) return;
2579
+ visited.add(current);
2580
+ }
2581
+ captureProcessEvidence(current, state);
2582
+ appendCause(current, state.causes);
2583
+ enqueueCauseChildren(current, state.causes.length, pending);
2584
+ }
2585
+ function captureProcessEvidence(current, state) {
2586
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
2587
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
2588
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
2589
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
2590
+ }
2591
+ function appendCause(current, causes) {
2592
+ const errors = read(current, "errors");
2593
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
2594
+ causes.push(errorCause(current));
2595
+ return;
2596
+ }
2597
+ if (!isObject(current)) {
2598
+ const message = safeText(current);
2599
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
2600
+ }
2601
+ }
2602
+ function errorCause(error) {
2603
+ const name = safeText(read(error, "name")) ?? "Error";
2604
+ const message = safeText(read(error, "message"));
2605
+ const codeValue = read(error, "code");
2606
+ const code = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
2607
+ const errnoValue = read(error, "errno");
2608
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
2609
+ const syscall = safeText(read(error, "syscall"));
2610
+ const path = safePath(read(error, "path"));
2611
+ return Object.freeze({ error_class: name, ...message === void 0 ? {} : { message }, ...code === void 0 ? {} : { code }, ...errno === void 0 ? {} : { errno }, ...syscall === void 0 ? {} : { syscall }, ...path === void 0 ? {} : { path } });
2612
+ }
2613
+ function enqueueCauseChildren(current, causeCount, pending) {
2614
+ const cause = read(current, "cause");
2615
+ if (cause !== void 0) pending.push(cause);
2616
+ const errors = read(current, "errors");
2617
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
2618
+ }
2619
+ function isObject(value) {
2620
+ return typeof value === "object" && value !== null;
2621
+ }
2622
+ function formatCause(cause) {
2623
+ const fields = [
2624
+ cause.error_class,
2625
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
2626
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
2627
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
2628
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
2629
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
2630
+ ].filter((field) => field !== void 0);
2631
+ return fields.join(" ");
2632
+ }
2633
+ function tail(value) {
2634
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
2635
+ return safeDiagnosticText(clipped);
2636
+ }
2637
+ function safeText(value) {
2638
+ if (typeof value !== "string") return void 0;
2639
+ const safe = safeDiagnosticText(value);
2640
+ if (safe.length === 0) return void 0;
2641
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
2642
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
2643
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
2644
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2645
+ }
2646
+ function safePath(value) {
2647
+ if (typeof value !== "string") return void 0;
2648
+ const safe = safeDiagnosticText(value);
2649
+ if (safe.length === 0) return void 0;
2650
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
2651
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
2652
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
2653
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
2654
+ }
2655
+ function safeDiagnosticText(value) {
2656
+ return redactOperatorDiagnosticText(String(value));
2657
+ }
2658
+ function outputText(value) {
2659
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
2660
+ if (value instanceof Uint8Array) {
2661
+ try {
2662
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
2663
+ } catch {
2664
+ return void 0;
2665
+ }
2666
+ }
2667
+ return void 0;
2668
+ }
2669
+ function safeStatus(value) {
2670
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2671
+ return typeof value === "string" ? safeText(value) : void 0;
2672
+ }
2673
+ function safeExitCode(value) {
2674
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
2675
+ }
2676
+ function read(value, key) {
2677
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
2678
+ try {
2679
+ return Reflect.get(value, key);
2680
+ } catch {
2681
+ return void 0;
2682
+ }
2683
+ }
2684
+ function redactHomePaths(value) {
2685
+ const paths = [
2686
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
2687
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
2688
+ ];
2689
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
2690
+ let output = "";
2691
+ let cursor = 0;
2692
+ for (const path of paths) {
2693
+ if (path.start < cursor) continue;
2694
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
2695
+ cursor = path.end;
2696
+ }
2697
+ return output + value.slice(cursor);
2698
+ }
2699
+ function configuredHomePathPatterns() {
2700
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
2701
+ return homes.flatMap((home) => {
2702
+ const root = home.replace(/[\\/]+$/gu, "");
2703
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
2704
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
2705
+ return [{ pattern, prefixLength: root.length }];
2706
+ });
2707
+ }
2708
+ function matchedHomePrefixLength(value) {
2709
+ let separators = 0;
2710
+ for (let index = 0; index < value.length; index += 1) {
2711
+ if (value[index] !== "/" && value[index] !== "\\") continue;
2712
+ separators += 1;
2713
+ if (separators === 3) return index;
2714
+ }
2715
+ return value.length;
2716
+ }
2717
+ function redactUrls(value) {
2718
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
2719
+ }
2720
+ function redactFilePaths(value) {
2721
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
2722
+ }
2723
+ function homePathRange(value, match, prefixLength) {
2724
+ const index = match.index;
2725
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
2726
+ const start = index;
2727
+ let end = start + match[0].length;
2728
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
2729
+ if (quote !== void 0) {
2730
+ const closing = value.indexOf(quote, end);
2731
+ if (closing >= 0) end = closing;
2732
+ }
2733
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
2734
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
2735
+ }
2736
+ function truncateUtf8(value, maxBytes) {
2737
+ if (byteLength(value) <= maxBytes) return value;
2738
+ let output = "";
2739
+ for (const character of value) {
2740
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
2741
+ output += character;
2742
+ }
2743
+ return `${output}…`;
2744
+ }
2745
+
2506
2746
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
2507
2747
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
2508
2748
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -2934,7 +3174,7 @@ function parseCanonicalJson(text, error) {
2934
3174
  if (canonical !== text.trim()) throw new Error(`noncanonical: ${refusalFacts([{ name: "config_bytes", value: Buffer.byteLength(text.trim(), "utf8"), expected: `the ${Buffer.byteLength(canonical, "utf8")} bytes of its canonical form` }, { name: "first_difference_index", value: firstDifferenceIndex(text.trim(), canonical) }])}`);
2935
3175
  return value;
2936
3176
  } catch (parseError) {
2937
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
3177
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
2938
3178
  }
2939
3179
  }
2940
3180
  function firstDifferenceIndex(left, right) {
@@ -3549,14 +3789,14 @@ var HostUsageFactsStore = class {
3549
3789
  const gate = new Promise((resolve) => {
3550
3790
  release = resolve;
3551
3791
  });
3552
- const tail = previous.then(() => gate);
3553
- SESSION_TRANSITION_TAILS.set(key, tail);
3792
+ const tail2 = previous.then(() => gate);
3793
+ SESSION_TRANSITION_TAILS.set(key, tail2);
3554
3794
  await previous;
3555
3795
  try {
3556
3796
  return await run();
3557
3797
  } finally {
3558
3798
  release?.();
3559
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
3799
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
3560
3800
  }
3561
3801
  }
3562
3802
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -4169,9 +4409,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
4169
4409
  let lastNewline = -1;
4170
4410
  while (position < size) {
4171
4411
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
4172
- const read = await handle.read(buffer, 0, buffer.length, position);
4173
- if (read.bytesRead === 0) break;
4174
- const chunk = buffer.subarray(0, read.bytesRead);
4412
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
4413
+ if (read2.bytesRead === 0) break;
4414
+ const chunk = buffer.subarray(0, read2.bytesRead);
4175
4415
  chunks.push(chunk);
4176
4416
  const newline = chunk.lastIndexOf(10);
4177
4417
  if (newline >= 0) lastNewline = total + newline;
@@ -4344,15 +4584,15 @@ var HostProducerDrainCore = class {
4344
4584
  return run;
4345
4585
  }
4346
4586
  async drainLocked() {
4347
- const read = await this.host.listEnvelopes();
4587
+ const read2 = await this.host.listEnvelopes();
4348
4588
  let removed = 0;
4349
4589
  let expired = 0;
4350
- for (const envelope of read.entries) {
4590
+ for (const envelope of read2.entries) {
4351
4591
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
4352
4592
  else removed += 1;
4353
4593
  await this.host.removeEnvelope(envelope);
4354
4594
  }
4355
- return { removed, expired, malformed: read.malformed };
4595
+ return { removed, expired, malformed: read2.malformed };
4356
4596
  }
4357
4597
  };
4358
4598
 
@@ -4436,29 +4676,46 @@ var HostUsageTranscriptSourceError = class extends Error {
4436
4676
  this.name = "HostUsageTranscriptSourceError";
4437
4677
  }
4438
4678
  };
4439
- async function readHostUsageTranscriptSource(read) {
4679
+ async function readHostUsageTranscriptSource(read2) {
4440
4680
  try {
4441
- return await read();
4681
+ return await read2();
4442
4682
  } catch (error) {
4443
4683
  throw new HostUsageTranscriptSourceError({ cause: error });
4444
4684
  }
4445
4685
  }
4446
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
4447
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
4448
- let failed = false;
4449
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4450
- const index = (startIndex + attempt) % registrations.length;
4451
- const registration = registrations[index];
4452
- if (registration === void 0) continue;
4453
- try {
4454
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
4455
- } catch (error) {
4456
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4686
+ var HostUsageRegistrationCapture = class {
4687
+ nextIndex = 0;
4688
+ producer;
4689
+ diagnosticSink;
4690
+ constructor(producer, diagnosticSink) {
4691
+ this.producer = producer;
4692
+ this.diagnosticSink = diagnosticSink;
4693
+ }
4694
+ async captureNext(registrations, capture) {
4695
+ let failed = false;
4696
+ let captured = false;
4697
+ const onFailure = () => {
4457
4698
  failed = true;
4699
+ };
4700
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
4701
+ const index = (this.nextIndex + attempt) % registrations.length;
4702
+ const registration = registrations[index];
4703
+ if (registration === void 0) continue;
4704
+ try {
4705
+ captured = await capture(registration, onFailure);
4706
+ if (captured) {
4707
+ this.nextIndex = (index + 1) % registrations.length;
4708
+ break;
4709
+ }
4710
+ } catch (error) {
4711
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
4712
+ onFailure();
4713
+ }
4458
4714
  }
4715
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
4716
+ return captured;
4459
4717
  }
4460
- return { captured: false, nextIndex: startIndex, failed };
4461
- }
4718
+ };
4462
4719
  async function openHostUsageTranscriptCursor(input) {
4463
4720
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants5.O_RDONLY));
4464
4721
  let source;
@@ -4757,6 +5014,13 @@ var CodexOutboxStore = class {
4757
5014
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
4758
5015
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
4759
5016
  }
5017
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
5018
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
5019
+ await this.prepare();
5020
+ const registration = await readOptionalJson2(path, validateRegistration);
5021
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
5022
+ return registration;
5023
+ }
4760
5024
  async listTranscriptRegistrations() {
4761
5025
  await this.prepare();
4762
5026
  const registrations = [];
@@ -4783,16 +5047,16 @@ var CodexOutboxStore = class {
4783
5047
  }
4784
5048
  async findByAlias(sourceRef, sessionRef, alias) {
4785
5049
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef) || !SAFE_REF3.test(alias)) return null;
4786
- const read = await this.list();
4787
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
5050
+ const read2 = await this.list();
5051
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
4788
5052
  if (envelope !== null) return envelopeMatch(envelope);
4789
5053
  await this.prepare();
4790
5054
  return null;
4791
5055
  }
4792
5056
  async hasPriorTurn(sourceRef, sessionRef) {
4793
5057
  if (!SAFE_REF3.test(sourceRef) || !SAFE_REF3.test(sessionRef)) return false;
4794
- const read = await this.list();
4795
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
5058
+ const read2 = await this.list();
5059
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
4796
5060
  return false;
4797
5061
  }
4798
5062
  entryPath(submissionRef) {
@@ -4848,7 +5112,7 @@ async function writeAtomicJson(path, value) {
4848
5112
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
4849
5113
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
4850
5114
  try {
4851
- const handle = await open4(temp, "wx");
5115
+ const handle = await open4(temp, "wx", 384);
4852
5116
  try {
4853
5117
  await handle.writeFile(text, "utf8");
4854
5118
  await handle.sync();
@@ -4890,13 +5154,20 @@ async function readOptionalJson2(path, validate) {
4890
5154
  }
4891
5155
  async function ensureOwnerDirectory(path) {
4892
5156
  try {
4893
- await stat2(path);
5157
+ try {
5158
+ const stats2 = await stat2(path);
5159
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
5160
+ return;
5161
+ } catch (error) {
5162
+ if (!isNotFound2(error)) throw error;
5163
+ }
5164
+ await mkdir4(path, { recursive: true, mode: 448 });
5165
+ const stats = await stat2(path);
5166
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4894
5167
  } catch (error) {
4895
- if (!isNotFound2(error)) throw storageError("Codex owner state directory is unavailable.");
4896
- await mkdir4(path, { recursive: true });
5168
+ if (error instanceof CodexHostAdapterError) throw error;
5169
+ throw storageError("Codex owner state directory is unavailable.");
4897
5170
  }
4898
- const stats = await stat2(path);
4899
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
4900
5171
  }
4901
5172
  async function readOwnerStateFile(path) {
4902
5173
  let handle;
@@ -5702,20 +5973,16 @@ var CodexUsageFactsCapturer = class {
5702
5973
  sources;
5703
5974
  usage;
5704
5975
  now;
5705
- diagnosticSink;
5706
- nextRegistrationIndex = 0;
5976
+ registrations;
5707
5977
  constructor(options) {
5708
5978
  this.sources = new CodexOutboxStore(options.outbox_dir);
5709
5979
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
5710
5980
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
5711
- this.diagnosticSink = options.diagnostic_sink;
5981
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
5712
5982
  }
5713
5983
  async captureNext() {
5714
5984
  const registrations = await this.sources.listTranscriptRegistrations();
5715
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
5716
- this.nextRegistrationIndex = result.nextIndex;
5717
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
5718
- return result.captured;
5985
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
5719
5986
  }
5720
5987
  async captureRegistration(registration) {
5721
5988
  const prepared = await openHostUsageTranscriptCursor({