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
package/README.md CHANGED
@@ -30,13 +30,13 @@ A task can also start at any intermediate step.
30
30
 
31
31
  **As an OpenClaw bot.** [AlignDev for OpenClaw](#start-as-an-openclaw-bot) deploys the assistant on a server, under its own name in Slack or Discord. It works on every project of the host, one thread per task.
32
32
 
33
- For a coding-agent assistant, parent host and delegated child are independent: `code.agent` selects Claude Code, Codex or Pi. Without that setting, the detected parent kind is the default child. OpenClaw deployment templates still offer Claude Code or Codex.
33
+ For a coding-agent assistant, parent host and delegated child are independent: a coding profile selects Claude Code, Codex or Pi. Without a profile selection, the detected parent kind supplies the default child. OpenClaw deployment templates offer all three agents on Slack or Discord, with explicit profiles and inventoried default/custom native stores. The Pi overlay uses a protected absolute-Node launcher while retaining project PATH. Its [deployment boundary](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/aligndev-openclaw.md#deployment-gate) explicitly permits writable native `auth.json` and adjacent locks for OAuth renewal. That file can persist same-account executable API-key commands; this is account-level persistence, not administrator privilege escalation. Other managed resources and trust retain controlled-maintenance protection. Project trust is not a sandbox, and offline checks do not certify live deployment.
34
34
 
35
35
  ## Start in Claude Code, Codex or Pi
36
36
 
37
37
  The project needs an AlignFirst `.plans` directory, in its repository or in a [companion directory](https://github.com/paleo/alignfirst/tree/main/packages/alignfirst#companion-directories). The [setup guide](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/coding-agent-assistant.md) prepares it.
38
38
 
39
- The child needs network access and writes outside the repository. Claude Code/Codex parents request their established sandbox bypass or elevation; approve that request when it comes. Pi uses ordinary OS permissions and saved project trust. It has no implied sandbox or per-command approval boundary, and `code.skipPermissions` has no effect on Pi.
39
+ The child needs network access and writes outside the repository. Claude Code/Codex parents request their established sandbox bypass or elevation; approve that request when it comes. Pi uses ordinary OS permissions and saved project trust. It has no implied sandbox or per-command approval boundary, and A profile's `skipPermissions` has no effect on Pi.
40
40
 
41
41
  ### With the Skill
42
42
 
@@ -74,29 +74,72 @@ Then ask your session to work with aligndev.
74
74
  ### Requirements
75
75
 
76
76
  - Node.js 22.11 or later. The assistant runs `aligndev` through `npx`, so there is nothing to install.
77
- - The selected child installed and authenticated: `claude` then `/login`, `codex login`, or `pi` then `/login <provider>` (or configured provider credentials). Pi requires Node.js 22.19 or later; the Pi adapter and extensions target Pi 1.3.0.
77
+ - The selected child installed and authenticated under the same effective environment and cwd as the child. Apply the profile's `unset/env/configDir`, including HOME, PATH and credential routing, before using `claude` then `/login`, `codex login`, or `pi` then `/login <provider>` (or configured provider credentials). A bare login in another shell may select another account. Pi requires Node.js 22.19 or later; the Pi adapter and extensions target Pi 1.3.0.
78
78
  - For Pi, select a usable native model, preferably `provider/model` (optional thinking suffix). Authenticate in the same account/configuration used by the child; never expose credential values in diagnostics.
79
79
  - Linux or macOS, or Windows through WSL.
80
80
 
81
81
  ## Configuration
82
82
 
83
- `~/.alignfirst/aligndev.settings.json` is optional. Without it, every key takes its default. For example, to launch Codex as the agent, whatever runs the assistant, with `sol` as the default model:
83
+ `~/.alignfirst/aligndev.settings.json` is optional. Without it, the detected parent kind supplies built-in child defaults. For example:
84
84
 
85
85
  ```json
86
86
  {
87
- "code": { "agent": "codex", "defaultModel": "sol" }
87
+ "code": {
88
+ "profile": "codex-personal",
89
+ "defaultProfiles": { "claude": "claude-personal", "codex": "codex-personal" },
90
+ "profiles": {
91
+ "codex-personal": { "agent": "codex", "configDir": "~/.codex", "defaultModel": "sol" },
92
+ "claude-personal": {
93
+ "agent": "claude", "configDir": "~/.claude", "defaultModel": "opus",
94
+ "unset": ["ANTHROPIC_API_KEY"]
95
+ },
96
+ "claude-work": {
97
+ "agent": "claude", "configDir": "~/.claude-work", "defaultModel": "opus",
98
+ "unset": ["ANTHROPIC_API_KEY"]
99
+ },
100
+ "pi-codex": {
101
+ "agent": "pi", "configDir": "~/.pi/agent", "defaultModel": "sol",
102
+ "modelAliases": { "sol": "openai/sol" },
103
+ "quota": { "source": "codex", "configDir": "~/.codex" }
104
+ },
105
+ "pi-anthropic": {
106
+ "agent": "pi", "configDir": "~/.pi/anthropic", "defaultModel": "opus",
107
+ "modelAliases": { "opus": "anthropic/opus" },
108
+ "quota": { "source": "claude", "configDir": "~/.claude" }
109
+ }
110
+ }
111
+ }
88
112
  }
89
113
  ```
90
114
 
91
- - `platform` — `codingAgent` (default) for a coding-agent assistant, `openclaw` for an OpenClaw bot.
92
- - `projectsRoot` — the projects directory of an OpenClaw host. Required by `openclaw`. `~/` expands to the home directory; a relative path resolves against `~/.alignfirst/`.
93
- - `code.agent` — the child: `claude`, `codex` or `pi`. Default: the coding agent running the assistant, detected from its environment. Set it to choose another child or resolve mixed host markers. It never selects the parent's launch tool.
94
- - `code.defaultModel` — the model of a new session without `--model`, one of the accepted models. Default: the child's own default. A resumed session keeps its recorded model; Pi resumes require the original worktree.
95
- - `code.models` — a nonempty list restricts accepted selectors. Defaults: Claude's `fable`, `opus`, `sonnet`, `haiku`, or Codex's `astra`, `sol`, `terra`, `luna`. Pi accepts any nonblank native selector by default, preferably `provider/model`; an absent or empty list adds no allowlist.
96
- - `code.skipPermissions` — `true` runs Claude Code with `--dangerously-skip-permissions` instead of `--permission-mode auto`, and Codex with `--dangerously-bypass-approvals-and-sandbox` instead of `--sandbox workspace-write`. Default: `false`. Irrelevant to Pi's ordinary OS permissions.
97
- - `code.unset` — environment variables to hide from the agent, such as an API key meant for another tool on the host.
115
+ The Pi targets illustrate native shorthand; availability depends on Pi's catalog and account. Exact provider-qualified IDs pin a model. Provider-qualified fuzzy selectors and thinking suffixes pass unchanged to Pi, which owns their resolution. AlignDev neither guesses providers nor implements newest-family ordering.
98
116
 
99
- Unknown keys and invalid values are errors. `aligndev code quota` is unsupported for Pi; consult the selected provider directly.
117
+ - `platform` — `codingAgent` (default), or `openclaw`.
118
+ - `projectsRoot` — projects directory, required by the OpenClaw playbook. `~/` uses the configured home; relative paths resolve against the settings directory.
119
+ - `code.profile` — global named child profile, independent of the parent host.
120
+ - `code.defaultProfiles` — defaults by detected agent kind. Remove `code.profile` above to use these defaults.
121
+ - `code.profiles` — complete profiles, with required `agent` (`claude`, `codex`, `pi`). Names and references are exact, nonblank strings. Profiles have no inheritance or merging.
122
+
123
+ Each profile accepts:
124
+
125
+ - `configDir` — native configuration and authentication storage: `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, or `PI_CODING_AGENT_DIR`. `~/` uses the configured home; relative paths resolve against the settings directory. Omission keeps native inherited/default storage.
126
+ - `env` — literal environment values for non-secret configuration. No interpolation or shell expansion. Keep credentials in native stores or separately provisioned process environments.
127
+ - `unset` — inherited variables to remove, including API keys that select an unintended authentication route. A variable cannot occur in both `env` and `unset`. An explicit `configDir` cannot coexist with its native directory variable in either field.
128
+ - `defaultModel` — new-session default, validated against accepted names. Omission uses the native default.
129
+ - `models` — a nonempty list replaces accepted names. Otherwise Claude accepts `fable`, `opus`, `sonnet`, `haiku`, Codex accepts `astra`, `sol`, `terra`, `luna`, and both add configured alias names. Pi accepts every nonblank selector. An empty list adds no override.
130
+ - `modelAliases` — one-step user-facing name → native selector mappings. Validate the chosen name first, expand once, then apply native handling. A Codex alias target such as `sol` still resolves through its bundled catalog.
131
+ - `skipPermissions` — defaults to false. Claude uses `--permission-mode auto`, or `--dangerously-skip-permissions`; Codex uses `--sandbox workspace-write`, or `--dangerously-bypass-approvals-and-sandbox`. Pi ignores this setting.
132
+ - `quota` — independent native usage reader: `source` is `claude`, `codex`, or `none`, with optional `configDir`, `env`, `unset`. `none` disables quota and accepts no other options. Omitted quota uses a native Claude/Codex profile's coding environment; Pi requires an explicit source.
133
+
134
+ Selection for new sessions, help, `guide code`, and quota: `--profile` → project registry selection → `code.profile` → detected-agent `code.defaultProfiles` → detected built-in defaults. Resume inserts its latest recorded profile before the global default. Explicit selections work without parent detection. Project selections use the actual working directory, matching linked worktrees through AlignFirst; help/guide/quota need no `.plans` or Git repository. `--profile` is rejected on status and unrelated guide topics.
135
+
136
+ `aligndev code quota [--profile <name>]` needs neither a ticket nor `.plans` and starts no coding session. Explicit quota settings start from the original caller environment, apply only their own `unset`, `env` and source-specific `configDir`, then strip parent-session identities. Coding-profile overrides and Pi credentials are not copied into the quota environment. The same path and validation rules apply. For multiple accounts, set quota `configDir` explicitly; omission deliberately keeps the native CLI's inherited/default configuration. Pair each Pi profile with the intended Codex or Claude account, as in the examples above. Reports name the profile and native source; the limits belong to that CLI's account. AlignDev does not verify that it matches Pi's account or infer it from a model. Native requests time out after 30 seconds and await bounded process cleanup.
137
+
138
+ The child inherits the caller environment, removes `unset`, then applies `env` and `configDir`. Parent-session identities are stripped afterward, and required adapter values win. The same finalized environment reaches discovery, execution and native context lookup. Help, guides and failures identify native storage selected through `configDir`, profile environment overrides, inherited variables or profile removal. They show environment-variable names and origins, never their values. Login must reproduce that effective environment and cwd. No environment values are printed or saved in run metadata.
139
+
140
+ Resume requires the same native agent and, for Pi, the same real directory. A selected account must contain the native conversation; failure never falls back to an old profile or accepts a new conversation. `--model` overrides the recorded user-facing model; otherwise that name is retained and validated under the current profile. A disallowed retained name requires an explicit replacement; a recorded null keeps the native conversation's model. Profile defaults apply only to new sessions. Retained aliases use the selected profile's current mappings, so changing a mapping can change the native target. Session metadata records profile, agent, chosen name, native ID and cwd; historical records without a profile read as null. Status reads durable metadata even when a launch profile has been deleted.
141
+
142
+ Unknown keys and invalid structural values fail with the settings path and field. Direct `code.agent/defaultModel/models/skipPermissions/unset` settings are retired and rejected. Move them manually into a named profile and select it with `code.profile`; see the [upgrade reference](https://github.com/paleo/alignfirst/blob/main/skills/alignfirst-setup-guide/references/alignfirst-upgrade.md#convert-aligndev-launch-settings). Authenticate under the selected native configuration before launching. Never retry against another account after an authentication or missing-conversation failure.
100
143
 
101
144
  ## Start as an OpenClaw Bot
102
145
 
@@ -105,7 +148,7 @@ AlignDev for OpenClaw runs the assistant as an OpenClaw bot. One deployment is a
105
148
  ```mermaid
106
149
  flowchart TD
107
150
  U([User]) -->|Slack or Discord| O[OpenClaw]
108
- O -->|aligndev guide and aligndev code| CA[Claude Code or Codex]
151
+ O -->|aligndev guide and aligndev code| CA[Claude Code, Codex or Pi]
109
152
  CA -->|AlignFirst protocols| FS[(Managed project)]
110
153
  ```
111
154
 
@@ -115,7 +158,7 @@ Install the setup skill where your agent will assemble the deployment's private
115
158
  npx -y skills add https://github.com/paleo/alignfirst --global --skill alignfirst-setup-guide
116
159
  ```
117
160
 
118
- Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code or Codex variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the full preparation contract: the `alignfirst context` section in its `AGENTS.md`, an optional work-files repository, docmap, isolated workspaces and a project-specific `DEVELOPERS.md`.
161
+ Then ask the agent to create an assistant. The skill collects the deployment values, renders one Slack or Discord variant and one Claude Code, Codex or Pi variant, and writes the installation, security, operation and recovery runbooks. Each managed project receives the full preparation contract: the `alignfirst context` section in its `AGENTS.md`, an optional work-files repository, docmap, isolated workspaces and a project-specific `DEVELOPERS.md`.
119
162
 
120
163
  ## Under the Hood
121
164
 
@@ -4,6 +4,7 @@ export interface AlignfirstResult {
4
4
  stderr: string;
5
5
  }
6
6
  export declare function runAlignfirst(command: string[], args: string[], cwd: string, env?: NodeJS.ProcessEnv): AlignfirstResult;
7
+ export declare function describeAlignfirst(command: string[], cwd: string, env: NodeJS.ProcessEnv): string;
7
8
  export declare function reserveSideTicket(command: string[], cwd: string, env: NodeJS.ProcessEnv): string;
8
9
  export declare function openTicket(command: string[], cwd: string, ticket: string, env: NodeJS.ProcessEnv): void;
9
10
  export declare function loadCatchup(command: string[], cwd: string, ticket: string, env: NodeJS.ProcessEnv): string;
@@ -1,4 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { accessSync, constants, existsSync, statSync } from "node:fs";
3
+ import { delimiter, resolve, sep } from "node:path";
4
+ import { readPackageVersion } from "./package-version.js";
2
5
  export function runAlignfirst(command, args, cwd, env = process.env) {
3
6
  const result = spawnSync(command[0], [...command.slice(1), ...args], {
4
7
  cwd,
@@ -7,7 +10,7 @@ export function runAlignfirst(command, args, cwd, env = process.env) {
7
10
  });
8
11
  if (result.error && isErrnoException(result.error) && result.error.code === "ENOENT") {
9
12
  throw new Error("alignfirst is not installed. Install it globally (`npm install -g alignfirst`), or run " +
10
- "aligndev through npx (`npx -y aligndev`).");
13
+ `aligndev through npx (\`npx -y aligndev\`). ${describeAlignfirst(command, cwd, env)}`);
11
14
  }
12
15
  if (result.error)
13
16
  throw result.error;
@@ -17,6 +20,45 @@ export function runAlignfirst(command, args, cwd, env = process.env) {
17
20
  stderr: result.stderr,
18
21
  };
19
22
  }
23
+ export function describeAlignfirst(command, cwd, env) {
24
+ const npx = command[0] === "npx";
25
+ const reason = npx
26
+ ? "aligndev was launched through npm/npx; npx prefers the project's local alignfirst dependency"
27
+ : "aligndev runs alignfirst from PATH when launched directly";
28
+ const facts = [`\`${command.join(" ")}\` (${reason})`];
29
+ if (!npx)
30
+ facts.push(describeExecutable(command[0], cwd, env));
31
+ const version = spawnSync(command[0], [...command.slice(1), "--version"], {
32
+ cwd,
33
+ env,
34
+ encoding: "utf8",
35
+ timeout: 10_000,
36
+ });
37
+ const line = version.stdout?.split(/\r?\n/, 1)[0]?.trim();
38
+ if (version.status === 0 && line !== undefined && line !== "" && line.length <= 80) {
39
+ facts.push(`version ${line}`);
40
+ }
41
+ const entry = process.argv[1] === undefined ? "" : ` at ${process.argv[1]}`;
42
+ facts.push(`aligndev ${readPackageVersion()}${entry}`);
43
+ return `alignfirst: ${facts.join("; ")}`.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ");
44
+ }
45
+ function describeExecutable(command, cwd, env) {
46
+ if (command.includes(sep)) {
47
+ return `executable ${command}${existsSync(resolve(cwd, command)) ? "" : " (not found)"}`;
48
+ }
49
+ for (const dir of env.PATH?.split(delimiter) ?? []) {
50
+ const path = resolve(cwd, dir, command);
51
+ try {
52
+ accessSync(path, constants.X_OK);
53
+ if (statSync(path).isFile())
54
+ return `executable ${path}`;
55
+ }
56
+ catch {
57
+ // Continue through PATH when an entry is missing or not executable.
58
+ }
59
+ }
60
+ return "not found on PATH";
61
+ }
20
62
  export function reserveSideTicket(command, cwd, env) {
21
63
  const result = runAlignfirst(command, ["ticket", "--side", "--json"], cwd, env);
22
64
  if (result.status !== 0) {
package/dist/cli.js CHANGED
@@ -1,13 +1,12 @@
1
- import { readFileSync } from "node:fs";
2
1
  import { homedir } from "node:os";
3
2
  import { runCode } from "./code/code-cli.js";
4
- import { CODING_AGENTS } from "./code/coding-agent.js";
5
- import { resolveExecutableModel } from "./code/models.js";
3
+ import { createExecutableModelResolver } from "./code/models.js";
6
4
  import { readQuota } from "./code/quota.js";
7
5
  import { resolveCommandForms } from "./command-form.js";
8
6
  import { loadConfig, PLATFORMS } from "./config.js";
9
7
  import { errorMessage } from "./errors.js";
10
8
  import { runGuide } from "./guide/guide-cli.js";
9
+ import { readPackageVersion } from "./package-version.js";
11
10
  import { runProject } from "./project/project-cli.js";
12
11
  export async function main(options) {
13
12
  const ctx = resolveContext(options);
@@ -26,11 +25,11 @@ export async function main(options) {
26
25
  return 1;
27
26
  }
28
27
  try {
28
+ if (command === "code")
29
+ return await runCode(tokens, () => loadConfig(ctx.home), ctx);
29
30
  const config = loadConfig(ctx.home);
30
31
  if (command === "project")
31
32
  return runProject(tokens, config, ctx);
32
- if (command === "code")
33
- return await runCode(tokens, config, ctx);
34
33
  return runGuide(tokens, config, ctx);
35
34
  }
36
35
  catch (error) {
@@ -57,8 +56,8 @@ ${usage}
57
56
  Run \`${aligndev} <command> --help\` for the usage of a command.
58
57
 
59
58
  Config (optional): ~/.alignfirst/aligndev.settings.json. "platform" (${PLATFORMS.join(" or ")})
60
- defaults to codingAgent. "code.agent" (${CODING_AGENTS.join(" or ")}) defaults to the coding agent that
61
- runs aligndev, detected from its environment.
59
+ defaults to codingAgent. Named code.profiles select child agents and native configuration.
60
+ Use code.profile for a global selection, or code.defaultProfiles for detected-agent defaults.
62
61
  `;
63
62
  }
64
63
  // Each row is a command, optionally followed by its description in an aligned column.
@@ -79,13 +78,7 @@ function resolveContext(options) {
79
78
  stderr: options?.stderr ?? process.stderr,
80
79
  forms,
81
80
  alignfirstCommand: options?.alignfirstCommand ?? forms.alignfirst.split(" "),
82
- modelResolver: options?.modelResolver ?? resolveExecutableModel,
81
+ modelResolver: options?.modelResolver ?? createExecutableModelResolver(),
83
82
  quotaReader: options?.quotaReader ?? readQuota,
84
83
  };
85
84
  }
86
- function readPackageVersion() {
87
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
88
- if (pkg.version === undefined)
89
- throw new Error("aligndev: package.json is missing 'version'");
90
- return pkg.version;
91
- }
@@ -1,7 +1,7 @@
1
1
  import type { AgentAdapter, AgentProtocolState, RunConfig } from "./run-agent.js";
2
2
  export declare function createClaudeAdapter(): AgentAdapter;
3
3
  export declare function buildClaudeArgs(config: RunConfig): string[];
4
- export declare function createClaudeState(): AgentProtocolState;
4
+ export declare function createClaudeState(config?: RunConfig): AgentProtocolState;
5
5
  export declare function interpretClaudeLine(line: string, state: AgentProtocolState): string | undefined;
6
6
  export declare function assessClaudeState(state: AgentProtocolState): {
7
7
  succeeded: boolean;
@@ -1,4 +1,4 @@
1
- import { isCompacted } from "./run-agent.js";
1
+ import { captureNativeSession, isCompacted } from "./run-agent.js";
2
2
  // After the agent's turn, `claude -p` waits for its background work, but stops it after 10 minutes
3
3
  // of idle waiting by default. `0` waits until the work ends.
4
4
  const CLAUDE_ENV = { CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: "0" };
@@ -31,8 +31,10 @@ export function buildClaudeArgs(config) {
31
31
  args.push("--model", config.executableModel);
32
32
  return args;
33
33
  }
34
- export function createClaudeState() {
34
+ export function createClaudeState(config) {
35
35
  return {
36
+ expectedSessionId: config?.resume,
37
+ earlierResults: [],
36
38
  protocolComplete: false,
37
39
  protocolFailed: false,
38
40
  authEvidence: false,
@@ -66,23 +68,34 @@ export function interpretClaudeLine(line, state) {
66
68
  }
67
69
  export function assessClaudeState(state) {
68
70
  return {
69
- succeeded: state.protocolComplete && !state.protocolFailed && state.result !== undefined,
71
+ succeeded: state.sessionId !== undefined &&
72
+ state.identityFailure === undefined &&
73
+ state.protocolComplete &&
74
+ !state.protocolFailed &&
75
+ state.result !== undefined,
70
76
  sessionId: state.sessionId,
71
77
  result: state.result,
72
- error: state.failure,
78
+ error: state.identityFailure ??
79
+ state.failure ??
80
+ (state.sessionId === undefined &&
81
+ (state.protocolComplete || state.expectedSessionId !== undefined)
82
+ ? "Claude reported no native session identity in the selected native configuration."
83
+ : undefined),
73
84
  authEvidence: state.authEvidence,
74
85
  contextTokens: state.contextTokens,
75
86
  contextCompacted: isCompacted(state),
76
87
  };
77
88
  }
78
- // Background work wakes the agent for more turns, each closed by its own `result` event. A turn
79
- // with nothing to report closes with an empty one, which must not erase the previous result.
89
+ // Background turns each close with a result. Keep superseded responses; empty turns erase none.
80
90
  function captureResult(result, state) {
81
91
  if (state.protocolFailed)
82
92
  state.failure = result;
83
- if (result === "" && state.result !== undefined)
93
+ if (result === "" || result === undefined)
84
94
  return;
95
+ if (state.result !== undefined)
96
+ state.earlierResults.push(state.result);
85
97
  state.result = result;
98
+ state.resultComplete = !state.protocolFailed;
86
99
  }
87
100
  // What the newest assistant response holds in the context window. Claude reports cache reads and
88
101
  // writes beside `input_tokens`, so the occupancy is their sum plus the response itself. A subagent
@@ -112,9 +125,9 @@ function parseEventLine(line) {
112
125
  }
113
126
  }
114
127
  function captureSessionId(event, state) {
115
- const id = asString(event.session_id);
116
- if (id !== undefined && id !== "")
117
- state.sessionId = id;
128
+ if (event.session_id !== undefined || (event.type === "system" && event.subtype === "init")) {
129
+ captureNativeSession(state, event.session_id, "Claude");
130
+ }
118
131
  }
119
132
  function renderMessageContent(event) {
120
133
  const message = event.message;
@@ -152,7 +165,8 @@ function renderToolResult(content) {
152
165
  }
153
166
  function claudeAuthenticationMessage(detail) {
154
167
  const base = "Coding agent not authenticated (authentication_failed): the host session is missing, " +
155
- "expired, or rejected. An administrator must re-login on the host (run `claude`, then " +
168
+ "expired, or rejected. An administrator must re-login with the same effective environment and cwd as the child " +
169
+ "(apply profile unset/env/configDir, including HOME, PATH and credential routing; run `claude`, then " +
156
170
  "`/login`) before `aligndev code` can run again.";
157
171
  const reason = detail?.trim();
158
172
  return reason === undefined || reason === "" ? base : `${base}\n\n${reason}`;
@@ -19,12 +19,15 @@ export interface CodeContext {
19
19
  }
20
20
  export type CodeCommand = {
21
21
  kind: "help";
22
+ profile?: string;
23
+ status?: boolean;
22
24
  } | {
23
25
  kind: "status";
24
26
  target: StatusTarget;
25
27
  includeResult: boolean;
26
28
  } | {
27
29
  kind: "quota";
30
+ profile?: string;
28
31
  } | {
29
32
  kind: "session";
30
33
  args: SessionArgs;
@@ -42,6 +45,7 @@ export type StatusTarget = {
42
45
  meta: string;
43
46
  };
44
47
  export interface SessionArgs {
48
+ profile?: string;
45
49
  resume?: string;
46
50
  ticket?: string;
47
51
  noTicket: boolean;
@@ -53,10 +57,10 @@ export interface SessionArgs {
53
57
  meta?: string;
54
58
  quiet?: boolean;
55
59
  }
56
- export declare function runCode(tokens: string[], config: LoadedConfig, ctx: CodeContext): Promise<number>;
60
+ export declare function runCode(tokens: string[], loadSettings: () => LoadedConfig, ctx: CodeContext): Promise<number>;
57
61
  export declare function parseCodeArgs(tokens: string[], aligndev: string): CodeCommand;
58
62
  export declare function validateSessionArgs(args: SessionArgs, models: readonly string[] | undefined): string | undefined;
59
- export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, ticket: string | undefined, records: SessionRecord[]): string | undefined;
63
+ export declare function checkLaunchGuards(args: SessionArgs, agent: CodingAgent, realCwd: string, ticket: string | undefined, records: SessionRecord[], previous?: SessionRecord): string | undefined;
60
64
  export declare function resolveTicket(args: SessionArgs, records: SessionRecord[]): string | undefined;
61
65
  export interface RunInput {
62
66
  args: SessionArgs;
@@ -65,7 +69,6 @@ export interface RunInput {
65
69
  ticket: string | undefined;
66
70
  cwd: string;
67
71
  sessionFilePath: string;
68
- env: NodeJS.ProcessEnv;
69
72
  executableModel: string | undefined;
70
73
  catchupContent?: string;
71
74
  contextContent?: string;