aiterm-mcp 0.70.39 → 0.70.41
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 +14 -1
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/agent-goal-native-result.js +13 -13
- package/dist/agent-goal.js +8 -8
- package/dist/agent-idle.js +2 -0
- package/dist/agent-lifecycle.js +33 -10
- package/dist/core.js +72 -32
- package/dist/errors.js +11 -0
- package/dist/harnesses/antigravity.js +10 -2
- package/dist/index.js +6 -3
- package/dist/process-runtime.js +21 -12
- package/dist/remote-terminal.js +15 -3
- package/dist/remote.js +69 -10
- package/dist/resume-checkpoint.js +2 -2
- package/dist/spawn-collect.js +51 -0
- package/dist/tmux-runtime.js +36 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.70.41] - 2026-11-13
|
|
11
|
+
|
|
12
|
+
- Antigravity CLI 1.5.7 seats start again. agy 1.5.7 draws a mode hint in the empty composer (`> Auto mode: edits & safe commands auto-approved (shift+tab to cycle)`, also Accept-edits, Plan and Best-of-N), and Aiterm accepted only a bare `>` line as the empty composer, so every `agent_launch` ended `AGENT_STARTUP_BLOCKED vendor_state_unknown` (Kiro, 2026-11-13; container agy replaced 2026-11-12 23:38 UTC). The empty composer is now the footer plus a bare `>` line or exactly such a hint line (also when it wraps at the pane edge); a typed draft still reads as not empty.
|
|
13
|
+
- Calls to a trusted terminal (`terminal`-bound seats) reuse one warm MCP session per terminal instead of starting `ssh`, the terminal's shell, a fresh `aiterm-mcp` and MCP initialize for every call (a37; Kiro, 2026-11-13: BellTeam `GET /api/goals` 5-9.5 s, waiting on terminal seats). Measured from the container with the terminals' 0.70.40, one seat's `pty_observe` + `agent_goal inspect`: MacBook 3.8 s → about 0.4 s; Windows (fox) 5.3 s → about 2.0 s, of which inspect itself takes 1.5 s on the terminal (three Windows process table reads). A request already sent is never replayed: a session found closed before a send is reopened, one lost after a send fails as before. A session is closed after 2 minutes unused or 10 minutes of age (a terminal's `aiterm-update` takes effect within 10 minutes), and it never keeps an otherwise idle process alive. `agent_launch` with private values still uses its own connection.
|
|
14
|
+
- A Claude or Codex seat whose launch env names a secret (`…TOKEN`, `…KEY`, `…AUTH` and the like, or a terminal seat's `AITERM_MCP_HEADER_n`) can now hibernate and resume into the same conversation (E8; Kiro, 2026-11-13, chart t29). Until 0.70.40 such a seat got no resume template at all, so `pty_close {hibernate:true}` answered `AGENT_HIBERNATE_UNAVAILABLE resume_unavailable` and every BellTeam seat (which names `BELLTEAM_MCP_TOKEN`) could only be started fresh. The template and recipe now keep the secret names only (`secret_environment`); values are never written to disk, and a 0.70.23-0.70.40 recipe that held the Claude login value is rewritten without it. `agent_launch` with `session_name` takes each value from that launch (private env line, then process env) and refuses with `AGENT_RESUME_SECRET_MISSING` (not started, seat stays hibernated) when one is missing; the Claude login keeps its 0.70.23 rule (not named: the seat resumes on the root's login). A send or dispatch that would resume such a seat refuses with `AGENT_RESUME_SECRETS_REQUIRED` and sends nothing; the idle clock leaves such seats running (`resume_needs_launch_values`). A resume that brings `mcp_config` with the same server names rewrites the seat's caller MCP file, so a terminal seat reaches the current forward port.
|
|
15
|
+
- `pty_list` `aiterm/seat_turns` rows of terminal-bound seats carry `route_since` (E9): when the terminal's seat-MCP reverse forward was last established (the forward keeper records `ready_at`), null while it is not ready.
|
|
16
|
+
|
|
17
|
+
## [0.70.40] - 2026-11-12
|
|
18
|
+
|
|
19
|
+
- 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).
|
|
20
|
+
|
|
10
21
|
## [0.70.39] - 2026-11-12
|
|
11
22
|
|
|
12
23
|
- 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 +3383,9 @@ prototype (preserved under `prototype/python/` as the porting source and referen
|
|
|
3372
3383
|
`ubuntu-latest` for Node 18/20/22, publishing to npm on `v*` tags with
|
|
3373
3384
|
provenance.
|
|
3374
3385
|
|
|
3375
|
-
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.
|
|
3386
|
+
[Unreleased]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.41...HEAD
|
|
3387
|
+
[0.70.41]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.40...v0.70.41
|
|
3388
|
+
[0.70.40]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.39...v0.70.40
|
|
3376
3389
|
[0.70.39]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.38...v0.70.39
|
|
3377
3390
|
[0.70.38]: https://github.com/kitepon/aiterm-mcp/compare/v0.70.37...v0.70.38
|
|
3378
3391
|
[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.
|
|
218
|
+
**状態:** 開発継続中 · 現行公開版 **v0.70.41** · 動作対象は 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.
|
|
230
|
+
**Status:** actively maintained · current public release **v0.70.41** · 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() });
|
package/dist/agent-goal.js
CHANGED
|
@@ -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/agent-idle.js
CHANGED
|
@@ -29,6 +29,8 @@ export function decideIdleSeat(seat, now, minutes = 30, expectedAnchor, immediat
|
|
|
29
29
|
return { ...result, reason: "conversation_id_unavailable" };
|
|
30
30
|
if (!seat.resume_ready)
|
|
31
31
|
return { ...result, reason: "resume_unavailable" };
|
|
32
|
+
if (!immediate && seat.resume_needs_launch_values)
|
|
33
|
+
return { ...result, reason: "resume_needs_launch_values" };
|
|
32
34
|
if (!limited && seat.turn_settled !== true)
|
|
33
35
|
return { ...result, reason: "turn_end_unconfirmed" };
|
|
34
36
|
const anchor = limited ?? seat.activity.last_turn_end_at ?? (!seat.activity.tracked ? seat.created_at : null);
|
package/dist/agent-lifecycle.js
CHANGED
|
@@ -7,11 +7,18 @@ import { agentMetadataPath, writeJson0600 } from "./agent-shared.js";
|
|
|
7
7
|
import { AitermError } from "./errors.js";
|
|
8
8
|
const launchId = z.string().regex(/^[a-f0-9]{32}$/);
|
|
9
9
|
const absolute = z.string().min(1).refine(value => path.isAbsolute(value) && !value.includes("\0"));
|
|
10
|
+
const envName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
|
|
11
|
+
/** A credential-shaped name, or a header value the body moved to the private line for a terminal seat (remote-terminal R5). */
|
|
12
|
+
export function isSecretEnvName(name) {
|
|
13
|
+
return /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(name) || /^AITERM_MCP_HEADER_\d+$/.test(name);
|
|
14
|
+
}
|
|
10
15
|
export const agentResumeRecipeSchema = z.object({
|
|
11
16
|
schema: z.literal("aiterm.agent-resume.v1"), launch_id: launchId,
|
|
12
17
|
kind: z.enum(["claude", "codex"]), vendor_session_id: z.string().regex(/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i),
|
|
13
18
|
executable: absolute, cwd: absolute, configuration_root: absolute, model: z.string().nullable(), reasoning_effort: z.string().nullable(), reasoning_effort_source: z.literal("vendor_default").optional(), fast: z.boolean(),
|
|
14
|
-
environment: z.record(
|
|
19
|
+
environment: z.record(envName, z.string().refine(value => !value.includes("\0")).nullable()),
|
|
20
|
+
// E8: names whose values a resume takes from its own launch; the values are never stored.
|
|
21
|
+
secret_environment: z.array(envName).optional(),
|
|
15
22
|
}).strict();
|
|
16
23
|
const identity = z.object({ pid: z.number().int().positive(), process_group_id: z.number().int().positive().nullable(),
|
|
17
24
|
started_identity: z.string().min(1), argv_digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict();
|
|
@@ -59,6 +66,16 @@ export function writeAgentResumeRecipe(meta, input) {
|
|
|
59
66
|
throw unavailable();
|
|
60
67
|
writeJson0600(file(meta, ".resume.json"), value);
|
|
61
68
|
}
|
|
69
|
+
/** Secret names of a recipe. A recipe from 0.70.40 or older may hold one in `environment`: its value is never used. */
|
|
70
|
+
export function recipeSecretNames(recipe) {
|
|
71
|
+
return [...new Set([...recipe.secret_environment ?? [], ...Object.keys(recipe.environment).filter(isSecretEnvName)])].sort();
|
|
72
|
+
}
|
|
73
|
+
/** The recipe as stored: secret names only, never their values. */
|
|
74
|
+
export function withoutSecretValues(recipe, secrets = recipeSecretNames(recipe)) {
|
|
75
|
+
const { secret_environment: _, ...rest } = recipe;
|
|
76
|
+
return { ...rest, environment: Object.fromEntries(Object.entries(recipe.environment).filter(([name]) => !isSecretEnvName(name) && !secrets.includes(name))),
|
|
77
|
+
...(secrets.length ? { secret_environment: secrets } : {}) };
|
|
78
|
+
}
|
|
62
79
|
export function agentResumeRecipeDigest(recipe) {
|
|
63
80
|
return createHash("sha256").update(JSON.stringify(agentResumeRecipeSchema.parse(recipe))).digest("hex");
|
|
64
81
|
}
|
|
@@ -151,12 +168,13 @@ export function writeAgentResumeTemplate(meta, input) {
|
|
|
151
168
|
export function captureAgentResumeTemplate(meta, effort, envNames, configurationRoot, env = process.env) {
|
|
152
169
|
if (meta.kind !== "claude" && meta.kind !== "codex")
|
|
153
170
|
return;
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
-
|
|
171
|
+
// Secret names are kept without values (E8): a resume takes them from its own launch.
|
|
172
|
+
const names = [...new Set([...envNames, ...(meta.kind === "claude" ? ["CLAUDE_CONFIG_DIR"] : [])])];
|
|
173
|
+
const secrets = names.filter(isSecretEnvName).sort();
|
|
157
174
|
writeAgentResumeTemplate(meta, { schema: "aiterm.agent-resume-template.v1", launch_id: meta.launch_id, kind: meta.kind,
|
|
158
175
|
executable: meta.agent_executable, cwd: meta.cwd, configuration_root: configurationRoot, model: meta.model ?? null, reasoning_effort: effort,
|
|
159
|
-
environment: Object.fromEntries(
|
|
176
|
+
environment: Object.fromEntries(names.filter(name => !isSecretEnvName(name)).map(name => [name, launchEnvValue(name, env) ?? null])),
|
|
177
|
+
...(secrets.length ? { secret_environment: secrets } : {}), state: "confirmed" });
|
|
160
178
|
}
|
|
161
179
|
export function finishAgentResumeConfiguration(meta, before, model, effort) {
|
|
162
180
|
const complete = !!model && !!effort;
|
|
@@ -168,9 +186,14 @@ export function finishAgentResumeConfiguration(meta, before, model, effort) {
|
|
|
168
186
|
export function refreshAgentResumeRecipe(meta) {
|
|
169
187
|
const template = readAgentResumeTemplate(meta);
|
|
170
188
|
if (!template) {
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
189
|
+
const stored = readAgentResumeRecipe(meta);
|
|
190
|
+
if (!stored?.model || !stored.reasoning_effort || (meta.kind === "claude" && !Object.hasOwn(stored.environment, "CLAUDE_CONFIG_DIR")))
|
|
191
|
+
return null;
|
|
192
|
+
// A 0.70.23-0.70.40 recipe may hold the Claude login value: keep its name only (E8).
|
|
193
|
+
const recipe = withoutSecretValues(stored);
|
|
194
|
+
if (agentResumeRecipeDigest(recipe) !== agentResumeRecipeDigest(stored))
|
|
195
|
+
writeAgentResumeRecipe(meta, recipe);
|
|
196
|
+
return recipe;
|
|
174
197
|
}
|
|
175
198
|
if (template.state !== "confirmed" || !template.model || (!template.reasoning_effort && !(meta.kind === "codex" && template.reasoning_effort === null && template.reasoning_effort_source === "vendor_default")) || template.model !== meta.model
|
|
176
199
|
|| template.executable !== meta.agent_executable || template.cwd !== meta.cwd || typeof meta.fast !== "boolean")
|
|
@@ -179,8 +202,8 @@ export function refreshAgentResumeRecipe(meta) {
|
|
|
179
202
|
|| !["low", "medium", "high", "xhigh", "max"].includes(template.reasoning_effort ?? "")))
|
|
180
203
|
return null;
|
|
181
204
|
const { state, ...settings } = template;
|
|
182
|
-
const candidate = agentResumeRecipeSchema.safeParse({ ...settings, schema: "aiterm.agent-resume.v1",
|
|
183
|
-
vendor_session_id: meta.vendor_session_id, fast: meta.fast });
|
|
205
|
+
const candidate = agentResumeRecipeSchema.safeParse(withoutSecretValues({ ...settings, schema: "aiterm.agent-resume.v1",
|
|
206
|
+
vendor_session_id: meta.vendor_session_id, fast: meta.fast }));
|
|
184
207
|
if (!candidate.success)
|
|
185
208
|
return null;
|
|
186
209
|
const previous = readAgentResumeRecipe(meta);
|
package/dist/core.js
CHANGED
|
@@ -40,7 +40,7 @@ import { initializeAgentActivity, recordAgentInput, recordAgentTurnEnd, readAgen
|
|
|
40
40
|
import { checkIdleSeat, decideIdleSeat, idleMinutes } from "./agent-idle.js";
|
|
41
41
|
import { AGENT_IDLE_ENABLED, armAgentIdleClock, endAgentIdleClock, idleClockDeadline, isAgentIdleClockOwner, requestAgentIdleClock, requestAgentIdleClocks } from "./agent-idle-clock.js";
|
|
42
42
|
import { stopProcessTree } from "./process-tree-stop.js";
|
|
43
|
-
import { writeAgentResumeRecoveryOrigin, confirmedAgentResumeRecoveryOrigin, readAgentResumeResolution, writeAgentResumeResolution, agentResumeRecordDigest, captureAgentResumeTemplate, readAgentResumeTemplate, writeAgentResumeTemplate, finishAgentResumeConfiguration, refreshAgentResumeRecipe, readAgentIdleClock, retireAgentIdleClock, readAgentResumeRecipe, writeAgentResumeRecipe, agentResumeRecipeDigest, readAgentLifecycle, writeAgentLifecycle, cancelAgentStopping, readAgentResumeAttempt, writeAgentResumeAttempt, readAgentResumeNative, writeAgentResumeNative } from "./agent-lifecycle.js";
|
|
43
|
+
import { writeAgentResumeRecoveryOrigin, confirmedAgentResumeRecoveryOrigin, readAgentResumeResolution, writeAgentResumeResolution, agentResumeRecordDigest, captureAgentResumeTemplate, readAgentResumeTemplate, writeAgentResumeTemplate, finishAgentResumeConfiguration, refreshAgentResumeRecipe, readAgentIdleClock, retireAgentIdleClock, readAgentResumeRecipe, writeAgentResumeRecipe, agentResumeRecipeDigest, isSecretEnvName, recipeSecretNames, withoutSecretValues, readAgentLifecycle, writeAgentLifecycle, cancelAgentStopping, readAgentResumeAttempt, writeAgentResumeAttempt, readAgentResumeNative, writeAgentResumeNative } from "./agent-lifecycle.js";
|
|
44
44
|
import { createCodexGoalObjective, editCodexGoalObjective, submitCodexGoalCommand } from "./harnesses/codex-goal-editor.js";
|
|
45
45
|
import { closeExpectedExecution, parseExecutionNativeSessions, executionNativeBindingSchema } from "./execution-close.js";
|
|
46
46
|
import { executionLaunchSchema, executionPointSchema } from "./execution-contract.js";
|
|
@@ -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
|
-
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";
|
|
58
|
+
import { AitermError, launchAuthRequired, launchInputRefusal, launchStartupBlocked, AgentResumeUnavailableError, AgentResumeError, AgentResumeSecretsError, 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, 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";
|
|
@@ -1966,7 +1966,7 @@ export async function checkAgentIdle(expectedInput, expectedAnchor, immediate =
|
|
|
1966
1966
|
const settled = meta.kind === "claude" ? done !== null && readClaudeOperationMarker(meta) === null
|
|
1967
1967
|
: meta.kind === "codex" ? done?.turn_id != null && done.turn_id === codexCompletedTurnId(meta) : agentTurnSettled(meta);
|
|
1968
1968
|
return { launch_id: meta.launch_id, created_at: meta.created_at, vendor_session_id: meta.vendor_session_id,
|
|
1969
|
-
resume_ready: resumeReady, native_configuration_confirmed: configurationScreen !== null
|
|
1969
|
+
resume_ready: resumeReady, resume_needs_launch_values: !!recipe && recipeSecretNames(recipe).length > 0, native_configuration_confirmed: configurationScreen !== null
|
|
1970
1970
|
&& (effectIssued || (slot?.last_attached_at != null && slot.last_attached_at < configurationStartedAt
|
|
1971
1971
|
&& configurationScreen === captureScreen(name, AGENT_TUI_READY_LINES))), activity: readAgentActivity(meta), state: live.state, reason: live.reason,
|
|
1972
1972
|
attached: slot?.attached ?? (effectIssued ? false : null), turn_settled: settled,
|
|
@@ -2298,7 +2298,7 @@ export function listSessionsResult(envKeys = [], runTmux = tmux, o = {}) {
|
|
|
2298
2298
|
const recipe = readAgentResumeRecipe(meta);
|
|
2299
2299
|
if (recipe?.kind === meta.kind && recipe.vendor_session_id === meta.vendor_session_id)
|
|
2300
2300
|
for (const key of envKeys)
|
|
2301
|
-
environment[key] = key
|
|
2301
|
+
environment[key] = isSecretEnvName(key) ? null : recipe.environment[key] ?? null;
|
|
2302
2302
|
if (state === "hibernated") {
|
|
2303
2303
|
try {
|
|
2304
2304
|
confirmedAgentResumeRecipe(meta, readAgentLifecycle(meta));
|
|
@@ -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
|
-
|
|
6055
|
-
|
|
6056
|
-
|
|
6057
|
-
|
|
6058
|
-
|
|
6059
|
-
|
|
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
|
|
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 =
|
|
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")
|
|
@@ -7060,7 +7073,11 @@ function adoptVanishedAgentNative(meta) {
|
|
|
7060
7073
|
}
|
|
7061
7074
|
// Claude's login, not a recipe setting (lifecycle-state-ownership 4b): a resume through agent_launch may replace it.
|
|
7062
7075
|
const CLAUDE_LOGIN_ENV = "CLAUDE_CODE_OAUTH_TOKEN";
|
|
7063
|
-
|
|
7076
|
+
/**
|
|
7077
|
+
* `secretValues` (E8, lifecycle-state-ownership 4c): the values agent_launch brought for the recipe's secret names (null = unset,
|
|
7078
|
+
* only the Claude login). Without them (pty_send, dispatch, vanished adopt) a recipe naming a secret is refused before any effect.
|
|
7079
|
+
*/
|
|
7080
|
+
async function resumeAgentInLock(name, readyTimeout, claudeRoot, secretValues) {
|
|
7064
7081
|
const previous = loadAgentMetadata(name);
|
|
7065
7082
|
readyTimeout ??= previous.kind === "codex" ? AGENT_TUI_FIRST_DRAW_TIMEOUT_MS : AGENT_TUI_READY_TIMEOUT_MS;
|
|
7066
7083
|
let lifecycle = readAgentLifecycle(previous);
|
|
@@ -7110,12 +7127,19 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot, claudeLogin) {
|
|
|
7110
7127
|
try {
|
|
7111
7128
|
assertExecutionResumeSupported();
|
|
7112
7129
|
const confirmed = confirmedAgentResumeRecipe(previous, lifecycle);
|
|
7130
|
+
const secretNames = [...new Set([...recipeSecretNames(confirmed), ...Object.keys(secretValues ?? {})])].sort();
|
|
7131
|
+
if (secretNames.length && !secretValues) {
|
|
7132
|
+
recorded = true; // a refusal before any effect, not a failed resume
|
|
7133
|
+
throw new AgentResumeSecretsError("AGENT_RESUME_SECRETS_REQUIRED", name, secretNames);
|
|
7134
|
+
}
|
|
7135
|
+
const stored = withoutSecretValues(confirmed, secretNames);
|
|
7113
7136
|
// Same vendor session under another Claude root; the caller proved the transcript is there.
|
|
7114
|
-
const rooted = claudeRoot &&
|
|
7115
|
-
environment: { ...
|
|
7116
|
-
// null = unset in the seat: it resumes on the root's own login.
|
|
7117
|
-
const recipe =
|
|
7118
|
-
|
|
7137
|
+
const rooted = claudeRoot && stored.kind === "claude" ? { ...stored, configuration_root: claudeRoot.root,
|
|
7138
|
+
environment: { ...stored.environment, CLAUDE_CONFIG_DIR: claudeRoot.selector } } : stored;
|
|
7139
|
+
// Values of this launch only; null = unset in the seat (the Claude login: it resumes on the root's own login).
|
|
7140
|
+
const recipe = { ...rooted, environment: { ...rooted.environment, ...Object.fromEntries(secretNames.map(key => [key, secretValues[key] ?? null])) } };
|
|
7141
|
+
// What goes to disk: the names still set, never their values.
|
|
7142
|
+
const saved = withoutSecretValues(recipe, secretNames.filter(key => recipe.environment[key] != null));
|
|
7119
7143
|
if (sessionExists(name))
|
|
7120
7144
|
throw uncertain();
|
|
7121
7145
|
const controlEnv = { ...process.env };
|
|
@@ -7195,7 +7219,7 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot, claudeLogin) {
|
|
|
7195
7219
|
next.fork_of = previous.fork_of;
|
|
7196
7220
|
writeAgentMetadata(next);
|
|
7197
7221
|
initializeAgentActivity(next);
|
|
7198
|
-
writeAgentResumeRecipe(next, { ...
|
|
7222
|
+
writeAgentResumeRecipe(next, { ...saved, launch_id: next.launch_id });
|
|
7199
7223
|
attempt = { schema: "aiterm.agent-resume-attempt.v1", launch_id: previous.launch_id, next_launch_id: next.launch_id,
|
|
7200
7224
|
state: "resuming", at: new Date().toISOString(), recipe_digest: lifecycle.recipe_digest };
|
|
7201
7225
|
phase = "attempt_save";
|
|
@@ -7209,8 +7233,8 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot, claudeLogin) {
|
|
|
7209
7233
|
const environment = [...Object.entries(recipe.environment),
|
|
7210
7234
|
...(next.kind === "codex" ? [["CODEX_HOME", recipe.configuration_root]] : []), ...agentEnvEntries(next, name)];
|
|
7211
7235
|
for (const [key, value] of environment) {
|
|
7212
|
-
//
|
|
7213
|
-
if (value !== null && key
|
|
7236
|
+
// Secret values never go on a multiplexer argv or into pty_list; the launch reads them from the 0600 file.
|
|
7237
|
+
if (value !== null && secretNames.includes(key))
|
|
7214
7238
|
continue;
|
|
7215
7239
|
const stored = value === null ? tmux("set-environment", isWin ? "-u" : "-r", "-t", name, key) : tmux("set-environment", "-t", name, key, value);
|
|
7216
7240
|
if (stored.code !== 0)
|
|
@@ -7252,9 +7276,10 @@ async function resumeAgentInLock(name, readyTimeout, claudeRoot, claudeLogin) {
|
|
|
7252
7276
|
phase = "ready_save";
|
|
7253
7277
|
writeAgentResumeTemplate(resumed, { schema: "aiterm.agent-resume-template.v1", launch_id: resumed.launch_id, state: "confirmed",
|
|
7254
7278
|
kind: recipe.kind, executable: recipe.executable, cwd: recipe.cwd, configuration_root: recipe.configuration_root,
|
|
7255
|
-
model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment:
|
|
7279
|
+
model: recipe.model, reasoning_effort: recipe.reasoning_effort, environment: saved.environment,
|
|
7280
|
+
...(saved.secret_environment ? { secret_environment: saved.secret_environment } : {}),
|
|
7256
7281
|
...(recipe.reasoning_effort_source ? { reasoning_effort_source: recipe.reasoning_effort_source } : {}) });
|
|
7257
|
-
writeAgentResumeRecipe(resumed, { ...
|
|
7282
|
+
writeAgentResumeRecipe(resumed, { ...saved, launch_id: resumed.launch_id });
|
|
7258
7283
|
writeAgentResumeAttempt(previous, { ...attempt, state: "ready", at: new Date().toISOString() });
|
|
7259
7284
|
return resumed;
|
|
7260
7285
|
}
|
|
@@ -8440,7 +8465,7 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
8440
8465
|
|| (opts.fast != null && opts.fast !== recipe.fast)
|
|
8441
8466
|
|| (opts.cwd != null && path.resolve(opts.cwd) !== recipe.cwd)
|
|
8442
8467
|
|| (opts.write_scope !== undefined && opts.write_scope !== previous.write_scope)
|
|
8443
|
-
|| (opts.env_vars !== undefined && !isDeepStrictEqual(resumeEnvNames(kind, opts.env_vars), resumeEnvNames(kind, Object.keys(recipe.environment)))))
|
|
8468
|
+
|| (opts.env_vars !== undefined && !isDeepStrictEqual(resumeEnvNames(kind, opts.env_vars), resumeEnvNames(kind, [...Object.keys(recipe.environment), ...recipeSecretNames(recipe)]))))
|
|
8444
8469
|
throw opts.require_existing_resume ? new AgentResumeUnavailableError(name) : new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したharness・設定・project・明示envで再開します。変更は再開後に行ってください。", 2);
|
|
8445
8470
|
// The only setting a resume may change: the Claude root, when it holds this conversation's transcript.
|
|
8446
8471
|
const rootChange = claudeRoot && (claudeRoot.root !== recipe.configuration_root
|
|
@@ -8450,11 +8475,26 @@ export async function openAgentWithInitialPrompt(kind, opts = {}) {
|
|
|
8450
8475
|
if (opts.launch_operation_id != null)
|
|
8451
8476
|
requireMatchingClaudeLaunch(name, validateOperationId(opts.launch_operation_id), claudeLaunchRequestDigest({ sessionName: name, model: opts.model ?? null, effort: opts.reasoning_effort ?? null,
|
|
8452
8477
|
cwd: opts.cwd ?? null, agentDone: true }));
|
|
8478
|
+
// E8: every secret name takes this launch's value (private line, then env). The Claude login keeps 4b: named or
|
|
8479
|
+
// env_vars omitted -> this launch's value, else unset (root login); every other name without a value refuses.
|
|
8480
|
+
const isLogin = (key) => kind === "claude" && key === CLAUDE_LOGIN_ENV;
|
|
8481
|
+
const secretNames = [...new Set([...recipeSecretNames(recipe), ...(kind === "claude" && opts.env_vars?.includes(CLAUDE_LOGIN_ENV) ? [CLAUDE_LOGIN_ENV] : [])])];
|
|
8482
|
+
const secretValues = Object.fromEntries(secretNames.map(key => [key,
|
|
8483
|
+
isLogin(key) && opts.env_vars !== undefined && !opts.env_vars.includes(key) ? null : launchEnvValue(key) ?? null]));
|
|
8484
|
+
const missing = secretNames.filter(key => secretValues[key] === null && !isLogin(key));
|
|
8485
|
+
if (missing.length)
|
|
8486
|
+
throw new AgentResumeSecretsError("AGENT_RESUME_SECRET_MISSING", name, missing);
|
|
8487
|
+
// A terminal seat's forward port P may have changed: the caller MCP file takes the new URLs, same servers only.
|
|
8488
|
+
if (opts.mcp_config != null && (kind === "claude" ? previous.claude_caller_mcp_file : previous.codex_caller_mcp_file)) {
|
|
8489
|
+
const file = (kind === "claude" ? previous.claude_caller_mcp_file : previous.codex_caller_mcp_file);
|
|
8490
|
+
const serverNames = (config) => Object.keys((config ?? {}).mcpServers ?? {}).sort();
|
|
8491
|
+
if (!isDeepStrictEqual(serverNames(JSON.parse(fs.readFileSync(file, "utf8"))), serverNames(opts.mcp_config)))
|
|
8492
|
+
throw new AitermError("AGENT_RESUME_CONFLICT: 同名の休止席は保存したMCP serverの名前で再開します。", 2);
|
|
8493
|
+
(kind === "claude" ? writeClaudeCallerFiles : writeCodexCallerFiles)({ ...previous }, null, opts.mcp_config);
|
|
8494
|
+
}
|
|
8453
8495
|
if (preparedLifecycle)
|
|
8454
8496
|
commitWorkingAgentResume(previous, preparedLifecycle);
|
|
8455
|
-
const
|
|
8456
|
-
? { value: opts.env_vars.includes(CLAUDE_LOGIN_ENV) ? launchEnvValue(CLAUDE_LOGIN_ENV) ?? null : null } : undefined;
|
|
8457
|
-
const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined, rootChange, claudeLogin);
|
|
8497
|
+
const resumed = await resumeAgentInLock(name, opts.ready_timeout ?? undefined, rootChange, secretValues);
|
|
8458
8498
|
return withAgentResumeTarget(resumed, async () => {
|
|
8459
8499
|
const hint = `${agentLabel(kind)} を保存した同じ会話へ再開した。\n${attachHint(name)}`;
|
|
8460
8500
|
const fastState = { fast: resumed.fast === true, fast_error: null };
|
package/dist/errors.js
CHANGED
|
@@ -52,6 +52,17 @@ export class AgentResumeError extends AitermError {
|
|
|
52
52
|
session_id: sessionId, launch_id: launchId, input: "not_sent", recovery: "inspect_session" };
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
|
+
/** E8: a resume needs secret values only the caller's agent_launch carries; nothing was started or sent, the seat stays hibernated. */
|
|
56
|
+
export class AgentResumeSecretsError extends AitermError {
|
|
57
|
+
resumeSecrets;
|
|
58
|
+
constructor(code, sessionId, names) {
|
|
59
|
+
super(`${code}: ${code === "AGENT_RESUME_SECRET_MISSING"
|
|
60
|
+
? `再開に要る秘密の値がこの起動にありません(${names.join(", ")})。`
|
|
61
|
+
: `この席の再開には秘密の値が要ります(${names.join(", ")})。agent_launch(session_name)で値を渡して再開してください。`}新規起動も本文送信もしていません。`, 2);
|
|
62
|
+
this.resumeSecrets = { schema: "aiterm.agent-resume-secrets.v1", code, session_id: sessionId, names,
|
|
63
|
+
effect: "not_started", input: "not_sent", state: "hibernated" };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
55
66
|
export class TelemetryOwnedError extends AitermError {
|
|
56
67
|
telemetryCode;
|
|
57
68
|
constructor(message, code, telemetryCode, cause) {
|
|
@@ -56,6 +56,14 @@ export function antigravityAuthStatus(bin, cwd, env = process.env) {
|
|
|
56
56
|
return { status: "unauthenticated", message: "Antigravity CLIのGoogleサインインが必要です" };
|
|
57
57
|
return { status: "failed", message: "Antigravity CLIの認証状態を確認できません" };
|
|
58
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The empty composer under the `? for shortcuts` footer: a bare `>` line, or the mode hint agy 1.5.7 draws there until
|
|
61
|
+
* the first key (`> Auto mode: edits & safe commands auto-approved (shift+tab to cycle)`; the hint may wrap at the pane edge).
|
|
62
|
+
*/
|
|
63
|
+
export function antigravityEmptyComposer(screen) {
|
|
64
|
+
return /\? for shortcuts/.test(screen)
|
|
65
|
+
&& /^\s*>\s*(?:[A-Z][\w-]* mode: [^\n]*(?:\n[^\n─>]*)?\(shift\+tab\s+to\s+cycle\)\s*)?$/m.test(screen);
|
|
66
|
+
}
|
|
59
67
|
export function antigravityAuthPane(screen) {
|
|
60
68
|
if (/\binvalid_grant\b/i.test(screen))
|
|
61
69
|
return { url: null, user_code: null, input_required: false,
|
|
@@ -70,7 +78,7 @@ export function antigravityAuthPane(screen) {
|
|
|
70
78
|
}
|
|
71
79
|
const url = authUrl(urlLines.join(""), ["accounts.google.com"]);
|
|
72
80
|
const complete = /Do you trust the contents of this project\?/.test(screen)
|
|
73
|
-
|| (
|
|
81
|
+
|| antigravityEmptyComposer(screen);
|
|
74
82
|
const base = { url, user_code: null, input_required: false, message: null, onboarding_complete: complete };
|
|
75
83
|
if (complete)
|
|
76
84
|
return base;
|
|
@@ -134,7 +142,7 @@ export function antigravityPaneObservation(screen) {
|
|
|
134
142
|
return { state: "blocked", reason: "vendor_action_required" };
|
|
135
143
|
if (/(?:Generating|Working)(?:\.{3}|…)|esc to interrupt/i.test(screen))
|
|
136
144
|
return { state: "busy", reason: "vendor_generating" };
|
|
137
|
-
if (
|
|
145
|
+
if (antigravityEmptyComposer(screen))
|
|
138
146
|
return { state: "idle", reason: "composer_ready" };
|
|
139
147
|
return { state: "unknown", reason: "vendor_state_unknown" };
|
|
140
148
|
}
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { terminalCwdFits } from "./remote-path.js";
|
|
|
6
6
|
import { launchEnvValue } from "./private-env.js";
|
|
7
7
|
import { AuthResponseError, authUiSchema, authBindingSchema, authResponseSchema } from "./agent-auth-ui.js";
|
|
8
8
|
import { configurationRequestSchema, configurationToolOutputSchema, applyConfigurationRequest, reconcileConfigurationRequest } from "./configure-request.js";
|
|
9
|
-
import { AitermError, AgentResumeUnavailableError, AgentResumeError, launchInputRefusal } from "./errors.js";
|
|
9
|
+
import { AitermError, AgentResumeUnavailableError, AgentResumeError, AgentResumeSecretsError, launchInputRefusal } from "./errors.js";
|
|
10
10
|
/**
|
|
11
11
|
* aiterm-mcp — AI が握るローカル永続端末を stdio MCP サーバとして公開する(Node/TS 版)。
|
|
12
12
|
*
|
|
@@ -241,6 +241,9 @@ export function createAitermServer(options = {}) {
|
|
|
241
241
|
if (e instanceof AgentResumeUnavailableError)
|
|
242
242
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
243
243
|
_meta: { "aiterm/resume_unavailable": { ...e.resumeUnavailable } } };
|
|
244
|
+
if (e instanceof AgentResumeSecretsError)
|
|
245
|
+
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
246
|
+
structuredContent: { ...e.resumeSecrets } };
|
|
244
247
|
if (e instanceof AgentResumeError)
|
|
245
248
|
return { content: [{ type: "text", text: "aiterm: " + msg }], isError: true,
|
|
246
249
|
structuredContent: { ...e.resumeFailure } };
|
|
@@ -874,7 +877,7 @@ export function createAitermServer(options = {}) {
|
|
|
874
877
|
// two readers of one seat at once leave one of them without the span lock (that seat comes back in its `unread`).
|
|
875
878
|
// Relays start before the synchronous local read so the terminal works meanwhile; their 4 s counts only time this
|
|
876
879
|
// process's event loop was free (loopDeadline), since a blocked loop cannot take the answer however soon it came.
|
|
877
|
-
const relays = Promise.all(terminalSeatGroups().map(({ target, sessions: bound }) => {
|
|
880
|
+
const relays = Promise.all(terminalSeatGroups().map(({ target, sessions: bound, route_since }) => {
|
|
878
881
|
const key = JSON.stringify([target, requestMeta]);
|
|
879
882
|
let call = remoteSeatTurnsInFlight.get(key);
|
|
880
883
|
if (!call) {
|
|
@@ -886,7 +889,7 @@ export function createAitermServer(options = {}) {
|
|
|
886
889
|
}
|
|
887
890
|
return Promise.race([
|
|
888
891
|
call.then(answer => Array.isArray(answer?.seats)
|
|
889
|
-
? { seats: answer.seats.filter((seat) => bound.includes(seat?.session_id)),
|
|
892
|
+
? { seats: answer.seats.filter((seat) => bound.includes(seat?.session_id)).map((seat) => ({ ...seat, route_since })),
|
|
890
893
|
unread: Array.isArray(answer.unread) ? answer.unread.filter((name) => bound.includes(name)) : [] }
|
|
891
894
|
: { seats: [], unread: bound }),
|
|
892
895
|
loopDeadline(4_000, { seats: [], unread: bound }),
|
package/dist/process-runtime.js
CHANGED
|
@@ -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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
-
|
|
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))
|
package/dist/remote-terminal.js
CHANGED
|
@@ -266,7 +266,13 @@ export class SshStdioTransport {
|
|
|
266
266
|
child.on("error", error => this.onerror?.(error));
|
|
267
267
|
child.on("close", () => { this.child = null; this.onclose?.(); });
|
|
268
268
|
child.stdin.on("error", error => this.onerror?.(error));
|
|
269
|
-
|
|
269
|
+
if (this.privateLine)
|
|
270
|
+
child.stdin.write(this.privateLine);
|
|
271
|
+
}
|
|
272
|
+
/** A kept session must not keep an idle process alive; it holds the loop only while a request waits on it. */
|
|
273
|
+
hold(on) {
|
|
274
|
+
for (const handle of [this.child, this.child?.stdin, this.child?.stdout, this.child?.stderr])
|
|
275
|
+
on ? handle?.ref?.() : handle?.unref?.();
|
|
270
276
|
}
|
|
271
277
|
async send(message) {
|
|
272
278
|
if (!this.child?.stdin)
|
|
@@ -747,7 +753,7 @@ export function terminalSeatGroups() {
|
|
|
747
753
|
for (const [session, ref] of Object.entries(readSeats()))
|
|
748
754
|
groups.set(ref, [...groups.get(ref) ?? [], session]);
|
|
749
755
|
return [...groups].flatMap(([ref, sessions]) => { try {
|
|
750
|
-
return [{ target: trustedTarget(binding(ref)), sessions }];
|
|
756
|
+
return [{ target: trustedTarget(binding(ref)), sessions, route_since: forwardRouteSince(ref) }];
|
|
751
757
|
}
|
|
752
758
|
catch {
|
|
753
759
|
return [];
|
|
@@ -869,7 +875,8 @@ function markReady(ref, ready) {
|
|
|
869
875
|
return;
|
|
870
876
|
const file = lockFile(ref), staged = `${file}.${process.pid}`;
|
|
871
877
|
try {
|
|
872
|
-
|
|
878
|
+
// ready_at (E9): when this ssh -R became ready; a newer one tells BellTeam the seats' route was rebuilt.
|
|
879
|
+
fs.writeFileSync(staged, JSON.stringify(ready ? { ...lockIdentity(), ready, ready_at: new Date().toISOString() } : lockIdentity()), { mode: 0o600 });
|
|
873
880
|
fs.renameSync(staged, file);
|
|
874
881
|
}
|
|
875
882
|
catch {
|
|
@@ -911,6 +918,11 @@ function forwardReady(ref, port) {
|
|
|
911
918
|
return false;
|
|
912
919
|
return Number(owner.pid) === process.pid ? Boolean(keepers.get(ref)?.child) : ownerAlive(owner);
|
|
913
920
|
}
|
|
921
|
+
/** E9: when the seats' current reverse forward was established; null when it is not ready or the time is unknown. */
|
|
922
|
+
export function forwardRouteSince(ref) {
|
|
923
|
+
const port = binding(ref).seat_forward_port, readyAt = lockOwner(ref)?.ready_at;
|
|
924
|
+
return port && typeof readyAt === "string" && forwardReady(ref, port) ? readyAt : null;
|
|
925
|
+
}
|
|
914
926
|
// T3: a launch in any process keeps the forward needed (the seat is bound only after it), so the owner never stops it meanwhile.
|
|
915
927
|
const launchFile = (ref) => path.join(ensureStateRoot(), `terminal-forward-${ref}.launch`);
|
|
916
928
|
function forwardNeeded(ref) {
|
package/dist/remote.js
CHANGED
|
@@ -223,6 +223,60 @@ export function remoteServerCommand(shell) {
|
|
|
223
223
|
}
|
|
224
224
|
export const REMOTE_CLIENT_NAME = "aiterm-remote";
|
|
225
225
|
/** 現地のaiterm-mcpへ1回だけMCP接続し、指定toolを呼んで閉じる。privateEnvは暗号化されたstdinの先頭行だけで渡す(remote-terminal.md R5)。 */
|
|
226
|
+
// a37: a trusted terminal keeps one warm MCP session (ssh + its aiterm-mcp, initialized) for calls without private values,
|
|
227
|
+
// so a call costs one round trip instead of a shell start, a node start and initialize. A sent request is never replayed.
|
|
228
|
+
const WARM_IDLE_MS = 2 * 60_000, WARM_MAX_AGE_MS = 10 * 60_000;
|
|
229
|
+
const warmSessions = new Map();
|
|
230
|
+
function retireWarm(ref, session) {
|
|
231
|
+
if (warmSessions.get(ref) === session)
|
|
232
|
+
warmSessions.delete(ref);
|
|
233
|
+
if (session.idle)
|
|
234
|
+
clearTimeout(session.idle);
|
|
235
|
+
if (!session.inflight)
|
|
236
|
+
void session.client.close().catch(() => { });
|
|
237
|
+
}
|
|
238
|
+
function warmSession(target, sshArgs) {
|
|
239
|
+
const ref = target.trusted_ref;
|
|
240
|
+
const kept = warmSessions.get(ref);
|
|
241
|
+
if (kept && !kept.dead && Date.now() - kept.born < WARM_MAX_AGE_MS)
|
|
242
|
+
return kept;
|
|
243
|
+
if (kept)
|
|
244
|
+
retireWarm(ref, kept);
|
|
245
|
+
const transport = new SshStdioTransport(sshArgs, ""), client = new Client({ name: REMOTE_CLIENT_NAME, version: pkg.version });
|
|
246
|
+
const session = { client, transport, born: Date.now(), inflight: 0, idle: null, dead: false,
|
|
247
|
+
ready: client.connect(transport, { timeout: 60_000 }).catch(() => {
|
|
248
|
+
retireWarm(ref, session);
|
|
249
|
+
const failure = classifySshFailure(transport.stderr);
|
|
250
|
+
throw new AitermError(`${failure.code}: ${failure.message}${failure.action ? ` (${failure.action})` : ""}`, 2);
|
|
251
|
+
}) };
|
|
252
|
+
client.onclose = () => { session.dead = true; if (warmSessions.get(ref) === session)
|
|
253
|
+
warmSessions.delete(ref); };
|
|
254
|
+
warmSessions.set(ref, session);
|
|
255
|
+
return session;
|
|
256
|
+
}
|
|
257
|
+
async function callWarm(target, sshArgs, request, timeoutMs) {
|
|
258
|
+
const session = warmSession(target, sshArgs);
|
|
259
|
+
session.inflight++;
|
|
260
|
+
if (session.idle) {
|
|
261
|
+
clearTimeout(session.idle);
|
|
262
|
+
session.idle = null;
|
|
263
|
+
}
|
|
264
|
+
session.transport.hold(true);
|
|
265
|
+
try {
|
|
266
|
+
await session.ready;
|
|
267
|
+
const result = await session.client.callTool(request, undefined, { timeout: timeoutMs, resetTimeoutOnProgress: true });
|
|
268
|
+
return { result, version: session.client.getServerVersion()?.version ?? null };
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
if (--session.inflight === 0) {
|
|
272
|
+
session.transport.hold(false);
|
|
273
|
+
if (session.dead || warmSessions.get(target.trusted_ref) !== session)
|
|
274
|
+
void session.client.close().catch(() => { });
|
|
275
|
+
else
|
|
276
|
+
session.idle = setTimeout(() => retireWarm(target.trusted_ref, session), WARM_IDLE_MS).unref();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
226
280
|
export async function callRemoteTool(target, name, args, timeoutMs = 600_000, privateEnv, meta) {
|
|
227
281
|
if (privateEnv && !target.trusted_ref)
|
|
228
282
|
throw new AitermError("REMOTE_PRIVATE_ENV_UNSUPPORTED: private values travel only to a terminal binding", 2);
|
|
@@ -231,6 +285,20 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
|
|
|
231
285
|
const command = target.trusted_ref ? terminalCommand(shell, terminalProgram(privateEnv ? ["aiterm-mcp", "--private-env-stdin"] : ["aiterm-mcp"]))
|
|
232
286
|
: privateEnv ? posixCommand("exec aiterm-mcp --private-env-stdin") : remoteServerCommand(shell);
|
|
233
287
|
const { args: sshArgs, env } = sshInvocation(target, command);
|
|
288
|
+
// Request _meta is opaque to the relay; progressToken belongs to this hop's client, not the caller's.
|
|
289
|
+
const { progressToken: _hop, ...forwarded } = meta ?? {};
|
|
290
|
+
const request = Object.keys(forwarded).length ? { name, arguments: args, _meta: forwarded } : { name, arguments: args };
|
|
291
|
+
const shape = (result, version) => ({
|
|
292
|
+
content: result.content ?? [],
|
|
293
|
+
...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
|
|
294
|
+
...(result.isError ? { isError: true } : {}),
|
|
295
|
+
...(result._meta ? { _meta: result._meta } : {}),
|
|
296
|
+
remote_version: version,
|
|
297
|
+
});
|
|
298
|
+
if (target.trusted_ref && !privateEnv) {
|
|
299
|
+
const { result, version } = await callWarm(target, sshArgs, request, timeoutMs);
|
|
300
|
+
return shape(result, version);
|
|
301
|
+
}
|
|
234
302
|
const transport = privateEnv
|
|
235
303
|
? new SshStdioTransport(sshArgs, `${JSON.stringify({ schema: PRIVATE_ENV_SCHEMA, env: privateEnv })}\n`)
|
|
236
304
|
: new StdioClientTransport({ command: "ssh", args: sshArgs, env, stderr: "pipe" });
|
|
@@ -252,17 +320,8 @@ export async function callRemoteTool(target, name, args, timeoutMs = 600_000, pr
|
|
|
252
320
|
const detail = stderr.trim().split("\n").slice(-3).join(" / ") || (error instanceof Error ? error.message : String(error));
|
|
253
321
|
throw new AitermError(`REMOTE_CONNECT_FAILED: ${remoteLabel(target)} のAitermへ接続できません(${detail})`, 2);
|
|
254
322
|
}
|
|
255
|
-
// Request _meta is opaque to the relay; progressToken belongs to this hop's client, not the caller's.
|
|
256
|
-
const { progressToken: _hop, ...forwarded } = meta ?? {};
|
|
257
|
-
const request = Object.keys(forwarded).length ? { name, arguments: args, _meta: forwarded } : { name, arguments: args };
|
|
258
323
|
const result = await client.callTool(request, undefined, { timeout: timeoutMs, resetTimeoutOnProgress: true });
|
|
259
|
-
return
|
|
260
|
-
content: result.content ?? [],
|
|
261
|
-
...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
|
|
262
|
-
...(result.isError ? { isError: true } : {}),
|
|
263
|
-
...(result._meta ? { _meta: result._meta } : {}),
|
|
264
|
-
remote_version: client.getServerVersion()?.version ?? null,
|
|
265
|
-
};
|
|
324
|
+
return shape(result, client.getServerVersion()?.version ?? null);
|
|
266
325
|
}
|
|
267
326
|
finally {
|
|
268
327
|
await client.close().catch(() => { });
|
|
@@ -87,7 +87,7 @@ export function validateResumeCheckpoint(input) {
|
|
|
87
87
|
|| recipe.kind !== 'codex' || recipe.vendor_session_id !== scope.vendor_session_id || recipe.configuration_root !== scope.configuration_root
|
|
88
88
|
|| recipe.fast !== false || recipe.cwd !== m.cwd || recipe.executable !== m.agent_executable || recipe.model !== (m.model ?? null))
|
|
89
89
|
refuse();
|
|
90
|
-
if (Object.keys(recipe.environment).some(key => /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(key)))
|
|
90
|
+
if (recipe.secret_environment?.length || Object.keys(recipe.environment).some(key => /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(key)))
|
|
91
91
|
refuse();
|
|
92
92
|
const lineage = ['agent_role', 'parent_session_id', 'delegation_depth', 'lineage', 'delegation_allowed'];
|
|
93
93
|
if (lineage.some(k => m[k] !== undefined) && lineage.some(k => m[k] === undefined))
|
|
@@ -120,7 +120,7 @@ export function validateResumeCheckpoint(input) {
|
|
|
120
120
|
refuse();
|
|
121
121
|
const template = get(id, 'template', false);
|
|
122
122
|
if (template && (template.kind !== 'codex' || template.configuration_root !== scope.configuration_root
|
|
123
|
-
|| Object.keys(template.environment).some(key => /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(key))))
|
|
123
|
+
|| template.secret_environment?.length || Object.keys(template.environment).some(key => /(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|AUTH)$/i.test(key))))
|
|
124
124
|
refuse();
|
|
125
125
|
const failure = get(id, 'failure', false);
|
|
126
126
|
if (failure && failure.session_id !== scope.session_id)
|
|
@@ -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
|
+
}
|
package/dist/tmux-runtime.js
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.70.41",
|
|
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": [
|