aiterm-mcp 0.70.39 → 0.70.40

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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.70.40] - 2026-11-12
11
+
12
+ - Parallel `agent_goal` `inspect` calls no longer run one at a time or stall the server. Every binding check (`resolve`, run 2-4 times per call) ran `tmux display-message` and the full `ps` table with `spawnSync`, so N inspects arriving together ran serially and blocked the event loop, delivery to every seat included (Kiro, 2026-11-13: BellTeam `GET /api/goals` took 8-17 s with ~25 live seats). These checks now run asynchronously, and checks that arrive together share one `tmux list-panes -a` read and one process table read (`freshShared`: a check only receives a read that began after its call, so no generation check uses an older table). Measured on the BellTeam container's live state, 27 seats (21 Claude, 6 Codex), inspect only: all in parallel 3.5 s → 0.68 s, longest event-loop block 3.1 s → 0.2 s, results identical to 0.70.39 for every seat. The check right before an input effect (`goalUi`) stays synchronous; inside a native target frame and on Windows the pane is read per session (asynchronously).
13
+
10
14
  ## [0.70.39] - 2026-11-12
11
15
 
12
16
  - A Codex goal read or Codex parent delivery no longer times out while the App Server's answer is already waiting. When Aiterm's event loop was blocked past the request deadline (15 s by default), the timer fired before the answer was read and the read failed (`native_goal_connection_unavailable`; Kiro, 2026-11-12, body Aiterm blocked ~16 s by Claude goal reads, which 0.70.34 removed). The timer now waits one turn of the loop and fails only if the request is still pending. Same change in the bundled Steer 0.5.3.
@@ -3372,7 +3376,8 @@ prototype (preserved under `prototype/python/` as the porting source and referen
3372
3376
  `ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
3373
3377
  provenance.
3374
3378
 
3375
- [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.39...HEAD
3379
+ [Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.40...HEAD
3380
+ [0.70.40]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.39...v0.70.40
3376
3381
  [0.70.39]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.38...v0.70.39
3377
3382
  [0.70.38]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.37...v0.70.38
3378
3383
  [0.70.37]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.36...v0.70.37
package/README.ja.md CHANGED
@@ -215,7 +215,7 @@ runtime-error store は canonical dotagents config の `collection.enabled: true
215
215
  場合だけ収集し、既定OFF、network送信は行いません。tag起点CIのnpm provenance(OIDC Trusted
216
216
  Publishing)で公開し、GitHub Release が Official MCP Registry を再登録します。
217
217
 
218
- **状態:** 開発継続中 · 現行公開版 **v0.70.39** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
218
+ **状態:** 開発継続中 · 現行公開版 **v0.70.40** · 動作対象は Linux · WSL2 · macOS · Windows ネイティブ · MIT · [変更履歴](CHANGELOG.md)。
219
219
 
220
220
  ### 更新と巻き戻し
221
221
 
package/README.md CHANGED
@@ -227,7 +227,7 @@ collection is off by default and performs no network I/O. It ships via
227
227
  tag-triggered CI with npm provenance (OIDC Trusted Publishing); the GitHub
228
228
  Release re-registers the Official MCP Registry entry.
229
229
 
230
- **Status:** actively maintained · current public release **v0.70.39** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
230
+ **Status:** actively maintained · current public release **v0.70.40** · runs on Linux · WSL2 · macOS · native Windows (tmux on POSIX, the tmux-CLI-compatible [psmux](https://github.com/psmux/psmux) on native Windows — no WSL required) · MIT · see the [CHANGELOG](CHANGELOG.md).
231
231
 
232
232
  ### Update and rollback
233
233
 
@@ -33,7 +33,7 @@ export async function manageGrokAgentGoal(input, runtime, origin = "automatic")
33
33
  const unavailable = () => { delete result.goal; result.binding = null; result.availability = 'unavailable'; for (const key of Object.keys(result.capabilities))
34
34
  result.capabilities[key] = false; };
35
35
  try {
36
- const target = runtime.resolve();
36
+ const target = await runtime.resolve();
37
37
  if (!target || target.session_id !== input.session_id || target.launch_id !== input.launch_id || target.harness !== 'grok-cli' || !target.vendor_session_id)
38
38
  return result;
39
39
  if (input.expected_thread_id !== undefined && input.expected_thread_id !== target.vendor_session_id)
@@ -45,7 +45,7 @@ export async function manageGrokAgentGoal(input, runtime, origin = "automatic")
45
45
  if (input.action === 'clear' && (input.objective !== undefined || input.token_budget !== undefined))
46
46
  return { ...result, outcome: 'unsupported', reason: 'native_goal_field_unsupported' };
47
47
  const observed = await runtime.read(target);
48
- if (!sameGoalTarget(runtime.resolve(), target))
48
+ if (!sameGoalTarget(await runtime.resolve(), target))
49
49
  return { ...result, reason: 'generation_replaced_after_status', readback: 'failed' };
50
50
  const clearStatus = observed.current?.current_status;
51
51
  // inspect reads the saved state only, so clear there is a candidate; the clear action itself requires the fresh UI status.
@@ -58,7 +58,7 @@ export async function manageGrokAgentGoal(input, runtime, origin = "automatic")
58
58
  return { ...result, outcome: 'rejected', reason: 'goal_missing' };
59
59
  if (!ready)
60
60
  return { ...result, outcome: 'rejected', reason: 'native_goal_clear_input_unconfirmed' };
61
- if (!sameGoalTarget(runtime.resolve(), target)) {
61
+ if (!sameGoalTarget(await runtime.resolve(), target)) {
62
62
  unavailable();
63
63
  return { ...result, outcome: 'unavailable', reason: 'generation_replaced' };
64
64
  }
@@ -74,10 +74,10 @@ export async function manageGrokAgentGoal(input, runtime, origin = "automatic")
74
74
  issued = false;
75
75
  unavailable();
76
76
  try {
77
- if (!sameGoalTarget(runtime.resolve(), target))
77
+ if (!sameGoalTarget(await runtime.resolve(), target))
78
78
  throw Error('generation_replaced');
79
79
  const fresh = await runtime.read(target);
80
- if (!sameGoalTarget(runtime.resolve(), target))
80
+ if (!sameGoalTarget(await runtime.resolve(), target))
81
81
  throw Error('generation_replaced');
82
82
  return { ...result, goal: fresh.current, binding: { session_id: target.session_id, launch_id: target.launch_id, thread_id: target.vendor_session_id }, availability: 'available', capabilities: { ...result.capabilities, inspect: true }, outcome: error.outcome, mutation: 'not_issued', readback: 'confirmed', reason: error.reason };
83
83
  }
@@ -85,10 +85,10 @@ export async function manageGrokAgentGoal(input, runtime, origin = "automatic")
85
85
  return { ...result, outcome: error.outcome, mutation: 'not_issued', readback: 'failed', reason: error.reason };
86
86
  }
87
87
  }
88
- if (!sameGoalTarget(runtime.resolve(), target))
88
+ if (!sameGoalTarget(await runtime.resolve(), target))
89
89
  throw Error('generation_replaced_after_mutation');
90
90
  const after = await runtime.read(target);
91
- if (!sameGoalTarget(runtime.resolve(), target) || after.current !== null)
91
+ if (!sameGoalTarget(await runtime.resolve(), target) || after.current !== null)
92
92
  throw Error('native_goal_clear_readback_unconfirmed');
93
93
  return agentGoalNativeResultSchema.parse({ ...result, goal: null, capabilities: { ...result.capabilities, clear: false }, outcome: 'applied', mutation: 'acknowledged', readback: 'confirmed', reason: 'native_goal_readback_confirmed', observed_at: new Date().toISOString() });
94
94
  }
@@ -105,7 +105,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
105
105
  outcome: "unavailable", mutation: input.action === "inspect" ? "not_requested" : "not_issued", readback: "not_attempted", reason: "binding_unavailable", observed_at: new Date().toISOString() };
106
106
  let issued = false;
107
107
  try {
108
- const target = runtime.resolve();
108
+ const target = await runtime.resolve();
109
109
  if (!target || target.session_id !== input.session_id || target.launch_id !== input.launch_id || target.harness !== "claude-code" || !target.vendor_session_id)
110
110
  return result;
111
111
  if (input.expected_thread_id !== undefined && input.expected_thread_id !== target.vendor_session_id)
@@ -115,7 +115,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
115
115
  if (input.action !== "inspect" && origin !== "user")
116
116
  return { ...result, outcome: "rejected", reason: "user_authorization_required" };
117
117
  const observed = await runtime.read(target);
118
- if (!sameGoalTarget(runtime.resolve(), target))
118
+ if (!sameGoalTarget(await runtime.resolve(), target))
119
119
  return { ...result, reason: "generation_replaced_after_status", readback: "failed" };
120
120
  const snapshot = (value) => ({ goal: value.current, ...(value.history ? { native_history: value.history } : {}) });
121
121
  Object.assign(result, { availability: "available", capabilities: { ...result.capabilities, inspect: true, clear: !!runtime.clear, create: !!runtime.setObjective, edit: !!runtime.setObjective },
@@ -130,7 +130,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
130
130
  return { ...result, outcome: "rejected", reason: "goal_already_exists" };
131
131
  if (input.action === "edit" && observed.current === null)
132
132
  return { ...result, outcome: "rejected", reason: "goal_missing" };
133
- if (!sameGoalTarget(runtime.resolve(), target))
133
+ if (!sameGoalTarget(await runtime.resolve(), target))
134
134
  return { ...result, availability: "unavailable", outcome: "unavailable", reason: "generation_replaced" };
135
135
  issued = true;
136
136
  delete result.goal;
@@ -148,7 +148,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
148
148
  issued = false;
149
149
  try {
150
150
  const fresh = await runtime.read(target);
151
- if (!sameGoalTarget(runtime.resolve(), target))
151
+ if (!sameGoalTarget(await runtime.resolve(), target))
152
152
  throw new Error("generation_replaced");
153
153
  return { ...result, ...snapshot(fresh), outcome: error.outcome, mutation: "not_issued", readback: "confirmed", reason: error.reason };
154
154
  }
@@ -156,7 +156,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
156
156
  return { ...result, outcome: error.outcome, mutation: "not_issued", readback: "failed", reason: error.reason };
157
157
  }
158
158
  }
159
- if (!sameGoalTarget(runtime.resolve(), target))
159
+ if (!sameGoalTarget(await runtime.resolve(), target))
160
160
  throw new Error("generation_replaced_after_mutation");
161
161
  const matched = (after) => input.action === "clear" ? after.current === null && (observed.current === null || (after.history?.terminal === "cleared" && after.history.native.condition === observed.current.native.condition)) : after.current?.phase === "active" && after.current.native.condition === input.objective;
162
162
  // Claude appends the new goal_status row shortly after it takes the command.
@@ -166,7 +166,7 @@ export async function manageClaudeAgentGoal(input, runtime, origin = "automatic"
166
166
  await pause(50);
167
167
  after = await runtime.read(target);
168
168
  }
169
- if (!sameGoalTarget(runtime.resolve(), target))
169
+ if (!sameGoalTarget(await runtime.resolve(), target))
170
170
  throw new Error("generation_replaced_after_readback");
171
171
  const matches = matched(after);
172
172
  return agentGoalNativeResultSchema.parse({ ...result, ...snapshot(after), mutation: matches ? "acknowledged" : "outcome_unknown", outcome: matches ? "applied" : "outcome_unknown", readback: matches ? "confirmed" : "mismatch", reason: matches ? "native_goal_readback_confirmed" : "native_goal_changed_before_readback", observed_at: new Date().toISOString() });
@@ -88,12 +88,12 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
88
88
  readback: "not_attempted", reason: "binding_unavailable", observed_at: new Date().toISOString() };
89
89
  let target;
90
90
  try {
91
- target = runtime.resolve();
91
+ target = await runtime.resolve();
92
92
  }
93
93
  catch {
94
94
  return result;
95
95
  }
96
- const same = () => sameGoalTarget(runtime.resolve(), target);
96
+ const same = async () => sameGoalTarget(await runtime.resolve(), target);
97
97
  if (!target || target.session_id !== input.session_id || target.launch_id !== input.launch_id)
98
98
  return result;
99
99
  result.harness = target.harness;
@@ -113,10 +113,10 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
113
113
  throw new Error("goal_thread_mismatch");
114
114
  return value.goal;
115
115
  };
116
- if (!same())
116
+ if (!(await same()))
117
117
  return { ...result, reason: "generation_replaced" };
118
118
  const before = await read();
119
- if (!same())
119
+ if (!(await same()))
120
120
  return { ...result, reason: "generation_replaced" };
121
121
  Object.assign(result, { availability: "available", capabilities: supported, goal: before,
122
122
  binding: { session_id: target.session_id, launch_id: target.launch_id, thread_id: threadId },
@@ -152,7 +152,7 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
152
152
  return reject("pause_requires_active_goal");
153
153
  if (runtime.beforeMutation && !runtime.beforeMutation(before))
154
154
  return reject("goal_changed_before_mutation");
155
- if (!same())
155
+ if (!(await same()))
156
156
  return { ...result, availability: "unavailable", outcome: "unavailable", reason: "generation_replaced" };
157
157
  const method = input.action === "clear" ? "thread/goal/clear" : "thread/goal/set";
158
158
  const params = { threadId, origin };
@@ -179,7 +179,7 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
179
179
  // UI preparation may have taken time. Do not restore a stale snapshot.
180
180
  try {
181
181
  const current = await read();
182
- if (!same())
182
+ if (!(await same()))
183
183
  throw new Error("generation_replaced");
184
184
  return { ...result, goal: current, outcome: error.outcome, readback: "confirmed", reason: error.reason };
185
185
  }
@@ -195,11 +195,11 @@ export async function manageAgentGoal(input, runtime, origin = "automatic") {
195
195
  throw new Error("goal_thread_mismatch");
196
196
  }
197
197
  result.mutation = "acknowledged";
198
- if (!same())
198
+ if (!(await same()))
199
199
  return { ...result, outcome: "outcome_unknown", readback: "failed", reason: "generation_replaced_after_mutation" };
200
200
  try {
201
201
  const after = await read();
202
- if (!same())
202
+ if (!(await same()))
203
203
  return { ...result, outcome: "outcome_unknown", readback: "failed", reason: "generation_replaced_after_readback" };
204
204
  result.goal = after;
205
205
  const matches = input.action === "clear" ? after === null : after !== null
package/dist/core.js CHANGED
@@ -51,12 +51,12 @@ import { isCursorMcpClient } from "aiterm-steer-delivery";
51
51
  import { antigravityBinding, antigravityAuthChoiceKey, antigravityCurrentModel, antigravityStartupAction, antigravityAgentArgv, writeAntigravityCallerFiles, checkAntigravityCallerInput, antigravityPromptWithCaller, antigravityQuotaLimit, antigravityModelChoices, antigravityAuthStatus, antigravityAuthPane, antigravityTranscriptText, bindAntigravitySession, createAntigravityAgentMetadata, mergeAntigravityHooks } from "./harnesses/antigravity.js";
52
52
  import { paneTokenHint } from "./harnesses/pane-tokens.js";
53
53
  import { unfinishedDeliveriesOwnedBy } from "./parent-delivery-owners.js";
54
- import { readLinuxProcessRegistrationIdentity, readClaudeRegistrationIdentity, readProcessEnvironment, readRuntimeProcesses, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
54
+ import { readLinuxProcessRegistrationIdentity, readClaudeRegistrationIdentity, readProcessEnvironment, readRuntimeProcesses, readRuntimeProcessesShared, readProcessIdentities, processSubtree, parentProcess, processIdentity, signalRuntimeProcess, backgroundProcesses, lazyRelayProcess, aitermProcessProbe, windowsConsoleHost, macKeepAwakeProcess, processElapsedSeconds } from "./process-runtime.js";
55
55
  import { liveNodeExecutable } from "./live-node.js";
56
56
  import { resolveClaudeConfigurationRoot, withClaudeConfigRoot, withClaudeSlotLogin } from "./claude-config-root.js";
57
57
  import { probeWriteBan, writeBanPrefix, windowsWriteBanArgv } from "./write-ban.js";
58
58
  import { AitermError, launchAuthRequired, launchInputRefusal, launchStartupBlocked, AgentResumeUnavailableError, AgentResumeError, telemetryOwnedFailure, ownTelemetryFailure } from "./errors.js";
59
- import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, } from "./tmux-runtime.js";
59
+ import { isWin, SOCKDIR, SOCK, tmuxCommand, readOnlyTmuxList, PtyDiagnosticError, tmuxCommandWithInput, sendPsmuxPayload, loadPtyBufferChunk, pasteBufferBaseArgs, tmuxNewSession, withNativeSessionCreation, withNativeSessionTarget, hasVerifiedNativeSessionTarget, withNativeSessionSetupRollback, hasNativeSessionSetupRollback, registeredSessionEnvironment, registerSessionEnvironment, attachCommand, normalizePaneCommand, atomicShellMultiline, appendMarkSentinel, paneShellForSubmission, adaptShellSubmission, settlePaneLog, paneCwdArgument, sessionEnvironmentLaunch, paneCommandArgs, rememberPaneShell, sessionPaneAsync, } from "./tmux-runtime.js";
60
60
  import { AGENT_DEFAULT_PREFACE, sleep, currentUid, runtimeStateBase, safeStatSize, readFileRange, writeJson0600, writeText0600, createEmpty0600, shq, LAUNCH_ID_RE, AGENT_LINEAGE_RE, AGENT_DONE_POLL_MS, AGENT_RATE_LIMIT_POLL_MS, pollGate, AGENT_EVENT_MAX_BYTES, assertSessionName, agentsDir, readAgentGeneration, selectAgentMetadataFile, publishAgentGeneration, agentMetadataPath, writeAgentMetadata, AGENT_EVENT_TAIL_BYTES, agentLabel, agentHarness, } from "./agent-shared.js";
61
61
  import { AuthResponseError, authUi, authPromptDigest, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
62
62
  import { processStartIdentity } from "./runtime-error-os.js";
@@ -6047,18 +6047,31 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6047
6047
  assertSessionName(input.session_id);
6048
6048
  if (input.action !== "inspect")
6049
6049
  assertExecutionContext(input.session_id);
6050
+ // Goal binding needs a live native process, not screen/CPU/activity collection.
6051
+ const panePid = (pane) => {
6052
+ if (pane.code !== 0)
6053
+ return null;
6054
+ const fields = pane.stdout.trim().split("\t"), pid = Number(fields[0]);
6055
+ return fields.length !== 2 || !Number.isSafeInteger(pid) || pid < 1 || fields[1] !== "0" ? null : pid;
6056
+ };
6057
+ const paneArgs = ["display-message", "-p", "-t", `=${input.session_id}:`, "#{pane_pid}\t#{pane_dead}"];
6058
+ // Right before an input effect (goalUi check) the binding is read synchronously, inside the admission.
6050
6059
  const resolve = () => {
6051
6060
  const meta = tryLoadAgentMetadata(input.session_id);
6052
6061
  if (meta?.launch_id !== input.launch_id)
6053
6062
  return null;
6054
- // Goal binding needs a live native process, not screen/CPU/activity collection.
6055
- const pane = tmux("display-message", "-p", "-t", `=${input.session_id}:`, "#{pane_pid}\t#{pane_dead}");
6056
- if (pane.code !== 0)
6057
- return null;
6058
- const fields = pane.stdout.trim().split("\t"), pid = Number(fields[0]);
6059
- if (fields.length !== 2 || !Number.isSafeInteger(pid) || pid < 1 || fields[1] !== "0")
6063
+ const pid = panePid(tmux(...paneArgs));
6064
+ return pid === null ? null : bindGoalTarget(meta, pid, readRuntimeProcesses());
6065
+ };
6066
+ // Every other binding check waits without blocking the event loop and shares one process table with the checks that arrive together.
6067
+ const resolveShared = async () => {
6068
+ const meta = tryLoadAgentMetadata(input.session_id);
6069
+ if (meta?.launch_id !== input.launch_id)
6060
6070
  return null;
6061
- const rows = readRuntimeProcesses();
6071
+ const pid = panePid(await sessionPaneAsync(input.session_id));
6072
+ return pid === null ? null : bindGoalTarget(meta, pid, await readRuntimeProcessesShared());
6073
+ };
6074
+ const bindGoalTarget = (meta, pid, rows) => {
6062
6075
  if (!rows.some(row => row.pid === pid))
6063
6076
  return null;
6064
6077
  const candidates = selectHarnessProcesses(meta, rows, processSubtree(rows, pid));
@@ -6240,12 +6253,12 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6240
6253
  };
6241
6254
  return { ui, rows: () => { const text = read('updates.jsonl', true); return text === null ? [] : text.split('\n').filter(line => line.trim()).map(line => JSON.parse(line)); }, state: () => { const text = read('goal/state.json', true); return text === null ? null : JSON.parse(text); } };
6242
6255
  };
6243
- const harness = resolve()?.harness;
6256
+ const harness = (await resolveShared())?.harness;
6244
6257
  if (sendHeld && harness !== "codex-cli")
6245
6258
  throw new ExecutionError("EXECUTION_STALE_GENERATION");
6246
6259
  if (harness === 'grok-cli') {
6247
6260
  // inspect reads the saved goal/state.json: no typing, no send lock. clear keeps the fresh UI status under the lock.
6248
- const run = () => manageGrokAgentGoal(input, { resolve,
6261
+ const run = () => manageGrokAgentGoal(input, { resolve: resolveShared,
6249
6262
  read: async (target) => input.action === 'inspect' ? readSavedGrokGoal(grokSavedState(target)) : readFreshGrokGoal(target.vendor_session_id, grokPort(target)),
6250
6263
  canClear: target => grokGoalClearReady(grokPort(target).ui),
6251
6264
  clear: (target, before) => clearGrokGoal(target.vendor_session_id, before, grokPort(target)),
@@ -6255,7 +6268,7 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6255
6268
  if (harness === "claude-code") {
6256
6269
  // Reading is the session transcript only: it writes nothing to the seat, so it needs no send lock,
6257
6270
  // composer, turn state, TTY owner or version check. Only a mutation types into the composer.
6258
- const run = () => manageClaudeAgentGoal(input, { resolve,
6271
+ const run = () => manageClaudeAgentGoal(input, { resolve: resolveShared,
6259
6272
  read: async (target) => {
6260
6273
  const meta = tryLoadAgentMetadata(input.session_id);
6261
6274
  if (!meta || meta.launch_id !== target.launch_id || meta.vendor_session_id !== target.vendor_session_id)
@@ -6275,7 +6288,7 @@ async function agentGoalInContext(input, origin, expectedGoal, sendHeld = false)
6275
6288
  setObjective: (target, objective) => setClaudeGoalObjective(goalUi(target), objective), }, origin);
6276
6289
  return input.action === "inspect" ? run() : withAgentSendLock(input.session_id, run);
6277
6290
  }
6278
- const run = () => manageAgentGoal(input, { resolve,
6291
+ const run = () => manageAgentGoal(input, { resolve: resolveShared,
6279
6292
  ...(expectedGoal ? { beforeMutation: (current) => JSON.stringify(current) === JSON.stringify(expectedGoal) } : {}),
6280
6293
  connect: (target, callback) => withCodexGoal(target, (request, supported, fields) => callback((method, params) => {
6281
6294
  if (method !== "thread/goal/set" && method !== "thread/goal/clear")
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import { processStartIdentity } from "./process-start.js";
4
4
  // OSのprocess表とnative PIDの所有者。argvは相関にだけ使い、公開identityにはdigestだけを載せる。
5
5
  import { spawnSync } from "node:child_process";
6
+ import { freshShared, spawnCollect } from "./spawn-collect.js";
6
7
  import { createHash } from "node:crypto";
7
8
  import path from "node:path";
8
9
  import { AitermError } from "./errors.js";
@@ -135,26 +136,25 @@ function processReadError(probe, result) {
135
136
  stdout_bytes: Buffer.byteLength(result.stdout ?? ""), stderr_bytes: Buffer.byteLength(result.stderr ?? "") };
136
137
  return new ProcessProbeError(`${isWin ? "Windowsのnative process" : "OSのprocess"}一覧を取得できません ${JSON.stringify(detail)}`, Object.freeze({ code: detail.code, status: detail.status, signal: detail.signal }));
137
138
  }
138
- export function readRuntimeProcesses(includeSession = false) {
139
- if (!isWin) {
140
- const result = spawnSync(POSIX_PS, includeSession ? POSIX_SESSION_TABLE_ARGS : POSIX_TABLE_ARGS, {
141
- encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000, maxBuffer: 16 * 1024 * 1024,
142
- });
143
- if (result.error || result.status !== 0)
144
- throw processReadError(includeSession ? "session_table" : "table", result);
145
- return parsePosixProcessTable(result.stdout, includeSession);
146
- }
139
+ function posixTableRun(includeSession) {
140
+ return [POSIX_PS, includeSession ? POSIX_SESSION_TABLE_ARGS : POSIX_TABLE_ARGS,
141
+ { encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, timeout: 10000, maxBuffer: 16 * 1024 * 1024 }];
142
+ }
143
+ function windowsTableRun() {
147
144
  const script = [
148
145
  ...WINDOWS_PROBE_HEADER,
149
146
  "@(Get-CimInstance Win32_Process | Where-Object { $null -ne $_.CreationDate -and $null -ne $_.CommandLine } | ForEach-Object {",
150
147
  "[ordered]@{ pid=[int]$_.ProcessId; parent_pid=[int]$_.ParentProcessId; executable=[string]$_.ExecutablePath; started_identity=$_.CreationDate.ToUniversalTime().ToString('o'); command=$_.CommandLine; cpu_seconds=([double]$_.KernelModeTime+[double]$_.UserModeTime)/10000000 }",
151
148
  "}) | ConvertTo-Json -Compress",
152
149
  ].join("\n");
153
- const result = spawnSync(resolveWindowsPowerShell7(), [...WINDOWS_PROBE_ARGS, Buffer.from(script, "utf16le").toString("base64")], {
154
- encoding: "utf8", timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true,
155
- });
150
+ return [resolveWindowsPowerShell7(), [...WINDOWS_PROBE_ARGS, Buffer.from(script, "utf16le").toString("base64")],
151
+ { encoding: "utf8", timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true }];
152
+ }
153
+ function parseRuntimeTable(result, includeSession) {
156
154
  if (result.error || result.status !== 0)
157
155
  throw processReadError(includeSession ? "session_table" : "table", result);
156
+ if (!isWin)
157
+ return parsePosixProcessTable(result.stdout, includeSession);
158
158
  let rows;
159
159
  try {
160
160
  rows = JSON.parse(result.stdout);
@@ -178,6 +178,15 @@ export function readRuntimeProcesses(includeSession = false) {
178
178
  };
179
179
  });
180
180
  }
181
+ export function readRuntimeProcesses(includeSession = false) {
182
+ const [bin, args, options] = isWin ? windowsTableRun() : posixTableRun(includeSession);
183
+ return parseRuntimeTable(spawnSync(bin, args, options), includeSession);
184
+ }
185
+ /** The process table without blocking the event loop; checks arriving together share one read that began after each call. */
186
+ export const readRuntimeProcessesShared = freshShared(() => {
187
+ const [bin, args, options] = isWin ? windowsTableRun() : posixTableRun(false);
188
+ return spawnCollect(bin, args, options).then(result => parseRuntimeTable(result, false));
189
+ });
181
190
  /** A held Process handle on Windows prevents a PID replacement from becoming the target. */
182
191
  export function signalRuntimeProcess(target, signal, group) {
183
192
  if (!Number.isSafeInteger(target.pid) || target.pid <= 1 || !Number.isFinite(Date.parse(target.started_identity))
@@ -0,0 +1,51 @@
1
+ import { spawn } from "node:child_process";
2
+ import path from "node:path";
3
+ /** spawnSync と同じ形の結果を、event loop を止めずに返す。timeout は ETIMEDOUT、出力の上限超えは ENOBUFS の error にする。 */
4
+ export function spawnCollect(bin, args, options) {
5
+ return new Promise(done => {
6
+ let stdout = "", stderr = "", error, settled = false;
7
+ let child;
8
+ const finish = (status, signal) => {
9
+ if (settled)
10
+ return;
11
+ settled = true;
12
+ clearTimeout(timer);
13
+ done({ pid: child?.pid ?? 0, output: [null, stdout, stderr], stdout, stderr, status: error ? null : status, signal, ...(error ? { error } : {}) });
14
+ };
15
+ const stop = (code) => { error ??= Object.assign(new Error(`${path.basename(bin)} ${code}`), { code }); child.kill("SIGKILL"); };
16
+ const timer = setTimeout(() => stop("ETIMEDOUT"), options.timeout);
17
+ try {
18
+ child = spawn(bin, args, { env: options.env, windowsHide: options.windowsHide, stdio: ["ignore", "pipe", "pipe"] });
19
+ }
20
+ catch (reason) {
21
+ error = reason;
22
+ finish(null, null);
23
+ return;
24
+ }
25
+ child.on("error", reason => { error ??= reason; finish(null, null); });
26
+ child.on("close", (status, signal) => finish(status, signal));
27
+ child.stdout.setEncoding("utf8");
28
+ child.stderr.setEncoding("utf8");
29
+ child.stdout.on("data", (chunk) => { stdout += chunk; if (stdout.length > options.maxBuffer)
30
+ stop("ENOBUFS"); });
31
+ child.stderr.on("data", (chunk) => { if (stderr.length < options.maxBuffer)
32
+ stderr += chunk; });
33
+ });
34
+ }
35
+ /**
36
+ * Shares one run among the callers that arrive together, without serving a stale one:
37
+ * a caller only receives a run that began after its call. Callers arriving while a run is in flight share the next run,
38
+ * so a burst of N callers costs at most two runs.
39
+ */
40
+ export function freshShared(run) {
41
+ let running = null, queued = null;
42
+ const start = () => {
43
+ queued = null;
44
+ const current = running = run();
45
+ const clear = () => { if (running === current)
46
+ running = null; };
47
+ current.then(clear, clear);
48
+ return current;
49
+ };
50
+ return () => queued ?? (running ? (queued = running.then(start, start)) : start());
51
+ }
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import stringWidth from 'string-width';
12
12
  import { AitermError, ptyDependencyError } from "./errors.js";
13
+ import { freshShared, spawnCollect } from "./spawn-collect.js";
13
14
  import { guardTmuxExecution, beforeExecutionEffect, hasExecutionCreationScope, prepareExecutionCreation, captureExecutionCreatedNative } from "./execution-effect.js";
14
15
  import { ExecutionError } from "./execution-wire.js";
15
16
  import { parseNativeSessionReceipt, nativePaneTarget, nativeSessionTarget, nativeSessionCondition } from "./native-session.js";
@@ -498,6 +499,41 @@ function runTmux(observe, input, args, session, deadline) {
498
499
  || spawnSync(bin, argv, spawnOpts());
499
500
  }
500
501
  diagnosticSpawnFailure(r, deadline);
502
+ return finishTmux(r, args, observe);
503
+ }
504
+ /** A read-only tmux command (display-message and the like) that does not block the event loop. Same routing, guards and failures as tmux(). */
505
+ export async function tmuxReadAsync(...input) {
506
+ const args = nativeConditionalArgs(nativeSessionArgs(guardTmuxExecution(input)));
507
+ let bin, argv;
508
+ if (isWin) {
509
+ ensureWinPsmux(true);
510
+ bin = psmuxBin();
511
+ argv = ["-L", WIN_NS, ...args];
512
+ }
513
+ else {
514
+ bin = resolveTmux(true);
515
+ argv = ["-S", SOCK, ...args];
516
+ }
517
+ const r = await spawnCollect(bin, argv, { env: tmuxSpawnEnv(), timeout: 60_000, maxBuffer: 64 * 1024 * 1024, windowsHide: true });
518
+ return finishTmux(r, args, true);
519
+ }
520
+ const listPanesShared = freshShared(() => tmuxReadAsync("list-panes", "-a", "-F", "#{session_name}\t#{window_active}\t#{pane_active}\t#{pane_pid}\t#{pane_dead}"));
521
+ /**
522
+ * `display-message -p -t =<name>: "#{pane_pid}\t#{pane_dead}"` without blocking the event loop.
523
+ * Outside a native target frame on POSIX, the checks arriving together share one `list-panes -a` read (the session's active window and pane).
524
+ * A native target frame routes the session to its pinned pane, and psmux is not measured for `list-panes -a`: both keep the per-session read.
525
+ */
526
+ export async function sessionPaneAsync(name) {
527
+ if (isWin || nativeTargets.getStore())
528
+ return tmuxReadAsync("display-message", "-p", "-t", `=${name}:`, "#{pane_pid}\t#{pane_dead}");
529
+ guardTmuxExecution(["list-panes", "-a"]);
530
+ const all = await listPanesShared();
531
+ if (all.code !== 0)
532
+ return all;
533
+ const row = all.stdout.split("\n").map(line => line.split("\t")).find(fields => fields[0] === name && fields[1] === "1" && fields[2] === "1");
534
+ return row ? { code: 0, stdout: `${row[3]}\t${row[4]}\n`, stderr: "" } : { code: 1, stdout: "", stderr: `can't find session: ${name}` };
535
+ }
536
+ function finishTmux(r, args, observe) {
501
537
  // ENOBUFS(出力が 64MiB 超)を「code=1 の失敗」へ握り潰すと部分/空 stdout を正常扱いしてしまう。区別して投げる。
502
538
  // EXPECTED-FAILURE: 外部システム境界(tmux 出力過大)
503
539
  if (r.error && r.error.code === "ENOBUFS") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiterm-mcp",
3
- "version": "0.70.39",
3
+ "version": "0.70.40",
4
4
  "mcpName": "io.github.kitepon/aiterm-mcp",
5
5
  "description": "Persistent terminal MCP with one harness-based launcher for Claude Code, Codex CLI, Grok CLI, Cursor Agent CLI, and Antigravity CLI, plus durable PTYs for SSH, containers, and REPLs.",
6
6
  "keywords": [