aligndev 0.24.0 → 0.26.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 (42) hide show
  1. package/README.md +73 -15
  2. package/dist/alignfirst-cli.d.ts +2 -0
  3. package/dist/alignfirst-cli.js +62 -1
  4. package/dist/cli.js +8 -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 +6 -3
  8. package/dist/code/code-cli.js +136 -63
  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.js +1 -1
  14. package/dist/code/models.d.ts +2 -2
  15. package/dist/code/models.js +20 -15
  16. package/dist/code/native-context.d.ts +2 -0
  17. package/dist/code/native-context.js +21 -0
  18. package/dist/code/pi-agent.js +12 -1
  19. package/dist/code/quota-process.d.ts +9 -0
  20. package/dist/code/quota-process.js +165 -0
  21. package/dist/code/quota.d.ts +2 -3
  22. package/dist/code/quota.js +91 -100
  23. package/dist/code/run-agent.d.ts +8 -2
  24. package/dist/code/run-agent.js +33 -16
  25. package/dist/code/session-file.d.ts +3 -0
  26. package/dist/code/session-file.js +32 -9
  27. package/dist/config.d.ts +44 -7
  28. package/dist/config.js +210 -44
  29. package/dist/guide/code-guide.d.ts +2 -2
  30. package/dist/guide/code-guide.js +10 -7
  31. package/dist/guide/guide-cli.js +16 -7
  32. package/dist/json-shape.d.ts +5 -3
  33. package/dist/json-shape.js +39 -12
  34. package/dist/package-version.d.ts +1 -0
  35. package/dist/package-version.js +7 -0
  36. package/dist/project/layout.d.ts +4 -0
  37. package/dist/project/layout.js +29 -11
  38. package/dist/project/render.js +3 -1
  39. package/dist/project/status.d.ts +2 -1
  40. package/dist/project/status.js +1 -0
  41. package/package.json +4 -4
  42. package/templates/guide/code.md +32 -11
@@ -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.
@@ -32,13 +32,18 @@ export async function runAgent(config, adapter, out, spawnProcess = spawnDirectC
32
32
  // Authentication evidence matters only when the run failed. Claude can recover after retrying
33
33
  // a 401, so evidence from a successful run must not produce an auth_required result.
34
34
  const authRequired = failed && (assessment.authEvidence || adapter.isAuthenticationError(outcome.stderr));
35
- 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;
36
41
  applyCompletion(config.sessionFilePath, {
37
42
  status: failed ? "failed" : "succeeded",
38
43
  endedAt: new Date().toISOString(),
39
44
  exitReason: authRequired ? "auth_required" : failed ? "error" : "completed",
40
- sessionId: assessment.sessionId ?? null,
41
- result,
45
+ sessionId,
46
+ result: formatResults(state.earlierResults, result),
42
47
  contextTokens: assessment.contextTokens ?? null,
43
48
  contextCompacted: assessment.contextCompacted ?? false,
44
49
  contextTokensError: assessment.contextTokensError ?? null,
@@ -46,7 +51,7 @@ export async function runAgent(config, adapter, out, spawnProcess = spawnDirectC
46
51
  return {
47
52
  status: failed ? "failed" : "succeeded",
48
53
  authRequired,
49
- sessionId: assessment.sessionId ?? null,
54
+ sessionId,
50
55
  result,
51
56
  };
52
57
  }
@@ -68,7 +73,7 @@ function selectResult(adapter, state, assessment, outcome, authRequired) {
68
73
  function spawnAgent(config, adapter, state, out, spawnProcess) {
69
74
  const child = spawnProcess(adapter.executable, adapter.buildArgs(config), {
70
75
  cwd: config.cwd,
71
- env: { ...buildAgentEnv(config.env, config.unset), ...adapter.env },
76
+ env: config.env,
72
77
  stdio: ["pipe", "pipe", "pipe"],
73
78
  });
74
79
  const detachChildGuards = guardChildLifecycle(child, config.sessionFilePath, state);
@@ -128,20 +133,30 @@ function drainLines(buffer, onLine) {
128
133
  }
129
134
  return rest;
130
135
  }
131
- export function buildAgentEnv(baseEnv, unset) {
132
- 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 };
133
153
  for (const name of ASSISTANT_SESSION_VARIABLES)
134
154
  delete env[name];
135
155
  if (env.PI_CODING_AGENT === "true")
136
156
  delete env.PI_CODING_AGENT;
137
157
  if (env.AI_AGENT === "pi")
138
158
  delete env.AI_AGENT;
139
- for (const name of unset) {
140
- const trimmed = name.trim();
141
- if (trimmed !== "")
142
- delete env[trimmed];
143
- }
144
- return env;
159
+ return { ...env, ...required };
145
160
  }
146
161
  function guardChildLifecycle(child, sessionFilePath, state) {
147
162
  // Seal the session, ask the child to stop, then force-kill it after a short grace period so
@@ -201,8 +216,10 @@ export function buildTerminationUpdate(signal, state, now) {
201
216
  status: "failed",
202
217
  endedAt: now.toISOString(),
203
218
  exitReason: "terminated",
204
- sessionId: state.sessionId ?? null,
205
- 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.`),
206
223
  contextTokens: state.contextTokens ?? null,
207
224
  contextCompacted: isCompacted(state),
208
225
  contextTokensError: state.contextTokensError ?? null,
@@ -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 {
@@ -1,25 +1,47 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  export const RESULT_MARKER = "\n---- Result ----\n";
4
+ const LATER_RESULT_SEPARATOR = "\n\n---- Later result ----\n\n";
5
+ export function createSessionFile(sessionsDir, ticket, now, frontmatter) {
6
+ const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
7
+ mkdirSync(dir, { recursive: true });
8
+ const stamp = formatStamp(now);
9
+ for (let suffix = 1;; ++suffix) {
10
+ const path = sessionFileCandidate(dir, stamp, suffix);
11
+ try {
12
+ claimSessionFile(path, frontmatter);
13
+ return path;
14
+ }
15
+ catch (error) {
16
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST")
17
+ throw error;
18
+ }
19
+ }
20
+ }
21
+ function sessionFileCandidate(dir, stamp, suffix) {
22
+ return join(dir, `${stamp}${suffix === 1 ? "" : `-${suffix}`}.md`);
23
+ }
24
+ function claimSessionFile(path, frontmatter) {
25
+ writeFileSync(path, `${serializeFrontmatter(frontmatter)}\n`, { flag: "wx" });
26
+ }
4
27
  // `sessionsDir` is the `.plans`-shaped directory holding the session directories: the resolved
5
28
  // `_aligndev` location, which is the resolved `.plans` unless the companion holds a separate tree.
6
29
  export function resolveSessionFilePath(sessionsDir, ticket, now, fileExists = existsSync) {
7
30
  const dir = join(sessionsDir, ...(ticket === undefined ? [] : [ticket]), "_aligndev");
8
31
  const stamp = formatStamp(now);
9
- let candidate = join(dir, `${stamp}.md`);
10
- let suffix = 2;
11
- while (fileExists(candidate)) {
12
- candidate = join(dir, `${stamp}-${suffix}.md`);
32
+ let suffix = 1;
33
+ while (fileExists(sessionFileCandidate(dir, stamp, suffix)))
13
34
  ++suffix;
14
- }
15
- return candidate;
35
+ return sessionFileCandidate(dir, stamp, suffix);
16
36
  }
17
37
  // Writes the initial `running` header. Present before the run starts so an interrupted run still
18
38
  // leaves an auditable record; the terminal frontmatter rewrite happens on completion.
19
39
  export function writeInitialSessionFile(sessionFilePath, frontmatter) {
20
- const header = `${serializeFrontmatter(frontmatter)}\n`;
21
40
  mkdirSync(dirname(sessionFilePath), { recursive: true });
22
- writeFileSync(sessionFilePath, header);
41
+ claimSessionFile(sessionFilePath, frontmatter);
42
+ }
43
+ export function formatResults(earlier, last) {
44
+ return [...earlier, last].join(LATER_RESULT_SEPARATOR);
23
45
  }
24
46
  // Appends the result block, then rewrites the frontmatter in place. Append-first keeps the tailed
25
47
  // transcript intact until the single terminal rewrite.
@@ -188,7 +210,7 @@ function serializeValue(value) {
188
210
  return needsQuote(value) ? JSON.stringify(value) : value;
189
211
  }
190
212
  function needsQuote(value) {
191
- return value === "" || /[:"#]/.test(value) || value !== value.trim();
213
+ return value === "" || /[:"#\p{Cc}\p{Zl}\p{Zp}]/u.test(value) || value !== value.trim();
192
214
  }
193
215
  function splitSessionFile(content) {
194
216
  const match = content.match(/^---\n([\s\S]*?)\n---\n/);
@@ -208,6 +230,7 @@ export function parseFrontmatter(block) {
208
230
  return {
209
231
  status: map.status ?? "running",
210
232
  agent: parseAgent(map.agent),
233
+ profile: map.profile ?? null,
211
234
  protocol: map.protocol ?? null,
212
235
  ticket: map.ticket ?? null,
213
236
  model: map.model ?? null,
package/dist/config.d.ts CHANGED
@@ -1,26 +1,63 @@
1
1
  import { type CodingAgent } from "./code/coding-agent.js";
2
+ import type { AligndevProjectSettings } from "./project/layout.js";
2
3
  export declare const PLATFORMS: readonly ["openclaw", "codingAgent"];
4
+ export declare const CONFIG_DIRECTORY_VARIABLES: {
5
+ readonly claude: "CLAUDE_CONFIG_DIR";
6
+ readonly codex: "CODEX_HOME";
7
+ readonly pi: "PI_CODING_AGENT_DIR";
8
+ };
3
9
  export type Platform = (typeof PLATFORMS)[number];
4
10
  export interface LoadedConfig {
5
11
  path: string;
6
12
  platform: Platform;
7
13
  projectsRoot?: ProjectsRoot;
8
- code: LoadedCodeConfig;
14
+ code: CodeSettings;
9
15
  }
10
16
  export interface ProjectsRoot {
11
17
  path: string;
12
18
  written: string;
13
19
  }
14
- export interface LoadedCodeConfig {
15
- agent?: CodingAgent;
20
+ export interface CodeSettings {
21
+ profile?: string;
22
+ profiles?: Record<string, CodingProfile>;
23
+ }
24
+ export interface CodingProfile {
25
+ agent: CodingAgent;
26
+ default?: boolean;
27
+ configDir?: string;
16
28
  defaultModel?: string;
17
29
  models?: string[];
30
+ modelAliases?: Record<string, string>;
31
+ skipPermissions?: boolean;
32
+ env?: Record<string, string>;
33
+ unset?: string[];
34
+ quota?: QuotaSettings;
35
+ }
36
+ export interface QuotaSettings {
37
+ source: "claude" | "codex" | "none";
38
+ configDir?: string;
39
+ env?: Record<string, string>;
40
+ unset?: string[];
41
+ }
42
+ export interface CodeConfig extends CodingProfile {
43
+ profile: string | null;
18
44
  skipPermissions: boolean;
19
45
  unset: string[];
20
- }
21
- export interface CodeConfig extends LoadedCodeConfig {
22
- agent: CodingAgent;
46
+ childEnv: NodeJS.ProcessEnv;
23
47
  }
24
48
  export declare function loadConfig(home: string): LoadedConfig;
25
- export declare function resolveCodeConfig(config: LoadedConfig, env: NodeJS.ProcessEnv): CodeConfig;
49
+ export type QuotaSource = "claude" | "codex";
50
+ export type ResolvedQuota = {
51
+ source: "none";
52
+ } | {
53
+ source: QuotaSource;
54
+ env: NodeJS.ProcessEnv;
55
+ };
56
+ export declare function resolveQuotaConfig(code: CodeConfig, callerEnv: NodeJS.ProcessEnv): ResolvedQuota;
57
+ export interface ProfileSelection {
58
+ project?: AligndevProjectSettings | null;
59
+ explicit?: string;
60
+ recorded?: string | null;
61
+ }
62
+ export declare function resolveCodeConfig(config: LoadedConfig, env: NodeJS.ProcessEnv, selection?: ProfileSelection): CodeConfig;
26
63
  export declare function requireProjectsRoot(config: LoadedConfig): ProjectsRoot;
package/dist/config.js CHANGED
@@ -1,41 +1,81 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
- import { CODING_AGENTS, detectCodingAgents } from "./code/coding-agent.js";
3
+ import { CODING_AGENTS, createAgentAdapter, detectCodingAgents, } from "./code/coding-agent.js";
4
4
  import { resolveModels } from "./code/models.js";
5
+ import { buildAgentEnv } from "./code/run-agent.js";
5
6
  import { errorMessage } from "./errors.js";
6
- import { arrayOf, boolean, literal, nonEmptyString, object, optional, parseShape, string, } from "./json-shape.js";
7
+ import { arrayOf, boolean, literal, matching, nonblankString, nonEmptyString, nulFreeString, object, optional, parseShape, record, } from "./json-shape.js";
7
8
  export const PLATFORMS = ["openclaw", "codingAgent"];
8
- const codeShape = object({
9
- agent: optional(literal(...CODING_AGENTS)),
10
- defaultModel: optional(nonEmptyString),
11
- models: optional(arrayOf(string)),
9
+ export const CONFIG_DIRECTORY_VARIABLES = {
10
+ claude: "CLAUDE_CONFIG_DIR",
11
+ codex: "CODEX_HOME",
12
+ pi: "PI_CODING_AGENT_DIR",
13
+ };
14
+ const environmentName = matching(/^[A-Za-z_][A-Za-z0-9_]*$/);
15
+ const environmentShape = record(nulFreeString, environmentName);
16
+ const quotaShape = object({
17
+ source: literal("claude", "codex", "none"),
18
+ configDir: optional(directoryValue),
19
+ env: optional(environmentShape),
20
+ unset: optional(arrayOf(environmentName)),
21
+ }, warnUnknownSetting);
22
+ const profileShape = object({
23
+ agent: literal(...CODING_AGENTS),
24
+ default: optional(boolean),
25
+ configDir: optional(directoryValue),
26
+ defaultModel: optional(nonblankString),
27
+ models: optional(arrayOf(nonblankString)),
28
+ modelAliases: optional(record(nonblankString, nonblankString)),
12
29
  skipPermissions: optional(boolean),
13
- unset: optional(arrayOf(string)),
14
- });
30
+ env: optional(environmentShape),
31
+ unset: optional(arrayOf(environmentName)),
32
+ quota: optional(quotaShape),
33
+ }, warnUnknownSetting);
34
+ const codeShape = object({
35
+ profile: optional(nonblankString),
36
+ profiles: optional(record(profileShape, nonblankString)),
37
+ }, warnUnknownSetting);
15
38
  const configShape = object({
16
39
  platform: optional(literal(...PLATFORMS)),
17
40
  projectsRoot: optional(nonEmptyString),
18
41
  code: optional(codeShape),
19
- });
20
- // An absent file is a normal state: every key takes its default. A leftover file under the old
21
- // name is an error, so a missed rename never silently drops the user's settings.
42
+ }, warnUnknownSetting);
43
+ const RETIRED_CODE_KEYS = ["agent", "defaultModel", "models", "skipPermissions", "unset"];
22
44
  export function loadConfig(home) {
23
45
  const path = join(home, ".alignfirst", "aligndev.settings.json");
24
46
  const value = existsSync(path) ? parseConfigFile(path) : absentConfig(home);
25
47
  const code = value.code ?? {};
48
+ for (const [name, profile] of Object.entries(code.profiles ?? {})) {
49
+ const field = `code.profiles[${JSON.stringify(name)}]`;
50
+ validateEnvironment(profile, profile.agent, field, path);
51
+ if (profile.configDir !== undefined)
52
+ profile.configDir = resolvePath(profile.configDir, home, path);
53
+ if (profile.quota !== undefined) {
54
+ const quota = profile.quota;
55
+ if (quota.source === "none") {
56
+ if (Object.keys(quota).some((key) => key !== "source")) {
57
+ throw invalidConfig(path, `${field}.quota with source none accepts no other options`);
58
+ }
59
+ }
60
+ else {
61
+ validateEnvironment(quota, quota.source, `${field}.quota`, path);
62
+ }
63
+ if (quota.configDir !== undefined)
64
+ quota.configDir = resolvePath(quota.configDir, home, path);
65
+ }
66
+ }
26
67
  return {
27
68
  path,
28
69
  platform: value.platform ?? "codingAgent",
29
70
  ...(value.projectsRoot === undefined
30
71
  ? {}
31
- : { projectsRoot: resolveProjectsRoot(value.projectsRoot, home, path) }),
32
- code: {
33
- ...(code.agent === undefined ? {} : { agent: code.agent }),
34
- ...(code.defaultModel === undefined ? {} : { defaultModel: code.defaultModel }),
35
- ...(code.models === undefined ? {} : { models: code.models }),
36
- skipPermissions: code.skipPermissions ?? false,
37
- unset: code.unset ?? [],
38
- },
72
+ : {
73
+ projectsRoot: {
74
+ path: resolvePath(value.projectsRoot, home, path),
75
+ written: value.projectsRoot,
76
+ },
77
+ }),
78
+ code,
39
79
  };
40
80
  }
41
81
  function absentConfig(home) {
@@ -46,51 +86,177 @@ function absentConfig(home) {
46
86
  return {};
47
87
  }
48
88
  function parseConfigFile(path) {
49
- let value;
89
+ let text;
50
90
  try {
51
- value = JSON.parse(readFileSync(path, "utf8"));
91
+ text = readFileSync(path, "utf8");
52
92
  }
53
93
  catch (error) {
54
94
  throw invalidConfig(path, errorMessage(error));
55
95
  }
96
+ let value;
97
+ try {
98
+ value = JSON.parse(text);
99
+ }
100
+ catch {
101
+ throw invalidConfig(path, "must contain valid JSON");
102
+ }
56
103
  return parseShape(configShape, value, (detail) => invalidConfig(path, detail));
57
104
  }
105
+ function warnUnknownSetting(path, key) {
106
+ const quoted = JSON.stringify(key).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (character) => character
107
+ .split("")
108
+ .map((unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`)
109
+ .join(""));
110
+ const field = /^[A-Za-z_$][\w$]*$/.test(key)
111
+ ? `${path === "" ? "" : `${path}.`}${key}`
112
+ : `${path === "" ? "settings" : path}[${quoted}]`;
113
+ let migration = "Remove it or check its spelling.";
114
+ if (path === "code" && key === "defaultProfiles") {
115
+ migration =
116
+ "code.defaultProfiles is retired: manually move each needed preference to its referenced " +
117
+ "matching-agent profile's default: true (omit singleton flags), remove the map and " +
118
+ "keep profile names unchanged. See " +
119
+ "https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/" +
120
+ "references/alignfirst-upgrade.md#convert-aligndev-profile-defaults";
121
+ }
122
+ else if (path === "code" && RETIRED_CODE_KEYS.includes(key)) {
123
+ migration =
124
+ "Retired launch setting: move it into code.profiles and select one with code.profile " +
125
+ "(manual conversion required).";
126
+ }
127
+ console.warn(`Warning: ignoring unknown aligndev setting ${field}. ${migration}`);
128
+ }
58
129
  function invalidConfig(path, detail) {
59
130
  return new Error(`Error: invalid aligndev config ${path}: ${detail}`);
60
131
  }
61
- function resolveProjectsRoot(written, home, path) {
132
+ function directoryValue(value, path) {
133
+ nonblankString(value, path);
134
+ return nulFreeString(value, path);
135
+ }
136
+ function validateEnvironment(settings, agent, field, path) {
137
+ for (const name of settings.unset ?? []) {
138
+ if (Object.hasOwn(settings.env ?? {}, name)) {
139
+ throw invalidConfig(path, `${field}.unset overlaps ${field}.env for ${name}`);
140
+ }
141
+ }
142
+ const variable = CONFIG_DIRECTORY_VARIABLES[agent];
143
+ if (settings.configDir !== undefined &&
144
+ (Object.hasOwn(settings.env ?? {}, variable) || settings.unset?.includes(variable))) {
145
+ throw invalidConfig(path, `${field}.configDir conflicts with env/unset for ${variable}`);
146
+ }
147
+ }
148
+ function resolvePath(written, home, path) {
62
149
  if (written.startsWith("~/"))
63
- return { path: join(home, written.slice(2)), written };
64
- return { path: isAbsolute(written) ? written : resolve(dirname(path), written), written };
65
- }
66
- export function resolveCodeConfig(config, env) {
67
- const code = { ...config.code, agent: resolveAgent(config, env) };
68
- checkDefaultModel(code, config.path);
69
- return code;
70
- }
71
- // The configured `code.agent` wins; otherwise, the coding agent that runs aligndev.
72
- function resolveAgent(config, env) {
73
- const { agent } = config.code;
74
- if (agent !== undefined)
75
- return agent;
150
+ return join(home, written.slice(2));
151
+ return isAbsolute(written) ? written : resolve(dirname(path), written);
152
+ }
153
+ export function resolveQuotaConfig(code, callerEnv) {
154
+ const quota = code.quota;
155
+ if (quota?.source === "none")
156
+ return { source: "none" };
157
+ if (quota === undefined) {
158
+ if (code.agent === "pi") {
159
+ throw new Error("Pi account quota is unsupported without explicit configuration: " +
160
+ "set quota.source to claude or codex with its native configDir, or none to disable it.");
161
+ }
162
+ return { source: code.agent, env: code.childEnv };
163
+ }
164
+ const overrides = { ...quota.env };
165
+ if (quota.configDir !== undefined)
166
+ overrides[CONFIG_DIRECTORY_VARIABLES[quota.source]] = quota.configDir;
167
+ return {
168
+ source: quota.source,
169
+ env: buildAgentEnv(callerEnv, quota.unset ?? [], overrides),
170
+ };
171
+ }
172
+ export function resolveCodeConfig(config, env, selection = {}) {
173
+ validateReferences(config);
174
+ const name = selection.explicit ?? selection.project?.profile ?? selection.recorded ?? config.code.profile;
175
+ let profile;
176
+ let effectiveName = name;
177
+ if (name !== undefined) {
178
+ profile = referencedProfile(config, name, "selected profile");
179
+ }
180
+ else if (selection.recorded === null) {
181
+ profile = { agent: detectAgent(config, env) };
182
+ }
183
+ else {
184
+ const automatic = resolveAutomaticProfile(config, env);
185
+ profile = automatic.profile;
186
+ effectiveName = automatic.name;
187
+ }
188
+ checkDefaultModel(profile, config.path, effectiveName);
189
+ const overrides = { ...profile.env };
190
+ if (profile.configDir !== undefined)
191
+ overrides[CONFIG_DIRECTORY_VARIABLES[profile.agent]] = profile.configDir;
192
+ return {
193
+ ...profile,
194
+ profile: effectiveName ?? null,
195
+ skipPermissions: profile.skipPermissions ?? false,
196
+ unset: profile.unset ?? [],
197
+ childEnv: buildAgentEnv(env, profile.unset ?? [], overrides, createAgentAdapter(profile.agent).env),
198
+ };
199
+ }
200
+ function validateReferences(config) {
201
+ if (config.code.profile !== undefined)
202
+ referencedProfile(config, config.code.profile, "code.profile");
203
+ for (const agent of CODING_AGENTS) {
204
+ const names = Object.entries(config.code.profiles ?? {})
205
+ .filter(([, profile]) => profile.agent === agent && profile.default === true)
206
+ .map(([name]) => JSON.stringify(name));
207
+ if (names.length > 1)
208
+ throw invalidConfig(config.path, `multiple default: true profiles for ${agent}: ${names.join(", ")}; ` +
209
+ `leave only one default: true for ${agent}`);
210
+ }
211
+ }
212
+ function referencedProfile(config, name, field) {
213
+ const profile = Object.hasOwn(config.code.profiles ?? {}, name)
214
+ ? config.code.profiles?.[name]
215
+ : undefined;
216
+ if (name.trim() === "" || profile === undefined) {
217
+ throw invalidConfig(config.path, `${field} references missing profile ${JSON.stringify(name)}; define it in code.profiles or select another --profile`);
218
+ }
219
+ return profile;
220
+ }
221
+ function resolveAutomaticProfile(config, env) {
222
+ const detected = detectCodingAgents(env);
223
+ const profiles = Object.entries(config.code.profiles ?? {});
224
+ if (detected.length === 0 && profiles.length === 1) {
225
+ const [name, profile] = profiles[0];
226
+ return { name, profile };
227
+ }
228
+ if (detected.length !== 1)
229
+ throw selectionRequired(config, detected);
230
+ const agent = detected[0];
231
+ const matching = profiles.filter(([, profile]) => profile.agent === agent);
232
+ if (matching.length === 0)
233
+ return { profile: { agent } };
234
+ const selected = matching.length === 1 ? matching[0] : matching.find(([, p]) => p.default === true);
235
+ if (selected !== undefined)
236
+ return { name: selected[0], profile: selected[1] };
237
+ throw invalidConfig(config.path, `multiple profiles for detected ${agent}: ${matching.map(([name]) => JSON.stringify(name)).join(", ")}; ` +
238
+ "select --profile, a project registry profile, code.profile, or set one matching " +
239
+ "profile's default: true");
240
+ }
241
+ function detectAgent(config, env) {
76
242
  const detected = detectCodingAgents(env);
77
243
  if (detected.length === 1)
78
244
  return detected[0];
245
+ throw selectionRequired(config, detected);
246
+ }
247
+ function selectionRequired(config, detected) {
79
248
  const problem = detected.length === 0
80
- ? `no coding agent detected (${CODING_AGENTS.join(", ")}): run from a supported agent, or set`
81
- : `multiple coding agents detected (${detected.join(", ")}): set`;
82
- throw new Error(`Error: ${problem} "code.agent" (${CODING_AGENTS.join(" or ")}) in ${config.path}.`);
249
+ ? `no coding agent detected (${CODING_AGENTS.join(", ")})`
250
+ : `multiple coding agents detected (${detected.join(", ")})`;
251
+ return new Error(`Error: ${problem}: select --profile, a project registry profile, or set "code.profile" in ${config.path}.`);
83
252
  }
84
- function checkDefaultModel(code, path) {
253
+ function checkDefaultModel(code, path, profile) {
85
254
  if (code.defaultModel === undefined)
86
255
  return;
87
- const models = resolveModels(code.agent, code.models);
88
- if (code.defaultModel.trim() === "") {
89
- throw new Error(`Error: code.defaultModel must be nonblank, in ${path}.`);
90
- }
256
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
91
257
  if (models === undefined || models.includes(code.defaultModel))
92
258
  return;
93
- throw new Error(`Error: code.defaultModel must be one of: ${models.join(", ")}, in ${path}.`);
259
+ throw invalidConfig(path, `code.profiles[${JSON.stringify(profile)}].defaultModel must be one of: ${models.join(", ")}`);
94
260
  }
95
261
  export function requireProjectsRoot(config) {
96
262
  if (config.projectsRoot !== undefined)
@@ -1,4 +1,4 @@
1
1
  import type { CodingAgent } from "../code/coding-agent.js";
2
2
  import type { CommandForms } from "../command-form.js";
3
- import type { Platform } from "../config.js";
4
- export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[] | undefined, defaultModel: string | undefined, forms: CommandForms): string;
3
+ import { type Platform } from "../config.js";
4
+ export declare function renderCodeGuide(platform: Platform, agent: CodingAgent, models: readonly string[] | undefined, defaultModel: string | undefined, forms: CommandForms, profile?: string | null, nativeStorage?: string): string;
@@ -1,17 +1,20 @@
1
+ import { CONFIG_DIRECTORY_VARIABLES } from "../config.js";
1
2
  import { renderGuideTemplate } from "./render-template.js";
2
- export function renderCodeGuide(platform, agent, models, defaultModel, forms) {
3
+ export function renderCodeGuide(platform, agent, models, defaultModel, forms, profile = null, nativeStorage = `${CONFIG_DIRECTORY_VARIABLES[agent]}: inherited/default native storage`) {
3
4
  return renderGuideTemplate("code.md", { platform }, forms, {
4
5
  AGENT: agent,
6
+ PROFILE: profile ?? "(built-in)",
7
+ NATIVE_CONFIG: nativeStorage,
5
8
  AUTH_COMMAND: agent === "pi"
6
- ? "`pi`, then `/login <provider>`, or configure provider credentials"
9
+ ? "`pi`, then `/login <provider>`, or configure provider credentials in the selected native configuration"
7
10
  : agent === "claude"
8
- ? "`claude`, then `/login`"
9
- : "`codex login`",
11
+ ? "`claude`, then `/login` in the selected native configuration"
12
+ : "`codex login` in the selected native configuration",
10
13
  PERMISSIONS: agent === "pi"
11
- ? "Pi uses ordinary OS permissions, including companion access. `code.skipPermissions` has no effect. Saved project trust is honored; no forced approval is passed"
14
+ ? "Pi uses ordinary OS permissions, including companion access. `profile.skipPermissions` has no effect. Saved project trust is honored; no forced approval is passed"
12
15
  : agent === "claude"
13
- ? "Normal runs use `--permission-mode auto`, plus `--add-dir <companion>` for a project with a companion directory. `code.skipPermissions: true` in the aligndev settings selects `--dangerously-skip-permissions`"
14
- : "Normal runs use `--sandbox workspace-write`, plus `--add-dir <companion>` for a project with a companion directory. `code.skipPermissions: true` in the aligndev settings selects `--dangerously-bypass-approvals-and-sandbox`",
16
+ ? "Normal runs use `--permission-mode auto`, plus `--add-dir <companion>` for a project with a companion directory. `profile.skipPermissions: true` in the aligndev settings selects `--dangerously-skip-permissions`"
17
+ : "Normal runs use `--sandbox workspace-write`, plus `--add-dir <companion>` for a project with a companion directory. `profile.skipPermissions: true` in the aligndev settings selects `--dangerously-bypass-approvals-and-sandbox`",
15
18
  MODEL_POLICY: models === undefined
16
19
  ? "Any nonblank pi-native selector, preferably `provider/model` (thinking suffixes supported)"
17
20
  : `One of ${models.map((model) => `\`${model}\``).join(", ")}`,