@rallycry/conveyor-agent 10.13.56 → 10.13.57
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/dist/{boot-RW7SNO6X.js → boot-37ZX7POR.js} +4 -4
- package/dist/{chunk-DSP4KR4B.js → chunk-MS43QSHO.js} +2 -2
- package/dist/{chunk-UAGIXPYD.js → chunk-PWYJZY3P.js} +122 -1
- package/dist/chunk-PWYJZY3P.js.map +1 -0
- package/dist/{chunk-PG3Z6RIC.js → chunk-VIEBOAJ7.js} +69 -12
- package/dist/chunk-VIEBOAJ7.js.map +1 -0
- package/dist/{chunk-7765OQU5.js → chunk-WVUQ5CH5.js} +16 -47
- package/dist/chunk-WVUQ5CH5.js.map +1 -0
- package/dist/cli.js +5 -5
- package/dist/index.js +3 -3
- package/dist/{server-EQUCOLNY.js → server-7UW4X3XF.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-7765OQU5.js.map +0 -1
- package/dist/chunk-PG3Z6RIC.js.map +0 -1
- package/dist/chunk-UAGIXPYD.js.map +0 -1
- /package/dist/{boot-RW7SNO6X.js.map → boot-37ZX7POR.js.map} +0 -0
- /package/dist/{chunk-DSP4KR4B.js.map → chunk-MS43QSHO.js.map} +0 -0
- /package/dist/{server-EQUCOLNY.js.map → server-7UW4X3XF.js.map} +0 -0
|
@@ -9,14 +9,14 @@ import {
|
|
|
9
9
|
readAgentVersion,
|
|
10
10
|
redactToken,
|
|
11
11
|
reportBootMilestone
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-WVUQ5CH5.js";
|
|
13
13
|
import {
|
|
14
14
|
workbenchPort
|
|
15
15
|
} from "./chunk-4VUQ2NPF.js";
|
|
16
16
|
import {
|
|
17
17
|
startWorkbenchServer
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
import "./chunk-
|
|
18
|
+
} from "./chunk-MS43QSHO.js";
|
|
19
|
+
import "./chunk-PWYJZY3P.js";
|
|
20
20
|
import {
|
|
21
21
|
DEFAULT_WORKBENCH_PORT
|
|
22
22
|
} from "./chunk-JIGG755T.js";
|
|
@@ -1316,4 +1316,4 @@ export {
|
|
|
1316
1316
|
runBoot,
|
|
1317
1317
|
workbenchBootSteps
|
|
1318
1318
|
};
|
|
1319
|
-
//# sourceMappingURL=boot-
|
|
1319
|
+
//# sourceMappingURL=boot-37ZX7POR.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
loadPtySpawn,
|
|
3
3
|
terminateProcessGroup
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-PWYJZY3P.js";
|
|
5
5
|
import {
|
|
6
6
|
FrameReader,
|
|
7
7
|
timingSafeTokenEqual,
|
|
@@ -296,4 +296,4 @@ async function runReaddir(socket, req) {
|
|
|
296
296
|
export {
|
|
297
297
|
startWorkbenchServer
|
|
298
298
|
};
|
|
299
|
-
//# sourceMappingURL=chunk-
|
|
299
|
+
//# sourceMappingURL=chunk-MS43QSHO.js.map
|
|
@@ -72,6 +72,117 @@ ${tail}`);
|
|
|
72
72
|
return errors;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
// src/boot/git-credential.ts
|
|
76
|
+
import { createHash } from "crypto";
|
|
77
|
+
import { chmodSync, existsSync, mkdirSync, renameSync, writeFileSync } from "fs";
|
|
78
|
+
import { homedir } from "os";
|
|
79
|
+
import { dirname, join } from "path";
|
|
80
|
+
function credentialDir(cwd) {
|
|
81
|
+
return join(dirname(cwd), ".conveyor-git-credentials");
|
|
82
|
+
}
|
|
83
|
+
function gitCredentialFile(cwd) {
|
|
84
|
+
const key = createHash("sha256").update(cwd).digest("hex").slice(0, 16);
|
|
85
|
+
return join(credentialDir(cwd), `${key}.store`);
|
|
86
|
+
}
|
|
87
|
+
function gitCredentialHelper(cwd) {
|
|
88
|
+
return `store --file=${gitCredentialFile(cwd)}`;
|
|
89
|
+
}
|
|
90
|
+
function writeGitCredential(cwd, cloneUrl, credential) {
|
|
91
|
+
const cleanUrl = new URL(cloneUrl);
|
|
92
|
+
if (!/^https?:$/.test(cleanUrl.protocol) || cleanUrl.username || cleanUrl.password) {
|
|
93
|
+
throw new Error("Git clone URL must be a credential-free HTTP(S) URL");
|
|
94
|
+
}
|
|
95
|
+
if (!credential.username || !credential.secret) {
|
|
96
|
+
throw new Error("Git credential username and secret are required");
|
|
97
|
+
}
|
|
98
|
+
const dir = credentialDir(cwd);
|
|
99
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
100
|
+
chmodSync(dir, 448);
|
|
101
|
+
cleanUrl.username = credential.username;
|
|
102
|
+
cleanUrl.password = credential.secret;
|
|
103
|
+
cleanUrl.pathname = "/";
|
|
104
|
+
cleanUrl.search = "";
|
|
105
|
+
cleanUrl.hash = "";
|
|
106
|
+
const target = gitCredentialFile(cwd);
|
|
107
|
+
writeSecretFile(target, `${cleanUrl.toString()}
|
|
108
|
+
`);
|
|
109
|
+
}
|
|
110
|
+
function githubTokenFilePath() {
|
|
111
|
+
return process.env.CONVEYOR_GITHUB_TOKEN_FILE || join(homedir(), ".conveyor", "github-token");
|
|
112
|
+
}
|
|
113
|
+
function ghConfigDir() {
|
|
114
|
+
return process.env.GH_CONFIG_DIR || join(homedir(), ".config", "gh");
|
|
115
|
+
}
|
|
116
|
+
function ghHostsFilePath() {
|
|
117
|
+
return join(ghConfigDir(), "hosts.yml");
|
|
118
|
+
}
|
|
119
|
+
function ghManagedMarkerPath() {
|
|
120
|
+
return join(ghConfigDir(), ".conveyor-managed");
|
|
121
|
+
}
|
|
122
|
+
function ghConfigFilePath() {
|
|
123
|
+
return join(ghConfigDir(), "config.yml");
|
|
124
|
+
}
|
|
125
|
+
function blockedDefaultWrite(overrideEnvKey) {
|
|
126
|
+
return Boolean(process.env.VITEST) && !process.env[overrideEnvKey];
|
|
127
|
+
}
|
|
128
|
+
function ghHostsManagedByConveyor() {
|
|
129
|
+
return existsSync(ghManagedMarkerPath()) && existsSync(ghHostsFilePath());
|
|
130
|
+
}
|
|
131
|
+
function writeSecretFile(target, contents) {
|
|
132
|
+
const dir = dirname(target);
|
|
133
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
134
|
+
chmodSync(dir, 448);
|
|
135
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
136
|
+
writeFileSync(temporary, contents, { encoding: "utf8", mode: 384 });
|
|
137
|
+
chmodSync(temporary, 384);
|
|
138
|
+
renameSync(temporary, target);
|
|
139
|
+
}
|
|
140
|
+
function writeGithubTokenFile(token) {
|
|
141
|
+
if (blockedDefaultWrite("CONVEYOR_GITHUB_TOKEN_FILE")) return false;
|
|
142
|
+
writeSecretFile(githubTokenFilePath(), `${token}
|
|
143
|
+
`);
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
function ensureGhConfigVersion() {
|
|
147
|
+
if (existsSync(ghConfigFilePath())) return;
|
|
148
|
+
writeSecretFile(ghConfigFilePath(), 'version: "1"\n');
|
|
149
|
+
}
|
|
150
|
+
function writeGhHostsConfig(token) {
|
|
151
|
+
if (blockedDefaultWrite("GH_CONFIG_DIR")) return false;
|
|
152
|
+
if (existsSync(ghHostsFilePath()) && !existsSync(ghManagedMarkerPath())) return false;
|
|
153
|
+
const host = process.env.GH_HOST || "github.com";
|
|
154
|
+
const user = process.env.CONVEYOR_GIT_USERNAME || "x-access-token";
|
|
155
|
+
const contents = [
|
|
156
|
+
"# Written by conveyor-agent \u2014 refreshed on every GitHub token refresh.",
|
|
157
|
+
"# Edits are overwritten. Do not add a second host entry here by hand.",
|
|
158
|
+
`${host}:`,
|
|
159
|
+
` oauth_token: ${token}`,
|
|
160
|
+
` user: ${user}`,
|
|
161
|
+
" git_protocol: https",
|
|
162
|
+
" users:",
|
|
163
|
+
` ${user}:`,
|
|
164
|
+
` oauth_token: ${token}`,
|
|
165
|
+
""
|
|
166
|
+
].join("\n");
|
|
167
|
+
writeSecretFile(ghHostsFilePath(), contents);
|
|
168
|
+
writeSecretFile(ghManagedMarkerPath(), "conveyor-agent\n");
|
|
169
|
+
ensureGhConfigVersion();
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
function syncGithubTokenFiles(token) {
|
|
173
|
+
const result = { tokenFile: false, ghHosts: false };
|
|
174
|
+
if (!token) return result;
|
|
175
|
+
try {
|
|
176
|
+
result.tokenFile = writeGithubTokenFile(token);
|
|
177
|
+
} catch {
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
result.ghHosts = writeGhHostsConfig(token);
|
|
181
|
+
} catch {
|
|
182
|
+
}
|
|
183
|
+
return result;
|
|
184
|
+
}
|
|
185
|
+
|
|
75
186
|
// src/utils/sleep.ts
|
|
76
187
|
function sleep(ms) {
|
|
77
188
|
return new Promise((resolve) => {
|
|
@@ -211,6 +322,12 @@ function inheritedEnv(socketPath) {
|
|
|
211
322
|
if (env.CLAUDE_CODE_OAUTH_TOKEN) {
|
|
212
323
|
delete env.ANTHROPIC_API_KEY;
|
|
213
324
|
}
|
|
325
|
+
if (ghHostsManagedByConveyor() && env.CONVEYOR_KEEP_GH_TOKEN_ENV !== "1") {
|
|
326
|
+
delete env.GH_TOKEN;
|
|
327
|
+
delete env.GITHUB_TOKEN;
|
|
328
|
+
delete env.CONVEYOR_GITHUB_TOKEN;
|
|
329
|
+
env.CONVEYOR_GITHUB_TOKEN_FILE = githubTokenFilePath();
|
|
330
|
+
}
|
|
214
331
|
if (socketPath) {
|
|
215
332
|
env.CONVEYOR_HOOK_SOCKET = socketPath;
|
|
216
333
|
}
|
|
@@ -374,6 +491,10 @@ function runStartCommand(cmd, cwd, onOutput) {
|
|
|
374
491
|
|
|
375
492
|
export {
|
|
376
493
|
sleep,
|
|
494
|
+
gitCredentialHelper,
|
|
495
|
+
writeGitCredential,
|
|
496
|
+
githubTokenFilePath,
|
|
497
|
+
syncGithubTokenFiles,
|
|
377
498
|
resolveClaudeBinary,
|
|
378
499
|
buildSpawnArgs,
|
|
379
500
|
spawnOptionsFingerprint,
|
|
@@ -404,4 +525,4 @@ export {
|
|
|
404
525
|
runAuthTokenCommand,
|
|
405
526
|
runStartCommand
|
|
406
527
|
};
|
|
407
|
-
//# sourceMappingURL=chunk-
|
|
528
|
+
//# sourceMappingURL=chunk-PWYJZY3P.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/harness/pty/pty-support.ts","../src/harness/pty/spawn-args.ts","../src/boot/git-credential.ts","../src/utils/sleep.ts","../src/setup/commands.ts"],"sourcesContent":["/**\n * Pure support helpers for PtySession — node-pty process loading, prompt-byte\n * encoding, the per-turn options projection, and the AskUserQuestion parser.\n * Extracted from `session.ts` so the orchestrator stays focused on lifecycle;\n * everything here is side-effect-free (or a thin wrapper over one) and unit\n * tested in isolation.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport type { HarnessQueryOptions, HarnessUserQuestion } from \"../types.js\";\n// spawn-args does not import this module, so this direction introduces no cycle.\nimport { cleanTerminalOutput } from \"./spawn-args.js\";\nimport { ghHostsManagedByConveyor, githubTokenFilePath } from \"../../boot/git-credential.js\";\n\n// Cap on the rolling tail of raw terminal output retained for diagnostics when\n// `claude` exits without a result. Bounded so a long-running session can't grow\n// this unboundedly; only the most recent bytes (where a failure surfaces) matter.\nexport const MAX_DIAGNOSTIC_OUTPUT = 4000;\n\n// Cap on transcript events buffered while no turn is draining (the parked\n// window between a completed turn and the next beginTurn / a passive turn).\n// Bounded, drop-oldest — a stale buffered `result` must never terminate a\n// fresh turn, and beginTurn clears the buffer anyway.\nexport const MAX_BETWEEN_TURN_BUFFER = 500;\n\n/** Settle window between the paste write and the submitting Enter write. */\nexport const SUBMIT_SETTLE_MS = 300;\n// Re-press cadence/bounds for the submit nudge (see armSubmitNudge). Fast\n// presses cover the Enter-swallowed-at-startup race; the slow phase covers\n// startup dialogs that render tens of seconds in on a cold pod (folder\n// trust, onboarding) — observed live 2026-07-02 parking code reviews ~13min+\n// when the trust dialog mounted after the fast window had expired.\nexport const SUBMIT_NUDGE_INTERVAL_MS = 2000;\nexport const SUBMIT_NUDGE_MAX_PRESSES = 5;\nexport const SUBMIT_NUDGE_SLOW_INTERVAL_MS = 5000;\nexport const SUBMIT_NUDGE_WINDOW_MS = 90_000;\n\n// How many times a failed prompt submission is recovered by tearing the CLI\n// down and respawning it with the same prompt. The nudge only presses Enter,\n// which cannot clear a startup dialog needing an arrow-key selection (the\n// 2026-07-22 fable-model-picker outage parked TUIs exactly that way) — a fresh\n// process is the only in-pod escape from that state. Bounded because a spawn\n// that reliably parks will park again, and an unbounded respawn loop would burn\n// the pod instead of surfacing the failure.\nexport const SUBMIT_REDELIVERY_MAX_ATTEMPTS = 2;\n\n// Plan-dialog auto-accept press cadence/bounds (see armPlanDialogAutoAccept).\n// The dialog usually renders within a second of the ExitPlanMode hook verdict,\n// but the window is deliberately wide: the only stop signal is the ExitPlanMode\n// PostToolUse envelope, and a missed dialog parks an auto card indefinitely\n// (observed live 2026-07-07: an approval dialog sat 42 minutes until a human\n// pressed Enter).\nexport const PLAN_DIALOG_FIRST_PRESS_MS = 700;\nexport const PLAN_DIALOG_INTERVAL_MS = 1500;\nexport const PLAN_DIALOG_SLOW_INTERVAL_MS = 5000;\nexport const PLAN_DIALOG_FAST_WINDOW_MS = 10_000;\nexport const PLAN_DIALOG_WINDOW_MS = 90_000;\n\n// Input-readiness DETECTION before the FIRST prompt write to a raw-relay TUI.\n//\n// A structured-events TUI recovers a prompt lost to startup via the submit\n// nudge (re-press Enter until a transcript record proves the turn began). A raw\n// adapter has no such evidence, so the nudge is never armed for it (see\n// armSubmitNudge's caller) — the single paste + Enter it gets must therefore\n// land on an input box that is actually accepting keystrokes, or the turn is\n// lost silently with the prompt nowhere and the card parked on an empty box.\n//\n// We DETECT that state rather than infer it from elapsed time. The method:\n// type a short sentinel, and watch for the TUI to render THAT SENTINEL back.\n// Only a live input box echoes typed characters into its own repaint, so a\n// rendered sentinel is positive proof; then it is erased and the real prompt is\n// pasted exactly once.\n//\n// Signals that were measured and rejected (opencode 1.18.15 / Claude Code\n// 2.1.226, macOS, driving node-pty directly):\n// - DECSET 2004 (bracketed-paste enable). Both TUIs set it in their FIRST\n// paint — opencode at 554ms, Claude at 267ms — ~2s before opencode accepts\n// input. It reports terminal setup, not input readiness.\n// - \"quiet since the last output frame\". opencode's startup paint contains an\n// internal ~1175ms gap (1172/1174/1177ms over three runs), so any quiet\n// window short enough to be responsive fires INSIDE the paint.\n// - \"any output right after our keystroke\". While the app is still painting,\n// output arrives coincidentally rather than causally: this reported ready at\n// 981ms and the prompt was then dropped. The ack must be the sentinel\n// itself, not merely activity.\n// - echoing the PROMPT back. opencode renders a multi-line paste as\n// \"[Pasted ~4 lines]\" and never shows the text, so the prompt cannot serve\n// as its own acknowledgement.\n//\n// Sentinel content is deliberately three inert lowercase letters: no digits\n// (Claude Code's folder-trust dialog is a numbered menu, where a stray \"1\"\n// would select \"Yes, I trust this folder\"), and no Enter/Esc/arrow keys.\nexport const RAW_TUI_PROBE_SENTINEL = \"zqx\";\n/** How long a probe waits for the TUI to render the sentinel back. */\nexport const RAW_TUI_PROBE_ACK_MS = 500;\n/** Gap between unacknowledged probes. */\nexport const RAW_TUI_PROBE_RETRY_MS = 250;\n/** Poll cadence while watching for the sentinel / for first output. */\nexport const RAW_TUI_PROBE_POLL_MS = 20;\n/** Bound on waiting for the process to paint anything at all. */\nexport const RAW_TUI_FIRST_OUTPUT_MAX_MS = 10_000;\n// Overall cap. On expiry we paste anyway rather than hang the turn: the adapter's\n// own exit diagnostics are a better failure signal than a silent stall.\nexport const RAW_TUI_INPUT_LIVE_MAX_MS = 20_000;\n\nfunction envMs(name: string, fallback: number): number {\n const raw = Number(process.env[name]);\n return Number.isFinite(raw) && raw > 0 ? raw : fallback;\n}\n\nexport function resolveSubmitSettleMs(): number {\n return envMs(\"CONVEYOR_PTY_SUBMIT_SETTLE_MS\", SUBMIT_SETTLE_MS);\n}\n\n/**\n * Effective raw-TUI input-probe timing. Overridable for ops and so tests can\n * drive the detector in milliseconds instead of seconds of real wall-clock.\n * `sentinel` is overridable too, for a TUI that ever treats \"zqx\" specially.\n */\nexport function resolveRawTuiProbeTiming(): {\n sentinel: string;\n ackMs: number;\n retryMs: number;\n pollMs: number;\n firstOutputMaxMs: number;\n maxMs: number;\n} {\n const sentinel = process.env.CONVEYOR_PTY_RAW_PROBE_SENTINEL;\n return {\n // A sentinel must be non-empty (it is what we search for) and must stay\n // free of digits and control chars — see the note on menu dialogs above.\n sentinel: sentinel && /^[a-z]{1,8}$/.test(sentinel) ? sentinel : RAW_TUI_PROBE_SENTINEL,\n ackMs: envMs(\"CONVEYOR_PTY_RAW_PROBE_ACK_MS\", RAW_TUI_PROBE_ACK_MS),\n retryMs: envMs(\"CONVEYOR_PTY_RAW_PROBE_RETRY_MS\", RAW_TUI_PROBE_RETRY_MS),\n pollMs: envMs(\"CONVEYOR_PTY_RAW_PROBE_POLL_MS\", RAW_TUI_PROBE_POLL_MS),\n firstOutputMaxMs: envMs(\"CONVEYOR_PTY_RAW_FIRST_OUTPUT_MAX_MS\", RAW_TUI_FIRST_OUTPUT_MAX_MS),\n maxMs: envMs(\"CONVEYOR_PTY_RAW_INPUT_LIVE_MAX_MS\", RAW_TUI_INPUT_LIVE_MAX_MS),\n };\n}\n\n/**\n * Did a TUI render our probe sentinel back? Positive proof that a live input box\n * consumed the keystrokes — the one signal that discriminated correctly in\n * testing (see the rejected-signals note above).\n *\n * Pure so the matching rule is testable without a pty. Compares against ANSI-\n * stripped output because the sentinel is repainted inside styling runs.\n *\n * PRECONDITION: the child must already own the terminal. Until a TUI switches\n * the tty out of canonical mode the line discipline echoes our own keystrokes\n * straight back, which is indistinguishable from a repaint and false-positives\n * immediately. `sawTerminalSetup` is the gate for that — always wait for it\n * first.\n */\nexport function sentinelEchoed(rawOutput: string, sentinel: string): boolean {\n return cleanTerminalOutput(rawOutput, Number.MAX_SAFE_INTEGER).includes(sentinel);\n}\n\n/** DEC private mode set/reset — `ESC [ ? <params> h|l`. */\nconst DEC_PRIVATE_MODE = new RegExp(`${String.fromCharCode(27)}\\\\[\\\\?[0-9;]+[hl]`);\n\n/**\n * Has the child taken control of the terminal?\n *\n * A DEC private-mode write (alternate screen, bracketed paste, mouse tracking,\n * cursor visibility…) is the child reconfiguring the tty for full-screen use,\n * which is also when it drops canonical mode and echo. Both TUIs do it in their\n * first paint — opencode at 554ms, Claude Code at 267ms — so this is a cheap,\n * observed precondition rather than another timer.\n *\n * It is deliberately NOT used as a readiness signal on its own: opencode sets\n * bracketed-paste ~2s before it will accept input. It only tells us our own\n * keystrokes will no longer be echoed by the kernel, making a sentinel echo\n * attributable to the app.\n */\nexport function sawTerminalSetup(rawOutput: string): boolean {\n return DEC_PRIVATE_MODE.test(rawOutput);\n}\n\n/**\n * Does this adapter's first prompt write need the readiness gate?\n *\n * A per-adapter capability, NOT derived from structuredEvents: opencode keeps\n * the gate even with the events plugin wired, because its TUI silently\n * discards early stdin while painting — the pasted text itself is lost, which\n * no submit nudge can recover. Claude skips it (the nudge suffices, and its\n * numbered startup menus make stray probe keystrokes actively unsafe).\n * Exported so the contract is pinned by a test rather than resting on one\n * `if` inside the session.\n */\nexport function needsRawReadyGate(caps: { rawPromptGate: boolean }): boolean {\n return caps.rawPromptGate;\n}\n\n/**\n * Effective submit-nudge timing. The exported constants above are the production\n * defaults; `CONVEYOR_PTY_NUDGE_INTERVAL_MS` / `_SLOW_INTERVAL_MS` / `_WINDOW_MS`\n * override them. Resolved at nudge-arm time (not import) so an integration test\n * can drive the two-phase fast→slow behavior in milliseconds instead of ~15s of\n * real wall-clock. `maxPresses` is deliberately NOT overridable — the fast→slow\n * phase-boundary count is the behavior under test.\n */\nexport function resolveSubmitNudgeTiming(): {\n intervalMs: number;\n slowIntervalMs: number;\n maxPresses: number;\n windowMs: number;\n} {\n return {\n intervalMs: envMs(\"CONVEYOR_PTY_NUDGE_INTERVAL_MS\", SUBMIT_NUDGE_INTERVAL_MS),\n slowIntervalMs: envMs(\"CONVEYOR_PTY_NUDGE_SLOW_INTERVAL_MS\", SUBMIT_NUDGE_SLOW_INTERVAL_MS),\n maxPresses: SUBMIT_NUDGE_MAX_PRESSES,\n windowMs: envMs(\"CONVEYOR_PTY_NUDGE_WINDOW_MS\", SUBMIT_NUDGE_WINDOW_MS),\n };\n}\n\n/**\n * How many respawn-and-redeliver attempts a failed prompt submission gets.\n * `CONVEYOR_PTY_SUBMIT_REDELIVERY_MAX` overrides it; `0` disables recovery\n * entirely (the failure is still detected and reported). Resolved at use time\n * so tests and ops can change it without a restart-order dependency.\n */\nexport function resolveSubmitRedeliveryMaxAttempts(): number {\n const value = process.env.CONVEYOR_PTY_SUBMIT_REDELIVERY_MAX;\n // An empty string is \"unset\", not \"0\" — `Number(\"\")` is 0, which would\n // silently disable recovery for anyone exporting the var blank.\n if (!value) return SUBMIT_REDELIVERY_MAX_ATTEMPTS;\n const raw = Number(value);\n return Number.isFinite(raw) && raw >= 0 ? raw : SUBMIT_REDELIVERY_MAX_ATTEMPTS;\n}\n\nexport function resolvePlanDialogTiming(): {\n firstPressMs: number;\n intervalMs: number;\n slowIntervalMs: number;\n fastWindowMs: number;\n windowMs: number;\n} {\n return {\n firstPressMs: envMs(\"CONVEYOR_PTY_PLAN_DIALOG_FIRST_PRESS_MS\", PLAN_DIALOG_FIRST_PRESS_MS),\n intervalMs: envMs(\"CONVEYOR_PTY_PLAN_DIALOG_INTERVAL_MS\", PLAN_DIALOG_INTERVAL_MS),\n slowIntervalMs: envMs(\n \"CONVEYOR_PTY_PLAN_DIALOG_SLOW_INTERVAL_MS\",\n PLAN_DIALOG_SLOW_INTERVAL_MS,\n ),\n fastWindowMs: envMs(\"CONVEYOR_PTY_PLAN_DIALOG_FAST_WINDOW_MS\", PLAN_DIALOG_FAST_WINDOW_MS),\n windowMs: envMs(\"CONVEYOR_PTY_PLAN_DIALOG_WINDOW_MS\", PLAN_DIALOG_WINDOW_MS),\n };\n}\n\n/**\n * The per-turn subset of HarnessQueryOptions — everything that legitimately\n * changes from one turn to the next while the same `claude` process serves them\n * all. The process-level fields (model, cwd, sessionId, appendSystemPrompt, …)\n * are fixed at spawn and captured separately in the spawn options.\n */\nexport interface TurnOptions {\n canUseTool?: HarnessQueryOptions[\"canUseTool\"];\n promptDelivery?: \"submit\" | \"prefill\";\n planDialogAutoAccept?: boolean;\n abortController?: AbortController;\n}\n\nexport function turnOptionsFrom(options: HarnessQueryOptions): TurnOptions {\n return {\n canUseTool: options.canUseTool,\n promptDelivery: options.promptDelivery,\n planDialogAutoAccept: options.planDialogAutoAccept,\n abortController: options.abortController,\n };\n}\n\nexport interface PtyProcess {\n /** node-pty exposes the child's pid (its own session/process-group leader\n * via forkpty). Optional because test fakes don't model a real process. */\n pid?: number;\n onData(listener: (data: string) => void): void;\n onExit(listener: (event: { exitCode: number }) => void): void;\n write(data: string): void;\n resize(cols: number, rows: number): void;\n kill(signal?: string): void;\n}\n\nexport const KILL_ESCALATION_MS = 5_000;\n\n/**\n * Kill a pty, escalating to SIGKILL if it hasn't exited within `escalationMs`.\n * node-pty's default kill (SIGHUP) can be ignored by a wedged `claude` (e.g.\n * mid-OOM), and a fire-and-forget kill would then leak the ~1GB process on the\n * pod. `hasExited()` (backed by the caller's onExit handler) cancels the\n * escalation on a clean exit; the timer is unref'd so it never holds the\n * process open on its own.\n */\nexport function killPtyWithEscalation(\n pty: Pick<PtyProcess, \"kill\">,\n hasExited: () => boolean,\n escalationMs: number = KILL_ESCALATION_MS,\n): void {\n try {\n pty.kill();\n } catch {\n /* already exited */\n }\n const timer = setTimeout(() => {\n if (hasExited()) return;\n try {\n pty.kill(\"SIGKILL\");\n } catch {\n /* already exited */\n }\n }, escalationMs);\n timer.unref?.();\n}\n\nexport interface PtySpawnOptions {\n name: string;\n cols: number;\n rows: number;\n cwd: string;\n env: Record<string, string>;\n}\n\nexport type PtySpawn = (file: string, args: string[], options: PtySpawnOptions) => PtyProcess;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction extractSpawn(mod: unknown): PtySpawn | null {\n if (!isRecord(mod)) return null;\n if (typeof mod.spawn === \"function\") return mod.spawn as PtySpawn;\n const def = mod.default;\n if (isRecord(def) && typeof def.spawn === \"function\") return def.spawn as PtySpawn;\n return null;\n}\n\nexport async function loadPtySpawn(): Promise<PtySpawn> {\n const mod: unknown = await import(\"node-pty\");\n const spawn = extractSpawn(mod);\n if (!spawn) throw new Error(\"node-pty: spawn export not found\");\n return spawn;\n}\n\n/**\n * The spawn implementation for this pod topology: node-pty locally, or the\n * workbench launcher's remote PTY in split-mode pods (the CLI must run in the\n * workbench container, next to the repo and inside the restartable cgroup).\n * Same PtySpawn contract either way — PtySession is topology-blind.\n */\nexport async function resolvePtySpawn(): Promise<PtySpawn> {\n const { workbenchEnabled } = await import(\"../../workbench/mode.js\");\n if (!workbenchEnabled()) return loadPtySpawn();\n const { getWorkbenchClient } = await import(\"../../workbench/client.js\");\n return (file, args, options) => getWorkbenchClient().spawnPty(file, args, options);\n}\n\n/**\n * Base directory for a PTY session's control files (settings.json,\n * mcp-config, hook socket). In split-mode pods this MUST be the shared\n * emptyDir — the spawned CLI reads these paths from the workbench container,\n * and the hook helper connects back over the unix socket, which crosses\n * containers only on a shared volume.\n */\nexport function sessionTempBase(): string {\n return process.env.CONVEYOR_SHARED_DIR ?? tmpdir();\n}\n\nexport function inheritedEnv(socketPath?: string): Record<string, string> {\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (typeof value === \"string\") env[key] = value;\n }\n // Do NOT force CLAUDE_CONFIG_DIR. Forcing it to ~/.claude makes the CLI read\n // <dir>/.claude.json — a fresh, un-onboarded config — instead of the user's\n // real ~/.claude.json, which re-triggers the first-run theme picker + login\n // even though valid credentials already exist in ~/.claude/. The loop above\n // already propagates an explicitly-set CLAUDE_CONFIG_DIR (pods/codespaces),\n // and the config dir is unchanged either way, so transcript tailing (which\n // uses claudeConfigHome()) still resolves to the same projects/ directory.\n // Belt-and-braces against the ANTHROPIC_API_KEY leak: when a subscription\n // OAuth token is in play, the TUI authenticates via the synthesized\n // credentials.json — an inherited ANTHROPIC_API_KEY would be treated as an\n // EXTERNAL API key and, once interactively approved, poison auth (the token\n // is sent via x-api-key → 401 forever). The API bundle already stops serving\n // the OAuth token under that name; stripping it here means no upstream leak\n // can reach the spawned CLI regardless. The two auth modes are mutually\n // exclusive (see session-runner's onApiKeyUpdate), so a real api_key launch\n // has no CLAUDE_CODE_OAUTH_TOKEN and keeps its ANTHROPIC_API_KEY.\n if (env.CLAUDE_CODE_OAUTH_TOKEN) {\n delete env.ANTHROPIC_API_KEY;\n }\n // A GitHub App installation token dies at ~1h, but this CLI is spawned once\n // and parked for hours — its env is a snapshot we can never update. Handing\n // it `GH_TOKEN`/`GITHUB_TOKEN` therefore guarantees a 401 on every `gh` call\n // past the first hour, and `gh` prefers those variables over its config\n // file, so a fresh hosts.yml would be ignored while they are set. Drop them\n // and let `gh` read the file the refresh timer keeps current. Only ever done\n // when Conveyor owns that file — otherwise dropping them leaves no\n // credential at all. `CONVEYOR_KEEP_GH_TOKEN_ENV=1` restores the old\n // behavior for debugging.\n if (ghHostsManagedByConveyor() && env.CONVEYOR_KEEP_GH_TOKEN_ENV !== \"1\") {\n delete env.GH_TOKEN;\n delete env.GITHUB_TOKEN;\n delete env.CONVEYOR_GITHUB_TOKEN;\n // Shells and scripts that need the value read it from here, fresh.\n env.CONVEYOR_GITHUB_TOKEN_FILE = githubTokenFilePath();\n }\n if (socketPath) {\n env.CONVEYOR_HOOK_SOCKET = socketPath;\n }\n // The conveyor MCP tool handlers proxy over the agent's API socket, and a\n // mid-flap call can block up to ~50s (20s reconnect-wait + 30s ack) before\n // failing with a retryable error. The CLI's default MCP timeouts are\n // shorter — hitting them made it abandon the MCP session mid-flap\n // (2026-07-08 wedge). Default both timeouts past the worst-case hang;\n // operator-set values win via the inherit loop above.\n env.MCP_TIMEOUT ??= \"60000\";\n env.MCP_TOOL_TIMEOUT ??= \"180000\";\n return env;\n}\n\n/**\n * The bracketed-paste bytes written to the CLI's stdin to deliver a prompt.\n * The text is wrapped in paste markers so embedded newlines land as literal\n * lines in the input box instead of submitting it early. The submitting Enter\n * is deliberately NOT part of these bytes: deliverPrompt() sends it as a\n * separate write after a settle window, because an Enter folded into the same\n * chunk as the paste can be swallowed by the CLI's paste-burst handling —\n * observed in production as an auto-mode prompt parked unsubmitted in the\n * input box. \"prefill\" delivery never sends an Enter at all.\n */\nexport function buildPromptBytes(text: string): string {\n return `\\x1b[200~${text}\\x1b[201~`;\n}\n\n/**\n * Render structured (multimodal) prompt content as pasteable text. Image\n * blocks are replaced with a tool reference — their base64 payload must NEVER\n * be pasted into the TUI input box. Upstream prompt builders already skip\n * image blocks for the PTY harness; this is the last line of defense.\n */\nexport function renderPromptContentText(content: unknown[]): string {\n return content\n .map((block) => {\n const b = block as { type?: string; text?: string };\n if (b?.type === \"text\" && typeof b.text === \"string\") return b.text;\n if (b?.type === \"image\") {\n return `[Image attachment — use list_task_files / get_attachment to view]`;\n }\n return JSON.stringify(block);\n })\n .join(\"\\n\\n\");\n}\n\nexport { sleep } from \"../../utils/sleep.js\";\n\n/** Current size of the transcript, or 0 if it does not exist yet. */\nexport async function transcriptSize(path: string): Promise<number> {\n try {\n return (await stat(path)).size;\n } catch {\n return 0;\n }\n}\n\n/**\n * Defensive extraction of AskUserQuestion's `questions` input from the hook\n * payload. Malformed entries are dropped rather than thrown — the event is\n * observe-only, so an empty list still arms the waiting_for_input report.\n */\nexport function parseUserQuestions(input: Record<string, unknown>): HarnessUserQuestion[] {\n if (!Array.isArray(input.questions)) return [];\n const questions: HarnessUserQuestion[] = [];\n for (const entry of input.questions) {\n if (!isRecord(entry)) continue;\n if (typeof entry.question !== \"string\") continue;\n const options = Array.isArray(entry.options)\n ? entry.options\n .filter(isRecord)\n .filter((o) => typeof o.label === \"string\")\n .map((o) => ({\n label: o.label as string,\n description: typeof o.description === \"string\" ? o.description : \"\",\n }))\n : [];\n questions.push({\n question: entry.question,\n header: typeof entry.header === \"string\" ? entry.header : \"\",\n options,\n ...(typeof entry.multiSelect === \"boolean\" ? { multiSelect: entry.multiSelect } : {}),\n });\n }\n return questions;\n}\n","/**\n * The `claude` CLI process boundary: resolve the binary, build its argv, and\n * interpret its exit when it dies before producing a result. Kept pure so it\n * can be unit-tested without a real spawn.\n */\n\nexport interface SpawnArgsInput {\n resume?: string;\n sessionId?: string;\n model: string;\n permissionMode: \"plan\" | \"bypassPermissions\";\n settingsPath: string;\n /** Extra system-prompt text appended via `--append-system-prompt`. */\n appendSystemPrompt?: string;\n mcpConfigPath?: string;\n /** When set with mcpConfigPath, the CLI uses ONLY that config and ignores the\n * user's `~/.claude.json` / project `.mcp.json` servers. */\n strictMcpConfig?: boolean;\n}\n\nexport function resolveClaudeBinary(): string {\n return process.env.CONVEYOR_CLAUDE_BIN ?? \"claude\";\n}\n\nexport function buildSpawnArgs(input: SpawnArgsInput): string[] {\n const args: string[] = [];\n if (input.resume) {\n args.push(\"--resume\", input.resume);\n } else if (input.sessionId) {\n args.push(\"--session-id\", input.sessionId);\n }\n args.push(\"--model\", input.model);\n if (input.permissionMode === \"bypassPermissions\") {\n args.push(\"--dangerously-skip-permissions\");\n } else {\n args.push(\"--permission-mode\", \"plan\");\n }\n args.push(\"--settings\", input.settingsPath);\n if (input.appendSystemPrompt) {\n args.push(\"--append-system-prompt\", input.appendSystemPrompt);\n }\n if (input.mcpConfigPath) {\n args.push(\"--mcp-config\", input.mcpConfigPath);\n if (input.strictMcpConfig) {\n args.push(\"--strict-mcp-config\");\n }\n }\n return args;\n}\n\n/**\n * A stable fingerprint of the spawn arguments that a REUSED (kept-alive) CLI\n * process cannot change — model, permission mode, appended system prompt, and\n * cwd are all baked into the live `claude` process at spawn. When a follow-up\n * turn would spawn with different values (most commonly a drifted\n * `appendSystemPrompt` after a plan/status edit), the parked process cannot\n * serve it, so the harness respawns instead of reusing. Keeping this beside\n * `buildSpawnArgs` ensures the two can't silently diverge.\n *\n * `settingsPath`, `mcpConfigPath`, and the hook socket path are deliberately\n * excluded: they are per-process resources that stay stable for the process's\n * whole life, so they never differentiate one turn from the next.\n */\nexport function spawnOptionsFingerprint(input: {\n model: string;\n permissionMode: \"plan\" | \"bypassPermissions\";\n appendSystemPrompt?: string;\n cwd: string;\n}): string {\n return JSON.stringify([\n input.model,\n input.permissionMode,\n input.appendSystemPrompt ?? \"\",\n input.cwd,\n ]);\n}\n\n// ─── Exit diagnostics ──────────────────────────────────────────────────────\n// The PTY harness never turns raw `claude` stdout/stderr into HarnessEvents —\n// it relays them to the S5 terminal instead. So when `claude` dies before\n// emitting a transcript result, the captured agent logs show only the generic\n// \"claude exited (code N) without a result\"; the real reason (a missing binary,\n// an auth/onboarding stop, an unknown CLI flag) scrolled past in the live\n// terminal only. These helpers fold a bounded, ANSI-stripped tail of that\n// scrollback back into the error so the failure is self-describing in the logs.\n\n// ESC (0x1B) built via fromCharCode so no control char appears as a source\n// literal (keeps the no-control-regex lint rule happy). Matches CSI sequences\n// (ESC [ ... final-byte) — the bulk of TUI escape noise; any stray ESC bytes\n// from other sequences are removed by the control-char pass below.\nconst ANSI_CSI = new RegExp(`${String.fromCharCode(27)}\\\\[[0-9;?]*[ -/]*[@-~]`, \"g\");\n\n/**\n * Strip ANSI escapes + terminal control noise and collapse to the last few\n * readable lines, capped at `maxChars`. Returns \"\" when nothing printable\n * remains (e.g. the process produced no output at all).\n */\nexport function cleanTerminalOutput(raw: string, maxChars = 1200): string {\n const noAnsi = raw.replace(ANSI_CSI, \"\");\n // Drop C0 control chars (and DEL) except tab; fold CR into newline.\n let out = \"\";\n for (const ch of noAnsi) {\n const code = ch.charCodeAt(0);\n if (ch === \"\\r\" || ch === \"\\n\") out += \"\\n\";\n else if (ch === \"\\t\") out += ch;\n else if (code < 0x20 || code === 0x7f) continue;\n else out += ch;\n }\n const lines = out\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.trim().length > 0);\n const text = lines.join(\"\\n\").trim();\n return text.length > maxChars ? `…${text.slice(-maxChars)}` : text;\n}\n\n/**\n * True when the terminal tail shows node-pty failed to exec the target binary\n * (missing `claude` CLI on PATH). node-pty prints `execvp(3) failed.: No such\n * file or directory` to the pty and the child exits with code 1.\n */\nexport function isMissingBinaryFailure(tail: string): boolean {\n return /execvp\\(\\d+\\) failed|no such file or directory|command not found/i.test(tail);\n}\n\n/**\n * Build the `errors[]` for a `claude` process that exited before emitting a\n * transcript result. The first entry is kept byte-for-byte stable so existing\n * consumers/log scrapers that key off it keep working; richer context is\n * appended after it.\n */\nexport function buildExitErrors(exitCode: number, rawOutput: string, binary: string): string[] {\n const errors = [`claude exited (code ${exitCode}) without a result`];\n const tail = cleanTerminalOutput(rawOutput);\n if (isMissingBinaryFailure(tail)) {\n errors.push(\n `The \\`${binary}\\` CLI could not be started — it is not installed or not on PATH. ` +\n `Install the Claude Code CLI in this environment (npm i -g @anthropic-ai/claude-code) ` +\n `or set CONVEYOR_CLAUDE_BIN to its absolute path.`,\n );\n }\n if (tail) {\n errors.push(`Last terminal output before exit:\\n${tail}`);\n }\n return errors;\n}\n","import { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, renameSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { GitCredential } from \"@project/shared\";\n\nfunction credentialDir(cwd: string): string {\n return join(dirname(cwd), \".conveyor-git-credentials\");\n}\n\nexport function gitCredentialFile(cwd: string): string {\n const key = createHash(\"sha256\").update(cwd).digest(\"hex\").slice(0, 16);\n return join(credentialDir(cwd), `${key}.store`);\n}\n\nexport function gitCredentialHelper(cwd: string): string {\n return `store --file=${gitCredentialFile(cwd)}`;\n}\n\n/** Persist a pod-lifetime credential outside the repository with owner-only permissions. */\nexport function writeGitCredential(cwd: string, cloneUrl: string, credential: GitCredential): void {\n const cleanUrl = new URL(cloneUrl);\n if (!/^https?:$/.test(cleanUrl.protocol) || cleanUrl.username || cleanUrl.password) {\n throw new Error(\"Git clone URL must be a credential-free HTTP(S) URL\");\n }\n if (!credential.username || !credential.secret) {\n throw new Error(\"Git credential username and secret are required\");\n }\n\n const dir = credentialDir(cwd);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n\n cleanUrl.username = credential.username;\n cleanUrl.password = credential.secret;\n cleanUrl.pathname = \"/\";\n cleanUrl.search = \"\";\n cleanUrl.hash = \"\";\n\n const target = gitCredentialFile(cwd);\n writeSecretFile(target, `${cleanUrl.toString()}\\n`);\n}\n\n// ── Refreshable GitHub credential files ────────────────────────────────────\n//\n// A GitHub App installation token dies at ~1h, but the pod's `claude` CLI is\n// spawned once and parked for hours (keep-alive PTY). A child process cannot\n// see its parent's later `process.env` writes, so a token exported into the\n// child env at spawn time is frozen: every `gh` call after the first hour 401s\n// and no re-export inside the agent's shell can fix it.\n//\n// The fix is to keep the credential in FILES that every refresh path rewrites,\n// the same way `writeGitCredential` above already keeps `git push` working:\n// - `~/.config/gh/hosts.yml` — what the `gh` CLI reads when no token env var\n// shadows it (see `inheritedEnv` in harness/pty/pty-support.ts).\n// - `~/.conveyor/github-token` — a plain file any shell or script can read\n// for a value that is fresh right now.\n\n/** Plain-text file holding the current GitHub token, for shells and scripts. */\nexport function githubTokenFilePath(): string {\n return process.env.CONVEYOR_GITHUB_TOKEN_FILE || join(homedir(), \".conveyor\", \"github-token\");\n}\n\nfunction ghConfigDir(): string {\n return process.env.GH_CONFIG_DIR || join(homedir(), \".config\", \"gh\");\n}\n\n/** The `gh` CLI's credential file. */\nexport function ghHostsFilePath(): string {\n return join(ghConfigDir(), \"hosts.yml\");\n}\n\n/** Marker proving the hosts.yml alongside it is ours, not a user's own login. */\nfunction ghManagedMarkerPath(): string {\n return join(ghConfigDir(), \".conveyor-managed\");\n}\n\n/** gh's general settings file. We only care that it declares a config version. */\nfunction ghConfigFilePath(): string {\n return join(ghConfigDir(), \"config.yml\");\n}\n\n/**\n * A test run must never write real credential files into the machine's home.\n * The suites that exercise these writers point `GH_CONFIG_DIR` /\n * `CONVEYOR_GITHUB_TOKEN_FILE` at a temp dir; without an override, a vitest\n * process writes nothing. This is not theoretical — a `pushToOrigin` unit test\n * refreshing to the literal token \"new-token\" wrote that value into a live\n * pod's `~/.config/gh/hosts.yml` and broke `gh` for the whole session.\n */\nfunction blockedDefaultWrite(overrideEnvKey: string): boolean {\n return Boolean(process.env.VITEST) && !process.env[overrideEnvKey];\n}\n\n/**\n * True when Conveyor owns the `gh` credential file. Callers use this to decide\n * whether dropping a frozen token env var is safe: without our own hosts.yml,\n * removing it would leave `gh` with no credential at all.\n */\nexport function ghHostsManagedByConveyor(): boolean {\n return existsSync(ghManagedMarkerPath()) && existsSync(ghHostsFilePath());\n}\n\n/** Atomic owner-only write, creating the parent directory owner-only. */\nfunction writeSecretFile(target: string, contents: string): void {\n const dir = dirname(target);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n const temporary = `${target}.${process.pid}.tmp`;\n writeFileSync(temporary, contents, { encoding: \"utf8\", mode: 0o600 });\n chmodSync(temporary, 0o600);\n renameSync(temporary, target);\n}\n\nfunction writeGithubTokenFile(token: string): boolean {\n if (blockedDefaultWrite(\"CONVEYOR_GITHUB_TOKEN_FILE\")) return false;\n writeSecretFile(githubTokenFilePath(), `${token}\\n`);\n return true;\n}\n\n/**\n * Declare the config version so gh treats hosts.yml as already migrated.\n * Without this, every gh invocation runs the multi-account migration, which\n * calls the API to resolve the account name — and an expired token then fails\n * the whole command with \"cowardly refusing to continue with multi account\n * migration\" instead of a plain 401. The agent is told to answer a 401 by\n * refreshing the token, so the plain 401 is the failure we want. Only written\n * when absent: config.yml also holds user preferences we must not overwrite.\n */\nfunction ensureGhConfigVersion(): void {\n if (existsSync(ghConfigFilePath())) return;\n writeSecretFile(ghConfigFilePath(), 'version: \"1\"\\n');\n}\n\n/**\n * Write the `gh` CLI credential file. Both the top-level keys and the `users`\n * map are emitted: gh reads the flat `oauth_token` and newer versions also\n * expect the per-user entry, so writing both keeps one file valid for either.\n */\nfunction writeGhHostsConfig(token: string): boolean {\n if (blockedDefaultWrite(\"GH_CONFIG_DIR\")) return false;\n // Never clobber a `gh` login this pod did not create — an environment that\n // authenticates gh for us (a GitHub Codespace, a developer's own machine)\n // keeps its own file, and the env-stripping caller then leaves that\n // environment's token variables in place.\n if (existsSync(ghHostsFilePath()) && !existsSync(ghManagedMarkerPath())) return false;\n const host = process.env.GH_HOST || \"github.com\";\n const user = process.env.CONVEYOR_GIT_USERNAME || \"x-access-token\";\n const contents = [\n \"# Written by conveyor-agent — refreshed on every GitHub token refresh.\",\n \"# Edits are overwritten. Do not add a second host entry here by hand.\",\n `${host}:`,\n ` oauth_token: ${token}`,\n ` user: ${user}`,\n \" git_protocol: https\",\n \" users:\",\n ` ${user}:`,\n ` oauth_token: ${token}`,\n \"\",\n ].join(\"\\n\");\n writeSecretFile(ghHostsFilePath(), contents);\n writeSecretFile(ghManagedMarkerPath(), \"conveyor-agent\\n\");\n ensureGhConfigVersion();\n return true;\n}\n\nexport interface GithubTokenFileSync {\n tokenFile: boolean;\n ghHosts: boolean;\n}\n\n/**\n * Refresh every file-based copy of the GitHub token. Never throws — a failed\n * write must not break the caller's real work (a push, a boot, a refresh\n * tick); the return value says which copies are now current.\n */\nexport function syncGithubTokenFiles(token: string | undefined): GithubTokenFileSync {\n const result: GithubTokenFileSync = { tokenFile: false, ghHosts: false };\n if (!token) return result;\n try {\n result.tokenFile = writeGithubTokenFile(token);\n } catch {\n // best effort\n }\n try {\n result.ghHosts = writeGhHostsConfig(token);\n } catch {\n // best effort\n }\n return result;\n}\n","export function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","import { spawn, execSync, type ChildProcess } from \"node:child_process\";\n\n/**\n * The structural surface of a start-command child the supervisor manages —\n * satisfied by a local ChildProcess and by the workbench client's\n * RemoteProcessHandle (split-mode pods, where the process lives in the\n * workbench container).\n */\nexport interface ManagedChildProcess extends NodeJS.EventEmitter {\n pid?: number | undefined;\n exitCode: number | null;\n kill(signal?: NodeJS.Signals | number): boolean;\n}\n\nconst PROCESS_TERMINATION_GRACE_MS = 5_000;\n\nfunction abortError(): Error {\n const error = new Error(\"Operation aborted\");\n error.name = \"AbortError\";\n return error;\n}\n\nfunction signalProcessGroup(child: ManagedChildProcess, signal: NodeJS.Signals): void {\n try {\n if (child.pid) process.kill(-child.pid, signal);\n else child.kill(signal);\n } catch {\n try {\n child.kill(signal);\n } catch {\n // The process already exited.\n }\n }\n}\n\nexport function terminateProcessGroup(\n // ChildProcess structurally satisfies ManagedChildProcess, so the single type\n // covers both callers; keeping them as a union makes the shared EventEmitter\n // methods (once/removeListener) non-callable under @types/node's overloads.\n child: ManagedChildProcess,\n graceMs = PROCESS_TERMINATION_GRACE_MS,\n): Promise<void> {\n if (child.exitCode !== null) return Promise.resolve();\n return new Promise((resolve) => {\n let settled = false;\n const finish = (): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.removeListener(\"exit\", finish);\n resolve();\n };\n const timer = setTimeout(() => {\n signalProcessGroup(child, \"SIGKILL\");\n finish();\n }, graceMs);\n timer.unref();\n child.once(\"exit\", finish);\n signalProcessGroup(child, \"SIGTERM\");\n });\n}\n\nexport function runSetupCommand(\n cmd: string,\n cwd: string,\n onOutput: (stream: \"stdout\" | \"stderr\", data: string) => void,\n signal?: AbortSignal,\n): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError());\n return new Promise((resolve, reject) => {\n const child = spawn(\"sh\", [\"-c\", cmd], {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: true,\n env: { ...process.env },\n });\n let settled = false;\n let aborting = false;\n const cleanup = (): void => signal?.removeEventListener(\"abort\", onAbort);\n const settle = (error?: Error): void => {\n if (settled) return;\n settled = true;\n cleanup();\n if (error) reject(error);\n else resolve();\n };\n const onAbort = (): void => {\n if (settled || aborting) return;\n aborting = true;\n void terminateProcessGroup(child).then(() => settle(abortError()));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (signal?.aborted) onAbort();\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (aborting || signal?.aborted) return;\n onOutput(\"stdout\", chunk.toString());\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n if (aborting || signal?.aborted) return;\n onOutput(\"stderr\", chunk.toString());\n });\n\n child.on(\"close\", (code) => {\n if (aborting) return;\n settle(code === 0 ? undefined : new Error(`Setup command exited with code ${code}`));\n });\n\n child.on(\"error\", (err) => {\n if (!aborting) settle(err);\n });\n });\n}\n\nconst AUTH_TOKEN_TIMEOUT_MS = 30_000;\n\nexport function runAuthTokenCommand(cmd: string, userEmail: string, cwd: string): string | null {\n try {\n const output = execSync(`${cmd} ${JSON.stringify(userEmail)}`, {\n cwd,\n timeout: AUTH_TOKEN_TIMEOUT_MS,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n env: { ...process.env },\n });\n const token = output.toString().trim();\n return token || null;\n } catch {\n return null;\n }\n}\n\nexport function runStartCommand(\n cmd: string,\n cwd: string,\n onOutput: (stream: \"stdout\" | \"stderr\", data: string) => void,\n): ChildProcess {\n const child = spawn(\"sh\", [\"-c\", cmd], {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: true,\n env: { ...process.env },\n });\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n onOutput(\"stdout\", chunk.toString());\n });\n\n child.stderr.on(\"data\", (chunk: Buffer) => {\n onOutput(\"stderr\", chunk.toString());\n });\n\n child.unref();\n return child;\n}\n"],"mappings":";AAQA,SAAS,YAAY;AACrB,SAAS,cAAc;;;ACWhB,SAAS,sBAA8B;AAC5C,SAAO,QAAQ,IAAI,uBAAuB;AAC5C;AAEO,SAAS,eAAe,OAAiC;AAC9D,QAAM,OAAiB,CAAC;AACxB,MAAI,MAAM,QAAQ;AAChB,SAAK,KAAK,YAAY,MAAM,MAAM;AAAA,EACpC,WA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AAU,MAAM,SAAS,CAAC;AAAA,EACrC,CAAC;AAED,QAAM,OAAO,GAAG,QAAQ,CAAC,UAAkB;AACzC,aAAS,UAAU,MAAM,SAAS,CAAC;AAAA,EACrC,CAAC;AAED,QAAM,MAAM;AACZ,SAAO;AACT;","names":["spawn"]}
|
|
@@ -3,13 +3,11 @@ import {
|
|
|
3
3
|
DEFAULT_RETRY_DELAY_MS,
|
|
4
4
|
FETCH_TIMEOUT_MS,
|
|
5
5
|
GIT_PREP_MAX_RETRIES,
|
|
6
|
-
gitCredentialHelper,
|
|
7
6
|
mapChatHistory,
|
|
8
7
|
readAgentVersion,
|
|
9
8
|
registerBootMilestoneSocketFallback,
|
|
10
|
-
reportBootMilestone
|
|
11
|
-
|
|
12
|
-
} from "./chunk-7765OQU5.js";
|
|
9
|
+
reportBootMilestone
|
|
10
|
+
} from "./chunk-WVUQ5CH5.js";
|
|
13
11
|
import {
|
|
14
12
|
LoopLagMonitor,
|
|
15
13
|
buildConveyorSocketOptions,
|
|
@@ -32,6 +30,8 @@ import {
|
|
|
32
30
|
buildPromptBytes,
|
|
33
31
|
buildSpawnArgs,
|
|
34
32
|
cleanTerminalOutput,
|
|
33
|
+
gitCredentialHelper,
|
|
34
|
+
githubTokenFilePath,
|
|
35
35
|
inheritedEnv,
|
|
36
36
|
killPtyWithEscalation,
|
|
37
37
|
needsRawReadyGate,
|
|
@@ -49,9 +49,11 @@ import {
|
|
|
49
49
|
sessionTempBase,
|
|
50
50
|
sleep,
|
|
51
51
|
spawnOptionsFingerprint,
|
|
52
|
+
syncGithubTokenFiles,
|
|
52
53
|
transcriptSize,
|
|
53
|
-
turnOptionsFrom
|
|
54
|
-
|
|
54
|
+
turnOptionsFrom,
|
|
55
|
+
writeGitCredential
|
|
56
|
+
} from "./chunk-PWYJZY3P.js";
|
|
55
57
|
|
|
56
58
|
// src/setup/bootstrap.ts
|
|
57
59
|
var BOOTSTRAP_TIMEOUT_MS = 3e4;
|
|
@@ -1159,6 +1161,8 @@ ${q.question}${q.options.length ? "\n" + q.options.map((o) => `- ${o.label}: ${o
|
|
|
1159
1161
|
if (!result.ok) return { refreshedClaude: false, refreshedTaskToken: false };
|
|
1160
1162
|
const previousTaskToken = process.env.CONVEYOR_TASK_TOKEN;
|
|
1161
1163
|
applyBootstrapToEnv(result.config);
|
|
1164
|
+
const env = result.config.envVars ?? {};
|
|
1165
|
+
syncGithubTokenFiles(env.CONVEYOR_GITHUB_TOKEN ?? env.GH_TOKEN ?? env.GITHUB_TOKEN);
|
|
1162
1166
|
const refreshedTaskToken = result.config.mode !== "project" && Boolean(result.config.taskToken) && result.config.taskToken !== previousTaskToken;
|
|
1163
1167
|
if (refreshedTaskToken && result.config.taskToken) {
|
|
1164
1168
|
this.config.taskToken = result.config.taskToken;
|
|
@@ -1188,7 +1192,10 @@ ${q.question}${q.options.length ? "\n" + q.options.map((o) => `- ${o.label}: ${o
|
|
|
1188
1192
|
for (const [key, value] of Object.entries(bundle.envVars ?? {})) {
|
|
1189
1193
|
process.env[key] = value;
|
|
1190
1194
|
}
|
|
1191
|
-
if (bundle.githubToken)
|
|
1195
|
+
if (bundle.githubToken) {
|
|
1196
|
+
process.env.CONVEYOR_GITHUB_TOKEN = bundle.githubToken;
|
|
1197
|
+
syncGithubTokenFiles(bundle.githubToken);
|
|
1198
|
+
}
|
|
1192
1199
|
if (bundle.anthropicKey) process.env.ANTHROPIC_API_KEY = bundle.anthropicKey;
|
|
1193
1200
|
if (bundle.gcpToken) process.env.CLOUDSDK_AUTH_ACCESS_TOKEN = bundle.gcpToken;
|
|
1194
1201
|
const refreshedTaskToken = Boolean(bundle.sessionJwt) && bundle.sessionJwt !== previousTaskToken;
|
|
@@ -1473,6 +1480,7 @@ async function updateRemoteToken(cwd, token) {
|
|
|
1473
1480
|
const cloneUrl = process.env.CONVEYOR_GIT_CLONE_URL || void 0;
|
|
1474
1481
|
await updateRemoteCredential(cwd, { username, secret: token, cloneUrl });
|
|
1475
1482
|
process.env.CONVEYOR_GIT_SECRET = token;
|
|
1483
|
+
syncGithubTokenFiles(token);
|
|
1476
1484
|
}
|
|
1477
1485
|
function wipRefForBranch(branch) {
|
|
1478
1486
|
return `conveyor-wip/${branch}`;
|
|
@@ -2625,6 +2633,20 @@ var GetProjectTagRequestSchema = z5.object({
|
|
|
2625
2633
|
/** Tag id or exact (case-insensitive) tag name. */
|
|
2626
2634
|
tag: z5.string().min(1).max(100)
|
|
2627
2635
|
});
|
|
2636
|
+
var ListProjectTagAttachmentsRequestSchema = z5.object({
|
|
2637
|
+
projectId: z5.string(),
|
|
2638
|
+
/** Tag id or exact (case-insensitive) tag name. */
|
|
2639
|
+
tag: z5.string().min(1).max(100),
|
|
2640
|
+
limit: z5.number().int().min(1).max(60).optional(),
|
|
2641
|
+
offset: z5.number().int().min(0).optional()
|
|
2642
|
+
});
|
|
2643
|
+
var SetProjectFileTagsRequestSchema = z5.object({
|
|
2644
|
+
projectId: z5.string(),
|
|
2645
|
+
taskId: z5.string(),
|
|
2646
|
+
fileId: z5.string(),
|
|
2647
|
+
tags: z5.array(z5.string().min(1).max(MAX_FILE_TAG_LENGTH)).max(MAX_FILE_TAGS),
|
|
2648
|
+
requestingUserId: z5.string().optional()
|
|
2649
|
+
});
|
|
2628
2650
|
var GetProjectSummaryRequestSchema = z5.object({
|
|
2629
2651
|
projectId: z5.string()
|
|
2630
2652
|
});
|
|
@@ -9936,11 +9958,11 @@ var readTaskChatContract = defineToolContract({
|
|
|
9936
9958
|
var listTagsContract = defineToolContract({
|
|
9937
9959
|
name: "list_tags",
|
|
9938
9960
|
agent: {
|
|
9939
|
-
description: "List the project glossary: every tag's id, name, color, description, parent/child tag ids, its contextPaths (the rule/doc/file/folder links it wires into agent context \u2014 `[]` means none),
|
|
9961
|
+
description: "List the project glossary: every tag's id, name, color, description, parent/child tag ids, its contextPaths (the rule/doc/file/folder links it wires into agent context \u2014 `[]` means none), whether it carries a full overview (fetch that with get_tag), and its attachmentCount (files labelled as examples of the term). The context links ship inline, so you only need get_tag for a term's full overview. Use the ids with get_tag / update_tag.",
|
|
9940
9962
|
fields: {}
|
|
9941
9963
|
},
|
|
9942
9964
|
mcp: {
|
|
9943
|
-
description: "List all project tags with names, IDs, colors, descriptions, hierarchy (parent/child ids), contextPaths (the rule/doc/file/folder links each tag wires into agent context \u2014 `[]` means none),
|
|
9965
|
+
description: "List all project tags with names, IDs, colors, descriptions, hierarchy (parent/child ids), contextPaths (the rule/doc/file/folder links each tag wires into agent context \u2014 `[]` means none), a hasOverview flag, and an attachmentCount (files labelled as examples of the term \u2014 read the tiles with list_tag_attachments). Context links ship inline; call get_tag only for a term's full overview. Pass projectId to target a specific project; otherwise the configured default project is used.",
|
|
9944
9966
|
fields: {
|
|
9945
9967
|
projectId: mcpProjectId
|
|
9946
9968
|
}
|
|
@@ -10047,13 +10069,13 @@ var tagRef = f.string({
|
|
|
10047
10069
|
var getTagContract = defineToolContract({
|
|
10048
10070
|
name: "get_tag",
|
|
10049
10071
|
agent: {
|
|
10050
|
-
description: "Read one tag's full glossary entry: description, the full markdown overview (the term's spec \u2014 philosophy, mechanics, invariants), linked files/rules (each with its verified-link status \u2014 ok/stale/unchecked \u2014 from the periodic repo check), parent/child tags, active-card count, and recent revisions with their reasons. Call this whenever a chat message, plan, or tag list points at a term you need the full context for. A response with `overviewPath` set means the overview is sourced from that repo file \u2014 prefer Reading the path from your checkout (branch-correct); the served overview is the base-branch materialization (`overviewSource.state`: ok/pending/stale).",
|
|
10072
|
+
description: "Read one tag's full glossary entry: description, the full markdown overview (the term's spec \u2014 philosophy, mechanics, invariants), linked files/rules (each with its verified-link status \u2014 ok/stale/unchecked \u2014 from the periodic repo check), parent/child tags, active-card count, attachment count (files labelled as examples of the term), and recent revisions with their reasons. Call this whenever a chat message, plan, or tag list points at a term you need the full context for. A response with `overviewPath` set means the overview is sourced from that repo file \u2014 prefer Reading the path from your checkout (branch-correct); the served overview is the base-branch materialization (`overviewSource.state`: ok/pending/stale).",
|
|
10051
10073
|
fields: {
|
|
10052
10074
|
tag: tagRef
|
|
10053
10075
|
}
|
|
10054
10076
|
},
|
|
10055
10077
|
mcp: {
|
|
10056
|
-
description: "Read one tag's full glossary entry \u2014 description, markdown overview, context links (each with its verified-link status: ok/stale/unchecked plus last-checked provenance), parent/child tags, active-card count, and recent revisions with provenance. A response with `overviewPath` set means the overview is sourced from that repo file at the base branch (`overviewSource.state`: ok/pending/stale) \u2014 clients with a checkout can read the path directly for the branch-correct copy. Pass projectId to target a specific project; otherwise the configured default project is used.",
|
|
10078
|
+
description: "Read one tag's full glossary entry \u2014 description, markdown overview, context links (each with its verified-link status: ok/stale/unchecked plus last-checked provenance), parent/child tags, active-card count, attachment count (files labelled as examples of the term \u2014 read the tiles with list_tag_attachments), and recent revisions with provenance. A response with `overviewPath` set means the overview is sourced from that repo file at the base branch (`overviewSource.state`: ok/pending/stale) \u2014 clients with a checkout can read the path directly for the branch-correct copy. Pass projectId to target a specific project; otherwise the configured default project is used.",
|
|
10057
10079
|
fields: {
|
|
10058
10080
|
projectId: mcpProjectId,
|
|
10059
10081
|
tag: tagRef
|
|
@@ -11137,10 +11159,45 @@ function buildVoteSuggestionTool(connection) {
|
|
|
11137
11159
|
}
|
|
11138
11160
|
);
|
|
11139
11161
|
}
|
|
11162
|
+
function buildRefreshGithubTokenTool(connection, config) {
|
|
11163
|
+
return defineTool(
|
|
11164
|
+
"refresh_github_token",
|
|
11165
|
+
"Mint a fresh GitHub token for this pod when git or gh fails with a 401 / 'Bad credentials'. The pod's token expires about every hour. This updates the git credential store and the gh CLI config, and returns the shell command that puts a current token in your environment.",
|
|
11166
|
+
{},
|
|
11167
|
+
async () => {
|
|
11168
|
+
try {
|
|
11169
|
+
const result = await connection.call("refreshGithubToken", {
|
|
11170
|
+
sessionId: connection.sessionId
|
|
11171
|
+
});
|
|
11172
|
+
await updateRemoteToken(config.workspaceDir, result.token);
|
|
11173
|
+
process.env.GITHUB_TOKEN = result.token;
|
|
11174
|
+
process.env.GH_TOKEN = result.token;
|
|
11175
|
+
const tokenFile = githubTokenFilePath();
|
|
11176
|
+
return textResult(
|
|
11177
|
+
[
|
|
11178
|
+
"GitHub token refreshed.",
|
|
11179
|
+
"- git: the credential store is updated, so `git push` works now with no extra step.",
|
|
11180
|
+
"- gh: the CLI config is updated, so `gh` works now with no extra step.",
|
|
11181
|
+
`- shell/scripts: read the current token from ${tokenFile}.`,
|
|
11182
|
+
` For a command that needs it in the environment: GITHUB_TOKEN=$(cat ${tokenFile}) <command>`,
|
|
11183
|
+
"Retry the failed command. If it still returns 401, the GitHub App install may be missing for this project \u2014 report that instead of retrying."
|
|
11184
|
+
].join("\n")
|
|
11185
|
+
);
|
|
11186
|
+
} catch (error) {
|
|
11187
|
+
return textResult(
|
|
11188
|
+
`Failed to refresh the GitHub token: ${error instanceof Error ? error.message : "Unknown error"}
|
|
11189
|
+
|
|
11190
|
+
The agent's connection to the API may be down. Wait for it to reconnect and try again.`
|
|
11191
|
+
);
|
|
11192
|
+
}
|
|
11193
|
+
}
|
|
11194
|
+
);
|
|
11195
|
+
}
|
|
11140
11196
|
function buildMutationTools(connection, config) {
|
|
11141
11197
|
return [
|
|
11142
11198
|
buildPostToChatTool(connection),
|
|
11143
11199
|
buildCreatePullRequestTool(connection, config),
|
|
11200
|
+
buildRefreshGithubTokenTool(connection, config),
|
|
11144
11201
|
buildAddDependencyTool(connection),
|
|
11145
11202
|
buildRemoveDependencyTool(connection),
|
|
11146
11203
|
buildCreateFollowUpTaskTool(connection),
|
|
@@ -16308,4 +16365,4 @@ export {
|
|
|
16308
16365
|
loadConveyorConfig,
|
|
16309
16366
|
unshallowRepo
|
|
16310
16367
|
};
|
|
16311
|
-
//# sourceMappingURL=chunk-
|
|
16368
|
+
//# sourceMappingURL=chunk-VIEBOAJ7.js.map
|