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.
Files changed (88) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/bridge/agent-email-relay.mjs +160 -160
  3. package/bridge/app-server-websocket-transport.mjs +219 -219
  4. package/bridge/archive/service.mjs +130 -130
  5. package/bridge/auth-profile-failover.mjs +58 -58
  6. package/bridge/auth-profile-manager.mjs +215 -215
  7. package/bridge/capacity-recovery.mjs +90 -90
  8. package/bridge/gpu-usage-history.mjs +322 -322
  9. package/bridge/local/history.mjs +20 -5
  10. package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -236
  11. package/bridge/plugins/aliyun-dlc/probe.mjs +701 -701
  12. package/bridge/private-gateway.mjs +371 -371
  13. package/bridge/private-start.mjs +22 -22
  14. package/bridge/probes/app-server-handoff-probe.mjs +87 -87
  15. package/bridge/probes/app-server-writer-probe.mjs +69 -69
  16. package/bridge/probes/assistant-search-probe.mjs +321 -321
  17. package/bridge/probes/dialogue-probe.mjs +462 -462
  18. package/bridge/probes/history-probe.mjs +430 -345
  19. package/bridge/probes/new-session-preflight.mjs +14 -14
  20. package/bridge/probes/profile-cancel-probe.mjs +17 -17
  21. package/bridge/probes/profile-delete-probe.mjs +26 -26
  22. package/bridge/probes/profile-list-probe.mjs +114 -114
  23. package/bridge/probes/profile-write-probe.mjs +109 -109
  24. package/bridge/probes/raw-context-probe.mjs +51 -51
  25. package/bridge/probes/remote-probe.mjs +627 -626
  26. package/bridge/probes/submission-probe.mjs +2 -2
  27. package/bridge/probes/takeover-probe.mjs +326 -326
  28. package/bridge/probes/vscode-open-preflight.mjs +21 -21
  29. package/bridge/providers/claude-interactive.py +463 -341
  30. package/bridge/providers/cli-command.mjs +103 -103
  31. package/bridge/providers/conversations.mjs +231 -231
  32. package/bridge/providers/native-commands.py +38 -38
  33. package/bridge/providers/native-session-state.mjs +14 -14
  34. package/bridge/providers/native-session-state.py +96 -96
  35. package/bridge/providers/remote-job.py +130 -130
  36. package/bridge/remote-app-server-command.mjs +121 -121
  37. package/bridge/remote-directory-listing.mjs +148 -148
  38. package/bridge/rollout-summary.mjs +20 -2
  39. package/bridge/routes/dialogue.mjs +48 -3
  40. package/bridge/routes/models.mjs +312 -312
  41. package/bridge/server.mjs +3357 -3332
  42. package/bridge/session-attachments.mjs +150 -150
  43. package/bridge/session-catalog/agy-history.py +141 -2
  44. package/bridge/session-catalog/catalog.mjs +17 -0
  45. package/bridge/session-catalog/probe.py +1207 -331
  46. package/bridge/session-catalog/routes.mjs +6 -0
  47. package/bridge/start.mjs +205 -205
  48. package/bridge/state-persistence.mjs +9 -1
  49. package/bridge/tmux-session-control.mjs +29 -29
  50. package/bridge/vscode-opener.mjs +157 -157
  51. package/bridge/web-terminal.mjs +52 -52
  52. package/bridge/workbench/manager-context.mjs +51 -51
  53. package/bridge/workbench/service.mjs +301 -301
  54. package/dist/client/.vite/manifest.json +4 -4
  55. package/dist/client/assets/{index-Enu1x0PS.js → index-BMior55c.js} +2 -2
  56. package/dist/client/assets/{layout-segment-context-CmJzExWq.js → layout-segment-context-DjGudgXn.js} +1 -1
  57. package/dist/client/assets/page-CJqXlhDs.js +551 -0
  58. package/dist/client/assets/page-LYzRz6_S.css +1 -0
  59. package/dist/client/favicon.svg +6 -6
  60. package/dist/server/__vite_rsc_assets_manifest.js +8 -8
  61. package/dist/server/index.js +7 -7
  62. package/dist/server/ssr/__vite_rsc_assets_manifest.js +8 -8
  63. package/dist/server/ssr/assets/{page-CYYyCnKD.js → page-BB9Dri2u.js} +2416 -271
  64. package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -0
  65. package/dist/server/ssr/index.js +1 -1
  66. package/dist/server/ssr/vinext-server.json +1 -1
  67. package/dist/server/vinext-server.json +1 -1
  68. package/dist/server/wrangler.json +1 -1
  69. package/lib/browser-snapshot-cache.js +53 -53
  70. package/lib/formula-preview.js +1 -1
  71. package/lib/incremental-snapshot.js +300 -300
  72. package/lib/markdown-math.js +151 -151
  73. package/lib/remote-links.js +95 -95
  74. package/lib/runtime-config.js +70 -70
  75. package/lib/session-filters.js +38 -38
  76. package/lib/ssh-config.js +26 -26
  77. package/lib/stable-order.js +39 -39
  78. package/lib/subagent-display-prefs.ts +130 -0
  79. package/package.json +1 -1
  80. package/scripts/agent-email-relay.mjs +104 -104
  81. package/scripts/email-notification-cli.mjs +28 -28
  82. package/scripts/enable-private-access.ps1 +109 -109
  83. package/scripts/fixtures/native-conversations.mjs +164 -6
  84. package/scripts/fixtures/workbench-conversations.mjs +475 -352
  85. package/scripts/preview-workbench.mjs +669 -669
  86. package/dist/client/assets/page-COBv6VWj.css +0 -1
  87. package/dist/client/assets/page-DVjU6VG_.js +0 -550
  88. package/dist/server/ssr/assets/page-COBv6VWj.css +0 -1
@@ -1,150 +1,150 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdir, open, readdir, rm, stat } from "node:fs/promises";
3
- import path from "node:path";
4
-
5
- export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024;
6
- export const MAX_ATTACHMENTS_PER_TURN = 8;
7
- export const MAX_ATTACHMENTS_TOTAL_BYTES = 100 * 1024 * 1024;
8
- const LOCAL_RETENTION_MS = 7 * 24 * 60 * 60_000;
9
-
10
- const STRUCTURED_IMAGE_MIME_TYPES = new Set([
11
- "image/gif",
12
- "image/jpeg",
13
- "image/png",
14
- "image/webp",
15
- ]);
16
-
17
- function cleanString(value, limit) {
18
- return typeof value === "string" ? value.trim().slice(0, limit) : "";
19
- }
20
-
21
- export function safeAttachmentFilename(value, uniqueSuffix = "") {
22
- const original = path.posix.basename(String(value || "attachment").replaceAll("\\", "/"));
23
- const extensionMatch = original.match(/(\.[a-zA-Z0-9]{1,12})$/);
24
- const extension = extensionMatch?.[1]?.toLowerCase() || "";
25
- const stem = original
26
- .slice(0, Math.max(0, original.length - extension.length))
27
- .normalize("NFKD")
28
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
29
- .replace(/^[-._]+|[-._]+$/g, "")
30
- .slice(0, 72) || "attachment";
31
- const suffix = String(uniqueSuffix || "")
32
- .replace(/[^a-zA-Z0-9_-]+/g, "")
33
- .slice(0, 32);
34
- return `${stem}${suffix ? `-${suffix}` : ""}${extension}`;
35
- }
36
-
37
- export function attachmentKind(mimeType) {
38
- return STRUCTURED_IMAGE_MIME_TYPES.has(cleanString(mimeType, 200).toLowerCase())
39
- ? "image"
40
- : "file";
41
- }
42
-
43
- export function isValidAttachmentPath(value) {
44
- return typeof value === "string" && (value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value));
45
- }
46
-
47
- export function normalizeTurnAttachments(value) {
48
- if (!Array.isArray(value)) return [];
49
- return value
50
- .slice(0, MAX_ATTACHMENTS_PER_TURN)
51
- .map((attachment) => ({
52
- name: cleanString(attachment?.name, 240) || "attachment",
53
- mimeType: cleanString(attachment?.mimeType, 200) || "application/octet-stream",
54
- size: Math.max(0, Math.floor(Number(attachment?.size) || 0)),
55
- remotePath: cleanString(attachment?.remotePath, 4_000),
56
- kind: attachment?.kind === "image" ? "image" : "file",
57
- }))
58
- .filter((attachment) => isValidAttachmentPath(attachment.remotePath));
59
- }
60
-
61
- export function formatUserPromptPreview(prompt, attachments = []) {
62
- const normalized = normalizeTurnAttachments(attachments);
63
- const text = typeof prompt === "string" ? prompt.trim() : "";
64
- if (!normalized.length) return text;
65
- const names = normalized.map((item) => item.name).join(", ");
66
- return text ? `${text}\n\n[附件: ${names}]` : `[附件: ${names}]`;
67
- }
68
-
69
- export function renderInstructionWithAttachments(prompt, attachments = []) {
70
- const normalized = normalizeTurnAttachments(attachments);
71
- // Callers validate their own prompt limits; formatting must not discard instructions.
72
- const text = typeof prompt === "string" ? prompt.trim() : "";
73
- if (!normalized.length) return text;
74
- const manifest = normalized.map(
75
- (attachment) =>
76
- `- ${attachment.name} (${attachment.mimeType}, ${attachment.size} bytes): ${attachment.remotePath}`,
77
- );
78
- return [
79
- text || "请查看并处理本条消息附带的文件。",
80
- "",
81
- "[SCOPE 网页附件:文件已安全上传到当前目标主机,请按以下绝对路径读取]",
82
- ...manifest,
83
- ].join("\n");
84
- }
85
-
86
- async function pruneOldLocalAttachments(dir, cutoffMs, depth = 0) {
87
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
88
- for (const entry of entries) {
89
- const entryPath = path.join(dir, entry.name);
90
- if (entry.isDirectory()) {
91
- if (depth < 2) {
92
- await pruneOldLocalAttachments(entryPath, cutoffMs, depth + 1);
93
- }
94
- const remaining = await readdir(entryPath).catch(() => ["keep"]);
95
- if (!remaining.length) await rm(entryPath, { recursive: true, force: true }).catch(() => {});
96
- } else if (entry.isFile()) {
97
- const info = await stat(entryPath).catch(() => null);
98
- if (info && info.mtimeMs < cutoffMs) {
99
- await rm(entryPath, { force: true }).catch(() => {});
100
- }
101
- }
102
- }
103
- }
104
-
105
- export async function streamAttachmentToLocal(request, { baseDir, scopeSegment, uploadId, filename }) {
106
- const declaredLength = Number(request.headers?.["content-length"] || 0);
107
- if (Number.isFinite(declaredLength) && declaredLength > MAX_ATTACHMENT_BYTES) {
108
- request.resume?.();
109
- throw Object.assign(new Error("单个附件不能超过 50 MiB"), { statusCode: 413 });
110
- }
111
- await pruneOldLocalAttachments(baseDir, Date.now() - LOCAL_RETENTION_MS).catch(() => {});
112
- const targetDir = path.join(baseDir, scopeSegment, uploadId);
113
- await mkdir(targetDir, { recursive: true, mode: 0o700 });
114
- const targetFile = path.join(targetDir, filename);
115
- // Open exclusively before consuming the request. FileHandle failures are caught
116
- // promises, rather than an early unhandled WriteStream error event.
117
- const writer = await open(targetFile, "wx", 0o600);
118
- let size = 0;
119
- const hash = createHash("sha256");
120
- try {
121
- for await (const rawChunk of request) {
122
- const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
123
- size += chunk.length;
124
- if (size > MAX_ATTACHMENT_BYTES) {
125
- request.resume?.();
126
- throw Object.assign(new Error("单个附件不能超过 50 MiB"), { statusCode: 413 });
127
- }
128
- hash.update(chunk);
129
- await writer.writeFile(chunk);
130
- }
131
- await writer.close();
132
- } catch (error) {
133
- await writer.close().catch(() => {});
134
- await rm(targetFile, { force: true }).catch(() => {});
135
- throw error;
136
- }
137
- return { remotePath: targetFile, size, sha256: hash.digest("hex") };
138
- }
139
-
140
- export function appServerTurnInput(prompt, attachments = []) {
141
- const normalized = normalizeTurnAttachments(attachments);
142
- const text = renderInstructionWithAttachments(prompt, normalized);
143
- const input = text ? [{ type: "text", text, text_elements: [] }] : [];
144
- for (const attachment of normalized) {
145
- if (attachment.kind === "image") {
146
- input.push({ type: "localImage", path: attachment.remotePath });
147
- }
148
- }
149
- return input;
150
- }
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, open, readdir, rm, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024;
6
+ export const MAX_ATTACHMENTS_PER_TURN = 8;
7
+ export const MAX_ATTACHMENTS_TOTAL_BYTES = 100 * 1024 * 1024;
8
+ const LOCAL_RETENTION_MS = 7 * 24 * 60 * 60_000;
9
+
10
+ const STRUCTURED_IMAGE_MIME_TYPES = new Set([
11
+ "image/gif",
12
+ "image/jpeg",
13
+ "image/png",
14
+ "image/webp",
15
+ ]);
16
+
17
+ function cleanString(value, limit) {
18
+ return typeof value === "string" ? value.trim().slice(0, limit) : "";
19
+ }
20
+
21
+ export function safeAttachmentFilename(value, uniqueSuffix = "") {
22
+ const original = path.posix.basename(String(value || "attachment").replaceAll("\\", "/"));
23
+ const extensionMatch = original.match(/(\.[a-zA-Z0-9]{1,12})$/);
24
+ const extension = extensionMatch?.[1]?.toLowerCase() || "";
25
+ const stem = original
26
+ .slice(0, Math.max(0, original.length - extension.length))
27
+ .normalize("NFKD")
28
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
29
+ .replace(/^[-._]+|[-._]+$/g, "")
30
+ .slice(0, 72) || "attachment";
31
+ const suffix = String(uniqueSuffix || "")
32
+ .replace(/[^a-zA-Z0-9_-]+/g, "")
33
+ .slice(0, 32);
34
+ return `${stem}${suffix ? `-${suffix}` : ""}${extension}`;
35
+ }
36
+
37
+ export function attachmentKind(mimeType) {
38
+ return STRUCTURED_IMAGE_MIME_TYPES.has(cleanString(mimeType, 200).toLowerCase())
39
+ ? "image"
40
+ : "file";
41
+ }
42
+
43
+ export function isValidAttachmentPath(value) {
44
+ return typeof value === "string" && (value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value));
45
+ }
46
+
47
+ export function normalizeTurnAttachments(value) {
48
+ if (!Array.isArray(value)) return [];
49
+ return value
50
+ .slice(0, MAX_ATTACHMENTS_PER_TURN)
51
+ .map((attachment) => ({
52
+ name: cleanString(attachment?.name, 240) || "attachment",
53
+ mimeType: cleanString(attachment?.mimeType, 200) || "application/octet-stream",
54
+ size: Math.max(0, Math.floor(Number(attachment?.size) || 0)),
55
+ remotePath: cleanString(attachment?.remotePath, 4_000),
56
+ kind: attachment?.kind === "image" ? "image" : "file",
57
+ }))
58
+ .filter((attachment) => isValidAttachmentPath(attachment.remotePath));
59
+ }
60
+
61
+ export function formatUserPromptPreview(prompt, attachments = []) {
62
+ const normalized = normalizeTurnAttachments(attachments);
63
+ const text = typeof prompt === "string" ? prompt.trim() : "";
64
+ if (!normalized.length) return text;
65
+ const names = normalized.map((item) => item.name).join(", ");
66
+ return text ? `${text}\n\n[附件: ${names}]` : `[附件: ${names}]`;
67
+ }
68
+
69
+ export function renderInstructionWithAttachments(prompt, attachments = []) {
70
+ const normalized = normalizeTurnAttachments(attachments);
71
+ // Callers validate their own prompt limits; formatting must not discard instructions.
72
+ const text = typeof prompt === "string" ? prompt.trim() : "";
73
+ if (!normalized.length) return text;
74
+ const manifest = normalized.map(
75
+ (attachment) =>
76
+ `- ${attachment.name} (${attachment.mimeType}, ${attachment.size} bytes): ${attachment.remotePath}`,
77
+ );
78
+ return [
79
+ text || "请查看并处理本条消息附带的文件。",
80
+ "",
81
+ "[SCOPE 网页附件:文件已安全上传到当前目标主机,请按以下绝对路径读取]",
82
+ ...manifest,
83
+ ].join("\n");
84
+ }
85
+
86
+ async function pruneOldLocalAttachments(dir, cutoffMs, depth = 0) {
87
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
88
+ for (const entry of entries) {
89
+ const entryPath = path.join(dir, entry.name);
90
+ if (entry.isDirectory()) {
91
+ if (depth < 2) {
92
+ await pruneOldLocalAttachments(entryPath, cutoffMs, depth + 1);
93
+ }
94
+ const remaining = await readdir(entryPath).catch(() => ["keep"]);
95
+ if (!remaining.length) await rm(entryPath, { recursive: true, force: true }).catch(() => {});
96
+ } else if (entry.isFile()) {
97
+ const info = await stat(entryPath).catch(() => null);
98
+ if (info && info.mtimeMs < cutoffMs) {
99
+ await rm(entryPath, { force: true }).catch(() => {});
100
+ }
101
+ }
102
+ }
103
+ }
104
+
105
+ export async function streamAttachmentToLocal(request, { baseDir, scopeSegment, uploadId, filename }) {
106
+ const declaredLength = Number(request.headers?.["content-length"] || 0);
107
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_ATTACHMENT_BYTES) {
108
+ request.resume?.();
109
+ throw Object.assign(new Error("单个附件不能超过 50 MiB"), { statusCode: 413 });
110
+ }
111
+ await pruneOldLocalAttachments(baseDir, Date.now() - LOCAL_RETENTION_MS).catch(() => {});
112
+ const targetDir = path.join(baseDir, scopeSegment, uploadId);
113
+ await mkdir(targetDir, { recursive: true, mode: 0o700 });
114
+ const targetFile = path.join(targetDir, filename);
115
+ // Open exclusively before consuming the request. FileHandle failures are caught
116
+ // promises, rather than an early unhandled WriteStream error event.
117
+ const writer = await open(targetFile, "wx", 0o600);
118
+ let size = 0;
119
+ const hash = createHash("sha256");
120
+ try {
121
+ for await (const rawChunk of request) {
122
+ const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk);
123
+ size += chunk.length;
124
+ if (size > MAX_ATTACHMENT_BYTES) {
125
+ request.resume?.();
126
+ throw Object.assign(new Error("单个附件不能超过 50 MiB"), { statusCode: 413 });
127
+ }
128
+ hash.update(chunk);
129
+ await writer.writeFile(chunk);
130
+ }
131
+ await writer.close();
132
+ } catch (error) {
133
+ await writer.close().catch(() => {});
134
+ await rm(targetFile, { force: true }).catch(() => {});
135
+ throw error;
136
+ }
137
+ return { remotePath: targetFile, size, sha256: hash.digest("hex") };
138
+ }
139
+
140
+ export function appServerTurnInput(prompt, attachments = []) {
141
+ const normalized = normalizeTurnAttachments(attachments);
142
+ const text = renderInstructionWithAttachments(prompt, normalized);
143
+ const input = text ? [{ type: "text", text, text_elements: [] }] : [];
144
+ for (const attachment of normalized) {
145
+ if (attachment.kind === "image") {
146
+ input.push({ type: "localImage", path: attachment.remotePath });
147
+ }
148
+ }
149
+ return input;
150
+ }
@@ -4,9 +4,18 @@ import json
4
4
  import os
5
5
  from pathlib import Path
6
6
  import re
7
+ import subprocess
7
8
  import sys
8
9
  import time
9
10
 
11
+ try:
12
+ import fcntl
13
+ except ImportError:
14
+ fcntl = None
15
+
16
+ if hasattr(sys.stdout, "reconfigure"):
17
+ sys.stdout.reconfigure(encoding="utf-8")
18
+
10
19
  MAX_BYTES = 2_000_000
11
20
  MAX_ROWS = 100
12
21
  MAX_TEXT = 30_000
@@ -190,16 +199,146 @@ def extract_subagents(root, filename):
190
199
  return result
191
200
 
192
201
 
202
+ def _scope_agy_lock_active(sid):
203
+ if fcntl is None or not sid:
204
+ return False
205
+ lock_file = Path.home() / ".local/state/scope/antigravity-sessions" / f"{sid}.lock"
206
+ if not lock_file.is_file():
207
+ return False
208
+ try:
209
+ with lock_file.open("r") as handle:
210
+ try:
211
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
212
+ except BlockingIOError:
213
+ return True
214
+ else:
215
+ fcntl.flock(handle, fcntl.LOCK_UN)
216
+ return False
217
+ except OSError:
218
+ return False
219
+
220
+
221
+ def _read_proc_cmdline(pid):
222
+ try:
223
+ raw = Path(f"/proc/{pid}/cmdline").read_bytes()
224
+ return [part for part in raw.decode("utf-8", errors="replace").split("\0") if part]
225
+ except OSError:
226
+ return []
227
+
228
+
229
+ def _read_proc_ppid(pid):
230
+ try:
231
+ txt = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
232
+ rparen = txt.rfind(")")
233
+ if rparen < 0:
234
+ return 0
235
+ fields = txt[rparen + 2:].split()
236
+ return int(fields[1]) if len(fields) > 1 else 0
237
+ except (OSError, ValueError):
238
+ return 0
239
+
240
+
241
+ def detect_agy_external_lock(sid):
242
+ if os.name == "nt" or not sid or _scope_agy_lock_active(sid):
243
+ return None
244
+ presence_locked = False
245
+ lock_file = Path.home() / ".gemini/antigravity-cli/presence" / f"{sid}.lock"
246
+ if fcntl is not None and lock_file.is_file():
247
+ try:
248
+ with lock_file.open("r") as handle:
249
+ try:
250
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
251
+ except BlockingIOError:
252
+ presence_locked = True
253
+ else:
254
+ fcntl.flock(handle, fcntl.LOCK_UN)
255
+ except OSError:
256
+ pass
257
+ holder_pid = 0
258
+ proc_root = Path("/proc")
259
+ if proc_root.is_dir():
260
+ for cmd_file in proc_root.glob("[0-9]*/cmdline"):
261
+ try:
262
+ pid = int(cmd_file.parent.name)
263
+ args = [p for p in cmd_file.read_bytes().decode("utf-8", errors="replace").split("\0") if p]
264
+ except (OSError, ValueError):
265
+ continue
266
+ if not args or not any(Path(a).name == "agy" or "antigravity" in Path(a).name for a in args[:2]):
267
+ continue
268
+ matched = any(args[i] in ("--conversation", "-c") and i + 1 < len(args) and args[i + 1] == sid for i in range(len(args)))
269
+ if not matched:
270
+ try:
271
+ for fd_link in (cmd_file.parent / "fd").iterdir():
272
+ try:
273
+ target = os.readlink(str(fd_link))
274
+ except OSError:
275
+ continue
276
+ if target.endswith(f"/antigravity-cli/presence/{sid}.lock"):
277
+ matched = True
278
+ break
279
+ except OSError:
280
+ pass
281
+ if matched:
282
+ holder_pid = pid
283
+ break
284
+ if not presence_locked and not holder_pid:
285
+ return None
286
+ is_scope = False
287
+ tty = ""
288
+ in_tmux = False
289
+ if holder_pid:
290
+ args = _read_proc_cmdline(holder_pid)
291
+ if len(args) >= 2 and Path(args[0]).name == "agy" and args[1] == "acp":
292
+ is_scope = True
293
+ if not is_scope:
294
+ cur = holder_pid
295
+ for _ in range(5):
296
+ ppid = _read_proc_ppid(cur)
297
+ if ppid <= 1 or ppid == cur:
298
+ break
299
+ pargs = " ".join(_read_proc_cmdline(ppid))
300
+ if ".local/state/scope/runs" in pargs or "antigravity-interactive" in pargs or "native-session-state" in pargs:
301
+ is_scope = True
302
+ break
303
+ cur = ppid
304
+ if is_scope:
305
+ return None
306
+ try:
307
+ link = os.readlink(f"/proc/{holder_pid}/fd/0")
308
+ if link.startswith("/dev/pts/") or link.startswith("/dev/tty"):
309
+ tty = link[len("/dev/"):]
310
+ try:
311
+ proc = subprocess.run(["tmux", "list-panes", "-a", "-F", "#{pane_tty}"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=1.5)
312
+ if proc.returncode == 0 and link in proc.stdout.splitlines():
313
+ in_tmux = True
314
+ except (OSError, subprocess.SubprocessError):
315
+ pass
316
+ except OSError:
317
+ pass
318
+ where = f"tmux ({tty})" if (in_tmux and tty) else (tty or "远端终端")
319
+ reason = f"外部终端占用 ({where} · PID {holder_pid})" if holder_pid else f"外部终端占用 ({where})"
320
+ return {
321
+ "locked": True,
322
+ "pid": holder_pid or None,
323
+ "tty": tty,
324
+ "inTmux": in_tmux,
325
+ "entrypoint": "cli",
326
+ "status": "active",
327
+ "reason": reason,
328
+ }
329
+
330
+
193
331
  def read_history(config):
194
332
  sid = config.get("sessionId", "")
195
333
  if not isinstance(sid, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}", sid):
196
334
  raise ValueError("Invalid AGY session ID")
335
+ ext_lock = detect_agy_external_lock(sid)
197
336
  root = (Path.home() / ".gemini/antigravity-cli/brain").resolve()
198
337
  folder = root / sid / ".system_generated/logs"
199
338
  candidates = [folder / "transcript_full.jsonl", folder / "transcript.jsonl"]
200
339
  filename = next((p for p in candidates if p.is_file()), None)
201
340
  if filename is None:
202
- return {"messages": [], "subagents": [], "summaryOnly": True, "reason": "此会话尚无可读取的文本历史"}
341
+ return {"messages": [], "subagents": [], "externalLock": ext_lock, "summaryOnly": True, "reason": "此会话尚无可读取的文本历史"}
203
342
  if root not in filename.resolve().parents:
204
343
  raise ValueError("AGY history path escapes its history directory")
205
344
  with filename.open("rb") as handle:
@@ -238,7 +377,7 @@ def read_history(config):
238
377
  current = os.fstat(handle.fileno())
239
378
  if (stamp.st_mtime_ns, stamp.st_size) != (current.st_mtime_ns, current.st_size):
240
379
  raise ValueError("AGY 历史正在更新,请稍后刷新")
241
- return {"messages": [item for _, item in selected], "subagents": extract_subagents(root, filename), "summaryOnly": False,
380
+ return {"messages": [item for _, item in selected], "subagents": extract_subagents(root, filename), "externalLock": ext_lock, "summaryOnly": False,
242
381
  "source": filename.name, "version": version, "reset": reset,
243
382
  "nextBefore": next_before if next_before > 0 else None,
244
383
  "limited": skipped or any(item.get("truncated") for _, item in selected) or (not selected and start > 0)}
@@ -90,4 +90,21 @@ export class SessionCatalog {
90
90
  }
91
91
  return this.probe(entry.host, { operation: "dialogue", provider: entry.provider, path: entry.path });
92
92
  }
93
+ async subagentWorkflow(key, { subagentId, version } = {}) {
94
+ if (!subagentId || typeof subagentId !== "string") {
95
+ throw new Error("缺少子代理标识");
96
+ }
97
+ const entry = this.get(key);
98
+ if (!entry) throw new Error("未找到会话,请刷新扫描");
99
+ if (entry.provider !== "claude" || !entry.path) {
100
+ throw new Error("当前会话不支持 Claude 子代理工作流读取");
101
+ }
102
+ return this.probe(entry.host, {
103
+ operation: "subagent_workflow",
104
+ provider: "claude",
105
+ path: entry.path,
106
+ subagentId: subagentId.trim(),
107
+ ...(version ? { version: String(version) } : {}),
108
+ });
109
+ }
93
110
  }