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
@@ -2,14 +2,15 @@ import { existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
2
2
  import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { loadCatchup, loadContext, openTicket, reserveSideTicket } from "../alignfirst-cli.js";
5
- import { resolveCodeConfig } from "../config.js";
5
+ import { resolveCodeConfig, resolveQuotaConfig, } from "../config.js";
6
6
  import { errorMessage } from "../errors.js";
7
7
  import { companionInUse, readProjectReport, } from "../project/layout.js";
8
8
  import { createAgentAdapter } from "./coding-agent.js";
9
- import { resolveModels } from "./models.js";
9
+ import { expandModelAlias, resolveModels } from "./models.js";
10
+ import { describeNativeStorage } from "./native-context.js";
10
11
  import { buildPrompt, PROTOCOLS } from "./prompt.js";
11
- import { buildAgentEnv, runAgent } from "./run-agent.js";
12
- import { applyCompletion, findNewestSessionFile, listSessionRecords, readPidStartTime, reconcileSessionFile, resolveSessionFilePath, RESULT_MARKER, writeInitialSessionFile, } from "./session-file.js";
12
+ import { runAgent } from "./run-agent.js";
13
+ import { applyCompletion, createSessionFile, findNewestSessionFile, listSessionRecords, readPidStartTime, reconcileSessionFile, RESULT_MARKER, } from "./session-file.js";
13
14
  // Distinct from 1 (ordinary run failure) so a script can branch on an auth failure that needs an
14
15
  // operator re-login rather than a retry.
15
16
  const EXIT_AUTH_REQUIRED = 2;
@@ -20,6 +21,7 @@ const SESSION_OPTIONS = {
20
21
  ticket: { type: "string" },
21
22
  message: { type: "string", short: "m" },
22
23
  model: { type: "string" },
24
+ profile: { type: "string" },
23
25
  meta: { type: "string" },
24
26
  quiet: { type: "boolean" },
25
27
  help: { type: "boolean", short: "h", default: false },
@@ -33,17 +35,35 @@ const CONTEXT_COMPANION_ITEMS = [
33
35
  ];
34
36
  const TICKET_PATH_ERROR = "Error: --ticket must be a single path segment " +
35
37
  "(letters, digits, '.', '-', '_'); no path separators or '..'.";
36
- export async function runCode(tokens, config, ctx) {
38
+ export async function runCode(tokens, loadSettings, ctx) {
37
39
  try {
38
40
  const command = parseCodeArgs(tokens, ctx.forms.aligndev);
39
41
  if (command.kind === "status")
40
42
  return showStatus(ctx, command.target, command.includeResult);
41
- const code = resolveCodeConfig(config, ctx.env);
43
+ if (command.kind === "help" && command.status === true) {
44
+ ctx.stdout.write(`${ctx.forms.aligndev} code status (<session-file> | --ticket <id> | --no-ticket | --meta <key>) [--result]\nRead durable metadata without reading settings.\n`);
45
+ return 0;
46
+ }
47
+ const config = loadSettings();
48
+ const report = readReport(ctx);
49
+ const records = command.kind === "session" ? listSessionRecords(report.locations._aligndev.path) : [];
50
+ const args = command.kind === "session" ? command.args : undefined;
51
+ const previous = args?.resume === undefined
52
+ ? undefined
53
+ : latestRecord(records.filter((record) => record.frontmatter.sessionId === args.resume));
54
+ if (args?.resume !== undefined && previous === undefined) {
55
+ throw new Error(unknownResumeError(args.resume, records));
56
+ }
57
+ const code = resolveCodeConfig(config, ctx.env, {
58
+ project: report.aligndev,
59
+ explicit: args?.profile ?? (command.kind === "session" ? undefined : command.profile),
60
+ recorded: previous?.frontmatter.profile,
61
+ });
42
62
  if (command.kind === "quota")
43
63
  return await showQuota(ctx, code);
44
- const models = resolveModels(code.agent, code.models);
64
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
45
65
  if (command.kind === "help") {
46
- ctx.stdout.write(renderHelp(code.agent, models, ctx.forms));
66
+ ctx.stdout.write(renderHelp(code, models, ctx.forms));
47
67
  return 0;
48
68
  }
49
69
  loadMessage(command.args, ctx.cwd);
@@ -52,7 +72,7 @@ export async function runCode(tokens, config, ctx) {
52
72
  ctx.stderr.write(`${validationError}\n`);
53
73
  return 1;
54
74
  }
55
- return await runSession(command.args, code, ctx);
75
+ return await runSession(command.args, code, ctx, report, records, previous);
56
76
  }
57
77
  catch (error) {
58
78
  ctx.stderr.write(`${errorMessage(error)}\n`);
@@ -84,12 +104,21 @@ function sessionTreeOf(report, cwd) {
84
104
  };
85
105
  }
86
106
  async function showQuota(ctx, code) {
87
- const report = await ctx.quotaReader(code.agent, {
88
- cwd: ctx.cwd,
89
- env: ctx.env,
90
- unset: code.unset,
91
- });
92
- ctx.stdout.write(`${report.trimEnd()}\n`);
107
+ const label = `profile ${JSON.stringify(code.profile ?? "(built-in)")}`;
108
+ const quota = resolveQuotaConfig(code, ctx.env);
109
+ if (quota.source === "none")
110
+ throw new Error(`Quota is disabled for ${label} (quota.source: none).`);
111
+ let report;
112
+ try {
113
+ report = await ctx.quotaReader(quota.source, { cwd: ctx.cwd, env: quota.env });
114
+ }
115
+ catch (error) {
116
+ throw new Error(`Quota source ${quota.source}, ${label}, selected native configuration: ${errorMessage(error)} ` +
117
+ `Check that ${quota.source} is installed and authenticated under this quota configuration.`);
118
+ }
119
+ ctx.stdout.write(`Profile: ${code.profile ?? "(built-in)"}; native source: ${quota.source}\n` +
120
+ "Limits belong to this native CLI's account; account pairing with the coding agent is not verified.\n" +
121
+ `${report.trimEnd()}\n`);
93
122
  return 0;
94
123
  }
95
124
  function resolveStatusTargetSessionFile(tree, target) {
@@ -161,6 +190,9 @@ function renderSessionStatus(cwd, sessionFilePath, frontmatter) {
161
190
  return [
162
191
  `sessionFile: ${displayPath(cwd, sessionFilePath)}`,
163
192
  `sessionId: ${frontmatter.sessionId ?? ""}`,
193
+ `agent: ${frontmatter.agent ?? ""}`,
194
+ `profile: ${frontmatter.profile ?? ""}`,
195
+ `model: ${frontmatter.model ?? ""}`,
164
196
  `status: ${frontmatter.status}`,
165
197
  `pid: ${frontmatter.pid ?? ""}`,
166
198
  `startedAt: ${frontmatter.startedAt}`,
@@ -180,7 +212,9 @@ export function parseCodeArgs(tokens, aligndev) {
180
212
  throw new Error(`Error: no command given. Run \`${aligndev} code --help\`.`);
181
213
  case "--help":
182
214
  case "-h":
183
- return { kind: "help" };
215
+ return parseBareCommand(tokens, "help");
216
+ case "--profile":
217
+ return parseBareCommand(tokens, "help");
184
218
  case "new":
185
219
  return parseNewCommand(rest);
186
220
  case "resume":
@@ -207,7 +241,7 @@ function parseStatusCommand(tokens) {
207
241
  allowPositionals: true,
208
242
  });
209
243
  if (values.help)
210
- return { kind: "help" };
244
+ return { kind: "help", status: true };
211
245
  const targetCount = positionals.length +
212
246
  Number(values.ticket !== undefined) +
213
247
  Number(values["no-ticket"]) +
@@ -235,10 +269,11 @@ function parseNewCommand(tokens) {
235
269
  strict: true,
236
270
  });
237
271
  if (values.help)
238
- return { kind: "help" };
272
+ return { kind: "help", ...(values.profile === undefined ? {} : { profile: values.profile }) };
239
273
  return {
240
274
  kind: "session",
241
275
  args: {
276
+ profile: values.profile,
242
277
  ticket: values.ticket,
243
278
  noTicket: values["no-ticket"],
244
279
  quiet: values.quiet,
@@ -259,7 +294,7 @@ function parseResumeCommand(tokens) {
259
294
  allowPositionals: true,
260
295
  });
261
296
  if (values.help)
262
- return { kind: "help" };
297
+ return { kind: "help", ...(values.profile === undefined ? {} : { profile: values.profile }) };
263
298
  if (positionals.length !== 1) {
264
299
  throw new Error("Error: `aligndev code resume` takes exactly one <sessionId>.");
265
300
  }
@@ -267,6 +302,7 @@ function parseResumeCommand(tokens) {
267
302
  kind: "session",
268
303
  args: {
269
304
  resume: positionals[0],
305
+ profile: values.profile,
270
306
  ticket: values.ticket,
271
307
  noTicket: false,
272
308
  quiet: values.quiet,
@@ -282,10 +318,16 @@ function parseResumeCommand(tokens) {
282
318
  function parseBareCommand(tokens, kind) {
283
319
  const { values } = parseArgs({
284
320
  args: tokens,
285
- options: { help: { type: "boolean", short: "h", default: false } },
321
+ options: {
322
+ help: { type: "boolean", short: "h", default: false },
323
+ profile: { type: "string" },
324
+ },
286
325
  strict: true,
287
326
  });
288
- return values.help ? { kind: "help" } : { kind };
327
+ return {
328
+ kind: values.help ? "help" : kind,
329
+ ...(values.profile === undefined ? {} : { profile: values.profile }),
330
+ };
289
331
  }
290
332
  export function validateSessionArgs(args, models) {
291
333
  const isNew = args.resume === undefined;
@@ -334,10 +376,9 @@ function isPathSafeTicket(ticket) {
334
376
  // agent's background task) — aligndev owns no backgrounding or callback of its own. The per-run session
335
377
  // file is the durable result handoff: on completion the frontmatter carries the session id and
336
378
  // status, and the `---- Result ----` block carries the outcome for a waking caller (or a human).
337
- async function runSession(args, code, ctx) {
379
+ async function runSession(args, code, ctx, report, records, previous) {
338
380
  const { cwd, env, stdout, stderr, forms, alignfirstCommand, modelResolver } = ctx;
339
381
  const { agent } = code;
340
- const report = readReport(ctx);
341
382
  const tree = sessionTreeOf(report, cwd);
342
383
  const plans = report.locations[".plans"];
343
384
  if (!plans.exists) {
@@ -345,13 +386,18 @@ async function runSession(args, code, ctx) {
345
386
  `Create it, or run \`${forms.alignfirst} plans setup <clone>\`.\n`);
346
387
  return 1;
347
388
  }
348
- const records = listSessionRecords(tree.sessionsDir);
349
- const resolvedTicket = args.noTicket ? undefined : resolveTicket(args, records);
350
- const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records);
389
+ const resolvedTicket = args.noTicket
390
+ ? undefined
391
+ : (args.ticket ??
392
+ (args.resume === undefined
393
+ ? inferTicketFromMessage(args.message ?? "")
394
+ : (previous?.frontmatter.ticket ?? undefined)));
395
+ const guardError = checkLaunchGuards(args, agent, tree.cwd, resolvedTicket, records, previous);
351
396
  if (guardError) {
352
397
  stderr.write(`${guardError}\n`);
353
398
  return 1;
354
399
  }
400
+ const model = selectModel(args, code, previous);
355
401
  const now = new Date();
356
402
  const ticket = args.noTicket ? reserveSideTicket(alignfirstCommand, cwd, env) : resolvedTicket;
357
403
  if (ticket !== undefined && !args.noTicket && args.resume === undefined) {
@@ -367,29 +413,29 @@ async function runSession(args, code, ctx) {
367
413
  const contextContent = args.resume === undefined && companionInUse(report, CONTEXT_COMPANION_ITEMS)
368
414
  ? loadContext(alignfirstCommand, cwd, env)
369
415
  : undefined;
370
- const model = selectModel(args, code, records);
371
- const sessionFilePath = resolveSessionFilePath(tree.sessionsDir, ticket, now);
372
- writeInitialSessionFile(sessionFilePath, buildFrontmatter({ args, agent, model, now, realCwd: tree.cwd, ticket }));
416
+ const sessionFilePath = createSessionFile(tree.sessionsDir, ticket, now, buildFrontmatter({ args, agent, profile: code.profile, model, now, realCwd: tree.cwd, ticket }));
373
417
  stdout.write(`Session file: ${displayPath(tree.cwd, sessionFilePath)}\n\n`);
374
418
  let executableModel;
375
419
  try {
376
- executableModel = await modelResolver(agent, model, {
420
+ executableModel = await modelResolver(agent, expandModelAlias(model, code.modelAliases), {
377
421
  cwd,
378
- env: buildAgentEnv(env, code.unset),
422
+ env: code.childEnv,
379
423
  });
380
424
  }
381
- catch (error) {
382
- const message = errorMessage(error);
425
+ catch {
426
+ const message = `Could not resolve the ${agent} model; check --model, profile.models/modelAliases and the agent installation. ` +
427
+ `${nativeContext(code)}.` +
428
+ (agent === "codex"
429
+ ? " For Codex aliases, update the Codex CLI or select an explicit full model slug."
430
+ : "");
383
431
  applyCompletion(sessionFilePath, {
384
432
  status: "failed",
385
433
  endedAt: new Date().toISOString(),
386
434
  exitReason: "error",
387
- sessionId: null,
435
+ sessionId: args.resume ?? null,
388
436
  result: message,
389
437
  });
390
- writeFailureDiagnostic(ctx, sessionFilePath, args.quiet === true
391
- ? `Could not resolve the ${agent} model; check --model, code.models and the agent installation.`
392
- : message);
438
+ writeFailureDiagnostic(ctx, sessionFilePath, message);
393
439
  return 1;
394
440
  }
395
441
  const runConfig = buildRunConfig({
@@ -399,7 +445,6 @@ async function runSession(args, code, ctx) {
399
445
  ticket,
400
446
  cwd,
401
447
  sessionFilePath,
402
- env,
403
448
  executableModel,
404
449
  catchupContent,
405
450
  contextContent,
@@ -411,15 +456,20 @@ async function runSession(args, code, ctx) {
411
456
  stdout.write(`\nSession ID: ${result.sessionId}\n`);
412
457
  }
413
458
  if (result.authRequired) {
414
- writeFailureDiagnostic(ctx, sessionFilePath, "coding agent not authenticated — an administrator must re-login on the host " +
415
- `(${authenticationInstruction(agent)}).`);
459
+ writeFailureDiagnostic(ctx, sessionFilePath, `${nativeContext(code)} not authenticated — an administrator must re-login ` +
460
+ "with the same effective environment as the child (apply profile unset/env/configDir, " +
461
+ "including HOME, PATH and credential routing), from the same working directory. " +
462
+ `Then use ${authenticationInstruction(agent)}. A bare login in another shell may use a different account.`);
416
463
  return EXIT_AUTH_REQUIRED;
417
464
  }
418
465
  if (result.status === "succeeded")
419
466
  return 0;
420
- writeFailureDiagnostic(ctx, sessionFilePath, failureDiagnostic(agent, result.result));
467
+ writeFailureDiagnostic(ctx, sessionFilePath, `${nativeContext(code)}: ${failureDiagnostic(agent, result.result)}${args.resume === undefined ? "" : " Check that the native conversation exists in this configuration; select the correct --profile or start a new session. No account fallback was attempted."}`);
421
468
  return 1;
422
469
  }
470
+ function nativeContext(code) {
471
+ return `${code.agent} profile ${JSON.stringify(code.profile ?? "(built-in)")} (${describeNativeStorage(code)})`;
472
+ }
423
473
  function authenticationInstruction(agent) {
424
474
  switch (agent) {
425
475
  case "claude":
@@ -444,7 +494,7 @@ function failureDiagnostic(agent, result) {
444
494
  }
445
495
  // Fail-fast launch guards, run against the (healed) session records before anything is written.
446
496
  // Returns the error to print, or `undefined` when the launch may proceed.
447
- export function checkLaunchGuards(args, agent, realCwd, ticket, records) {
497
+ export function checkLaunchGuards(args, agent, realCwd, ticket, records, previous) {
448
498
  if (args.resume !== undefined) {
449
499
  // A resumed run writes a new session file carrying the same sessionId as the original, so one
450
500
  // id can match several records — a running status on any of them blocks.
@@ -456,7 +506,7 @@ export function checkLaunchGuards(args, agent, realCwd, ticket, records) {
456
506
  return (`Error: session ${args.resume} is still running (pid ${running.frontmatter.pid}); ` +
457
507
  "wait for it to finish or kill it.");
458
508
  }
459
- const latest = latestRecord(matches);
509
+ const latest = previous ?? latestRecord(matches);
460
510
  if (latest.frontmatter.agent === null) {
461
511
  return (`Error: session ${args.resume} predates agent-aware sessions and cannot be resumed; ` +
462
512
  "start a new session.");
@@ -529,7 +579,7 @@ export function resolveTicket(args, records) {
529
579
  // Latest record of the resumed session that carries a ticket — the resumed run keeps writing
530
580
  // under the same ticket directory, and its frontmatter keeps the ticket for later resumes.
531
581
  function inheritTicketFromResume(resume, records) {
532
- const ticketed = records.filter((r) => r.frontmatter.sessionId === resume && r.frontmatter.ticket !== null);
582
+ const ticketed = records.filter((r) => r.frontmatter.sessionId === resume);
533
583
  const latest = ticketed.sort((a, b) => b.frontmatter.startedAt.localeCompare(a.frontmatter.startedAt))[0];
534
584
  return latest?.frontmatter.ticket ?? undefined;
535
585
  }
@@ -546,26 +596,30 @@ function inferTicketFromMessage(message) {
546
596
  return;
547
597
  return [...candidates][0];
548
598
  }
549
- // `--model` wins. Otherwise a new session takes `code.defaultModel`, and a resume keeps the model
550
- // of its latest run, unchecked against the current allowlist. `undefined` leaves the agent's
551
- // default.
552
- function selectModel(args, code, records) {
599
+ // A null recorded model retains the native conversation's model; profile defaults are new-only.
600
+ function selectModel(args, code, previous) {
553
601
  if (args.model !== undefined)
554
602
  return args.model;
555
603
  if (args.resume === undefined)
556
604
  return code.defaultModel;
557
- const runs = records.filter((r) => r.frontmatter.sessionId === args.resume);
558
- return latestRecord(runs).frontmatter.model ?? undefined;
605
+ const model = previous?.frontmatter.model ?? undefined;
606
+ const models = resolveModels(code.agent, code.models, code.modelAliases);
607
+ if (model !== undefined &&
608
+ (model.trim() === "" || (models !== undefined && !models.includes(model)))) {
609
+ throw new Error("Error: retained session model is not accepted by the selected profile; supply --model with an accepted replacement.");
610
+ }
611
+ return model;
559
612
  }
560
613
  function buildFrontmatter(input) {
561
614
  const { args, now, ticket } = input;
562
615
  return {
563
616
  status: "running",
564
617
  agent: input.agent,
618
+ profile: input.profile,
565
619
  protocol: args.protocol ?? null,
566
620
  ticket: ticket ?? null,
567
621
  model: input.model ?? null,
568
- sessionId: null,
622
+ sessionId: args.resume ?? null,
569
623
  command: formatCommand(args),
570
624
  meta: args.meta ?? null,
571
625
  pid: process.pid,
@@ -595,6 +649,8 @@ function formatCommand(args) {
595
649
  parts.push("--catchup");
596
650
  if (args.model !== undefined)
597
651
  parts.push("--model", args.model);
652
+ if (args.profile !== undefined)
653
+ parts.push("--profile", JSON.stringify(args.profile));
598
654
  if (args.messageFile !== undefined) {
599
655
  parts.push("--message-file", JSON.stringify(args.messageFile));
600
656
  }
@@ -620,6 +676,7 @@ export function buildRunConfig(input) {
620
676
  alignfirst: input.alignfirst,
621
677
  }),
622
678
  sessionFilePath: input.sessionFilePath,
679
+ nativeContext: nativeContext(code),
623
680
  cwd: input.cwd,
624
681
  resume: args.resume,
625
682
  quiet: args.quiet,
@@ -628,8 +685,7 @@ export function buildRunConfig(input) {
628
685
  additionalDirectories: code.agent !== "pi" && !code.skipPermissions && report.companion !== null
629
686
  ? [report.companion.dir]
630
687
  : [],
631
- unset: code.unset,
632
- env: input.env,
688
+ env: code.childEnv,
633
689
  };
634
690
  }
635
691
  // A registered companion becomes writable before its directory exists: create it for the agent.
@@ -639,10 +695,11 @@ function createMissingCompanion(report) {
639
695
  return;
640
696
  mkdirSync(companion.dir, { recursive: true });
641
697
  }
642
- function renderHelp(agent, models, forms) {
698
+ function renderHelp(code, models, forms) {
699
+ const { agent, profile, defaultModel } = code;
643
700
  const { aligndev, alignfirst } = forms;
644
701
  const permissionMode = agent === "pi"
645
- ? "Ordinary OS permissions; code.skipPermissions has no effect. Saved project trust is honored."
702
+ ? "Ordinary OS permissions; profile.skipPermissions has no effect. Saved project trust is honored."
646
703
  : agent === "claude"
647
704
  ? "--permission-mode auto (dangerous opt-out: --dangerously-skip-permissions)"
648
705
  : "--sandbox workspace-write (dangerous opt-out: --dangerously-bypass-approvals-and-sandbox)";
@@ -671,7 +728,7 @@ Commands:
671
728
  run of the ticket, of no-ticket work, or of the --meta key. Includes
672
729
  contextTokens, the context-window occupancy the run ended on, and
673
730
  contextCompacted. Does not start an agent.
674
- quota Show account limits and reset times (unsupported for pi).
731
+ quota Show native account limits via the profile's quota source.
675
732
 
676
733
  Options (status):
677
734
  --ticket <id> Newest run of that ticket.
@@ -693,7 +750,7 @@ Options (new, resume):
693
750
  -m, --message "..." Message to send. Required for spec/aad, or without protocol/catchup.
694
751
  --message-file <path> Read the message from a UTF-8 file, or stdin with -. Exclusive with -m.
695
752
  --model <model> ${modelPolicy}. A new session defaults to
696
- code.defaultModel, else to the coding agent's default. A resume keeps the
753
+ profile.defaultModel, else to the coding agent's default. A resume keeps the
697
754
  session's model.
698
755
  --meta "..." Opaque handoff string, stored verbatim in the session file frontmatter
699
756
  (\`meta:\`). aligndev never interprets it; a later reader of the session file
@@ -702,12 +759,28 @@ Options (new, resume):
702
759
  ${requires}
703
760
 
704
761
  Config (~/.alignfirst/aligndev.settings.json):
705
- code.agent Coding agent: claude, codex or pi (selected: ${agent}). Defaults to the coding
706
- agent that runs aligndev.
707
- code.defaultModel Default model of a new session, one of the models accepted by --model.
708
- code.models List replacing the models accepted by --model.
709
- code.skipPermissions true to run the coding agent with permission prompts disabled.
710
- code.unset Env vars to strip from the coding agent child.
762
+ Unknown/obsolete keys are ignored with value-free warnings on stderr. Recognized invalid values
763
+ and duplicate defaults still fail. Settings are never rewritten. Retired direct launch keys and
764
+ code.defaultProfiles have no effect; convert them manually to profiles and profile.default flags.
765
+ code.profile Global named profile. Effective profile: ${profile ?? "(built-in)"} (selected: ${agent}).
766
+ code.profiles Complete named profiles: agent, default, configDir, env, unset,
767
+ defaultModel, models, modelAliases, skipPermissions, quota. No inheritance.
768
+ profile.default Optional boolean preference for that agent; at most one true per agent.
769
+ A sole matching profile is inferred without a flag. No matching profile
770
+ uses detected built-ins. Without a parent, only a sole total profile is
771
+ inferred; multiple parents require a named choice.
772
+ --profile <name> Override for new, resume, quota and help (also guide code).
773
+ Precedence: explicit > project > recorded named resume > global > automatic.
774
+ Historical null/missing-profile resumes keep detected built-ins unless
775
+ explicit/project/global selection replaces them; no automatic inference.
776
+ Model default ${defaultModel ?? "native default"} (new only). Resume retains and validates its model.
777
+ One configured alias expands before native model handling.
778
+
779
+ Native configuration: ${describeNativeStorage(code)}.
780
+ Login must use the same effective environment as the child: apply profile unset/env/configDir,
781
+ including HOME, PATH and credential routing, from the same working directory. Then use
782
+ ${authenticationInstruction(agent)}. A bare login in another shell may use a different account.
783
+ Environment values are omitted.
711
784
 
712
785
  Selected-agent permissions: ${permissionMode}
713
786
  The project's companion directory is prepared before launch; pi uses ordinary OS access.
@@ -1,7 +1,7 @@
1
- import type { AgentAdapter, AgentProtocolState, RunConfig } from "./run-agent.js";
1
+ import { type AgentAdapter, type AgentProtocolState, type RunConfig } from "./run-agent.js";
2
2
  export declare function createCodexAdapter(): AgentAdapter;
3
3
  export declare function buildCodexArgs(config: RunConfig): string[];
4
- export declare function createCodexState(): AgentProtocolState;
4
+ export declare function createCodexState(config?: RunConfig): AgentProtocolState;
5
5
  export declare function interpretCodexLine(line: string, state: AgentProtocolState): string | undefined;
6
6
  export declare function assessCodexState(state: AgentProtocolState): {
7
7
  succeeded: boolean;
@@ -1,4 +1,5 @@
1
1
  import { readCodexContext } from "./codex-rollout.js";
2
+ import { captureNativeSession, } from "./run-agent.js";
2
3
  export function createCodexAdapter() {
3
4
  return {
4
5
  executable: "codex",
@@ -30,8 +31,11 @@ export function buildCodexArgs(config) {
30
31
  args.push("-");
31
32
  return args;
32
33
  }
33
- export function createCodexState() {
34
+ export function createCodexState(config) {
34
35
  return {
36
+ expectedSessionId: config?.resume,
37
+ earlierResults: [],
38
+ nativeEnv: config?.env ?? {},
35
39
  protocolComplete: false,
36
40
  protocolFailed: false,
37
41
  authEvidence: false,
@@ -48,6 +52,7 @@ export function interpretCodexLine(line, state) {
48
52
  return captureCompletedItem(event, state);
49
53
  case "turn.completed":
50
54
  state.protocolComplete = true;
55
+ state.resultComplete = !state.protocolFailed;
51
56
  captureStreamTotal(event, state);
52
57
  return;
53
58
  case "turn.failed":
@@ -60,13 +65,22 @@ export function interpretCodexLine(line, state) {
60
65
  }
61
66
  }
62
67
  export function assessCodexState(state) {
63
- const succeeded = state.protocolComplete && !state.protocolFailed && state.result !== undefined;
64
- const context = readCodexContext(state.sessionId, state.streamTotalTokens);
68
+ const succeeded = state.sessionId !== undefined &&
69
+ state.identityFailure === undefined &&
70
+ state.protocolComplete &&
71
+ !state.protocolFailed &&
72
+ state.result !== undefined;
73
+ const context = readCodexContext(state.sessionId, state.streamTotalTokens, state.nativeEnv);
65
74
  return {
66
75
  succeeded,
67
76
  sessionId: state.sessionId,
68
77
  result: state.result,
69
- error: succeeded ? undefined : state.failure,
78
+ error: state.identityFailure ??
79
+ (succeeded ? undefined : state.failure) ??
80
+ (state.sessionId === undefined &&
81
+ (state.protocolComplete || state.expectedSessionId !== undefined)
82
+ ? "Codex reported no native session identity in the selected native configuration."
83
+ : undefined),
70
84
  authEvidence: state.authEvidence,
71
85
  contextTokens: context.contextTokens ?? undefined,
72
86
  contextCompacted: context.compacted,
@@ -94,8 +108,7 @@ function parseCodexLine(line) {
94
108
  }
95
109
  function captureThread(event, state) {
96
110
  const id = asString(event.thread_id);
97
- if (id !== undefined && id !== "")
98
- state.sessionId = id;
111
+ captureNativeSession(state, id, "Codex");
99
112
  return `[init] session ${id ?? "?"}`;
100
113
  }
101
114
  function captureCompletedItem(event, state) {
@@ -104,8 +117,10 @@ function captureCompletedItem(event, state) {
104
117
  return;
105
118
  if (item.type === "agent_message") {
106
119
  const text = asString(item.text);
107
- if (text !== undefined && text !== "")
120
+ if (text !== undefined && text !== "") {
108
121
  state.result = text;
122
+ state.resultComplete = false;
123
+ }
109
124
  return text;
110
125
  }
111
126
  if (item.type !== "error")
@@ -152,7 +167,8 @@ function missingCodexOutcome(state) {
152
167
  return "Codex turn completed without a final agent message.";
153
168
  }
154
169
  function codexAuthenticationMessage(detail) {
155
- const base = "Coding agent not authenticated: an administrator must run `codex login` on the host before " +
170
+ const base = "Coding agent not authenticated: an administrator must run `codex login` with the same effective environment " +
171
+ "and cwd as the child (apply profile unset/env/configDir, including HOME, PATH and credential routing) before " +
156
172
  "`aligndev code` can run again.";
157
173
  const reason = detail?.trim();
158
174
  return reason === undefined || reason === "" ? base : `${base}\n\n${reason}`;
@@ -15,4 +15,4 @@ export interface CodexContextReading {
15
15
  * equal it, which pins the file to this run and turns any change in the Codex format into a
16
16
  * reported error rather than a plausible wrong number.
17
17
  */
18
- export declare function readCodexContext(threadId: string | undefined, streamTotal: number | undefined): CodexContextReading;
18
+ export declare function readCodexContext(threadId: string | undefined, streamTotal: number | undefined, env?: NodeJS.ProcessEnv): CodexContextReading;
@@ -1,5 +1,4 @@
1
1
  import { readdirSync, readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
2
  import { basename, join } from "node:path";
4
3
  // Codex writes one rollout per thread under `$CODEX_HOME/sessions/<year>/<month>/<day>/`. The plain
5
4
  // file is `rollout-<timestamp>-<threadId>.jsonl`; a compacted thread appends `_<uuid>`.
@@ -18,12 +17,17 @@ const ROLLOUT_SUFFIX = ".jsonl";
18
17
  * equal it, which pins the file to this run and turns any change in the Codex format into a
19
18
  * reported error rather than a plausible wrong number.
20
19
  */
21
- export function readCodexContext(threadId, streamTotal) {
20
+ export function readCodexContext(threadId, streamTotal, env = {}) {
22
21
  if (threadId === undefined || threadId === "")
23
22
  return failed("Codex reported no thread id.");
24
23
  if (streamTotal === undefined)
25
24
  return failed("Codex reported no turn.completed usage.");
26
- const path = findRolloutPath(threadId);
25
+ const home = env.HOME ?? env.USERPROFILE;
26
+ const nativeHome = env.CODEX_HOME ?? (home === undefined ? undefined : join(home, ".codex"));
27
+ if (nativeHome === undefined) {
28
+ return failed("Codex native home is unavailable in the child environment.");
29
+ }
30
+ const path = findRolloutPath(threadId, nativeHome);
27
31
  if (path === undefined)
28
32
  return failed(`No Codex rollout found for thread ${threadId}.`);
29
33
  const records = readUsageRecords(path);
@@ -43,8 +47,8 @@ export function readCodexContext(threadId, streamTotal) {
43
47
  function failed(error) {
44
48
  return { contextTokens: null, compacted: false, error };
45
49
  }
46
- function findRolloutPath(threadId) {
47
- const root = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), SESSIONS_DIR);
50
+ function findRolloutPath(threadId, nativeHome) {
51
+ const root = join(nativeHome, SESSIONS_DIR);
48
52
  let entries;
49
53
  try {
50
54
  entries = readdirSync(root, { recursive: true, encoding: "utf8" });
@@ -12,7 +12,7 @@ export function createAgentAdapter(agent) {
12
12
  return createPiAdapter();
13
13
  }
14
14
  }
15
- // Host markers select the child only when code.agent is absent.
15
+ // Host detection is reached only when no named profile selects a child.
16
16
  export function detectCodingAgents(env) {
17
17
  const detected = [];
18
18
  if (env.CLAUDECODE === "1")
@@ -1,7 +1,7 @@
1
1
  import type { CodingAgent } from "./coding-agent.js";
2
2
  export declare const CLAUDE_DEFAULT_MODELS: readonly ["fable", "opus", "sonnet", "haiku"];
3
3
  export declare const CODEX_DEFAULT_MODELS: readonly ["astra", "sol", "terra", "luna"];
4
- export declare function resolveModels(agent: CodingAgent, override: readonly string[] | undefined): readonly string[] | undefined;
4
+ export declare function resolveModels(agent: CodingAgent, override: readonly string[] | undefined, aliases?: Readonly<Record<string, string>>): readonly string[] | undefined;
5
5
  export interface ModelDiscoveryContext {
6
6
  cwd: string;
7
7
  env: NodeJS.ProcessEnv;
@@ -9,6 +9,6 @@ export interface ModelDiscoveryContext {
9
9
  export type ModelCatalogRunner = (context: ModelDiscoveryContext) => Promise<string>;
10
10
  export type ExecutableModelResolver = (agent: CodingAgent, selectedModel: string | undefined, context: ModelDiscoveryContext) => Promise<string | undefined>;
11
11
  export declare function createExecutableModelResolver(runCatalog?: ModelCatalogRunner): ExecutableModelResolver;
12
- export declare const resolveExecutableModel: ExecutableModelResolver;
12
+ export declare function expandModelAlias(model: string | undefined, aliases?: Readonly<Record<string, string>>): string | undefined;
13
13
  export declare function parseBundledModelSlugs(output: string): readonly string[];
14
14
  export declare function selectNewestCodexModel(slugs: readonly string[], alias: string): string | undefined;