aiterm-mcp 0.62.5 → 0.63.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.
@@ -271,7 +271,7 @@ export function windowsAgentLaunchLine(cwd, env, argv, exited) {
271
271
  for (const [name, value] of env) {
272
272
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
273
273
  throw new AitermError("環境変数名が不正です", 2);
274
- parts.push(`$env:${name}=${psq(value)}`);
274
+ parts.push(value === null ? `Remove-Item -LiteralPath 'Env:${name}' -ErrorAction SilentlyContinue` : `$env:${name}=${psq(value)}`);
275
275
  }
276
276
  parts.push(`& ${argv.map(psq).join(" ")}`);
277
277
  const command = parts.join("; ");
@@ -253,6 +253,67 @@ export function agentMetadataPath(name, launchId) {
253
253
  throw new AitermError(`launch_id が不正です: ${launchId}`, 2);
254
254
  return path.join(agentsDir(), `${name}.${launchId}.agent.json`);
255
255
  }
256
+ const generationPath = (name) => {
257
+ assertSessionName(name);
258
+ return path.join(agentsDir(), `${name}.active-launch.json`);
259
+ };
260
+ export function readAgentGeneration(name) {
261
+ let body;
262
+ try {
263
+ body = fs.readFileSync(generationPath(name), "utf8");
264
+ }
265
+ catch (error) {
266
+ if (error.code === "ENOENT")
267
+ return null;
268
+ throw error;
269
+ }
270
+ try {
271
+ const value = JSON.parse(body);
272
+ if (value.schema !== "aiterm.agent-generation.v1" || typeof value.launch_id !== "string" || !LAUNCH_ID_RE.test(value.launch_id)
273
+ || !(value.previous_launch_id === null || (typeof value.previous_launch_id === "string" && LAUNCH_ID_RE.test(value.previous_launch_id)))
274
+ || value.previous_launch_id === value.launch_id)
275
+ throw new Error();
276
+ return value;
277
+ }
278
+ catch {
279
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動世代を確認できません。", 2);
280
+ }
281
+ }
282
+ /** No pointer changes until a complete per-launch metadata record is durable. Caller owns seat admission. */
283
+ export function publishAgentGeneration(previous, next = previous) {
284
+ const name = previous.aiterm_session, current = readAgentGeneration(name);
285
+ if (current && current.launch_id !== previous.launch_id)
286
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 起動世代が置き換わっています。", 2);
287
+ if (!current) {
288
+ const files = fs.readdirSync(agentsDir()).filter(file => file.startsWith(name + ".") && file.endsWith(".agent.json"));
289
+ if (files.length !== 1 || files[0] !== path.basename(agentMetadataPath(name, previous.launch_id)))
290
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 元の起動世代を特定できません。", 2);
291
+ }
292
+ const source = JSON.parse(fs.readFileSync(agentMetadataPath(name, previous.launch_id), "utf8"));
293
+ const stored = JSON.parse(fs.readFileSync(agentMetadataPath(name, next.launch_id), "utf8"));
294
+ if (source.launch_id !== previous.launch_id || source.aiterm_session !== name || source.kind !== previous.kind
295
+ || source.vendor_session_id !== previous.vendor_session_id || next.aiterm_session !== name || stored.aiterm_session !== name || stored.launch_id !== next.launch_id
296
+ || stored.kind !== previous.kind || stored.kind !== next.kind || stored.vendor_session_id !== previous.vendor_session_id
297
+ || stored.vendor_session_id !== next.vendor_session_id
298
+ || ["parent_session_id", "delegation_depth", "lineage"].some(field => stored[field] !== source[field])
299
+ || (next.launch_id !== previous.launch_id && (stored.resumed_from !== previous.launch_id || next.resumed_from !== previous.launch_id)))
300
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 復帰先が元の会話と一致しません。", 2);
301
+ writeJson0600(generationPath(name), { schema: "aiterm.agent-generation.v1", launch_id: next.launch_id,
302
+ previous_launch_id: next.launch_id === previous.launch_id ? current?.previous_launch_id ?? previous.resumed_from ?? null : previous.launch_id });
303
+ }
304
+ /** A staged second generation is invisible until publication; missing/broken pointers never fall back. */
305
+ export function selectAgentMetadataFile(name, files) {
306
+ const current = readAgentGeneration(name);
307
+ if (current) {
308
+ const selected = path.basename(agentMetadataPath(name, current.launch_id));
309
+ if (files.includes(selected))
310
+ return selected;
311
+ throw new AitermError("AGENT_RESUME_UNCONFIRMED: 現在の起動記録がありません。", 2);
312
+ }
313
+ if (files.length !== 1)
314
+ throw new AitermError(`session '${name}' の agent metadata が複数あります。閉じて起動し直してください。`, 2);
315
+ return files[0];
316
+ }
256
317
  export function agentWaitLockPath(name, launchId) {
257
318
  assertSessionName(name);
258
319
  if (!LAUNCH_ID_RE.test(launchId))
@@ -20,14 +20,20 @@ export function parseArgs(argv) {
20
20
  let timeout = null;
21
21
  let cursor = null;
22
22
  let steer = null;
23
+ let expectedLaunchId;
23
24
  for (let i = 0; i < argv.length; i++) {
24
25
  const a = argv[i];
25
- if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer") {
26
+ if (a === "--session" || a === "--operation" || a === "--timeout" || a === "--cursor" || a === "--steer" || a === "--launch") {
26
27
  const v = argv[i + 1];
27
28
  if (v === undefined)
28
29
  throw new Error(`${a} に値がありません。${USAGE}`);
29
30
  i++;
30
- if (a === "--session") {
31
+ if (a === "--launch") {
32
+ if (expectedLaunchId !== undefined || !/^[0-9a-f]{32}$/.test(v))
33
+ throw new Error(`--launch が不正又は重複しています。${USAGE}`);
34
+ expectedLaunchId = v;
35
+ }
36
+ else if (a === "--session") {
31
37
  if (session !== null)
32
38
  throw new Error(`--session が重複しています。${USAGE}`);
33
39
  if (!SESSION_RE.test(v))
@@ -73,7 +79,7 @@ export function parseArgs(argv) {
73
79
  throw new Error(`--session は必須です。${USAGE}`);
74
80
  if (steer !== null && operationId !== null)
75
81
  throw new Error(`--steer は --operation と併用できません。${USAGE}`);
76
- return { session, operationId, timeout: timeout ?? 600, cursor, steer };
82
+ return { session, operationId, timeout: timeout ?? 600, cursor, steer, ...(expectedLaunchId ? { expectedLaunchId } : {}) };
77
83
  }
78
84
  function emit(value) {
79
85
  process.stdout.write(JSON.stringify(value) + "\n");
@@ -99,13 +105,14 @@ export async function main(argv) {
99
105
  timeout: cmd.timeout,
100
106
  cursor: cmd.cursor,
101
107
  steer: cmd.steer,
108
+ expected_launch_id: cmd.expectedLaunchId,
102
109
  });
103
110
  }
104
111
  catch (e) {
105
112
  // Grok は利用上限に達すると auth 正本を自壊させることがあり(2026-08-22 実測)、
106
113
  // metadata検証が認証不在で止まる。現在のviewportに上限パネルがある場合だけ
107
114
  // rate_limitedとして返し、古いlogで現在の認証エラーを置き換えない。
108
- if (e instanceof AitermError && /Grok 認証正本/.test(e.message)) {
115
+ if (!cmd.expectedLaunchId && e instanceof AitermError && /Grok 認証正本/.test(e.message)) {
109
116
  const limited = detectAgentRateLimit("grok", cmd.session);
110
117
  if (limited) {
111
118
  emit({
@@ -3,6 +3,8 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { currentUid as uid, runtimeStateBase } from "./state-root.js";
5
5
  import { createHash, randomBytes } from "node:crypto";
6
+ import { requestAgentIdleClock } from "./agent-idle-clock.js";
7
+ import { recordAgentTurnEnd } from "./agent-activity.js";
6
8
  const LAUNCH_ID_RE = /^[0-9a-f]{32}$/;
7
9
  const SESSION_RE = /^[A-Za-z0-9_-]{1,64}$/;
8
10
  import { parseClaudeOperationMarker } from "./claude-operation-marker.js";
@@ -199,6 +201,7 @@ async function main() {
199
201
  result_bytes: resultBytes,
200
202
  text,
201
203
  });
204
+ const endedAt = new Date().toISOString();
202
205
  appendEvent(eventFile, {
203
206
  type: "agent_done",
204
207
  vendor: "claude",
@@ -212,9 +215,17 @@ async function main() {
212
215
  stop_hook_active: !!payload.stop_hook_active,
213
216
  result_digest: resultDigest,
214
217
  result_bytes: resultBytes,
215
- at: new Date().toISOString(),
218
+ at: endedAt,
216
219
  });
220
+ try {
221
+ recordAgentTurnEnd({ aiterm_session: session, launch_id: launchId }, { vendor: "claude",
222
+ vendor_session_id: payload.session_id, turn_id: null, operation_id: operationId, at: endedAt });
223
+ }
224
+ catch {
225
+ process.stderr.write("aiterm: AGENT_ACTIVITY_UNCONFIRMED: 番の終了時刻を保存できません。Stop結果は保存済みです。\n");
226
+ }
217
227
  if (operationMarker)
218
228
  consumeOperationMarker(operationFile, operationMarker);
229
+ requestAgentIdleClock(session, launchId);
219
230
  }
220
231
  main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
@@ -0,0 +1,63 @@
1
+ import { AitermError } from "./errors.js";
2
+ function confirmed(result) {
3
+ return result.availability === "available" && result.readback === "confirmed";
4
+ }
5
+ function goalState(result) {
6
+ if (!confirmed(result))
7
+ return `unknown (${result.reason})`;
8
+ return result.schema === "aiterm.agent-goal-result.v1" ? result.goal?.status ?? "none" : "native v2";
9
+ }
10
+ /** Only a pause owned by this request may be restored; native goal data stays with the CLI. */
11
+ export async function configureWithPausedGoal(runtime, configure) {
12
+ const before = await runtime.goal("inspect");
13
+ if (!confirmed(before) || before.goal === null)
14
+ return configure();
15
+ if (before.schema !== "aiterm.agent-goal-result.v1") {
16
+ throw new AitermError("GOAL_CONFIGURE_UNSUPPORTED: このgoalは一時停止に対応していません。goalを停止または完了にしてから agent_configure してください。設定は変えていません。", 2);
17
+ }
18
+ if (before.goal?.status !== "active")
19
+ return configure();
20
+ const paused = await runtime.goal("pause", before.goal);
21
+ if (!confirmed(paused) || paused.outcome !== "applied" || paused.schema !== "aiterm.agent-goal-result.v1" || paused.goal?.status !== "paused") {
22
+ throw new AitermError(`GOAL_CONFIGURE_PAUSE_UNCONFIRMED: goal=${goalState(paused)} (${paused.reason})。設定は変えていません。goalの状態を確認してから再実行してください。`, 2);
23
+ }
24
+ let value;
25
+ let failure;
26
+ let failed = false;
27
+ let applied = false;
28
+ try {
29
+ await runtime.waitForTurnEnd();
30
+ value = await configure();
31
+ applied = true;
32
+ }
33
+ catch (error) {
34
+ failed = true;
35
+ failure = error;
36
+ }
37
+ let restored = "unknown";
38
+ let resumedSuccessfully = false;
39
+ try {
40
+ const current = await runtime.goal("inspect");
41
+ if (confirmed(current) && current.schema === "aiterm.agent-goal-result.v1" && current.goal?.status === "paused"
42
+ && current.goal.threadId === paused.goal.threadId && current.goal.createdAt === paused.goal.createdAt
43
+ && current.goal.objective === paused.goal.objective && current.goal.tokenBudget === paused.goal.tokenBudget) {
44
+ const resumed = await runtime.goal("resume", current.goal);
45
+ restored = goalState(resumed);
46
+ resumedSuccessfully = confirmed(resumed) && resumed.outcome === "applied" && resumed.schema === "aiterm.agent-goal-result.v1" && resumed.goal?.status === "active";
47
+ }
48
+ else
49
+ restored = goalState(current) + " (goal changed; not resumed)";
50
+ }
51
+ catch (error) {
52
+ restored = `unknown (${error instanceof Error ? error.message : String(error)})`;
53
+ }
54
+ if (resumedSuccessfully) {
55
+ if (!failed)
56
+ return value;
57
+ const error = failure instanceof Error ? failure : new Error(String(failure));
58
+ error.message += " goal=active(一時停止したgoalは再開済み)。";
59
+ throw error;
60
+ }
61
+ throw new AitermError(`GOAL_CONFIGURE_RESTORE_UNCONFIRMED: ${applied ? "設定変更は完了" : "設定変更は未完了"}。goal=${restored}。` +
62
+ (failed ? ` ${failure instanceof Error ? failure.message : String(failure)}` : "") + " goalの状態を確認してください。", 2);
63
+ }