aligndev 0.23.3 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +74 -19
  2. package/dist/alignfirst-cli.d.ts +1 -0
  3. package/dist/alignfirst-cli.js +43 -1
  4. package/dist/cli.js +7 -14
  5. package/dist/code/claude-agent.d.ts +1 -1
  6. package/dist/code/claude-agent.js +25 -11
  7. package/dist/code/code-cli.d.ts +9 -4
  8. package/dist/code/code-cli.js +216 -84
  9. package/dist/code/codex-agent.d.ts +2 -2
  10. package/dist/code/codex-agent.js +24 -8
  11. package/dist/code/codex-rollout.d.ts +1 -1
  12. package/dist/code/codex-rollout.js +9 -5
  13. package/dist/code/coding-agent.d.ts +1 -1
  14. package/dist/code/coding-agent.js +13 -4
  15. package/dist/code/models.d.ts +2 -2
  16. package/dist/code/models.js +27 -15
  17. package/dist/code/native-context.d.ts +2 -0
  18. package/dist/code/native-context.js +21 -0
  19. package/dist/code/pi-agent.d.ts +2 -0
  20. package/dist/code/pi-agent.js +240 -0
  21. package/dist/code/quota-process.d.ts +9 -0
  22. package/dist/code/quota-process.js +165 -0
  23. package/dist/code/quota.d.ts +2 -3
  24. package/dist/code/quota.js +92 -98
  25. package/dist/code/run-agent.d.ts +12 -3
  26. package/dist/code/run-agent.js +48 -19
  27. package/dist/code/session-file.d.ts +3 -0
  28. package/dist/code/session-file.js +33 -10
  29. package/dist/config.d.ts +44 -7
  30. package/dist/config.js +163 -36
  31. package/dist/guide/code-guide.d.ts +2 -2
  32. package/dist/guide/code-guide.js +17 -6
  33. package/dist/guide/guide-cli.js +16 -7
  34. package/dist/json-shape.d.ts +3 -0
  35. package/dist/json-shape.js +23 -0
  36. package/dist/package-version.d.ts +1 -0
  37. package/dist/package-version.js +7 -0
  38. package/dist/project/layout.d.ts +4 -0
  39. package/dist/project/layout.js +28 -10
  40. package/dist/project/render.js +3 -1
  41. package/dist/project/status.d.ts +2 -1
  42. package/dist/project/status.js +1 -0
  43. package/package.json +1 -1
  44. package/templates/guide/code.md +102 -21
  45. package/templates/guide/playbook/consultation.md +5 -0
  46. package/templates/guide/playbook/playbook.md +12 -2
  47. package/templates/guide/playbook/project-workspace-setup.md +1 -1
  48. package/templates/guide/playbook/working-session.md +10 -0
@@ -0,0 +1,165 @@
1
+ const OUTPUT_LIMIT_BYTES = 1_048_576;
2
+ const TERMINATION_GRACE_MS = 250;
3
+ const KILL_GRACE_MS = 1_000;
4
+ export function runQuotaProcess(child, protocol) {
5
+ return new Promise((resolve, reject) => {
6
+ const state = {
7
+ child,
8
+ protocol,
9
+ completing: false,
10
+ closed: false,
11
+ bytes: 0,
12
+ release: () => { },
13
+ resolve,
14
+ reject,
15
+ };
16
+ state.release = observeProcess(state);
17
+ state.requestTimer = setTimeout(() => finish(state, new Error(`${protocol.source} timed out while reading usage limits.`)), protocol.timeoutMs);
18
+ try {
19
+ protocol.start?.((message) => writeMessage(state, message));
20
+ }
21
+ catch {
22
+ finish(state, new Error(`${protocol.source} could not write the quota request.`));
23
+ }
24
+ });
25
+ }
26
+ function observeProcess(state) {
27
+ const { child, protocol } = state;
28
+ const exitGuard = () => signalChild(state, "SIGKILL");
29
+ const onSignal = () => finish(state, new Error(`${protocol.source} quota request was terminated.`));
30
+ const onError = () => finish(state, new Error(`${protocol.source} quota process could not start.`));
31
+ const onInputError = () => finish(state, new Error(`${protocol.source} could not write the quota request.`));
32
+ const onOutputError = () => finish(state, new Error(`${protocol.source} could not read quota output.`));
33
+ const onStdout = (chunk) => readStdout(state, chunk);
34
+ const onStderr = (chunk) => acceptOutput(state, chunk);
35
+ const onClose = (code) => closeProcess(state, code);
36
+ process.on("exit", exitGuard);
37
+ process.on("SIGINT", onSignal);
38
+ process.on("SIGTERM", onSignal);
39
+ child.on("error", onError);
40
+ child.once("close", onClose);
41
+ child.stdin.on("error", onInputError);
42
+ child.stdout.on("error", onOutputError);
43
+ child.stderr.on("error", onOutputError);
44
+ child.stdout.setEncoding("utf8");
45
+ child.stderr.setEncoding("utf8");
46
+ child.stdout.on("data", onStdout);
47
+ child.stderr.on("data", onStderr);
48
+ return () => {
49
+ process.off("exit", exitGuard);
50
+ process.off("SIGINT", onSignal);
51
+ process.off("SIGTERM", onSignal);
52
+ child.off("error", onError);
53
+ child.off("close", onClose);
54
+ child.stdin.off("error", onInputError);
55
+ child.stdout.off("error", onOutputError);
56
+ child.stderr.off("error", onOutputError);
57
+ child.stdout.off("data", onStdout);
58
+ child.stderr.off("data", onStderr);
59
+ };
60
+ }
61
+ function signalChild(state, signal) {
62
+ if (state.child.exitCode !== null || state.child.signalCode !== null)
63
+ return;
64
+ try {
65
+ state.child.kill(signal);
66
+ }
67
+ catch {
68
+ state.error = new Error(`${state.protocol.source} quota process could not be terminated.`);
69
+ }
70
+ }
71
+ function finish(state, error, result) {
72
+ if (state.completing)
73
+ return;
74
+ state.completing = true;
75
+ state.error = error;
76
+ state.result = result;
77
+ clearTimeout(state.requestTimer);
78
+ if (state.closed) {
79
+ settle(state);
80
+ return;
81
+ }
82
+ try {
83
+ state.child.stdin.end();
84
+ }
85
+ catch {
86
+ state.error = new Error(`${state.protocol.source} could not close the quota request.`);
87
+ }
88
+ signalChild(state, "SIGTERM");
89
+ state.terminationTimer = setTimeout(() => {
90
+ signalChild(state, "SIGKILL");
91
+ state.killTimer = setTimeout(() => cleanupExpired(state), KILL_GRACE_MS);
92
+ }, TERMINATION_GRACE_MS);
93
+ }
94
+ function settle(state) {
95
+ clearTimeout(state.requestTimer);
96
+ clearTimeout(state.terminationTimer);
97
+ clearTimeout(state.killTimer);
98
+ state.release();
99
+ if (state.error !== undefined)
100
+ state.reject(state.error);
101
+ else if (state.result !== undefined)
102
+ state.resolve(state.result);
103
+ else
104
+ state.reject(new Error(`${state.protocol.source} returned no usage response.`));
105
+ }
106
+ function cleanupExpired(state) {
107
+ // Pipe owners outside the direct child must not keep the request pending.
108
+ state.child.stdin.destroy();
109
+ state.child.stdout.destroy();
110
+ state.child.stderr.destroy();
111
+ state.error = new Error(`${state.protocol.source} quota process cleanup did not complete.`);
112
+ if (state.child.exitCode !== null || state.child.signalCode !== null)
113
+ settle(state);
114
+ // Retain guards/listeners until unresolved ownership ends, even after reporting failure.
115
+ else
116
+ state.reject(state.error);
117
+ }
118
+ function writeMessage(state, message) {
119
+ if (state.completing)
120
+ return;
121
+ try {
122
+ state.child.stdin.write(`${JSON.stringify(message)}\n`);
123
+ }
124
+ catch {
125
+ finish(state, new Error(`${state.protocol.source} could not write the quota request.`));
126
+ }
127
+ }
128
+ function readStdout(state, chunk) {
129
+ if (!acceptOutput(state, chunk))
130
+ return;
131
+ try {
132
+ const result = state.protocol.stdout(chunk, (message) => writeMessage(state, message));
133
+ if (result !== undefined)
134
+ finish(state, undefined, result);
135
+ }
136
+ catch (error) {
137
+ finish(state, error instanceof Error ? error : new Error("Malformed quota response."));
138
+ }
139
+ }
140
+ function acceptOutput(state, chunk) {
141
+ if (state.completing)
142
+ return false;
143
+ state.bytes += Buffer.byteLength(chunk);
144
+ if (state.bytes <= OUTPUT_LIMIT_BYTES)
145
+ return true;
146
+ finish(state, new Error(`${state.protocol.source} quota output exceeded the safety limit.`));
147
+ return false;
148
+ }
149
+ function closeProcess(state, code) {
150
+ state.closed = true;
151
+ if (state.completing) {
152
+ settle(state);
153
+ return;
154
+ }
155
+ if (state.protocol.close === undefined) {
156
+ finish(state, new Error(`${state.protocol.source} exited before returning usage limits; check native authentication.`));
157
+ return;
158
+ }
159
+ try {
160
+ finish(state, undefined, state.protocol.close(code));
161
+ }
162
+ catch (error) {
163
+ finish(state, error instanceof Error ? error : new Error("Quota request failed."));
164
+ }
165
+ }
@@ -1,12 +1,11 @@
1
1
  import { type ChildProcessWithoutNullStreams } from "node:child_process";
2
- import type { CodingAgent } from "./coding-agent.js";
2
+ import type { QuotaSource } from "../config.js";
3
3
  export declare const readQuota: QuotaReader;
4
4
  export interface QuotaContext {
5
5
  cwd: string;
6
6
  env: NodeJS.ProcessEnv;
7
- unset: readonly string[];
8
7
  }
9
- export type QuotaReader = (agent: CodingAgent, context: QuotaContext) => Promise<string>;
8
+ export type QuotaReader = (source: QuotaSource, context: QuotaContext) => Promise<string>;
10
9
  export interface QuotaProcessAdapter {
11
10
  execute(file: string, args: string[], options: QuotaProcessOptions & {
12
11
  timeout: number;
@@ -1,6 +1,5 @@
1
- import { execFile, spawn } from "node:child_process";
2
- import { promisify } from "node:util";
3
- import { buildAgentEnv } from "./run-agent.js";
1
+ import { spawn } from "node:child_process";
2
+ import { runQuotaProcess } from "./quota-process.js";
4
3
  const QUOTA_TIMEOUT_MS = 30_000;
5
4
  const CLAUDE_PRIVACY_OPT_OUTS = [
6
5
  "DISABLE_TELEMETRY",
@@ -9,18 +8,24 @@ const CLAUDE_PRIVACY_OPT_OUTS = [
9
8
  "DISABLE_BUG_COMMAND",
10
9
  "CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY",
11
10
  ];
12
- const execFileAsync = promisify(execFile);
13
11
  const DEFAULT_QUOTA_PROCESS_ADAPTER = {
14
12
  execute: executeQuotaProcess,
15
13
  spawn: spawnQuotaProcess,
16
14
  };
17
15
  export const readQuota = createQuotaReader();
18
16
  export function createQuotaReader(adapter = DEFAULT_QUOTA_PROCESS_ADAPTER, timeoutMs = QUOTA_TIMEOUT_MS) {
19
- return async (agent, context) => {
20
- const env = buildAgentEnv(context.env, context.unset);
21
- return agent === "claude"
22
- ? readClaudeQuota({ ...context, env: translateClaudePrivacyOptOut(env) }, adapter, timeoutMs)
23
- : readCodexQuota({ ...context, env }, adapter, timeoutMs);
17
+ return async (source, context) => {
18
+ try {
19
+ return source === "claude"
20
+ ? await readClaudeQuota({ ...context, env: translateClaudePrivacyOptOut({ ...context.env }) }, adapter, timeoutMs)
21
+ : await readCodexQuota(context, adapter, timeoutMs);
22
+ }
23
+ catch (error) {
24
+ if (error instanceof Error && /^(Codex|Claude Code) /.test(error.message))
25
+ throw error;
26
+ throw new Error(`${source === "claude" ? "Claude Code" : "Codex"} quota command failed; ` +
27
+ "check that the native CLI is installed and authenticated in the selected configuration.");
28
+ }
24
29
  };
25
30
  }
26
31
  function translateClaudePrivacyOptOut(env) {
@@ -71,48 +76,33 @@ function requestCodexQuota(context, adapter, timeoutMs) {
71
76
  return exchangeCodexMessages(child, timeoutMs);
72
77
  }
73
78
  function exchangeCodexMessages(child, timeoutMs) {
74
- const detachGuard = guardChild(child);
75
- return new Promise((resolve, reject) => {
76
- let settled = false;
77
- const finish = (error, result) => {
78
- if (settled)
79
- return;
80
- settled = true;
81
- clearTimeout(timer);
82
- detachGuard();
83
- child.kill("SIGTERM");
84
- if (error)
85
- reject(error);
86
- else
87
- resolve(result);
88
- };
89
- const timer = setTimeout(() => finish(new Error("Codex timed out while reading usage limits.")), timeoutMs);
90
- const readStderr = observeCodexOutput(child, finish);
91
- observeCodexLifecycle(child, finish, () => settled, readStderr);
92
- initializeCodex(child);
93
- });
94
- }
95
- function guardChild(child) {
96
- const kill = () => {
97
- if (child.exitCode === null && child.signalCode === null)
98
- child.kill("SIGTERM");
99
- };
100
- process.on("exit", kill);
101
- return () => process.off("exit", kill);
102
- }
103
- function observeCodexOutput(child, finish) {
104
79
  let stdout = "";
105
- let stderr = "";
106
- child.stdout.setEncoding("utf8");
107
- child.stdout.on("data", (chunk) => {
108
- stdout += chunk;
109
- stdout = drainJsonLines(stdout, (message) => handleCodexMessage(child, message, finish));
110
- });
111
- child.stderr.setEncoding("utf8");
112
- child.stderr.on("data", (chunk) => {
113
- stderr += chunk;
80
+ let initialized = false;
81
+ let response;
82
+ return runQuotaProcess(child, {
83
+ source: "Codex",
84
+ timeoutMs,
85
+ start: initializeCodex,
86
+ stdout(chunk, write) {
87
+ stdout = drainJsonLines(stdout + chunk, (message) => {
88
+ if (response !== undefined)
89
+ return;
90
+ if (message.id === 0 && !initialized) {
91
+ if (!isRecord(message.result) || message.error !== undefined)
92
+ throw new Error("Codex could not initialize quota reading; check native authentication.");
93
+ initialized = true;
94
+ write({ method: "initialized", params: {} });
95
+ write({ method: "account/rateLimits/read", id: 1 });
96
+ }
97
+ if (message.id !== 1)
98
+ return;
99
+ if (!initialized || !isRecord(message.result) || message.error !== undefined)
100
+ throw new Error("Codex could not read usage limits; check native authentication.");
101
+ response = message.result;
102
+ });
103
+ return response;
104
+ },
114
105
  });
115
- return () => stderr;
116
106
  }
117
107
  function drainJsonLines(buffer, onMessage) {
118
108
  const lines = buffer.split("\n");
@@ -125,48 +115,16 @@ function drainJsonLines(buffer, onMessage) {
125
115
  value = JSON.parse(line);
126
116
  }
127
117
  catch {
128
- continue;
118
+ throw new Error("Codex returned malformed quota JSON; check native CLI usage.");
129
119
  }
130
- if (isRecord(value))
131
- onMessage(value);
120
+ if (!isRecord(value))
121
+ throw new Error("Codex returned an unexpected usage response.");
122
+ onMessage(value);
132
123
  }
133
124
  return rest;
134
125
  }
135
- function handleCodexMessage(child, message, finish) {
136
- if (message.id === 0 && message.result !== undefined) {
137
- sendCodexMessage(child, { method: "initialized", params: {} });
138
- sendCodexMessage(child, { method: "account/rateLimits/read", id: 1 });
139
- }
140
- if (message.id !== 1)
141
- return;
142
- if (isRecord(message.error)) {
143
- const detail = message.error.message;
144
- finish(new Error(typeof detail === "string"
145
- ? `Codex could not read usage limits: ${detail}`
146
- : "Codex could not read the current usage limits."));
147
- return;
148
- }
149
- finish(undefined, message.result);
150
- }
151
- function sendCodexMessage(child, message) {
152
- child.stdin.write(`${JSON.stringify(message)}\n`);
153
- }
154
- function observeCodexLifecycle(child, finish, isSettled, readStderr) {
155
- child.stdin.on("error", (error) => {
156
- finish(new Error(`Codex could not read usage limits: ${error.message}`));
157
- });
158
- child.on("error", (error) => finish(error));
159
- child.on("close", (code) => {
160
- if (isSettled())
161
- return;
162
- const detail = readStderr().trim();
163
- finish(new Error(detail !== ""
164
- ? `Codex could not read usage limits: ${detail}`
165
- : `Codex app-server exited with code ${code ?? "unknown"}.`));
166
- });
167
- }
168
- function initializeCodex(child) {
169
- sendCodexMessage(child, {
126
+ function initializeCodex(write) {
127
+ write({
170
128
  method: "initialize",
171
129
  id: 0,
172
130
  params: {
@@ -179,14 +137,31 @@ function initializeCodex(child) {
179
137
  });
180
138
  }
181
139
  async function executeQuotaProcess(file, args, options) {
182
- const { stdout } = await execFileAsync(file, args, {
183
- ...options,
184
- encoding: "utf8",
140
+ const child = spawnQuotaProcess(file, args, options);
141
+ let stdout = "";
142
+ const result = await runQuotaProcess(child, {
143
+ source: "Claude Code",
144
+ timeoutMs: options.timeout,
145
+ stdout(chunk) {
146
+ stdout += chunk;
147
+ },
148
+ close(code) {
149
+ if (code !== 0)
150
+ throw new Error("Claude Code could not read usage limits; check native authentication.");
151
+ return stdout;
152
+ },
153
+ start() {
154
+ child.stdin.end();
155
+ },
185
156
  });
186
- return { stdout };
157
+ return { stdout: result };
187
158
  }
188
159
  function spawnQuotaProcess(file, args, options) {
189
- return spawn(file, args, { ...options, stdio: ["pipe", "pipe", "pipe"] });
160
+ return spawn(file, args, {
161
+ cwd: options.cwd,
162
+ env: options.env,
163
+ stdio: ["pipe", "pipe", "pipe"],
164
+ });
190
165
  }
191
166
  export function formatCodexQuota(response, formatTime = formatLocalTime) {
192
167
  const bucket = parseCodexBucket(response);
@@ -195,9 +170,17 @@ export function formatCodexQuota(response, formatTime = formatLocalTime) {
195
170
  function parseCodexBucket(response) {
196
171
  if (!isRecord(response))
197
172
  throw new Error("Codex returned an unexpected usage response.");
198
- const bucket = parseBucket(response.rateLimits);
173
+ const named = response.rateLimitsByLimitId;
174
+ const authoritative = isRecord(named) && Object.hasOwn(named, "codex");
175
+ const value = authoritative ? named.codex : response.rateLimits;
176
+ if (isRecord(value) && value.limitId != null && value.limitId !== "codex") {
177
+ throw new Error("Codex returned a different limit bucket; expected the codex bucket.");
178
+ }
179
+ const bucket = parseBucket(value);
199
180
  if (bucket === undefined) {
200
- throw new Error("Codex returned no usage windows for the current account.");
181
+ throw new Error(authoritative
182
+ ? "Codex returned a malformed named codex snapshot with no usage windows; check native CLI usage."
183
+ : "Codex returned no usage windows for the current account; check native CLI usage.");
201
184
  }
202
185
  return bucket;
203
186
  }
@@ -210,14 +193,25 @@ function parseBucket(value) {
210
193
  return { windows };
211
194
  }
212
195
  function parseWindow(value) {
213
- if (!isRecord(value) || typeof value.usedPercent !== "number")
196
+ if (!isRecord(value) || !finiteNumber(value.usedPercent))
197
+ return;
198
+ if (value.usedPercent < 0 || value.usedPercent > 100)
199
+ return;
200
+ const duration = value.windowDurationMins;
201
+ if (duration != null && (!finiteNumber(duration) || duration <= 0))
202
+ return;
203
+ const reset = value.resetsAt;
204
+ if (reset != null && (!finiteNumber(reset) || reset < 0 || reset > 8_640_000_000_000))
214
205
  return;
215
206
  return {
216
207
  usedPercent: value.usedPercent,
217
- windowDurationMins: typeof value.windowDurationMins === "number" ? value.windowDurationMins : null,
218
- resetsAt: typeof value.resetsAt === "number" ? value.resetsAt : null,
208
+ windowDurationMins: duration ?? null,
209
+ resetsAt: reset ?? null,
219
210
  };
220
211
  }
212
+ function finiteNumber(value) {
213
+ return typeof value === "number" && Number.isFinite(value);
214
+ }
221
215
  function formatBucket(bucket, formatTime) {
222
216
  const windows = bucket.windows.map((window, index) => {
223
217
  const duration = formatDuration(window.windowDurationMins, index);
@@ -244,5 +238,5 @@ function formatLocalTime(timestampSeconds) {
244
238
  return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(timestampSeconds * 1000));
245
239
  }
246
240
  function isRecord(value) {
247
- return typeof value === "object" && value !== null;
241
+ return typeof value === "object" && value !== null && !Array.isArray(value);
248
242
  }
@@ -4,12 +4,13 @@ import { type CompletionUpdate } from "./session-file.js";
4
4
  export interface RunConfig {
5
5
  prompt: string;
6
6
  sessionFilePath: string;
7
+ nativeContext?: string;
7
8
  cwd: string;
8
9
  resume?: string;
10
+ quiet?: boolean;
9
11
  executableModel: string | undefined;
10
12
  skipPermissions: boolean;
11
13
  additionalDirectories: readonly string[];
12
- unset: readonly string[];
13
14
  env: NodeJS.ProcessEnv;
14
15
  }
15
16
  export interface RunResult {
@@ -21,13 +22,20 @@ export interface RunResult {
21
22
  export interface AgentProtocolState {
22
23
  sessionId?: string;
23
24
  result?: string;
25
+ resultComplete?: boolean;
26
+ earlierResults: string[];
24
27
  failure?: string;
25
28
  protocolComplete: boolean;
26
29
  protocolFailed: boolean;
27
30
  authEvidence: boolean;
28
31
  contextTokens?: number;
29
32
  peakContextTokens?: number;
33
+ contextCompacted?: boolean;
34
+ contextTokensError?: string;
30
35
  streamTotalTokens?: number;
36
+ expectedSessionId?: string;
37
+ identityFailure?: string;
38
+ nativeEnv?: NodeJS.ProcessEnv;
31
39
  }
32
40
  export interface AgentAssessment {
33
41
  succeeded: boolean;
@@ -43,7 +51,7 @@ export interface AgentAdapter {
43
51
  executable: string;
44
52
  env?: Readonly<Record<string, string>>;
45
53
  buildArgs(config: RunConfig): string[];
46
- createState(): AgentProtocolState;
54
+ createState(config: RunConfig): AgentProtocolState;
47
55
  interpretLine(line: string, state: AgentProtocolState): string | undefined;
48
56
  assess(state: AgentProtocolState): AgentAssessment;
49
57
  isAuthenticationError(message: string): boolean;
@@ -56,6 +64,7 @@ export type SpawnAgentProcess = (command: string, args: readonly string[], optio
56
64
  stdio: ["pipe", "pipe", "pipe"];
57
65
  }) => ChildProcess;
58
66
  export declare function runAgent(config: RunConfig, adapter: AgentAdapter, out: Output, spawnProcess?: SpawnAgentProcess): Promise<RunResult>;
59
- export declare function buildAgentEnv(baseEnv: NodeJS.ProcessEnv, unset: readonly string[]): NodeJS.ProcessEnv;
67
+ export declare function captureNativeSession(state: AgentProtocolState, id: unknown, agent: string): void;
68
+ export declare function buildAgentEnv(baseEnv: NodeJS.ProcessEnv, unset: readonly string[], overrides?: Readonly<Record<string, string>>, required?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
60
69
  export declare function buildTerminationUpdate(signal: NodeJS.Signals, state: AgentProtocolState, now: Date): CompletionUpdate;
61
70
  export declare function isCompacted(state: AgentProtocolState): boolean;
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { appendTranscript, applyCompletion } from "./session-file.js";
2
+ import { appendTranscript, applyCompletion, formatResults, } from "./session-file.js";
3
3
  const TERMINATION_GRACE_MS = 2000;
4
4
  // A coding-agent session exports its own identity to every command it runs; when the assistant
5
5
  // runs in one, the agent it launches must not inherit it.
@@ -18,22 +18,32 @@ const ASSISTANT_SESSION_VARIABLES = [
18
18
  "CODEX_THREAD_ID",
19
19
  "CODEX_CI",
20
20
  "CODEX_SANDBOX_NETWORK_DISABLED",
21
+ "PI_SESSION_ID",
22
+ "PI_SESSION_FILE",
23
+ "PI_PROVIDER",
24
+ "PI_MODEL",
25
+ "PI_REASONING_LEVEL",
21
26
  ];
22
27
  export async function runAgent(config, adapter, out, spawnProcess = spawnDirectChild) {
23
- const state = adapter.createState();
28
+ const state = adapter.createState(config);
24
29
  const outcome = await spawnAgent(config, adapter, state, out, spawnProcess);
25
30
  const assessment = adapter.assess(state);
26
31
  const failed = outcome.exitCode !== 0 || !assessment.succeeded;
27
32
  // Authentication evidence matters only when the run failed. Claude can recover after retrying
28
33
  // a 401, so evidence from a successful run must not produce an auth_required result.
29
34
  const authRequired = failed && (assessment.authEvidence || adapter.isAuthenticationError(outcome.stderr));
30
- const result = selectResult(adapter, state, assessment, outcome, authRequired);
35
+ const selectedResult = selectResult(adapter, state, assessment, outcome, authRequired);
36
+ const result = failed && config.nativeContext !== undefined
37
+ ? `${config.nativeContext}: ${selectedResult}`
38
+ : selectedResult;
39
+ // Durable identity belongs to the requested conversation, even when native validation fails.
40
+ const sessionId = config.resume ?? assessment.sessionId ?? null;
31
41
  applyCompletion(config.sessionFilePath, {
32
42
  status: failed ? "failed" : "succeeded",
33
43
  endedAt: new Date().toISOString(),
34
44
  exitReason: authRequired ? "auth_required" : failed ? "error" : "completed",
35
- sessionId: assessment.sessionId ?? null,
36
- result,
45
+ sessionId,
46
+ result: formatResults(state.earlierResults, result),
37
47
  contextTokens: assessment.contextTokens ?? null,
38
48
  contextCompacted: assessment.contextCompacted ?? false,
39
49
  contextTokensError: assessment.contextTokensError ?? null,
@@ -41,7 +51,7 @@ export async function runAgent(config, adapter, out, spawnProcess = spawnDirectC
41
51
  return {
42
52
  status: failed ? "failed" : "succeeded",
43
53
  authRequired,
44
- sessionId: assessment.sessionId ?? null,
54
+ sessionId,
45
55
  result,
46
56
  };
47
57
  }
@@ -63,7 +73,7 @@ function selectResult(adapter, state, assessment, outcome, authRequired) {
63
73
  function spawnAgent(config, adapter, state, out, spawnProcess) {
64
74
  const child = spawnProcess(adapter.executable, adapter.buildArgs(config), {
65
75
  cwd: config.cwd,
66
- env: { ...buildAgentEnv(config.env, config.unset), ...adapter.env },
76
+ env: config.env,
67
77
  stdio: ["pipe", "pipe", "pipe"],
68
78
  });
69
79
  const detachChildGuards = guardChildLifecycle(child, config.sessionFilePath, state);
@@ -111,7 +121,8 @@ function emitLine(config, adapter, line, state, out) {
111
121
  if (rendered === undefined)
112
122
  return;
113
123
  appendTranscript(config.sessionFilePath, `${rendered}\n`);
114
- out.write(`${rendered}\n`);
124
+ if (config.quiet !== true)
125
+ out.write(`${rendered}\n`);
115
126
  }
116
127
  function drainLines(buffer, onLine) {
117
128
  const lines = buffer.split("\n");
@@ -122,16 +133,30 @@ function drainLines(buffer, onLine) {
122
133
  }
123
134
  return rest;
124
135
  }
125
- export function buildAgentEnv(baseEnv, unset) {
126
- const env = { ...baseEnv };
136
+ export function captureNativeSession(state, id, agent) {
137
+ if (typeof id !== "string" || id.trim() === "") {
138
+ state.identityFailure ??= `${agent} stream reported no native session identity.`;
139
+ return;
140
+ }
141
+ const expected = state.expectedSessionId ?? state.sessionId;
142
+ if (expected !== undefined && id !== expected) {
143
+ state.identityFailure ??= `${agent} resumed/native session identity changed; the conversation may be unavailable in the selected native configuration. Start a new session or select the correct profile.`;
144
+ return;
145
+ }
146
+ state.sessionId = id;
147
+ }
148
+ export function buildAgentEnv(baseEnv, unset, overrides = {}, required = {}) {
149
+ const inherited = { ...baseEnv };
150
+ for (const name of unset)
151
+ delete inherited[name];
152
+ const env = { ...inherited, ...overrides };
127
153
  for (const name of ASSISTANT_SESSION_VARIABLES)
128
154
  delete env[name];
129
- for (const name of unset) {
130
- const trimmed = name.trim();
131
- if (trimmed !== "")
132
- delete env[trimmed];
133
- }
134
- return env;
155
+ if (env.PI_CODING_AGENT === "true")
156
+ delete env.PI_CODING_AGENT;
157
+ if (env.AI_AGENT === "pi")
158
+ delete env.AI_AGENT;
159
+ return { ...env, ...required };
135
160
  }
136
161
  function guardChildLifecycle(child, sessionFilePath, state) {
137
162
  // Seal the session, ask the child to stop, then force-kill it after a short grace period so
@@ -191,16 +216,20 @@ export function buildTerminationUpdate(signal, state, now) {
191
216
  status: "failed",
192
217
  endedAt: now.toISOString(),
193
218
  exitReason: "terminated",
194
- sessionId: state.sessionId ?? null,
195
- result: `Terminated by ${signal} before completion.`,
219
+ sessionId: state.expectedSessionId ?? state.sessionId ?? null,
220
+ result: formatResults(state.resultComplete === true && state.result !== undefined
221
+ ? [...state.earlierResults, state.result]
222
+ : state.earlierResults, `Terminated by ${signal} before completion.`),
196
223
  contextTokens: state.contextTokens ?? null,
197
224
  contextCompacted: isCompacted(state),
198
- contextTokensError: null,
225
+ contextTokensError: state.contextTokensError ?? null,
199
226
  };
200
227
  }
201
228
  // Occupancy only falls when the agent compacts the conversation, so a peak above the final figure
202
229
  // is the compaction itself.
203
230
  export function isCompacted(state) {
231
+ if (state.contextCompacted !== undefined)
232
+ return state.contextCompacted;
204
233
  const { contextTokens, peakContextTokens } = state;
205
234
  if (contextTokens === undefined || peakContextTokens === undefined)
206
235
  return false;
@@ -2,6 +2,7 @@ import type { CodingAgent } from "./coding-agent.js";
2
2
  export interface SessionFrontmatter {
3
3
  status: "running" | "succeeded" | "failed";
4
4
  agent: CodingAgent | null;
5
+ profile: string | null;
5
6
  protocol: string | null;
6
7
  ticket: string | null;
7
8
  model: string | null;
@@ -19,6 +20,7 @@ export interface SessionFrontmatter {
19
20
  contextTokensError: string | null;
20
21
  }
21
22
  export declare const RESULT_MARKER = "\n---- Result ----\n";
23
+ export declare function createSessionFile(sessionsDir: string, ticket: string | undefined, now: Date, frontmatter: SessionFrontmatter): string;
22
24
  export declare function resolveSessionFilePath(sessionsDir: string, ticket: string | undefined, now: Date, fileExists?: (path: string) => boolean): string;
23
25
  export declare function writeInitialSessionFile(sessionFilePath: string, frontmatter: SessionFrontmatter): void;
24
26
  export interface CompletionUpdate {
@@ -31,6 +33,7 @@ export interface CompletionUpdate {
31
33
  contextCompacted?: boolean;
32
34
  contextTokensError?: string | null;
33
35
  }
36
+ export declare function formatResults(earlier: readonly string[], last: string): string;
34
37
  export declare function applyCompletion(sessionFilePath: string, update: CompletionUpdate): void;
35
38
  export declare function appendTranscript(sessionFilePath: string, text: string): void;
36
39
  export interface SessionCompletion {