@ainecto/cli 0.14.0-next.4 → 0.14.0-next.6

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.
@@ -25,9 +25,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  mod
26
26
  ));
27
27
 
28
- // ../ainecto-cli/node_modules/@xterm/addon-serialize/lib/addon-serialize.js
28
+ // node_modules/@xterm/addon-serialize/lib/addon-serialize.js
29
29
  var require_addon_serialize = __commonJS({
30
- "../ainecto-cli/node_modules/@xterm/addon-serialize/lib/addon-serialize.js"(exports, module) {
30
+ "node_modules/@xterm/addon-serialize/lib/addon-serialize.js"(exports, module) {
31
31
  "use strict";
32
32
  !(function(t, e) {
33
33
  "object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.SerializeAddon = e() : t.SerializeAddon = e();
@@ -391,9 +391,9 @@ var require_addon_serialize = __commonJS({
391
391
  }
392
392
  });
393
393
 
394
- // ../ainecto-cli/node_modules/@xterm/headless/lib-headless/xterm-headless.js
394
+ // node_modules/@xterm/headless/lib-headless/xterm-headless.js
395
395
  var require_xterm_headless = __commonJS({
396
- "../ainecto-cli/node_modules/@xterm/headless/lib-headless/xterm-headless.js"(exports) {
396
+ "node_modules/@xterm/headless/lib-headless/xterm-headless.js"(exports) {
397
397
  "use strict";
398
398
  (() => {
399
399
  "use strict";
@@ -5678,7 +5678,7 @@ function legacyRoleInput(flag, envVars = process.env) {
5678
5678
 
5679
5679
  // src/core/version.ts
5680
5680
  var UNBUNDLED_VERSION = "dev";
5681
- var CLI_VERSION = true ? "0.14.0-next.4" : UNBUNDLED_VERSION;
5681
+ var CLI_VERSION = true ? "0.14.0-next.6" : UNBUNDLED_VERSION;
5682
5682
  var PACKAGE_NAME = "@ainecto/mcp";
5683
5683
  var CLI_USER_AGENT = `${PACKAGE_NAME} ${CLI_VERSION}`;
5684
5684
  function bridgePackageSpec(version = CLI_VERSION) {
@@ -8613,12 +8613,12 @@ function readRecord(content) {
8613
8613
  }
8614
8614
  };
8615
8615
  }
8616
- function serializeRecord(record) {
8616
+ function serializeRecord(record2) {
8617
8617
  return `${JSON.stringify({
8618
8618
  kind: RECORD_KIND,
8619
8619
  version: RECORD_VERSION,
8620
- files: record.files,
8621
- createdDirectories: record.createdDirectories
8620
+ files: record2.files,
8621
+ createdDirectories: record2.createdDirectories
8622
8622
  }, null, 2)}
8623
8623
  `;
8624
8624
  }
@@ -8875,20 +8875,20 @@ function planInit(input) {
8875
8875
  const carriedRecord = previous.state === "valid" ? previous.record : emptyRecord();
8876
8876
  const writes = [];
8877
8877
  const notes = [];
8878
- const record = {
8878
+ const record2 = {
8879
8879
  version: carriedRecord.version,
8880
8880
  files: { ...carriedRecord.files },
8881
8881
  createdDirectories: [...carriedRecord.createdDirectories]
8882
8882
  };
8883
8883
  const priorOf = (path, current) => {
8884
- const prior = record.files[path];
8884
+ const prior = record2.files[path];
8885
8885
  if (prior === void 0) {
8886
8886
  return void 0;
8887
8887
  }
8888
8888
  if (sameOwned(prior.written, current) || sameOwned(prior.original, current)) {
8889
8889
  return prior;
8890
8890
  }
8891
- delete record.files[path];
8891
+ delete record2.files[path];
8892
8892
  notes.push(`${path}: it changed outside ainecto, so the older backup was dropped and this is the new baseline.`);
8893
8893
  return void 0;
8894
8894
  };
@@ -8897,7 +8897,7 @@ function planInit(input) {
8897
8897
  if (prior === void 0 && original.at !== "absent") {
8898
8898
  notes.push(`${path} already existed; its original was saved and --undo will restore it.`);
8899
8899
  }
8900
- record.files[path] = {
8900
+ record2.files[path] = {
8901
8901
  scope: "whole",
8902
8902
  createdByUs: prior?.createdByUs ?? existing === void 0,
8903
8903
  original,
@@ -8940,7 +8940,7 @@ function planInit(input) {
8940
8940
  if (prior === void 0 && original.at !== "absent") {
8941
8941
  notes.push(`${target.path}: your existing "${SERVER_NAME}" entry was saved and will be restored by --undo`);
8942
8942
  }
8943
- record.files[target.path] = {
8943
+ record2.files[target.path] = {
8944
8944
  scope: "entry",
8945
8945
  createdByUs: prior?.createdByUs ?? existing === void 0,
8946
8946
  original,
@@ -8985,7 +8985,7 @@ ${codexContent}`);
8985
8985
  continue;
8986
8986
  }
8987
8987
  const blockNow = existing === void 0 ? void 0 : existingMarkerBlock(existing);
8988
- const carried = record.files[target.path];
8988
+ const carried = record2.files[target.path];
8989
8989
  let content;
8990
8990
  try {
8991
8991
  content = upsertMarkerBlock(existing, note);
@@ -9007,7 +9007,7 @@ ${codexContent}`);
9007
9007
  if (prior === void 0 && original.at !== "absent") {
9008
9008
  notes.push(`${target.path}: an existing ainecto block was saved and will be restored by --undo`);
9009
9009
  }
9010
- record.files[target.path] = {
9010
+ record2.files[target.path] = {
9011
9011
  scope: "block",
9012
9012
  createdByUs: prior?.createdByUs ?? existing === void 0,
9013
9013
  original,
@@ -9033,7 +9033,7 @@ ${codexContent}`);
9033
9033
  if (existingConfig !== void 0 && theirConfig === void 0) {
9034
9034
  notes.push(`${HARNESS_CONFIG_PATH} is not a JSON object \u2014 left untouched.`);
9035
9035
  } else {
9036
- const priorConfig = record.files[HARNESS_CONFIG_PATH];
9036
+ const priorConfig = record2.files[HARNESS_CONFIG_PATH];
9037
9037
  const originalFields = {};
9038
9038
  for (const field of OUR_CONFIG_FIELDS) {
9039
9039
  const presentNow = theirConfig !== void 0 && hasField(theirConfig, field);
@@ -9065,7 +9065,7 @@ ${codexContent}`);
9065
9065
  }
9066
9066
  }
9067
9067
  const mergedConfig = serialize({ ...retained, ...ourFields });
9068
- record.files[HARNESS_CONFIG_PATH] = {
9068
+ record2.files[HARNESS_CONFIG_PATH] = {
9069
9069
  scope: "fields",
9070
9070
  createdByUs: priorConfig?.createdByUs ?? existingConfig === void 0,
9071
9071
  original: ABSENT,
@@ -9083,7 +9083,7 @@ ${codexContent}`);
9083
9083
  }
9084
9084
  }
9085
9085
  const existingRecord = input.files.get(HARNESS_RECORD_PATH);
9086
- const recordContent = serializeRecord(record);
9086
+ const recordContent = serializeRecord(record2);
9087
9087
  if (recordContent !== existingRecord) {
9088
9088
  writes.push({
9089
9089
  path: HARNESS_RECORD_PATH,
@@ -9091,7 +9091,7 @@ ${codexContent}`);
9091
9091
  existed: existingRecord !== void 0
9092
9092
  });
9093
9093
  }
9094
- return { writes, deletes: [], notes, record };
9094
+ return { writes, deletes: [], notes, record: record2 };
9095
9095
  }
9096
9096
  function planUndo(input) {
9097
9097
  const state = input.record ?? readRecord(input.files.get(HARNESS_RECORD_PATH));
@@ -9113,9 +9113,9 @@ function planUndo(input) {
9113
9113
  tail();
9114
9114
  return { writes, deletes, notes };
9115
9115
  }
9116
- const record = state.record;
9117
- const remaining = { ...record.files };
9118
- for (const [path, contract] of Object.entries(record.files)) {
9116
+ const record2 = state.record;
9117
+ const remaining = { ...record2.files };
9118
+ for (const [path, contract] of Object.entries(record2.files)) {
9119
9119
  const outcome = undoOne(path, contract, input.files.get(path));
9120
9120
  if (outcome.kind !== "unresolved" && outcome.kind !== "keep" && outcome.note !== void 0) {
9121
9121
  notes.push(outcome.note);
@@ -9135,7 +9135,7 @@ function planUndo(input) {
9135
9135
  tail();
9136
9136
  if (input.files.get(HARNESS_RECORD_PATH) !== void 0) {
9137
9137
  if (Object.keys(remaining).length > 0) {
9138
- const reduced = { ...record, files: remaining };
9138
+ const reduced = { ...record2, files: remaining };
9139
9139
  writes.push({ path: HARNESS_RECORD_PATH, content: serializeRecord(reduced), existed: true });
9140
9140
  notes.push(
9141
9141
  `${HARNESS_RECORD_PATH}: kept, with the finished items removed \u2014 it still holds the backups --undo needs. Run --undo again once the items above are resolved.`
@@ -9144,7 +9144,7 @@ function planUndo(input) {
9144
9144
  deletes.push(HARNESS_RECORD_PATH);
9145
9145
  }
9146
9146
  }
9147
- const removableDirectories = parentsOf(deletes).filter((directory) => record.createdDirectories.includes(directory));
9147
+ const removableDirectories = parentsOf(deletes).filter((directory) => record2.createdDirectories.includes(directory));
9148
9148
  return { writes, deletes, notes, removableDirectories };
9149
9149
  }
9150
9150
  function unexplainedMarkers(existing, contract) {
@@ -9561,9 +9561,9 @@ async function applyPlan(root, plan, dryRun, snapshot, recordFirst = true) {
9561
9561
  }
9562
9562
  const applied = [];
9563
9563
  try {
9564
- const isRecord13 = (path) => !recordFirst && path === HARNESS_RECORD_PATH;
9565
- const recordWrites = plan.writes.filter((write) => isRecord13(write.path));
9566
- const recordDeletes = plan.deletes.filter((path) => isRecord13(path));
9564
+ const isRecord14 = (path) => !recordFirst && path === HARNESS_RECORD_PATH;
9565
+ const recordWrites = plan.writes.filter((write) => isRecord14(write.path));
9566
+ const recordDeletes = plan.deletes.filter((path) => isRecord14(path));
9567
9567
  const createdDirectories = [...plan.record?.createdDirectories ?? []];
9568
9568
  const rememberDirectories = (directories) => {
9569
9569
  for (const directory of directories) {
@@ -9605,8 +9605,8 @@ async function applyPlan(root, plan, dryRun, snapshot, recordFirst = true) {
9605
9605
  };
9606
9606
  try {
9607
9607
  await apply(
9608
- orderedWrites(plan.writes.filter((write) => !isRecord13(write.path)), recordFirst),
9609
- plan.deletes.filter((path) => !isRecord13(path))
9608
+ orderedWrites(plan.writes.filter((write) => !isRecord14(write.path)), recordFirst),
9609
+ plan.deletes.filter((path) => !isRecord14(path))
9610
9610
  );
9611
9611
  await recordDirectoriesOrExplain(false);
9612
9612
  await apply(recordWrites, recordDeletes);
@@ -9626,9 +9626,9 @@ Already applied before this failure: ${applied.join(", ") || "(nothing)"}`
9626
9626
  }
9627
9627
  }
9628
9628
  function orderedWrites(writes, recordFirst) {
9629
- const record = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9629
+ const record2 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9630
9630
  const rest = writes.filter((write) => write.path !== HARNESS_RECORD_PATH);
9631
- return recordFirst ? [...record, ...rest] : [...rest, ...record];
9631
+ return recordFirst ? [...record2, ...rest] : [...rest, ...record2];
9632
9632
  }
9633
9633
  async function assertUnchangedSinceSnapshot(root, relativePath, snapshot) {
9634
9634
  if (!snapshot.has(relativePath)) {
@@ -10605,73 +10605,73 @@ function parseClientMessage(line) {
10605
10605
  } catch {
10606
10606
  throw new TermProtocolError("Not a JSON line.");
10607
10607
  }
10608
- const record = asRecord(value);
10609
- const op = stringField(record, "op");
10608
+ const record2 = asRecord(value);
10609
+ const op = stringField(record2, "op");
10610
10610
  if (op === "in") {
10611
- return { op, d: stringField(record, "d") };
10611
+ return { op, d: stringField(record2, "d") };
10612
10612
  }
10613
10613
  if (op === "resize") {
10614
- return { op, cols: sizeField(record, "cols"), rows: sizeField(record, "rows") };
10614
+ return { op, cols: sizeField(record2, "cols"), rows: sizeField(record2, "rows") };
10615
10615
  }
10616
- const id = stringField(record, "id");
10616
+ const id = stringField(record2, "id");
10617
10617
  switch (op) {
10618
10618
  case "new":
10619
10619
  return {
10620
10620
  id,
10621
10621
  op,
10622
- name: stringField(record, "name"),
10623
- cwd: stringField(record, "cwd"),
10624
- command: record.command === null ? null : stringArrayField(record, "command"),
10625
- env: stringMapField(record, "env"),
10626
- cols: optionalSize(record, "cols"),
10627
- rows: optionalSize(record, "rows")
10622
+ name: stringField(record2, "name"),
10623
+ cwd: stringField(record2, "cwd"),
10624
+ command: record2.command === null ? null : stringArrayField(record2, "command"),
10625
+ env: stringMapField(record2, "env"),
10626
+ cols: optionalSize(record2, "cols"),
10627
+ rows: optionalSize(record2, "rows")
10628
10628
  };
10629
10629
  case "ls":
10630
10630
  case "kill-server":
10631
10631
  case "detach":
10632
10632
  return { id, op };
10633
10633
  case "send":
10634
- return { id, op, name: stringField(record, "name"), text: stringField(record, "text"), paste: record.paste === true };
10634
+ return { id, op, name: stringField(record2, "name"), text: stringField(record2, "text"), paste: record2.paste === true };
10635
10635
  case "key":
10636
- return { id, op, name: stringField(record, "name"), key: stringField(record, "key") };
10636
+ return { id, op, name: stringField(record2, "name"), key: stringField(record2, "key") };
10637
10637
  case "read":
10638
- return { id, op, name: stringField(record, "name"), scrollback: record.scrollback === true, lines: optionalSize(record, "lines") };
10638
+ return { id, op, name: stringField(record2, "name"), scrollback: record2.scrollback === true, lines: optionalSize(record2, "lines") };
10639
10639
  case "kill":
10640
10640
  case "watch":
10641
- return { id, op, name: stringField(record, "name") };
10641
+ return { id, op, name: stringField(record2, "name") };
10642
10642
  case "restore":
10643
- return { id, op, env: stringMapField(record, "env") };
10643
+ return { id, op, env: stringMapField(record2, "env") };
10644
10644
  case "attach":
10645
- return { id, op, name: stringField(record, "name"), cols: sizeField(record, "cols"), rows: sizeField(record, "rows") };
10645
+ return { id, op, name: stringField(record2, "name"), cols: sizeField(record2, "cols"), rows: sizeField(record2, "rows") };
10646
10646
  default:
10647
10647
  throw new TermProtocolError(`Unknown op "${op}".`);
10648
10648
  }
10649
10649
  }
10650
10650
  function parseDaemonMessage(line) {
10651
- const record = asRecord(JSON.parse(line));
10652
- if (typeof record.event === "string") {
10653
- switch (record.event) {
10651
+ const record2 = asRecord(JSON.parse(line));
10652
+ if (typeof record2.event === "string") {
10653
+ switch (record2.event) {
10654
10654
  case "screen":
10655
10655
  case "out":
10656
- return { event: record.event, d: stringField(record, "d") };
10656
+ return { event: record2.event, d: stringField(record2, "d") };
10657
10657
  case "changed":
10658
10658
  return { event: "changed" };
10659
10659
  case "exit":
10660
10660
  return {
10661
10661
  event: "exit",
10662
- exitCode: typeof record.exitCode === "number" ? record.exitCode : 0,
10663
- signal: typeof record.signal === "number" ? record.signal : 0,
10664
- reset: stringField(record, "reset")
10662
+ exitCode: typeof record2.exitCode === "number" ? record2.exitCode : 0,
10663
+ signal: typeof record2.signal === "number" ? record2.signal : 0,
10664
+ reset: stringField(record2, "reset")
10665
10665
  };
10666
10666
  default:
10667
- throw new TermProtocolError(`Unknown event "${record.event}".`);
10667
+ throw new TermProtocolError(`Unknown event "${record2.event}".`);
10668
10668
  }
10669
10669
  }
10670
- const id = stringField(record, "id");
10671
- if (record.ok === true) {
10672
- return { id, ok: true, data: record.data };
10670
+ const id = stringField(record2, "id");
10671
+ if (record2.ok === true) {
10672
+ return { id, ok: true, data: record2.data };
10673
10673
  }
10674
- const error = asRecord(record.error);
10674
+ const error = asRecord(record2.error);
10675
10675
  return { id, ok: false, error: { code: stringField(error, "code"), message: stringField(error, "message") } };
10676
10676
  }
10677
10677
  function asRecord(value) {
@@ -10680,22 +10680,22 @@ function asRecord(value) {
10680
10680
  }
10681
10681
  return value;
10682
10682
  }
10683
- function stringField(record, key) {
10684
- const value = record[key];
10683
+ function stringField(record2, key) {
10684
+ const value = record2[key];
10685
10685
  if (typeof value !== "string") {
10686
10686
  throw new TermProtocolError(`"${key}" must be a string.`);
10687
10687
  }
10688
10688
  return value;
10689
10689
  }
10690
- function stringArrayField(record, key) {
10691
- const value = record[key];
10690
+ function stringArrayField(record2, key) {
10691
+ const value = record2[key];
10692
10692
  if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string")) {
10693
10693
  throw new TermProtocolError(`"${key}" must be a non-empty string array.`);
10694
10694
  }
10695
10695
  return value;
10696
10696
  }
10697
- function stringMapField(record, key) {
10698
- const value = asRecord(record[key]);
10697
+ function stringMapField(record2, key) {
10698
+ const value = asRecord(record2[key]);
10699
10699
  const output = {};
10700
10700
  for (const [name, item] of Object.entries(value)) {
10701
10701
  if (typeof item === "string") {
@@ -10704,15 +10704,15 @@ function stringMapField(record, key) {
10704
10704
  }
10705
10705
  return output;
10706
10706
  }
10707
- function sizeField(record, key) {
10708
- const value = record[key];
10707
+ function sizeField(record2, key) {
10708
+ const value = record2[key];
10709
10709
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
10710
10710
  throw new TermProtocolError(`"${key}" must be a positive integer.`);
10711
10711
  }
10712
10712
  return value;
10713
10713
  }
10714
- function optionalSize(record, key) {
10715
- return record[key] === void 0 ? void 0 : sizeField(record, key);
10714
+ function optionalSize(record2, key) {
10715
+ return record2[key] === void 0 ? void 0 : sizeField(record2, key);
10716
10716
  }
10717
10717
 
10718
10718
  // src/core/term/client.ts
@@ -10949,8 +10949,8 @@ var DaemonLog = class {
10949
10949
  enableRotation() {
10950
10950
  this.rotating = true;
10951
10951
  }
10952
- write(record) {
10953
- const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record })}
10952
+ write(record2) {
10953
+ const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record2 })}
10954
10954
  `;
10955
10955
  try {
10956
10956
  if (this.rotating) {
@@ -12548,9 +12548,9 @@ function resetField(data) {
12548
12548
  return data && typeof data === "object" && "reset" in data && typeof data.reset === "string" ? data.reset : void 0;
12549
12549
  }
12550
12550
  function restoreSummary(data) {
12551
- const record = data && typeof data === "object" ? data : {};
12552
- const names = (key) => Array.isArray(record[key]) ? record[key].filter((item) => typeof item === "string") : [];
12553
- const failed = Array.isArray(record.failed) ? record.failed : [];
12551
+ const record2 = data && typeof data === "object" ? data : {};
12552
+ const names = (key) => Array.isArray(record2[key]) ? record2[key].filter((item) => typeof item === "string") : [];
12553
+ const failed = Array.isArray(record2.failed) ? record2.failed : [];
12554
12554
  const parts = [
12555
12555
  names("restored").length ? `Restored: ${names("restored").join(", ")}` : "",
12556
12556
  names("running").length ? `Already running: ${names("running").join(", ")}` : "",
@@ -12567,6 +12567,7 @@ import { hostname } from "os";
12567
12567
 
12568
12568
  // src/core/agent/agents.ts
12569
12569
  var AGENT_IDS = ["claude-code", "codex"];
12570
+ var AGENT_MCP_CLIENT_NAMES = { "claude-code": "claude-code", codex: "codex-mcp-client" };
12570
12571
  var DEFAULT_AGENT = "claude-code";
12571
12572
  function isAgentId(value) {
12572
12573
  return typeof value === "string" && AGENT_IDS.includes(value);
@@ -12580,8 +12581,8 @@ function agentReplySchema(textMaxCharacters) {
12580
12581
  };
12581
12582
  }
12582
12583
  var AINECTO_MCP_SERVER = "ainecto";
12583
- function ainectoBridge(nodePath, cliScript, endpoint) {
12584
- return { command: nodePath, args: [cliScript, "--endpoint", endpoint, "mcp"] };
12584
+ function ainectoBridge(nodePath, cliScript, endpoint, agentName) {
12585
+ return { command: nodePath, args: [cliScript, "--endpoint", endpoint, "mcp", ...agentName ? ["--agent", agentName] : []] };
12585
12586
  }
12586
12587
  function agentEnv(env) {
12587
12588
  const out = { ...env };
@@ -12861,7 +12862,13 @@ function claudeCodeAdapter(deps) {
12861
12862
  }
12862
12863
  return claudeAuthFromJson(run.stdout, run.code, run.stderrTail, hasApiKeyVariable(deps.env));
12863
12864
  },
12864
- open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new ClaudeCodeSession(conversationUuid, resumeRef, deps.args({ textMaxCharacters, resumeSessionId: resumeRef }), deps)
12865
+ open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new ClaudeCodeSession(
12866
+ conversationUuid,
12867
+ resumeRef,
12868
+ agentName,
12869
+ deps.args({ textMaxCharacters, resumeSessionId: resumeRef, agentName }),
12870
+ deps
12871
+ )
12865
12872
  };
12866
12873
  }
12867
12874
  function hasApiKeyVariable(env) {
@@ -12887,8 +12894,9 @@ function claudeAuthFromJson(stdout, code, stderrTail, apiKeyVariable) {
12887
12894
  };
12888
12895
  }
12889
12896
  var ClaudeCodeSession = class {
12890
- constructor(conversationUuid, resumeRef, args, deps) {
12897
+ constructor(conversationUuid, resumeRef, agentName, args, deps) {
12891
12898
  this.conversationUuid = conversationUuid;
12899
+ this.agentName = agentName;
12892
12900
  this.deps = deps;
12893
12901
  this.resumed = resumeRef !== void 0;
12894
12902
  this.child = new AgentChild(deps.spawnImpl, CLAUDE, args, { cwd: deps.cwd, env: deps.env }, {
@@ -12898,6 +12906,7 @@ var ClaudeCodeSession = class {
12898
12906
  deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
12899
12907
  }
12900
12908
  conversationUuid;
12909
+ agentName;
12901
12910
  deps;
12902
12911
  agent = "claude-code";
12903
12912
  resumed;
@@ -13113,7 +13122,7 @@ function codexAdapter(deps) {
13113
13122
  await server.child.stop();
13114
13123
  }
13115
13124
  },
13116
- open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, deps)
13125
+ open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, agentName, deps)
13117
13126
  };
13118
13127
  }
13119
13128
  var CodexRpc = class {
@@ -13213,12 +13222,13 @@ function startAppServer(deps, args, hooks) {
13213
13222
  return { child, rpc };
13214
13223
  }
13215
13224
  var CodexSession = class {
13216
- constructor(conversationUuid, resumeRef, textMaxCharacters, deps) {
13225
+ constructor(conversationUuid, resumeRef, textMaxCharacters, agentName, deps) {
13217
13226
  this.conversationUuid = conversationUuid;
13218
13227
  this.textMaxCharacters = textMaxCharacters;
13228
+ this.agentName = agentName;
13219
13229
  this.deps = deps;
13220
13230
  this.resumed = resumeRef !== void 0;
13221
- const server = startAppServer(deps, deps.appServerArgs, {
13231
+ const server = startAppServer(deps, deps.appServerArgs(agentName), {
13222
13232
  notification: (method, params) => this.onNotification(method, params),
13223
13233
  exit: (exit) => this.onExit(exit)
13224
13234
  });
@@ -13229,6 +13239,7 @@ var CodexSession = class {
13229
13239
  }
13230
13240
  conversationUuid;
13231
13241
  textMaxCharacters;
13242
+ agentName;
13232
13243
  deps;
13233
13244
  agent = "codex";
13234
13245
  resumed;
@@ -13472,6 +13483,100 @@ function parseJson2(text) {
13472
13483
  }
13473
13484
  }
13474
13485
 
13486
+ // src/core/agent/tools.ts
13487
+ import { randomUUID as randomUUID3 } from "crypto";
13488
+ var TOOL_PREFIX = "mcp__ainecto__";
13489
+ var AgentToolError = class extends Error {
13490
+ constructor(message, tool, code, retryable = false) {
13491
+ super(message);
13492
+ this.tool = tool;
13493
+ this.code = code;
13494
+ this.retryable = retryable;
13495
+ this.name = "AgentToolError";
13496
+ }
13497
+ tool;
13498
+ code;
13499
+ retryable;
13500
+ };
13501
+ function createAgentTools(input) {
13502
+ const asClients = /* @__PURE__ */ new Map();
13503
+ const clientFor = (identity) => {
13504
+ if (!identity || !input.clientAs) return input.client;
13505
+ const key = `${identity.agent}\0${identity.name}`;
13506
+ let found = asClients.get(key);
13507
+ if (!found) {
13508
+ found = input.clientAs(identity);
13509
+ asClients.set(key, found);
13510
+ }
13511
+ return found;
13512
+ };
13513
+ async function logged(tool, bytes, run, as) {
13514
+ const callId = randomUUID3();
13515
+ const started = Date.now();
13516
+ input.log.write({ event: "agent_call", callId, op: "tool", tool, ...as ? { agent: as.agent, agentName: as.name } : {}, bytes });
13517
+ let outcome = { ok: false, error: "no response" };
13518
+ try {
13519
+ const value = await run();
13520
+ outcome = { ok: true };
13521
+ return value;
13522
+ } catch (error) {
13523
+ const failure2 = toToolError(tool, error);
13524
+ outcome = { ok: false, ...failure2.code ? { code: failure2.code } : {}, error: failure2.message };
13525
+ throw failure2;
13526
+ } finally {
13527
+ input.log.write({ event: "agent_call_response", callId, op: "tool", tool, ...outcome, ms: Date.now() - started });
13528
+ }
13529
+ }
13530
+ return {
13531
+ call(tool, args, options = {}) {
13532
+ return logged(tool, Buffer.byteLength(JSON.stringify(args), "utf8"), async () => {
13533
+ const raw = await clientFor(options.as).toolsCall(TOOL_PREFIX + tool, args);
13534
+ if (isToolError(raw)) throw new AgentToolError(toolErrorText(raw), tool, codeInText(toolErrorText(raw)));
13535
+ const payload = unwrapMcpToolPayload(raw);
13536
+ if (!isRecord13(payload)) throw new AgentToolError(`${tool} did not return an object.`, tool, "MCP_PROTOCOL_ERROR");
13537
+ return payload;
13538
+ }, options.as);
13539
+ },
13540
+ list() {
13541
+ return logged("tools/list", 0, () => input.client.toolsList());
13542
+ }
13543
+ };
13544
+ }
13545
+ function toolsAs(tools, identity) {
13546
+ return {
13547
+ call: (tool, args, options) => tools.call(tool, args, { as: identity, ...options }),
13548
+ list: () => tools.list()
13549
+ };
13550
+ }
13551
+ function toToolError(tool, error) {
13552
+ if (error instanceof AgentToolError) return error;
13553
+ if (error instanceof McpRpcError) {
13554
+ const details = isRecord13(error.details) ? error.details : {};
13555
+ const data = isRecord13(details.data) ? details.data : {};
13556
+ const status = typeof details.status === "number" ? details.status : void 0;
13557
+ const code = typeof data.code === "string" ? data.code : typeof details.error === "string" ? details.error : error.code;
13558
+ const rpcCode = typeof details.code === "number" ? details.code : void 0;
13559
+ return new AgentToolError(
13560
+ error.message,
13561
+ tool,
13562
+ code,
13563
+ status !== void 0 && status >= 500 || rpcCode !== void 0 && (rpcCode >= 500 || rpcCode === -32603)
13564
+ );
13565
+ }
13566
+ return new AgentToolError(error instanceof Error ? error.message : String(error), tool, void 0, true);
13567
+ }
13568
+ function codeInText(text) {
13569
+ try {
13570
+ const parsed = JSON.parse(text);
13571
+ return isRecord13(parsed) && typeof parsed.code === "string" ? parsed.code : void 0;
13572
+ } catch {
13573
+ return void 0;
13574
+ }
13575
+ }
13576
+ function isRecord13(value) {
13577
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13578
+ }
13579
+
13475
13580
  // src/core/agent/log.ts
13476
13581
  function openAgentLog(paths) {
13477
13582
  const log = new DaemonLog(paths.log, paths.previousLog);
@@ -13488,13 +13593,73 @@ function agentPaths(home = homedir3()) {
13488
13593
  dir,
13489
13594
  work: join7(dir, "work"),
13490
13595
  sessions: join7(dir, "sessions.json"),
13596
+ runs: join7(dir, "runs.json"),
13491
13597
  log: join7(dir, "agent.log"),
13492
13598
  previousLog: join7(dir, "agent.log.1")
13493
13599
  };
13494
13600
  }
13495
13601
 
13602
+ // src/core/agent/runs.ts
13603
+ import { readFile as readFile9, rename as rename6, writeFile as writeFile6 } from "fs/promises";
13604
+ var AgentRunLog = class {
13605
+ constructor(path, log) {
13606
+ this.path = path;
13607
+ this.log = log;
13608
+ }
13609
+ path;
13610
+ log;
13611
+ runs = /* @__PURE__ */ new Map();
13612
+ /** 읽어서 남은 줄을 돌려준다 — 결과는 로그 한 줄. */
13613
+ async load() {
13614
+ let reason;
13615
+ const runs = /* @__PURE__ */ new Map();
13616
+ try {
13617
+ const parsed = JSON.parse(await readFile9(this.path, "utf8"));
13618
+ for (const value of Array.isArray(parsed.runs) ? parsed.runs : []) {
13619
+ const e = value ?? {};
13620
+ if (typeof e.cardUuid === "string" && typeof e.startedAt === "string") {
13621
+ runs.set(e.cardUuid, {
13622
+ cardUuid: e.cardUuid,
13623
+ ...typeof e.workId === "string" ? { workId: e.workId } : {},
13624
+ ...typeof e.agent === "string" ? { agent: e.agent } : {},
13625
+ startedAt: e.startedAt
13626
+ });
13627
+ }
13628
+ }
13629
+ } catch (error) {
13630
+ reason = isNodeError(error, "ENOENT") ? "missing" : `unreadable: ${error instanceof Error ? error.message : String(error)}`;
13631
+ runs.clear();
13632
+ }
13633
+ this.runs = runs;
13634
+ this.log.write({ event: "runs_load", entries: runs.size, ...reason ? { reason } : {} });
13635
+ if (reason?.startsWith("unreadable")) await this.save();
13636
+ return [...runs.values()];
13637
+ }
13638
+ /** 돌기 시작(수락 직후) · 작업이 열리면 workId 를 더한다 — 처음 적은 시각은 그대로. */
13639
+ async started(cardUuid, workId, agent) {
13640
+ const before = this.runs.get(cardUuid);
13641
+ this.runs.set(cardUuid, {
13642
+ cardUuid,
13643
+ ...workId ?? before?.workId ? { workId: workId ?? before?.workId } : {},
13644
+ agent,
13645
+ startedAt: before?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
13646
+ });
13647
+ await this.save();
13648
+ }
13649
+ async finished(cardUuid) {
13650
+ if (!this.runs.delete(cardUuid)) return;
13651
+ await this.save();
13652
+ }
13653
+ async save() {
13654
+ const tmp = `${this.path}.tmp`;
13655
+ await writeFile6(tmp, `${JSON.stringify({ version: 1, runs: [...this.runs.values()] }, null, 2)}
13656
+ `, { mode: PRIVATE_FILE_MODE });
13657
+ await rename6(tmp, this.path);
13658
+ }
13659
+ };
13660
+
13496
13661
  // src/core/agent/readiness.ts
13497
- import { randomUUID as randomUUID3 } from "crypto";
13662
+ import { randomUUID as randomUUID4 } from "crypto";
13498
13663
  async function checkAgents(adapters, log) {
13499
13664
  return await Promise.all(adapters.map(async (adapter) => {
13500
13665
  const detected = await probe(
@@ -13528,7 +13693,7 @@ function openAgents(checks) {
13528
13693
  return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready, ...check.auth ? { auth: check.auth } : {} }));
13529
13694
  }
13530
13695
  async function probe(log, agent, kind, work, summary) {
13531
- const callId = randomUUID3();
13696
+ const callId = randomUUID4();
13532
13697
  const started = Date.now();
13533
13698
  log.write({ event: "agent_probe", callId, agent, probe: kind });
13534
13699
  try {
@@ -13560,6 +13725,10 @@ function agentPromptText(text, context) {
13560
13725
  if (d && typeof d.uuid === "string") {
13561
13726
  parts.push(`open document \xAB${str(d.title)}\xBB (documentUuid ${d.uuid}${typeof d.type === "string" ? `, ${d.type}` : ""})`);
13562
13727
  }
13728
+ const files = Array.isArray(context?.attachments) ? context.attachments.map((f) => str(f?.filename)).filter((name) => name !== "") : [];
13729
+ if (files.length > 0) {
13730
+ parts.push(`attached files ${files.map((name) => `\xAB${name}\xBB`).join(", ")} (names only \u2014 the files are not available on this machine)`);
13731
+ }
13563
13732
  if (parts.length === 0) return text;
13564
13733
  return `[AiNecto context \u2014 "this project" / "this document" mean these] ${parts.join(" \xB7 ")}
13565
13734
 
@@ -13622,15 +13791,368 @@ function clip(text, max) {
13622
13791
  return chars.length <= max ? chars.join("") : `${chars.slice(0, max - 1).join("")}\u2026`;
13623
13792
  }
13624
13793
 
13794
+ // src/core/agent/todoRun.ts
13795
+ var TODO_KINDS = ["CARD_ASSIGNED", "DECISION_ANSWERED"];
13796
+ function resumeTodo(entry) {
13797
+ return { todoId: `resume:${entry.cardUuid}`, kind: "RESUME", cardUuid: entry.cardUuid, ...entry.workId ? { workId: entry.workId } : {} };
13798
+ }
13799
+ function todosIn(res) {
13800
+ const raw = Array.isArray(res.items) ? res.items : [];
13801
+ const items = raw.flatMap((value) => {
13802
+ const item = record(value);
13803
+ const target = record(item.target);
13804
+ const kind = item.kind;
13805
+ if (typeof item.todoId !== "string" || !isTodoKind(kind) || target.type !== "KANBAN_CARD" || typeof target.uuid !== "string") {
13806
+ return [];
13807
+ }
13808
+ return [{
13809
+ todoId: item.todoId,
13810
+ kind,
13811
+ cardUuid: target.uuid,
13812
+ ...typeof target.commentId === "number" ? { commentId: target.commentId } : {}
13813
+ }];
13814
+ });
13815
+ const last = raw.length > 0 ? record(raw[raw.length - 1]).todoId : void 0;
13816
+ return { items, ...res.hasMore === true && typeof last === "string" ? { next: last } : {} };
13817
+ }
13818
+ function isTodoKind(value) {
13819
+ return typeof value === "string" && TODO_KINDS.includes(value);
13820
+ }
13821
+ function renewDelayMs(claimExpiresAt, nowMs) {
13822
+ if (typeof claimExpiresAt !== "string") return void 0;
13823
+ const at = Date.parse(claimExpiresAt);
13824
+ if (!Number.isFinite(at)) return void 0;
13825
+ return Math.max(0, Math.floor((at - nowMs) / 2));
13826
+ }
13827
+ function cardFactsOf(detail) {
13828
+ const d = record(detail);
13829
+ const card = record(d.card);
13830
+ if (typeof card.uuid !== "string" || typeof card.status !== "string") {
13831
+ throw new AgentToolError("The card detail has no uuid or status.", "kanban_list_cards", "MCP_PROTOCOL_ERROR");
13832
+ }
13833
+ const work = record(d.work);
13834
+ const owner = record(card.assignee);
13835
+ return {
13836
+ uuid: card.uuid,
13837
+ ...typeof card.key === "string" ? { key: card.key } : {},
13838
+ title: str2(card.title),
13839
+ ...typeof d.boardUuid === "string" ? { boardUuid: d.boardUuid } : {},
13840
+ status: card.status,
13841
+ ...typeof card.assignmentState === "string" ? { assignmentState: card.assignmentState } : {},
13842
+ blocked: card.blocked === true,
13843
+ ...typeof d.description === "string" && d.description.trim() ? { description: d.description } : {},
13844
+ criteria: (Array.isArray(d.criteria) ? d.criteria : []).flatMap((c) => {
13845
+ const v = record(c);
13846
+ return typeof v.text === "string" ? [{ text: v.text, done: v.done === true }] : [];
13847
+ }),
13848
+ ...typeof owner.userId === "string" ? { ownerUserId: owner.userId } : {},
13849
+ ...typeof work.workId === "string" ? { workId: work.workId } : {}
13850
+ };
13851
+ }
13852
+ function answerComments(listed, commentId) {
13853
+ const all = (Array.isArray(listed.comments) ? listed.comments : []).map(record).filter((c) => typeof c.id === "number");
13854
+ const rootOf = (c) => typeof c.rootCommentId === "number" ? c.rootCommentId : typeof c.parentCommentId === "number" ? c.parentCommentId : c.id;
13855
+ const roots = /* @__PURE__ */ new Set();
13856
+ const pointed = all.find((c) => c.id === commentId);
13857
+ if (pointed) roots.add(rootOf(pointed));
13858
+ for (const c of all) {
13859
+ if (c.kind === "QUESTION" && c.questionState !== "RESOLVED" && c.parentCommentId == null) roots.add(c.id);
13860
+ }
13861
+ return all.filter((c) => roots.has(rootOf(c))).map((c) => ({
13862
+ id: c.id,
13863
+ author: str2(record(c.author).displayName) || "?",
13864
+ kind: str2(c.kind) || "COMMENT",
13865
+ body: str2(c.body),
13866
+ ...typeof c.questionState === "string" ? { questionState: c.questionState } : {}
13867
+ }));
13868
+ }
13869
+ var PROMPT_HEADS = {
13870
+ CARD_ASSIGNED: "[AiNecto auto-run] The person handed you this kanban card with auto-run. Do the work with the AiNecto tools.",
13871
+ DECISION_ANSWERED: "[AiNecto auto-run \u2014 continue] The person answered on this card (or asked for changes). Continue the same work.",
13872
+ RESUME: "[AiNecto auto-run \u2014 resume] This machine stopped while you were working this card. Continue the same work: first check what is already done with report_work_progress (CHECKPOINT)."
13873
+ };
13874
+ function todoPromptText(input) {
13875
+ const { card, workId } = input;
13876
+ const owner = card.ownerUserId ?? "the card's assignee";
13877
+ const lines = [
13878
+ PROMPT_HEADS[input.kind],
13879
+ "",
13880
+ `Card \xAB${card.title}\xBB (${card.key ? `${card.key}, ` : ""}cardUuid ${card.uuid}${card.boardUuid ? `, boardUuid ${card.boardUuid}` : ""}) \xB7 status ${card.status}${card.blocked ? " \xB7 blocked" : ""}`,
13881
+ `AI work: workId ${workId} \u2014 send this workId with every AiNecto call for this card and report each step with report_work_progress (read each response before going on).`
13882
+ ];
13883
+ if (card.description) lines.push("", "Description:", card.description);
13884
+ if (card.criteria.length > 0) {
13885
+ lines.push("", "Done criteria:", ...card.criteria.map((c) => `- [${c.done ? "x" : " "}] ${c.text}`));
13886
+ }
13887
+ if (input.answers.length > 0) {
13888
+ lines.push(
13889
+ "",
13890
+ "Comments to read (oldest first):",
13891
+ ...input.answers.map((a) => `- #${a.id} ${a.kind}${a.questionState ? ` (${a.questionState})` : ""} by ${a.author}: ${a.body}`)
13892
+ );
13893
+ lines.push("", `First read them: report_work_progress (it lists the comments to read \u2014 send \`read\` with its checkId), resolve_comments for the questions that are answered, and if the card is blocked, kanban_card_action {cardUuid: "${card.uuid}", action: "unblock"}. Then continue the work.`);
13894
+ }
13895
+ lines.push(
13896
+ "",
13897
+ "If you need the person's decision, do not guess. Ask and stop:",
13898
+ `1) create_comments {cardUuid: "${card.uuid}", workId: "${workId}", items: [{kind: "QUESTION", body: <your question>}]}`,
13899
+ `2) kanban_card_action {cardUuid: "${card.uuid}", action: "block", reason: <one line>, responderIds: ["${owner}"]}`,
13900
+ `3) report_work_progress {workId: "${workId}", stepId: <the step>, status: "BLOCKED"}`,
13901
+ "Then answer with what you asked. You will be called again on this card when they answer.",
13902
+ "",
13903
+ "Do not request review, approve, or finish the card yourself \u2014 this PC posts your answer as the result and asks the person to review it.",
13904
+ "Do not call finish_work: the AI work stays open until the person approves the result (finishing it early blocks the hand-over).",
13905
+ "Your answer (reply) is shown to the person in this card's auto-run conversation: say what you did, or what you asked."
13906
+ );
13907
+ return lines.join("\n");
13908
+ }
13909
+ async function runTodo(deps, todo) {
13910
+ const started = Date.now();
13911
+ deps.log.write({ event: "todo_run", todoId: todo.todoId, kind: todo.kind, cardUuid: todo.cardUuid });
13912
+ let outcome;
13913
+ let workId;
13914
+ let conversationUuid;
13915
+ let failure2;
13916
+ let warning;
13917
+ try {
13918
+ const ends = async (value) => {
13919
+ outcome = value;
13920
+ if (value !== "stopped") await deps.runs?.finished(todo.cardUuid);
13921
+ return value;
13922
+ };
13923
+ let card = await readCard(deps.tools, todo.cardUuid);
13924
+ if (todo.kind === "RESUME" && !resumable(card, todo.workId)) return await ends("not_runnable");
13925
+ if (todo.kind === "CARD_ASSIGNED" && card.assignmentState === "PENDING") {
13926
+ card = await act(deps.tools, card.uuid, "accept");
13927
+ await deps.runs?.started(card.uuid);
13928
+ }
13929
+ if (todo.kind !== "DECISION_ANSWERED" && card.status === "TODO") card = await act(deps.tools, card.uuid, "start");
13930
+ if (card.status !== "IN_PROGRESS") return await ends("not_runnable");
13931
+ workId = card.workId ?? await startWork(deps.tools, card.uuid);
13932
+ if (todo.kind !== "DECISION_ANSWERED") await deps.runs?.started(card.uuid, workId);
13933
+ conversationUuid = await postToRun(deps, card.uuid, workId, OPENINGS[todo.kind](card.title));
13934
+ const answers = todo.kind === "DECISION_ANSWERED" ? answerComments(await deps.tools.call("list_comments", { cardUuid: card.uuid, workId }), todo.commentId) : [];
13935
+ if (deps.signal.aborted) {
13936
+ outcome = "stopped";
13937
+ return outcome;
13938
+ }
13939
+ const reply = await deps.runAgent({
13940
+ todoId: todo.todoId,
13941
+ conversationUuid,
13942
+ text: todoPromptText({ kind: todo.kind, card, workId, answers })
13943
+ });
13944
+ if (deps.signal.aborted) {
13945
+ outcome = "stopped";
13946
+ return outcome;
13947
+ }
13948
+ await postToRun(deps, card.uuid, workId, reply.reply);
13949
+ if (reply.status !== "DONE") return await ends("agent_failed");
13950
+ const after = await readCard(deps.tools, card.uuid, workId);
13951
+ if (after.blocked) return await ends("decision_requested");
13952
+ if (after.status !== "IN_PROGRESS") return await ends("not_runnable");
13953
+ warning = await handOverResult(deps, after, workId, reply.reply);
13954
+ return await ends("review_requested");
13955
+ } catch (error) {
13956
+ failure2 = error instanceof Error ? error : new Error(String(error));
13957
+ throw error;
13958
+ } finally {
13959
+ deps.log.write({
13960
+ event: "todo_run_result",
13961
+ todoId: todo.todoId,
13962
+ kind: todo.kind,
13963
+ cardUuid: todo.cardUuid,
13964
+ outcome: outcome ?? `error: ${failure2?.message ?? "unknown"}`,
13965
+ ...warning ? { warning } : {},
13966
+ ...failure2 instanceof AgentToolError ? { tool: failure2.tool, ...failure2.code ? { code: failure2.code } : {} } : {},
13967
+ ...workId ? { workId } : {},
13968
+ ...conversationUuid ? { conversationUuid } : {},
13969
+ ms: Date.now() - started
13970
+ });
13971
+ }
13972
+ }
13973
+ var OPENINGS = {
13974
+ CARD_ASSIGNED: (title) => `\xAB${title}\xBB \uC791\uC5C5\uC744 \uC2DC\uC791\uD588\uC5B4\uC694.`,
13975
+ DECISION_ANSWERED: (title) => `\uB2F5\uC744 \uBC1B\uC544 \xAB${title}\xBB \uC791\uC5C5\uC744 \uC774\uC5B4 \uAC00\uC694.`,
13976
+ RESUME: (title) => `\uC774 PC \uAC00 \uB2E4\uC2DC \uCF1C\uC838 \xAB${title}\xBB \uC791\uC5C5\uC744 \uC774\uC5B4 \uAC00\uC694.`
13977
+ };
13978
+ function resumable(card, workId) {
13979
+ if (card.assignmentState !== "ACCEPTED" || card.blocked) return false;
13980
+ if (card.status !== "TODO" && card.status !== "IN_PROGRESS") return false;
13981
+ return !workId || !card.workId || card.workId === workId;
13982
+ }
13983
+ async function handOverResult(deps, card, workId, result) {
13984
+ await deps.tools.call("create_comments", {
13985
+ cardUuid: card.uuid,
13986
+ workId,
13987
+ items: [{ kind: "COMMENT", body: clip(result, deps.textMaxCharacters), resultReview: true }]
13988
+ });
13989
+ try {
13990
+ await deps.tools.call("report_work_progress", { workId, status: "CHECKPOINT" });
13991
+ return void 0;
13992
+ } catch (error) {
13993
+ if (error instanceof AgentToolError && error.code === "WORK_NOT_IN_PROGRESS") return `report_work_progress: ${error.code}`;
13994
+ throw error;
13995
+ }
13996
+ }
13997
+ async function readCard(tools, cardUuid, workId) {
13998
+ const res = await tools.call("kanban_list_cards", { cardUuids: [cardUuid], ...workId ? { workId } : {} });
13999
+ const cards = Array.isArray(res.cards) ? res.cards : [];
14000
+ return cardFactsOf(cards[0]);
14001
+ }
14002
+ async function act(tools, cardUuid, action) {
14003
+ const res = await tools.call("kanban_card_action", { cardUuid, action });
14004
+ return cardFactsOf(res.card);
14005
+ }
14006
+ async function startWork(tools, cardUuid) {
14007
+ const res = await tools.call("start_work", { cardUuid });
14008
+ const workId = typeof res.workId === "string" ? res.workId : record(res.work).workId;
14009
+ if (typeof workId !== "string") throw new AgentToolError("start_work returned no workId.", "start_work", "MCP_PROTOCOL_ERROR");
14010
+ return workId;
14011
+ }
14012
+ async function postToRun(deps, cardUuid, workId, body) {
14013
+ const res = await deps.tools.call("send_auto_run_message", { cardUuid, workId, body: clip(body, deps.textMaxCharacters) });
14014
+ if (typeof res.conversationUuid !== "string") {
14015
+ throw new AgentToolError("send_auto_run_message returned no conversationUuid.", "send_auto_run_message", "MCP_PROTOCOL_ERROR");
14016
+ }
14017
+ return res.conversationUuid;
14018
+ }
14019
+ function record(value) {
14020
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
14021
+ }
14022
+ function str2(value) {
14023
+ return typeof value === "string" ? value : "";
14024
+ }
14025
+ var STOP_WORK_ERRORS = /* @__PURE__ */ new Set(["CLOSED_BY_HUMAN", "SUPERSEDED", "ACCESS_LOST"]);
14026
+ async function updateTodo(tools, item) {
14027
+ const res = await tools.call("update_agent_todos", { items: [item] });
14028
+ return record(Array.isArray(res.results) ? res.results[0] : void 0);
14029
+ }
14030
+ async function claimTodo(tools, log, todo) {
14031
+ const result = await updateTodo(tools, { todoId: todo.todoId, action: "claim" });
14032
+ const ok = result.ok === true && typeof result.leaseToken === "string";
14033
+ log.write({
14034
+ event: "todo_lease",
14035
+ todoId: todo.todoId,
14036
+ action: "claim",
14037
+ ok,
14038
+ ...ok ? {} : { error: str2(result.error) || "no leaseToken" },
14039
+ ...typeof result.claimExpiresAt === "string" ? { next: result.claimExpiresAt } : {}
14040
+ });
14041
+ if (!ok) return void 0;
14042
+ return {
14043
+ todo,
14044
+ leaseToken: result.leaseToken,
14045
+ ...typeof result.claimExpiresAt === "string" ? { claimExpiresAt: result.claimExpiresAt } : {}
14046
+ };
14047
+ }
14048
+ function keepLease(tools, log, claimed, onLost, now = Date.now) {
14049
+ let timer;
14050
+ let stopped = false;
14051
+ const schedule = (expiresAt) => {
14052
+ const delay = renewDelayMs(expiresAt, now());
14053
+ if (stopped || delay === void 0) return;
14054
+ timer = setTimeout(() => void renew(), delay);
14055
+ timer.unref?.();
14056
+ };
14057
+ const renew = async () => {
14058
+ if (stopped) return;
14059
+ let error;
14060
+ let next;
14061
+ try {
14062
+ const result = await updateTodo(tools, { todoId: claimed.todo.todoId, action: "renew", leaseToken: claimed.leaseToken });
14063
+ if (result.ok === true) {
14064
+ if (typeof result.leaseToken === "string") claimed.leaseToken = result.leaseToken;
14065
+ next = typeof result.claimExpiresAt === "string" ? result.claimExpiresAt : void 0;
14066
+ claimed.claimExpiresAt = next;
14067
+ } else {
14068
+ error = str2(result.error) || "renew refused";
14069
+ }
14070
+ } catch (failure2) {
14071
+ error = failure2 instanceof Error ? failure2.message : String(failure2);
14072
+ next = claimed.claimExpiresAt;
14073
+ }
14074
+ log.write({
14075
+ event: "todo_lease",
14076
+ todoId: claimed.todo.todoId,
14077
+ action: "renew",
14078
+ ok: error === void 0,
14079
+ ...error ? { error } : {},
14080
+ ...next ? { next } : {}
14081
+ });
14082
+ if (error !== void 0 && STOP_WORK_ERRORS.has(error)) {
14083
+ stopped = true;
14084
+ onLost(error);
14085
+ return;
14086
+ }
14087
+ if (error !== void 0 && next === void 0) return;
14088
+ if (next !== void 0 && Date.parse(next) <= now()) return;
14089
+ schedule(next);
14090
+ };
14091
+ schedule(claimed.claimExpiresAt);
14092
+ return {
14093
+ stop() {
14094
+ stopped = true;
14095
+ if (timer) clearTimeout(timer);
14096
+ }
14097
+ };
14098
+ }
14099
+ async function closeTodo(tools, log, claimed, action, note) {
14100
+ let error;
14101
+ try {
14102
+ const result = await updateTodo(tools, {
14103
+ todoId: claimed.todo.todoId,
14104
+ action,
14105
+ leaseToken: claimed.leaseToken,
14106
+ ...action === "complete" && note ? { note } : {}
14107
+ });
14108
+ if (result.ok !== true) error = str2(result.error) || `${action} refused`;
14109
+ } catch (failure2) {
14110
+ error = failure2 instanceof Error ? failure2.message : String(failure2);
14111
+ }
14112
+ log.write({ event: "todo_lease", todoId: claimed.todo.todoId, action, ok: error === void 0, ...error ? { error } : {} });
14113
+ }
14114
+
13625
14115
  // src/core/agent/serve.ts
13626
- var PC_FEATURES = ["stop"];
14116
+ var PC_FEATURES = ["stop", "todos"];
14117
+ function pcFeatures(takesTodos) {
14118
+ return PC_FEATURES.filter((f) => f !== "todos" || takesTodos);
14119
+ }
14120
+ var todoKey = (todoId) => `todo:${todoId}`;
14121
+ var TODO_NOTES = {
14122
+ review_requested: "Worked the card and asked for review.",
14123
+ decision_requested: "Asked for a decision on the card.",
14124
+ not_runnable: "The card is no longer in progress.",
14125
+ agent_failed: "The agent run failed; see the auto-run conversation.",
14126
+ stopped: "Stopped."
14127
+ };
13627
14128
  async function runAgentServe(deps) {
13628
- const opened = await openLink(deps);
14129
+ const folderName = deps.todos?.agentName;
14130
+ let opened;
14131
+ try {
14132
+ opened = await openLink(deps, openAgentsBody(deps.agents, folderName));
14133
+ } catch (error) {
14134
+ if (error instanceof AgentCallError && error.status === 400 && error.code === "AGENT_NAME_INVALID") {
14135
+ deps.print(`AiNecto did not accept the agent name \xAB${folderName ?? ""}\xBB in this folder's .ainecto/agent.local (${error.message}). Set a valid name with \`ainecto init --agent NAME\` (or delete .ainecto/agent.local), then run \`ainecto agent serve\` again.`);
14136
+ return { exitCode: 1, reason: "agent_name_invalid" };
14137
+ }
14138
+ throw error;
14139
+ }
13629
14140
  const linkId = String(opened.linkId);
13630
14141
  deps.http.useLinkToken(String(opened.linkToken));
13631
14142
  const limits = serverLimits(opened.limits);
13632
- const names = deps.agents.map((a) => deps.adapters.get(a.id)?.displayName ?? a.id).join(" / ");
14143
+ const displayName = (id) => deps.adapters.get(id)?.displayName ?? id;
14144
+ const names = deps.agents.map((a) => displayName(a.id)).join(" / ");
13633
14145
  deps.print(`Connected to AiNecto as ${deps.hostName}. Requests to \xABMy agent\xBB in AiNecto Chat now run in ${names} on this machine. Press Ctrl+C to stop.`);
14146
+ const { identities, refused } = identitiesIn(opened.agents, deps.adapters);
14147
+ for (const r of refused) {
14148
+ deps.print(`${displayName(r.agent)}: AiNecto refused its agent identity (${r.error}), so auto-run cards for ${displayName(r.agent)} are not taken here.` + (r.error === "AGENT_LIMIT" ? " Archive an agent you no longer use in AiNecto, then start `ainecto agent serve` again." : ""));
14149
+ }
14150
+ const todos = deps.todos && identities.length > 0 ? { tools: deps.todos.tools, runs: deps.todos.runs, identities } : void 0;
14151
+ if (todos) {
14152
+ deps.print(`Auto-run cards handed to ${identities.map((i) => `${displayName(i.agent)} (${i.name})`).join(" and ")} run here.`);
14153
+ } else if (deps.todos && refused.length === 0) {
14154
+ deps.print("Auto-run cards are not taken here: AiNecto did not give this connection an agent identity (update the server, or sign in to Claude Code or Codex).");
14155
+ }
13634
14156
  const stopController = new AbortController();
13635
14157
  let stopReason;
13636
14158
  let exitCode2 = 0;
@@ -13640,11 +14162,13 @@ async function runAgentServe(deps) {
13640
14162
  const queue = [];
13641
14163
  const stopping = /* @__PURE__ */ new Set();
13642
14164
  let current;
13643
- const requestStop = (turnUuid) => {
13644
- if (stopping.has(turnUuid)) return;
13645
- stopping.add(turnUuid);
13646
- const running = current?.turnUuid === turnUuid;
13647
- deps.log.write({ event: "stop_request", turnUuid, running, queued: queue.some((o) => o.turnUuid === turnUuid) });
14165
+ let todoInFlight;
14166
+ let wakeTodos;
14167
+ const requestStop = (key) => {
14168
+ if (stopping.has(key)) return;
14169
+ stopping.add(key);
14170
+ const running = current?.key === key;
14171
+ deps.log.write({ event: "stop_request", turnUuid: key, running, queued: queue.some((j) => jobKey(j) === key) });
13648
14172
  if (running) void current?.session.interrupt();
13649
14173
  };
13650
14174
  const stop = (reason, code, message) => {
@@ -13654,6 +14178,7 @@ async function runAgentServe(deps) {
13654
14178
  if (message) deps.print(message);
13655
14179
  stopController.abort();
13656
14180
  wakeWorker?.();
14181
+ wakeTodos?.();
13657
14182
  for (const session of live.values()) void session.close();
13658
14183
  };
13659
14184
  const onUserStop = () => stop("signal", 0, "Stopping\u2026");
@@ -13681,7 +14206,7 @@ async function runAgentServe(deps) {
13681
14206
  deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, agent: offer.agent, duplicate });
13682
14207
  if (duplicate) continue;
13683
14208
  received.add(offer.turnUuid);
13684
- queue.push(offer);
14209
+ queue.push({ kind: "chat", offer });
13685
14210
  wakeWorker?.();
13686
14211
  }
13687
14212
  for (const turnUuid of stopsIn(res)) requestStop(turnUuid);
@@ -13696,9 +14221,9 @@ async function runAgentServe(deps) {
13696
14221
  }
13697
14222
  }
13698
14223
  })();
13699
- const sessionFor = async (adapter, conversationUuid) => {
14224
+ const sessionFor = async (adapter, conversationUuid, agentName) => {
13700
14225
  const existing = live.get(adapter.id);
13701
- if (existing && existing.conversationUuid === conversationUuid && existing.alive) return existing;
14226
+ if (existing && existing.conversationUuid === conversationUuid && existing.agentName === agentName && existing.alive) return existing;
13702
14227
  if (existing) {
13703
14228
  live.delete(adapter.id);
13704
14229
  await existing.close();
@@ -13706,7 +14231,8 @@ async function runAgentServe(deps) {
13706
14231
  const session = adapter.open({
13707
14232
  conversationUuid,
13708
14233
  resumeRef: deps.sessions.get(conversationUuid, adapter.id),
13709
- textMaxCharacters: limits.textMaxCharacters
14234
+ textMaxCharacters: limits.textMaxCharacters,
14235
+ ...agentName ? { agentName } : {}
13710
14236
  });
13711
14237
  live.set(adapter.id, session);
13712
14238
  return session;
@@ -13720,18 +14246,19 @@ async function runAgentServe(deps) {
13720
14246
  let failure2;
13721
14247
  try {
13722
14248
  try {
13723
- session = adapter ? await sessionFor(adapter, offer.conversationUuid) : void 0;
14249
+ session = adapter ? await sessionFor(adapter, offer.conversationUuid, offer.agentName) : void 0;
13724
14250
  } finally {
13725
14251
  deps.log.write({
13726
14252
  event: "agent_request",
13727
14253
  turnUuid: offer.turnUuid,
14254
+ todoId: offer.todoId,
13728
14255
  agent: offer.agent,
13729
14256
  conversationUuid: offer.conversationUuid,
13730
14257
  pid: session?.pid ?? -1,
13731
14258
  textLength: offer.text.length
13732
14259
  });
13733
14260
  }
13734
- if (stopping.has(offer.turnUuid)) {
14261
+ if (stopping.has(offer.key)) {
13735
14262
  reply = stoppedReply(void 0, limits);
13736
14263
  return reply;
13737
14264
  }
@@ -13745,7 +14272,7 @@ async function runAgentServe(deps) {
13745
14272
  };
13746
14273
  return reply;
13747
14274
  }
13748
- current = { turnUuid: offer.turnUuid, session };
14275
+ current = { key: offer.key, session };
13749
14276
  try {
13750
14277
  outcome = await session.send(agentPromptText(offer.text, offer.context), deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
13751
14278
  } finally {
@@ -13761,7 +14288,7 @@ async function runAgentServe(deps) {
13761
14288
  } else if (session.sessionRef) {
13762
14289
  await deps.sessions.set(offer.conversationUuid, adapter.id, session.sessionRef);
13763
14290
  }
13764
- reply = stopping.has(offer.turnUuid) ? stoppedReply(outcome, limits) : replyForOutcome(outcome, limits, adapter.displayName);
14291
+ reply = stopping.has(offer.key) ? stoppedReply(outcome, limits) : replyForOutcome(outcome, limits, adapter.displayName);
13765
14292
  return reply;
13766
14293
  } catch (error) {
13767
14294
  failure2 = error instanceof Error ? error.message : String(error);
@@ -13772,6 +14299,7 @@ async function runAgentServe(deps) {
13772
14299
  deps.log.write({
13773
14300
  event: "agent_response",
13774
14301
  turnUuid: offer.turnUuid,
14302
+ todoId: offer.todoId,
13775
14303
  agent: offer.agent,
13776
14304
  ms: Date.now() - started,
13777
14305
  outcome: outcome?.kind ?? `error: ${failure2 ?? "unknown"}`,
@@ -13814,21 +14342,120 @@ async function runAgentServe(deps) {
13814
14342
  }
13815
14343
  }
13816
14344
  };
14345
+ const runTodoJob = async (job) => {
14346
+ const t = todos;
14347
+ const { claimed, identity } = job;
14348
+ const runs = t.runs;
14349
+ let outcome;
14350
+ try {
14351
+ outcome = await runTodo({
14352
+ tools: toolsAs(t.tools, identity),
14353
+ ...runs ? { runs: {
14354
+ started: (cardUuid, workId) => runs.started(cardUuid, workId, identity.agent),
14355
+ finished: (cardUuid) => runs.finished(cardUuid)
14356
+ } } : {},
14357
+ log: deps.log,
14358
+ textMaxCharacters: limits.textMaxCharacters,
14359
+ signal: stopController.signal,
14360
+ runAgent: ({ todoId, conversationUuid, text }) => runTurn({ key: todoKey(todoId), todoId, conversationUuid, agent: identity.agent, text, agentName: identity.name })
14361
+ }, job.todo);
14362
+ } catch {
14363
+ } finally {
14364
+ job.lease?.stop();
14365
+ }
14366
+ if (claimed && (stopReason || outcome === "stopped")) {
14367
+ await closeTodo(toolsAs(t.tools, identity), deps.log, claimed, "release");
14368
+ } else if (claimed && outcome !== void 0 && claimed.todo.kind === "DECISION_ANSWERED") {
14369
+ await closeTodo(toolsAs(t.tools, identity), deps.log, claimed, "complete", TODO_NOTES[outcome]);
14370
+ }
14371
+ todoInFlight = void 0;
14372
+ wakeTodos?.();
14373
+ };
13817
14374
  const worker = (async () => {
13818
14375
  while (!stopReason) {
13819
- const offer = queue.shift();
13820
- if (!offer) {
14376
+ const job = queue.shift();
14377
+ if (!job) {
13821
14378
  await new Promise((resolve4) => {
13822
14379
  wakeWorker = resolve4;
13823
14380
  });
13824
14381
  wakeWorker = void 0;
13825
14382
  continue;
13826
14383
  }
13827
- const reply = await runTurn(offer);
13828
- if (!stopReason) await sendReply(offer, reply);
14384
+ if (job.kind === "todo") {
14385
+ await runTodoJob(job);
14386
+ continue;
14387
+ }
14388
+ const reply = await runTurn({ key: job.offer.turnUuid, ...job.offer });
14389
+ if (!stopReason) await sendReply(job.offer, reply);
13829
14390
  }
13830
14391
  })();
13831
- await Promise.allSettled([pollLoop, worker]);
14392
+ const takeTodo = async (identity) => {
14393
+ const tools = toolsAs(todos.tools, identity);
14394
+ let after;
14395
+ do {
14396
+ const page = todosIn(await tools.call(
14397
+ "list_agent_todos",
14398
+ { state: ["OPEN"], kinds: [...TODO_KINDS], agent: identity.agentUuid, ...after ? { after } : {} }
14399
+ ));
14400
+ for (const todo of page.items) {
14401
+ if (stopReason) return false;
14402
+ const claimed = await claimTodo(tools, deps.log, todo);
14403
+ if (!claimed) continue;
14404
+ todoInFlight = todo.cardUuid;
14405
+ const lease = keepLease(tools, deps.log, claimed, () => requestStop(todoKey(todo.todoId)));
14406
+ queue.push({ kind: "todo", todo, identity, claimed, lease });
14407
+ wakeWorker?.();
14408
+ return true;
14409
+ }
14410
+ after = page.next;
14411
+ } while (after && !stopReason);
14412
+ return false;
14413
+ };
14414
+ const todoLoop = (async () => {
14415
+ if (!todos) return;
14416
+ let resumes = [];
14417
+ try {
14418
+ resumes = todos.runs ? (await todos.runs.load()).flatMap((entry) => {
14419
+ const identity = todos.identities.find((i) => i.agent === (entry.agent ?? todos.identities[0]?.agent));
14420
+ return identity ? [{ todo: resumeTodo(entry), identity }] : [];
14421
+ }) : [];
14422
+ } catch {
14423
+ }
14424
+ let turn = 0;
14425
+ while (!stopReason) {
14426
+ if (!todoInFlight) {
14427
+ const resume = resumes.shift();
14428
+ if (resume) {
14429
+ todoInFlight = resume.todo.cardUuid;
14430
+ queue.push({ kind: "todo", todo: resume.todo, identity: resume.identity });
14431
+ wakeWorker?.();
14432
+ } else {
14433
+ for (let i = 0; i < todos.identities.length && !stopReason; i += 1) {
14434
+ const identity = todos.identities[(turn + i) % todos.identities.length];
14435
+ try {
14436
+ if (await takeTodo(identity)) {
14437
+ turn = (turn + i + 1) % todos.identities.length;
14438
+ break;
14439
+ }
14440
+ } catch {
14441
+ }
14442
+ }
14443
+ }
14444
+ }
14445
+ if (stopReason) return;
14446
+ await new Promise((resolve4) => {
14447
+ wakeTodos = resolve4;
14448
+ void sleep(limits.pollHoldSeconds * 1e3, stopController.signal).then(resolve4);
14449
+ });
14450
+ wakeTodos = void 0;
14451
+ }
14452
+ })();
14453
+ await Promise.allSettled([pollLoop, worker, todoLoop]);
14454
+ for (const job of queue.splice(0)) {
14455
+ if (job.kind !== "todo" || !job.claimed) continue;
14456
+ job.lease?.stop();
14457
+ await closeTodo(toolsAs(todos.tools, job.identity), deps.log, job.claimed, "release");
14458
+ }
13832
14459
  deps.signal.removeEventListener("abort", onUserStop);
13833
14460
  await Promise.all([...live.values()].map((session) => session.close()));
13834
14461
  if (stopReason === "signal") {
@@ -13839,6 +14466,9 @@ async function runAgentServe(deps) {
13839
14466
  }
13840
14467
  return { exitCode: exitCode2, reason: stopReason ?? "unknown" };
13841
14468
  }
14469
+ function jobKey(job) {
14470
+ return job.kind === "chat" ? job.offer.turnUuid : todoKey(job.todo.todoId);
14471
+ }
13842
14472
  function serverLimits(value) {
13843
14473
  const v = value ?? {};
13844
14474
  const num = (key) => {
@@ -13850,16 +14480,50 @@ function serverLimits(value) {
13850
14480
  };
13851
14481
  return { pollHoldSeconds: num("pollHoldSeconds"), textMaxCharacters: num("textMaxCharacters"), documentsMax: num("documentsMax") };
13852
14482
  }
13853
- async function openLink(deps) {
13854
- const base = { hostName: deps.hostName, cliVersion: deps.cliVersion, agents: deps.agents };
13855
- try {
13856
- return await deps.http.call("open", { ...base, features: [...PC_FEATURES] });
13857
- } catch (error) {
13858
- if (!(error instanceof AgentCallError) || error.status !== 400 || error.code !== "INVALID") throw error;
13859
- deps.log.write({ event: "open_without_features", features: [...PC_FEATURES] });
13860
- return await deps.http.call("open", base);
14483
+ async function openLink(deps, agents) {
14484
+ const base = { hostName: deps.hostName, cliVersion: deps.cliVersion };
14485
+ const named = agents.some((a) => a.name !== void 0);
14486
+ const unnamed = agents.map(({ name: _name, ...rest }) => rest);
14487
+ const features = pcFeatures(deps.todos !== void 0);
14488
+ const older = features.filter((f) => f !== "todos");
14489
+ const attempts = [
14490
+ { body: { ...base, agents, features } },
14491
+ ...older.length < features.length ? [{ body: { ...base, agents, features: older }, dropped: "features.todos" }] : [],
14492
+ ...named ? [{ body: { ...base, agents: unnamed, features: older }, dropped: "agents.name" }] : [],
14493
+ { body: { ...base, agents: unnamed }, dropped: "features" }
14494
+ ];
14495
+ for (let i = 0; ; i += 1) {
14496
+ const attempt = attempts[i];
14497
+ if (attempt.dropped) deps.log.write({ event: "open_without_features", features: [attempt.dropped] });
14498
+ try {
14499
+ return await deps.http.call("open", attempt.body);
14500
+ } catch (error) {
14501
+ const old = error instanceof AgentCallError && error.status === 400 && error.code === "INVALID";
14502
+ if (!old || i === attempts.length - 1) throw error;
14503
+ }
13861
14504
  }
13862
14505
  }
14506
+ function folderKind(agents) {
14507
+ return agents.find((a) => a.ready && a.id === DEFAULT_AGENT)?.id ?? agents.find((a) => a.ready)?.id;
14508
+ }
14509
+ function openAgentsBody(agents, folderName) {
14510
+ const kind = folderName ? folderKind(agents) : void 0;
14511
+ return agents.map((a) => ({ id: a.id, ready: a.ready, ...a.auth ? { auth: a.auth } : {}, ...a.id === kind ? { name: folderName } : {} }));
14512
+ }
14513
+ function identitiesIn(value, adapters) {
14514
+ const identities = [];
14515
+ const refused = [];
14516
+ for (const raw of Array.isArray(value) ? value : []) {
14517
+ const a = raw ?? {};
14518
+ if (!isAgentId(a.id) || !adapters.has(a.id)) continue;
14519
+ if (typeof a.agentUuid === "string" && typeof a.name === "string") {
14520
+ identities.push({ agent: a.id, agentUuid: a.agentUuid, name: a.name });
14521
+ } else if (typeof a.error === "string") {
14522
+ refused.push({ agent: a.id, error: a.error });
14523
+ }
14524
+ }
14525
+ return { identities, refused };
14526
+ }
13863
14527
  function stopsIn(res) {
13864
14528
  return Array.isArray(res.stops) ? res.stops.filter((t) => typeof t === "string") : [];
13865
14529
  }
@@ -13893,7 +14557,7 @@ function sleep(ms, signal) {
13893
14557
  }
13894
14558
 
13895
14559
  // src/core/agent/sessions.ts
13896
- import { readFile as readFile9, rename as rename6, writeFile as writeFile6 } from "fs/promises";
14560
+ import { readFile as readFile10, rename as rename7, writeFile as writeFile7 } from "fs/promises";
13897
14561
  var AgentSessionMap = class {
13898
14562
  constructor(path) {
13899
14563
  this.path = path;
@@ -13902,7 +14566,7 @@ var AgentSessionMap = class {
13902
14566
  map = emptyMap();
13903
14567
  async load() {
13904
14568
  try {
13905
- const parsed = JSON.parse(await readFile9(this.path, "utf8"));
14569
+ const parsed = JSON.parse(await readFile10(this.path, "utf8"));
13906
14570
  const map = emptyMap();
13907
14571
  map[DEFAULT_AGENT] = entries(parsed.conversations);
13908
14572
  const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
@@ -13929,13 +14593,13 @@ var AgentSessionMap = class {
13929
14593
  async save() {
13930
14594
  const byAgent = Object.fromEntries(AGENT_IDS.filter((id) => id !== DEFAULT_AGENT).map((id) => [id, this.map[id]]));
13931
14595
  const tmp = `${this.path}.tmp`;
13932
- await writeFile6(
14596
+ await writeFile7(
13933
14597
  tmp,
13934
14598
  `${JSON.stringify({ version: 2, conversations: this.map[DEFAULT_AGENT], byAgent }, null, 2)}
13935
14599
  `,
13936
14600
  { mode: PRIVATE_FILE_MODE }
13937
14601
  );
13938
- await rename6(tmp, this.path);
14602
+ await rename7(tmp, this.path);
13939
14603
  }
13940
14604
  };
13941
14605
  function emptyMap() {
@@ -13955,7 +14619,7 @@ function entries(value) {
13955
14619
 
13956
14620
  // src/adapters/cli/agentCommand.ts
13957
14621
  var AGENT_HELP_LINES = [
13958
- " ainecto agent serve [--env prod|dev] answer \xABMy agent\xBB requests from AiNecto Chat with Claude Code or Codex on this machine (Ctrl+C to stop; log: ~/.ainecto/agent/agent.log)"
14622
+ " ainecto agent serve [--env prod|dev] answer \xABMy agent\xBB requests from AiNecto Chat with Claude Code or Codex on this machine, and run the auto-run cards handed to them (name one: ainecto init --agent NAME) (Ctrl+C to stop; log: ~/.ainecto/agent/agent.log)"
13959
14623
  ];
13960
14624
  function isAgentCommand(domain, action) {
13961
14625
  return domain === "agent" && action === "serve";
@@ -13967,32 +14631,24 @@ async function executeAgentServe(input) {
13967
14631
  await ensurePrivateDir(paths.work);
13968
14632
  const log = openAgentLog(paths);
13969
14633
  const host = hostname();
13970
- const rpc = new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli" });
13971
- const started = Date.now();
13972
- log.write({ event: "agent_call", callId: `tools-list-${started}`, op: "tools_list", bytes: 0 });
13973
- let writeTools;
13974
- try {
13975
- writeTools = writeToolNames(await rpc.toolsList());
13976
- log.write({ event: "agent_call_response", callId: `tools-list-${started}`, op: "tools_list", ok: true, ms: Date.now() - started });
13977
- } catch (error) {
13978
- log.write({
13979
- event: "agent_call_response",
13980
- callId: `tools-list-${started}`,
13981
- op: "tools_list",
13982
- ok: false,
13983
- error: error instanceof Error ? error.message : String(error),
13984
- ms: Date.now() - started
13985
- });
13986
- throw error;
13987
- }
14634
+ const client = (agentName) => new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli", ...agentName ? { agentName } : {} });
14635
+ const tools = createAgentTools({
14636
+ client: client(),
14637
+ clientAs: (identity) => {
14638
+ const as = client(identity.name);
14639
+ as.useAgent(AGENT_MCP_CLIENT_NAMES[identity.agent]);
14640
+ return as;
14641
+ },
14642
+ log
14643
+ });
14644
+ const writeTools = writeToolNames(await tools.list());
13988
14645
  const cliScript = process.argv[1];
13989
14646
  if (!cliScript) throw new Error("Cannot find the path of this CLI to start the AiNecto bridge for the agents.");
13990
- const bridge = ainectoBridge(process.execPath, cliScript, input.endpoint);
14647
+ const bridge = (agentName) => ainectoBridge(process.execPath, cliScript, input.endpoint, agentName);
13991
14648
  const shared = { spawnImpl: spawnAgent, cwd: paths.work, env: agentEnv(process.env), log, writeTools };
13992
- const mcpConfig = claudeMcpConfig(bridge);
13993
14649
  const all = [
13994
- claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig, resumeSessionId }) }),
13995
- codexAdapter({ ...shared, appServerArgs: codexAppServerArgs(bridge, writeTools), clientVersion: CLI_VERSION })
14650
+ claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId, agentName }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig: claudeMcpConfig(bridge(agentName)), resumeSessionId }) }),
14651
+ codexAdapter({ ...shared, appServerArgs: (agentName) => codexAppServerArgs(bridge(agentName), writeTools), clientVersion: CLI_VERSION })
13996
14652
  ];
13997
14653
  const checks = await checkAgents(all, log);
13998
14654
  log.write({
@@ -14037,7 +14693,8 @@ async function executeAgentServe(input) {
14037
14693
  cliVersion: CLI_VERSION,
14038
14694
  print: (line) => input.io.stderr.write(`${line}
14039
14695
  `),
14040
- signal: controller.signal
14696
+ signal: controller.signal,
14697
+ todos: { tools, agentName: input.agentName, runs: new AgentRunLog(paths.runs, log) }
14041
14698
  });
14042
14699
  log.write({ event: "serve_stop", pid: process.pid, reason: result.reason });
14043
14700
  return result.exitCode;
@@ -14167,7 +14824,7 @@ async function runAinectoCli(argv, io) {
14167
14824
  });
14168
14825
  }
14169
14826
  if (isAgentCommand(domain, action)) {
14170
- return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io });
14827
+ return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io, agentName });
14171
14828
  }
14172
14829
  if (domain === "auth") {
14173
14830
  return await handleAuth(action, connect2().auth, resolved.endpoint, parsed.json, io);