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.
Files changed (42) hide show
  1. package/README.md +58 -15
  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 +6 -3
  8. package/dist/code/code-cli.js +128 -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 +162 -38
  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 +3 -0
  33. package/dist/json-shape.js +23 -0
  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 +28 -10
  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 +1 -1
  42. package/templates/guide/code.md +26 -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
+ defaultProfiles?: Partial<Record<CodingAgent, string>>;
23
+ profiles?: Record<string, CodingProfile>;
24
+ }
25
+ export interface CodingProfile {
26
+ agent: CodingAgent;
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,85 @@
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
+ });
22
+ const profileShape = object({
23
+ agent: literal(...CODING_AGENTS),
24
+ configDir: optional(directoryValue),
25
+ defaultModel: optional(nonblankString),
26
+ models: optional(arrayOf(nonblankString)),
27
+ modelAliases: optional(record(nonblankString, nonblankString)),
12
28
  skipPermissions: optional(boolean),
13
- unset: optional(arrayOf(string)),
29
+ env: optional(environmentShape),
30
+ unset: optional(arrayOf(environmentName)),
31
+ quota: optional(quotaShape),
32
+ });
33
+ const codeShape = object({
34
+ profile: optional(nonblankString),
35
+ defaultProfiles: optional(object({
36
+ claude: optional(nonblankString),
37
+ codex: optional(nonblankString),
38
+ pi: optional(nonblankString),
39
+ })),
40
+ profiles: optional(record(profileShape, nonblankString)),
14
41
  });
15
42
  const configShape = object({
16
43
  platform: optional(literal(...PLATFORMS)),
17
44
  projectsRoot: optional(nonEmptyString),
18
45
  code: optional(codeShape),
19
46
  });
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.
47
+ const RETIRED_CODE_KEYS = ["agent", "defaultModel", "models", "skipPermissions", "unset"];
22
48
  export function loadConfig(home) {
23
49
  const path = join(home, ".alignfirst", "aligndev.settings.json");
24
50
  const value = existsSync(path) ? parseConfigFile(path) : absentConfig(home);
25
51
  const code = value.code ?? {};
52
+ for (const [name, profile] of Object.entries(code.profiles ?? {})) {
53
+ const field = `code.profiles[${JSON.stringify(name)}]`;
54
+ validateEnvironment(profile, profile.agent, field, path);
55
+ if (profile.configDir !== undefined)
56
+ profile.configDir = resolvePath(profile.configDir, home, path);
57
+ if (profile.quota !== undefined) {
58
+ const quota = profile.quota;
59
+ if (quota.source === "none") {
60
+ if (Object.keys(quota).some((key) => key !== "source")) {
61
+ throw invalidConfig(path, `${field}.quota with source none accepts no other options`);
62
+ }
63
+ }
64
+ else {
65
+ validateEnvironment(quota, quota.source, `${field}.quota`, path);
66
+ }
67
+ if (quota.configDir !== undefined)
68
+ quota.configDir = resolvePath(quota.configDir, home, path);
69
+ }
70
+ }
26
71
  return {
27
72
  path,
28
73
  platform: value.platform ?? "codingAgent",
29
74
  ...(value.projectsRoot === undefined
30
75
  ? {}
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
- },
76
+ : {
77
+ projectsRoot: {
78
+ path: resolvePath(value.projectsRoot, home, path),
79
+ written: value.projectsRoot,
80
+ },
81
+ }),
82
+ code,
39
83
  };
40
84
  }
41
85
  function absentConfig(home) {
@@ -53,44 +97,124 @@ function parseConfigFile(path) {
53
97
  catch (error) {
54
98
  throw invalidConfig(path, errorMessage(error));
55
99
  }
100
+ if (typeof value === "object" &&
101
+ value !== null &&
102
+ "code" in value &&
103
+ typeof value.code === "object" &&
104
+ value.code !== null) {
105
+ const retired = RETIRED_CODE_KEYS.find((key) => Object.hasOwn(value.code ?? {}, key));
106
+ if (retired !== undefined) {
107
+ throw invalidConfig(path, `code.${retired} is retired: move launch settings into ` +
108
+ "code.profiles and select one with code.profile (manual conversion required)");
109
+ }
110
+ }
56
111
  return parseShape(configShape, value, (detail) => invalidConfig(path, detail));
57
112
  }
58
113
  function invalidConfig(path, detail) {
59
114
  return new Error(`Error: invalid aligndev config ${path}: ${detail}`);
60
115
  }
61
- function resolveProjectsRoot(written, home, path) {
116
+ function directoryValue(value, path) {
117
+ nonblankString(value, path);
118
+ return nulFreeString(value, path);
119
+ }
120
+ function validateEnvironment(settings, agent, field, path) {
121
+ for (const name of settings.unset ?? []) {
122
+ if (Object.hasOwn(settings.env ?? {}, name)) {
123
+ throw invalidConfig(path, `${field}.unset overlaps ${field}.env for ${name}`);
124
+ }
125
+ }
126
+ const variable = CONFIG_DIRECTORY_VARIABLES[agent];
127
+ if (settings.configDir !== undefined &&
128
+ (Object.hasOwn(settings.env ?? {}, variable) || settings.unset?.includes(variable))) {
129
+ throw invalidConfig(path, `${field}.configDir conflicts with env/unset for ${variable}`);
130
+ }
131
+ }
132
+ function resolvePath(written, home, path) {
62
133
  if (written.startsWith("~/"))
63
- return { path: join(home, written.slice(2)), written };
64
- return { path: isAbsolute(written) ? written : resolve(dirname(path), written), written };
134
+ return join(home, written.slice(2));
135
+ return isAbsolute(written) ? written : resolve(dirname(path), written);
65
136
  }
66
- export function resolveCodeConfig(config, env) {
67
- const code = { ...config.code, agent: resolveAgent(config, env) };
68
- checkDefaultModel(code, config.path);
69
- return code;
137
+ export function resolveQuotaConfig(code, callerEnv) {
138
+ const quota = code.quota;
139
+ if (quota?.source === "none")
140
+ return { source: "none" };
141
+ if (quota === undefined) {
142
+ if (code.agent === "pi") {
143
+ throw new Error("Pi account quota is unsupported without explicit configuration: " +
144
+ "set quota.source to claude or codex with its native configDir, or none to disable it.");
145
+ }
146
+ return { source: code.agent, env: code.childEnv };
147
+ }
148
+ const overrides = { ...quota.env };
149
+ if (quota.configDir !== undefined)
150
+ overrides[CONFIG_DIRECTORY_VARIABLES[quota.source]] = quota.configDir;
151
+ return {
152
+ source: quota.source,
153
+ env: buildAgentEnv(callerEnv, quota.unset ?? [], overrides),
154
+ };
155
+ }
156
+ export function resolveCodeConfig(config, env, selection = {}) {
157
+ validateReferences(config);
158
+ const name = selection.explicit ?? selection.project?.profile ?? selection.recorded ?? config.code.profile;
159
+ let profile;
160
+ let effectiveName = name;
161
+ if (name !== undefined) {
162
+ profile = referencedProfile(config, name, "selected profile");
163
+ }
164
+ else {
165
+ const agent = detectAgent(config, env);
166
+ effectiveName = config.code.defaultProfiles?.[agent];
167
+ profile =
168
+ effectiveName === undefined
169
+ ? { agent }
170
+ : referencedProfile(config, effectiveName, "defaultProfiles");
171
+ }
172
+ checkDefaultModel(profile, config.path, effectiveName);
173
+ const overrides = { ...profile.env };
174
+ if (profile.configDir !== undefined)
175
+ overrides[CONFIG_DIRECTORY_VARIABLES[profile.agent]] = profile.configDir;
176
+ return {
177
+ ...profile,
178
+ profile: effectiveName ?? null,
179
+ skipPermissions: profile.skipPermissions ?? false,
180
+ unset: profile.unset ?? [],
181
+ childEnv: buildAgentEnv(env, profile.unset ?? [], overrides, createAgentAdapter(profile.agent).env),
182
+ };
70
183
  }
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;
184
+ function validateReferences(config) {
185
+ if (config.code.profile !== undefined)
186
+ referencedProfile(config, config.code.profile, "code.profile");
187
+ for (const [agent, name] of Object.entries(config.code.defaultProfiles ?? {})) {
188
+ const profile = referencedProfile(config, name, `code.defaultProfiles.${agent}`);
189
+ if (profile.agent !== agent)
190
+ throw invalidConfig(config.path, `code.defaultProfiles.${agent} references a ${profile.agent} profile`);
191
+ }
192
+ }
193
+ function referencedProfile(config, name, field) {
194
+ const profile = Object.hasOwn(config.code.profiles ?? {}, name)
195
+ ? config.code.profiles?.[name]
196
+ : undefined;
197
+ if (name.trim() === "" || profile === undefined) {
198
+ throw invalidConfig(config.path, `${field} references missing profile ${JSON.stringify(name)}; define it in code.profiles or select another --profile`);
199
+ }
200
+ return profile;
201
+ }
202
+ function detectAgent(config, env) {
76
203
  const detected = detectCodingAgents(env);
77
204
  if (detected.length === 1)
78
205
  return detected[0];
79
206
  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}.`);
207
+ ? `no coding agent detected (${CODING_AGENTS.join(", ")})`
208
+ : `multiple coding agents detected (${detected.join(", ")})`;
209
+ throw new Error(`Error: ${problem}: select --profile or set "code.profile" in ${config.path}.`);
83
210
  }
84
- function checkDefaultModel(code, path) {
211
+ function checkDefaultModel(code, path, profile) {
85
212
  if (code.defaultModel === undefined)
86
213
  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
- }
214
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
91
215
  if (models === undefined || models.includes(code.defaultModel))
92
216
  return;
93
- throw new Error(`Error: code.defaultModel must be one of: ${models.join(", ")}, in ${path}.`);
217
+ throw invalidConfig(path, `code.profiles[${JSON.stringify(profile)}].defaultModel must be one of: ${models.join(", ")}`);
94
218
  }
95
219
  export function requireProjectsRoot(config) {
96
220
  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(", ")}`,
@@ -1,7 +1,9 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { resolveModels } from "../code/models.js";
3
+ import { describeNativeStorage } from "../code/native-context.js";
3
4
  import { PLATFORMS, requireProjectsRoot, resolveCodeConfig, } from "../config.js";
4
5
  import { errorMessage } from "../errors.js";
6
+ import { readProjectReport } from "../project/layout.js";
5
7
  import { renderProjectsGuideForRoot } from "../project/project-cli.js";
6
8
  import { renderCodeGuide } from "./code-guide.js";
7
9
  import { resolveGuideFile } from "./guide-file.js";
@@ -23,6 +25,7 @@ function parseGuideArgs(tokens) {
23
25
  args: tokens,
24
26
  options: {
25
27
  root: { type: "string" },
28
+ profile: { type: "string" },
26
29
  help: { type: "boolean", short: "h", default: false },
27
30
  },
28
31
  strict: true,
@@ -34,12 +37,15 @@ function parseGuideArgs(tokens) {
34
37
  if (values.root !== undefined && topic !== "project") {
35
38
  throw new Error("Error: --root is valid only with `aligndev guide project`.");
36
39
  }
37
- return { topic, root: values.root, help: values.help };
40
+ if (values.profile !== undefined && topic !== "code") {
41
+ throw new Error("Error: --profile is valid only with `aligndev guide code`.");
42
+ }
43
+ return { topic, root: values.root, profile: values.profile, help: values.help };
38
44
  }
39
45
  function renderUsage(forms) {
40
46
  const playbookTopics = PLATFORMS.map((platform) => ` ${platform}: ${PLAYBOOK_TOPICS[platform].join(", ")}`);
41
47
  return `Usage:
42
- ${forms.aligndev} guide [<topic>] [--root <path>]
48
+ ${forms.aligndev} guide [<topic>] [--root <path>] [--profile <name>]
43
49
  ${forms.aligndev} guide --help
44
50
 
45
51
  Without a topic, prints the playbook of the platform set in the aligndev settings.
@@ -54,16 +60,19 @@ ${playbookTopics.join("\n")}
54
60
  }
55
61
  function renderTopic(args, config, ctx) {
56
62
  if (args.topic === "code")
57
- return renderCodeTopic(config, ctx);
63
+ return renderCodeTopic(config, ctx, args.profile);
58
64
  if (args.topic === "project" && config.platform === "openclaw") {
59
65
  return renderProjectsGuideForRoot({ ...ctx, projectsRoot: config.projectsRoot }, args.root);
60
66
  }
61
67
  return renderPlaybookTopic(args.topic, config, ctx);
62
68
  }
63
- function renderCodeTopic(config, ctx) {
64
- const code = resolveCodeConfig(config, ctx.env);
65
- const models = resolveModels(code.agent, code.models);
66
- return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms);
69
+ function renderCodeTopic(config, ctx, profile) {
70
+ const report = readProjectReport(ctx.alignfirstCommand, ctx.cwd, ctx.env);
71
+ if ("error" in report)
72
+ throw new Error(report.error);
73
+ const code = resolveCodeConfig(config, ctx.env, { project: report.aligndev, explicit: profile });
74
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
75
+ return renderCodeGuide(config.platform, code.agent, models, code.defaultModel, ctx.forms, code.profile, describeNativeStorage(code));
67
76
  }
68
77
  function renderPlaybookTopic(topic, config, ctx) {
69
78
  if (topic !== undefined)
@@ -9,6 +9,9 @@ type Fields<T> = {
9
9
  export declare function parseShape<T>(check: Check<T>, value: unknown, toError: (detail: string) => Error): T;
10
10
  /** Rejects the first unknown key, then checks each field in declaration order. */
11
11
  export declare function object<T extends object>(fields: Fields<T>): Check<T>;
12
+ export declare function record<T>(check: Check<T>, keyCheck?: Check<string>): Check<Record<string, T>>;
13
+ export declare function nonblankString(value: unknown, path: string): string;
14
+ export declare function nulFreeString(value: unknown, path: string): string;
12
15
  export declare function optional<T>(check: Check<T>): OptionalField<T>;
13
16
  export declare function literal<const T extends readonly (string | number)[]>(...values: T): Check<T[number]>;
14
17
  export declare function integerBetween(min: number, max: number): Check<number>;
@@ -33,6 +33,29 @@ export function object(fields) {
33
33
  return result;
34
34
  };
35
35
  }
36
+ export function record(check, keyCheck = string) {
37
+ return (value, path) => {
38
+ if (!isPlainObject(value))
39
+ throw shapeError(path, "be an object");
40
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
41
+ const fieldPath = childPath(path, key);
42
+ keyCheck(key, fieldPath);
43
+ return [key, check(item, fieldPath)];
44
+ }));
45
+ };
46
+ }
47
+ export function nonblankString(value, path) {
48
+ const text = string(value, path);
49
+ if (text.trim() === "")
50
+ throw shapeError(path, "be nonblank");
51
+ return text;
52
+ }
53
+ export function nulFreeString(value, path) {
54
+ const text = string(value, path);
55
+ if (text.includes("\u0000"))
56
+ throw shapeError(path, "contain no NUL characters");
57
+ return text;
58
+ }
36
59
  function isPlainObject(value) {
37
60
  if (typeof value !== "object" || value === null)
38
61
  return false;
@@ -0,0 +1 @@
1
+ export declare function readPackageVersion(): string;