aligndev 0.24.0 → 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.
- package/README.md +58 -15
- package/dist/alignfirst-cli.d.ts +1 -0
- package/dist/alignfirst-cli.js +43 -1
- package/dist/cli.js +7 -14
- package/dist/code/claude-agent.d.ts +1 -1
- package/dist/code/claude-agent.js +25 -11
- package/dist/code/code-cli.d.ts +6 -3
- package/dist/code/code-cli.js +128 -63
- package/dist/code/codex-agent.d.ts +2 -2
- package/dist/code/codex-agent.js +24 -8
- package/dist/code/codex-rollout.d.ts +1 -1
- package/dist/code/codex-rollout.js +9 -5
- package/dist/code/coding-agent.js +1 -1
- package/dist/code/models.d.ts +2 -2
- package/dist/code/models.js +20 -15
- package/dist/code/native-context.d.ts +2 -0
- package/dist/code/native-context.js +21 -0
- package/dist/code/pi-agent.js +12 -1
- package/dist/code/quota-process.d.ts +9 -0
- package/dist/code/quota-process.js +165 -0
- package/dist/code/quota.d.ts +2 -3
- package/dist/code/quota.js +91 -100
- package/dist/code/run-agent.d.ts +8 -2
- package/dist/code/run-agent.js +33 -16
- package/dist/code/session-file.d.ts +3 -0
- package/dist/code/session-file.js +32 -9
- package/dist/config.d.ts +44 -7
- package/dist/config.js +162 -38
- package/dist/guide/code-guide.d.ts +2 -2
- package/dist/guide/code-guide.js +10 -7
- package/dist/guide/guide-cli.js +16 -7
- package/dist/json-shape.d.ts +3 -0
- package/dist/json-shape.js +23 -0
- package/dist/package-version.d.ts +1 -0
- package/dist/package-version.js +7 -0
- package/dist/project/layout.d.ts +4 -0
- package/dist/project/layout.js +28 -10
- package/dist/project/render.js +3 -1
- package/dist/project/status.d.ts +2 -1
- package/dist/project/status.js +1 -0
- package/package.json +1 -1
- package/templates/guide/code.md +26 -11
package/dist/code/models.js
CHANGED
|
@@ -5,38 +5,44 @@ const CODEX_ALIASES = new Set(CODEX_DEFAULT_MODELS);
|
|
|
5
5
|
const CODEX_MODEL_PATTERN = new RegExp(`^gpt-([0-9]+)(?:\\.([0-9]+))?-(${CODEX_DEFAULT_MODELS.join("|")})$`);
|
|
6
6
|
const CODEX_CATALOG_MAX_BUFFER = 8 * 1024 * 1024;
|
|
7
7
|
const CODEX_CATALOG_TIMEOUT_MS = 30_000;
|
|
8
|
-
export function resolveModels(agent, override) {
|
|
8
|
+
export function resolveModels(agent, override, aliases = {}) {
|
|
9
9
|
if (override !== undefined && override.length > 0)
|
|
10
10
|
return override;
|
|
11
11
|
switch (agent) {
|
|
12
12
|
case "claude":
|
|
13
|
-
return CLAUDE_DEFAULT_MODELS;
|
|
13
|
+
return [...new Set([...CLAUDE_DEFAULT_MODELS, ...Object.keys(aliases)])];
|
|
14
14
|
case "codex":
|
|
15
|
-
return CODEX_DEFAULT_MODELS;
|
|
15
|
+
return [...new Set([...CODEX_DEFAULT_MODELS, ...Object.keys(aliases)])];
|
|
16
16
|
case "pi":
|
|
17
17
|
return;
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
export function createExecutableModelResolver(runCatalog = runCodexModelCatalog) {
|
|
21
|
-
|
|
21
|
+
const catalogs = new WeakMap();
|
|
22
22
|
return async (agent, selectedModel, context) => {
|
|
23
23
|
if (selectedModel === undefined)
|
|
24
24
|
return;
|
|
25
25
|
if (agent !== "codex" || !CODEX_ALIASES.has(selectedModel))
|
|
26
26
|
return selectedModel;
|
|
27
27
|
try {
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
let catalog = catalogs.get(context.env);
|
|
29
|
+
if (catalog === undefined) {
|
|
30
|
+
catalog = runCatalog(context).then(parseBundledModelSlugs);
|
|
31
|
+
catalogs.set(context.env, catalog);
|
|
32
|
+
}
|
|
33
|
+
const slug = selectNewestCodexModel(await catalog, selectedModel);
|
|
30
34
|
if (slug !== undefined)
|
|
31
35
|
return slug;
|
|
32
36
|
throw new Error("the bundled catalog contains no matching model");
|
|
33
37
|
}
|
|
34
|
-
catch
|
|
35
|
-
throw new Error(codexAliasError(selectedModel
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(codexAliasError(selectedModel));
|
|
36
40
|
}
|
|
37
41
|
};
|
|
38
42
|
}
|
|
39
|
-
export
|
|
43
|
+
export function expandModelAlias(model, aliases = {}) {
|
|
44
|
+
return model !== undefined && Object.hasOwn(aliases, model) ? aliases[model] : model;
|
|
45
|
+
}
|
|
40
46
|
export function parseBundledModelSlugs(output) {
|
|
41
47
|
let value;
|
|
42
48
|
try {
|
|
@@ -75,9 +81,9 @@ function runCodexModelCatalog(context) {
|
|
|
75
81
|
encoding: "utf8",
|
|
76
82
|
maxBuffer: CODEX_CATALOG_MAX_BUFFER,
|
|
77
83
|
timeout: CODEX_CATALOG_TIMEOUT_MS,
|
|
78
|
-
}, (error, stdout
|
|
84
|
+
}, (error, stdout) => {
|
|
79
85
|
if (error) {
|
|
80
|
-
reject(new Error(
|
|
86
|
+
reject(new Error("Codex model catalog command failed."));
|
|
81
87
|
return;
|
|
82
88
|
}
|
|
83
89
|
resolve(stdout);
|
|
@@ -85,10 +91,9 @@ function runCodexModelCatalog(context) {
|
|
|
85
91
|
child.stdin?.end();
|
|
86
92
|
});
|
|
87
93
|
}
|
|
88
|
-
function codexAliasError(alias
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
"Update the Codex CLI, or set `code.models` in the aligndev settings to an explicit full model " +
|
|
94
|
+
function codexAliasError(alias) {
|
|
95
|
+
return (`Unable to resolve Codex model alias ${JSON.stringify(alias)} from the bundled catalog. ` +
|
|
96
|
+
"Update the Codex CLI, or set `code.profiles.<name>.models` in the aligndev settings to an explicit full model " +
|
|
92
97
|
"slug and select that value.");
|
|
93
98
|
}
|
|
94
99
|
function isRecord(value) {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { CONFIG_DIRECTORY_VARIABLES } from "../config.js";
|
|
2
|
+
export function describeNativeStorage(code) {
|
|
3
|
+
const variable = CONFIG_DIRECTORY_VARIABLES[code.agent];
|
|
4
|
+
const directory = code.configDir === undefined
|
|
5
|
+
? describeVariable(code, variable)
|
|
6
|
+
: `${variable}: configDir ${JSON.stringify(code.configDir)}`;
|
|
7
|
+
const home = ["HOME", "USERPROFILE"]
|
|
8
|
+
.filter((name) => code.childEnv[name] !== undefined || code.unset?.includes(name))
|
|
9
|
+
.map((name) => describeVariable(code, name));
|
|
10
|
+
return [directory, ...home].join("; ");
|
|
11
|
+
}
|
|
12
|
+
function describeVariable(code, name) {
|
|
13
|
+
if (code.env !== undefined && Object.hasOwn(code.env, name)) {
|
|
14
|
+
return `${name}: profile env override (value omitted)`;
|
|
15
|
+
}
|
|
16
|
+
if (code.unset?.includes(name))
|
|
17
|
+
return `${name}: unset by profile; native defaults apply`;
|
|
18
|
+
return code.childEnv[name] === undefined
|
|
19
|
+
? `${name}: native default storage`
|
|
20
|
+
: `${name}: inherited environment (value omitted)`;
|
|
21
|
+
}
|
package/dist/code/pi-agent.js
CHANGED
|
@@ -31,6 +31,7 @@ function buildPiArgs(config) {
|
|
|
31
31
|
function createPiState(config) {
|
|
32
32
|
return {
|
|
33
33
|
expectedSessionId: config.resume,
|
|
34
|
+
earlierResults: [],
|
|
34
35
|
headerSeen: false,
|
|
35
36
|
settledAborted: false,
|
|
36
37
|
protocolComplete: false,
|
|
@@ -59,6 +60,7 @@ function interpretPiLine(line, state) {
|
|
|
59
60
|
return captureHeader(event, state);
|
|
60
61
|
case "agent_start":
|
|
61
62
|
case "turn_start":
|
|
63
|
+
supersedeCompletedResponse(state);
|
|
62
64
|
state.stopReason = undefined;
|
|
63
65
|
state.result = undefined;
|
|
64
66
|
state.protocolComplete = false;
|
|
@@ -70,6 +72,7 @@ function interpretPiLine(line, state) {
|
|
|
70
72
|
case "message_start":
|
|
71
73
|
state.protocolComplete = false;
|
|
72
74
|
if (isRecord(event.message) && event.message.role === "assistant") {
|
|
75
|
+
supersedeCompletedResponse(state);
|
|
73
76
|
state.stopReason = undefined;
|
|
74
77
|
state.result = undefined;
|
|
75
78
|
captureUsage(undefined, state);
|
|
@@ -101,6 +104,12 @@ function interpretPiLine(line, state) {
|
|
|
101
104
|
return;
|
|
102
105
|
}
|
|
103
106
|
}
|
|
107
|
+
function supersedeCompletedResponse(state) {
|
|
108
|
+
if (state.stopReason === "stop" && state.result !== undefined) {
|
|
109
|
+
state.earlierResults.push(state.result);
|
|
110
|
+
}
|
|
111
|
+
state.resultComplete = false;
|
|
112
|
+
}
|
|
104
113
|
function invalidProtocol(state, detail) {
|
|
105
114
|
state.protocolFailed = true;
|
|
106
115
|
state.failure = `Invalid pi JSON stream: ${detail}.`;
|
|
@@ -151,6 +160,7 @@ function captureMessage(event, state) {
|
|
|
151
160
|
: [])
|
|
152
161
|
.join("\n");
|
|
153
162
|
state.result = text.trim() === "" ? undefined : text;
|
|
163
|
+
state.resultComplete = message.stopReason === "stop";
|
|
154
164
|
// A malformed protocol remains fatal even if a later model response succeeds.
|
|
155
165
|
if (!state.protocolFailed) {
|
|
156
166
|
state.failure = typeof message.errorMessage === "string" ? message.errorMessage : undefined;
|
|
@@ -224,6 +234,7 @@ function isPiAuthenticationError(message) {
|
|
|
224
234
|
}
|
|
225
235
|
function piAuthenticationMessage(detail) {
|
|
226
236
|
const base = "Coding agent not authenticated: run `pi`, then `/login <provider>`, or configure " +
|
|
227
|
-
"the provider's credentials
|
|
237
|
+
"the provider's credentials with the same effective environment and cwd as the child " +
|
|
238
|
+
"(apply profile unset/env/configDir, including HOME, PATH and credential routing) before running `aligndev code` again.";
|
|
228
239
|
return detail === undefined || detail.trim() === "" ? base : `${base}\n\n${detail}`;
|
|
229
240
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
+
export interface QuotaProcessProtocol<T> {
|
|
3
|
+
source: string;
|
|
4
|
+
timeoutMs: number;
|
|
5
|
+
start?: (write: (message: unknown) => void) => void;
|
|
6
|
+
stdout: (chunk: string, write: (message: unknown) => void) => T | undefined;
|
|
7
|
+
close?: (code: number | null) => T;
|
|
8
|
+
}
|
|
9
|
+
export declare function runQuotaProcess<T>(child: ChildProcessWithoutNullStreams, protocol: QuotaProcessProtocol<T>): Promise<T>;
|
|
@@ -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
|
+
}
|
package/dist/code/quota.d.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
|
-
import type {
|
|
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 = (
|
|
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;
|
package/dist/code/quota.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
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,21 +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 (
|
|
20
|
-
|
|
21
|
-
|
|
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.");
|
|
22
28
|
}
|
|
23
|
-
const env = buildAgentEnv(context.env, context.unset);
|
|
24
|
-
return agent === "claude"
|
|
25
|
-
? readClaudeQuota({ ...context, env: translateClaudePrivacyOptOut(env) }, adapter, timeoutMs)
|
|
26
|
-
: readCodexQuota({ ...context, env }, adapter, timeoutMs);
|
|
27
29
|
};
|
|
28
30
|
}
|
|
29
31
|
function translateClaudePrivacyOptOut(env) {
|
|
@@ -74,48 +76,33 @@ function requestCodexQuota(context, adapter, timeoutMs) {
|
|
|
74
76
|
return exchangeCodexMessages(child, timeoutMs);
|
|
75
77
|
}
|
|
76
78
|
function exchangeCodexMessages(child, timeoutMs) {
|
|
77
|
-
const detachGuard = guardChild(child);
|
|
78
|
-
return new Promise((resolve, reject) => {
|
|
79
|
-
let settled = false;
|
|
80
|
-
const finish = (error, result) => {
|
|
81
|
-
if (settled)
|
|
82
|
-
return;
|
|
83
|
-
settled = true;
|
|
84
|
-
clearTimeout(timer);
|
|
85
|
-
detachGuard();
|
|
86
|
-
child.kill("SIGTERM");
|
|
87
|
-
if (error)
|
|
88
|
-
reject(error);
|
|
89
|
-
else
|
|
90
|
-
resolve(result);
|
|
91
|
-
};
|
|
92
|
-
const timer = setTimeout(() => finish(new Error("Codex timed out while reading usage limits.")), timeoutMs);
|
|
93
|
-
const readStderr = observeCodexOutput(child, finish);
|
|
94
|
-
observeCodexLifecycle(child, finish, () => settled, readStderr);
|
|
95
|
-
initializeCodex(child);
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
function guardChild(child) {
|
|
99
|
-
const kill = () => {
|
|
100
|
-
if (child.exitCode === null && child.signalCode === null)
|
|
101
|
-
child.kill("SIGTERM");
|
|
102
|
-
};
|
|
103
|
-
process.on("exit", kill);
|
|
104
|
-
return () => process.off("exit", kill);
|
|
105
|
-
}
|
|
106
|
-
function observeCodexOutput(child, finish) {
|
|
107
79
|
let stdout = "";
|
|
108
|
-
let
|
|
109
|
-
|
|
110
|
-
child
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
+
},
|
|
117
105
|
});
|
|
118
|
-
return () => stderr;
|
|
119
106
|
}
|
|
120
107
|
function drainJsonLines(buffer, onMessage) {
|
|
121
108
|
const lines = buffer.split("\n");
|
|
@@ -128,48 +115,16 @@ function drainJsonLines(buffer, onMessage) {
|
|
|
128
115
|
value = JSON.parse(line);
|
|
129
116
|
}
|
|
130
117
|
catch {
|
|
131
|
-
|
|
118
|
+
throw new Error("Codex returned malformed quota JSON; check native CLI usage.");
|
|
132
119
|
}
|
|
133
|
-
if (isRecord(value))
|
|
134
|
-
|
|
120
|
+
if (!isRecord(value))
|
|
121
|
+
throw new Error("Codex returned an unexpected usage response.");
|
|
122
|
+
onMessage(value);
|
|
135
123
|
}
|
|
136
124
|
return rest;
|
|
137
125
|
}
|
|
138
|
-
function
|
|
139
|
-
|
|
140
|
-
sendCodexMessage(child, { method: "initialized", params: {} });
|
|
141
|
-
sendCodexMessage(child, { method: "account/rateLimits/read", id: 1 });
|
|
142
|
-
}
|
|
143
|
-
if (message.id !== 1)
|
|
144
|
-
return;
|
|
145
|
-
if (isRecord(message.error)) {
|
|
146
|
-
const detail = message.error.message;
|
|
147
|
-
finish(new Error(typeof detail === "string"
|
|
148
|
-
? `Codex could not read usage limits: ${detail}`
|
|
149
|
-
: "Codex could not read the current usage limits."));
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
finish(undefined, message.result);
|
|
153
|
-
}
|
|
154
|
-
function sendCodexMessage(child, message) {
|
|
155
|
-
child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
156
|
-
}
|
|
157
|
-
function observeCodexLifecycle(child, finish, isSettled, readStderr) {
|
|
158
|
-
child.stdin.on("error", (error) => {
|
|
159
|
-
finish(new Error(`Codex could not read usage limits: ${error.message}`));
|
|
160
|
-
});
|
|
161
|
-
child.on("error", (error) => finish(error));
|
|
162
|
-
child.on("close", (code) => {
|
|
163
|
-
if (isSettled())
|
|
164
|
-
return;
|
|
165
|
-
const detail = readStderr().trim();
|
|
166
|
-
finish(new Error(detail !== ""
|
|
167
|
-
? `Codex could not read usage limits: ${detail}`
|
|
168
|
-
: `Codex app-server exited with code ${code ?? "unknown"}.`));
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
function initializeCodex(child) {
|
|
172
|
-
sendCodexMessage(child, {
|
|
126
|
+
function initializeCodex(write) {
|
|
127
|
+
write({
|
|
173
128
|
method: "initialize",
|
|
174
129
|
id: 0,
|
|
175
130
|
params: {
|
|
@@ -182,14 +137,31 @@ function initializeCodex(child) {
|
|
|
182
137
|
});
|
|
183
138
|
}
|
|
184
139
|
async function executeQuotaProcess(file, args, options) {
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
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
|
+
},
|
|
188
156
|
});
|
|
189
|
-
return { stdout };
|
|
157
|
+
return { stdout: result };
|
|
190
158
|
}
|
|
191
159
|
function spawnQuotaProcess(file, args, options) {
|
|
192
|
-
return spawn(file, args, {
|
|
160
|
+
return spawn(file, args, {
|
|
161
|
+
cwd: options.cwd,
|
|
162
|
+
env: options.env,
|
|
163
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
164
|
+
});
|
|
193
165
|
}
|
|
194
166
|
export function formatCodexQuota(response, formatTime = formatLocalTime) {
|
|
195
167
|
const bucket = parseCodexBucket(response);
|
|
@@ -198,9 +170,17 @@ export function formatCodexQuota(response, formatTime = formatLocalTime) {
|
|
|
198
170
|
function parseCodexBucket(response) {
|
|
199
171
|
if (!isRecord(response))
|
|
200
172
|
throw new Error("Codex returned an unexpected usage response.");
|
|
201
|
-
const
|
|
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);
|
|
202
180
|
if (bucket === undefined) {
|
|
203
|
-
throw new Error(
|
|
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.");
|
|
204
184
|
}
|
|
205
185
|
return bucket;
|
|
206
186
|
}
|
|
@@ -213,14 +193,25 @@ function parseBucket(value) {
|
|
|
213
193
|
return { windows };
|
|
214
194
|
}
|
|
215
195
|
function parseWindow(value) {
|
|
216
|
-
if (!isRecord(value) ||
|
|
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))
|
|
217
205
|
return;
|
|
218
206
|
return {
|
|
219
207
|
usedPercent: value.usedPercent,
|
|
220
|
-
windowDurationMins:
|
|
221
|
-
resetsAt:
|
|
208
|
+
windowDurationMins: duration ?? null,
|
|
209
|
+
resetsAt: reset ?? null,
|
|
222
210
|
};
|
|
223
211
|
}
|
|
212
|
+
function finiteNumber(value) {
|
|
213
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
214
|
+
}
|
|
224
215
|
function formatBucket(bucket, formatTime) {
|
|
225
216
|
const windows = bucket.windows.map((window, index) => {
|
|
226
217
|
const duration = formatDuration(window.windowDurationMins, index);
|
|
@@ -247,5 +238,5 @@ function formatLocalTime(timestampSeconds) {
|
|
|
247
238
|
return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(timestampSeconds * 1000));
|
|
248
239
|
}
|
|
249
240
|
function isRecord(value) {
|
|
250
|
-
return typeof value === "object" && value !== null;
|
|
241
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
251
242
|
}
|
package/dist/code/run-agent.d.ts
CHANGED
|
@@ -4,13 +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;
|
|
9
10
|
quiet?: boolean;
|
|
10
11
|
executableModel: string | undefined;
|
|
11
12
|
skipPermissions: boolean;
|
|
12
13
|
additionalDirectories: readonly string[];
|
|
13
|
-
unset: readonly string[];
|
|
14
14
|
env: NodeJS.ProcessEnv;
|
|
15
15
|
}
|
|
16
16
|
export interface RunResult {
|
|
@@ -22,6 +22,8 @@ export interface RunResult {
|
|
|
22
22
|
export interface AgentProtocolState {
|
|
23
23
|
sessionId?: string;
|
|
24
24
|
result?: string;
|
|
25
|
+
resultComplete?: boolean;
|
|
26
|
+
earlierResults: string[];
|
|
25
27
|
failure?: string;
|
|
26
28
|
protocolComplete: boolean;
|
|
27
29
|
protocolFailed: boolean;
|
|
@@ -31,6 +33,9 @@ export interface AgentProtocolState {
|
|
|
31
33
|
contextCompacted?: boolean;
|
|
32
34
|
contextTokensError?: string;
|
|
33
35
|
streamTotalTokens?: number;
|
|
36
|
+
expectedSessionId?: string;
|
|
37
|
+
identityFailure?: string;
|
|
38
|
+
nativeEnv?: NodeJS.ProcessEnv;
|
|
34
39
|
}
|
|
35
40
|
export interface AgentAssessment {
|
|
36
41
|
succeeded: boolean;
|
|
@@ -59,6 +64,7 @@ export type SpawnAgentProcess = (command: string, args: readonly string[], optio
|
|
|
59
64
|
stdio: ["pipe", "pipe", "pipe"];
|
|
60
65
|
}) => ChildProcess;
|
|
61
66
|
export declare function runAgent(config: RunConfig, adapter: AgentAdapter, out: Output, spawnProcess?: SpawnAgentProcess): Promise<RunResult>;
|
|
62
|
-
export declare function
|
|
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;
|
|
63
69
|
export declare function buildTerminationUpdate(signal: NodeJS.Signals, state: AgentProtocolState, now: Date): CompletionUpdate;
|
|
64
70
|
export declare function isCompacted(state: AgentProtocolState): boolean;
|