@corca-org/ceal-host-win32-x64 1.0.24 → 1.0.25
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.
- package/README.md +2 -2
- package/bin/ceal-host.exe +0 -0
- package/libexec/ceal-host/ceal-host-background.exe +0 -0
- package/libexec/ceal-host/claude-hook.mjs +183 -77
- package/libexec/ceal-host/claude-invocation-authentication.mjs +322 -100
- package/libexec/ceal-host/claude-producer.mjs +175 -69
- package/libexec/ceal-host/codex-hook.mjs +170 -64
- package/libexec/ceal-host/codex-invocation-authentication.mjs +307 -85
- package/libexec/ceal-host/codex-producer.mjs +164 -58
- package/libexec/ceal-host/control.mjs +563 -210
- package/libexec/ceal-host/relay.mjs +115 -29
- package/package.json +1 -1
- package/share/ceal-host/bundle-manifest.json +13 -13
- package/share/ceal-host/bundle-manifest.sigstore.json +1 -1
|
@@ -2396,6 +2396,12 @@ var CALLER_RECOVERABLE_NEXT_ACTION_VALUES = [
|
|
|
2396
2396
|
// (never connected, revoked, or expired). The caller runs that exact
|
|
2397
2397
|
// Operation, completes the consent it hands back, and retries the same call.
|
|
2398
2398
|
"connect_personal_account",
|
|
2399
|
+
// The refusal names the caller's own preferences update step: the read
|
|
2400
|
+
// needs a personal connection the caller holds but has not selected in
|
|
2401
|
+
// Ceal preferences, or has not confirmed through the initial review. The
|
|
2402
|
+
// caller reads personal.preferences.get, runs personal.preferences.update
|
|
2403
|
+
// at the current revision to select it, and retries the same call.
|
|
2404
|
+
"update_personal_preferences",
|
|
2399
2405
|
// The provider or Gateway named a bounded wait; the caller waits that long
|
|
2400
2406
|
// and submits the same read again.
|
|
2401
2407
|
"retry_after",
|
|
@@ -2945,9 +2951,11 @@ var LOCAL_COMMAND_INVALID = "The local command or argument is invalid.";
|
|
|
2945
2951
|
var LOCAL_TRANSPORT_INCOMPLETE = "The local Ceal transport could not complete; report this as a gap.";
|
|
2946
2952
|
var GATEWAY_TRANSPORT_UNAVAILABLE = "The Gateway transport is unavailable; ask an administrator to restore Gateway availability.";
|
|
2947
2953
|
var HOST_AUTHENTICATION_UNAVAILABLE = "The Host could not authenticate this invocation; report this as a gap.";
|
|
2948
|
-
var
|
|
2954
|
+
var CEAL_CLIENT_UPGRADE_COMMAND = "npm install -g @corca-org/ceal";
|
|
2955
|
+
var CLIENT_HOST_RELEASE_MISMATCH = `Install or upgrade the Ceal CLI and Host Relay to the same release as the Gateway, then retry. Update with \`${CEAL_CLIENT_UPGRADE_COMMAND}\`.`;
|
|
2949
2956
|
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.";
|
|
2950
|
-
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn;
|
|
2957
|
+
var HOST_CONTEXT_UNAVAILABLE = "The Host could not select this turn right now; the Host may be restarting. Wait briefly and retry the same command. If you know you are in an ephemeral side conversation, `ceal --standalone ...` uses your configured Ceal session/Gateway permissions without Host session/turn correlation. Otherwise return to the original regular conversation. Host refusal never switches modes. If the retry still fails, report intended Host calls as a gap.";
|
|
2958
|
+
var HOST_RELAY_RESTARTING = "The Host Relay is temporarily unavailable while the Host restarts; wait briefly and retry the same command. If the retry still fails, report this as a gap.";
|
|
2951
2959
|
var SESSION_CONTEXT_UNAVAILABLE = "The local Gateway session context is unavailable.";
|
|
2952
2960
|
var SESSION_ADOPT_RECOVERY = "The refresh Session is no longer usable. Run `ceal session adopt --gateway <origin> --email <email>` to complete mailbox-confirmed recovery.";
|
|
2953
2961
|
function guidance(message, next_action, http_status, retryable = false, redaction_class = "model_safe") {
|
|
@@ -2977,6 +2985,9 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
2977
2985
|
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),
|
|
2978
2986
|
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),
|
|
2979
2987
|
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),
|
|
2988
|
+
// A stored session that predates the authority-epoch commitment carries no
|
|
2989
|
+
// epoch to compare, so it can never refresh: adopt a fresh session instead.
|
|
2990
|
+
authority_epoch_unknown: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 401),
|
|
2980
2991
|
refresh_inactive: guidance(SESSION_ADOPT_RECOVERY, "repair_or_adopt_session", 410),
|
|
2981
2992
|
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),
|
|
2982
2993
|
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),
|
|
@@ -3101,7 +3112,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
3101
3112
|
host_session_unavailable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 401),
|
|
3102
3113
|
// The bounded Host reason does not prove ephemerality. A Host refusal never
|
|
3103
3114
|
// changes mode; standalone remains the separate Client authority path.
|
|
3104
|
-
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "
|
|
3115
|
+
host_context_unavailable: guidance(HOST_CONTEXT_UNAVAILABLE, "retry", 401, true),
|
|
3105
3116
|
host_context_activation_wait_exhausted: guidance("The Host selected this turn, but its invocation context did not activate before the bounded wait ended. Wait for the supplied retry_after_ms value, then retry the same command.", "retry_after", 401, true),
|
|
3106
3117
|
host_invocation_context_stale: guidance("The Host turn changed while this invocation was authenticating. Its command cannot be rebound safely; report this invocation as a gap.", "answer_with_gap", 401),
|
|
3107
3118
|
host_invocation_context_expired: guidance("The Host invocation context expired before authentication completed. This invocation cannot be retried in the expired turn; report it as a gap.", "answer_with_gap", 401),
|
|
@@ -3118,7 +3129,7 @@ var CEAL_FAILURE_GUIDANCE_TABLE = Object.freeze({
|
|
|
3118
3129
|
// Moved from the retired `CEAL_HOST_AUTHENTICATION_POLICY` remedy: the
|
|
3119
3130
|
// sandboxed Relay socket names the run-alone retry.
|
|
3120
3131
|
host_relay_permission_denied: guidance("An agent sandbox denied the Host Relay socket; run `ceal` as the only command, with no pipe, redirect, or `&&`, so the Host allow rule runs it outside the sandbox.", "rerun_outside_agent_sandbox", 403),
|
|
3121
|
-
host_relay_unavailable: guidance(
|
|
3132
|
+
host_relay_unavailable: guidance(HOST_RELAY_RESTARTING, "retry", 503, true),
|
|
3122
3133
|
host_mint_transient_retryable: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "retry", 503, true),
|
|
3123
3134
|
host_mint_failed: guidance(HOST_AUTHENTICATION_UNAVAILABLE, "answer_with_gap", 500),
|
|
3124
3135
|
host_relay_failed: guidance(HOST_INSTALL_REPAIR, "install_ceal_host", 502),
|
|
@@ -3366,7 +3377,7 @@ var CEAL_OPERATION_JSON_SCHEMA_BUDGET = Object.freeze({
|
|
|
3366
3377
|
max_literal_nodes: 512
|
|
3367
3378
|
});
|
|
3368
3379
|
|
|
3369
|
-
// packages/ceal-client-protocol/src/operation-json-schema.ts
|
|
3380
|
+
// packages/ceal-client-protocol/src/operation-json-schema-leaf-validators.ts
|
|
3370
3381
|
var JSON_DESCRIPTION_CONTROL_CHARACTER = new RegExp("\\p{Cc}", "u");
|
|
3371
3382
|
|
|
3372
3383
|
// packages/ceal-client-protocol/src/operation-contract-validation.ts
|
|
@@ -3517,7 +3528,8 @@ var CEAL_OPERATION_ID_PLACEHOLDER = "<operation-id>";
|
|
|
3517
3528
|
var CEAL_OPERATION_INPUT_PLACEHOLDER = "<json-object>";
|
|
3518
3529
|
var MODEL_INVOCATION_BASE_ARGUMENTS = [CEAL_OPERATION_INVOKE_COMMAND, CEAL_OPERATION_ID_PLACEHOLDER].join(" ");
|
|
3519
3530
|
var CEAL_MODEL_INVOCATION_ARGUMENTS = [MODEL_INVOCATION_BASE_ARGUMENTS, CEAL_OPERATION_INPUT_FLAG, shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)].join(" ");
|
|
3520
|
-
var
|
|
3531
|
+
var CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE = `For caller-owned fields, add ${CEAL_OPERATION_INPUT_FLAG} ${shellSingleQuoted(CEAL_OPERATION_INPUT_PLACEHOLDER)}. Use inline JSON for short input; for longer or generated input, put exactly one JSON object in a caller-owned regular non-symlink UTF-8 JSON file and pass --input @path; relative paths resolve from the command working directory.`;
|
|
3532
|
+
var CEAL_MODEL_INPUT_SOURCE_GUIDANCE = `${CEAL_MODEL_INPUT_SOURCE_BASE_GUIDANCE} On Windows, write the JSON file first; use the program's .cmd launcher with --input and only one quoted @path argument.`;
|
|
3521
3533
|
function shellSingleQuoted(value) {
|
|
3522
3534
|
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
3523
3535
|
}
|
|
@@ -4505,9 +4517,11 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
4505
4517
|
invalid_arguments: Object.freeze({ classification: "host_arguments_invalid", next_action: "answer_with_gap" }),
|
|
4506
4518
|
options_invalid: Object.freeze({ classification: "host_configuration_invalid", next_action: "answer_with_gap" }),
|
|
4507
4519
|
session_unavailable: Object.freeze({ classification: "host_session_unavailable", next_action: "answer_with_gap" }),
|
|
4508
|
-
//
|
|
4509
|
-
//
|
|
4510
|
-
|
|
4520
|
+
// A missing turn right after a Host restart clears by itself once the
|
|
4521
|
+
// watcher reactivates the turn, so the caller waits briefly and retries;
|
|
4522
|
+
// a caller that knows it is in an ephemeral side conversation keeps the
|
|
4523
|
+
// standalone fallback the guidance names second.
|
|
4524
|
+
context_unavailable: Object.freeze({ classification: "host_context_unavailable", next_action: "retry" }),
|
|
4511
4525
|
activation_wait_exhausted: Object.freeze({ classification: "host_context_activation_wait_exhausted", next_action: "retry_after" }),
|
|
4512
4526
|
context_replaced: Object.freeze({ classification: "host_invocation_context_stale", next_action: "answer_with_gap" }),
|
|
4513
4527
|
// `no_binding` now means the producer has no real current Host session. The
|
|
@@ -4524,7 +4538,7 @@ var CEAL_HOST_AUTHENTICATION_POLICY = Object.freeze({
|
|
|
4524
4538
|
gateway_response_invalid: Object.freeze({ classification: "host_mint_gateway_response_invalid", next_action: "answer_with_gap" }),
|
|
4525
4539
|
producer_frame_invalid: Object.freeze({ classification: "host_producer_frame_invalid", next_action: "ask_admin" }),
|
|
4526
4540
|
relay_permission_denied: Object.freeze({ classification: "host_relay_permission_denied", next_action: "rerun_outside_agent_sandbox" }),
|
|
4527
|
-
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "
|
|
4541
|
+
relay_unavailable: Object.freeze({ classification: "host_relay_unavailable", next_action: "retry" }),
|
|
4528
4542
|
transient_retryable: Object.freeze({ classification: "host_mint_transient_retryable", next_action: "retry" }),
|
|
4529
4543
|
mint_failed: Object.freeze({ classification: "host_mint_failed", next_action: "answer_with_gap" }),
|
|
4530
4544
|
relay_failed: Object.freeze({ classification: "host_relay_failed", next_action: "install_ceal_host" }),
|
|
@@ -5104,8 +5118,80 @@ import { execFile } from "node:child_process";
|
|
|
5104
5118
|
import { createHash as createHash5 } from "node:crypto";
|
|
5105
5119
|
import { constants } from "node:fs";
|
|
5106
5120
|
import { lstat as lstat3, open } from "node:fs/promises";
|
|
5107
|
-
import { dirname as dirname2, join as
|
|
5121
|
+
import { dirname as dirname2, join as join3, win32 as win324 } from "node:path";
|
|
5108
5122
|
import { fileURLToPath } from "node:url";
|
|
5123
|
+
|
|
5124
|
+
// host/spawn-working-directory.ts
|
|
5125
|
+
import { mkdirSync } from "node:fs";
|
|
5126
|
+
import { tmpdir } from "node:os";
|
|
5127
|
+
import { isAbsolute, join as join2, normalize, parse, sep } from "node:path";
|
|
5128
|
+
function resolveCealSpawnWorkingDirectory(stateRoot, keepOutside = []) {
|
|
5129
|
+
const candidates = [];
|
|
5130
|
+
const explicit = candidateDir(stateRoot);
|
|
5131
|
+
if (explicit !== void 0) candidates.push(explicit);
|
|
5132
|
+
const fallback = defaultHostStateRoot();
|
|
5133
|
+
if (fallback !== void 0 && !candidates.some((candidate) => sameDir(candidate, fallback))) candidates.push(fallback);
|
|
5134
|
+
const temporary = candidateDir(join2(tmpdir(), "ceal-spawn-cwd"));
|
|
5135
|
+
if (temporary !== void 0 && !candidates.some((candidate) => sameDir(candidate, temporary))) candidates.push(temporary);
|
|
5136
|
+
for (const dir of candidates) {
|
|
5137
|
+
if (!keptOutside(dir, keepOutside)) continue;
|
|
5138
|
+
try {
|
|
5139
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
5140
|
+
return dir;
|
|
5141
|
+
} catch {
|
|
5142
|
+
continue;
|
|
5143
|
+
}
|
|
5144
|
+
}
|
|
5145
|
+
return tmpdir();
|
|
5146
|
+
}
|
|
5147
|
+
function candidateDir(dir) {
|
|
5148
|
+
if (dir === void 0 || dir === "") return void 0;
|
|
5149
|
+
if (!isAbsolute(dir) || normalize(dir) !== dir || parse(dir).root === dir) return void 0;
|
|
5150
|
+
return normalize(dir);
|
|
5151
|
+
}
|
|
5152
|
+
function defaultHostStateRoot() {
|
|
5153
|
+
if (process.platform === "win32") {
|
|
5154
|
+
const localAppData = nonEmptyEnv("LOCALAPPDATA");
|
|
5155
|
+
if (localAppData === void 0) return void 0;
|
|
5156
|
+
return candidateDir(join2(localAppData, "Ceal", "Host"));
|
|
5157
|
+
}
|
|
5158
|
+
if (process.platform === "darwin") {
|
|
5159
|
+
const home2 = nonEmptyEnv("HOME");
|
|
5160
|
+
if (home2 === void 0) return void 0;
|
|
5161
|
+
return candidateDir(join2(home2, "Library", "Application Support", "Ceal", "Host"));
|
|
5162
|
+
}
|
|
5163
|
+
const xdg = nonEmptyEnv("XDG_STATE_HOME");
|
|
5164
|
+
if (xdg !== void 0) {
|
|
5165
|
+
const root = candidateDir(join2(xdg, "ceal", "host"));
|
|
5166
|
+
if (root !== void 0) return root;
|
|
5167
|
+
}
|
|
5168
|
+
const home = nonEmptyEnv("HOME");
|
|
5169
|
+
if (home === void 0) return void 0;
|
|
5170
|
+
return candidateDir(join2(home, ".local", "state", "ceal", "host"));
|
|
5171
|
+
}
|
|
5172
|
+
function nonEmptyEnv(name) {
|
|
5173
|
+
const value = process.env[name];
|
|
5174
|
+
return value === void 0 || value === "" ? void 0 : value;
|
|
5175
|
+
}
|
|
5176
|
+
function keptOutside(dir, keepOutside) {
|
|
5177
|
+
for (const tree of keepOutside) {
|
|
5178
|
+
const clean = candidateDir(tree);
|
|
5179
|
+
if (clean === void 0) continue;
|
|
5180
|
+
if (insideDir(dir, clean)) return false;
|
|
5181
|
+
}
|
|
5182
|
+
return true;
|
|
5183
|
+
}
|
|
5184
|
+
function insideDir(dir, tree) {
|
|
5185
|
+
if (sameDir(dir, tree)) return true;
|
|
5186
|
+
if (process.platform === "win32") return dir.toLowerCase().startsWith(tree.toLowerCase() + sep);
|
|
5187
|
+
return dir.startsWith(tree + sep);
|
|
5188
|
+
}
|
|
5189
|
+
function sameDir(left, right) {
|
|
5190
|
+
if (process.platform === "win32") return left.toLowerCase() === right.toLowerCase();
|
|
5191
|
+
return left === right;
|
|
5192
|
+
}
|
|
5193
|
+
|
|
5194
|
+
// host/secure-file.ts
|
|
5109
5195
|
var SecureFileCustodyError = class extends Error {
|
|
5110
5196
|
name = "SecureFileCustodyError";
|
|
5111
5197
|
reason;
|
|
@@ -5236,7 +5322,7 @@ async function runSecurefsCommand(args, maxBytes, custody, stdin) {
|
|
|
5236
5322
|
const executable = custody.securefs_executable ?? resolveInstalledHostExecutable(process.platform);
|
|
5237
5323
|
const processArgs = [...custody.securefs_args_prefix ?? [], ...args];
|
|
5238
5324
|
return await new Promise((resolve, reject2) => {
|
|
5239
|
-
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES }, (error, stdout, stderr) => {
|
|
5325
|
+
const child = execFile(executable, processArgs, { encoding: "buffer", windowsHide: true, timeout: WINDOWS_SECUREFS_TIMEOUT_MS, maxBuffer: maxBytes + WINDOWS_SECUREFS_DIAGNOSTIC_BYTES, cwd: resolveCealSpawnWorkingDirectory() }, (error, stdout, stderr) => {
|
|
5240
5326
|
const exitCode = error === null ? 0 : typeof error.code === "number" ? error.code : null;
|
|
5241
5327
|
if (exitCode === null) {
|
|
5242
5328
|
reject2(new SecureFileCustodyError("unavailable", "The installed Windows Host securefs command could not run."));
|
|
@@ -5265,7 +5351,7 @@ function securefsRefusal(stderr) {
|
|
|
5265
5351
|
}
|
|
5266
5352
|
function resolveInstalledHostExecutable(platform) {
|
|
5267
5353
|
const privateRuntimeRoot = dirname2(fileURLToPath(import.meta.url));
|
|
5268
|
-
return platform === "win32" ? win324.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") :
|
|
5354
|
+
return platform === "win32" ? win324.join(privateRuntimeRoot, "..", "..", "bin", "ceal-host.exe") : join3(privateRuntimeRoot, "..", "..", "bin", "ceal-host");
|
|
5269
5355
|
}
|
|
5270
5356
|
function isRecord(value) {
|
|
5271
5357
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -5665,7 +5751,7 @@ import { setTimeout as delay2 } from "node:timers/promises";
|
|
|
5665
5751
|
import { createHash as createHash6 } from "node:crypto";
|
|
5666
5752
|
import { constants as constants4 } from "node:fs";
|
|
5667
5753
|
import { mkdir as mkdir3, open as open3, opendir as opendir2, unlink as unlink3 } from "node:fs/promises";
|
|
5668
|
-
import { dirname as dirname5, join as
|
|
5754
|
+
import { dirname as dirname5, join as join4 } from "node:path";
|
|
5669
5755
|
|
|
5670
5756
|
// host/relay/src/durable-atomic-replacement.ts
|
|
5671
5757
|
import { lstat as lstat5, mkdir as mkdir2, open as open2, rename, unlink as unlink2 } from "node:fs/promises";
|
|
@@ -5818,9 +5904,9 @@ var HostUsageFactsStore = class {
|
|
|
5818
5904
|
afterBatchPublish;
|
|
5819
5905
|
sessionDirectoryCursor;
|
|
5820
5906
|
constructor(options) {
|
|
5821
|
-
this.root =
|
|
5822
|
-
this.sessions =
|
|
5823
|
-
this.batches =
|
|
5907
|
+
this.root = join4(options.outbox_dir, "usage-facts");
|
|
5908
|
+
this.sessions = join4(this.root, "sessions");
|
|
5909
|
+
this.batches = join4(this.root, "batches");
|
|
5824
5910
|
this.platform = options.platform ?? process.platform;
|
|
5825
5911
|
this.custody = options.secure_file_custody ?? {};
|
|
5826
5912
|
this.afterPendingWrite = options.afterPendingWrite;
|
|
@@ -5837,7 +5923,6 @@ var HostUsageFactsStore = class {
|
|
|
5837
5923
|
await cursor?.close();
|
|
5838
5924
|
}
|
|
5839
5925
|
async readState(producer, hostSourceRef, hostSessionRef) {
|
|
5840
|
-
await this.prepare();
|
|
5841
5926
|
const path = this.sessionPath(producer, hostSourceRef, hostSessionRef);
|
|
5842
5927
|
const value = await readOptionalJson(path, HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
5843
5928
|
if (value === null) return null;
|
|
@@ -5895,11 +5980,15 @@ var HostUsageFactsStore = class {
|
|
|
5895
5980
|
}
|
|
5896
5981
|
/** Remove unreferenced local batch objects in bounded pieces after settling any exact pending transition. */
|
|
5897
5982
|
async sweepOrphanedBatches(state) {
|
|
5898
|
-
await this.prepare();
|
|
5899
5983
|
const directoryPath = this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref);
|
|
5900
|
-
await preparePrivateDirectory(directoryPath, this.platform, this.custody);
|
|
5901
5984
|
const expected = expectedBatchNames(state);
|
|
5902
|
-
|
|
5985
|
+
let directory;
|
|
5986
|
+
try {
|
|
5987
|
+
directory = await opendir2(directoryPath);
|
|
5988
|
+
} catch (error) {
|
|
5989
|
+
if (errorCode2(error) === "ENOENT") return 0;
|
|
5990
|
+
throw error;
|
|
5991
|
+
}
|
|
5903
5992
|
let inspected = 0;
|
|
5904
5993
|
let deleted = 0;
|
|
5905
5994
|
try {
|
|
@@ -5908,7 +5997,7 @@ var HostUsageFactsStore = class {
|
|
|
5908
5997
|
if (entry === null) break;
|
|
5909
5998
|
inspected += 1;
|
|
5910
5999
|
if (!isOrphanBatchEntry(entry, expected)) continue;
|
|
5911
|
-
await unlink3(
|
|
6000
|
+
await unlink3(join4(directoryPath, entry.name));
|
|
5912
6001
|
deleted += 1;
|
|
5913
6002
|
}
|
|
5914
6003
|
} finally {
|
|
@@ -5936,10 +6025,9 @@ var HostUsageFactsStore = class {
|
|
|
5936
6025
|
});
|
|
5937
6026
|
}
|
|
5938
6027
|
async nextUploadCandidate(producer, hostSourceRef) {
|
|
5939
|
-
await this.prepare();
|
|
5940
6028
|
const names = await this.readNextSessionNames();
|
|
5941
6029
|
for (const name of names) {
|
|
5942
|
-
const state = await readOptionalJson(
|
|
6030
|
+
const state = await readOptionalJson(join4(this.sessions, name), HOST_USAGE_FACTS_STATE_MAX_BYTES, this.platform, this.custody);
|
|
5943
6031
|
if (state === null) continue;
|
|
5944
6032
|
validateStateOwner(state, producer, hostSourceRef);
|
|
5945
6033
|
let validated = state;
|
|
@@ -5954,7 +6042,14 @@ var HostUsageFactsStore = class {
|
|
|
5954
6042
|
return null;
|
|
5955
6043
|
}
|
|
5956
6044
|
async readNextSessionNames() {
|
|
5957
|
-
this.sessionDirectoryCursor
|
|
6045
|
+
if (this.sessionDirectoryCursor === void 0) {
|
|
6046
|
+
try {
|
|
6047
|
+
this.sessionDirectoryCursor = await opendir2(this.sessions);
|
|
6048
|
+
} catch (error) {
|
|
6049
|
+
if (errorCode2(error) === "ENOENT") return [];
|
|
6050
|
+
throw error;
|
|
6051
|
+
}
|
|
6052
|
+
}
|
|
5958
6053
|
const names = [];
|
|
5959
6054
|
let inspected = 0;
|
|
5960
6055
|
while (inspected < HOST_USAGE_FACTS_UPLOAD_SCAN_SESSIONS) {
|
|
@@ -6120,14 +6215,14 @@ var HostUsageFactsStore = class {
|
|
|
6120
6215
|
}
|
|
6121
6216
|
}
|
|
6122
6217
|
sessionPath(producer, hostSourceRef, hostSessionRef) {
|
|
6123
|
-
return
|
|
6218
|
+
return join4(this.sessions, `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`);
|
|
6124
6219
|
}
|
|
6125
6220
|
batchSessionDirectory(producer, hostSourceRef, hostSessionRef) {
|
|
6126
6221
|
const sessionName = `${sha2563(JSON.stringify({ producer, host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }))}.json`;
|
|
6127
|
-
return
|
|
6222
|
+
return join4(this.batches, sessionName.slice(0, -5));
|
|
6128
6223
|
}
|
|
6129
6224
|
batchPath(state, batchRef) {
|
|
6130
|
-
return
|
|
6225
|
+
return join4(this.batchSessionDirectory(state.producer, state.host_source_ref, state.host_session_ref), batchFileName(batchRef));
|
|
6131
6226
|
}
|
|
6132
6227
|
};
|
|
6133
6228
|
function serializeBatch(batch) {
|
|
@@ -6369,7 +6464,7 @@ function sha2563(value) {
|
|
|
6369
6464
|
// host/service-log.ts
|
|
6370
6465
|
import { constants as constants5 } from "node:fs";
|
|
6371
6466
|
import { copyFile, mkdir as mkdir4, stat, truncate, appendFile } from "node:fs/promises";
|
|
6372
|
-
import { dirname as dirname6, isAbsolute, posix as posix5, win32 as win326 } from "node:path";
|
|
6467
|
+
import { dirname as dirname6, isAbsolute as isAbsolute2, posix as posix5, win32 as win326 } from "node:path";
|
|
6373
6468
|
|
|
6374
6469
|
// host/service-log-delivery.ts
|
|
6375
6470
|
var HOST_SERVICE_LOG_DELIVERY_SCHEMA = "ceal.host_service_log_delivery.v1";
|
|
@@ -6542,7 +6637,7 @@ async function persistHostServiceLogLine(line, environment = process.env) {
|
|
|
6542
6637
|
await appendHostServiceLogLine(path, line).catch(() => void 0);
|
|
6543
6638
|
}
|
|
6544
6639
|
async function appendHostServiceLogLine(path, line) {
|
|
6545
|
-
if (!
|
|
6640
|
+
if (!isAbsolute2(path)) return;
|
|
6546
6641
|
await ensureHostServiceLogDirectory(path);
|
|
6547
6642
|
await appendFile(path, line);
|
|
6548
6643
|
}
|
|
@@ -6605,6 +6700,10 @@ var HostUsageFactsUploader = class {
|
|
|
6605
6700
|
async close() {
|
|
6606
6701
|
await this.store.close();
|
|
6607
6702
|
}
|
|
6703
|
+
/** The start owner prepares the store once, so idle ticks below never re-prepare. */
|
|
6704
|
+
async prepare() {
|
|
6705
|
+
await this.store.prepare();
|
|
6706
|
+
}
|
|
6608
6707
|
async uploadOne(signal) {
|
|
6609
6708
|
const candidate = await this.store.nextUploadCandidate(this.options.producer, this.options.host_source_ref);
|
|
6610
6709
|
if (candidate === null) return false;
|
|
@@ -6627,6 +6726,11 @@ var HostUsageFactsUploader = class {
|
|
|
6627
6726
|
};
|
|
6628
6727
|
async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
6629
6728
|
const uploader = new HostUsageFactsUploader(options);
|
|
6729
|
+
try {
|
|
6730
|
+
await uploader.prepare();
|
|
6731
|
+
} catch {
|
|
6732
|
+
writeHostServiceDiagnostic(options.producer, "usage_upload_failed", void 0, "upload_failed");
|
|
6733
|
+
}
|
|
6630
6734
|
let delay3 = 500;
|
|
6631
6735
|
let failures = 0;
|
|
6632
6736
|
try {
|
|
@@ -6656,6 +6760,7 @@ async function runHostUsageFactsUploader(options, signal, wait = waitForAbort) {
|
|
|
6656
6760
|
|
|
6657
6761
|
// host/relay/src/host-producer-core.ts
|
|
6658
6762
|
import { createHash as createHash7 } from "node:crypto";
|
|
6763
|
+
import { readdir } from "node:fs/promises";
|
|
6659
6764
|
var HOST_TRANSCRIPT_CURSOR_REASONS = vocabulary(["transcript_replaced", "transcript_truncated", "transcript_rewritten", "transcript_malformed"]);
|
|
6660
6765
|
function isHostTranscriptCursorReason(value) {
|
|
6661
6766
|
return typeof value === "string" && HOST_TRANSCRIPT_CURSOR_REASONS.some((reason) => reason === value);
|
|
@@ -6861,6 +6966,14 @@ var HostTranscriptWatcher = class {
|
|
|
6861
6966
|
return transcriptCursorBoundsReason(handle, cursor, size);
|
|
6862
6967
|
}
|
|
6863
6968
|
};
|
|
6969
|
+
async function listHostOutboxDirectoryNames(directory) {
|
|
6970
|
+
try {
|
|
6971
|
+
return await readdir(directory);
|
|
6972
|
+
} catch (error) {
|
|
6973
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return [];
|
|
6974
|
+
throw error;
|
|
6975
|
+
}
|
|
6976
|
+
}
|
|
6864
6977
|
var HostProducerDrainCore = class {
|
|
6865
6978
|
host;
|
|
6866
6979
|
now;
|
|
@@ -6888,8 +7001,8 @@ var HostProducerDrainCore = class {
|
|
|
6888
7001
|
};
|
|
6889
7002
|
|
|
6890
7003
|
// host/claude/src/claude-outbox.ts
|
|
6891
|
-
import { mkdir as mkdir5,
|
|
6892
|
-
import { isAbsolute as
|
|
7004
|
+
import { mkdir as mkdir5, readFile, unlink as unlink4 } from "node:fs/promises";
|
|
7005
|
+
import { isAbsolute as isAbsolute4, join as join5 } from "node:path";
|
|
6893
7006
|
|
|
6894
7007
|
// host/invocation-context.ts
|
|
6895
7008
|
var HOST_INVOCATION_TURN_SELECTION_SCHEMA = "ceal.host_invocation_turn_selection.v1";
|
|
@@ -7049,9 +7162,9 @@ async function resumeOversizedLine(handle, offset, size) {
|
|
|
7049
7162
|
const { bytesRead } = await readHostUsageTranscriptSource(() => handle.read(bytes, 0, bytes.length, offset));
|
|
7050
7163
|
if (bytesRead < 1) return { lines: [], end_offset: offset, skipping_oversized_line: true, oversized_rows: 0 };
|
|
7051
7164
|
const chunk = bytes.subarray(0, bytesRead);
|
|
7052
|
-
const
|
|
7053
|
-
if (
|
|
7054
|
-
return completeChunk(chunk.subarray(
|
|
7165
|
+
const delimiter2 = chunk.indexOf(10);
|
|
7166
|
+
if (delimiter2 < 0) return { lines: [], end_offset: offset + bytesRead, skipping_oversized_line: true, oversized_rows: 0 };
|
|
7167
|
+
return completeChunk(chunk.subarray(delimiter2 + 1), offset + delimiter2 + 1);
|
|
7055
7168
|
}
|
|
7056
7169
|
function completeChunk(chunk, offset) {
|
|
7057
7170
|
const parsed = completeLinePrefix(chunk, offset);
|
|
@@ -7125,7 +7238,7 @@ var ClaudeHostError = class extends Error {
|
|
|
7125
7238
|
};
|
|
7126
7239
|
|
|
7127
7240
|
// host/claude/src/claude-invocation-context.ts
|
|
7128
|
-
import { isAbsolute as
|
|
7241
|
+
import { isAbsolute as isAbsolute3 } from "node:path";
|
|
7129
7242
|
function claudeInvocationContextFromTurn(identity, promptRef, expiresAt, workingDirectory, turnGenerationRef) {
|
|
7130
7243
|
return invocationContextFromTurn(identity, promptRef, expiresAt, { schema_version: CLAUDE_INVOCATION_CONTEXT_SCHEMA_VERSION, validate: validateClaudeHostInvocationContext, working_directory: workingDirectory, turn_generation_ref: turnGenerationRef });
|
|
7131
7244
|
}
|
|
@@ -7154,7 +7267,7 @@ function optionalSafeRef(value) {
|
|
|
7154
7267
|
return value === void 0 || safeRef2(value);
|
|
7155
7268
|
}
|
|
7156
7269
|
function optionalDirectory(value) {
|
|
7157
|
-
return value === void 0 || typeof value === "string" &&
|
|
7270
|
+
return value === void 0 || typeof value === "string" && isAbsolute3(value) && !value.includes("\0") && value.length <= 4096;
|
|
7158
7271
|
}
|
|
7159
7272
|
function safeRef2(value) {
|
|
7160
7273
|
return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value);
|
|
@@ -7179,14 +7292,14 @@ var ClaudeOutboxStore = class {
|
|
|
7179
7292
|
activeContexts;
|
|
7180
7293
|
turnSelections;
|
|
7181
7294
|
constructor(directory) {
|
|
7182
|
-
if (!
|
|
7295
|
+
if (!isAbsolute4(directory)) throw new ClaudeHostError("configuration", "Claude outbox directory must be absolute.");
|
|
7183
7296
|
this.directory = directory;
|
|
7184
|
-
this.envelopes =
|
|
7185
|
-
this.sessions =
|
|
7186
|
-
this.registrations =
|
|
7187
|
-
this.cursors =
|
|
7188
|
-
this.activeContexts =
|
|
7189
|
-
this.turnSelections =
|
|
7297
|
+
this.envelopes = join5(directory, "envelopes");
|
|
7298
|
+
this.sessions = join5(directory, "sessions");
|
|
7299
|
+
this.registrations = join5(directory, "transcript-registrations");
|
|
7300
|
+
this.cursors = join5(directory, "transcript-cursors");
|
|
7301
|
+
this.activeContexts = join5(directory, "active-contexts");
|
|
7302
|
+
this.turnSelections = join5(directory, "turn-selections");
|
|
7190
7303
|
}
|
|
7191
7304
|
async prepare() {
|
|
7192
7305
|
for (const path of [this.envelopes, this.sessions, this.registrations, this.cursors, this.activeContexts, this.turnSelections]) {
|
|
@@ -7214,6 +7327,7 @@ var ClaudeOutboxStore = class {
|
|
|
7214
7327
|
const path = this.activeContextPath(identity);
|
|
7215
7328
|
const active = await readProjectionFile(path);
|
|
7216
7329
|
if (active === null || active.prompt_ref !== promptRef || active.identity.host_turn_ref !== identity.host_turn_ref) return false;
|
|
7330
|
+
await this.prepare();
|
|
7217
7331
|
const updated = { ...active, turn_generation_ref: turnGenerationRef };
|
|
7218
7332
|
validateClaudeHostInvocationContext(updated);
|
|
7219
7333
|
await durableAtomicReplace(path, JSON.stringify(updated));
|
|
@@ -7226,17 +7340,15 @@ var ClaudeOutboxStore = class {
|
|
|
7226
7340
|
*/
|
|
7227
7341
|
async readRawInvocationContext(hostSourceRef, hostSessionRef) {
|
|
7228
7342
|
if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host context identity or clock is invalid.");
|
|
7229
|
-
await this.prepare();
|
|
7230
7343
|
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, readProjectionFile);
|
|
7231
7344
|
return context;
|
|
7232
7345
|
}
|
|
7233
7346
|
async listInvocationContexts(now = /* @__PURE__ */ new Date()) {
|
|
7234
|
-
await this.prepare();
|
|
7235
7347
|
const contexts = [];
|
|
7236
|
-
for (const name of await
|
|
7348
|
+
for (const name of await listHostOutboxDirectoryNames(this.activeContexts)) {
|
|
7237
7349
|
if (!name.endsWith(".json")) continue;
|
|
7238
7350
|
try {
|
|
7239
|
-
const value = JSON.parse(await readFile(
|
|
7351
|
+
const value = JSON.parse(await readFile(join5(this.activeContexts, name), "utf8"));
|
|
7240
7352
|
validateClaudeHostInvocationContext(value);
|
|
7241
7353
|
if (Date.parse(value.expires_at) > now.getTime()) contexts.push(value);
|
|
7242
7354
|
} catch {
|
|
@@ -7250,13 +7362,12 @@ var ClaudeOutboxStore = class {
|
|
|
7250
7362
|
await durableAtomicReplace(this.envelopePath(entry.submission_ref), JSON.stringify(entry));
|
|
7251
7363
|
}
|
|
7252
7364
|
async listEnvelopes() {
|
|
7253
|
-
await this.prepare();
|
|
7254
7365
|
const entries = [];
|
|
7255
7366
|
let malformed = 0;
|
|
7256
|
-
for (const name of await
|
|
7367
|
+
for (const name of await listHostOutboxDirectoryNames(this.envelopes)) {
|
|
7257
7368
|
if (!name.endsWith(".json")) continue;
|
|
7258
7369
|
try {
|
|
7259
|
-
const value = JSON.parse(await readFile(
|
|
7370
|
+
const value = JSON.parse(await readFile(join5(this.envelopes, name), "utf8"));
|
|
7260
7371
|
validateEnvelope(value);
|
|
7261
7372
|
entries.push(value);
|
|
7262
7373
|
} catch {
|
|
@@ -7277,13 +7388,12 @@ var ClaudeOutboxStore = class {
|
|
|
7277
7388
|
async saveSession(snapshot) {
|
|
7278
7389
|
validateSession(snapshot);
|
|
7279
7390
|
await this.prepare();
|
|
7280
|
-
await durableAtomicReplace(
|
|
7391
|
+
await durableAtomicReplace(join5(this.sessions, `${cealRequestSha256({ source: snapshot.host_source_ref, session: snapshot.host_session_ref })}.json`), JSON.stringify(snapshot));
|
|
7281
7392
|
}
|
|
7282
7393
|
async readSession(sourceRef, sessionRef) {
|
|
7283
7394
|
if (!SAFE_REF4.test(sourceRef) || !SAFE_REF4.test(sessionRef)) throw new ClaudeHostError("invalid_input", "Claude session identity is invalid.");
|
|
7284
|
-
await this.prepare();
|
|
7285
7395
|
try {
|
|
7286
|
-
const value = JSON.parse(await readFile(
|
|
7396
|
+
const value = JSON.parse(await readFile(join5(this.sessions, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`), "utf8"));
|
|
7287
7397
|
validateSession(value);
|
|
7288
7398
|
return value;
|
|
7289
7399
|
} catch (error) {
|
|
@@ -7314,18 +7424,16 @@ var ClaudeOutboxStore = class {
|
|
|
7314
7424
|
}
|
|
7315
7425
|
async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
|
|
7316
7426
|
if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude transcript session identity is invalid.");
|
|
7317
|
-
await this.prepare();
|
|
7318
7427
|
const registration = await this.readRegistrationFile(this.registrationPath(hostSourceRef, hostSessionRef));
|
|
7319
7428
|
if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw new ClaudeHostError("storage", "Claude transcript registration identity does not match its session.");
|
|
7320
7429
|
return registration;
|
|
7321
7430
|
}
|
|
7322
7431
|
async listTranscriptRegistrations() {
|
|
7323
|
-
await this.prepare();
|
|
7324
7432
|
const registrations = [];
|
|
7325
|
-
for (const name of await
|
|
7433
|
+
for (const name of await listHostOutboxDirectoryNames(this.registrations)) {
|
|
7326
7434
|
if (!name.endsWith(".json")) continue;
|
|
7327
7435
|
try {
|
|
7328
|
-
const value = JSON.parse(await readFile(
|
|
7436
|
+
const value = JSON.parse(await readFile(join5(this.registrations, name), "utf8"));
|
|
7329
7437
|
validateRegistration(value);
|
|
7330
7438
|
registrations.push(value);
|
|
7331
7439
|
} catch {
|
|
@@ -7335,7 +7443,6 @@ var ClaudeOutboxStore = class {
|
|
|
7335
7443
|
}
|
|
7336
7444
|
async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
|
|
7337
7445
|
if (!SAFE_REF4.test(hostSourceRef) || !SAFE_REF4.test(hostSessionRef)) throw new ClaudeHostError("invalid_input", "Claude Host turn selection identity is invalid.");
|
|
7338
|
-
await this.prepare();
|
|
7339
7446
|
try {
|
|
7340
7447
|
const value = JSON.parse(await readFile(this.turnSelectionPath(hostSourceRef, hostSessionRef), "utf8"));
|
|
7341
7448
|
if (!isHostInvocationTurnSelection(value) || value.host_source_ref !== hostSourceRef || value.host_session_ref !== hostSessionRef) throw new ClaudeHostError("storage", "Claude Host turn selection is malformed.");
|
|
@@ -7347,7 +7454,6 @@ var ClaudeOutboxStore = class {
|
|
|
7347
7454
|
}
|
|
7348
7455
|
async readTranscriptCursor(registration) {
|
|
7349
7456
|
validateRegistration(registration);
|
|
7350
|
-
await this.prepare();
|
|
7351
7457
|
try {
|
|
7352
7458
|
const value = JSON.parse(await readFile(this.cursorPath(registration.host_source_ref, registration.host_session_ref), "utf8"));
|
|
7353
7459
|
validateCursor(value);
|
|
@@ -7363,16 +7469,16 @@ var ClaudeOutboxStore = class {
|
|
|
7363
7469
|
await durableAtomicReplace(this.cursorPath(cursor.host_source_ref, cursor.host_session_ref), JSON.stringify(cursor));
|
|
7364
7470
|
}
|
|
7365
7471
|
envelopePath(ref) {
|
|
7366
|
-
return
|
|
7472
|
+
return join5(this.envelopes, `${cealRequestSha256(ref)}.json`);
|
|
7367
7473
|
}
|
|
7368
7474
|
registrationPath(sourceRef, sessionRef) {
|
|
7369
|
-
return
|
|
7475
|
+
return join5(this.registrations, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
7370
7476
|
}
|
|
7371
7477
|
turnSelectionPath(sourceRef, sessionRef) {
|
|
7372
|
-
return
|
|
7478
|
+
return join5(this.turnSelections, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
7373
7479
|
}
|
|
7374
7480
|
cursorPath(sourceRef, sessionRef) {
|
|
7375
|
-
return
|
|
7481
|
+
return join5(this.cursors, `${cealRequestSha256({ source: sourceRef, session: sessionRef })}.json`);
|
|
7376
7482
|
}
|
|
7377
7483
|
async readRegistrationFile(path) {
|
|
7378
7484
|
try {
|
|
@@ -7392,7 +7498,7 @@ var ClaudeOutboxStore = class {
|
|
|
7392
7498
|
}
|
|
7393
7499
|
}
|
|
7394
7500
|
activeContextPath(identity) {
|
|
7395
|
-
return
|
|
7501
|
+
return join5(this.activeContexts, `${invocationContextKey(identity)}.json`);
|
|
7396
7502
|
}
|
|
7397
7503
|
};
|
|
7398
7504
|
function validateInvocationContextReadArguments(hostSourceRef, hostSessionRef, now) {
|
|
@@ -7468,7 +7574,7 @@ function validateRegistration(value) {
|
|
|
7468
7574
|
if (!timestamp2(value.registered_at) || !timestamp2(value.expires_at)) throw new ClaudeHostError("storage", "Claude transcript registration timestamps are malformed.");
|
|
7469
7575
|
}
|
|
7470
7576
|
function validateRegistrationPaths(cwd, transcriptPath) {
|
|
7471
|
-
if (cwd !== void 0 && (typeof cwd !== "string" || !
|
|
7577
|
+
if (cwd !== void 0 && (typeof cwd !== "string" || !isAbsolute4(cwd) || cwd.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS || cwd.includes("\0"))) {
|
|
7472
7578
|
throw new ClaudeHostError("storage", "Claude transcript registration working directory is malformed.");
|
|
7473
7579
|
}
|
|
7474
7580
|
if (typeof transcriptPath !== "string" || transcriptPath.length === 0 || transcriptPath.length > CLAUDE_TRANSCRIPT_PATH_MAX_CHARACTERS) {
|
|
@@ -7589,7 +7695,7 @@ var ClaudeProducer = class {
|
|
|
7589
7695
|
// host/claude/src/claude-transcript-watcher.ts
|
|
7590
7696
|
import { readdir as readdir2 } from "node:fs/promises";
|
|
7591
7697
|
import { isDeepStrictEqual } from "node:util";
|
|
7592
|
-
import { join as
|
|
7698
|
+
import { join as join6 } from "node:path";
|
|
7593
7699
|
|
|
7594
7700
|
// host/claude/src/claude-decoder.ts
|
|
7595
7701
|
import { createHash as createHash8 } from "node:crypto";
|
|
@@ -7965,7 +8071,7 @@ var ClaudeTranscriptWatcher = class extends HostTranscriptWatcher {
|
|
|
7965
8071
|
return consumed;
|
|
7966
8072
|
}
|
|
7967
8073
|
async consumeSubagentFile(draft, directory, name) {
|
|
7968
|
-
const path =
|
|
8074
|
+
const path = join6(directory, name);
|
|
7969
8075
|
let handle;
|
|
7970
8076
|
try {
|
|
7971
8077
|
handle = await openNoFollow(path);
|
|
@@ -8214,7 +8320,7 @@ function isAssistantUsageLine(record7) {
|
|
|
8214
8320
|
}
|
|
8215
8321
|
function subagentsDirectory(transcriptPath) {
|
|
8216
8322
|
const stem = transcriptPath.endsWith(".jsonl") ? transcriptPath.slice(0, -".jsonl".length) : transcriptPath;
|
|
8217
|
-
return
|
|
8323
|
+
return join6(stem, "subagents");
|
|
8218
8324
|
}
|
|
8219
8325
|
function observationRef(hostSourceRef, event, identity, value) {
|
|
8220
8326
|
return cealHostObservationRef("claude", transcriptObjectSha256({ host_source_ref: hostSourceRef, event, identity, value }));
|
|
@@ -8270,7 +8376,7 @@ async function drainClaudeProducerOnce(options) {
|
|
|
8270
8376
|
import { createHash as createHash9 } from "node:crypto";
|
|
8271
8377
|
import { constants as constants7 } from "node:fs";
|
|
8272
8378
|
import { readdir as readdir3 } from "node:fs/promises";
|
|
8273
|
-
import { join as
|
|
8379
|
+
import { join as join7 } from "node:path";
|
|
8274
8380
|
var ClaudeUsageFactsCapturer = class {
|
|
8275
8381
|
sources;
|
|
8276
8382
|
usage;
|
|
@@ -8383,7 +8489,7 @@ var ClaudeUsageFactsCapturer = class {
|
|
|
8383
8489
|
async captureSubagentFile(registration, name, state) {
|
|
8384
8490
|
let handle;
|
|
8385
8491
|
try {
|
|
8386
|
-
const opened = await readHostUsageTranscriptSource(() => openNoFollow(
|
|
8492
|
+
const opened = await readHostUsageTranscriptSource(() => openNoFollow(join7(subagentsDirectory(registration.transcript_path), name), constants7.O_RDONLY));
|
|
8387
8493
|
handle = opened;
|
|
8388
8494
|
const file = await readHostUsageTranscriptSource(() => ownedClaudeTranscriptFile(opened));
|
|
8389
8495
|
const sourceRef = sourceFileRef(registration, file.device, file.inode);
|
|
@@ -8650,8 +8756,8 @@ var CLAUDE_PRODUCER_DESCRIPTOR = {
|
|
|
8650
8756
|
};
|
|
8651
8757
|
|
|
8652
8758
|
// host/codex/src/codex-outbox.ts
|
|
8653
|
-
import { mkdir as mkdir6, open as open4,
|
|
8654
|
-
import { dirname as dirname7, isAbsolute as
|
|
8759
|
+
import { mkdir as mkdir6, open as open4, rename as rename2, stat as stat2, unlink as unlink5 } from "node:fs/promises";
|
|
8760
|
+
import { dirname as dirname7, isAbsolute as isAbsolute5, join as join8 } from "node:path";
|
|
8655
8761
|
|
|
8656
8762
|
// host/codex/src/codex-types.ts
|
|
8657
8763
|
var CODEX_CLI_VERSION = "0.152.0";
|
|
@@ -8660,6 +8766,23 @@ var CODEX_HOOKS_CONFIG_FILE = "hooks.json";
|
|
|
8660
8766
|
var CODEX_HOOK_OWNER = "ceal-codex-host-observation-v1";
|
|
8661
8767
|
var CODEX_THREAD_ID_ENVIRONMENT = "CODEX_THREAD_ID";
|
|
8662
8768
|
var CODEX_SESSION_ID_ENVIRONMENT = "CODEX_SESSION_ID";
|
|
8769
|
+
var CODEX_TOOL_CALL_CORRELATION_MIN_VERSION = "0.163.0";
|
|
8770
|
+
var CODEX_VERSION_HINT_UPGRADE_FOR_TOOL_CALL_CORRELATION = "codex_upgrade_recommended_for_tool_call_correlation";
|
|
8771
|
+
function codexVersionHint(version) {
|
|
8772
|
+
const observed = parseCodexVersion(version);
|
|
8773
|
+
const minimum = parseCodexVersion(CODEX_TOOL_CALL_CORRELATION_MIN_VERSION);
|
|
8774
|
+
if (observed === null || minimum === null) return void 0;
|
|
8775
|
+
return compareCodexVersions(observed, minimum) < 0 ? CODEX_VERSION_HINT_UPGRADE_FOR_TOOL_CALL_CORRELATION : void 0;
|
|
8776
|
+
}
|
|
8777
|
+
function compareCodexVersions(left, right) {
|
|
8778
|
+
return left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
|
|
8779
|
+
}
|
|
8780
|
+
function parseCodexVersion(version) {
|
|
8781
|
+
if (version === void 0) return null;
|
|
8782
|
+
const match = /^(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:[-+].*)?$/u.exec(version.trim());
|
|
8783
|
+
if (match?.[1] === void 0 || match[2] === void 0 || match[3] === void 0) return null;
|
|
8784
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
8785
|
+
}
|
|
8663
8786
|
var CODEX_OUTBOX_SCHEMA_VERSION = "ceal.codex_observation_outbox.v1";
|
|
8664
8787
|
var CODEX_SESSION_SCHEMA_VERSION = "ceal.codex_session.v1";
|
|
8665
8788
|
var CODEX_INVOCATION_CONTEXT_SCHEMA_VERSION = "ceal.codex_invocation_context.v1";
|
|
@@ -8730,12 +8853,12 @@ var CodexOutboxStore = class {
|
|
|
8730
8853
|
constructor(directory) {
|
|
8731
8854
|
if (typeof directory !== "string" || directory.length === 0) throw new CodexHostAdapterError("configuration", "Codex outbox directory is required.");
|
|
8732
8855
|
this.directory = directory;
|
|
8733
|
-
this.entriesDirectory =
|
|
8734
|
-
this.sessionsDirectory =
|
|
8735
|
-
this.activeContextsDirectory =
|
|
8736
|
-
this.turnSelectionsDirectory =
|
|
8737
|
-
this.registrationsDirectory =
|
|
8738
|
-
this.cursorsDirectory =
|
|
8856
|
+
this.entriesDirectory = join8(directory, "entries");
|
|
8857
|
+
this.sessionsDirectory = join8(directory, "sessions");
|
|
8858
|
+
this.activeContextsDirectory = join8(directory, "active-contexts");
|
|
8859
|
+
this.turnSelectionsDirectory = join8(directory, "turn-selections");
|
|
8860
|
+
this.registrationsDirectory = join8(directory, "transcript-registrations");
|
|
8861
|
+
this.cursorsDirectory = join8(directory, "transcript-cursors");
|
|
8739
8862
|
}
|
|
8740
8863
|
async prepare() {
|
|
8741
8864
|
for (const path of [this.directory, this.entriesDirectory, this.sessionsDirectory, this.activeContextsDirectory, this.turnSelectionsDirectory, this.registrationsDirectory, this.cursorsDirectory]) {
|
|
@@ -8748,13 +8871,12 @@ var CodexOutboxStore = class {
|
|
|
8748
8871
|
await writeAtomicJson(this.entryPath(entry.submission_ref), entry);
|
|
8749
8872
|
}
|
|
8750
8873
|
async list() {
|
|
8751
|
-
await this.prepare();
|
|
8752
8874
|
const entries = [];
|
|
8753
8875
|
let malformed = 0;
|
|
8754
|
-
for (const name of await
|
|
8876
|
+
for (const name of await listHostOutboxDirectoryNames(this.entriesDirectory)) {
|
|
8755
8877
|
if (!name.endsWith(".json")) continue;
|
|
8756
8878
|
try {
|
|
8757
|
-
const value = JSON.parse(await readOwnerStateFile(
|
|
8879
|
+
const value = JSON.parse(await readOwnerStateFile(join8(this.entriesDirectory, name)));
|
|
8758
8880
|
validateEnvelope2(value);
|
|
8759
8881
|
entries.push(value);
|
|
8760
8882
|
} catch {
|
|
@@ -8799,7 +8921,6 @@ var CodexOutboxStore = class {
|
|
|
8799
8921
|
}
|
|
8800
8922
|
async readInvocationTurnSelection(hostSourceRef, hostSessionRef) {
|
|
8801
8923
|
if (!SAFE_REF5.test(hostSourceRef) || !SAFE_REF5.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host turn selection identity is invalid.");
|
|
8802
|
-
await this.prepare();
|
|
8803
8924
|
return readOptionalJson2(this.turnSelectionPath(hostSourceRef, hostSessionRef), validateTurnSelection);
|
|
8804
8925
|
}
|
|
8805
8926
|
async attachInvocationTurnGeneration(identity, promptRef, turnGenerationRef) {
|
|
@@ -8808,6 +8929,7 @@ var CodexOutboxStore = class {
|
|
|
8808
8929
|
const path = this.activeContextPath(identity);
|
|
8809
8930
|
const active = await readOptionalJson2(path, validateCodexHostInvocationContext);
|
|
8810
8931
|
if (active === null || active.prompt_ref !== promptRef || !sameIdentity(active.identity, identity)) return false;
|
|
8932
|
+
await this.prepare();
|
|
8811
8933
|
await writeAtomicJson(path, { ...active, turn_generation_ref: turnGenerationRef });
|
|
8812
8934
|
return true;
|
|
8813
8935
|
}
|
|
@@ -8824,7 +8946,6 @@ var CodexOutboxStore = class {
|
|
|
8824
8946
|
*/
|
|
8825
8947
|
async readRawInvocationContext(hostSourceRef, hostSessionRef) {
|
|
8826
8948
|
if (!SAFE_REF5.test(hostSourceRef) || !SAFE_REF5.test(hostSessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex Host session identity is invalid.");
|
|
8827
|
-
await this.prepare();
|
|
8828
8949
|
const context = await readLatestSessionProjection(this.activeContextPath({ host_source_ref: hostSourceRef, host_session_ref: hostSessionRef }), hostSourceRef, hostSessionRef, (file) => readOptionalJson2(file, validateCodexHostInvocationContext));
|
|
8829
8950
|
return context;
|
|
8830
8951
|
}
|
|
@@ -8848,7 +8969,6 @@ var CodexOutboxStore = class {
|
|
|
8848
8969
|
async readSession(sourceRef, sessionRef) {
|
|
8849
8970
|
const identity = { host_source_ref: sourceRef, host_session_ref: sessionRef };
|
|
8850
8971
|
if (!SAFE_REF5.test(sourceRef) || !SAFE_REF5.test(sessionRef)) throw new CodexHostAdapterError("invalid_input", "Codex session identity is invalid.");
|
|
8851
|
-
await this.prepare();
|
|
8852
8972
|
return readOptionalJson2(this.sessionPath(identity.host_source_ref, identity.host_session_ref), validateSession2);
|
|
8853
8973
|
}
|
|
8854
8974
|
async registerTranscript(registration) {
|
|
@@ -8876,18 +8996,16 @@ var CodexOutboxStore = class {
|
|
|
8876
8996
|
}
|
|
8877
8997
|
async readTranscriptRegistration(hostSourceRef, hostSessionRef) {
|
|
8878
8998
|
const path = this.registrationPath(hostSourceRef, hostSessionRef);
|
|
8879
|
-
await this.prepare();
|
|
8880
8999
|
const registration = await readOptionalJson2(path, validateRegistration2);
|
|
8881
9000
|
if (registration !== null && (registration.host_source_ref !== hostSourceRef || registration.host_session_ref !== hostSessionRef)) throw storageError("Codex transcript registration identity does not match its session.");
|
|
8882
9001
|
return registration;
|
|
8883
9002
|
}
|
|
8884
9003
|
async listTranscriptRegistrations() {
|
|
8885
|
-
await this.prepare();
|
|
8886
9004
|
const registrations = [];
|
|
8887
|
-
for (const name of await
|
|
9005
|
+
for (const name of await listHostOutboxDirectoryNames(this.registrationsDirectory)) {
|
|
8888
9006
|
if (!name.endsWith(".json")) continue;
|
|
8889
9007
|
try {
|
|
8890
|
-
const value = JSON.parse(await readOwnerStateFile(
|
|
9008
|
+
const value = JSON.parse(await readOwnerStateFile(join8(this.registrationsDirectory, name)));
|
|
8891
9009
|
validateRegistration2(value);
|
|
8892
9010
|
registrations.push(value);
|
|
8893
9011
|
} catch {
|
|
@@ -8897,7 +9015,6 @@ var CodexOutboxStore = class {
|
|
|
8897
9015
|
}
|
|
8898
9016
|
async readTranscriptCursor(registration) {
|
|
8899
9017
|
validateRegistration2(registration);
|
|
8900
|
-
await this.prepare();
|
|
8901
9018
|
return readOptionalJson2(this.cursorPath(registration.host_source_ref, registration.host_session_ref), validateCursor2);
|
|
8902
9019
|
}
|
|
8903
9020
|
async writeTranscriptCursor(cursor) {
|
|
@@ -8910,7 +9027,6 @@ var CodexOutboxStore = class {
|
|
|
8910
9027
|
const read2 = await this.list();
|
|
8911
9028
|
const envelope = findEnvelopeByAlias(read2.entries, sourceRef, sessionRef, alias);
|
|
8912
9029
|
if (envelope !== null) return envelopeMatch(envelope);
|
|
8913
|
-
await this.prepare();
|
|
8914
9030
|
return null;
|
|
8915
9031
|
}
|
|
8916
9032
|
async hasPriorTurn(sourceRef, sessionRef) {
|
|
@@ -8921,22 +9037,22 @@ var CodexOutboxStore = class {
|
|
|
8921
9037
|
}
|
|
8922
9038
|
entryPath(submissionRef2) {
|
|
8923
9039
|
if (!SAFE_REF5.test(submissionRef2)) throw storageError("Codex submission identity is malformed.");
|
|
8924
|
-
return
|
|
9040
|
+
return join8(this.entriesDirectory, `${cealRequestSha256(submissionRef2)}.json`);
|
|
8925
9041
|
}
|
|
8926
9042
|
sessionPath(sourceRef, sessionRef) {
|
|
8927
|
-
return
|
|
9043
|
+
return join8(this.sessionsDirectory, `${identityKey({ host_source_ref: sourceRef, host_session_ref: sessionRef, host_turn_ref: "session" })}.json`);
|
|
8928
9044
|
}
|
|
8929
9045
|
activeContextPath(identity) {
|
|
8930
|
-
return
|
|
9046
|
+
return join8(this.activeContextsDirectory, `${invocationContextKey(identity)}.json`);
|
|
8931
9047
|
}
|
|
8932
9048
|
turnSelectionPath(sourceRef, sessionRef) {
|
|
8933
|
-
return
|
|
9049
|
+
return join8(this.turnSelectionsDirectory, `${invocationContextKey({ host_source_ref: sourceRef, host_session_ref: sessionRef })}.json`);
|
|
8934
9050
|
}
|
|
8935
9051
|
registrationPath(sourceRef, sessionRef) {
|
|
8936
|
-
return
|
|
9052
|
+
return join8(this.registrationsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
|
|
8937
9053
|
}
|
|
8938
9054
|
cursorPath(sourceRef, sessionRef) {
|
|
8939
|
-
return
|
|
9055
|
+
return join8(this.cursorsDirectory, `${sessionStateKey(sourceRef, sessionRef)}.json`);
|
|
8940
9056
|
}
|
|
8941
9057
|
};
|
|
8942
9058
|
async function removeOwnerState(path, what) {
|
|
@@ -9070,7 +9186,7 @@ function validateRegistrationFields(value) {
|
|
|
9070
9186
|
if (!isTimestamp(value.registered_at) || !isTimestamp(value.expires_at)) throw storageError(`Codex transcript registration timestamps are malformed (${refusalFacts([{ name: "registered_at", value: value.registered_at }, { name: "expires_at", value: value.expires_at }])}).`);
|
|
9071
9187
|
}
|
|
9072
9188
|
function validRegistrationCwd(value) {
|
|
9073
|
-
return value === void 0 || typeof value === "string" &&
|
|
9189
|
+
return value === void 0 || typeof value === "string" && isAbsolute5(value) && value.length <= CODEX_TRANSCRIPT_PATH_MAX_CHARACTERS && !value.includes("\0");
|
|
9074
9190
|
}
|
|
9075
9191
|
function validateCursor2(value) {
|
|
9076
9192
|
if (!isRecord7(value)) throw storageError("Codex transcript cursor is malformed.");
|
|
@@ -9462,11 +9578,11 @@ function timestamp5(now) {
|
|
|
9462
9578
|
}
|
|
9463
9579
|
|
|
9464
9580
|
// host/codex/src/codex-runtime-paths.ts
|
|
9465
|
-
import { join as
|
|
9581
|
+
import { join as join9 } from "node:path";
|
|
9466
9582
|
var CODEX_HOME_ENVIRONMENT = "CODEX_HOME";
|
|
9467
9583
|
var CODEX_HOME_DEFAULT_DIRECTORY = ".codex";
|
|
9468
9584
|
function resolveCodexHome(environment, home) {
|
|
9469
|
-
return environment[CODEX_HOME_ENVIRONMENT] ||
|
|
9585
|
+
return environment[CODEX_HOME_ENVIRONMENT] || join9(home, CODEX_HOME_DEFAULT_DIRECTORY);
|
|
9470
9586
|
}
|
|
9471
9587
|
|
|
9472
9588
|
// host/codex/src/codex-adapter.ts
|
|
@@ -10079,7 +10195,7 @@ var CODEX_PRODUCER_DESCRIPTOR = {
|
|
|
10079
10195
|
|
|
10080
10196
|
// host/relay/src/host-relay-runtime.ts
|
|
10081
10197
|
import { constants as constants8 } from "node:fs";
|
|
10082
|
-
import { dirname as dirname8, join as
|
|
10198
|
+
import { dirname as dirname8, join as join10 } from "node:path";
|
|
10083
10199
|
|
|
10084
10200
|
// host/json-duplicate-guard.ts
|
|
10085
10201
|
function rejectDuplicateJsonKeys(text, errors) {
|
|
@@ -10678,7 +10794,7 @@ function rejectDuplicateJsonKeys2(text) {
|
|
|
10678
10794
|
|
|
10679
10795
|
// host/lifecycle/src/host-runtime-hooks.ts
|
|
10680
10796
|
import { lstat as lstat10 } from "node:fs/promises";
|
|
10681
|
-
import { basename as basename3, dirname as dirname12, join as
|
|
10797
|
+
import { basename as basename3, dirname as dirname12, join as join18 } from "node:path";
|
|
10682
10798
|
|
|
10683
10799
|
// host/hook-drift-policy.ts
|
|
10684
10800
|
var REINSTALL_REPAIRS_PREFIX = ["owned_hook_drifted:"];
|
|
@@ -10691,7 +10807,7 @@ var OPERATOR_ONLY = /* @__PURE__ */ new Set([
|
|
|
10691
10807
|
"settings_malformed",
|
|
10692
10808
|
"local_capability_foreign"
|
|
10693
10809
|
]);
|
|
10694
|
-
var OPERATOR_ONLY_PREFIX = ["duplicate_owned_hook:"];
|
|
10810
|
+
var OPERATOR_ONLY_PREFIX = ["duplicate_owned_hook:", "hook_trust_modified:"];
|
|
10695
10811
|
function hookDriftRemedyFor(reason) {
|
|
10696
10812
|
if (OPERATOR_ONLY.has(reason) || OPERATOR_ONLY_PREFIX.some((prefix) => reason.startsWith(prefix))) return "operator";
|
|
10697
10813
|
if (REINSTALL_REPAIRS.has(reason) || REINSTALL_REPAIRS_PREFIX.some((prefix) => reason.startsWith(prefix))) return "reinstall";
|
|
@@ -10708,7 +10824,7 @@ import { constants as constants9 } from "node:fs";
|
|
|
10708
10824
|
import { randomUUID } from "node:crypto";
|
|
10709
10825
|
import { lstat as lstat6, mkdir as mkdir7, readlink, realpath, rename as rename3, stat as stat3, unlink as unlink6 } from "node:fs/promises";
|
|
10710
10826
|
import { homedir } from "node:os";
|
|
10711
|
-
import { basename, dirname as dirname9, isAbsolute as
|
|
10827
|
+
import { basename, dirname as dirname9, isAbsolute as isAbsolute6, join as join11, normalize as normalize2, parse as parse2 } from "node:path";
|
|
10712
10828
|
|
|
10713
10829
|
// host/command-vector.ts
|
|
10714
10830
|
import { win32 as win328 } from "node:path";
|
|
@@ -10728,6 +10844,17 @@ function validateHostCommandVector(vector, windowsConsumer = "cmd") {
|
|
|
10728
10844
|
function formatHostCommand(vector, platform) {
|
|
10729
10845
|
return formatWith(vector, platform === "windows" ? quoteWindowsArgument : quotePosixArgument);
|
|
10730
10846
|
}
|
|
10847
|
+
function hostScriptLauncherInvocation(launcherPath2, args, kind, platform = process.platform, environment = process.env) {
|
|
10848
|
+
if (kind === "node") return { executable: process.execPath, args: [launcherPath2, ...args] };
|
|
10849
|
+
if (platform === "win32" && kind === "cmd") return windowsCmdLauncherInvocation(launcherPath2, args, environment);
|
|
10850
|
+
if (platform === "win32" && kind === "powershell") {
|
|
10851
|
+
return {
|
|
10852
|
+
executable: win328.join(environmentValue(environment, "SystemRoot", platform) ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
|
|
10853
|
+
args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", launcherPath2, ...args]
|
|
10854
|
+
};
|
|
10855
|
+
}
|
|
10856
|
+
return { executable: launcherPath2, args };
|
|
10857
|
+
}
|
|
10731
10858
|
function formatWindowsPowerShellCmdScriptCommand(launcherPath2, args, environment = process.env) {
|
|
10732
10859
|
validateWindowsCmdScriptVector(launcherPath2, args, "cmd");
|
|
10733
10860
|
if (args.some((argument) => !WINDOWS_FIXED_CMD_ARGUMENT.test(argument))) throw new TypeError("Host script launcher argument is outside the Windows launcher alphabet.");
|
|
@@ -10737,10 +10864,22 @@ function formatWindowsPowerShellCmdScriptCommand(launcherPath2, args, environmen
|
|
|
10737
10864
|
const invocation = ["&", commandProcessor, "/d", "/v:off", "/s", "/c", command].map((value, index) => index === 0 ? value : quotePowerShellLiteral(value)).join(" ");
|
|
10738
10865
|
return boundedHostCommand(`$LASTEXITCODE = 1; ${invocation}; exit $LASTEXITCODE`);
|
|
10739
10866
|
}
|
|
10867
|
+
function windowsCmdLauncherInvocation(launcherPath2, args, environment) {
|
|
10868
|
+
validateWindowsCmdScriptVector(launcherPath2, args, "direct-exec");
|
|
10869
|
+
const variable = "CEAL_HOST_SCRIPT_LAUNCHER_PATH";
|
|
10870
|
+
const command = `"%${variable}%" ${args.map(quoteWindowsArgument).join(" ")}`.trimEnd();
|
|
10871
|
+
return { ...windowsCmdInvocation(environment, `"${command}"`), environment: { [variable]: launcherPath2 }, windowsVerbatimArguments: true };
|
|
10872
|
+
}
|
|
10740
10873
|
function validateWindowsCmdScriptVector(launcherPath2, args, consumer) {
|
|
10741
10874
|
if (invalidText(launcherPath2) || launcherPath2.includes('"')) throw new TypeError("Host script launcher path is invalid.");
|
|
10742
10875
|
validateHostCommandVector({ executable: launcherPath2, args }, consumer);
|
|
10743
10876
|
}
|
|
10877
|
+
function windowsCmdInvocation(environment, command) {
|
|
10878
|
+
return { executable: windowsAmbientCommandProcessor(environment), args: ["/d", "/v:off", "/s", "/c", command] };
|
|
10879
|
+
}
|
|
10880
|
+
function windowsAmbientCommandProcessor(environment) {
|
|
10881
|
+
return environmentValue(environment, "ComSpec", "win32") ?? "cmd.exe";
|
|
10882
|
+
}
|
|
10744
10883
|
function windowsSystemCommandProcessor(environment) {
|
|
10745
10884
|
const systemRoot = environmentValue(environment, "SystemRoot", "win32");
|
|
10746
10885
|
if (systemRoot === void 0 || !/^[A-Za-z]:[\\/]/u.test(systemRoot) || systemRoot.split(/[\\/]/u).some((segment) => segment === "." || segment === "..")) throw new TypeError("Windows SystemRoot is unavailable or invalid.");
|
|
@@ -10793,17 +10932,17 @@ var HostEntryLinkError = class extends Error {
|
|
|
10793
10932
|
}
|
|
10794
10933
|
};
|
|
10795
10934
|
function resolveHostEntryRoot(producerHome, producerDirectory) {
|
|
10796
|
-
const home = producerHome ??
|
|
10797
|
-
if (!
|
|
10935
|
+
const home = producerHome ?? join11(homedir(), producerDirectory);
|
|
10936
|
+
if (!isAbsolute6(home)) throw new TypeError("Host producer home must be absolute.");
|
|
10798
10937
|
const userRoot = basename(home) === producerDirectory ? dirname9(home) : home;
|
|
10799
|
-
return
|
|
10938
|
+
return join11(userRoot, ...HOST_ENTRY_DIRECTORY);
|
|
10800
10939
|
}
|
|
10801
10940
|
function hostEntryCommand({ entryRoot, module: module2, configFlag, configFile, platform = process.platform }) {
|
|
10802
10941
|
assertLauncherArgument(module2, "module");
|
|
10803
10942
|
assertLauncherArgument(configFile, "configuration file");
|
|
10804
10943
|
if (!/^--[A-Za-z0-9_-]+$/u.test(configFlag)) throw new TypeError("Host entry configuration flag must be a long option name.");
|
|
10805
10944
|
return {
|
|
10806
|
-
executable:
|
|
10945
|
+
executable: join11(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER),
|
|
10807
10946
|
args: [module2, `${configFlag}=${configFile}`]
|
|
10808
10947
|
};
|
|
10809
10948
|
}
|
|
@@ -10812,8 +10951,8 @@ async function installHostEntryLinks(entryRoot, targets, platform = process.plat
|
|
|
10812
10951
|
assertWindowsEntryPaths(entryRoot, targets, platform);
|
|
10813
10952
|
await assertEntryRootProven(entryRoot, platform, custody);
|
|
10814
10953
|
await Promise.all([assertCanonicalDirectory(targets.runtime, "runtime"), assertCanonicalDirectory(targets.services, "services")]);
|
|
10815
|
-
if (platform === "win32") await assertLegacyLinkOrAbsent(
|
|
10816
|
-
await assertLegacyLinkOrAbsent(
|
|
10954
|
+
if (platform === "win32") await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
|
|
10955
|
+
await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
|
|
10817
10956
|
await preparePrivateEntryRoot(entryRoot);
|
|
10818
10957
|
return reconcileEntryLaunchers(entryRoot, targets, platform, custody, renameRetry);
|
|
10819
10958
|
}
|
|
@@ -10854,31 +10993,31 @@ async function reconcileEntryLaunchers(entryRoot, targets, platform, custody, re
|
|
|
10854
10993
|
}
|
|
10855
10994
|
async function removeLegacyEntryPaths(entryRoot, platform) {
|
|
10856
10995
|
let removed = false;
|
|
10857
|
-
if (platform === "win32") removed = await removeLegacyPath(
|
|
10858
|
-
return await removeLegacyPath(
|
|
10996
|
+
if (platform === "win32") removed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
|
|
10997
|
+
return await removeLegacyPath(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || removed;
|
|
10859
10998
|
}
|
|
10860
10999
|
async function inspectHostEntryLinks(entryRoot, targets, platform = process.platform, custody = {}) {
|
|
10861
11000
|
assertAbsolute(entryRoot, targets);
|
|
10862
11001
|
await assertEntryRootProven(entryRoot, platform, custody);
|
|
10863
11002
|
const installed = await readInstalledLauncher(launcherPath(entryRoot, platform), platform, custody);
|
|
10864
11003
|
if (installed.status === "absent") return "missing";
|
|
10865
|
-
if (await pathExists(
|
|
11004
|
+
if (await pathExists(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || platform === "win32" && await pathExists(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER))) return "drifted";
|
|
10866
11005
|
if (installed.status !== "ready") return "drifted";
|
|
10867
11006
|
return installed.targets.runtime === targets.runtime && installed.targets.services === targets.services ? "ready" : "drifted";
|
|
10868
11007
|
}
|
|
10869
11008
|
async function removeHostEntryLinks(entryRoot, platform = process.platform, custody = {}) {
|
|
10870
|
-
if (!
|
|
11009
|
+
if (!isAbsolute6(entryRoot)) throw new TypeError("Host entry root must be absolute.");
|
|
10871
11010
|
await assertEntryRootProven(entryRoot, platform, custody);
|
|
10872
|
-
if (platform === "win32") await assertLegacyLinkOrAbsent(
|
|
10873
|
-
await assertLegacyLinkOrAbsent(
|
|
11011
|
+
if (platform === "win32") await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER));
|
|
11012
|
+
await assertLegacyLinkOrAbsent(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES));
|
|
10874
11013
|
let changed = false;
|
|
10875
11014
|
changed = await removeLauncherFile(launcherPath(entryRoot, platform), platform, custody) || changed;
|
|
10876
|
-
if (platform === "win32") changed = await removeLegacyPath(
|
|
10877
|
-
changed = await removeLegacyPath(
|
|
11015
|
+
if (platform === "win32") changed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_RUNTIME_LAUNCHER)) || changed;
|
|
11016
|
+
changed = await removeLegacyPath(join11(entryRoot, HOST_ENTRY_LEGACY_SERVICES)) || changed;
|
|
10878
11017
|
return changed;
|
|
10879
11018
|
}
|
|
10880
11019
|
function launcherPath(entryRoot, platform) {
|
|
10881
|
-
return
|
|
11020
|
+
return join11(entryRoot, platform === "win32" ? HOST_ENTRY_WINDOWS_RUNTIME_LAUNCHER : HOST_ENTRY_RUNTIME_LAUNCHER);
|
|
10882
11021
|
}
|
|
10883
11022
|
async function readInstalledLauncher(path, platform, custody) {
|
|
10884
11023
|
const handle = await openLauncherFile(path, platform, custody);
|
|
@@ -11127,7 +11266,7 @@ async function assertOwnedEntryRootDirectory(logical, physical, platform, custod
|
|
|
11127
11266
|
if ((info.mode & 18) !== 0) throw new HostEntryLinkError("entry_root_unowned", `Host entry root ancestor ${logical} grants cross-user write access; remove the group/other write bits, then rerun.`);
|
|
11128
11267
|
}
|
|
11129
11268
|
function assertAbsolute(entryRoot, targets) {
|
|
11130
|
-
if (![entryRoot, targets.runtime, targets.services].every((value) => typeof value === "string" &&
|
|
11269
|
+
if (![entryRoot, targets.runtime, targets.services].every((value) => typeof value === "string" && isAbsolute6(value) && !hasControlCharacters3(value))) throw new TypeError("Host entry root and launcher targets must be absolute paths without control characters.");
|
|
11131
11270
|
}
|
|
11132
11271
|
function hasControlCharacters3(value) {
|
|
11133
11272
|
for (const character of value) {
|
|
@@ -11137,7 +11276,7 @@ function hasControlCharacters3(value) {
|
|
|
11137
11276
|
return false;
|
|
11138
11277
|
}
|
|
11139
11278
|
async function assertCanonicalDirectory(target, role) {
|
|
11140
|
-
if (!
|
|
11279
|
+
if (!isAbsolute6(target) || normalize2(target) !== target || parse2(target).root === target) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must be a canonical absolute non-root path.", [`target_role:${role}`, "target_path_invalid"]);
|
|
11141
11280
|
try {
|
|
11142
11281
|
if (await realpath(target) !== target) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must resolve to its canonical directory.", [`target_role:${role}`, "target_not_canonical"]);
|
|
11143
11282
|
if (!(await stat3(target)).isDirectory()) throw new HostEntryLinkError("entry_target_invalid", "Host launcher target must resolve to its canonical directory.", [`target_role:${role}`, "target_not_directory"]);
|
|
@@ -11164,18 +11303,18 @@ import { constants as constants11 } from "node:fs";
|
|
|
11164
11303
|
import { chmod, copyFile as copyFile2, lstat as lstat8, mkdir as mkdir8, open as open5, readFile as readFile2, rename as rename4, unlink as unlink7 } from "node:fs/promises";
|
|
11165
11304
|
import { createHash as createHash13 } from "node:crypto";
|
|
11166
11305
|
import { homedir as homedir2 } from "node:os";
|
|
11167
|
-
import { dirname as dirname10, isAbsolute as
|
|
11306
|
+
import { dirname as dirname10, isAbsolute as isAbsolute8, join as join14 } from "node:path";
|
|
11168
11307
|
|
|
11169
11308
|
// host/local-capability-descriptor.ts
|
|
11170
11309
|
import { constants as constants10 } from "node:fs";
|
|
11171
|
-
import { isAbsolute as
|
|
11310
|
+
import { isAbsolute as isAbsolute7, join as join12 } from "node:path";
|
|
11172
11311
|
import { lstat as lstat7 } from "node:fs/promises";
|
|
11173
11312
|
var HOST_LOCAL_CAPABILITY_AUTHENTICATION_SUFFIX = Object.freeze(["authenticate", "--client-nonce"]);
|
|
11174
11313
|
var HOST_LOCAL_CAPABILITY_AUTHENTICATION_MODE = "nonce";
|
|
11175
11314
|
var HOST_LOCAL_CAPABILITY_EXECUTION_MODE = "verbatim";
|
|
11176
11315
|
function hostLocalCapabilityPath(userHome, producer) {
|
|
11177
|
-
if (!
|
|
11178
|
-
return
|
|
11316
|
+
if (!isAbsolute7(userHome)) throw new TypeError("Host local capability user home must be absolute.");
|
|
11317
|
+
return join12(userHome, ".ceal", "local-capabilities", `${producer}.json`);
|
|
11179
11318
|
}
|
|
11180
11319
|
function hostLocalCapabilityDescriptor(input) {
|
|
11181
11320
|
const argv = [input.authenticationCommand.executable, ...input.authenticationCommand.args];
|
|
@@ -11323,11 +11462,11 @@ function isRecord9(value) {
|
|
|
11323
11462
|
}
|
|
11324
11463
|
|
|
11325
11464
|
// host/claude/src/claude-runtime-paths.ts
|
|
11326
|
-
import { join as
|
|
11465
|
+
import { join as join13 } from "node:path";
|
|
11327
11466
|
var CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT = "CLAUDE_CONFIG_DIR";
|
|
11328
11467
|
var CLAUDE_HOME_DEFAULT_DIRECTORY = ".claude";
|
|
11329
11468
|
function resolveClaudeConfigHome(environment, home) {
|
|
11330
|
-
return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] ||
|
|
11469
|
+
return environment[CLAUDE_CONFIG_DIRECTORY_ENVIRONMENT] || join13(home, CLAUDE_HOME_DEFAULT_DIRECTORY);
|
|
11331
11470
|
}
|
|
11332
11471
|
|
|
11333
11472
|
// host/claude/src/claude-installer.ts
|
|
@@ -11337,7 +11476,7 @@ var CLAUDE_LOCAL_CAPABILITY_ACTIVATION = Object.freeze({ environment: CLAUDE_SES
|
|
|
11337
11476
|
var CLAUDE_CLIENT_ALLOW_RULE = `Bash(${CEAL_SESSION_ENTRY_INVOCATION}:*)`;
|
|
11338
11477
|
var PERMISSION_OWNERSHIP_SCHEMA = "ceal.claude_permission_ownership.v1";
|
|
11339
11478
|
function resolveClaudeSettingsPath(claudeHome, environment = process.env) {
|
|
11340
|
-
return
|
|
11479
|
+
return join14(claudeHome ?? resolveClaudeConfigHome(environment, homedir2()), "settings.json");
|
|
11341
11480
|
}
|
|
11342
11481
|
async function installClaudeHooks(options) {
|
|
11343
11482
|
const normalized = validateOptions(options);
|
|
@@ -11345,15 +11484,14 @@ async function installClaudeHooks(options) {
|
|
|
11345
11484
|
const executableSha256 = await inspectExecutable(command.executable);
|
|
11346
11485
|
const current = await readSettingsForMutation(normalized.settings_path);
|
|
11347
11486
|
let next = mergeOwnedHooks(current, command);
|
|
11348
|
-
|
|
11349
|
-
|
|
11350
|
-
next = withAllowEntries(next, [...allowEntries(next), CLAUDE_CLIENT_ALLOW_RULE]);
|
|
11351
|
-
}
|
|
11487
|
+
const addsAllow = !allowEntries(next).includes(CLAUDE_CLIENT_ALLOW_RULE);
|
|
11488
|
+
if (addsAllow) next = withAllowEntries(next, [...allowEntries(next), CLAUDE_CLIENT_ALLOW_RULE]);
|
|
11352
11489
|
const changed = JSON.stringify(current) !== JSON.stringify(next);
|
|
11353
11490
|
if (changed) {
|
|
11354
11491
|
await backup(normalized.settings_path);
|
|
11355
11492
|
await writeAtomicJson2(normalized.settings_path, next);
|
|
11356
11493
|
}
|
|
11494
|
+
if (addsAllow) await writeAtomicJson2(normalized.permission_ownership_path, { schema_version: PERMISSION_OWNERSHIP_SCHEMA, settings_path: normalized.settings_path, allow: CLAUDE_CLIENT_ALLOW_RULE });
|
|
11357
11495
|
return { settings_path: normalized.settings_path, changed, events: CLAUDE_HOOK_EVENTS, executable_sha256: executableSha256 };
|
|
11358
11496
|
}
|
|
11359
11497
|
async function uninstallClaudeHooks(options) {
|
|
@@ -11408,7 +11546,7 @@ function validateClaudeLocalCapabilityDescriptor(encoded) {
|
|
|
11408
11546
|
return inspection.document;
|
|
11409
11547
|
}
|
|
11410
11548
|
async function installClaudeLocalCapability(path, authenticationCommand, custody = {}) {
|
|
11411
|
-
if (!
|
|
11549
|
+
if (!isAbsolute8(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
|
|
11412
11550
|
try {
|
|
11413
11551
|
validateHostCommandVector(authenticationCommand);
|
|
11414
11552
|
} catch (error) {
|
|
@@ -11442,7 +11580,7 @@ async function inspectClaudeLocalCapability(path, authenticationCommand, custody
|
|
|
11442
11580
|
return localCapabilityDescriptorMatches(current.encoded, claudeLocalCapabilityDescriptor(authenticationCommand)) ? [] : ["local_capability_drifted"];
|
|
11443
11581
|
}
|
|
11444
11582
|
async function removeClaudeLocalCapability(path, authenticationCommand, custody = {}) {
|
|
11445
|
-
if (!
|
|
11583
|
+
if (!isAbsolute8(path)) throw new ClaudeHostError("configuration", "Claude local capability path must be absolute.");
|
|
11446
11584
|
let descriptor2;
|
|
11447
11585
|
try {
|
|
11448
11586
|
validateHostCommandVector(authenticationCommand);
|
|
@@ -11582,7 +11720,7 @@ function eventEntries(hooks, event) {
|
|
|
11582
11720
|
}
|
|
11583
11721
|
function validateOptions(options) {
|
|
11584
11722
|
const settingsPath = options.settings_path ?? resolveClaudeSettingsPath(options.claude_home);
|
|
11585
|
-
if (!
|
|
11723
|
+
if (!isAbsolute8(settingsPath) || !isAbsolute8(options.permission_ownership_path) || !isAbsolute8(options.hook_executable) || options.hook_executable.includes("\0") || options.hook_executable.includes("\n") || options.hook_executable.includes('"')) throw new ClaudeHostError("configuration", "Claude installer paths must be absolute and shell-safe.");
|
|
11586
11724
|
try {
|
|
11587
11725
|
const command = resolveHookCommand(options);
|
|
11588
11726
|
validateHostCommandVector(command);
|
|
@@ -11667,27 +11805,32 @@ var import_toml = __toESM(require_toml(), 1);
|
|
|
11667
11805
|
import { createHash as createHash14 } from "node:crypto";
|
|
11668
11806
|
import { copyFile as copyFile3, lstat as lstat9, mkdir as mkdir9, open as open6, readFile as readFile3, rename as rename5, unlink as unlink8 } from "node:fs/promises";
|
|
11669
11807
|
import { homedir as homedir3 } from "node:os";
|
|
11670
|
-
import { basename as basename2, dirname as dirname11, isAbsolute as
|
|
11808
|
+
import { basename as basename2, dirname as dirname11, isAbsolute as isAbsolute9, join as join17 } from "node:path";
|
|
11671
11809
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
11672
11810
|
|
|
11673
11811
|
// host/codex/src/codex-sandbox-rule.ts
|
|
11674
|
-
import { join as
|
|
11812
|
+
import { join as join15 } from "node:path";
|
|
11675
11813
|
var CODEX_RULES_DIRECTORY = "rules";
|
|
11676
11814
|
var CODEX_SANDBOX_RULE_FILE = "ceal-host.rules";
|
|
11677
11815
|
var CODEX_SANDBOX_RULE_MARKER = `# ceal-owner: ${CODEX_HOOK_OWNER}`;
|
|
11678
11816
|
var CODEX_SANDBOX_RULE_JUSTIFICATION = "Ceal client: needs its session store outside the workspace, network access to the Ceal Gateway, and the Ceal Host relay socket.";
|
|
11679
11817
|
function codexSandboxRulePath(codexHome) {
|
|
11680
|
-
return
|
|
11818
|
+
return join15(codexHome, CODEX_RULES_DIRECTORY, CODEX_SANDBOX_RULE_FILE);
|
|
11819
|
+
}
|
|
11820
|
+
function codexClientExecutableSpellings(platform) {
|
|
11821
|
+
return platform === "win32" ? [CEAL_SESSION_ENTRY_INVOCATION, `${CEAL_SESSION_ENTRY_INVOCATION}.cmd`] : [CEAL_SESSION_ENTRY_INVOCATION];
|
|
11681
11822
|
}
|
|
11682
|
-
function codexSandboxRuleText() {
|
|
11823
|
+
function codexSandboxRuleText(platform = process.platform) {
|
|
11683
11824
|
return [
|
|
11684
11825
|
CODEX_SANDBOX_RULE_MARKER,
|
|
11685
11826
|
"# Written by `ceal-host install` and removed by `ceal-host uninstall`; edits here are overwritten. Put your own rules in another .rules file.",
|
|
11686
|
-
|
|
11687
|
-
|
|
11688
|
-
|
|
11689
|
-
|
|
11690
|
-
|
|
11827
|
+
...codexClientExecutableSpellings(platform).flatMap((spelling) => [
|
|
11828
|
+
"prefix_rule(",
|
|
11829
|
+
` pattern = [${JSON.stringify(spelling)}],`,
|
|
11830
|
+
' decision = "allow",',
|
|
11831
|
+
` justification = ${JSON.stringify(CODEX_SANDBOX_RULE_JUSTIFICATION)},`,
|
|
11832
|
+
")"
|
|
11833
|
+
]),
|
|
11691
11834
|
""
|
|
11692
11835
|
].join("\n");
|
|
11693
11836
|
}
|
|
@@ -11700,6 +11843,191 @@ function codexSandboxRuleReasons(state) {
|
|
|
11700
11843
|
return state === "installed" ? [] : [`sandbox_rule_${state}`];
|
|
11701
11844
|
}
|
|
11702
11845
|
|
|
11846
|
+
// host/codex/src/codex-hook-trust-verdict.ts
|
|
11847
|
+
import { spawn } from "node:child_process";
|
|
11848
|
+
import { constants as constants12, access } from "node:fs/promises";
|
|
11849
|
+
import { delimiter, join as join16 } from "node:path";
|
|
11850
|
+
var PRODUCER_EVENT_BY_NAME = {
|
|
11851
|
+
sessionStart: "SessionStart",
|
|
11852
|
+
userPromptSubmit: "UserPromptSubmit"
|
|
11853
|
+
};
|
|
11854
|
+
function summarizeCodexProducerTrust(response2, ownerMarker = CODEX_HOOK_OWNER) {
|
|
11855
|
+
const hooks = parseHooksListResponse(response2);
|
|
11856
|
+
if (hooks === void 0) return { available: false };
|
|
11857
|
+
const reasons = [];
|
|
11858
|
+
for (const event of CODEX_HOOK_EVENTS) {
|
|
11859
|
+
const owned = hooks.filter((hook) => PRODUCER_EVENT_BY_NAME[hook.event_name] === event && hook.command !== void 0 && hook.command.includes(`--ceal-hook-owner=${ownerMarker}`));
|
|
11860
|
+
if (owned.length === 0) {
|
|
11861
|
+
reasons.push("hook_untrusted_review_required");
|
|
11862
|
+
continue;
|
|
11863
|
+
}
|
|
11864
|
+
for (const hook of owned) {
|
|
11865
|
+
if (hook.enabled === false) reasons.push("hook_disabled");
|
|
11866
|
+
else if (hook.trust_status === "trusted") continue;
|
|
11867
|
+
else if (hook.trust_status === "modified") reasons.push(`hook_trust_modified:${event}`);
|
|
11868
|
+
else reasons.push("hook_untrusted_review_required");
|
|
11869
|
+
}
|
|
11870
|
+
}
|
|
11871
|
+
return { available: true, reasons, proven_trusted: reasons.length === 0 };
|
|
11872
|
+
}
|
|
11873
|
+
function parseHooksListResponse(response2) {
|
|
11874
|
+
if (!isRecord10(response2) || !Array.isArray(response2.data)) return void 0;
|
|
11875
|
+
const verdicts = [];
|
|
11876
|
+
for (const entry of response2.data) {
|
|
11877
|
+
if (!isRecord10(entry) || !Array.isArray(entry.hooks)) return void 0;
|
|
11878
|
+
for (const hook of entry.hooks) {
|
|
11879
|
+
const parsed = parseHookMetadata(hook);
|
|
11880
|
+
if (parsed === void 0) return void 0;
|
|
11881
|
+
verdicts.push(parsed);
|
|
11882
|
+
}
|
|
11883
|
+
}
|
|
11884
|
+
return verdicts;
|
|
11885
|
+
}
|
|
11886
|
+
function parseHookMetadata(hook) {
|
|
11887
|
+
if (!isRecord10(hook)) return void 0;
|
|
11888
|
+
const eventName = requiredString(hook, "eventName");
|
|
11889
|
+
const trustStatus = requiredString(hook, "trustStatus");
|
|
11890
|
+
const enabled = requiredBoolean(hook, "enabled");
|
|
11891
|
+
const command = optionalString(hook, "command");
|
|
11892
|
+
const key = optionalString(hook, "key");
|
|
11893
|
+
const sourcePath = optionalString(hook, "sourcePath");
|
|
11894
|
+
if (eventName === void 0 || trustStatus === void 0 || enabled === void 0) return void 0;
|
|
11895
|
+
if (command === INVALID_FIELD || key === INVALID_FIELD || sourcePath === INVALID_FIELD) return void 0;
|
|
11896
|
+
return {
|
|
11897
|
+
event_name: eventName,
|
|
11898
|
+
...key === void 0 ? {} : { key },
|
|
11899
|
+
enabled,
|
|
11900
|
+
trust_status: trustStatus,
|
|
11901
|
+
...command === void 0 ? {} : { command },
|
|
11902
|
+
...sourcePath === void 0 ? {} : { source_path: sourcePath }
|
|
11903
|
+
};
|
|
11904
|
+
}
|
|
11905
|
+
var INVALID_FIELD = /* @__PURE__ */ Symbol("invalid-field");
|
|
11906
|
+
function requiredString(record7, field) {
|
|
11907
|
+
const value = record7[field];
|
|
11908
|
+
return typeof value === "string" ? value : void 0;
|
|
11909
|
+
}
|
|
11910
|
+
function requiredBoolean(record7, field) {
|
|
11911
|
+
const value = record7[field];
|
|
11912
|
+
return typeof value === "boolean" ? value : void 0;
|
|
11913
|
+
}
|
|
11914
|
+
function optionalString(record7, field) {
|
|
11915
|
+
const value = record7[field];
|
|
11916
|
+
if (value === void 0) return void 0;
|
|
11917
|
+
return typeof value === "string" ? value : INVALID_FIELD;
|
|
11918
|
+
}
|
|
11919
|
+
async function readCodexHookVerdictsResponse(options = {}) {
|
|
11920
|
+
const executable = options.codex_executable ?? await resolveCodexExecutableOnPath();
|
|
11921
|
+
if (executable === void 0) return void 0;
|
|
11922
|
+
const spawnAppServer = options.spawn_app_server ?? defaultSpawnAppServer;
|
|
11923
|
+
const timeoutMs = options.timeout_ms ?? 3e4;
|
|
11924
|
+
try {
|
|
11925
|
+
return await queryHooksList(spawnAppServer, executable, options.cwd ?? process.cwd(), timeoutMs, options.codex_home);
|
|
11926
|
+
} catch {
|
|
11927
|
+
return void 0;
|
|
11928
|
+
}
|
|
11929
|
+
}
|
|
11930
|
+
async function queryHooksList(spawnAppServer, executable, cwd, timeoutMs, codexHome) {
|
|
11931
|
+
const child = spawnAppServer(executable, ["app-server"], { env: codexHome === void 0 ? { ...process.env } : { ...process.env, [CODEX_HOME_ENVIRONMENT]: codexHome } });
|
|
11932
|
+
const done = new Promise((resolve) => {
|
|
11933
|
+
let buffer = "";
|
|
11934
|
+
const finish = (value) => {
|
|
11935
|
+
removeListeners();
|
|
11936
|
+
resolve(value);
|
|
11937
|
+
};
|
|
11938
|
+
const timer = setTimeout(() => finish(void 0), timeoutMs);
|
|
11939
|
+
const removeListeners = () => {
|
|
11940
|
+
clearTimeout(timer);
|
|
11941
|
+
child.stdout.removeAllListeners("data");
|
|
11942
|
+
child.stderr.removeAllListeners("data");
|
|
11943
|
+
child.stdin.removeAllListeners("error");
|
|
11944
|
+
child.removeAllListeners("error");
|
|
11945
|
+
child.removeAllListeners("close");
|
|
11946
|
+
};
|
|
11947
|
+
const onData = (chunk) => {
|
|
11948
|
+
buffer += chunk.toString("utf8");
|
|
11949
|
+
if (buffer.length > 4 * 1024 * 1024) {
|
|
11950
|
+
kill(child);
|
|
11951
|
+
finish(void 0);
|
|
11952
|
+
return;
|
|
11953
|
+
}
|
|
11954
|
+
let newline;
|
|
11955
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
11956
|
+
const line = buffer.slice(0, newline).trim();
|
|
11957
|
+
buffer = buffer.slice(newline + 1);
|
|
11958
|
+
if (line.length === 0) continue;
|
|
11959
|
+
let message;
|
|
11960
|
+
try {
|
|
11961
|
+
message = JSON.parse(line);
|
|
11962
|
+
} catch {
|
|
11963
|
+
continue;
|
|
11964
|
+
}
|
|
11965
|
+
if (isRecord10(message) && message.id === 3) {
|
|
11966
|
+
kill(child);
|
|
11967
|
+
finish(isRecord10(message) && "result" in message ? message.result : void 0);
|
|
11968
|
+
return;
|
|
11969
|
+
}
|
|
11970
|
+
}
|
|
11971
|
+
};
|
|
11972
|
+
child.stdout.on("data", onData);
|
|
11973
|
+
child.stderr.on("data", () => {
|
|
11974
|
+
});
|
|
11975
|
+
child.stdin.on("error", () => finish(void 0));
|
|
11976
|
+
child.on("error", () => finish(void 0));
|
|
11977
|
+
child.on("close", () => finish(void 0));
|
|
11978
|
+
try {
|
|
11979
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { clientInfo: { name: "ceal-host", version: "0.0.0" } } })}
|
|
11980
|
+
`);
|
|
11981
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "initialized", params: {} })}
|
|
11982
|
+
`);
|
|
11983
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 3, method: "hooks/list", params: { cwds: [cwd] } })}
|
|
11984
|
+
`);
|
|
11985
|
+
} catch {
|
|
11986
|
+
finish(void 0);
|
|
11987
|
+
}
|
|
11988
|
+
});
|
|
11989
|
+
try {
|
|
11990
|
+
return await done;
|
|
11991
|
+
} finally {
|
|
11992
|
+
kill(child);
|
|
11993
|
+
}
|
|
11994
|
+
}
|
|
11995
|
+
function kill(child) {
|
|
11996
|
+
try {
|
|
11997
|
+
child.kill();
|
|
11998
|
+
} catch {
|
|
11999
|
+
}
|
|
12000
|
+
}
|
|
12001
|
+
function defaultSpawnAppServer(executable, args, options) {
|
|
12002
|
+
const invocation = process.platform === "win32" && executable.toLowerCase().endsWith(".cmd") ? hostScriptLauncherInvocation(executable, args, "cmd", process.platform, options.env) : { executable, args };
|
|
12003
|
+
const child = spawn(invocation.executable, [...invocation.args], { env: { ...options.env, ...invocation.environment }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, ...invocation.windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments } });
|
|
12004
|
+
if (child.stdin === null || child.stdout === null || child.stderr === null) throw new Error("Codex app-server stdio is unavailable.");
|
|
12005
|
+
return { stdin: child.stdin, stdout: child.stdout, stderr: child.stderr, kill: () => {
|
|
12006
|
+
child.stdin?.destroy();
|
|
12007
|
+
return child.kill();
|
|
12008
|
+
}, on: child.on.bind(child), removeAllListeners: child.removeAllListeners.bind(child) };
|
|
12009
|
+
}
|
|
12010
|
+
async function resolveCodexExecutableOnPath() {
|
|
12011
|
+
const pathValue = process.env.PATH;
|
|
12012
|
+
if (pathValue === void 0 || pathValue.length === 0) return void 0;
|
|
12013
|
+
const candidates = process.platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
|
|
12014
|
+
for (const directory of pathValue.split(delimiter)) {
|
|
12015
|
+
if (directory.length === 0) continue;
|
|
12016
|
+
for (const candidate of candidates) {
|
|
12017
|
+
const full = join16(directory, candidate);
|
|
12018
|
+
try {
|
|
12019
|
+
await access(full, process.platform === "win32" ? constants12.F_OK : constants12.X_OK);
|
|
12020
|
+
return full;
|
|
12021
|
+
} catch {
|
|
12022
|
+
}
|
|
12023
|
+
}
|
|
12024
|
+
}
|
|
12025
|
+
return void 0;
|
|
12026
|
+
}
|
|
12027
|
+
function isRecord10(value) {
|
|
12028
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12029
|
+
}
|
|
12030
|
+
|
|
11703
12031
|
// host/codex/src/codex-installer.ts
|
|
11704
12032
|
var CODEX_HOOK_COMMAND_MAX_CHARACTERS = 4096;
|
|
11705
12033
|
function codexHooksInstalled(doctor) {
|
|
@@ -11711,7 +12039,7 @@ function resolveRepoCodexInvocationAuthenticationExecutable() {
|
|
|
11711
12039
|
function resolveCodexHooksConfigPath(codexHome) {
|
|
11712
12040
|
const home = codexHome ?? resolveCodexHome(process.env, homedir3());
|
|
11713
12041
|
if (typeof home !== "string" || home.length === 0) throw new CodexHostAdapterError("configuration", "Codex home is unavailable.");
|
|
11714
|
-
return
|
|
12042
|
+
return join17(home, CODEX_HOOKS_CONFIG_FILE);
|
|
11715
12043
|
}
|
|
11716
12044
|
async function installCodexHooks(options) {
|
|
11717
12045
|
const normalized = validateInstallerOptions(options);
|
|
@@ -11751,32 +12079,34 @@ async function doctorCodexHooks(options) {
|
|
|
11751
12079
|
const configPath = options.config_path ?? resolveCodexHooksConfigPath(options.codex_home);
|
|
11752
12080
|
const trustPath = codexConfigPath(configPath);
|
|
11753
12081
|
const hookCommand2 = resolveHookCommand2(options);
|
|
12082
|
+
const versionHint = codexVersionHint(options.codex_version);
|
|
12083
|
+
const withVersionHint = (result) => versionHint === void 0 ? result : { ...result, codex_version_hint: versionHint };
|
|
11754
12084
|
const invalidCommand = invalidHookCommandDoctorResult(hookCommand2, configPath, trustPath);
|
|
11755
|
-
if (invalidCommand !== null) return invalidCommand;
|
|
12085
|
+
if (invalidCommand !== null) return withVersionHint(invalidCommand);
|
|
11756
12086
|
const { authenticationCommand, localCapabilityPath } = resolveLocalCapabilityInstallation(options);
|
|
11757
12087
|
const unsupported = unsupportedDoctorResult(options, configPath, trustPath);
|
|
11758
|
-
if (unsupported !== null) return unsupported;
|
|
12088
|
+
if (unsupported !== null) return withVersionHint(unsupported);
|
|
11759
12089
|
const current = await readDoctorConfig(configPath, trustPath);
|
|
11760
|
-
if (current.status !== "ready") return current.result;
|
|
12090
|
+
if (current.status !== "ready") return withVersionHint(current.result);
|
|
11761
12091
|
const config = current.result;
|
|
11762
12092
|
const configured = CODEX_HOOK_EVENTS.filter((event) => ownedEntries2(config, event).length > 0);
|
|
11763
12093
|
const missing = CODEX_HOOK_EVENTS.filter((event) => ownedEntries2(config, event).length === 0);
|
|
11764
12094
|
let trust;
|
|
11765
12095
|
try {
|
|
11766
|
-
trust = await inspectCodexTrust(configPath, config, hookCommand2);
|
|
12096
|
+
trust = await inspectCodexTrust(configPath, config, hookCommand2, options.hook_verdicts);
|
|
11767
12097
|
} catch (error) {
|
|
11768
|
-
if (error instanceof CodexHostAdapterError && error.code === "configuration") return doctorResult("malformed", configPath, trustPath, TRUST_UNAVAILABLE, configured, missing, ["malformed_config"]);
|
|
12098
|
+
if (error instanceof CodexHostAdapterError && error.code === "configuration") return withVersionHint(doctorResult("malformed", configPath, trustPath, TRUST_UNAVAILABLE, configured, missing, ["malformed_config"]));
|
|
11769
12099
|
throw error;
|
|
11770
12100
|
}
|
|
11771
12101
|
const sandboxRule = codexSandboxRuleReasons(await readCodexSandboxRuleState(codexSandboxRulePath(dirname11(configPath))));
|
|
11772
12102
|
const reasons = [...trust.reasons, ...await inspectCodexLocalCapability(localCapabilityPath, authenticationCommand, options.secure_file_custody), ...sandboxRule];
|
|
11773
12103
|
const status = codexDoctorStatus(missing, trust, reasons);
|
|
11774
|
-
return doctorResult(status, configPath, trustPath, trust, configured, missing, reasons);
|
|
12104
|
+
return withVersionHint(doctorResult(status, configPath, trustPath, trust, configured, missing, reasons));
|
|
11775
12105
|
}
|
|
11776
12106
|
function codexDoctorStatus(missing, trust, reasons) {
|
|
11777
12107
|
if (missing.length > 0) return "drifted";
|
|
11778
12108
|
if (trust.state === "trusted" && reasons.length === 0) return "ready";
|
|
11779
|
-
return reasons.every((reason) => reason === "hook_untrusted_review_required") ? "installed" : "drifted";
|
|
12109
|
+
return reasons.every((reason) => reason === "hook_untrusted_review_required" || reason.startsWith("hook_trust_modified:")) ? "installed" : "drifted";
|
|
11780
12110
|
}
|
|
11781
12111
|
function invalidHookCommandDoctorResult(command, configPath, trustPath) {
|
|
11782
12112
|
try {
|
|
@@ -11801,7 +12131,7 @@ async function readDoctorConfig(configPath, trustPath) {
|
|
|
11801
12131
|
}
|
|
11802
12132
|
function validateInstallerOptions(options) {
|
|
11803
12133
|
const configPath = options.config_path ?? resolveCodexHooksConfigPath(options.codex_home);
|
|
11804
|
-
if (!
|
|
12134
|
+
if (!isAbsolute9(configPath) || typeof options.hook_executable !== "string" || !isAbsolute9(options.hook_executable)) throw new CodexHostAdapterError("configuration", "Codex installer paths must be absolute.");
|
|
11805
12135
|
requireLocalCapabilityPath(options.local_capability_path);
|
|
11806
12136
|
validateOptionalInstallerPaths(options);
|
|
11807
12137
|
try {
|
|
@@ -11816,11 +12146,11 @@ function resolveHookCommand2(options) {
|
|
|
11816
12146
|
return { executable: options.hook_executable, args: options.hook_arguments ?? [] };
|
|
11817
12147
|
}
|
|
11818
12148
|
function validateOptionalInstallerPaths(options) {
|
|
11819
|
-
if (options.invocation_authentication_executable !== void 0 && !
|
|
12149
|
+
if (options.invocation_authentication_executable !== void 0 && !isAbsolute9(options.invocation_authentication_executable)) throw new CodexHostAdapterError("configuration", "Codex invocation authentication executable path must be absolute.");
|
|
11820
12150
|
}
|
|
11821
12151
|
var CODEX_LOCAL_CAPABILITY_OWNER = CODEX_HOOK_OWNER;
|
|
11822
12152
|
function requireLocalCapabilityPath(value) {
|
|
11823
|
-
if (typeof value !== "string" || !
|
|
12153
|
+
if (typeof value !== "string" || !isAbsolute9(value)) throw new CodexHostAdapterError("configuration", "Codex local capability path must be absolute.");
|
|
11824
12154
|
return value;
|
|
11825
12155
|
}
|
|
11826
12156
|
function resolveLocalCapabilityInstallation(options) {
|
|
@@ -11952,7 +12282,7 @@ async function readConfig(path) {
|
|
|
11952
12282
|
const stats = await lstat9(path);
|
|
11953
12283
|
if (!stats.isFile() || stats.isSymbolicLink()) throw configurationError("Codex hooks configuration is malformed.");
|
|
11954
12284
|
const value = JSON.parse(await readFile3(path, "utf8"));
|
|
11955
|
-
if (!
|
|
12285
|
+
if (!isRecord11(value)) throw configurationError("Codex hooks configuration is malformed.");
|
|
11956
12286
|
validateHooksConfig(value);
|
|
11957
12287
|
return value;
|
|
11958
12288
|
} catch (error) {
|
|
@@ -11973,7 +12303,7 @@ function validateHooksConfig(config) {
|
|
|
11973
12303
|
if (Object.keys(config).some((key) => key !== "description" && key !== "hooks")) throw configurationError("Codex hooks configuration is malformed.");
|
|
11974
12304
|
if (config.description !== void 0 && typeof config.description !== "string") throw configurationError("Codex hooks configuration is malformed.");
|
|
11975
12305
|
if (config.hooks === void 0) return;
|
|
11976
|
-
if (!
|
|
12306
|
+
if (!isRecord11(config.hooks)) throw configurationError("Codex hooks configuration is malformed.");
|
|
11977
12307
|
for (const event of CODEX_HOOK_EVENTS) {
|
|
11978
12308
|
const value = config.hooks[event];
|
|
11979
12309
|
if (value === void 0) continue;
|
|
@@ -11982,7 +12312,7 @@ function validateHooksConfig(config) {
|
|
|
11982
12312
|
}
|
|
11983
12313
|
}
|
|
11984
12314
|
function validateHookEntry(entry) {
|
|
11985
|
-
if (!
|
|
12315
|
+
if (!isRecord11(entry)) throw configurationError("Codex hook entry is malformed.");
|
|
11986
12316
|
if (Array.isArray(entry.hooks)) {
|
|
11987
12317
|
if (entry.matcher !== void 0 && typeof entry.matcher !== "string") throw configurationError("Codex hook matcher is malformed.");
|
|
11988
12318
|
for (const handler of entry.hooks) validateHookHandler(handler);
|
|
@@ -11991,7 +12321,7 @@ function validateHookEntry(entry) {
|
|
|
11991
12321
|
throw configurationError("Codex hook entry is malformed.");
|
|
11992
12322
|
}
|
|
11993
12323
|
function validateHookHandler(entry) {
|
|
11994
|
-
if (!
|
|
12324
|
+
if (!isRecord11(entry) || typeof entry.type !== "string") throw configurationError("Codex hook handler is malformed.");
|
|
11995
12325
|
if (entry.type === "command") return validateCommandHookHandler(entry);
|
|
11996
12326
|
if (entry.type === "mcp_tool") return validateMcpHookHandler(entry);
|
|
11997
12327
|
if (entry.type === "prompt" || entry.type === "agent") return;
|
|
@@ -12021,9 +12351,9 @@ function validateOptionalBoolean(value, message) {
|
|
|
12021
12351
|
function normalizeHookGroups(entries) {
|
|
12022
12352
|
const groups = [];
|
|
12023
12353
|
for (const entry of entries) {
|
|
12024
|
-
if (!
|
|
12354
|
+
if (!isRecord11(entry)) throw configurationError("Codex hook entry is malformed.");
|
|
12025
12355
|
if (Array.isArray(entry.hooks)) {
|
|
12026
|
-
groups.push({ ...entry, hooks: entry.hooks.filter(
|
|
12356
|
+
groups.push({ ...entry, hooks: entry.hooks.filter(isRecord11) });
|
|
12027
12357
|
continue;
|
|
12028
12358
|
}
|
|
12029
12359
|
throw configurationError("Codex hook entry is malformed.");
|
|
@@ -12034,7 +12364,7 @@ function ownedHookEntry(command, event) {
|
|
|
12034
12364
|
return { type: "command", command: hookCommand(command, event, "posix"), commandWindows: hookCommand(command, event, "windows"), async: false };
|
|
12035
12365
|
}
|
|
12036
12366
|
function mergeOwnedHooks2(config, command) {
|
|
12037
|
-
const hooks =
|
|
12367
|
+
const hooks = isRecord11(config.hooks) ? { ...config.hooks } : {};
|
|
12038
12368
|
for (const event of CODEX_HOOK_EVENTS) {
|
|
12039
12369
|
const groups = Array.isArray(hooks[event]) ? normalizeHookGroups(hooks[event]) : [];
|
|
12040
12370
|
const retained = groups.map((group) => ({ ...group, hooks: group.hooks.filter((entry) => !ownedHookHandler(entry)) })).filter((group) => group.hooks.length > 0);
|
|
@@ -12044,7 +12374,7 @@ function mergeOwnedHooks2(config, command) {
|
|
|
12044
12374
|
return { ...config, hooks };
|
|
12045
12375
|
}
|
|
12046
12376
|
function removeOwnedHooks2(config) {
|
|
12047
|
-
if (!
|
|
12377
|
+
if (!isRecord11(config.hooks)) return config;
|
|
12048
12378
|
const hooks = { ...config.hooks };
|
|
12049
12379
|
for (const event of CODEX_HOOK_EVENTS) {
|
|
12050
12380
|
removeOwnedEvent(hooks, event);
|
|
@@ -12058,7 +12388,7 @@ function removeOwnedEvent(hooks, event) {
|
|
|
12058
12388
|
else hooks[event] = retained;
|
|
12059
12389
|
}
|
|
12060
12390
|
function ownedEntries2(config, event) {
|
|
12061
|
-
if (!
|
|
12391
|
+
if (!isRecord11(config.hooks) || !Array.isArray(config.hooks[event])) return [];
|
|
12062
12392
|
return normalizeHookGroups(config.hooks[event]).flatMap((group) => group.hooks.filter(ownedHookHandler));
|
|
12063
12393
|
}
|
|
12064
12394
|
function ownedHookHandler(entry) {
|
|
@@ -12086,7 +12416,7 @@ async function writeAtomicJson3(path, value) {
|
|
|
12086
12416
|
}
|
|
12087
12417
|
async function writeAtomicText(path, text) {
|
|
12088
12418
|
await mkdir9(dirname11(path), { recursive: true, mode: 448 });
|
|
12089
|
-
const temp =
|
|
12419
|
+
const temp = join17(dirname11(path), `.${basename2(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
|
|
12090
12420
|
let ownsTemp = false;
|
|
12091
12421
|
try {
|
|
12092
12422
|
const handle = await open6(temp, "wx", 384);
|
|
@@ -12124,14 +12454,19 @@ async function backupTextFile(path) {
|
|
|
12124
12454
|
}
|
|
12125
12455
|
}
|
|
12126
12456
|
var TRUST_UNAVAILABLE = { state: "unavailable", codex_trust: "unavailable" };
|
|
12127
|
-
async function inspectCodexTrust(configPath, config, command) {
|
|
12457
|
+
async function inspectCodexTrust(configPath, config, command, hookVerdicts) {
|
|
12128
12458
|
const executable = await inspectHookExecutable(command.executable);
|
|
12129
12459
|
const owned = CODEX_HOOK_EVENTS.flatMap((event) => ownedHookLocations(config, event));
|
|
12130
12460
|
if (owned.length === 0) return { ...TRUST_UNAVAILABLE, reasons: executable };
|
|
12461
|
+
const verdict = summarizeCodexProducerTrust(hookVerdicts);
|
|
12462
|
+
if (verdict.available) {
|
|
12463
|
+
const reasons2 = [...verdict.reasons, ...inspectHookCommands(config, command), ...executable];
|
|
12464
|
+
return { ...trustInspection(reasons2), codex_trust: verdict.proven_trusted ? "trusted" : "awaiting_codex_approval" };
|
|
12465
|
+
}
|
|
12131
12466
|
const codexConfig = await readTrustConfig(configPath);
|
|
12132
12467
|
const states = codexConfig === null ? /* @__PURE__ */ new Map() : codexHookStates(codexConfig);
|
|
12133
12468
|
const reasons = [...inspectHookStates(configPath, owned, states), ...inspectHookCommands(config, command), ...executable];
|
|
12134
|
-
return { ...trustInspection(reasons), codex_trust: reasons.includes("hook_untrusted_review_required") ? "awaiting_codex_approval" : "
|
|
12469
|
+
return { ...trustInspection(reasons), codex_trust: reasons.includes("hook_untrusted_review_required") ? "awaiting_codex_approval" : "unproven" };
|
|
12135
12470
|
}
|
|
12136
12471
|
function inspectHookCommands(config, command) {
|
|
12137
12472
|
return CODEX_HOOK_EVENTS.flatMap((event) => {
|
|
@@ -12176,11 +12511,11 @@ async function inspectHookExecutable(path) {
|
|
|
12176
12511
|
}
|
|
12177
12512
|
}
|
|
12178
12513
|
function trustInspection(reasons) {
|
|
12179
|
-
if (reasons.some((reason) => reason === "hook_disabled" || reason === "hook_executable_unavailable" || reason === "duplicate_owned_hook")) return { state: "modified", reasons };
|
|
12514
|
+
if (reasons.some((reason) => reason === "hook_disabled" || reason === "hook_executable_unavailable" || reason === "duplicate_owned_hook" || reason.startsWith("hook_trust_modified:"))) return { state: "modified", reasons };
|
|
12180
12515
|
return reasons.length === 0 ? { state: "trusted", reasons } : { state: "untrusted", reasons };
|
|
12181
12516
|
}
|
|
12182
12517
|
function ownedHookLocations(config, event) {
|
|
12183
|
-
if (!
|
|
12518
|
+
if (!isRecord11(config.hooks) || !Array.isArray(config.hooks[event])) return [];
|
|
12184
12519
|
return normalizeHookGroups(config.hooks[event]).flatMap((group, groupIndex) => group.hooks.flatMap((handler, handlerIndex) => ownedHookHandler(handler) ? [{ event, group_index: groupIndex, handler_index: handlerIndex, handler }] : []));
|
|
12185
12520
|
}
|
|
12186
12521
|
async function readCodexConfig(path) {
|
|
@@ -12188,7 +12523,7 @@ async function readCodexConfig(path) {
|
|
|
12188
12523
|
const stats = await lstat9(path);
|
|
12189
12524
|
if (!stats.isFile() || stats.isSymbolicLink()) throw configurationError("Codex config.toml is malformed.");
|
|
12190
12525
|
const value = import_toml.default.parse(await readFile3(path, "utf8"));
|
|
12191
|
-
if (!
|
|
12526
|
+
if (!isRecord11(value)) throw configurationError("Codex config.toml is malformed.");
|
|
12192
12527
|
return value;
|
|
12193
12528
|
} catch (error) {
|
|
12194
12529
|
if (error instanceof CodexHostAdapterError) throw error;
|
|
@@ -12201,20 +12536,20 @@ function codexHookStates(config) {
|
|
|
12201
12536
|
if (hooks === void 0) return /* @__PURE__ */ new Map();
|
|
12202
12537
|
const state = hooks.state;
|
|
12203
12538
|
if (state === void 0) return /* @__PURE__ */ new Map();
|
|
12204
|
-
if (!
|
|
12539
|
+
if (!isRecord11(state)) throw configurationError("Codex config.toml hook state is malformed.");
|
|
12205
12540
|
return new Map(Object.entries(state).map(([key, entry]) => [key, parseCodexHookState(entry)]));
|
|
12206
12541
|
}
|
|
12207
12542
|
function codexHooksTable(config) {
|
|
12208
12543
|
if (config.hooks === void 0) return void 0;
|
|
12209
|
-
if (!
|
|
12544
|
+
if (!isRecord11(config.hooks)) throw configurationError("Codex config.toml hook state is malformed.");
|
|
12210
12545
|
return config.hooks;
|
|
12211
12546
|
}
|
|
12212
12547
|
function parseCodexHookState(entry) {
|
|
12213
|
-
if (!
|
|
12548
|
+
if (!isRecord11(entry) || entry.enabled !== void 0 && typeof entry.enabled !== "boolean" || entry.trusted_hash !== void 0 && typeof entry.trusted_hash !== "string") throw configurationError("Codex config.toml hook state is malformed.");
|
|
12214
12549
|
return { ...entry.enabled === void 0 ? {} : { enabled: entry.enabled }, ...entry.trusted_hash === void 0 ? {} : { trusted_hash: entry.trusted_hash } };
|
|
12215
12550
|
}
|
|
12216
12551
|
function codexConfigPath(configPath) {
|
|
12217
|
-
return
|
|
12552
|
+
return join17(dirname11(configPath), "config.toml");
|
|
12218
12553
|
}
|
|
12219
12554
|
function codexHookStateKey(configPath, event, groupIndex, handlerIndex) {
|
|
12220
12555
|
return `${configPath}:${hookEventKeyLabel(event)}:${groupIndex}:${handlerIndex}`;
|
|
@@ -12225,11 +12560,11 @@ function hookEventKeyLabel(event) {
|
|
|
12225
12560
|
function doctorResult(status, configPath, trustPath, trust, configured, missing, reasons) {
|
|
12226
12561
|
return { status, config_path: configPath, trust_path: trustPath, trust_state: trust.state, codex_trust: trust.codex_trust, feature: CODEX_HOOK_FEATURE, latest_tested_version: CODEX_CLI_VERSION, version_policy: "owned_schema_compatible", configured_events: configured, missing_events: missing, drift_reasons: reasons };
|
|
12227
12562
|
}
|
|
12228
|
-
function
|
|
12563
|
+
function isRecord11(value) {
|
|
12229
12564
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12230
12565
|
}
|
|
12231
12566
|
function isNotFound4(error) {
|
|
12232
|
-
return
|
|
12567
|
+
return isRecord11(error) && error.code === "ENOENT";
|
|
12233
12568
|
}
|
|
12234
12569
|
function storageError2(message) {
|
|
12235
12570
|
return new CodexHostAdapterError("storage", message);
|
|
@@ -12347,6 +12682,7 @@ async function reconcileProducerHooks(producer, entry, homes, repaired = false)
|
|
|
12347
12682
|
async function inspectProducerHooks(producer, entry, homes) {
|
|
12348
12683
|
if (producer === "codex") {
|
|
12349
12684
|
await readHostProducerConfig(CODEX_PRODUCER_DESCRIPTOR, entry.configPath, process.platform, homes.custody);
|
|
12685
|
+
const hook_verdicts = await readCodexHookVerdictsResponse({ ...homes.codex_home === void 0 ? {} : { codex_home: homes.codex_home } });
|
|
12350
12686
|
const result2 = await doctorCodexHooks({
|
|
12351
12687
|
local_capability_path: hostLocalCapabilityPath(homes.user_home, "codex"),
|
|
12352
12688
|
secure_file_custody: homes.custody,
|
|
@@ -12354,7 +12690,8 @@ async function inspectProducerHooks(producer, entry, homes) {
|
|
|
12354
12690
|
hook_executable: entry.hook.executable,
|
|
12355
12691
|
hook_arguments: entry.hook.args,
|
|
12356
12692
|
invocation_authentication_executable: entry.authentication.executable,
|
|
12357
|
-
invocation_authentication_arguments: entry.authentication.args
|
|
12693
|
+
invocation_authentication_arguments: entry.authentication.args,
|
|
12694
|
+
hook_verdicts
|
|
12358
12695
|
});
|
|
12359
12696
|
return codexHooksInstalled(result2) ? null : { status: result2.status, reasons: result2.drift_reasons };
|
|
12360
12697
|
}
|
|
@@ -12373,7 +12710,7 @@ async function validatePrivateRuntimePaths(paths, selection) {
|
|
|
12373
12710
|
}
|
|
12374
12711
|
}
|
|
12375
12712
|
function claudePermissionOwnershipPath(stateRoot) {
|
|
12376
|
-
return
|
|
12713
|
+
return join18(stateRoot, "ownership", "claude", "permission-ownership.json");
|
|
12377
12714
|
}
|
|
12378
12715
|
async function assertRegularRuntimeFile(path) {
|
|
12379
12716
|
let info;
|
|
@@ -12394,8 +12731,8 @@ function selectedProducers(selection) {
|
|
|
12394
12731
|
|
|
12395
12732
|
// host/lifecycle/src/host-runtime-services-macos.ts
|
|
12396
12733
|
import { execFile as execFile2 } from "node:child_process";
|
|
12397
|
-
import { constants as
|
|
12398
|
-
import { chmod as chmod2, lstat as lstat11, mkdir as mkdir10, open as open7, readdir as
|
|
12734
|
+
import { constants as constants13 } from "node:fs";
|
|
12735
|
+
import { chmod as chmod2, lstat as lstat11, mkdir as mkdir10, open as open7, readdir as readdir4, rename as rename6, unlink as unlink9 } from "node:fs/promises";
|
|
12399
12736
|
import { homedir as homedir4 } from "node:os";
|
|
12400
12737
|
import { posix as posix9 } from "node:path";
|
|
12401
12738
|
import { promisify } from "node:util";
|
|
@@ -12431,11 +12768,11 @@ async function requireCurrentAccountHome(options) {
|
|
|
12431
12768
|
} catch {
|
|
12432
12769
|
throw homeUnavailable();
|
|
12433
12770
|
}
|
|
12434
|
-
const
|
|
12771
|
+
const normalize3 = (value) => {
|
|
12435
12772
|
const normalized = path.normalize(value);
|
|
12436
12773
|
return options.platform === "win32" ? normalized.toLocaleLowerCase("en-US") : normalized;
|
|
12437
12774
|
};
|
|
12438
|
-
if (
|
|
12775
|
+
if (normalize3(configuredResolved) !== normalize3(accountResolved)) {
|
|
12439
12776
|
throw new HostRuntimeReasonedError("host_manager_home_mismatch", ["manager_home_mismatch", "restore_account_home_environment"]);
|
|
12440
12777
|
}
|
|
12441
12778
|
}
|
|
@@ -12568,7 +12905,7 @@ var MAX_PLIST_BYTES = 64 * 1024;
|
|
|
12568
12905
|
var SERVICE_PROCESS_POLL_MS = 50;
|
|
12569
12906
|
var LAUNCHCTL = "/bin/launchctl";
|
|
12570
12907
|
var OWNER_MARKER = "ceal-host-runtime-service-v1";
|
|
12571
|
-
var { basename: basename4, dirname: dirname13, join:
|
|
12908
|
+
var { basename: basename4, dirname: dirname13, join: join19 } = posix9;
|
|
12572
12909
|
var MacosHostRuntimeServiceError = class extends Error {
|
|
12573
12910
|
code;
|
|
12574
12911
|
/**
|
|
@@ -12600,7 +12937,7 @@ function createMacosHostRuntimeServiceAdapter(options) {
|
|
|
12600
12937
|
return new MacosHostRuntimeServiceAdapter(directory, absoluteNormalized(options.log_directory), uid, options.run_launchctl ?? runMacosLaunchctl, options.run_process ?? runMacosPs, options.progress ?? (() => void 0), managerPreflight, resolveMacosHostRuntimeClock(options.clock));
|
|
12601
12938
|
}
|
|
12602
12939
|
function macosLaunchAgentsDirectory(environment) {
|
|
12603
|
-
return
|
|
12940
|
+
return join19(environment.HOME || homedir4(), "Library", "LaunchAgents");
|
|
12604
12941
|
}
|
|
12605
12942
|
function assertMacosServicePlatform(platform) {
|
|
12606
12943
|
if (platform !== "darwin") throw new MacosHostRuntimeServiceError("unsupported", `The launchd Host service adapter requires macOS (${refusalFact("platform", platform, "darwin")}).`, ["fact:platform"]);
|
|
@@ -12648,7 +12985,7 @@ function loadedReferencesMatch(stdout, service) {
|
|
|
12648
12985
|
}
|
|
12649
12986
|
async function runMacosLaunchctl(args) {
|
|
12650
12987
|
try {
|
|
12651
|
-
const result = await execFileAsync(LAUNCHCTL, [...args], { encoding: "utf8", timeout: 15e3, maxBuffer: HOST_RUNTIME_SERVICE_COMMAND_MAX_OUTPUT_BYTES });
|
|
12988
|
+
const result = await execFileAsync(LAUNCHCTL, [...args], { encoding: "utf8", timeout: 15e3, maxBuffer: HOST_RUNTIME_SERVICE_COMMAND_MAX_OUTPUT_BYTES, cwd: resolveCealSpawnWorkingDirectory() });
|
|
12652
12989
|
return boundedLaunchctlResult({ exit_code: 0, stdout: result.stdout, stderr: result.stderr });
|
|
12653
12990
|
} catch (error) {
|
|
12654
12991
|
const failure = executionFailure(error);
|
|
@@ -12657,7 +12994,7 @@ async function runMacosLaunchctl(args) {
|
|
|
12657
12994
|
}
|
|
12658
12995
|
async function runMacosPs(args) {
|
|
12659
12996
|
try {
|
|
12660
|
-
const result = await execFileAsync("/bin/ps", [...args], { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024 });
|
|
12997
|
+
const result = await execFileAsync("/bin/ps", [...args], { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024, cwd: resolveCealSpawnWorkingDirectory() });
|
|
12661
12998
|
return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
|
|
12662
12999
|
} catch (error) {
|
|
12663
13000
|
const failure = executionFailure(error);
|
|
@@ -12791,7 +13128,7 @@ var MacosHostRuntimeServiceAdapter = class {
|
|
|
12791
13128
|
const labels = /* @__PURE__ */ new Set();
|
|
12792
13129
|
let files;
|
|
12793
13130
|
try {
|
|
12794
|
-
files = (await
|
|
13131
|
+
files = (await readdir4(this.directory)).sort();
|
|
12795
13132
|
} catch {
|
|
12796
13133
|
files = [];
|
|
12797
13134
|
}
|
|
@@ -12821,7 +13158,7 @@ var MacosHostRuntimeServiceAdapter = class {
|
|
|
12821
13158
|
async ownedLabelPrefix(label) {
|
|
12822
13159
|
let managed;
|
|
12823
13160
|
try {
|
|
12824
|
-
managed = await readManagedPlist(
|
|
13161
|
+
managed = await readManagedPlist(join19(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid);
|
|
12825
13162
|
} catch {
|
|
12826
13163
|
return {};
|
|
12827
13164
|
}
|
|
@@ -12852,7 +13189,7 @@ var MacosHostRuntimeServiceAdapter = class {
|
|
|
12852
13189
|
}
|
|
12853
13190
|
async hasOwnedDefinition(label) {
|
|
12854
13191
|
try {
|
|
12855
|
-
return await readManagedPlist(
|
|
13192
|
+
return await readManagedPlist(join19(this.directory, `${label}.plist`), `<!-- ${OWNER_MARKER}:${label} -->`, this.uid) !== null;
|
|
12856
13193
|
} catch (error) {
|
|
12857
13194
|
if (error instanceof MacosHostRuntimeServiceError) return false;
|
|
12858
13195
|
throw error;
|
|
@@ -12936,7 +13273,7 @@ var MacosHostRuntimeServiceAdapter = class {
|
|
|
12936
13273
|
}
|
|
12937
13274
|
owner(prefix, component) {
|
|
12938
13275
|
const label = macosHostRuntimeServiceLabel(prefix, component);
|
|
12939
|
-
return { label, marker: `<!-- ${OWNER_MARKER}:${label} -->`, path:
|
|
13276
|
+
return { label, marker: `<!-- ${OWNER_MARKER}:${label} -->`, path: join19(this.directory, `${label}.plist`), target: `gui/${this.uid}/${label}`, log: macosHostRuntimeServiceLogPath(this.logDirectory, component) };
|
|
12940
13277
|
}
|
|
12941
13278
|
async launchctl(args) {
|
|
12942
13279
|
return boundedLaunchctlResult(await this.runner(args));
|
|
@@ -12966,6 +13303,10 @@ function launchAgentPlist(owner, service) {
|
|
|
12966
13303
|
'<plist version="1.0"><dict>',
|
|
12967
13304
|
`<key>Label</key><string>${label}</string>`,
|
|
12968
13305
|
`<key>ProgramArguments</key><array>${argumentsXml}</array>`,
|
|
13306
|
+
// The service's working directory must never sit inside the prefix
|
|
13307
|
+
// activation swaps; owner.log names the per-service file in the
|
|
13308
|
+
// per-state-root log directory, so its parent is that stable directory.
|
|
13309
|
+
`<key>WorkingDirectory</key><string>${xml(dirname13(owner.log))}</string>`,
|
|
12969
13310
|
"<key>RunAtLoad</key><true/>",
|
|
12970
13311
|
"<key>KeepAlive</key><true/>",
|
|
12971
13312
|
"<key>ProcessType</key><string>Background</string>",
|
|
@@ -13023,7 +13364,7 @@ async function readManagedPlist(path, marker, uid) {
|
|
|
13023
13364
|
async function writeManagedPlist(path, marker, text, uid, repairLooseMode = false) {
|
|
13024
13365
|
const current = await readManagedPlist(path, marker, uid);
|
|
13025
13366
|
if (current?.text === text && !repairLooseMode) return;
|
|
13026
|
-
const temporary =
|
|
13367
|
+
const temporary = join19(dirname13(path), `.${basename4(path)}.${process.pid}.${createHash15("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0, 12)}.tmp`);
|
|
13027
13368
|
try {
|
|
13028
13369
|
const handle = await open7(temporary, "wx", 384);
|
|
13029
13370
|
try {
|
|
@@ -13034,7 +13375,7 @@ async function writeManagedPlist(path, marker, text, uid, repairLooseMode = fals
|
|
|
13034
13375
|
}
|
|
13035
13376
|
await chmod2(temporary, 384);
|
|
13036
13377
|
await rename6(temporary, path);
|
|
13037
|
-
const directory = await open7(dirname13(path),
|
|
13378
|
+
const directory = await open7(dirname13(path), constants13.O_RDONLY);
|
|
13038
13379
|
try {
|
|
13039
13380
|
await directory.sync();
|
|
13040
13381
|
} finally {
|
|
@@ -13229,7 +13570,10 @@ function wireService(prefix, service, logDirectory) {
|
|
|
13229
13570
|
executable: win3211.join(prefix, ...HOST_WINDOWS_BACKGROUND_RELATIVE_PATH.split("/")),
|
|
13230
13571
|
// Task Scheduler ExecAction launches the executable directly, never
|
|
13231
13572
|
// through cmd.exe, so `%` and `!` in user paths stay literal here.
|
|
13232
|
-
arguments: [service.command.executable, ...argumentsWithLog].map(quoteWindowsExecArgument).join(" ")
|
|
13573
|
+
arguments: [service.command.executable, ...argumentsWithLog].map(quoteWindowsExecArgument).join(" "),
|
|
13574
|
+
// The task's own working directory must never sit inside the prefix
|
|
13575
|
+
// activation swaps; the per-state-root log directory is stable and outside it.
|
|
13576
|
+
...logDirectory === void 0 ? {} : { working_directory: logDirectory }
|
|
13233
13577
|
};
|
|
13234
13578
|
}
|
|
13235
13579
|
function validateWindowsService(prefix, service) {
|
|
@@ -13317,15 +13661,15 @@ function parseInstallations(result) {
|
|
|
13317
13661
|
return assembleHostRuntimeInstallations(groups);
|
|
13318
13662
|
}
|
|
13319
13663
|
function isWireResult(value) {
|
|
13320
|
-
return
|
|
13664
|
+
return isRecord12(value) && value.schema_version === WINDOWS_SERVICE_RESULT_SCHEMA && value.ok === true && (value.observations === void 0 || Array.isArray(value.observations)) && (value.tasks === void 0 || Array.isArray(value.tasks));
|
|
13321
13665
|
}
|
|
13322
13666
|
function isWireInstallationTask(value) {
|
|
13323
|
-
if (!
|
|
13667
|
+
if (!isRecord12(value) || typeof value.installation_id !== "string" || !isServiceComponent2(value.component) || !isServiceState(value.state) || typeof value.name !== "string") return false;
|
|
13324
13668
|
const match = WINDOWS_HOST_TASK_NAME_PATTERN.exec(value.name);
|
|
13325
13669
|
return match?.[1] === value.installation_id && match[2] === value.component;
|
|
13326
13670
|
}
|
|
13327
13671
|
function isWireObservation(value) {
|
|
13328
|
-
return
|
|
13672
|
+
return isRecord12(value) && isServiceComponent2(value.component) && isServiceState(value.state) && typeof value.definition_matches === "boolean" && (value.startup_pending === void 0 || typeof value.startup_pending === "boolean") && (value.last_task_result === void 0 || Number.isSafeInteger(value.last_task_result));
|
|
13329
13673
|
}
|
|
13330
13674
|
function isServiceComponent2(value) {
|
|
13331
13675
|
return HOST_RUNTIME_SERVICE_COMPONENTS.some((component) => component === value);
|
|
@@ -13341,7 +13685,7 @@ function boundedProcessFailure(result) {
|
|
|
13341
13685
|
const detail = result.stderr.trim().slice(0, 1024);
|
|
13342
13686
|
return detail.length === 0 ? `The Windows service operation exited with code ${result.exit_code}.` : `The Windows service operation failed: ${detail}`;
|
|
13343
13687
|
}
|
|
13344
|
-
function
|
|
13688
|
+
function isRecord12(value) {
|
|
13345
13689
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13346
13690
|
}
|
|
13347
13691
|
function sameCommand2(left, right) {
|
|
@@ -13411,6 +13755,7 @@ function Test-CealDefinition($task, $wanted) {
|
|
|
13411
13755
|
$action = $definition.Actions.Item(1)
|
|
13412
13756
|
$trigger = $definition.Triggers.Item(1)
|
|
13413
13757
|
if ($action.Type -ne 0 -or [string]$action.Path -cne [string]$wanted.executable -or [string]$action.Arguments -cne [string]$wanted.arguments) { return $false }
|
|
13758
|
+
if ([string]$action.WorkingDirectory -cne [string]$wanted.working_directory) { return $false }
|
|
13414
13759
|
if ($trigger.Type -ne 9 -or -not $trigger.Enabled -or -not (Test-CealSid ([string]$trigger.UserId))) { return $false }
|
|
13415
13760
|
if (-not (Test-CealSid ([string]$definition.Principal.UserId)) -or $definition.Principal.LogonType -ne 3 -or $definition.Principal.RunLevel -ne 0) { return $false }
|
|
13416
13761
|
if (-not $definition.Settings.Enabled -or -not $definition.Settings.StartWhenAvailable -or [string]$definition.Settings.ExecutionTimeLimit -cne 'PT0S' -or $definition.Settings.MultipleInstances -ne 2) { return $false }
|
|
@@ -13440,6 +13785,10 @@ function Register-CealTask($wanted) {
|
|
|
13440
13785
|
$action = $definition.Actions.Create(0)
|
|
13441
13786
|
$action.Path = [string]$wanted.executable
|
|
13442
13787
|
$action.Arguments = [string]$wanted.arguments
|
|
13788
|
+
if ([string]$wanted.working_directory -ne '') {
|
|
13789
|
+
$null = New-Item -ItemType Directory -Force -Path ([string]$wanted.working_directory)
|
|
13790
|
+
$action.WorkingDirectory = [string]$wanted.working_directory
|
|
13791
|
+
}
|
|
13443
13792
|
return $folder.RegisterTaskDefinition((Get-CealTaskName ([string]$wanted.component)), $definition, 6, $sid, $null, 3, $null)
|
|
13444
13793
|
}
|
|
13445
13794
|
|
|
@@ -13524,11 +13873,11 @@ throw 'Unsupported Windows Host service operation.'
|
|
|
13524
13873
|
var WINDOWS_TASK_SCHEDULER_PROGRAM = Buffer.from(TASK_SCHEDULER_SOURCE, "utf16le").toString("base64");
|
|
13525
13874
|
|
|
13526
13875
|
// host/lifecycle/src/host-runtime-windows-process.ts
|
|
13527
|
-
import { spawn } from "node:child_process";
|
|
13528
|
-
var spawnWindowsHostProcess = (executable, args, options) =>
|
|
13876
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
13877
|
+
var spawnWindowsHostProcess = (executable, args, options) => spawn2(executable, [...args], options);
|
|
13529
13878
|
function runWindowsHostProcess(invocation, spawnProcess = spawnWindowsHostProcess) {
|
|
13530
13879
|
return new Promise((resolve) => {
|
|
13531
|
-
const child = spawnProcess(invocation.executable, [...invocation.args], { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
13880
|
+
const child = spawnProcess(invocation.executable, [...invocation.args], { shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"], cwd: resolveCealSpawnWorkingDirectory() });
|
|
13532
13881
|
const stdout = [];
|
|
13533
13882
|
const stderr = [];
|
|
13534
13883
|
let stdoutBytes = 0;
|
|
@@ -13572,7 +13921,7 @@ function runWindowsHostProcess(invocation, spawnProcess = spawnWindowsHostProces
|
|
|
13572
13921
|
|
|
13573
13922
|
// host/lifecycle/src/host-runtime-systemd.ts
|
|
13574
13923
|
import { createHash as createHash16, randomUUID as randomUUID2 } from "node:crypto";
|
|
13575
|
-
import { lstat as lstat12, mkdir as mkdir11, open as open8, readFile as readFile4, readdir as
|
|
13924
|
+
import { lstat as lstat12, mkdir as mkdir11, open as open8, readFile as readFile4, readdir as readdir5, rename as rename7, unlink as unlink10 } from "node:fs/promises";
|
|
13576
13925
|
import { posix as posix10 } from "node:path";
|
|
13577
13926
|
|
|
13578
13927
|
// scripts/lib/systemd-unit-path.ts
|
|
@@ -13682,6 +14031,7 @@ function createLinuxUserSystemdAdapter(options) {
|
|
|
13682
14031
|
const unitDirectory = absoluteNormalizedNonRoot(options.unit_directory, "systemd user unit directory");
|
|
13683
14032
|
const systemctl = absoluteNormalizedNonRoot(options.systemctl_path ?? CEAL_SYSTEMCTL_EXECUTABLE_PATH, "systemctl executable");
|
|
13684
14033
|
const journalctl = absoluteNormalizedNonRoot(options.journalctl_path ?? DEFAULT_JOURNALCTL_PATH, "journalctl executable");
|
|
14034
|
+
const workingDirectory = options.working_directory === void 0 ? void 0 : absoluteNormalizedNonRoot(options.working_directory, "systemd service working directory");
|
|
13685
14035
|
const run = options.run;
|
|
13686
14036
|
return {
|
|
13687
14037
|
async reconcile({ previous, target }) {
|
|
@@ -13692,7 +14042,7 @@ function createLinuxUserSystemdAdapter(options) {
|
|
|
13692
14042
|
await ensurePrivateUnitDirectory(unitDirectory);
|
|
13693
14043
|
if (target.services.length > 0) await refuseForeignCealUnits(unitDirectory, run, systemctl, identity);
|
|
13694
14044
|
const removableUnits = await ownedHostUnits(unitDirectory, identity);
|
|
13695
|
-
for (const service of target.services) await replaceOwnedUnit(unitDirectory, identity, service);
|
|
14045
|
+
for (const service of target.services) await replaceOwnedUnit(unitDirectory, identity, service, workingDirectory);
|
|
13696
14046
|
for (const unit of removableUnits) {
|
|
13697
14047
|
if (targetByComponent.has(unit.component)) continue;
|
|
13698
14048
|
await invokeSystemctl(run, systemctl, ["--user", "disable", "--now", unitName(unit.identity, unit.component)]);
|
|
@@ -13771,7 +14121,7 @@ function serviceMap(set) {
|
|
|
13771
14121
|
}
|
|
13772
14122
|
async function ownedHostUnits(directory, identity) {
|
|
13773
14123
|
const owned = [];
|
|
13774
|
-
for (const name of await
|
|
14124
|
+
for (const name of await readdir5(directory)) {
|
|
13775
14125
|
const match = CEAL_HOST_UNIT_PATTERN.exec(name);
|
|
13776
14126
|
if (match === null) continue;
|
|
13777
14127
|
const unitIdentity = match[1];
|
|
@@ -13782,7 +14132,7 @@ async function ownedHostUnits(directory, identity) {
|
|
|
13782
14132
|
return owned.sort((left, right) => unitName(left.identity, left.component).localeCompare(unitName(right.identity, right.component)));
|
|
13783
14133
|
}
|
|
13784
14134
|
async function refuseForeignCealUnits(directory, run, systemctl, identity) {
|
|
13785
|
-
const names = (await
|
|
14135
|
+
const names = (await readdir5(directory)).sort();
|
|
13786
14136
|
for (const name of names) {
|
|
13787
14137
|
const parsed = parseCealHostUnit(name);
|
|
13788
14138
|
if (parsed === void 0 || parsed.identity === identity) continue;
|
|
@@ -13826,7 +14176,7 @@ async function listSystemdInstallations(directory, run, systemctl) {
|
|
|
13826
14176
|
async function collectCealUnitNames(directory, run, systemctl) {
|
|
13827
14177
|
let files;
|
|
13828
14178
|
try {
|
|
13829
|
-
files = (await
|
|
14179
|
+
files = (await readdir5(directory)).sort();
|
|
13830
14180
|
} catch {
|
|
13831
14181
|
return [];
|
|
13832
14182
|
}
|
|
@@ -13933,10 +14283,10 @@ async function ownedUnitPresent(path, identity, component) {
|
|
|
13933
14283
|
throw projectionError(renderOperatorDiagnostic(error));
|
|
13934
14284
|
}
|
|
13935
14285
|
}
|
|
13936
|
-
async function replaceOwnedUnit(directory, identity, service) {
|
|
14286
|
+
async function replaceOwnedUnit(directory, identity, service, workingDirectory) {
|
|
13937
14287
|
const destination = unitPath(directory, identity, service.component);
|
|
13938
14288
|
const temporary = posix10.join(directory, `.${unitName(identity, service.component)}.${randomUUID2()}.tmp`);
|
|
13939
|
-
const content = renderUnit(identity, service);
|
|
14289
|
+
const content = renderUnit(identity, service, workingDirectory);
|
|
13940
14290
|
try {
|
|
13941
14291
|
const handle = await open8(temporary, "wx", 384);
|
|
13942
14292
|
try {
|
|
@@ -13968,7 +14318,7 @@ async function syncDirectory3(directory) {
|
|
|
13968
14318
|
await handle.close();
|
|
13969
14319
|
}
|
|
13970
14320
|
}
|
|
13971
|
-
function renderUnit(identity, service) {
|
|
14321
|
+
function renderUnit(identity, service, workingDirectory) {
|
|
13972
14322
|
return [
|
|
13973
14323
|
ownerPreamble(identity, service.component).trimEnd(),
|
|
13974
14324
|
"[Unit]",
|
|
@@ -13980,6 +14330,9 @@ function renderUnit(identity, service) {
|
|
|
13980
14330
|
"Type=simple",
|
|
13981
14331
|
"UMask=0077",
|
|
13982
14332
|
`ExecStart=${systemdCommandLine(service.command.executable, service.command.args, true)}`,
|
|
14333
|
+
// The service's working directory must never sit inside the prefix
|
|
14334
|
+
// activation swaps; the composed working directory is per-state-root and outside it.
|
|
14335
|
+
...workingDirectory === void 0 ? [] : [`WorkingDirectory=${workingDirectory}`],
|
|
13983
14336
|
"Restart=on-failure",
|
|
13984
14337
|
"RestartSec=3",
|
|
13985
14338
|
"",
|
|
@@ -14318,7 +14671,7 @@ function platformServiceAdapter(platform, environment, stateRoot, progress) {
|
|
|
14318
14671
|
if (platform === "linux") {
|
|
14319
14672
|
const configRoot = environment.XDG_CONFIG_HOME ?? (environment.HOME === void 0 ? void 0 : posix11.join(environment.HOME, ".config"));
|
|
14320
14673
|
if (configRoot === void 0) throw platformUnavailable();
|
|
14321
|
-
return createLinuxUserSystemdAdapter({ unit_directory: posix11.join(configRoot, "systemd", "user"), run: runSystemctl });
|
|
14674
|
+
return createLinuxUserSystemdAdapter({ unit_directory: posix11.join(configRoot, "systemd", "user"), run: runSystemctl, working_directory: resolveCealSpawnWorkingDirectory(stateRoot) });
|
|
14322
14675
|
}
|
|
14323
14676
|
if (platform === "win32") {
|
|
14324
14677
|
const systemRoot = environmentValue(environment, "SystemRoot", platform);
|
|
@@ -14329,7 +14682,7 @@ function platformServiceAdapter(platform, environment, stateRoot, progress) {
|
|
|
14329
14682
|
}
|
|
14330
14683
|
async function runSystemctl(executable, args, options) {
|
|
14331
14684
|
try {
|
|
14332
|
-
const result = await execFileAsync2(executable, [...args], { encoding: "utf8", timeout: options.timeout_ms, maxBuffer: options.max_output_bytes });
|
|
14685
|
+
const result = await execFileAsync2(executable, [...args], { encoding: "utf8", timeout: options.timeout_ms, maxBuffer: options.max_output_bytes, cwd: resolveCealSpawnWorkingDirectory() });
|
|
14333
14686
|
return { exit_code: 0, stdout: result.stdout, stderr: result.stderr };
|
|
14334
14687
|
} catch (error) {
|
|
14335
14688
|
return processFailure(error);
|