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.
- package/README.md +74 -19
- 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 +9 -4
- package/dist/code/code-cli.js +216 -84
- 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.d.ts +1 -1
- package/dist/code/coding-agent.js +13 -4
- package/dist/code/models.d.ts +2 -2
- package/dist/code/models.js +27 -15
- package/dist/code/native-context.d.ts +2 -0
- package/dist/code/native-context.js +21 -0
- package/dist/code/pi-agent.d.ts +2 -0
- package/dist/code/pi-agent.js +240 -0
- 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 +92 -98
- package/dist/code/run-agent.d.ts +12 -3
- package/dist/code/run-agent.js +48 -19
- package/dist/code/session-file.d.ts +3 -0
- package/dist/code/session-file.js +33 -10
- package/dist/config.d.ts +44 -7
- package/dist/config.js +163 -36
- package/dist/guide/code-guide.d.ts +2 -2
- package/dist/guide/code-guide.js +17 -6
- 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 +102 -21
- package/templates/guide/playbook/consultation.md +5 -0
- package/templates/guide/playbook/playbook.md +12 -2
- package/templates/guide/playbook/project-workspace-setup.md +1 -1
- package/templates/guide/playbook/working-session.md +10 -0
package/dist/code/codex-agent.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readCodexContext } from "./codex-rollout.js";
|
|
2
|
+
import { captureNativeSession, } from "./run-agent.js";
|
|
2
3
|
export function createCodexAdapter() {
|
|
3
4
|
return {
|
|
4
5
|
executable: "codex",
|
|
@@ -30,8 +31,11 @@ export function buildCodexArgs(config) {
|
|
|
30
31
|
args.push("-");
|
|
31
32
|
return args;
|
|
32
33
|
}
|
|
33
|
-
export function createCodexState() {
|
|
34
|
+
export function createCodexState(config) {
|
|
34
35
|
return {
|
|
36
|
+
expectedSessionId: config?.resume,
|
|
37
|
+
earlierResults: [],
|
|
38
|
+
nativeEnv: config?.env ?? {},
|
|
35
39
|
protocolComplete: false,
|
|
36
40
|
protocolFailed: false,
|
|
37
41
|
authEvidence: false,
|
|
@@ -48,6 +52,7 @@ export function interpretCodexLine(line, state) {
|
|
|
48
52
|
return captureCompletedItem(event, state);
|
|
49
53
|
case "turn.completed":
|
|
50
54
|
state.protocolComplete = true;
|
|
55
|
+
state.resultComplete = !state.protocolFailed;
|
|
51
56
|
captureStreamTotal(event, state);
|
|
52
57
|
return;
|
|
53
58
|
case "turn.failed":
|
|
@@ -60,13 +65,22 @@ export function interpretCodexLine(line, state) {
|
|
|
60
65
|
}
|
|
61
66
|
}
|
|
62
67
|
export function assessCodexState(state) {
|
|
63
|
-
const succeeded = state.
|
|
64
|
-
|
|
68
|
+
const succeeded = state.sessionId !== undefined &&
|
|
69
|
+
state.identityFailure === undefined &&
|
|
70
|
+
state.protocolComplete &&
|
|
71
|
+
!state.protocolFailed &&
|
|
72
|
+
state.result !== undefined;
|
|
73
|
+
const context = readCodexContext(state.sessionId, state.streamTotalTokens, state.nativeEnv);
|
|
65
74
|
return {
|
|
66
75
|
succeeded,
|
|
67
76
|
sessionId: state.sessionId,
|
|
68
77
|
result: state.result,
|
|
69
|
-
error:
|
|
78
|
+
error: state.identityFailure ??
|
|
79
|
+
(succeeded ? undefined : state.failure) ??
|
|
80
|
+
(state.sessionId === undefined &&
|
|
81
|
+
(state.protocolComplete || state.expectedSessionId !== undefined)
|
|
82
|
+
? "Codex reported no native session identity in the selected native configuration."
|
|
83
|
+
: undefined),
|
|
70
84
|
authEvidence: state.authEvidence,
|
|
71
85
|
contextTokens: context.contextTokens ?? undefined,
|
|
72
86
|
contextCompacted: context.compacted,
|
|
@@ -94,8 +108,7 @@ function parseCodexLine(line) {
|
|
|
94
108
|
}
|
|
95
109
|
function captureThread(event, state) {
|
|
96
110
|
const id = asString(event.thread_id);
|
|
97
|
-
|
|
98
|
-
state.sessionId = id;
|
|
111
|
+
captureNativeSession(state, id, "Codex");
|
|
99
112
|
return `[init] session ${id ?? "?"}`;
|
|
100
113
|
}
|
|
101
114
|
function captureCompletedItem(event, state) {
|
|
@@ -104,8 +117,10 @@ function captureCompletedItem(event, state) {
|
|
|
104
117
|
return;
|
|
105
118
|
if (item.type === "agent_message") {
|
|
106
119
|
const text = asString(item.text);
|
|
107
|
-
if (text !== undefined && text !== "")
|
|
120
|
+
if (text !== undefined && text !== "") {
|
|
108
121
|
state.result = text;
|
|
122
|
+
state.resultComplete = false;
|
|
123
|
+
}
|
|
109
124
|
return text;
|
|
110
125
|
}
|
|
111
126
|
if (item.type !== "error")
|
|
@@ -152,7 +167,8 @@ function missingCodexOutcome(state) {
|
|
|
152
167
|
return "Codex turn completed without a final agent message.";
|
|
153
168
|
}
|
|
154
169
|
function codexAuthenticationMessage(detail) {
|
|
155
|
-
const base = "Coding agent not authenticated: an administrator must run `codex login`
|
|
170
|
+
const base = "Coding agent not authenticated: an administrator must run `codex login` with the same effective environment " +
|
|
171
|
+
"and cwd as the child (apply profile unset/env/configDir, including HOME, PATH and credential routing) before " +
|
|
156
172
|
"`aligndev code` can run again.";
|
|
157
173
|
const reason = detail?.trim();
|
|
158
174
|
return reason === undefined || reason === "" ? base : `${base}\n\n${reason}`;
|
|
@@ -15,4 +15,4 @@ export interface CodexContextReading {
|
|
|
15
15
|
* equal it, which pins the file to this run and turns any change in the Codex format into a
|
|
16
16
|
* reported error rather than a plausible wrong number.
|
|
17
17
|
*/
|
|
18
|
-
export declare function readCodexContext(threadId: string | undefined, streamTotal: number | undefined): CodexContextReading;
|
|
18
|
+
export declare function readCodexContext(threadId: string | undefined, streamTotal: number | undefined, env?: NodeJS.ProcessEnv): CodexContextReading;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
2
|
import { basename, join } from "node:path";
|
|
4
3
|
// Codex writes one rollout per thread under `$CODEX_HOME/sessions/<year>/<month>/<day>/`. The plain
|
|
5
4
|
// file is `rollout-<timestamp>-<threadId>.jsonl`; a compacted thread appends `_<uuid>`.
|
|
@@ -18,12 +17,17 @@ const ROLLOUT_SUFFIX = ".jsonl";
|
|
|
18
17
|
* equal it, which pins the file to this run and turns any change in the Codex format into a
|
|
19
18
|
* reported error rather than a plausible wrong number.
|
|
20
19
|
*/
|
|
21
|
-
export function readCodexContext(threadId, streamTotal) {
|
|
20
|
+
export function readCodexContext(threadId, streamTotal, env = {}) {
|
|
22
21
|
if (threadId === undefined || threadId === "")
|
|
23
22
|
return failed("Codex reported no thread id.");
|
|
24
23
|
if (streamTotal === undefined)
|
|
25
24
|
return failed("Codex reported no turn.completed usage.");
|
|
26
|
-
const
|
|
25
|
+
const home = env.HOME ?? env.USERPROFILE;
|
|
26
|
+
const nativeHome = env.CODEX_HOME ?? (home === undefined ? undefined : join(home, ".codex"));
|
|
27
|
+
if (nativeHome === undefined) {
|
|
28
|
+
return failed("Codex native home is unavailable in the child environment.");
|
|
29
|
+
}
|
|
30
|
+
const path = findRolloutPath(threadId, nativeHome);
|
|
27
31
|
if (path === undefined)
|
|
28
32
|
return failed(`No Codex rollout found for thread ${threadId}.`);
|
|
29
33
|
const records = readUsageRecords(path);
|
|
@@ -43,8 +47,8 @@ export function readCodexContext(threadId, streamTotal) {
|
|
|
43
47
|
function failed(error) {
|
|
44
48
|
return { contextTokens: null, compacted: false, error };
|
|
45
49
|
}
|
|
46
|
-
function findRolloutPath(threadId) {
|
|
47
|
-
const root = join(
|
|
50
|
+
function findRolloutPath(threadId, nativeHome) {
|
|
51
|
+
const root = join(nativeHome, SESSIONS_DIR);
|
|
48
52
|
let entries;
|
|
49
53
|
try {
|
|
50
54
|
entries = readdirSync(root, { recursive: true, encoding: "utf8" });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentAdapter } from "./run-agent.js";
|
|
2
|
-
export declare const CODING_AGENTS: readonly ["claude", "codex"];
|
|
2
|
+
export declare const CODING_AGENTS: readonly ["claude", "codex", "pi"];
|
|
3
3
|
export type CodingAgent = (typeof CODING_AGENTS)[number];
|
|
4
4
|
export declare function createAgentAdapter(agent: CodingAgent): AgentAdapter;
|
|
5
5
|
export declare function detectCodingAgents(env: NodeJS.ProcessEnv): CodingAgent[];
|
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
import { createClaudeAdapter } from "./claude-agent.js";
|
|
2
2
|
import { createCodexAdapter } from "./codex-agent.js";
|
|
3
|
-
|
|
3
|
+
import { createPiAdapter } from "./pi-agent.js";
|
|
4
|
+
export const CODING_AGENTS = ["claude", "codex", "pi"];
|
|
4
5
|
export function createAgentAdapter(agent) {
|
|
5
|
-
|
|
6
|
+
switch (agent) {
|
|
7
|
+
case "claude":
|
|
8
|
+
return createClaudeAdapter();
|
|
9
|
+
case "codex":
|
|
10
|
+
return createCodexAdapter();
|
|
11
|
+
case "pi":
|
|
12
|
+
return createPiAdapter();
|
|
13
|
+
}
|
|
6
14
|
}
|
|
7
|
-
//
|
|
8
|
-
// Codex sets `CODEX_THREAD_ID`.
|
|
15
|
+
// Host detection is reached only when no named profile selects a child.
|
|
9
16
|
export function detectCodingAgents(env) {
|
|
10
17
|
const detected = [];
|
|
11
18
|
if (env.CLAUDECODE === "1")
|
|
12
19
|
detected.push("claude");
|
|
13
20
|
if (env.CODEX_THREAD_ID !== undefined && env.CODEX_THREAD_ID !== "")
|
|
14
21
|
detected.push("codex");
|
|
22
|
+
if (env.PI_CODING_AGENT === "true" || env.AI_AGENT === "pi")
|
|
23
|
+
detected.push("pi");
|
|
15
24
|
return detected;
|
|
16
25
|
}
|
package/dist/code/models.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { CodingAgent } from "./coding-agent.js";
|
|
2
2
|
export declare const CLAUDE_DEFAULT_MODELS: readonly ["fable", "opus", "sonnet", "haiku"];
|
|
3
3
|
export declare const CODEX_DEFAULT_MODELS: readonly ["astra", "sol", "terra", "luna"];
|
|
4
|
-
export declare function resolveModels(agent: CodingAgent, override: readonly string[] | undefined): readonly string[];
|
|
4
|
+
export declare function resolveModels(agent: CodingAgent, override: readonly string[] | undefined, aliases?: Readonly<Record<string, string>>): readonly string[] | undefined;
|
|
5
5
|
export interface ModelDiscoveryContext {
|
|
6
6
|
cwd: string;
|
|
7
7
|
env: NodeJS.ProcessEnv;
|
|
@@ -9,6 +9,6 @@ export interface ModelDiscoveryContext {
|
|
|
9
9
|
export type ModelCatalogRunner = (context: ModelDiscoveryContext) => Promise<string>;
|
|
10
10
|
export type ExecutableModelResolver = (agent: CodingAgent, selectedModel: string | undefined, context: ModelDiscoveryContext) => Promise<string | undefined>;
|
|
11
11
|
export declare function createExecutableModelResolver(runCatalog?: ModelCatalogRunner): ExecutableModelResolver;
|
|
12
|
-
export declare
|
|
12
|
+
export declare function expandModelAlias(model: string | undefined, aliases?: Readonly<Record<string, string>>): string | undefined;
|
|
13
13
|
export declare function parseBundledModelSlugs(output: string): readonly string[];
|
|
14
14
|
export declare function selectNewestCodexModel(slugs: readonly string[], alias: string): string | undefined;
|
package/dist/code/models.js
CHANGED
|
@@ -5,31 +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
|
+
case "claude":
|
|
13
|
+
return [...new Set([...CLAUDE_DEFAULT_MODELS, ...Object.keys(aliases)])];
|
|
14
|
+
case "codex":
|
|
15
|
+
return [...new Set([...CODEX_DEFAULT_MODELS, ...Object.keys(aliases)])];
|
|
16
|
+
case "pi":
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
12
19
|
}
|
|
13
20
|
export function createExecutableModelResolver(runCatalog = runCodexModelCatalog) {
|
|
14
|
-
|
|
21
|
+
const catalogs = new WeakMap();
|
|
15
22
|
return async (agent, selectedModel, context) => {
|
|
16
23
|
if (selectedModel === undefined)
|
|
17
24
|
return;
|
|
18
|
-
if (agent
|
|
25
|
+
if (agent !== "codex" || !CODEX_ALIASES.has(selectedModel))
|
|
19
26
|
return selectedModel;
|
|
20
27
|
try {
|
|
21
|
-
|
|
22
|
-
|
|
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);
|
|
23
34
|
if (slug !== undefined)
|
|
24
35
|
return slug;
|
|
25
36
|
throw new Error("the bundled catalog contains no matching model");
|
|
26
37
|
}
|
|
27
|
-
catch
|
|
28
|
-
throw new Error(codexAliasError(selectedModel
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(codexAliasError(selectedModel));
|
|
29
40
|
}
|
|
30
41
|
};
|
|
31
42
|
}
|
|
32
|
-
export
|
|
43
|
+
export function expandModelAlias(model, aliases = {}) {
|
|
44
|
+
return model !== undefined && Object.hasOwn(aliases, model) ? aliases[model] : model;
|
|
45
|
+
}
|
|
33
46
|
export function parseBundledModelSlugs(output) {
|
|
34
47
|
let value;
|
|
35
48
|
try {
|
|
@@ -68,9 +81,9 @@ function runCodexModelCatalog(context) {
|
|
|
68
81
|
encoding: "utf8",
|
|
69
82
|
maxBuffer: CODEX_CATALOG_MAX_BUFFER,
|
|
70
83
|
timeout: CODEX_CATALOG_TIMEOUT_MS,
|
|
71
|
-
}, (error, stdout
|
|
84
|
+
}, (error, stdout) => {
|
|
72
85
|
if (error) {
|
|
73
|
-
reject(new Error(
|
|
86
|
+
reject(new Error("Codex model catalog command failed."));
|
|
74
87
|
return;
|
|
75
88
|
}
|
|
76
89
|
resolve(stdout);
|
|
@@ -78,10 +91,9 @@ function runCodexModelCatalog(context) {
|
|
|
78
91
|
child.stdin?.end();
|
|
79
92
|
});
|
|
80
93
|
}
|
|
81
|
-
function codexAliasError(alias
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
"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 " +
|
|
85
97
|
"slug and select that value.");
|
|
86
98
|
}
|
|
87
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
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
const MISSING_USAGE = "Pi's latest assistant message did not report valid context usage.";
|
|
2
|
+
const STOP_REASONS = new Set([
|
|
3
|
+
"pending",
|
|
4
|
+
"stop",
|
|
5
|
+
"length",
|
|
6
|
+
"toolUse",
|
|
7
|
+
"error",
|
|
8
|
+
"aborted",
|
|
9
|
+
"deferred",
|
|
10
|
+
]);
|
|
11
|
+
export function createPiAdapter() {
|
|
12
|
+
return {
|
|
13
|
+
executable: "pi",
|
|
14
|
+
buildArgs: buildPiArgs,
|
|
15
|
+
createState: createPiState,
|
|
16
|
+
interpretLine: interpretPiLine,
|
|
17
|
+
assess: assessPiState,
|
|
18
|
+
isAuthenticationError: isPiAuthenticationError,
|
|
19
|
+
authenticationMessage: piAuthenticationMessage,
|
|
20
|
+
failureMessage: piFailure,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function buildPiArgs(config) {
|
|
24
|
+
const args = ["--mode", "json"];
|
|
25
|
+
if (config.executableModel !== undefined)
|
|
26
|
+
args.push("--model", config.executableModel);
|
|
27
|
+
if (config.resume !== undefined)
|
|
28
|
+
args.push("--session", config.resume);
|
|
29
|
+
return args;
|
|
30
|
+
}
|
|
31
|
+
function createPiState(config) {
|
|
32
|
+
return {
|
|
33
|
+
expectedSessionId: config.resume,
|
|
34
|
+
earlierResults: [],
|
|
35
|
+
headerSeen: false,
|
|
36
|
+
settledAborted: false,
|
|
37
|
+
protocolComplete: false,
|
|
38
|
+
protocolFailed: false,
|
|
39
|
+
authEvidence: false,
|
|
40
|
+
contextCompacted: false,
|
|
41
|
+
contextTokensError: MISSING_USAGE,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function interpretPiLine(line, state) {
|
|
45
|
+
let event;
|
|
46
|
+
try {
|
|
47
|
+
event = JSON.parse(line);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return invalidProtocol(state, "invalid JSON record");
|
|
51
|
+
}
|
|
52
|
+
if (!isRecord(event) || typeof event.type !== "string") {
|
|
53
|
+
return invalidProtocol(state, "expected an event object with a type");
|
|
54
|
+
}
|
|
55
|
+
if (!state.headerSeen && event.type !== "session") {
|
|
56
|
+
invalidProtocol(state, "missing initial session header");
|
|
57
|
+
}
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case "session":
|
|
60
|
+
return captureHeader(event, state);
|
|
61
|
+
case "agent_start":
|
|
62
|
+
case "turn_start":
|
|
63
|
+
supersedeCompletedResponse(state);
|
|
64
|
+
state.stopReason = undefined;
|
|
65
|
+
state.result = undefined;
|
|
66
|
+
state.protocolComplete = false;
|
|
67
|
+
return;
|
|
68
|
+
case "auto_retry_start":
|
|
69
|
+
case "compaction_start":
|
|
70
|
+
state.protocolComplete = false;
|
|
71
|
+
return;
|
|
72
|
+
case "message_start":
|
|
73
|
+
state.protocolComplete = false;
|
|
74
|
+
if (isRecord(event.message) && event.message.role === "assistant") {
|
|
75
|
+
supersedeCompletedResponse(state);
|
|
76
|
+
state.stopReason = undefined;
|
|
77
|
+
state.result = undefined;
|
|
78
|
+
captureUsage(undefined, state);
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
case "message_end":
|
|
82
|
+
return captureMessage(event, state);
|
|
83
|
+
case "agent_settled":
|
|
84
|
+
if (typeof event.aborted !== "boolean") {
|
|
85
|
+
return invalidProtocol(state, "agent_settled requires an aborted boolean");
|
|
86
|
+
}
|
|
87
|
+
state.protocolComplete = true;
|
|
88
|
+
state.settledAborted = event.aborted;
|
|
89
|
+
return;
|
|
90
|
+
case "tool_execution_start":
|
|
91
|
+
case "tool_execution_end":
|
|
92
|
+
return renderTool(event);
|
|
93
|
+
case "compaction_end":
|
|
94
|
+
if (event.aborted === false && isRecord(event.result))
|
|
95
|
+
state.contextCompacted = true;
|
|
96
|
+
return;
|
|
97
|
+
case "auto_retry_end":
|
|
98
|
+
if (event.success === false && typeof event.finalError === "string") {
|
|
99
|
+
state.failure = event.finalError;
|
|
100
|
+
state.authEvidence = isPiAuthenticationError(event.finalError);
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
default:
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
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
|
+
}
|
|
113
|
+
function invalidProtocol(state, detail) {
|
|
114
|
+
state.protocolFailed = true;
|
|
115
|
+
state.failure = `Invalid pi JSON stream: ${detail}.`;
|
|
116
|
+
return `[error] ${state.failure}`;
|
|
117
|
+
}
|
|
118
|
+
function isRecord(value) {
|
|
119
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
120
|
+
}
|
|
121
|
+
function captureHeader(event, state) {
|
|
122
|
+
if (state.headerSeen ||
|
|
123
|
+
event.version !== 3 ||
|
|
124
|
+
typeof event.id !== "string" ||
|
|
125
|
+
!/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(event.id) ||
|
|
126
|
+
typeof event.cwd !== "string" ||
|
|
127
|
+
event.cwd.trim() === "" ||
|
|
128
|
+
typeof event.timestamp !== "string" ||
|
|
129
|
+
!Number.isFinite(Date.parse(event.timestamp))) {
|
|
130
|
+
return invalidProtocol(state, "invalid or unsupported session header (requires pi 1.3.0)");
|
|
131
|
+
}
|
|
132
|
+
state.headerSeen = true;
|
|
133
|
+
if (state.expectedSessionId !== undefined && event.id !== state.expectedSessionId) {
|
|
134
|
+
return invalidProtocol(state, `resumed session ID ${event.id} differs from ${state.expectedSessionId}`);
|
|
135
|
+
}
|
|
136
|
+
state.sessionId = event.id;
|
|
137
|
+
return `[init] session ${event.id}`;
|
|
138
|
+
}
|
|
139
|
+
function captureMessage(event, state) {
|
|
140
|
+
state.protocolComplete = false;
|
|
141
|
+
const message = event.message;
|
|
142
|
+
if (!isRecord(message) || typeof message.role !== "string") {
|
|
143
|
+
return invalidProtocol(state, "message_end requires a message with a role");
|
|
144
|
+
}
|
|
145
|
+
if (message.role !== "assistant")
|
|
146
|
+
return;
|
|
147
|
+
captureUsage(message.usage, state);
|
|
148
|
+
if (!Array.isArray(message.content) ||
|
|
149
|
+
typeof message.stopReason !== "string" ||
|
|
150
|
+
!STOP_REASONS.has(message.stopReason) ||
|
|
151
|
+
message.content.some((block) => !isRecord(block) ||
|
|
152
|
+
typeof block.type !== "string" ||
|
|
153
|
+
(block.type === "text" && typeof block.text !== "string"))) {
|
|
154
|
+
return invalidProtocol(state, "invalid assistant message_end content or stop reason");
|
|
155
|
+
}
|
|
156
|
+
state.stopReason = message.stopReason;
|
|
157
|
+
const text = message.content
|
|
158
|
+
.flatMap((block) => isRecord(block) && block.type === "text" && typeof block.text === "string"
|
|
159
|
+
? [block.text]
|
|
160
|
+
: [])
|
|
161
|
+
.join("\n");
|
|
162
|
+
state.result = text.trim() === "" ? undefined : text;
|
|
163
|
+
state.resultComplete = message.stopReason === "stop";
|
|
164
|
+
// A malformed protocol remains fatal even if a later model response succeeds.
|
|
165
|
+
if (!state.protocolFailed) {
|
|
166
|
+
state.failure = typeof message.errorMessage === "string" ? message.errorMessage : undefined;
|
|
167
|
+
}
|
|
168
|
+
state.authEvidence =
|
|
169
|
+
(message.stopReason === "error" || message.stopReason === "aborted") &&
|
|
170
|
+
typeof message.errorMessage === "string" &&
|
|
171
|
+
isPiAuthenticationError(message.errorMessage);
|
|
172
|
+
return state.result ?? (state.failure === undefined ? undefined : `[error] ${state.failure}`);
|
|
173
|
+
}
|
|
174
|
+
function captureUsage(usage, state) {
|
|
175
|
+
state.contextTokens = undefined;
|
|
176
|
+
state.contextTokensError = MISSING_USAGE;
|
|
177
|
+
if (!isRecord(usage))
|
|
178
|
+
return;
|
|
179
|
+
let total = 0;
|
|
180
|
+
for (const key of ["input", "output", "cacheRead", "cacheWrite"]) {
|
|
181
|
+
const count = usage[key];
|
|
182
|
+
if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0)
|
|
183
|
+
return;
|
|
184
|
+
total += count;
|
|
185
|
+
}
|
|
186
|
+
if (!Number.isSafeInteger(total))
|
|
187
|
+
return;
|
|
188
|
+
state.contextTokens = total;
|
|
189
|
+
state.contextTokensError = undefined;
|
|
190
|
+
}
|
|
191
|
+
function renderTool(event) {
|
|
192
|
+
if (typeof event.toolName !== "string")
|
|
193
|
+
return;
|
|
194
|
+
const outcome = event.type === "tool_execution_start" ? "start" : event.isError === true ? "error" : "done";
|
|
195
|
+
return `[tool: ${event.toolName}] ${outcome}`;
|
|
196
|
+
}
|
|
197
|
+
function assessPiState(state) {
|
|
198
|
+
const succeeded = state.sessionId !== undefined &&
|
|
199
|
+
state.protocolComplete &&
|
|
200
|
+
!state.protocolFailed &&
|
|
201
|
+
!state.settledAborted &&
|
|
202
|
+
state.stopReason === "stop" &&
|
|
203
|
+
state.result !== undefined &&
|
|
204
|
+
state.failure === undefined;
|
|
205
|
+
return {
|
|
206
|
+
succeeded,
|
|
207
|
+
sessionId: state.sessionId,
|
|
208
|
+
result: state.result,
|
|
209
|
+
error: succeeded || (!state.headerSeen && !state.protocolFailed) ? undefined : piFailure(state),
|
|
210
|
+
authEvidence: state.authEvidence,
|
|
211
|
+
contextTokens: state.contextTokens,
|
|
212
|
+
contextCompacted: state.contextCompacted,
|
|
213
|
+
contextTokensError: state.contextTokensError,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function piFailure(state) {
|
|
217
|
+
if (state.failure !== undefined)
|
|
218
|
+
return state.failure;
|
|
219
|
+
if (state.sessionId === undefined)
|
|
220
|
+
return "Pi stream ended without valid session identity.";
|
|
221
|
+
if (!state.protocolComplete)
|
|
222
|
+
return "Pi stream ended before agent_settled.";
|
|
223
|
+
if (state.settledAborted)
|
|
224
|
+
return "Pi run settled after an abort.";
|
|
225
|
+
if (state.stopReason !== "stop")
|
|
226
|
+
return `Pi final assistant stop reason: ${state.stopReason ?? "missing"}.`;
|
|
227
|
+
return "Pi run settled without a meaningful final assistant result.";
|
|
228
|
+
}
|
|
229
|
+
function isPiAuthenticationError(message) {
|
|
230
|
+
return message
|
|
231
|
+
.split("\n")
|
|
232
|
+
.some((line) => /^(?:Error:\s*)?No API key found for [^\r\n]+\.\s*$/.test(line.trim()) ||
|
|
233
|
+
/^(?:Error:\s*)?Authentication failed for "[^"]+"[.:\s]/.test(line.trim()));
|
|
234
|
+
}
|
|
235
|
+
function piAuthenticationMessage(detail) {
|
|
236
|
+
const base = "Coding agent not authenticated: run `pi`, then `/login <provider>`, or configure " +
|
|
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.";
|
|
239
|
+
return detail === undefined || detail.trim() === "" ? base : `${base}\n\n${detail}`;
|
|
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>;
|