@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.
@@ -2118,7 +2118,7 @@ var client_wire_contract_default = {
2118
2118
  },
2119
2119
  command_request: {
2120
2120
  schema_name: "ceal.command_request",
2121
- fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context"],
2121
+ fields: ["schema_version", "argv", "operation", "client_nonce", "context_token", "request_context", "materialize_result"],
2122
2122
  absolute_transport_max_bytes: 65536
2123
2123
  },
2124
2124
  command_resolution: {
@@ -2164,7 +2164,7 @@ var client_wire_contract_default = {
2164
2164
  },
2165
2165
  command_response: {
2166
2166
  schema_name: "ceal.command_response",
2167
- fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context"],
2167
+ fields: ["schema_version", "exit_code", "document", "operation_id", "visible_output_max_bytes", "local_delivery", "verified_artifact", "request_context", "result_file"],
2168
2168
  descriptor_field: "verified_artifact",
2169
2169
  request_context_field: "request_context",
2170
2170
  required_fields: [
@@ -2177,7 +2177,8 @@ var client_wire_contract_default = {
2177
2177
  "visible_output_max_bytes",
2178
2178
  "local_delivery",
2179
2179
  "verified_artifact",
2180
- "request_context"
2180
+ "request_context",
2181
+ "result_file"
2181
2182
  ],
2182
2183
  bare_document_fields: [
2183
2184
  "invocation",
@@ -2446,6 +2447,9 @@ var CEAL_OPERATION_READINESS_VALUES = vocabulary(["ready", "degraded", "unavaila
2446
2447
  var CEAL_TARGET_REQUIREMENTS = vocabulary(["required", "optional", "none"]);
2447
2448
  var CEAL_AUDIT_OUTCOMES = vocabulary(["succeeded", "denied", "failed"]);
2448
2449
  var CEAL_GATEWAY_PROVIDER_STEP_OUTCOMES = vocabulary(["completed", "rejected", "throttled", "failed"]);
2450
+ var CEAL_GATEWAY_CORPUS_READ_PROVIDERS = vocabulary(["slack", "google_drive", "notion"]);
2451
+ var CEAL_GATEWAY_CORPUS_READ_OUTCOMES = vocabulary(["answered_from_corpus", "live_fallback"]);
2452
+ var CEAL_GATEWAY_CORPUS_READ_FALLBACK_REASONS = vocabulary(["uncovered_window", "stale", "not_organization_public", "partition_missing"]);
2449
2453
  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"]);
2450
2454
  var CEAL_GATEWAY_READ_REUSE_UNAVAILABLE_REASONS = vocabulary(["not_reported", "storage_unavailable", "coverage_incomplete", "freshness_refresh_required", "not_reusable", "bypassed"]);
2451
2455
  var CEAL_GATEWAY_DERIVED_STORE_FAILURE_CLASSES = vocabulary(["storage_unavailable", "decode_mismatch", "write_conflict", "quota", "store_error"]);
@@ -2486,6 +2490,21 @@ var CEAL_GATEWAY_ORGANIZATION_ROUTE_FACT_CALL_KEYS = Object.freeze([
2486
2490
  ]);
2487
2491
 
2488
2492
  // packages/ceal-client-protocol/src/gateway-validation-primitives.ts
2493
+ var POSIX_HOME_ROOTS = [["/", "home"].join(""), ["/", "Users"].join("")];
2494
+ var WINDOWS_HOME_ROOT = ["C:", "\\", "Users"].join("");
2495
+ var USER_SEGMENT_BODY = "[^/\\\\ \\t\\r\\n\"'`${}]+";
2496
+ var POSIX_SEGMENT_END = "(?:/|$|(?=[\\s\"'`]))";
2497
+ var WINDOWS_SEGMENT_END = "(?:\\\\+|$|(?=[\\s\"'`]))";
2498
+ var WINDOWS_USER_SEGMENT_BODY = "[^\\\\ \\t\\r\\n\"'`${}]+";
2499
+ var ABSOLUTE_PATH_BOUNDARY = "(?<![A-Za-z0-9_])";
2500
+ function escapePathPattern(value) {
2501
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2502
+ }
2503
+ function machineHomePathPatterns(flags) {
2504
+ const posix5 = `${ABSOLUTE_PATH_BOUNDARY}(?:${POSIX_HOME_ROOTS.map(escapePathPattern).join("|")})/${USER_SEGMENT_BODY}${POSIX_SEGMENT_END}`;
2505
+ const windows = `${ABSOLUTE_PATH_BOUNDARY}${escapePathPattern(WINDOWS_HOME_ROOT)}\\\\+${WINDOWS_USER_SEGMENT_BODY}${WINDOWS_SEGMENT_END}`;
2506
+ return [new RegExp(posix5, flags), new RegExp(windows, flags)];
2507
+ }
2489
2508
  var CealProtocolValidationError = class extends Error {
2490
2509
  name = "CealProtocolValidationError";
2491
2510
  code;
@@ -2846,6 +2865,7 @@ var CLIENT_HOST_RELEASE_MISMATCH = "Install or upgrade the Ceal CLI and Host Rel
2846
2865
  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.";
2847
2866
  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.";
2848
2867
  var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
2868
+ var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
2849
2869
  function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
2850
2870
  return Object.freeze({ message, next_action, http_status, retryable, redaction_class });
2851
2871
  }
@@ -2866,13 +2886,18 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2866
2886
  context_not_selected: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2867
2887
  context_store_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2868
2888
  context_store_conflict: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2869
- refresh_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2870
- refresh_expired: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2871
- refresh_replayed: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2872
- refresh_revoked: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2873
- person_inactive: guidance("The Person is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2874
- principal_inactive: guidance("The Principal is inactive, so the Gateway refused this refresh without revoking the Session family.", "ask_admin", 403),
2875
- refresh_recovery_unavailable: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2889
+ refresh_invalid: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2890
+ refresh_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2891
+ refresh_replayed: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2892
+ refresh_revoked: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
2893
+ 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),
2894
+ 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),
2895
+ 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),
2896
+ refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2897
+ 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),
2898
+ 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),
2899
+ refresh_state_unavailable: guidance("The Gateway session state store is temporarily unavailable; retry the same refresh attempt when it is available.", "retry", 503, true),
2900
+ refresh_recovery_expired: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
2876
2901
  refresh_custody_invalid: guidance(SESSION_CONTEXT_UNAVAILABLE, "repair_or_adopt_session", 401),
2877
2902
  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),
2878
2903
  local_output_exists: guidance("The selected local output path already exists; nothing was written to it.", "choose_new_output_path", 400),
@@ -2887,10 +2912,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2887
2912
  resource_stream_failed: guidance("The provider resource stream failed; ask an administrator to inspect the Gateway failure log.", "ask_admin", 500),
2888
2913
  gateway_unavailable: guidance(GATEWAY_TRANSPORT_UNAVAILABLE, "ask_admin", 503, true),
2889
2914
  contract_mismatch: guidance(CLIENT_HOST_RELEASE_MISMATCH, "upgrade_ceal_client", 409),
2890
- // `gateway_starting` is the one retryable envelope the serving gate answers on every route while starting
2891
- // (`cli/internal/client/gateway_startup_wait.go` re-drives it); the sentence is the client default that renders
2892
- // when the wait ends still unserved, moved from the `localFailureText` default branch.
2893
- [CEAL_GATEWAY_STARTING_FAILURE_CODE]: guidance(LOCAL_TRANSPORT_INCOMPLETE, "answer_with_gap", 503, true),
2915
+ // The serving gate answers before refresh execution, so retrying the same attempt is safe.
2916
+ [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),
2894
2917
  gateway_internal_error: guidance("The Gateway failed without exposing internal state; report this as a gap.", "answer_with_gap", 500),
2895
2918
  // The serving gate emits this code with no message; the sentence is the owner-normalized form of the
2896
2919
  // `gateway_internal_error` guidance (decided with the operator 2026-10-13).
@@ -2902,6 +2925,8 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
2902
2925
  // The safe move varies by request. Keep the sentence conditional on the
2903
2926
  // same `retryable` and `next_action` facts the response exposes.
2904
2927
  unknown_outcome: guidance("The transport outcome is unknown; use retryable and next_action to decide whether it can be repeated.", "answer_with_gap", 500),
2928
+ // 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.
2929
+ 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),
2905
2930
  // Restored verbatim from the retired `localFailureText`
2906
2931
  // `refresh_unknown_outcome` case: a refresh that ends unknown leaves the
2907
2932
  // session context unavailable, so the caller repairs or adopts the
@@ -3571,6 +3596,8 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3571
3596
  "review_submitted",
3572
3597
  "comment_created",
3573
3598
  "reaction_created",
3599
+ "pull_request_merged",
3600
+ "release_published",
3574
3601
  "ceal_write_completed",
3575
3602
  "event_start",
3576
3603
  "all_day_start",
@@ -3582,7 +3609,7 @@ var CEAL_ACTIVITY_TIMESTAMP_BASES = vocabulary([
3582
3609
  "page_last_edited",
3583
3610
  "resource_modified"
3584
3611
  ]);
3585
- var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "notion"]);
3612
+ var CEAL_ACTIVITY_CONNECTOR_KINDS = vocabulary(["slack", "github", "google-calendar", "google-drive", "google-mail", "notion"]);
3586
3613
  var CEAL_ACTIVITY_UNSUPPORTED_EVENT_KIND_CODE = "unsupported_event_kind";
3587
3614
  var CEAL_ACTIVITY_GAP_CODES = vocabulary([
3588
3615
  "provider_page_budget",
@@ -3603,6 +3630,8 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3603
3630
  "github.pull_request.opened",
3604
3631
  "github.issue.edited",
3605
3632
  "github.pull_request.edited",
3633
+ "github.pull_request.merged",
3634
+ "github.release.published",
3606
3635
  "github.review.submitted",
3607
3636
  "github.issue_comment.created",
3608
3637
  "github.review_comment.created",
@@ -3616,6 +3645,7 @@ var CEAL_ACTIVITY_EVENT_KINDS = vocabulary([
3616
3645
  "drive.file.created",
3617
3646
  "drive.file.modified",
3618
3647
  "drive.file.viewed",
3648
+ "mail.sent",
3619
3649
  "notion.page.created",
3620
3650
  "notion.page.edited"
3621
3651
  ]);
@@ -3629,6 +3659,8 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3629
3659
  "github.review_comment.created": "comment_created",
3630
3660
  "github.issue.opened": "resource_created",
3631
3661
  "github.pull_request.opened": "resource_created",
3662
+ "github.pull_request.merged": "pull_request_merged",
3663
+ "github.release.published": "release_published",
3632
3664
  "github.issue.edited": "resource_modified",
3633
3665
  "github.pull_request.edited": "resource_modified",
3634
3666
  "github.reaction.created": "reaction_created",
@@ -3639,6 +3671,7 @@ var CEAL_ACTIVITY_EVENT_TIMESTAMP_BASIS_MAP = Object.freeze({
3639
3671
  "drive.file.created": "file_created",
3640
3672
  "drive.file.modified": "file_modified_by_me",
3641
3673
  "drive.file.viewed": "file_viewed_by_me",
3674
+ "mail.sent": "message_created",
3642
3675
  "notion.page.created": "page_created",
3643
3676
  "notion.page.edited": "page_last_edited"
3644
3677
  });
@@ -3749,6 +3782,8 @@ var CEAL_REFRESH_FAILURE_CODES = vocabulary([
3749
3782
  "principal_inactive",
3750
3783
  "authority_replaced",
3751
3784
  "refresh_recovery_unavailable",
3785
+ "refresh_recovery_outcome_unavailable",
3786
+ "refresh_state_unavailable",
3752
3787
  "refresh_recovery_expired",
3753
3788
  // The serving gate answers this while the Gateway is still starting and the
3754
3789
  // refresh was never attempted; the same attempt stays retryable. It is never
@@ -4594,6 +4629,211 @@ var CEAL_SUPPORTED_GATEWAY_PROTOCOL_RANGE = Object.freeze({
4594
4629
  maximum: CEAL_PROTOCOL_VERSION
4595
4630
  });
4596
4631
 
4632
+ // packages/ceal-client-protocol/src/operator-diagnostic.ts
4633
+ var OPERATOR_DIAGNOSTIC_MAX_BYTES = 2048;
4634
+ var OPERATOR_DIAGNOSTIC_MAX_CAUSES = 8;
4635
+ var OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT = 512;
4636
+ var OPERATOR_DIAGNOSTIC_PATH_LIMIT = 1024;
4637
+ var OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT = 256;
4638
+ var OPERATOR_DIAGNOSTIC_HOME_PATHS = machineHomePathPatterns("gu");
4639
+ function redactOperatorDiagnosticSecrets(value) {
4640
+ 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]");
4641
+ }
4642
+ function redactOperatorDiagnosticText(value) {
4643
+ const normalized = normalizeCealSingleLineText(value);
4644
+ return normalizeCealSingleLineText(redactOperatorDiagnosticSecrets(redactFilePaths(redactHomePaths(redactUrls(normalized)))));
4645
+ }
4646
+ function renderOperatorDiagnostic(value) {
4647
+ const state = collectDiagnosticState(value);
4648
+ const fields = [
4649
+ state.status === void 0 ? void 0 : `status=${JSON.stringify(safeDiagnosticText(state.status))}`,
4650
+ state.exitCode === void 0 ? void 0 : `exit_code=${state.exitCode}`,
4651
+ state.stdout === void 0 ? void 0 : `stdout_tail=${JSON.stringify(tail(state.stdout))}`,
4652
+ state.stderr === void 0 ? void 0 : `stderr_tail=${JSON.stringify(tail(state.stderr))}`,
4653
+ state.causes.length === 0 ? void 0 : `causes=${state.causes.map(formatCause).join(" <- ")}`
4654
+ ].filter((field) => field !== void 0);
4655
+ const rendered = fields.length === 0 ? "unknown_failure" : fields.join(" ");
4656
+ return truncateUtf8(rendered, OPERATOR_DIAGNOSTIC_MAX_BYTES);
4657
+ }
4658
+ function collectDiagnosticState(value) {
4659
+ const state = { causes: [], status: void 0, exitCode: void 0, stdout: void 0, stderr: void 0 };
4660
+ const visited = /* @__PURE__ */ new Set(), pending = [value];
4661
+ while (pending.length > 0 && state.causes.length < OPERATOR_DIAGNOSTIC_MAX_CAUSES) {
4662
+ const current = pending.shift();
4663
+ if (current !== void 0) visitDiagnosticNode(current, state, pending, visited);
4664
+ }
4665
+ return state;
4666
+ }
4667
+ function visitDiagnosticNode(current, state, pending, visited) {
4668
+ if (isObject(current)) {
4669
+ if (visited.has(current)) return;
4670
+ visited.add(current);
4671
+ }
4672
+ captureProcessEvidence(current, state);
4673
+ appendCause(current, state.causes);
4674
+ enqueueCauseChildren(current, state.causes.length, pending);
4675
+ }
4676
+ function captureProcessEvidence(current, state) {
4677
+ if (state.status === void 0) state.status = safeStatus(read(current, "status"));
4678
+ if (state.exitCode === void 0) state.exitCode = safeExitCode(read(current, "exitCode")) ?? safeExitCode(read(current, "status")) ?? safeExitCode(read(current, "code"));
4679
+ if (state.stdout === void 0) state.stdout = outputText(read(current, "stdout"));
4680
+ if (state.stderr === void 0) state.stderr = outputText(read(current, "stderr"));
4681
+ }
4682
+ function appendCause(current, causes) {
4683
+ const errors = read(current, "errors");
4684
+ if (current instanceof Error && (!(current instanceof AggregateError) || !Array.isArray(errors) || errors.length === 0)) {
4685
+ causes.push(errorCause(current));
4686
+ return;
4687
+ }
4688
+ if (!isObject(current)) {
4689
+ const message = safeText(current);
4690
+ if (message !== void 0) causes.push(Object.freeze({ error_class: typeof current, message }));
4691
+ }
4692
+ }
4693
+ function errorCause(error) {
4694
+ const name = safeText(read(error, "name")) ?? "Error";
4695
+ const message = safeText(read(error, "message"));
4696
+ const codeValue = read(error, "code");
4697
+ const code = typeof codeValue === "number" && Number.isFinite(codeValue) ? codeValue : safeText(codeValue);
4698
+ const errnoValue = read(error, "errno");
4699
+ const errno = typeof errnoValue === "number" && Number.isSafeInteger(errnoValue) ? errnoValue : void 0;
4700
+ const syscall = safeText(read(error, "syscall"));
4701
+ const path = safePath(read(error, "path"));
4702
+ 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 } });
4703
+ }
4704
+ function enqueueCauseChildren(current, causeCount, pending) {
4705
+ const cause = read(current, "cause");
4706
+ if (cause !== void 0) pending.push(cause);
4707
+ const errors = read(current, "errors");
4708
+ if (Array.isArray(errors)) pending.push(...errors.slice(0, OPERATOR_DIAGNOSTIC_MAX_CAUSES - causeCount));
4709
+ }
4710
+ function isObject(value) {
4711
+ return typeof value === "object" && value !== null;
4712
+ }
4713
+ function formatCause(cause) {
4714
+ const fields = [
4715
+ cause.error_class,
4716
+ cause.code === void 0 ? void 0 : `code=${JSON.stringify(safeDiagnosticText(cause.code))}`,
4717
+ cause.errno === void 0 ? void 0 : `errno=${cause.errno}`,
4718
+ cause.syscall === void 0 ? void 0 : `syscall=${JSON.stringify(cause.syscall)}`,
4719
+ cause.path === void 0 ? void 0 : `path=${JSON.stringify(cause.path)}`,
4720
+ cause.message === void 0 ? void 0 : `message=${cause.message}`
4721
+ ].filter((field) => field !== void 0);
4722
+ return fields.join(" ");
4723
+ }
4724
+ function tail(value) {
4725
+ const clipped = value.length <= OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT ? value : `…${value.slice(-OPERATOR_DIAGNOSTIC_STREAM_TAIL_LIMIT)}`;
4726
+ return safeDiagnosticText(clipped);
4727
+ }
4728
+ function safeText(value) {
4729
+ if (typeof value !== "string") return void 0;
4730
+ const safe = safeDiagnosticText(value);
4731
+ if (safe.length === 0) return void 0;
4732
+ if (safe.length <= OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT) return safe;
4733
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT / 2);
4734
+ const tail2 = OPERATOR_DIAGNOSTIC_CAUSE_MESSAGE_LIMIT - head - 1;
4735
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4736
+ }
4737
+ function safePath(value) {
4738
+ if (typeof value !== "string") return void 0;
4739
+ const safe = safeDiagnosticText(value);
4740
+ if (safe.length === 0) return void 0;
4741
+ if (safe.length <= OPERATOR_DIAGNOSTIC_PATH_LIMIT) return safe;
4742
+ const head = Math.floor(OPERATOR_DIAGNOSTIC_PATH_LIMIT / 2);
4743
+ const tail2 = OPERATOR_DIAGNOSTIC_PATH_LIMIT - head - 1;
4744
+ return `${safe.slice(0, head)}…${safe.slice(-tail2)}`;
4745
+ }
4746
+ function safeDiagnosticText(value) {
4747
+ return redactOperatorDiagnosticText(String(value));
4748
+ }
4749
+ function outputText(value) {
4750
+ if (typeof value === "string") return redactOperatorDiagnosticText(value);
4751
+ if (value instanceof Uint8Array) {
4752
+ try {
4753
+ return redactOperatorDiagnosticText(new TextDecoder().decode(value));
4754
+ } catch {
4755
+ return void 0;
4756
+ }
4757
+ }
4758
+ return void 0;
4759
+ }
4760
+ function safeStatus(value) {
4761
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4762
+ return typeof value === "string" ? safeText(value) : void 0;
4763
+ }
4764
+ function safeExitCode(value) {
4765
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : void 0;
4766
+ }
4767
+ function read(value, key) {
4768
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return void 0;
4769
+ try {
4770
+ return Reflect.get(value, key);
4771
+ } catch {
4772
+ return void 0;
4773
+ }
4774
+ }
4775
+ function redactHomePaths(value) {
4776
+ const paths = [
4777
+ ...OPERATOR_DIAGNOSTIC_HOME_PATHS.flatMap((pattern) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, matchedHomePrefixLength(match[0])))),
4778
+ ...configuredHomePathPatterns().flatMap(({ pattern, prefixLength }) => [...value.matchAll(pattern)].map((match) => homePathRange(value, match, prefixLength)))
4779
+ ];
4780
+ paths.sort((left, right) => left.start - right.start || right.end - left.end);
4781
+ let output = "";
4782
+ let cursor = 0;
4783
+ for (const path of paths) {
4784
+ if (path.start < cursor) continue;
4785
+ output += `${value.slice(cursor, path.start)}[home path redacted]${value.slice(path.prefixEnd, path.end)}`;
4786
+ cursor = path.end;
4787
+ }
4788
+ return output + value.slice(cursor);
4789
+ }
4790
+ function configuredHomePathPatterns() {
4791
+ const homes = [...new Set([process.env.HOME, process.env.USERPROFILE].filter((home) => home !== void 0 && home.length > 0))];
4792
+ return homes.flatMap((home) => {
4793
+ const root = home.replace(/[\\/]+$/gu, "");
4794
+ if (root.length === 0 || root === "/" || /^[A-Za-z]:$/u.test(root)) return [];
4795
+ const pattern = new RegExp(`(?<![A-Za-z0-9_])${escapePathPattern(root)}(?=$|[\\\\/\\s"'\`<>(){}\\[\\],;])`, /^[A-Za-z]:[\\/]/u.test(root) ? "giu" : "gu");
4796
+ return [{ pattern, prefixLength: root.length }];
4797
+ });
4798
+ }
4799
+ function matchedHomePrefixLength(value) {
4800
+ let separators = 0;
4801
+ for (let index = 0; index < value.length; index += 1) {
4802
+ if (value[index] !== "/" && value[index] !== "\\") continue;
4803
+ separators += 1;
4804
+ if (separators === 3) return index;
4805
+ }
4806
+ return value.length;
4807
+ }
4808
+ function redactUrls(value) {
4809
+ return value.replaceAll(/https?:\/\/[^\s"'<>]+/giu, "[url redacted]");
4810
+ }
4811
+ function redactFilePaths(value) {
4812
+ return value.replaceAll(/(?<![A-Za-z0-9._-]|\[home path redacted\])(?:[A-Za-z]:[\\/]|\\\\[^\\\s]+\\|\/)[^:\r\n"'<>]*?(?=:\d+(?::\d+)?(?:[:\s]|$)|[\r\n]|["'])/gu, "[path redacted]");
4813
+ }
4814
+ function homePathRange(value, match, prefixLength) {
4815
+ const index = match.index;
4816
+ if (index === void 0) return { start: value.length, end: value.length, prefixEnd: value.length };
4817
+ const start = index;
4818
+ let end = start + match[0].length;
4819
+ const quote = start > 0 && (value[start - 1] === "'" || value[start - 1] === '"') ? value[start - 1] : void 0;
4820
+ if (quote !== void 0) {
4821
+ const closing = value.indexOf(quote, end);
4822
+ if (closing >= 0) end = closing;
4823
+ }
4824
+ while (end < value.length && !/[\s"'`<>(){}[\],;]/u.test(value[end] ?? "")) end += 1;
4825
+ return { start, end, prefixEnd: Math.min(start + prefixLength, end) };
4826
+ }
4827
+ function truncateUtf8(value, maxBytes) {
4828
+ if (byteLength(value) <= maxBytes) return value;
4829
+ let output = "";
4830
+ for (const character of value) {
4831
+ if (byteLength(`${output}${character}…`) > maxBytes) break;
4832
+ output += character;
4833
+ }
4834
+ return `${output}…`;
4835
+ }
4836
+
4597
4837
  // packages/ceal-client-protocol/src/admin-projection-vocabulary.ts
4598
4838
  var ADMIN_PROJECTION_STATES = vocabulary(["ready", "empty", "partial", "unknown"]);
4599
4839
  var ADMIN_VIEW_KINDS = vocabulary(["request_detail", "resource_access_timeline", "weekly_usage"]);
@@ -4734,10 +4974,10 @@ function failureDetail(error) {
4734
4974
  function errorCode(error) {
4735
4975
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
4736
4976
  }
4737
- function hostClientProbe(result, read) {
4977
+ function hostClientProbe(result, read2) {
4738
4978
  if (result === null) return { kind: "unreachable" };
4739
4979
  if (result.exit_code !== 0) return { kind: "refused", exit_code: result.exit_code };
4740
- const value = read(result);
4980
+ const value = read2(result);
4741
4981
  return value === null ? { kind: "unreadable" } : { kind: "value", value };
4742
4982
  }
4743
4983
  function hostClientProbeRefusal(probe, subject) {
@@ -4869,7 +5109,7 @@ async function inspectExecutable(options, environment, component) {
4869
5109
  try {
4870
5110
  executable = await (options.resolve_executable ?? resolveCealExecutable)(options.executable ?? "ceal", environment);
4871
5111
  } catch (error) {
4872
- return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${refusalFact("error", error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
5112
+ return inspectedFailure("ceal_unavailable", `The ${component} Host cannot resolve an executable Ceal client from its current environment (${renderOperatorDiagnostic(error)}).`, `Install the intended Ceal client in the Host PATH, restart ${component}, and run this doctor again.`);
4873
5113
  }
4874
5114
  if (!validExpectations(options) || options.expected_sha256 !== void 0 && executable.sha256 !== options.expected_sha256) return inspectedFailure("ceal_identity_mismatch", `The Ceal executable visible to the ${component} Host does not match the intended candidate.`, `Install the exact candidate bytes, restart ${component}, and run this doctor with the expected identity.`);
4875
5115
  return { ok: true, value: executable };
@@ -5400,9 +5640,9 @@ function mergeHostInvocationHumanMessageWindow(existing, chronological) {
5400
5640
  }
5401
5641
  return boundCealHostInvocationHumanMessageWindow(newestFirst, existing?.truncated ?? false);
5402
5642
  }
5403
- async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations, readCursor, identity, decodeLine) {
5643
+ async function readRegisteredHostInvocationHumanMessageWindow(readRegistration, readCursor, identity, decodeLine) {
5404
5644
  try {
5405
- const registration = await findLiveHostInvocationRegistration(listRegistrations, identity);
5645
+ const registration = await findLiveHostInvocationRegistration(readRegistration, identity);
5406
5646
  const cursor = await readCursor(registration);
5407
5647
  assertUsableHostInvocationHumanMessageCursor(cursor, registration);
5408
5648
  return await readHostInvocationHumanMessageWindow(registration, cursor, (line) => decodeLine(line, registration, cursor));
@@ -5410,9 +5650,9 @@ async function readRegisteredHostInvocationHumanMessageWindow(listRegistrations,
5410
5650
  throw new TypeError("context_unavailable");
5411
5651
  }
5412
5652
  }
5413
- async function findLiveHostInvocationRegistration(listRegistrations, identity) {
5414
- const registration = (await listRegistrations()).find((candidate) => candidate.host_source_ref === identity.host_source_ref && candidate.host_session_ref === identity.host_session_ref && Date.parse(candidate.expires_at) > Date.now());
5415
- if (registration === void 0) throw new TypeError("context_unavailable");
5653
+ async function findLiveHostInvocationRegistration(readRegistration, identity) {
5654
+ const registration = await readRegistration(identity);
5655
+ if (registration === null || registration.host_source_ref !== identity.host_source_ref || registration.host_session_ref !== identity.host_session_ref || !(Date.parse(registration.expires_at) > Date.now())) throw new TypeError("context_unavailable");
5416
5656
  return registration;
5417
5657
  }
5418
5658
  function assertUsableHostInvocationHumanMessageCursor(cursor, registration) {
@@ -5479,9 +5719,9 @@ async function readTranscriptCompleteChunk(handle, offset, size) {
5479
5719
  let lastNewline = -1;
5480
5720
  while (position < size) {
5481
5721
  const buffer = Buffer.alloc(Math.min(HOST_TRANSCRIPT_READ_CHUNK_BYTES, size - position));
5482
- const read = await handle.read(buffer, 0, buffer.length, position);
5483
- if (read.bytesRead === 0) break;
5484
- const chunk = buffer.subarray(0, read.bytesRead);
5722
+ const read2 = await handle.read(buffer, 0, buffer.length, position);
5723
+ if (read2.bytesRead === 0) break;
5724
+ const chunk = buffer.subarray(0, read2.bytesRead);
5485
5725
  chunks.push(chunk);
5486
5726
  const newline = chunk.lastIndexOf(10);
5487
5727
  if (newline >= 0) lastNewline = total + newline;
@@ -5654,15 +5894,15 @@ var HostProducerDrainCore = class {
5654
5894
  return run;
5655
5895
  }
5656
5896
  async drainLocked() {
5657
- const read = await this.host.listEnvelopes();
5897
+ const read2 = await this.host.listEnvelopes();
5658
5898
  let removed = 0;
5659
5899
  let expired = 0;
5660
- for (const envelope of read.entries) {
5900
+ for (const envelope of read2.entries) {
5661
5901
  if (Date.parse(this.host.expiresAtOf(envelope)) <= this.now().getTime()) expired += 1;
5662
5902
  else removed += 1;
5663
5903
  await this.host.removeEnvelope(envelope);
5664
5904
  }
5665
- return { removed, expired, malformed: read.malformed };
5905
+ return { removed, expired, malformed: read2.malformed };
5666
5906
  }
5667
5907
  };
5668
5908
 
@@ -6112,14 +6352,14 @@ var HostUsageFactsStore = class {
6112
6352
  const gate = new Promise((resolve) => {
6113
6353
  release = resolve;
6114
6354
  });
6115
- const tail = previous.then(() => gate);
6116
- SESSION_TRANSITION_TAILS.set(key, tail);
6355
+ const tail2 = previous.then(() => gate);
6356
+ SESSION_TRANSITION_TAILS.set(key, tail2);
6117
6357
  await previous;
6118
6358
  try {
6119
6359
  return await run();
6120
6360
  } finally {
6121
6361
  release?.();
6122
- if (SESSION_TRANSITION_TAILS.get(key) === tail) SESSION_TRANSITION_TAILS.delete(key);
6362
+ if (SESSION_TRANSITION_TAILS.get(key) === tail2) SESSION_TRANSITION_TAILS.delete(key);
6123
6363
  }
6124
6364
  }
6125
6365
  sessionPath(producer, hostSourceRef, hostSessionRef) {
@@ -6380,29 +6620,46 @@ var HostUsageTranscriptSourceError = class extends Error {
6380
6620
  this.name = "HostUsageTranscriptSourceError";
6381
6621
  }
6382
6622
  };
6383
- async function readHostUsageTranscriptSource(read) {
6623
+ async function readHostUsageTranscriptSource(read2) {
6384
6624
  try {
6385
- return await read();
6625
+ return await read2();
6386
6626
  } catch (error) {
6387
6627
  throw new HostUsageTranscriptSourceError({ cause: error });
6388
6628
  }
6389
6629
  }
6390
- async function captureNextHostUsageRegistration(registrations, startIndex, capture) {
6391
- if (registrations.length === 0) return { captured: false, nextIndex: startIndex, failed: false };
6392
- let failed = false;
6393
- for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6394
- const index = (startIndex + attempt) % registrations.length;
6395
- const registration = registrations[index];
6396
- if (registration === void 0) continue;
6397
- try {
6398
- if (await capture(registration)) return { captured: true, nextIndex: (index + 1) % registrations.length, failed };
6399
- } catch (error) {
6400
- if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6630
+ var HostUsageRegistrationCapture = class {
6631
+ nextIndex = 0;
6632
+ producer;
6633
+ diagnosticSink;
6634
+ constructor(producer, diagnosticSink) {
6635
+ this.producer = producer;
6636
+ this.diagnosticSink = diagnosticSink;
6637
+ }
6638
+ async captureNext(registrations, capture) {
6639
+ let failed = false;
6640
+ let captured = false;
6641
+ const onFailure = () => {
6401
6642
  failed = true;
6643
+ };
6644
+ for (let attempt = 0; attempt < registrations.length; attempt += 1) {
6645
+ const index = (this.nextIndex + attempt) % registrations.length;
6646
+ const registration = registrations[index];
6647
+ if (registration === void 0) continue;
6648
+ try {
6649
+ captured = await capture(registration, onFailure);
6650
+ if (captured) {
6651
+ this.nextIndex = (index + 1) % registrations.length;
6652
+ break;
6653
+ }
6654
+ } catch (error) {
6655
+ if (!(error instanceof HostUsageTranscriptSourceError)) throw error;
6656
+ onFailure();
6657
+ }
6402
6658
  }
6659
+ if (failed) writeHostServiceDiagnostic(this.producer, "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
6660
+ return captured;
6403
6661
  }
6404
- return { captured: false, nextIndex: startIndex, failed };
6405
- }
6662
+ };
6406
6663
  async function openHostUsageTranscriptCursor(input) {
6407
6664
  const handle = await readHostUsageTranscriptSource(() => openNoFollow(input.path, constants3.O_RDONLY));
6408
6665
  let source;
@@ -7658,7 +7915,7 @@ function parseCanonicalJson(text, error) {
7658
7915
  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) }])}`);
7659
7916
  return value;
7660
7917
  } catch (parseError) {
7661
- throw error("invalid_config", refusalFacts([{ name: "parse_error", value: parseError }, { name: "config_bytes", value: Buffer.byteLength(text, "utf8"), expected: "canonical JSON" }]));
7918
+ throw error("invalid_config", `parse_error=${renderOperatorDiagnostic(parseError)}; ${refusalFact("config_bytes", Buffer.byteLength(text, "utf8"), "canonical JSON")}`);
7662
7919
  }
7663
7920
  }
7664
7921
  function firstDifferenceIndex(left, right) {
@@ -8250,6 +8507,13 @@ var CodexOutboxStore = class {
8250
8507
  await removeOwnerState(this.registrationPath(registration.host_source_ref, registration.host_session_ref), "registration");
8251
8508
  await removeOwnerState(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "cursor");
8252
8509
  }
8510
+ async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
8511
+ const path = this.registrationPath(hostSourceRef, hostSessionRef);
8512
+ await this.prepare();
8513
+ const registration = await readOptionalJson2(path, validateRegistration);
8514
+ if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
8515
+ return registration;
8516
+ }
8253
8517
  async listTranscriptRegistrations() {
8254
8518
  await this.prepare();
8255
8519
  const registrations = [];
@@ -8276,16 +8540,16 @@ var CodexOutboxStore = class {
8276
8540
  }
8277
8541
  async findByAlias(sourceRef, sessionRef, alias) {
8278
8542
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef) || !SAFE_REF6.test(alias)) return null;
8279
- const read = await this.list();
8280
- const envelope = findEnvelopeByAlias(read.entries, sourceRef, sessionRef, alias);
8543
+ const read2 = await this.list();
8544
+ const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
8281
8545
  if (envelope !== null) return envelopeMatch(envelope);
8282
8546
  await this.prepare();
8283
8547
  return null;
8284
8548
  }
8285
8549
  async hasPriorTurn(sourceRef, sessionRef) {
8286
8550
  if (!SAFE_REF6.test(sourceRef) || !SAFE_REF6.test(sessionRef)) return false;
8287
- const read = await this.list();
8288
- if (read.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8551
+ const read2 = await this.list();
8552
+ if (read2.entries.some((entry) => entry.identity.host_source_ref === sourceRef && entry.identity.host_session_ref === sessionRef)) return true;
8289
8553
  return false;
8290
8554
  }
8291
8555
  entryPath(submissionRef) {
@@ -8341,7 +8605,7 @@ async function writeAtomicJson(path, value) {
8341
8605
  if (text === void 0) throw storageError("Codex owner state cannot be serialized.");
8342
8606
  const temp = `${path}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
8343
8607
  try {
8344
- const handle = await open5(temp, "wx");
8608
+ const handle = await open5(temp, "wx", 384);
8345
8609
  try {
8346
8610
  await handle.writeFile(text, "utf8");
8347
8611
  await handle.sync();
@@ -8383,13 +8647,20 @@ async function readOptionalJson2(path, validate) {
8383
8647
  }
8384
8648
  async function ensureOwnerDirectory(path) {
8385
8649
  try {
8386
- await stat3(path);
8650
+ try {
8651
+ const stats2 = await stat3(path);
8652
+ if (!stats2.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8653
+ return;
8654
+ } catch (error) {
8655
+ if (!isNotFound(error)) throw error;
8656
+ }
8657
+ await mkdir5(path, { recursive: true, mode: 448 });
8658
+ const stats = await stat3(path);
8659
+ if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8387
8660
  } catch (error) {
8388
- if (!isNotFound(error)) throw storageError("Codex owner state directory is unavailable.");
8389
- await mkdir5(path, { recursive: true });
8661
+ if (error instanceof CodexHostAdapterError) throw error;
8662
+ throw storageError("Codex owner state directory is unavailable.");
8390
8663
  }
8391
- const stats = await stat3(path);
8392
- if (!stats.isDirectory()) throw storageError("Codex owner state path is not a directory.");
8393
8664
  }
8394
8665
  async function readOwnerStateFile(path) {
8395
8666
  let handle;
@@ -8940,20 +9211,16 @@ var CodexUsageFactsCapturer = class {
8940
9211
  sources;
8941
9212
  usage;
8942
9213
  now;
8943
- diagnosticSink;
8944
- nextRegistrationIndex = 0;
9214
+ registrations;
8945
9215
  constructor(options) {
8946
9216
  this.sources = new CodexOutboxStore(options.outbox_dir);
8947
9217
  this.usage = new HostUsageFactsStore({ outbox_dir: options.outbox_dir, ...options.store_options });
8948
9218
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
8949
- this.diagnosticSink = options.diagnostic_sink;
9219
+ this.registrations = new HostUsageRegistrationCapture("codex", options.diagnostic_sink);
8950
9220
  }
8951
9221
  async captureNext() {
8952
9222
  const registrations = await this.sources.listTranscriptRegistrations();
8953
- const result = await captureNextHostUsageRegistration(registrations, this.nextRegistrationIndex, (registration) => this.captureRegistration(registration));
8954
- this.nextRegistrationIndex = result.nextIndex;
8955
- if (result.failed) writeHostServiceDiagnostic("codex", "usage_capture_failed", void 0, "capture_failed", this.diagnosticSink);
8956
- return result.captured;
9223
+ return await this.registrations.captureNext(registrations, (registration) => this.captureRegistration(registration));
8957
9224
  }
8958
9225
  async captureRegistration(registration) {
8959
9226
  const prepared = await openHostUsageTranscriptCursor({
@@ -9234,7 +9501,7 @@ function runCodexInvocationAuthenticationCommand(args, options) {
9234
9501
  }
9235
9502
  async function readCodexInvocationHumanMessageWindow(input) {
9236
9503
  let lastOrdinal;
9237
- return readRegisteredHostInvocationHumanMessageWindow(() => input.store.listTranscriptRegistrations(), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration, cursor) => {
9504
+ return readRegisteredHostInvocationHumanMessageWindow((identity) => input.store.readTranscriptRegistration(identity.host_source_ref, identity.host_session_ref), (registration) => input.store.readTranscriptCursor(registration), input.identity, (line, registration, cursor) => {
9238
9505
  let record3;
9239
9506
  try {
9240
9507
  record3 = decodeCodexTranscriptLine(line);