@keyou007/agent-bot 0.1.27-alpha.1 → 0.1.27-alpha.2
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 +24 -0
- package/README.md +54 -4
- package/README.zh.md +54 -4
- package/SECURITY.md +14 -0
- package/assets/workspace-sessions.js +648 -0
- package/assets/workspace.css +160 -0
- package/assets/workspace.js +1795 -0
- package/config.example.yaml +3 -2
- package/dist/codex/CodexEventMapper.js +35 -0
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +50 -4
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/codex/TraeTaskNotification.js +44 -0
- package/dist/codex/TraeTaskNotification.js.map +1 -0
- package/dist/config/SettingsStore.js +1 -1
- package/dist/config/SettingsStore.js.map +1 -1
- package/dist/config/loadConfig.js +3 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/paths.js +3 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/feishu/CardRenderer.js +54 -10
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +2 -2
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +103 -16
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +61 -17
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +1 -1
- package/dist/local-files/GitDiffPreview.js +11 -7
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LocalFileViewerServer.js +273 -25
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownFileLinks.js +5 -4
- package/dist/local-files/MarkdownFileLinks.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +32 -10
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WebPageTitle.js +85 -0
- package/dist/local-files/WebPageTitle.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +553 -0
- package/dist/local-files/WorkspaceFiles.js.map +1 -0
- package/dist/local-files/WorkspaceOrigin.js +38 -0
- package/dist/local-files/WorkspaceOrigin.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +19 -0
- package/dist/local-files/WorkspacePage.js.map +1 -0
- package/dist/local-files/WorkspaceSessions.js +689 -0
- package/dist/local-files/WorkspaceSessions.js.map +1 -0
- package/dist/presentation/TurnStateReducer.js +74 -13
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnActivity.js +41 -0
- package/dist/presentation/turnActivity.js.map +1 -0
- package/dist/presentation/turnStatus.js +11 -0
- package/dist/presentation/turnStatus.js.map +1 -1
- package/dist/presentation/visibleTurnActivities.js +4 -2
- package/dist/presentation/visibleTurnActivities.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +150 -14
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/types.js +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/state/InboundMessageStore.js +54 -0
- package/dist/state/InboundMessageStore.js.map +1 -0
- package/dist/state/StateStore.js +71 -1
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +4 -2
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/migrations.js +20 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -0
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/supervision/SafeRestartScheduler.js +33 -16
- package/dist/supervision/SafeRestartScheduler.js.map +1 -1
- package/dist/terminal/TerminalLinks.js +32 -0
- package/dist/terminal/TerminalLinks.js.map +1 -1
- package/dist/terminal/TerminalPage.js +44 -24
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/terminal/TerminalServer.js +103 -39
- package/dist/terminal/TerminalServer.js.map +1 -1
- package/docs/technical-reference.md +1 -1
- package/docs/technical-reference.zh.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +3 -1
- package/src/codex/CodexEventMapper.ts +39 -1
- package/src/codex/CodexRuntime.ts +54 -4
- package/src/codex/TraeTaskNotification.ts +49 -0
- package/src/config/SettingsStore.ts +1 -1
- package/src/config/loadConfig.ts +3 -2
- package/src/config/paths.ts +4 -0
- package/src/feishu/CardRenderer.ts +45 -11
- package/src/feishu/FeishuMessageClient.ts +2 -2
- package/src/feishu/FeishuTurnPresenter.ts +110 -20
- package/src/index.ts +62 -17
- package/src/local-files/DiagramPreview.ts +1 -1
- package/src/local-files/GitDiffPreview.ts +10 -7
- package/src/local-files/LocalFileViewerServer.ts +243 -25
- package/src/local-files/MarkdownFileLinks.ts +5 -3
- package/src/local-files/TurnPreviewPage.ts +35 -9
- package/src/local-files/WebPageTitle.ts +59 -0
- package/src/local-files/WorkspaceFiles.ts +468 -0
- package/src/local-files/WorkspaceOrigin.ts +31 -0
- package/src/local-files/WorkspacePage.ts +21 -0
- package/src/local-files/WorkspaceSessions.ts +587 -0
- package/src/presentation/TurnStateReducer.ts +76 -14
- package/src/presentation/turnActivity.ts +43 -0
- package/src/presentation/turnStatus.ts +14 -0
- package/src/presentation/turnViewTypes.ts +10 -1
- package/src/presentation/visibleTurnActivities.ts +4 -2
- package/src/proxy/ProxySessionController.ts +149 -13
- package/src/runtime/types.ts +17 -0
- package/src/state/InboundMessageStore.ts +72 -0
- package/src/state/StateStore.ts +80 -1
- package/src/state/TurnPreviewJournal.ts +4 -2
- package/src/state/migrations.ts +20 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -0
- package/src/supervision/SafeRestartScheduler.ts +42 -18
- package/src/terminal/TerminalLinks.ts +26 -0
- package/src/terminal/TerminalPage.ts +44 -24
- package/src/terminal/TerminalServer.ts +98 -36
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type Database from "better-sqlite3";
|
|
2
|
+
import type { IncomingMessage } from "../feishu/types.js";
|
|
3
|
+
|
|
4
|
+
export interface PendingInboundMessage {
|
|
5
|
+
message: IncomingMessage;
|
|
6
|
+
localSessionId?: string;
|
|
7
|
+
executionGeneration: number;
|
|
8
|
+
status: "received" | "dispatching";
|
|
9
|
+
createdAt: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class InboundMessageStore {
|
|
13
|
+
constructor(private readonly db: Database.Database) {}
|
|
14
|
+
|
|
15
|
+
claim(message: IncomingMessage, localSessionId?: string, executionGeneration = 0): boolean {
|
|
16
|
+
return this.db.transaction(() => {
|
|
17
|
+
const now = new Date().toISOString();
|
|
18
|
+
const receipt = this.db.prepare(`INSERT OR IGNORE INTO inbound_event_receipts
|
|
19
|
+
(event_id, event_kind, created_at) VALUES (?, 'message', ?)`).run(message.messageId, now);
|
|
20
|
+
if (!receipt.changes) return false;
|
|
21
|
+
this.db.prepare(`INSERT INTO inbound_messages
|
|
22
|
+
(message_id, context_key, message_json, local_session_id, execution_generation, status, created_at)
|
|
23
|
+
VALUES (?, ?, ?, ?, ?, 'received', ?)`).run(
|
|
24
|
+
message.messageId, message.contextKey, JSON.stringify(message), localSessionId ?? null, executionGeneration, now,
|
|
25
|
+
);
|
|
26
|
+
return true;
|
|
27
|
+
})();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
beginDispatch(messageId: string): void {
|
|
31
|
+
this.db.prepare("UPDATE inbound_messages SET status = 'dispatching' WHERE message_id = ? AND status = 'received'")
|
|
32
|
+
.run(messageId);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
isPending(messageId: string): boolean {
|
|
36
|
+
return Boolean(this.db.prepare("SELECT 1 FROM inbound_messages WHERE message_id = ? AND status IN ('received', 'dispatching')")
|
|
37
|
+
.get(messageId));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
finish(messageId: string): void {
|
|
41
|
+
this.db.prepare("UPDATE inbound_messages SET status = 'handled', message_json = NULL WHERE message_id = ?")
|
|
42
|
+
.run(messageId);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
listPending(): PendingInboundMessage[] {
|
|
46
|
+
const rows = this.db.prepare(`SELECT message_json, local_session_id, execution_generation, status, created_at
|
|
47
|
+
FROM inbound_messages WHERE status IN ('received', 'dispatching') ORDER BY rowid`).all() as Array<{
|
|
48
|
+
message_json: string; local_session_id: string | null; execution_generation: number;
|
|
49
|
+
status: PendingInboundMessage["status"]; created_at: string;
|
|
50
|
+
}>;
|
|
51
|
+
return rows.map((row) => ({
|
|
52
|
+
message: JSON.parse(row.message_json) as IncomingMessage,
|
|
53
|
+
localSessionId: row.local_session_id ?? undefined,
|
|
54
|
+
executionGeneration: row.execution_generation,
|
|
55
|
+
status: row.status,
|
|
56
|
+
createdAt: row.created_at,
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
hasNewerMessage(messageId: string, contextKey: string, localSessionId?: string): boolean {
|
|
61
|
+
return Boolean(this.db.prepare(`SELECT 1 FROM inbound_messages
|
|
62
|
+
WHERE (context_key = ? OR local_session_id = ?)
|
|
63
|
+
AND rowid > (SELECT rowid FROM inbound_messages WHERE message_id = ?) LIMIT 1`)
|
|
64
|
+
.get(contextKey, localSessionId ?? null, messageId));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
hasDurableWork(messageId: string): boolean {
|
|
68
|
+
return Boolean(this.db.prepare(`SELECT 1 FROM message_turn_bindings WHERE message_id = ?
|
|
69
|
+
UNION ALL SELECT 1 FROM turn_attempts WHERE message_id = ?
|
|
70
|
+
UNION ALL SELECT 1 FROM queued_prompts WHERE message_id = ? LIMIT 1`).get(messageId, messageId, messageId));
|
|
71
|
+
}
|
|
72
|
+
}
|
package/src/state/StateStore.ts
CHANGED
|
@@ -7,6 +7,7 @@ import Database from "better-sqlite3";
|
|
|
7
7
|
import { ScheduledTaskStore } from "../scheduling/ScheduledTaskStore.js";
|
|
8
8
|
import { migrations } from "./migrations.js";
|
|
9
9
|
import { ExecutionProvenanceStore } from "./ExecutionProvenanceStore.js";
|
|
10
|
+
import { InboundMessageStore } from "./InboundMessageStore.js";
|
|
10
11
|
import type { UpdateCheckSchedule, UpdateNotice } from "../updates/types.js";
|
|
11
12
|
import type { ConversationTurn, RuntimeExecutionSettings } from "../runtime/types.js";
|
|
12
13
|
|
|
@@ -296,6 +297,7 @@ export class StateStore {
|
|
|
296
297
|
readonly previews: TurnPreviewJournal;
|
|
297
298
|
readonly schedules: ScheduledTaskStore;
|
|
298
299
|
readonly provenance: ExecutionProvenanceStore;
|
|
300
|
+
readonly inboundMessages: InboundMessageStore;
|
|
299
301
|
|
|
300
302
|
constructor(sqlitePath: string, onPreviewError?: (error: unknown) => void) {
|
|
301
303
|
this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
|
|
@@ -315,6 +317,7 @@ export class StateStore {
|
|
|
315
317
|
this.ensureRecentContextReceiptColumns();
|
|
316
318
|
this.schedules = new ScheduledTaskStore(this.db);
|
|
317
319
|
this.provenance = new ExecutionProvenanceStore(this.db);
|
|
320
|
+
this.inboundMessages = new InboundMessageStore(this.db);
|
|
318
321
|
this.initializeContextSessionMappings();
|
|
319
322
|
this.db.exec("DROP INDEX IF EXISTS idx_sessions_remote_session_id_unique");
|
|
320
323
|
this.reconcileDuplicateRemoteSessions();
|
|
@@ -1287,6 +1290,81 @@ export class StateStore {
|
|
|
1287
1290
|
})();
|
|
1288
1291
|
}
|
|
1289
1292
|
|
|
1293
|
+
workspaceRequest(id: string) {
|
|
1294
|
+
return this.db.prepare(`SELECT local_session_id AS localSessionId, fingerprint, status, posted, message
|
|
1295
|
+
FROM workspace_requests WHERE id = ?`).get(id) as
|
|
1296
|
+
{ localSessionId: string; fingerprint: string; status: string; posted: number; message: string | null } | undefined;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
beginWorkspaceRequest(id: string, localSessionId: string, fingerprint: string): void {
|
|
1300
|
+
this.db.prepare("INSERT INTO workspace_requests (id, local_session_id, fingerprint, status, created_at) VALUES (?, ?, ?, 'pending', ?)")
|
|
1301
|
+
.run(id, localSessionId, fingerprint, Date.now());
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
updateWorkspaceRequest(id: string, status: "pending" | "accepted" | "failed" | "unknown" | "stale", posted = false, message?: string): void {
|
|
1305
|
+
this.db.prepare("UPDATE workspace_requests SET status = ?, posted = max(posted, ?), message = ? WHERE id = ?")
|
|
1306
|
+
.run(status, Number(posted), message ?? null, id);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
workspaceTurnHead(task: SessionRecord): string | undefined {
|
|
1310
|
+
if (task.lastTurnId && task.status !== "running" && task.status !== "starting"
|
|
1311
|
+
&& this.db.prepare("SELECT 1 FROM turn_snapshots WHERE turn_id = ?").get(task.lastTurnId)) return task.lastTurnId;
|
|
1312
|
+
const row = this.db.prepare(`SELECT turn_id AS id FROM turn_snapshots
|
|
1313
|
+
WHERE local_session_id = ? ORDER BY coalesce(json_extract(snapshot_json, '$.startedAt'), 0) DESC, updated_at DESC, rowid DESC LIMIT 1`)
|
|
1314
|
+
.get(task.localSessionId) as { id: string } | undefined;
|
|
1315
|
+
return row?.id ?? this.findForkSourceTurnId(task.localSessionId);
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
workspaceTurnPage(localSessionId: string, head: string | undefined, before?: string, limit = 20): {
|
|
1319
|
+
ids: string[]; more: boolean; beforeMissing: boolean;
|
|
1320
|
+
} {
|
|
1321
|
+
const read = this.db.prepare(`SELECT s.local_session_id AS owner, p.turn_id AS linked, p.parent_turn_id AS parent
|
|
1322
|
+
FROM turn_snapshots s LEFT JOIN turn_parent_links p ON p.turn_id = s.turn_id WHERE s.turn_id = ?`);
|
|
1323
|
+
type Node = { owner: string; linked: string | null; parent: string | null };
|
|
1324
|
+
let id = head;
|
|
1325
|
+
let fallback = true;
|
|
1326
|
+
const ids: string[] = [], seen = new Set<string>();
|
|
1327
|
+
let found = !before;
|
|
1328
|
+
while (id && !seen.has(id) && seen.size < 20_000 && ids.length <= limit) {
|
|
1329
|
+
seen.add(id);
|
|
1330
|
+
let node = read.get(id) as Node | undefined;
|
|
1331
|
+
if (!node || seen.size === 1 && node.owner !== localSessionId && !this.hasTaskHistoryTurn(localSessionId, id)) break;
|
|
1332
|
+
if (fallback && !node.linked) {
|
|
1333
|
+
this.backfillTurnParents(node.owner);
|
|
1334
|
+
node = read.get(id) as Node;
|
|
1335
|
+
fallback = false;
|
|
1336
|
+
}
|
|
1337
|
+
if (found) ids.push(id);
|
|
1338
|
+
if (id === before) found = true;
|
|
1339
|
+
id = node.parent ?? (seen.size === 1 && node.owner === localSessionId
|
|
1340
|
+
? this.findForkSourceTurnId(localSessionId) : undefined);
|
|
1341
|
+
}
|
|
1342
|
+
return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
workspaceTurnText(turnId: string) {
|
|
1346
|
+
return this.db.prepare(`SELECT updated_at AS revision,
|
|
1347
|
+
substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
|
|
1348
|
+
snapshot_json -> '$.promptImagePaths' AS promptImages,
|
|
1349
|
+
substr(json_extract(snapshot_json, '$.finalResponse'), 1, 48001) AS answer,
|
|
1350
|
+
substr(json_extract(snapshot_json, '$.assistantText'), 1, 48001) AS live,
|
|
1351
|
+
substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
|
|
1352
|
+
substr(json_extract(snapshot_json, '$.statusMessage'), 1, 3000) AS notice,
|
|
1353
|
+
json_extract(snapshot_json, '$.status') AS status,
|
|
1354
|
+
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1355
|
+
json_extract(snapshot_json, '$.historyDetail') AS detail,
|
|
1356
|
+
(SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images))) FROM (
|
|
1357
|
+
SELECT json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
|
|
1358
|
+
substr(json_extract(value, '$.text'), 1, 4000) AS body,
|
|
1359
|
+
value -> '$.localImagePaths' AS images
|
|
1360
|
+
FROM json_each(snapshot_json, '$.activities')
|
|
1361
|
+
WHERE json_extract(value, '$.kind') IN ('user', 'assistant') LIMIT 30)) AS dialogue
|
|
1362
|
+
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as {
|
|
1363
|
+
revision: string; prompt: string | null; promptImages: string | null; answer: string | null; live: string | null;
|
|
1364
|
+
error: string | null; notice: string | null; status: string; startedAt: number; detail: string | null; dialogue: string;
|
|
1365
|
+
} | undefined;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1290
1368
|
getTurnSnapshot(turnId: string): unknown {
|
|
1291
1369
|
const row = this.db
|
|
1292
1370
|
.prepare("SELECT snapshot_json FROM turn_snapshots WHERE turn_id = ?")
|
|
@@ -1957,7 +2035,8 @@ export class StateStore {
|
|
|
1957
2035
|
FROM turn_snapshots AS snapshots
|
|
1958
2036
|
LEFT JOIN turn_deliveries AS deliveries ON deliveries.turn_id = snapshots.turn_id
|
|
1959
2037
|
WHERE json_extract(snapshots.snapshot_json, '$.status') = 'completed'
|
|
1960
|
-
AND length(coalesce(json_extract(snapshots.snapshot_json, '$.finalResponse'), '')) > 0
|
|
2038
|
+
AND (length(coalesce(json_extract(snapshots.snapshot_json, '$.finalResponse'), '')) > 0
|
|
2039
|
+
OR json_array_length(snapshots.snapshot_json, '$.taskNotificationCard') > 0)
|
|
1961
2040
|
AND deliveries.final_delivered_at IS NULL
|
|
1962
2041
|
ORDER BY snapshots.updated_at ASC
|
|
1963
2042
|
`).all() as Array<{
|
|
@@ -4,6 +4,7 @@ import { createHash, type Hash } from "node:crypto";
|
|
|
4
4
|
import type { AgentEvent, ToolState } from "../runtime/types.js";
|
|
5
5
|
import { approvalActivityId, continueTurnView, reduceTurnEvent } from "../presentation/TurnStateReducer.js";
|
|
6
6
|
import type { TurnViewState } from "../presentation/turnViewTypes.js";
|
|
7
|
+
import { normalizeTurnActivity } from "../presentation/turnActivity.js";
|
|
7
8
|
|
|
8
9
|
type TextChange = { key: string; field: string; append: boolean; text: string };
|
|
9
10
|
export type PreviewRecord =
|
|
@@ -307,7 +308,7 @@ export class TurnPreviewProjection {
|
|
|
307
308
|
|
|
308
309
|
apply(record: PreviewRecord, revision: number): void {
|
|
309
310
|
if (record.kind === "seed") {
|
|
310
|
-
this.state = { ...record.state, activities:
|
|
311
|
+
this.state = { ...record.state, activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: false };
|
|
311
312
|
for (const change of seedTexts(record.state)) this.text.set(change.key, this.wantsFull(change.key) ? change.text : change.text.slice(0, 6000));
|
|
312
313
|
if (this.details !== true) {
|
|
313
314
|
this.state = { ...this.state, fullToolOutputs: {}, fullToolErrors: {}, activities: this.state.activities.map((a) => a.kind === "tool"
|
|
@@ -383,7 +384,8 @@ export class TurnPreviewProjection {
|
|
|
383
384
|
const reasoningId = event.type === "reasoning_delta" || event.type === "reasoning_completed" ? event.itemId
|
|
384
385
|
: event.type === "progress" ? event.reasoning?.itemId : undefined;
|
|
385
386
|
if (reasoningId) this.state.reasoningItems = this.state.reasoningItems?.map((r) => r.itemId === reasoningId ? { ...r, previewRevision: revision } : r);
|
|
386
|
-
if (event.type === "context_compaction"
|
|
387
|
+
if (event.type === "context_compaction" || event.type === "model_queue_updated"
|
|
388
|
+
|| old.modelQueueActivityId && !this.state.modelQueueActivityId) {
|
|
387
389
|
for (const a of this.state.activities) if (!old.activities.includes(a)) this.changed.add(a.id);
|
|
388
390
|
}
|
|
389
391
|
if (event.type === "approval_resolved") this.changed.add(approvalActivityId(event.turnId, event.requestId));
|
package/src/state/migrations.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export const migrations = [
|
|
2
|
+
`CREATE TABLE IF NOT EXISTS workspace_requests (
|
|
3
|
+
id TEXT PRIMARY KEY, local_session_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL, posted INTEGER NOT NULL DEFAULT 0, message TEXT, created_at INTEGER NOT NULL
|
|
5
|
+
);
|
|
6
|
+
CREATE INDEX IF NOT EXISTS idx_workspace_requests_task ON workspace_requests(local_session_id, created_at DESC);`,
|
|
2
7
|
`CREATE TABLE IF NOT EXISTS execution_provenance (
|
|
3
8
|
submission_id TEXT PRIMARY KEY, instruction_id TEXT NOT NULL, attempt_id TEXT NOT NULL,
|
|
4
9
|
local_session_id TEXT NOT NULL, turn_id TEXT, trigger TEXT NOT NULL, parent_source_turn_id TEXT,
|
|
@@ -70,6 +75,19 @@ export const migrations = [
|
|
|
70
75
|
);
|
|
71
76
|
`,
|
|
72
77
|
`
|
|
78
|
+
CREATE TABLE IF NOT EXISTS inbound_messages (
|
|
79
|
+
message_id TEXT PRIMARY KEY,
|
|
80
|
+
context_key TEXT NOT NULL,
|
|
81
|
+
message_json TEXT,
|
|
82
|
+
local_session_id TEXT,
|
|
83
|
+
execution_generation INTEGER NOT NULL DEFAULT 0,
|
|
84
|
+
status TEXT NOT NULL,
|
|
85
|
+
created_at TEXT NOT NULL
|
|
86
|
+
);
|
|
87
|
+
CREATE INDEX IF NOT EXISTS idx_inbound_messages_status ON inbound_messages(status);
|
|
88
|
+
CREATE INDEX IF NOT EXISTS idx_inbound_messages_context ON inbound_messages(context_key, created_at);
|
|
89
|
+
`,
|
|
90
|
+
`
|
|
73
91
|
CREATE TABLE IF NOT EXISTS message_reactions (
|
|
74
92
|
message_id TEXT PRIMARY KEY,
|
|
75
93
|
context_key TEXT NOT NULL,
|
|
@@ -184,6 +202,7 @@ export const migrations = [
|
|
|
184
202
|
ON turn_attempts(local_session_id, updated_at);
|
|
185
203
|
CREATE INDEX IF NOT EXISTS idx_turn_attempts_turn
|
|
186
204
|
ON turn_attempts(turn_id);
|
|
205
|
+
CREATE INDEX IF NOT EXISTS idx_turn_attempts_message ON turn_attempts(message_id);
|
|
187
206
|
`,
|
|
188
207
|
`
|
|
189
208
|
CREATE TABLE IF NOT EXISTS goal_card_deliveries (
|
|
@@ -259,5 +278,6 @@ export const migrations = [
|
|
|
259
278
|
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_status ON scheduled_runs(status);
|
|
260
279
|
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_job ON scheduled_runs(job_id);
|
|
261
280
|
CREATE INDEX IF NOT EXISTS idx_turn_attempts_pending_turn ON turn_attempts(pending_turn_id);
|
|
281
|
+
CREATE INDEX IF NOT EXISTS idx_workspace_turn_head ON turn_snapshots(local_session_id, coalesce(json_extract(snapshot_json, '$.startedAt'), 0) DESC, updated_at DESC);
|
|
262
282
|
`,
|
|
263
283
|
] as const;
|
|
@@ -156,6 +156,7 @@ export class SafeRestartNotifier {
|
|
|
156
156
|
phase: status.phase,
|
|
157
157
|
remainingMs: status.remainingMs,
|
|
158
158
|
pendingFinalDeliveries: status.activity.pendingFinalDeliveries,
|
|
159
|
+
pendingInboundMessages: status.activity.pendingInboundMessages,
|
|
159
160
|
activeTerminals: status.activity.activeTerminals,
|
|
160
161
|
terminalBlockers: status.activity.terminalBlockers,
|
|
161
162
|
contextKey,
|
|
@@ -5,6 +5,7 @@ export interface ServerActivityState {
|
|
|
5
5
|
terminalBlockers?: ActiveTerminal[];
|
|
6
6
|
runningSessions: number;
|
|
7
7
|
pendingFinalDeliveries: number;
|
|
8
|
+
pendingInboundMessages?: number;
|
|
8
9
|
latestInboundAt?: string;
|
|
9
10
|
}
|
|
10
11
|
|
|
@@ -32,7 +33,7 @@ export interface SafeRestartStatus {
|
|
|
32
33
|
|
|
33
34
|
export interface SafeRestartSchedulerOptions {
|
|
34
35
|
readActivity(): ServerActivityState;
|
|
35
|
-
onReady(reason: string, notificationTargets: RestartNotificationTarget[]): void | Promise<void>;
|
|
36
|
+
onReady(reason: string, notificationTargets: RestartNotificationTarget[]): void | boolean | Promise<void | boolean>;
|
|
36
37
|
onStatus?(status: SafeRestartStatus): void | Promise<void>;
|
|
37
38
|
onStatusError?(error: unknown): void;
|
|
38
39
|
quietPeriodMs?: number;
|
|
@@ -54,6 +55,7 @@ export class SafeRestartScheduler {
|
|
|
54
55
|
private scheduleId = 0;
|
|
55
56
|
private restartImmediatelyIfIdle = false;
|
|
56
57
|
private restartingNow = false;
|
|
58
|
+
private forcingNow = false;
|
|
57
59
|
|
|
58
60
|
constructor(private readonly options: SafeRestartSchedulerOptions) {}
|
|
59
61
|
|
|
@@ -65,6 +67,10 @@ export class SafeRestartScheduler {
|
|
|
65
67
|
return this.restartingNow;
|
|
66
68
|
}
|
|
67
69
|
|
|
70
|
+
get forcing(): boolean {
|
|
71
|
+
return this.forcingNow;
|
|
72
|
+
}
|
|
73
|
+
|
|
68
74
|
get pendingReason(): string | undefined {
|
|
69
75
|
return this.reason;
|
|
70
76
|
}
|
|
@@ -108,14 +114,13 @@ export class SafeRestartScheduler {
|
|
|
108
114
|
|
|
109
115
|
async forceScheduled(expectedScheduleId: number): Promise<boolean> {
|
|
110
116
|
const reason = this.reason;
|
|
111
|
-
if (!reason || this.scheduleId !== expectedScheduleId) return false;
|
|
112
|
-
|
|
113
|
-
return true;
|
|
117
|
+
if (!reason || this.restartingNow || this.scheduleId !== expectedScheduleId) return false;
|
|
118
|
+
return this.restart(reason, expectedScheduleId, this.options.readActivity(), true);
|
|
114
119
|
}
|
|
115
120
|
|
|
116
121
|
async cancelScheduled(expectedScheduleId: number): Promise<boolean> {
|
|
117
122
|
const reason = this.reason;
|
|
118
|
-
if (!reason || this.scheduleId !== expectedScheduleId) return false;
|
|
123
|
+
if (!reason || this.restartingNow || this.scheduleId !== expectedScheduleId) return false;
|
|
119
124
|
const activity = this.options.readActivity();
|
|
120
125
|
const notificationTargets = this.notificationTargetsSnapshot();
|
|
121
126
|
this.clear();
|
|
@@ -218,20 +223,28 @@ export class SafeRestartScheduler {
|
|
|
218
223
|
await this.restart(reason, scheduleId, confirmed);
|
|
219
224
|
}
|
|
220
225
|
|
|
221
|
-
private async restart(reason: string, scheduleId: number, activity: ServerActivityState): Promise<
|
|
226
|
+
private async restart(reason: string, scheduleId: number, activity: ServerActivityState, force = false): Promise<boolean> {
|
|
227
|
+
if (this.restartingNow) return false;
|
|
222
228
|
this.restartingNow = true;
|
|
229
|
+
this.forcingNow = force;
|
|
223
230
|
const notificationTargets = this.notificationTargetsSnapshot();
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
reason
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
finally {
|
|
231
|
+
try {
|
|
232
|
+
await this.emitStatus({ scheduleId, reason, notificationTargets, phase: "restarting", activity, remainingMs: 0 });
|
|
233
|
+
const confirmed = this.options.readActivity();
|
|
234
|
+
if (this.scheduleId !== scheduleId || !this.reason || (!force && (
|
|
235
|
+
hasActiveWork(confirmed) || confirmed.pendingFinalDeliveries > 0
|
|
236
|
+
|| confirmed.latestInboundAt !== activity.latestInboundAt
|
|
237
|
+
))) return false;
|
|
238
|
+
if (await this.options.onReady(reason, notificationTargets) === false) return false;
|
|
239
|
+
if (this.scheduleId === scheduleId) this.clear();
|
|
240
|
+
return true;
|
|
241
|
+
} finally {
|
|
242
|
+
this.restartingNow = false;
|
|
243
|
+
this.forcingNow = false;
|
|
244
|
+
this.idleSince = undefined;
|
|
245
|
+
this.idleInboundAt = undefined;
|
|
246
|
+
if (this.reason && this.scheduleId === scheduleId) this.restartImmediatelyIfIdle = false;
|
|
247
|
+
}
|
|
235
248
|
}
|
|
236
249
|
|
|
237
250
|
private requestPoll(): void {
|
|
@@ -285,7 +298,18 @@ export class SafeRestartScheduler {
|
|
|
285
298
|
}
|
|
286
299
|
|
|
287
300
|
function hasActiveWork(state: ServerActivityState): boolean {
|
|
288
|
-
return state.runningSessions > 0 || (state.activeTerminals ?? 0) > 0;
|
|
301
|
+
return state.runningSessions > 0 || (state.activeTerminals ?? 0) > 0 || (state.pendingInboundMessages ?? 0) > 0;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function commitRestartHandoff(
|
|
305
|
+
state: ServerActivityState,
|
|
306
|
+
expectedInboundAt: string | undefined,
|
|
307
|
+
pauseInbound: () => void,
|
|
308
|
+
force = false,
|
|
309
|
+
): boolean {
|
|
310
|
+
if (!force && (hasActiveWork(state) || state.pendingFinalDeliveries > 0 || state.latestInboundAt !== expectedInboundAt)) return false;
|
|
311
|
+
pauseInbound();
|
|
312
|
+
return true;
|
|
289
313
|
}
|
|
290
314
|
|
|
291
315
|
function normalizedNotificationTarget(
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
|
|
6
6
|
const record = z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{8}$/u), jobId: z.string().regex(/^[a-f0-9-]{36}$/u) });
|
|
7
|
+
const workspaceRecord = z.object({ token: record.shape.token, cwd: z.string().min(1), ownerId: z.string().min(1), instance: z.string().regex(/^[a-f0-9]{16}$/u) });
|
|
7
8
|
|
|
8
9
|
export class TerminalLinks {
|
|
9
10
|
constructor(private readonly directory: string, private readonly secret: Buffer) {
|
|
@@ -40,6 +41,31 @@ export class TerminalLinks {
|
|
|
40
41
|
throw new Error("Unable to allocate a terminal recovery link.");
|
|
41
42
|
}
|
|
42
43
|
|
|
44
|
+
createWorkspace(cwd: string, ownerId: string, instance: string): string {
|
|
45
|
+
workspaceRecord.omit({ token: true }).parse({ cwd, ownerId, instance });
|
|
46
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
47
|
+
const token = createHmac("sha256", this.secret).update(JSON.stringify(["terminal:workspace", cwd, ownerId, instance, attempt])).digest("base64url").slice(0, 8);
|
|
48
|
+
const existing = this.resolveWorkspace(token);
|
|
49
|
+
if (existing?.cwd === cwd && existing.ownerId === ownerId && existing.instance === instance) return token;
|
|
50
|
+
try {
|
|
51
|
+
fs.writeFileSync(this.filePath(token), JSON.stringify({ token, cwd, ownerId, instance }), { flag: "wx", mode: 0o600 });
|
|
52
|
+
return token;
|
|
53
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
|
54
|
+
}
|
|
55
|
+
throw new Error("Unable to allocate a workspace terminal link.");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
resolveWorkspace(token: string): z.infer<typeof workspaceRecord> | undefined {
|
|
59
|
+
if (!/^[A-Za-z0-9_-]{8}$/u.test(token)) return undefined;
|
|
60
|
+
try {
|
|
61
|
+
const parsed = workspaceRecord.safeParse(JSON.parse(fs.readFileSync(this.filePath(token), "utf8")) as unknown);
|
|
62
|
+
return parsed.success && parsed.data.token === token ? parsed.data : undefined;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof SyntaxError || (error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
43
69
|
resolve(token: string): string | undefined {
|
|
44
70
|
if (!/^[A-Za-z0-9_-]{8}$/u.test(token)) return undefined;
|
|
45
71
|
let content: string;
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { DEFAULT_TERMINAL_PASSWORD } from "../config/schema.js";
|
|
2
2
|
|
|
3
|
-
export function terminalPage(base: string, recovery = false, autoResume = false, defaultPassword = false): string {
|
|
4
|
-
defaultPassword = defaultPassword && !autoResume;
|
|
3
|
+
export function terminalPage(base: string, recovery = false, autoResume = false, defaultPassword = false, workspace = false): string {
|
|
4
|
+
defaultPassword = defaultPassword && !autoResume && !workspace;
|
|
5
5
|
base = base.replaceAll("&", "&").replaceAll(String.fromCharCode(34), """).replaceAll("<", "<").replaceAll(">", ">");
|
|
6
6
|
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
7
7
|
<title>AgentBot Terminal</title><link rel="stylesheet" href="${base}/assets/xterm.css"><link rel="stylesheet" href="${base}/assets/terminal.css">
|
|
8
8
|
<script defer src="${base}/assets/xterm.js"></script><script defer src="${base}/assets/fit.js"></script><script defer src="${base}/assets/terminal.js"></script></head>
|
|
9
|
-
<body data-base="${base}" data-recovery="${recovery}" data-resume="${autoResume}" data-default-password="${defaultPassword}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" title="前台连接不因空闲关闭;后台空闲或网页断开 30 分钟后关闭。重连重新计时,可从原会话的终端管理卡打开或关闭终端。" disabled>关闭终端</button></header>
|
|
10
|
-
<section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p
|
|
9
|
+
<body data-base="${base}" data-recovery="${recovery}" data-resume="${autoResume}" data-default-password="${defaultPassword}" data-workspace="${workspace}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" title="前台连接不因空闲关闭;后台空闲或网页断开 30 分钟后关闭。重连重新计时,可从原会话的终端管理卡打开或关闭终端。" disabled>关闭终端</button></header>
|
|
10
|
+
<section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p>${workspace
|
|
11
|
+
? '<button id="welcome-connect" type="button">连接</button>'
|
|
12
|
+
: `<label for="password">终端密码</label><div class="password-row"><input id="password" type="password" autocomplete="current-password" maxlength="256" value="${defaultPassword ? DEFAULT_TERMINAL_PASSWORD : ""}" aria-describedby="password-hint" autofocus><button id="welcome-connect" type="button">连接</button></div><p id="password-hint">与工作台共用密码,可在飞书 /setting → 高级 → 工作台 / 终端密码中修改。</p>`}</section><div id="terminal"></div>
|
|
11
13
|
</body></html>`;
|
|
12
14
|
}
|
|
13
15
|
|
|
@@ -30,18 +32,20 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
30
32
|
const recovery = document.body.dataset.recovery === 'true';
|
|
31
33
|
const autoResume = recovery && document.body.dataset.resume === 'true';
|
|
32
34
|
const defaultPassword = document.body.dataset.defaultPassword === 'true';
|
|
33
|
-
const
|
|
35
|
+
const workspace = document.body.dataset.workspace === 'true';
|
|
36
|
+
const initialPassword = password?.value;
|
|
34
37
|
if (autoResume) document.getElementById('welcome').hidden = true;
|
|
35
38
|
if (recovery) document.querySelector('#welcome h1').textContent = '恢复已有终端';
|
|
36
39
|
let session, ws, term, observer, retryTimer, socketTimer, checking, visibilityTimer, countdownTimer;
|
|
37
|
-
let socketReady = false;
|
|
40
|
+
let socketReady = false, startRequested = false;
|
|
38
41
|
let epoch = 0, failures = 0, stopped = false, pageHidden = false, offline = false, busy = false;
|
|
39
42
|
try { session = JSON.parse(sessionStorage.getItem(storageKey) || 'null'); } catch {}
|
|
40
|
-
|
|
43
|
+
let parentVisible = window.parent === window;
|
|
44
|
+
const awake = () => parentVisible && !pageHidden && !document.hidden && !offline;
|
|
41
45
|
const post = async (route, data, controller = new AbortController()) => {
|
|
42
46
|
const timer = setTimeout(() => controller.abort(), 10000);
|
|
43
47
|
try {
|
|
44
|
-
const response = await fetch(base + '/api/' + route, { method:'POST', credentials:'omit', cache:'no-store',
|
|
48
|
+
const response = await fetch(base + '/api/' + route, { method:'POST', credentials:workspace?'same-origin':'omit', cache:'no-store',
|
|
45
49
|
signal:controller.signal, headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) });
|
|
46
50
|
let value;
|
|
47
51
|
try { value = await response.json(); } catch {
|
|
@@ -62,7 +66,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
62
66
|
button.disabled = busy || (!!session && !retry);
|
|
63
67
|
}
|
|
64
68
|
close.disabled = busy || !session;
|
|
65
|
-
password.disabled = busy;
|
|
69
|
+
if (password) password.disabled = busy;
|
|
66
70
|
}
|
|
67
71
|
function invalidate() {
|
|
68
72
|
cancelDefaultConnect();
|
|
@@ -89,7 +93,13 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
89
93
|
session = undefined; sessionStorage.removeItem(storageKey);
|
|
90
94
|
buttons(true);
|
|
91
95
|
}
|
|
92
|
-
function end(text
|
|
96
|
+
function end(text, clear = false) {
|
|
97
|
+
stopped = true; invalidate(); forget(); status.textContent = text;
|
|
98
|
+
if (clear) {
|
|
99
|
+
observer?.disconnect(); term?.dispose(); term = undefined;
|
|
100
|
+
document.body.classList.remove('connected');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
93
103
|
function fail(text) { stopped = true; invalidate(); status.textContent = text; buttons(true); }
|
|
94
104
|
function schedule(delay) {
|
|
95
105
|
clearTimeout(retryTimer);
|
|
@@ -117,7 +127,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
117
127
|
const url = new URL(base + '/socket', location.origin); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
118
128
|
let socket;
|
|
119
129
|
try { socket = new WebSocket(url); } catch (error) { retry('WebSocket 连接失败', error); return; }
|
|
120
|
-
ws = socket; status.textContent = '授权已通过,正在连接终端…'; buttons();
|
|
130
|
+
ws = socket; status.textContent = workspace ? '正在连接终端…' : '授权已通过,正在连接终端…'; buttons();
|
|
121
131
|
const valid = () => ws === socket && generation === epoch && session === current && !stopped;
|
|
122
132
|
socketTimer = setTimeout(() => {
|
|
123
133
|
if (!valid()) return;
|
|
@@ -164,7 +174,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
164
174
|
// before subsequently queued live output is parsed. Startup output is live.
|
|
165
175
|
if (result.output) terminal.write(result.output, restored); else restored();
|
|
166
176
|
} else if (result.type === 'data') term?.write(result.data);
|
|
167
|
-
else if (result.type === 'exit') end(result.message || '终端已结束');
|
|
177
|
+
else if (result.type === 'exit') end(result.message || '终端已结束', workspace && result.clear === true);
|
|
168
178
|
else if (result.type === 'error') fail((result.stage === 'spawn' ? 'Shell 启动失败:' : '终端连接被拒绝:') + result.message);
|
|
169
179
|
} catch (error) { fail('终端界面初始化或消息处理失败:' + message(error)); }
|
|
170
180
|
};
|
|
@@ -189,7 +199,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
189
199
|
else end(result.message || '授权已失效,请重新请求连接');
|
|
190
200
|
} catch (error) {
|
|
191
201
|
if (generation !== epoch || current !== session || stopped || !awake()) return;
|
|
192
|
-
if ([400,401,404,410].includes(error.httpStatus)) end('
|
|
202
|
+
if ([400,401,404,410].includes(error.httpStatus)) end('连接状态查询失败:' + message(error) + '。请重新请求连接。', workspace && error.httpStatus === 401);
|
|
193
203
|
else if (error.httpStatus === 403) fail('授权状态查询被拒绝:' + message(error));
|
|
194
204
|
else retry('暂时无法查询授权状态', error);
|
|
195
205
|
} finally { if (checking === controller) checking = undefined; }
|
|
@@ -199,22 +209,22 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
199
209
|
stopped = false; failures = 0; invalidate();
|
|
200
210
|
if (session) { status.textContent = '正在恢复已有终端授权…'; buttons(); check(); return; }
|
|
201
211
|
document.body.classList.remove('connected');
|
|
202
|
-
if (!autoResume && !password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
|
|
203
|
-
busy = true; buttons(); status.textContent = autoResume ? '正在恢复原终端…' : '正在验证密码…';
|
|
212
|
+
if (password && !autoResume && !password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
|
|
213
|
+
busy = true; buttons(); status.textContent = workspace ? '正在打开终端…' : autoResume ? '正在恢复原终端…' : '正在验证密码…';
|
|
204
214
|
try {
|
|
205
215
|
if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器不支持安全随机数,请使用新版浏览器。');
|
|
206
216
|
const browserKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), (n) => n.toString(16).padStart(2,'0')).join('');
|
|
207
|
-
const result = await post('request', {launch:location.pathname,browserKey,password:autoResume ? undefined : password
|
|
208
|
-
password.value = '';
|
|
217
|
+
const result = await post('request', {launch:location.pathname,browserKey,password:autoResume ? undefined : password?.value});
|
|
218
|
+
if (password) password.value = '';
|
|
209
219
|
session = {requestId:result.requestId,browserKey}; sessionStorage.setItem(storageKey,JSON.stringify(session));
|
|
210
|
-
status.textContent = autoResume ? '正在恢复原终端…' : '密码已验证,正在连接终端…';
|
|
211
|
-
} catch (error) { status.textContent = '连接失败:' + message(error); password
|
|
220
|
+
status.textContent = workspace ? '正在连接终端…' : autoResume ? '正在恢复原终端…' : '密码已验证,正在连接终端…';
|
|
221
|
+
} catch (error) { status.textContent = '连接失败:' + message(error); password?.focus(); }
|
|
212
222
|
finally { busy = false; buttons(!session); }
|
|
213
223
|
check();
|
|
214
224
|
};
|
|
215
|
-
password
|
|
216
|
-
password
|
|
217
|
-
password
|
|
225
|
+
password?.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
|
|
226
|
+
password?.addEventListener('input', cancelDefaultConnect);
|
|
227
|
+
password?.addEventListener('change', cancelDefaultConnect);
|
|
218
228
|
interrupt.onclick = () => { if (ws?.readyState === WebSocket.OPEN && !interrupt.disabled) ws.send(JSON.stringify({type:'input',data:String.fromCharCode(3)})); };
|
|
219
229
|
close.onclick = async () => {
|
|
220
230
|
if (busy || !session || !confirm('关闭该终端和 Shell?\n' + close.title + '\n已脱离终端的后台进程可能继续运行。')) return;
|
|
@@ -230,8 +240,12 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
230
240
|
if (session && !stopped) { status.textContent = '连接已暂停,返回网页或网络恢复后自动重连'; buttons(true); }
|
|
231
241
|
}
|
|
232
242
|
function resume() {
|
|
233
|
-
if (stopped || !awake() || busy
|
|
234
|
-
|
|
243
|
+
if (stopped || !awake() || busy) return;
|
|
244
|
+
if (startRequested) {
|
|
245
|
+
startRequested = false;
|
|
246
|
+
if (!session) { connect.click(); return; }
|
|
247
|
+
}
|
|
248
|
+
if (session) { clearTimeout(retryTimer); check(); }
|
|
235
249
|
}
|
|
236
250
|
window.addEventListener('pagehide', () => { pageHidden = true; suspend(); });
|
|
237
251
|
window.addEventListener('pageshow', () => { pageHidden = false; resume(); });
|
|
@@ -239,6 +253,12 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
239
253
|
window.addEventListener('offline', () => { offline = true; suspend(); });
|
|
240
254
|
window.addEventListener('online', () => { offline = false; resume(); });
|
|
241
255
|
window.addEventListener('focus', resume);
|
|
256
|
+
window.addEventListener('message', event => {
|
|
257
|
+
if (window.parent === window || event.source !== window.parent || event.origin !== location.origin || event.data?.type !== 'agentbot-workspace-visibility' || typeof event.data.visible !== 'boolean') return;
|
|
258
|
+
if (workspace && event.data.start === true) startRequested = true;
|
|
259
|
+
parentVisible = event.data.visible; reportVisibility();
|
|
260
|
+
if (parentVisible) resume(); else if (!ws) suspend();
|
|
261
|
+
});
|
|
242
262
|
buttons();
|
|
243
263
|
if (!session && autoResume) connect.click();
|
|
244
264
|
else if (!session && defaultPassword) countdown();
|