scope-agent-workbench 0.2.0 → 0.2.3
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 +41 -0
- package/bridge/agent-email-relay.mjs +160 -160
- package/bridge/app-server-websocket-transport.mjs +219 -219
- package/bridge/archive/service.mjs +130 -130
- package/bridge/auth-profile-failover.mjs +58 -58
- package/bridge/auth-profile-manager.mjs +215 -215
- package/bridge/capacity-recovery.mjs +90 -90
- package/bridge/gpu-usage-history.mjs +322 -322
- package/bridge/local/history.mjs +20 -5
- package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
- package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
- package/bridge/private-gateway.mjs +371 -371
- package/bridge/private-start.mjs +22 -22
- package/bridge/probes/app-server-handoff-probe.mjs +87 -87
- package/bridge/probes/app-server-writer-probe.mjs +69 -69
- package/bridge/probes/assistant-search-probe.mjs +321 -321
- package/bridge/probes/dialogue-probe.mjs +462 -462
- package/bridge/probes/history-probe.mjs +430 -345
- package/bridge/probes/new-session-preflight.mjs +14 -14
- package/bridge/probes/profile-cancel-probe.mjs +17 -17
- package/bridge/probes/profile-delete-probe.mjs +26 -26
- package/bridge/probes/profile-list-probe.mjs +114 -114
- package/bridge/probes/profile-write-probe.mjs +109 -109
- package/bridge/probes/raw-context-probe.mjs +51 -51
- package/bridge/probes/remote-probe.mjs +627 -626
- package/bridge/probes/submission-probe.mjs +2 -2
- package/bridge/probes/takeover-probe.mjs +326 -326
- package/bridge/probes/vscode-open-preflight.mjs +21 -21
- package/bridge/providers/claude-interactive.py +463 -341
- package/bridge/providers/cli-command.mjs +103 -103
- package/bridge/providers/conversations.mjs +231 -231
- package/bridge/providers/native-commands.py +38 -38
- package/bridge/providers/native-session-state.mjs +14 -14
- package/bridge/providers/native-session-state.py +96 -96
- package/bridge/providers/remote-job.py +130 -130
- package/bridge/remote-app-server-command.mjs +121 -121
- package/bridge/remote-directory-listing.mjs +148 -148
- package/bridge/rollout-summary.mjs +20 -2
- package/bridge/routes/dialogue.mjs +48 -3
- package/bridge/routes/models.mjs +312 -312
- package/bridge/server.mjs +3357 -3332
- package/bridge/session-attachments.mjs +150 -150
- package/bridge/session-catalog/agy-history.py +141 -2
- package/bridge/session-catalog/catalog.mjs +17 -0
- package/bridge/session-catalog/probe.py +1207 -331
- package/bridge/session-catalog/routes.mjs +6 -0
- package/bridge/start.mjs +205 -205
- package/bridge/state-persistence.mjs +9 -1
- package/bridge/tmux-session-control.mjs +29 -29
- package/bridge/vscode-opener.mjs +157 -157
- package/bridge/web-terminal.mjs +52 -52
- package/bridge/workbench/manager-context.mjs +51 -51
- package/bridge/workbench/service.mjs +301 -301
- package/dist/client/.vite/manifest.json +4 -4
- package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
- package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
- package/dist/client/assets/page-CJqXlhDs.js +551 -0
- package/dist/client/assets/page-LYzRz6_S.css +1 -0
- package/dist/client/favicon.svg +6 -6
- package/dist/server/__vite_rsc_assets_manifest.js +8 -8
- package/dist/server/index.js +7 -7
- package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
- package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
- package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
- package/dist/server/ssr/index.js +1 -1
- package/dist/server/ssr/vinext-server.json +1 -1
- package/dist/server/vinext-server.json +1 -1
- package/dist/server/wrangler.json +1 -1
- package/lib/browser-snapshot-cache.js +53 -53
- package/lib/formula-preview.js +1 -1
- package/lib/incremental-snapshot.js +300 -300
- package/lib/markdown-math.js +151 -151
- package/lib/remote-links.js +95 -95
- package/lib/runtime-config.js +70 -70
- package/lib/session-filters.js +38 -38
- package/lib/ssh-config.js +26 -26
- package/lib/stable-order.js +39 -39
- package/lib/subagent-display-prefs.ts +130 -0
- package/package.json +1 -1
- package/scripts/agent-email-relay.mjs +104 -104
- package/scripts/email-notification-cli.mjs +28 -28
- package/scripts/enable-private-access.ps1 +109 -109
- package/scripts/fixtures/native-conversations.mjs +164 -6
- package/scripts/fixtures/workbench-conversations.mjs +475 -352
- package/scripts/preview-workbench.mjs +669 -669
- package/dist/client/assets/page-COBv6VWj.css +0 -1
- package/dist/client/assets/page-DVjU6VG_.js +0 -550
- package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
|
@@ -1,231 +1,231 @@
|
|
|
1
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { LOCAL_HOST, workingDirectory } from "../../lib/execution-host.js";
|
|
5
|
-
import {
|
|
6
|
-
formatUserPromptPreview,
|
|
7
|
-
normalizeTurnAttachments,
|
|
8
|
-
renderInstructionWithAttachments,
|
|
9
|
-
} from "../session-attachments.mjs";
|
|
10
|
-
|
|
11
|
-
/** Persistent CLI conversations. One durable spool job per turn; polling never launches work. */
|
|
12
|
-
export class CliConversations {
|
|
13
|
-
constructor({ filename, adapter, hosts, settings, catalog, models, commands, lifecycle, resolveAttachments = null }) {
|
|
14
|
-
Object.assign(this, { filename, adapter, hosts, settings, catalog, models, commands, lifecycle, resolveAttachments });
|
|
15
|
-
this.sessions = new Map(); this.pending = new Map(); this.writes = Promise.resolve();
|
|
16
|
-
}
|
|
17
|
-
async load() {
|
|
18
|
-
try { for (const session of JSON.parse(await readFile(this.filename, "utf8"))) this.sessions.set(session.key, session); }
|
|
19
|
-
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
20
|
-
return this;
|
|
21
|
-
}
|
|
22
|
-
save() {
|
|
23
|
-
const data = JSON.stringify([...this.sessions.values()]);
|
|
24
|
-
this.writes = this.writes.catch(() => {}).then(async () => {
|
|
25
|
-
await mkdir(path.dirname(this.filename), { recursive: true });
|
|
26
|
-
const temporary = `${this.filename}.tmp`;
|
|
27
|
-
await writeFile(temporary, data, { mode: 0o600 });
|
|
28
|
-
await rename(temporary, this.filename);
|
|
29
|
-
});
|
|
30
|
-
return this.writes;
|
|
31
|
-
}
|
|
32
|
-
entries() {
|
|
33
|
-
return [...this.sessions.values()].map(({ key, host, provider, sessionId, cwd, title, model, status, updatedAt, phase, subagents }) => ({
|
|
34
|
-
key,
|
|
35
|
-
host,
|
|
36
|
-
provider,
|
|
37
|
-
sessionId,
|
|
38
|
-
cwd,
|
|
39
|
-
title,
|
|
40
|
-
model,
|
|
41
|
-
status,
|
|
42
|
-
updatedAt,
|
|
43
|
-
phase,
|
|
44
|
-
managed: true,
|
|
45
|
-
activeSubagents: Array.isArray(subagents) ? subagents.filter((item) => item?.status === "working").length : 0,
|
|
46
|
-
}));
|
|
47
|
-
}
|
|
48
|
-
start() {
|
|
49
|
-
this.timer = setInterval(() => { void this.refresh(); }, 5000);
|
|
50
|
-
this.timer.unref();
|
|
51
|
-
void this.refresh();
|
|
52
|
-
}
|
|
53
|
-
stop() { clearInterval(this.timer); }
|
|
54
|
-
async refresh() {
|
|
55
|
-
if (this.refreshing) return;
|
|
56
|
-
this.refreshing = true;
|
|
57
|
-
try {
|
|
58
|
-
const queue = [...this.sessions.values()].filter((session) => session.job && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status) && this.hosts().some((host) => host.alias === session.host && host.reachable));
|
|
59
|
-
await Promise.all(Array.from({ length: Math.min(3, queue.length) }, async () => {
|
|
60
|
-
for (let session; (session = queue.shift());) await this.read(session.key);
|
|
61
|
-
}));
|
|
62
|
-
} finally { this.refreshing = false; }
|
|
63
|
-
}
|
|
64
|
-
async send(body) {
|
|
65
|
-
const rawPrompt = String(body.prompt || "").trim();
|
|
66
|
-
if (rawPrompt.length > 60_000) throw new Error("请输入消息(不超过 60000 字符)");
|
|
67
|
-
let session = body.key ? this.sessions.get(body.key) : null;
|
|
68
|
-
const existing = body.key && !session ? this.catalog.get(body.key) : null;
|
|
69
|
-
if (body.key && !session && !existing) throw new Error("找不到会话,请重新扫描");
|
|
70
|
-
const provider = session?.provider || existing?.provider || body.provider;
|
|
71
|
-
const hasRawAttachments = Array.isArray(body.attachments) && body.attachments.length > 0;
|
|
72
|
-
if (!rawPrompt && !hasRawAttachments) throw new Error("请输入消息(不超过 60000 字符)");
|
|
73
|
-
if (!["claude", "antigravity"].includes(provider)) throw new Error("不支持此 Agent");
|
|
74
|
-
const host = session?.host || existing?.host || body.host;
|
|
75
|
-
if (host === LOCAL_HOST) throw new Error("Claude / Antigravity 网页会话暂需选择远程设备;本机历史可浏览");
|
|
76
|
-
if (!this.hosts().some((item) => item.alias === host && item.reachable)) throw new Error("设备当前离线");
|
|
77
|
-
const cwd = workingDirectory(host, session?.cwd || existing?.cwd || body.cwd);
|
|
78
|
-
const scopeKey = String(body.attachmentScope || body.key || "new-session");
|
|
79
|
-
const attachments = hasRawAttachments
|
|
80
|
-
? (this.resolveAttachments
|
|
81
|
-
? this.resolveAttachments(body.attachments, host, { scope: scopeKey })
|
|
82
|
-
: normalizeTurnAttachments(body.attachments))
|
|
83
|
-
: [];
|
|
84
|
-
if (!rawPrompt && !attachments.length) throw new Error("请输入消息(不超过 60000 字符)");
|
|
85
|
-
if (rawPrompt) await this.commands?.validate(host, provider, cwd, rawPrompt);
|
|
86
|
-
if (session && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) throw new Error("上一轮尚未结束或状态待确认,请稍后重试");
|
|
87
|
-
if (session?.turns.length && !session.sessionId) throw new Error("上一轮未返回可续接的会话标识,请新建会话;不会悄悄丢失上下文继续");
|
|
88
|
-
let model = String(body.model ?? session?.model ?? "").trim();
|
|
89
|
-
if (model.length > 200 || /[\x00-\x1f]/.test(model)) throw new Error("模型名称无效");
|
|
90
|
-
const config = { ...this.settings(provider, host), model };
|
|
91
|
-
const permissionMode = body.permissionMode ?? session?.permissionMode ?? (provider === "claude" ? "auto" : "default");
|
|
92
|
-
if (!["auto", "default", "workspace", "plan", ...(provider === "antigravity" ? ["full"] : [])].includes(permissionMode)) throw new Error("不支持此权限设置");
|
|
93
|
-
const effort = String(body.effort ?? session?.effort ?? "");
|
|
94
|
-
if (effort && !["low", "medium", "high", "xhigh", "max"].includes(effort)) throw new Error("不支持此推理强度");
|
|
95
|
-
await this.models?.validate(host, provider, model);
|
|
96
|
-
if (provider === "claude") await this.models?.validateClaudeOptions?.(host, model, effort, permissionMode);
|
|
97
|
-
if (provider === "antigravity" && this.models?.validateAgyOptions) { model = await this.models.validateAgyOptions(host, model, effort, permissionMode); config.model = model; }
|
|
98
|
-
const resumeId = session?.sessionId || existing?.sessionId;
|
|
99
|
-
if (resumeId) await this.lifecycle?.(host, resumeId, "check", provider);
|
|
100
|
-
// Model discovery is asynchronous. Recheck the session after it so two
|
|
101
|
-
// sends cannot claim the same native conversation while discovery runs.
|
|
102
|
-
session = body.key ? this.sessions.get(body.key) || session : session;
|
|
103
|
-
if (session && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) throw new Error("上一轮尚未结束或状态待确认,请稍后重试");
|
|
104
|
-
const displayPrompt = formatUserPromptPreview(rawPrompt, attachments);
|
|
105
|
-
const effectivePrompt = renderInstructionWithAttachments(rawPrompt, attachments);
|
|
106
|
-
if (!session) {
|
|
107
|
-
const key = existing?.key || `cli:${randomUUID()}`;
|
|
108
|
-
session = { key, host, cwd, provider, sessionId: existing?.sessionId || null, title: (rawPrompt || attachments.map((a) => a.name).join(", ")).slice(0, 120), turns: [] };
|
|
109
|
-
this.sessions.set(key, session);
|
|
110
|
-
}
|
|
111
|
-
const task = { id: randomUUID(), host, cwd, provider, interactive: true, prompt: effectivePrompt, permissionMode, effort, resumeSessionId: session.sessionId || null };
|
|
112
|
-
session.effort = effort;
|
|
113
|
-
session.permissionMode = permissionMode;
|
|
114
|
-
session.model = model; session.status = "launching"; session.updatedAt = Date.now();
|
|
115
|
-
session.turns.push({ id: task.id, prompt: displayPrompt, text: "", status: "launching", createdAt: session.updatedAt });
|
|
116
|
-
session.job = task;
|
|
117
|
-
try {
|
|
118
|
-
await this.save();
|
|
119
|
-
await this.adapter.launch(task, { providers: { [provider]: config } });
|
|
120
|
-
session.status = "running";
|
|
121
|
-
session.turns.at(-1).status = "running";
|
|
122
|
-
} catch (error) {
|
|
123
|
-
// A lost launch response may still mean the remote job started. Never retry automatically.
|
|
124
|
-
session.status = "unknown";
|
|
125
|
-
session.turns.at(-1).error = error.message;
|
|
126
|
-
}
|
|
127
|
-
await this.save();
|
|
128
|
-
return this.view(session);
|
|
129
|
-
}
|
|
130
|
-
view(session) {
|
|
131
|
-
const { job, ...value } = session;
|
|
132
|
-
return { ...value, interactive: job?.interactive === true };
|
|
133
|
-
}
|
|
134
|
-
async control(body) {
|
|
135
|
-
const session = this.sessions.get(body.key);
|
|
136
|
-
if (!session?.job?.interactive) throw new Error("此会话没有可用交互通道");
|
|
137
|
-
if (!["running", "waiting_permission"].includes(session.status)) throw new Error("会话未在运行或正在结束,请刷新后重试");
|
|
138
|
-
if (!this.hosts().some(h => h.alias === session.host && h.reachable)) throw new Error("设备当前离线,未发送控制请求");
|
|
139
|
-
const control = { id: String(body.id || randomUUID()), action: body.action };
|
|
140
|
-
if (!/^[a-f0-9-]{36}$/.test(control.id)) throw new Error("请求标识无效");
|
|
141
|
-
if (body.action === "message") {
|
|
142
|
-
const rawPrompt = String(body.prompt || "").trim();
|
|
143
|
-
const hasRawAttachments = Array.isArray(body.attachments) && body.attachments.length > 0;
|
|
144
|
-
const attachments = hasRawAttachments
|
|
145
|
-
? (this.resolveAttachments
|
|
146
|
-
? this.resolveAttachments(body.attachments, session.host, { scope: session.key })
|
|
147
|
-
: normalizeTurnAttachments(body.attachments))
|
|
148
|
-
: [];
|
|
149
|
-
if ((!rawPrompt && !attachments.length) || rawPrompt.length > 60000) throw new Error("请输入消息(不超过 60000 字符)");
|
|
150
|
-
if (rawPrompt) await this.commands?.validate(session.host, session.provider, session.cwd, rawPrompt, session.commands);
|
|
151
|
-
control.prompt = renderInstructionWithAttachments(rawPrompt, attachments);
|
|
152
|
-
} else if (body.action === "permission") {
|
|
153
|
-
if (!["allow", "deny", ...(session.provider === "antigravity" ? ["cancel"] : [])].includes(body.decision)) throw new Error("无效审批结果");
|
|
154
|
-
control.requestId = String(body.requestId || ""); control.decision = body.decision;
|
|
155
|
-
if (body.optionId !== undefined) control.optionId = String(body.optionId);
|
|
156
|
-
if (body.content !== undefined) {
|
|
157
|
-
if (!body.content || typeof body.content !== "object" || Array.isArray(body.content) || JSON.stringify(body.content).length > 60000) throw new Error("表单内容无效");
|
|
158
|
-
control.content = body.content;
|
|
159
|
-
}
|
|
160
|
-
if (body.answers) {
|
|
161
|
-
if (typeof body.answers !== "object" || Array.isArray(body.answers) || Object.values(body.answers).some(v => typeof v !== "string" || v.length > 10000)) throw new Error("回答格式无效");
|
|
162
|
-
control.answers = body.answers;
|
|
163
|
-
}
|
|
164
|
-
} else if (body.action !== "stop") throw new Error("不支持的控制操作");
|
|
165
|
-
await this.adapter.control(session.job, control);
|
|
166
|
-
return { controlId: control.id, status: "queued" };
|
|
167
|
-
}
|
|
168
|
-
async changeState({ key, action }) {
|
|
169
|
-
if (!["archive", "delete", "restore"].includes(action)) throw new Error("无效操作");
|
|
170
|
-
const entry = this.sessions.get(key) || this.catalog.get(key);
|
|
171
|
-
if (!entry || !["claude", "antigravity"].includes(entry.provider) || !entry.sessionId) throw new Error("仅支持已有 Claude / Antigravity 会话");
|
|
172
|
-
if (["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(entry.status)) throw new Error("会话仍在运行或状态待确认");
|
|
173
|
-
if (!this.hosts().some(h => h.alias === entry.host && h.reachable)) throw new Error("主机离线,未修改归档状态");
|
|
174
|
-
if (!this.lifecycle) throw new Error("远端归档服务不可用");
|
|
175
|
-
const result = await this.lifecycle(entry.host, entry.sessionId, action, entry.provider);
|
|
176
|
-
for (const item of this.sessions.values()) if (item.host === entry.host && item.provider === entry.provider && item.sessionId === entry.sessionId) item.phase = result.phase;
|
|
177
|
-
// Update the cached catalog immediately, then reconcile against remote state.
|
|
178
|
-
for (const item of this.catalog.records?.values() || []) if (item.host === entry.host && item.provider === entry.provider && item.sessionId === entry.sessionId) item.phase = result.phase;
|
|
179
|
-
await this.save();
|
|
180
|
-
void this.catalog.refresh(true);
|
|
181
|
-
return result;
|
|
182
|
-
}
|
|
183
|
-
async read(key) {
|
|
184
|
-
const session = this.sessions.get(key);
|
|
185
|
-
if (!session) return null;
|
|
186
|
-
if (session.job && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) {
|
|
187
|
-
if (!this.pending.has(key)) {
|
|
188
|
-
this.pending.set(key, this.poll(session).finally(() => this.pending.delete(key)));
|
|
189
|
-
}
|
|
190
|
-
await this.pending.get(key);
|
|
191
|
-
}
|
|
192
|
-
return this.view(session);
|
|
193
|
-
}
|
|
194
|
-
async poll(session) {
|
|
195
|
-
try {
|
|
196
|
-
const result = await this.adapter.poll(session.job);
|
|
197
|
-
const turn = session.turns.at(-1);
|
|
198
|
-
if (session.job.interactive) {
|
|
199
|
-
session.sessionId = result.sessionId || session.sessionId;
|
|
200
|
-
turn.events = result.events || turn.events || [];
|
|
201
|
-
turn.partial = result.partial || "";
|
|
202
|
-
turn.truncated = Boolean(result.truncated);
|
|
203
|
-
session.permissions = result.permissions || [];
|
|
204
|
-
session.controlResults = result.controlResults || [];
|
|
205
|
-
if (Array.isArray(result.commands)) session.commands = result.commands;
|
|
206
|
-
if (Array.isArray(result.subagents)) {
|
|
207
|
-
session.subagents = result.subagents;
|
|
208
|
-
turn.subagents = result.subagents;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
if (["completed", "failed", "stopped"].includes(result.status)) {
|
|
212
|
-
session.status = result.status;
|
|
213
|
-
session.sessionId = result.sessionId || session.sessionId;
|
|
214
|
-
turn.status = result.status; turn.text = (result.text || "").slice(-120_000); turn.error = result.error || null; turn.errorCode = result.errorCode || null;
|
|
215
|
-
if (["stopped", "failed"].includes(result.status) && Array.isArray(session.subagents)) {
|
|
216
|
-
session.subagents = session.subagents.map((item) =>
|
|
217
|
-
item?.status === "working" ? { ...item, status: result.status } : item,
|
|
218
|
-
);
|
|
219
|
-
turn.subagents = session.subagents;
|
|
220
|
-
}
|
|
221
|
-
session.updatedAt = Date.now();
|
|
222
|
-
await this.save();
|
|
223
|
-
void this.catalog.refresh(true);
|
|
224
|
-
} else {
|
|
225
|
-
session.status = ["running", "waiting_permission", "stopping", "finishing"].includes(result.status) ? result.status : "unknown";
|
|
226
|
-
turn.status = session.status;
|
|
227
|
-
turn.error = result.error || null;
|
|
228
|
-
}
|
|
229
|
-
} catch (error) { session.turns.at(-1).error = `读取进度失败:${error.message}`; }
|
|
230
|
-
}
|
|
231
|
-
}
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { LOCAL_HOST, workingDirectory } from "../../lib/execution-host.js";
|
|
5
|
+
import {
|
|
6
|
+
formatUserPromptPreview,
|
|
7
|
+
normalizeTurnAttachments,
|
|
8
|
+
renderInstructionWithAttachments,
|
|
9
|
+
} from "../session-attachments.mjs";
|
|
10
|
+
|
|
11
|
+
/** Persistent CLI conversations. One durable spool job per turn; polling never launches work. */
|
|
12
|
+
export class CliConversations {
|
|
13
|
+
constructor({ filename, adapter, hosts, settings, catalog, models, commands, lifecycle, resolveAttachments = null }) {
|
|
14
|
+
Object.assign(this, { filename, adapter, hosts, settings, catalog, models, commands, lifecycle, resolveAttachments });
|
|
15
|
+
this.sessions = new Map(); this.pending = new Map(); this.writes = Promise.resolve();
|
|
16
|
+
}
|
|
17
|
+
async load() {
|
|
18
|
+
try { for (const session of JSON.parse(await readFile(this.filename, "utf8"))) this.sessions.set(session.key, session); }
|
|
19
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
20
|
+
return this;
|
|
21
|
+
}
|
|
22
|
+
save() {
|
|
23
|
+
const data = JSON.stringify([...this.sessions.values()]);
|
|
24
|
+
this.writes = this.writes.catch(() => {}).then(async () => {
|
|
25
|
+
await mkdir(path.dirname(this.filename), { recursive: true });
|
|
26
|
+
const temporary = `${this.filename}.tmp`;
|
|
27
|
+
await writeFile(temporary, data, { mode: 0o600 });
|
|
28
|
+
await rename(temporary, this.filename);
|
|
29
|
+
});
|
|
30
|
+
return this.writes;
|
|
31
|
+
}
|
|
32
|
+
entries() {
|
|
33
|
+
return [...this.sessions.values()].map(({ key, host, provider, sessionId, cwd, title, model, status, updatedAt, phase, subagents }) => ({
|
|
34
|
+
key,
|
|
35
|
+
host,
|
|
36
|
+
provider,
|
|
37
|
+
sessionId,
|
|
38
|
+
cwd,
|
|
39
|
+
title,
|
|
40
|
+
model,
|
|
41
|
+
status,
|
|
42
|
+
updatedAt,
|
|
43
|
+
phase,
|
|
44
|
+
managed: true,
|
|
45
|
+
activeSubagents: Array.isArray(subagents) ? subagents.filter((item) => item?.status === "working").length : 0,
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
start() {
|
|
49
|
+
this.timer = setInterval(() => { void this.refresh(); }, 5000);
|
|
50
|
+
this.timer.unref();
|
|
51
|
+
void this.refresh();
|
|
52
|
+
}
|
|
53
|
+
stop() { clearInterval(this.timer); }
|
|
54
|
+
async refresh() {
|
|
55
|
+
if (this.refreshing) return;
|
|
56
|
+
this.refreshing = true;
|
|
57
|
+
try {
|
|
58
|
+
const queue = [...this.sessions.values()].filter((session) => session.job && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status) && this.hosts().some((host) => host.alias === session.host && host.reachable));
|
|
59
|
+
await Promise.all(Array.from({ length: Math.min(3, queue.length) }, async () => {
|
|
60
|
+
for (let session; (session = queue.shift());) await this.read(session.key);
|
|
61
|
+
}));
|
|
62
|
+
} finally { this.refreshing = false; }
|
|
63
|
+
}
|
|
64
|
+
async send(body) {
|
|
65
|
+
const rawPrompt = String(body.prompt || "").trim();
|
|
66
|
+
if (rawPrompt.length > 60_000) throw new Error("请输入消息(不超过 60000 字符)");
|
|
67
|
+
let session = body.key ? this.sessions.get(body.key) : null;
|
|
68
|
+
const existing = body.key && !session ? this.catalog.get(body.key) : null;
|
|
69
|
+
if (body.key && !session && !existing) throw new Error("找不到会话,请重新扫描");
|
|
70
|
+
const provider = session?.provider || existing?.provider || body.provider;
|
|
71
|
+
const hasRawAttachments = Array.isArray(body.attachments) && body.attachments.length > 0;
|
|
72
|
+
if (!rawPrompt && !hasRawAttachments) throw new Error("请输入消息(不超过 60000 字符)");
|
|
73
|
+
if (!["claude", "antigravity"].includes(provider)) throw new Error("不支持此 Agent");
|
|
74
|
+
const host = session?.host || existing?.host || body.host;
|
|
75
|
+
if (host === LOCAL_HOST) throw new Error("Claude / Antigravity 网页会话暂需选择远程设备;本机历史可浏览");
|
|
76
|
+
if (!this.hosts().some((item) => item.alias === host && item.reachable)) throw new Error("设备当前离线");
|
|
77
|
+
const cwd = workingDirectory(host, session?.cwd || existing?.cwd || body.cwd);
|
|
78
|
+
const scopeKey = String(body.attachmentScope || body.key || "new-session");
|
|
79
|
+
const attachments = hasRawAttachments
|
|
80
|
+
? (this.resolveAttachments
|
|
81
|
+
? this.resolveAttachments(body.attachments, host, { scope: scopeKey })
|
|
82
|
+
: normalizeTurnAttachments(body.attachments))
|
|
83
|
+
: [];
|
|
84
|
+
if (!rawPrompt && !attachments.length) throw new Error("请输入消息(不超过 60000 字符)");
|
|
85
|
+
if (rawPrompt) await this.commands?.validate(host, provider, cwd, rawPrompt);
|
|
86
|
+
if (session && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) throw new Error("上一轮尚未结束或状态待确认,请稍后重试");
|
|
87
|
+
if (session?.turns.length && !session.sessionId) throw new Error("上一轮未返回可续接的会话标识,请新建会话;不会悄悄丢失上下文继续");
|
|
88
|
+
let model = String(body.model ?? session?.model ?? "").trim();
|
|
89
|
+
if (model.length > 200 || /[\x00-\x1f]/.test(model)) throw new Error("模型名称无效");
|
|
90
|
+
const config = { ...this.settings(provider, host), model };
|
|
91
|
+
const permissionMode = body.permissionMode ?? session?.permissionMode ?? (provider === "claude" ? "auto" : "default");
|
|
92
|
+
if (!["auto", "default", "workspace", "plan", ...(provider === "antigravity" ? ["full"] : [])].includes(permissionMode)) throw new Error("不支持此权限设置");
|
|
93
|
+
const effort = String(body.effort ?? session?.effort ?? "");
|
|
94
|
+
if (effort && !["low", "medium", "high", "xhigh", "max"].includes(effort)) throw new Error("不支持此推理强度");
|
|
95
|
+
await this.models?.validate(host, provider, model);
|
|
96
|
+
if (provider === "claude") await this.models?.validateClaudeOptions?.(host, model, effort, permissionMode);
|
|
97
|
+
if (provider === "antigravity" && this.models?.validateAgyOptions) { model = await this.models.validateAgyOptions(host, model, effort, permissionMode); config.model = model; }
|
|
98
|
+
const resumeId = session?.sessionId || existing?.sessionId;
|
|
99
|
+
if (resumeId) await this.lifecycle?.(host, resumeId, "check", provider);
|
|
100
|
+
// Model discovery is asynchronous. Recheck the session after it so two
|
|
101
|
+
// sends cannot claim the same native conversation while discovery runs.
|
|
102
|
+
session = body.key ? this.sessions.get(body.key) || session : session;
|
|
103
|
+
if (session && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) throw new Error("上一轮尚未结束或状态待确认,请稍后重试");
|
|
104
|
+
const displayPrompt = formatUserPromptPreview(rawPrompt, attachments);
|
|
105
|
+
const effectivePrompt = renderInstructionWithAttachments(rawPrompt, attachments);
|
|
106
|
+
if (!session) {
|
|
107
|
+
const key = existing?.key || `cli:${randomUUID()}`;
|
|
108
|
+
session = { key, host, cwd, provider, sessionId: existing?.sessionId || null, title: (rawPrompt || attachments.map((a) => a.name).join(", ")).slice(0, 120), turns: [] };
|
|
109
|
+
this.sessions.set(key, session);
|
|
110
|
+
}
|
|
111
|
+
const task = { id: randomUUID(), host, cwd, provider, interactive: true, prompt: effectivePrompt, permissionMode, effort, resumeSessionId: session.sessionId || null };
|
|
112
|
+
session.effort = effort;
|
|
113
|
+
session.permissionMode = permissionMode;
|
|
114
|
+
session.model = model; session.status = "launching"; session.updatedAt = Date.now();
|
|
115
|
+
session.turns.push({ id: task.id, prompt: displayPrompt, text: "", status: "launching", createdAt: session.updatedAt });
|
|
116
|
+
session.job = task;
|
|
117
|
+
try {
|
|
118
|
+
await this.save();
|
|
119
|
+
await this.adapter.launch(task, { providers: { [provider]: config } });
|
|
120
|
+
session.status = "running";
|
|
121
|
+
session.turns.at(-1).status = "running";
|
|
122
|
+
} catch (error) {
|
|
123
|
+
// A lost launch response may still mean the remote job started. Never retry automatically.
|
|
124
|
+
session.status = "unknown";
|
|
125
|
+
session.turns.at(-1).error = error.message;
|
|
126
|
+
}
|
|
127
|
+
await this.save();
|
|
128
|
+
return this.view(session);
|
|
129
|
+
}
|
|
130
|
+
view(session) {
|
|
131
|
+
const { job, ...value } = session;
|
|
132
|
+
return { ...value, interactive: job?.interactive === true };
|
|
133
|
+
}
|
|
134
|
+
async control(body) {
|
|
135
|
+
const session = this.sessions.get(body.key);
|
|
136
|
+
if (!session?.job?.interactive) throw new Error("此会话没有可用交互通道");
|
|
137
|
+
if (!["running", "waiting_permission"].includes(session.status)) throw new Error("会话未在运行或正在结束,请刷新后重试");
|
|
138
|
+
if (!this.hosts().some(h => h.alias === session.host && h.reachable)) throw new Error("设备当前离线,未发送控制请求");
|
|
139
|
+
const control = { id: String(body.id || randomUUID()), action: body.action };
|
|
140
|
+
if (!/^[a-f0-9-]{36}$/.test(control.id)) throw new Error("请求标识无效");
|
|
141
|
+
if (body.action === "message") {
|
|
142
|
+
const rawPrompt = String(body.prompt || "").trim();
|
|
143
|
+
const hasRawAttachments = Array.isArray(body.attachments) && body.attachments.length > 0;
|
|
144
|
+
const attachments = hasRawAttachments
|
|
145
|
+
? (this.resolveAttachments
|
|
146
|
+
? this.resolveAttachments(body.attachments, session.host, { scope: session.key })
|
|
147
|
+
: normalizeTurnAttachments(body.attachments))
|
|
148
|
+
: [];
|
|
149
|
+
if ((!rawPrompt && !attachments.length) || rawPrompt.length > 60000) throw new Error("请输入消息(不超过 60000 字符)");
|
|
150
|
+
if (rawPrompt) await this.commands?.validate(session.host, session.provider, session.cwd, rawPrompt, session.commands);
|
|
151
|
+
control.prompt = renderInstructionWithAttachments(rawPrompt, attachments);
|
|
152
|
+
} else if (body.action === "permission") {
|
|
153
|
+
if (!["allow", "deny", ...(session.provider === "antigravity" ? ["cancel"] : [])].includes(body.decision)) throw new Error("无效审批结果");
|
|
154
|
+
control.requestId = String(body.requestId || ""); control.decision = body.decision;
|
|
155
|
+
if (body.optionId !== undefined) control.optionId = String(body.optionId);
|
|
156
|
+
if (body.content !== undefined) {
|
|
157
|
+
if (!body.content || typeof body.content !== "object" || Array.isArray(body.content) || JSON.stringify(body.content).length > 60000) throw new Error("表单内容无效");
|
|
158
|
+
control.content = body.content;
|
|
159
|
+
}
|
|
160
|
+
if (body.answers) {
|
|
161
|
+
if (typeof body.answers !== "object" || Array.isArray(body.answers) || Object.values(body.answers).some(v => typeof v !== "string" || v.length > 10000)) throw new Error("回答格式无效");
|
|
162
|
+
control.answers = body.answers;
|
|
163
|
+
}
|
|
164
|
+
} else if (body.action !== "stop") throw new Error("不支持的控制操作");
|
|
165
|
+
await this.adapter.control(session.job, control);
|
|
166
|
+
return { controlId: control.id, status: "queued" };
|
|
167
|
+
}
|
|
168
|
+
async changeState({ key, action }) {
|
|
169
|
+
if (!["archive", "delete", "restore"].includes(action)) throw new Error("无效操作");
|
|
170
|
+
const entry = this.sessions.get(key) || this.catalog.get(key);
|
|
171
|
+
if (!entry || !["claude", "antigravity"].includes(entry.provider) || !entry.sessionId) throw new Error("仅支持已有 Claude / Antigravity 会话");
|
|
172
|
+
if (["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(entry.status)) throw new Error("会话仍在运行或状态待确认");
|
|
173
|
+
if (!this.hosts().some(h => h.alias === entry.host && h.reachable)) throw new Error("主机离线,未修改归档状态");
|
|
174
|
+
if (!this.lifecycle) throw new Error("远端归档服务不可用");
|
|
175
|
+
const result = await this.lifecycle(entry.host, entry.sessionId, action, entry.provider);
|
|
176
|
+
for (const item of this.sessions.values()) if (item.host === entry.host && item.provider === entry.provider && item.sessionId === entry.sessionId) item.phase = result.phase;
|
|
177
|
+
// Update the cached catalog immediately, then reconcile against remote state.
|
|
178
|
+
for (const item of this.catalog.records?.values() || []) if (item.host === entry.host && item.provider === entry.provider && item.sessionId === entry.sessionId) item.phase = result.phase;
|
|
179
|
+
await this.save();
|
|
180
|
+
void this.catalog.refresh(true);
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
async read(key) {
|
|
184
|
+
const session = this.sessions.get(key);
|
|
185
|
+
if (!session) return null;
|
|
186
|
+
if (session.job && ["launching", "running", "waiting_permission", "stopping", "finishing", "unknown"].includes(session.status)) {
|
|
187
|
+
if (!this.pending.has(key)) {
|
|
188
|
+
this.pending.set(key, this.poll(session).finally(() => this.pending.delete(key)));
|
|
189
|
+
}
|
|
190
|
+
await this.pending.get(key);
|
|
191
|
+
}
|
|
192
|
+
return this.view(session);
|
|
193
|
+
}
|
|
194
|
+
async poll(session) {
|
|
195
|
+
try {
|
|
196
|
+
const result = await this.adapter.poll(session.job);
|
|
197
|
+
const turn = session.turns.at(-1);
|
|
198
|
+
if (session.job.interactive) {
|
|
199
|
+
session.sessionId = result.sessionId || session.sessionId;
|
|
200
|
+
turn.events = result.events || turn.events || [];
|
|
201
|
+
turn.partial = result.partial || "";
|
|
202
|
+
turn.truncated = Boolean(result.truncated);
|
|
203
|
+
session.permissions = result.permissions || [];
|
|
204
|
+
session.controlResults = result.controlResults || [];
|
|
205
|
+
if (Array.isArray(result.commands)) session.commands = result.commands;
|
|
206
|
+
if (Array.isArray(result.subagents)) {
|
|
207
|
+
session.subagents = result.subagents;
|
|
208
|
+
turn.subagents = result.subagents;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (["completed", "failed", "stopped"].includes(result.status)) {
|
|
212
|
+
session.status = result.status;
|
|
213
|
+
session.sessionId = result.sessionId || session.sessionId;
|
|
214
|
+
turn.status = result.status; turn.text = (result.text || "").slice(-120_000); turn.error = result.error || null; turn.errorCode = result.errorCode || null;
|
|
215
|
+
if (["stopped", "failed"].includes(result.status) && Array.isArray(session.subagents)) {
|
|
216
|
+
session.subagents = session.subagents.map((item) =>
|
|
217
|
+
item?.status === "working" ? { ...item, status: result.status } : item,
|
|
218
|
+
);
|
|
219
|
+
turn.subagents = session.subagents;
|
|
220
|
+
}
|
|
221
|
+
session.updatedAt = Date.now();
|
|
222
|
+
await this.save();
|
|
223
|
+
void this.catalog.refresh(true);
|
|
224
|
+
} else {
|
|
225
|
+
session.status = ["running", "waiting_permission", "stopping", "finishing"].includes(result.status) ? result.status : "unknown";
|
|
226
|
+
turn.status = session.status;
|
|
227
|
+
turn.error = result.error || null;
|
|
228
|
+
}
|
|
229
|
+
} catch (error) { session.turns.at(-1).error = `读取进度失败:${error.message}`; }
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
"""Discover session-scoped commands without sending a prompt. No account data exported."""
|
|
2
|
-
import json
|
|
3
|
-
import os
|
|
4
|
-
import selectors
|
|
5
|
-
import subprocess
|
|
6
|
-
import sys
|
|
7
|
-
import time
|
|
8
|
-
|
|
9
|
-
provider, executable, cwd = sys.argv[1:4]
|
|
10
|
-
if provider != "claude": raise ValueError("Use the owned ACP session command catalog")
|
|
11
|
-
args = [executable, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--no-session-persistence"]
|
|
12
|
-
child = subprocess.Popen(args, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, start_new_session=True)
|
|
13
|
-
def send(value):
|
|
14
|
-
child.stdin.write((json.dumps(value) + "\n").encode()); child.stdin.flush()
|
|
15
|
-
try:
|
|
16
|
-
send({"type": "control_request", "request_id": "commands", "request": {"subtype": "initialize", "hooks": {}}})
|
|
17
|
-
selector = selectors.DefaultSelector(); selector.register(child.stdout, selectors.EVENT_READ)
|
|
18
|
-
buffer, deadline, found = b"", time.monotonic() + 25, False
|
|
19
|
-
while time.monotonic() < deadline and not found:
|
|
20
|
-
if not selector.select(.5): continue
|
|
21
|
-
chunk = os.read(child.stdout.fileno(), 65536)
|
|
22
|
-
if not chunk: break
|
|
23
|
-
buffer += chunk
|
|
24
|
-
if len(buffer) > 1000000: raise RuntimeError("Command catalog exceeds limit")
|
|
25
|
-
while b"\n" in buffer:
|
|
26
|
-
line, buffer = buffer.split(b"\n", 1)
|
|
27
|
-
try: value = json.loads(line)
|
|
28
|
-
except ValueError: continue
|
|
29
|
-
if provider == "claude" and value.get("type") == "control_response":
|
|
30
|
-
response = value.get("response", {})
|
|
31
|
-
if response.get("subtype") == "error": raise RuntimeError("Claude command discovery failed")
|
|
32
|
-
print(json.dumps({"commands": response.get("response", {}).get("commands", [])})); found = True; break
|
|
33
|
-
if not found: raise RuntimeError("Agent did not return command catalog")
|
|
34
|
-
finally:
|
|
35
|
-
import signal
|
|
36
|
-
os.killpg(child.pid, signal.SIGTERM) if child.poll() is None else None
|
|
37
|
-
try: child.wait(timeout=3)
|
|
38
|
-
except subprocess.TimeoutExpired: os.killpg(child.pid, signal.SIGKILL); child.wait()
|
|
1
|
+
"""Discover session-scoped commands without sending a prompt. No account data exported."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import selectors
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
provider, executable, cwd = sys.argv[1:4]
|
|
10
|
+
if provider != "claude": raise ValueError("Use the owned ACP session command catalog")
|
|
11
|
+
args = [executable, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--no-session-persistence"]
|
|
12
|
+
child = subprocess.Popen(args, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, start_new_session=True)
|
|
13
|
+
def send(value):
|
|
14
|
+
child.stdin.write((json.dumps(value) + "\n").encode()); child.stdin.flush()
|
|
15
|
+
try:
|
|
16
|
+
send({"type": "control_request", "request_id": "commands", "request": {"subtype": "initialize", "hooks": {}}})
|
|
17
|
+
selector = selectors.DefaultSelector(); selector.register(child.stdout, selectors.EVENT_READ)
|
|
18
|
+
buffer, deadline, found = b"", time.monotonic() + 25, False
|
|
19
|
+
while time.monotonic() < deadline and not found:
|
|
20
|
+
if not selector.select(.5): continue
|
|
21
|
+
chunk = os.read(child.stdout.fileno(), 65536)
|
|
22
|
+
if not chunk: break
|
|
23
|
+
buffer += chunk
|
|
24
|
+
if len(buffer) > 1000000: raise RuntimeError("Command catalog exceeds limit")
|
|
25
|
+
while b"\n" in buffer:
|
|
26
|
+
line, buffer = buffer.split(b"\n", 1)
|
|
27
|
+
try: value = json.loads(line)
|
|
28
|
+
except ValueError: continue
|
|
29
|
+
if provider == "claude" and value.get("type") == "control_response":
|
|
30
|
+
response = value.get("response", {})
|
|
31
|
+
if response.get("subtype") == "error": raise RuntimeError("Claude command discovery failed")
|
|
32
|
+
print(json.dumps({"commands": response.get("response", {}).get("commands", [])})); found = True; break
|
|
33
|
+
if not found: raise RuntimeError("Agent did not return command catalog")
|
|
34
|
+
finally:
|
|
35
|
+
import signal
|
|
36
|
+
os.killpg(child.pid, signal.SIGTERM) if child.poll() is None else None
|
|
37
|
+
try: child.wait(timeout=3)
|
|
38
|
+
except subprocess.TimeoutExpired: os.killpg(child.pid, signal.SIGKILL); child.wait()
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { shellQuote } from "./cli-command.mjs";
|
|
3
|
-
const source = readFile(new URL("./native-session-state.py", import.meta.url), "utf8");
|
|
4
|
-
export async function nativeGuardCommand(payload) {
|
|
5
|
-
const code = Buffer.from(await source).toString("base64");
|
|
6
|
-
return `python3 -c ${shellQuote(`import base64;exec(base64.b64decode('${code}'))`)} ${shellQuote(Buffer.from(JSON.stringify(payload)).toString("base64url"))}`;
|
|
7
|
-
}
|
|
8
|
-
export function nativeSessionState(run) {
|
|
9
|
-
return async (host, sessionId, action, provider = "claude") => {
|
|
10
|
-
const result = await run(host, await nativeGuardCommand({ sessionId, action, provider }), "", 15000, 64000);
|
|
11
|
-
if (result.code !== 0) throw new Error((result.stderr || "无法核实 Agent 会话状态").trim().split("\n").at(-1));
|
|
12
|
-
return JSON.parse(result.stdout.trim());
|
|
13
|
-
};
|
|
14
|
-
}
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { shellQuote } from "./cli-command.mjs";
|
|
3
|
+
const source = readFile(new URL("./native-session-state.py", import.meta.url), "utf8");
|
|
4
|
+
export async function nativeGuardCommand(payload) {
|
|
5
|
+
const code = Buffer.from(await source).toString("base64");
|
|
6
|
+
return `python3 -c ${shellQuote(`import base64;exec(base64.b64decode('${code}'))`)} ${shellQuote(Buffer.from(JSON.stringify(payload)).toString("base64url"))}`;
|
|
7
|
+
}
|
|
8
|
+
export function nativeSessionState(run) {
|
|
9
|
+
return async (host, sessionId, action, provider = "claude") => {
|
|
10
|
+
const result = await run(host, await nativeGuardCommand({ sessionId, action, provider }), "", 15000, 64000);
|
|
11
|
+
if (result.code !== 0) throw new Error((result.stderr || "无法核实 Agent 会话状态").trim().split("\n").at(-1));
|
|
12
|
+
return JSON.parse(result.stdout.trim());
|
|
13
|
+
};
|
|
14
|
+
}
|