agent-things 0.0.0-stage → 1.2.1
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/LICENSE +21 -0
- package/NOTICE +5 -0
- package/README.md +221 -2
- package/README.zh-CN.md +222 -0
- package/bin/agent-things.cjs +8 -0
- package/bin/antigravity-session-status.cjs +96 -0
- package/bin/claude-session-status.cjs +55 -0
- package/bin/codex-session-status.cjs +287 -0
- package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
- package/mods/agent-things-ui/SKILL.md +10 -0
- package/mods/agent-things-ui/hooks/controls.js +112 -0
- package/mods/agent-things-ui/hooks/foundation.js +431 -0
- package/mods/agent-things-ui/hooks/hooks.json +1 -0
- package/mods/agent-things-ui/hooks/presentation.js +223 -0
- package/mods/agent-things-ui/hooks/progress.js +1 -0
- package/mods/agent-things-ui/hooks/register.js +382 -0
- package/native/bin/bridge +0 -0
- package/native/bin/bridge.json +20 -0
- package/native/session-status-bridge.swift +280 -0
- package/outputs/antigravity-session-status.js +2476 -0
- package/outputs/codex-session-status.js +1761 -0
- package/package.json +75 -4
- package/scripts/build-antigravity-bundle.cjs +35 -0
- package/scripts/build-codex-bundle.cjs +31 -0
- package/scripts/build-native-bridge.cjs +55 -0
- package/scripts/build-shared-ui.cjs +16 -0
- package/scripts/setup-antigravity-service.cjs +71 -0
- package/scripts/setup-claude-service.cjs +21 -0
- package/skills/agent-things/SKILL.en.md +95 -0
- package/skills/agent-things/SKILL.md +99 -0
- package/skills/codex/things/SKILL.en.md +10 -0
- package/skills/codex/things/SKILL.md +10 -0
- package/skills/things/SKILL.en.md +10 -0
- package/skills/things/SKILL.md +10 -0
- package/skills/things/checklist.en.md +91 -0
- package/skills/things/checklist.md +95 -0
- package/src/analysis-app-server.cjs +74 -0
- package/src/analysis-assets/output.en.schema.json +93 -0
- package/src/analysis-assets/output.schema.json +93 -0
- package/src/analysis-assets/prompt.en.txt +17 -0
- package/src/analysis-assets/prompt.zh-CN.txt +18 -0
- package/src/analysis-budget.cjs +105 -0
- package/src/analysis-git.cjs +38 -0
- package/src/analysis-history.cjs +150 -0
- package/src/analysis-ledger.cjs +82 -0
- package/src/analysis-log.cjs +62 -0
- package/src/analysis-runner.cjs +203 -0
- package/src/analysis-service.cjs +197 -0
- package/src/analysis-source.cjs +72 -0
- package/src/antigravity-card.cjs +2063 -0
- package/src/antigravity-hook.cjs +138 -0
- package/src/antigravity-mcp-config.cjs +36 -0
- package/src/app-server.cjs +96 -0
- package/src/cdp.cjs +115 -0
- package/src/claude-inline-install.cjs +38 -0
- package/src/claude-mcp-config.cjs +29 -0
- package/src/cli/arguments.cjs +30 -0
- package/src/cli/environment-probe.cjs +130 -0
- package/src/cli/integration-state.cjs +15 -0
- package/src/cli/interactive-cli.cjs +236 -0
- package/src/cli/prompt-tui.cjs +420 -0
- package/src/cli/setup-orchestrator.cjs +449 -0
- package/src/codex-mcp-config.cjs +67 -0
- package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
- package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
- package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
- package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
- package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
- package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
- package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
- package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
- package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
- package/src/harnesses/antigravity/transcript-source.cjs +100 -0
- package/src/harnesses/claude/claude-harness.js +93 -0
- package/src/harnesses/claude/claude-host-helper.cjs +176 -0
- package/src/harnesses/claude/claude-injector.cjs +95 -0
- package/src/harnesses/claude/claude-local-source.cjs +106 -0
- package/src/harnesses/claude/claude-navigation.cjs +99 -0
- package/src/harnesses/claude/claude-runner.cjs +74 -0
- package/src/harnesses/claude/claude-service.cjs +313 -0
- package/src/harnesses/claude/claude-source.cjs +70 -0
- package/src/harnesses/codex/codex-analysis.cjs +10 -0
- package/src/harnesses/codex/codex-card-bridge.js +123 -0
- package/src/harnesses/codex/codex-card-events.cjs +76 -0
- package/src/harnesses/codex/codex-card.cjs +169 -0
- package/src/harnesses/codex/codex-git.cjs +24 -0
- package/src/harnesses/codex/codex-harness.js +229 -0
- package/src/harnesses/codex/codex-local-card.js +97 -0
- package/src/harnesses/codex/codex-progress-context.cjs +84 -0
- package/src/harnesses/codex/codex-service.cjs +502 -0
- package/src/i18n.cjs +174 -0
- package/src/launchd.cjs +105 -0
- package/src/lifecycle-lock.cjs +13 -0
- package/src/local-progress-http.cjs +267 -0
- package/src/manual-status-agent.cjs +12 -0
- package/src/manual-status-startup.cjs +66 -0
- package/src/manual-status-store.cjs +466 -0
- package/src/mcp-stdio.cjs +67 -0
- package/src/model-router.cjs +63 -0
- package/src/native-bridge.cjs +17 -0
- package/src/npm-updates.cjs +228 -0
- package/src/plugins/things/assets/logo.svg +13 -0
- package/src/plugins/things/plugin.json +6 -0
- package/src/plugins/things/sidecars/things_board/app.js +447 -0
- package/src/plugins/things/sidecars/things_board/index.html +2141 -0
- package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
- package/src/plugins/things/sidecars/things_board/package.json +6 -0
- package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
- package/src/plugins/things/sidecars/things_board/styles.css +560 -0
- package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
- package/src/progress-error.cjs +54 -0
- package/src/progress-tools.cjs +145 -0
- package/src/project-path.cjs +15 -0
- package/src/renderer-resource.cjs +17 -0
- package/src/request-budget.cjs +24 -0
- package/src/resolve.cjs +51 -0
- package/src/runtime-install.cjs +635 -0
- package/src/session-status-filter.cjs +136 -0
- package/src/session-status.js +992 -0
- package/src/session-view.cjs +34 -0
- package/src/startup/controller.cjs +354 -0
- package/src/startup/watch.cjs +126 -0
- package/src/state-file-lock.cjs +31 -0
- package/src/task-provenance.cjs +42 -0
- package/src/ui-foundation.cjs +435 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('node:path');
|
|
3
|
+
const { createHash } = require('node:crypto');
|
|
4
|
+
const { errorDetails } = require('./progress-error.cjs');
|
|
5
|
+
const { readConfiguredLang } = require('./i18n.cjs');
|
|
6
|
+
const PROTOCOL_VERSION = 1;
|
|
7
|
+
function sessionView(store, key, { projectGit, capabilities = {}, projection = null, lang } = {}) {
|
|
8
|
+
const activeLang = lang || (typeof store.lang === 'function' ? store.lang() : readConfiguredLang({ dataDir: store.file ? path.dirname(store.file) : undefined }));
|
|
9
|
+
let saved, analysisObj, event, tasks, git, versionInput;
|
|
10
|
+
if (projection || typeof store.readSessionProjection === 'function') {
|
|
11
|
+
const view = projection || store.readSessionProjection(key);
|
|
12
|
+
saved = view.record;
|
|
13
|
+
analysisObj = view.analysis;
|
|
14
|
+
event = view.latestAnalysisEvent;
|
|
15
|
+
tasks = (saved && saved.state !== null ? view.activeTasks : null) || analysisObj?.ledger?.tasks || [];
|
|
16
|
+
git = projectGit || analysisObj?.projectGit || null;
|
|
17
|
+
versionInput = view.timelineVersionInput;
|
|
18
|
+
} else {
|
|
19
|
+
const snapshot = store.snapshot(), state = store.analysisState(key);
|
|
20
|
+
saved = snapshot.records[key];
|
|
21
|
+
analysisObj = state.analysis;
|
|
22
|
+
event = state.timeline.findLast(item => item.source === 'analysis');
|
|
23
|
+
tasks = store.getProgress(key)?.tasks || analysisObj?.ledger?.tasks || [];
|
|
24
|
+
git = projectGit || analysisObj?.projectGit || null;
|
|
25
|
+
versionInput = JSON.stringify([saved, analysisObj, state.timeline]);
|
|
26
|
+
}
|
|
27
|
+
const record = saved?.state ? saved : null;
|
|
28
|
+
const analysis = { status: event?.status || 'idle', stage: event?.stage || null, runId: event?.actionSequence ?? null,
|
|
29
|
+
error: event?.status === 'failed' ? errorDetails({ code: event.errorCode }, 'ANALYSIS_FAILED', activeLang) : null };
|
|
30
|
+
const sessionVersion = createHash('sha256').update(versionInput).digest('hex');
|
|
31
|
+
return { schemaVersion: PROTOCOL_VERSION, key, sessionVersion, recordRevision: saved?.revision ?? 0, record, tasks, analysis,
|
|
32
|
+
projectGit: git, capabilities: { read: true, save: true, clear: true, analyze: JSON.parse(key)[0] === 'local', watch: true, locate: false, update: true, ...capabilities } };
|
|
33
|
+
}
|
|
34
|
+
module.exports = { sessionView, PROTOCOL_VERSION };
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
4
|
+
const MAX_LAUNCH_AGE_MS = 8000;
|
|
5
|
+
const MAX_STARTUP_WAIT_MS = 120000;
|
|
6
|
+
const INPUT_QUIET_MS = 350;
|
|
7
|
+
// A quit request that reaches ChatGPT before its main process shows a window is approved
|
|
8
|
+
// by AppKit without the app's own quit lifecycle: the app keeps running, then exits
|
|
9
|
+
// abruptly minutes later. Only ask once a window has been on screen for a moment.
|
|
10
|
+
const WINDOW_SETTLE_MS = 1000;
|
|
11
|
+
// ChatGPT can drain background work before the final shutdown.
|
|
12
|
+
const QUIT_TIMEOUT_MS = 25000;
|
|
13
|
+
// A windowless app is inside its own quit lifecycle; ChatGPT has taken 5–43 s there.
|
|
14
|
+
// Keep the handoff for it, but never claim an exit this long after the request.
|
|
15
|
+
const MAX_DRAIN_MS = 600000;
|
|
16
|
+
// Quitting closes every window first. A target that keeps a window this long after an
|
|
17
|
+
// accepted request has cancelled it: ChatGPT does so when it rebuilds its main window
|
|
18
|
+
// during startup (2026-11-14 15:53, PID69030). Re-ask only while nobody has touched input.
|
|
19
|
+
const DECLINED_AFTER_MS = 5000;
|
|
20
|
+
const MAX_QUIT_RETRIES = 2;
|
|
21
|
+
const COOLDOWN_MS = 120000;
|
|
22
|
+
|
|
23
|
+
// Decides whether a freshly opened Codex may be swapped for one with the debugging port.
|
|
24
|
+
// All side effects go through `adapter`, so every guard below is testable without a real app.
|
|
25
|
+
class StartupController {
|
|
26
|
+
constructor(adapter, { now = Date.now, sleep = delay, lastAttemptAt = 0, attemptPid, attemptInputStamp, pendingHandoff = null, cooldownMs = COOLDOWN_MS, allowClientRestart = true, windowSettleMs = WINDOW_SETTLE_MS } = {}) {
|
|
27
|
+
Object.assign(this, { adapter, now, sleep, lastAttemptAt, attemptPid, attemptInputStamp, cooldownMs, windowSettleMs });
|
|
28
|
+
this.allowClientRestart = allowClientRestart === true;
|
|
29
|
+
this.seen = new Set();
|
|
30
|
+
this.seenIncomplete = new Set();
|
|
31
|
+
this.baselined = false;
|
|
32
|
+
this.busy = false;
|
|
33
|
+
this.stopped = false;
|
|
34
|
+
this.pendingLaunch = false;
|
|
35
|
+
this.pendingHandoff = pendingHandoff;
|
|
36
|
+
this.windowSeen = null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Bridges without window information never report a ready host, so nothing is quit early.
|
|
40
|
+
hostReady(app) {
|
|
41
|
+
if (!app.finishedLaunching || !(app.windows > 0)) {
|
|
42
|
+
if (this.windowSeen?.key === app.key) this.windowSeen = null;
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
if (this.windowSeen?.key !== app.key) this.windowSeen = { key: app.key, since: this.now() };
|
|
46
|
+
return this.now() - this.windowSeen.since >= this.windowSettleMs;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
stop() {
|
|
50
|
+
this.stopped = true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
remember(apps) {
|
|
54
|
+
for (const app of apps) {
|
|
55
|
+
this.seen.add(app.key);
|
|
56
|
+
if (app.launchedAt === 0) this.seenIncomplete.add(app.pid);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async tick() {
|
|
61
|
+
if (this.busy || this.stopped) return;
|
|
62
|
+
this.busy = true;
|
|
63
|
+
this.pendingLaunch = false;
|
|
64
|
+
try {
|
|
65
|
+
await this.evaluate();
|
|
66
|
+
} catch (error) {
|
|
67
|
+
await this.adapter.record('error', { message: error.message }).catch(() => {});
|
|
68
|
+
} finally {
|
|
69
|
+
this.busy = false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async evaluate() {
|
|
74
|
+
const snapshot = await this.adapter.snapshot();
|
|
75
|
+
if (!this.allowClientRestart) {
|
|
76
|
+
this.seen = new Set(snapshot.apps.map(app => app.key));
|
|
77
|
+
this.baselined = true;
|
|
78
|
+
await this.adapter.record('observing', { existingApps: snapshot.apps.length });
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
// Anything already running when we start is somebody's work session: never touch it.
|
|
82
|
+
if (!this.baselined) {
|
|
83
|
+
this.remember(snapshot.apps);
|
|
84
|
+
this.baselined = true;
|
|
85
|
+
await this.adapter.record('watching', { existingApps: snapshot.apps.length });
|
|
86
|
+
if (this.pendingHandoff) await this.resumeHandoff(snapshot);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (this.pendingHandoff) {
|
|
91
|
+
await this.resumeHandoff(snapshot);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const livePids = new Set(snapshot.apps.map(app => app.pid));
|
|
96
|
+
for (const pid of this.seenIncomplete) {
|
|
97
|
+
if (!livePids.has(pid)) this.seenIncomplete.delete(pid);
|
|
98
|
+
}
|
|
99
|
+
const fresh = snapshot.apps.filter(app => !this.seen.has(app.key) && !this.seenIncomplete.has(app.pid));
|
|
100
|
+
if (this.seen.size > 256) this.seen = new Set(snapshot.apps.map(app => app.key));
|
|
101
|
+
// An updater relaunch can briefly overlap the retiring process. Keep the young
|
|
102
|
+
// newcomer unclaimed until it is alone instead of marking it seen forever.
|
|
103
|
+
if (fresh.length === 1 && snapshot.apps.length > 1 && fresh[0].launchedAt > 0
|
|
104
|
+
&& this.now() - fresh[0].launchedAt <= MAX_LAUNCH_AGE_MS) {
|
|
105
|
+
for (const app of snapshot.apps) if (app !== fresh[0]) this.seen.add(app.key);
|
|
106
|
+
this.pendingLaunch = true;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (fresh.length !== 1 || snapshot.apps.length !== 1) {
|
|
110
|
+
this.remember(snapshot.apps);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const app = fresh[0];
|
|
115
|
+
const now = this.now();
|
|
116
|
+
if (app.launchedAt === 0) {
|
|
117
|
+
if (this.pendingIdentity?.pid !== app.pid) this.pendingIdentity = { pid: app.pid, since: now };
|
|
118
|
+
if (now - this.pendingIdentity.since < MAX_LAUNCH_AGE_MS) this.pendingLaunch = true;
|
|
119
|
+
else this.remember([app]);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
this.pendingIdentity = null;
|
|
123
|
+
const age = now - app.launchedAt;
|
|
124
|
+
if (!app.argumentsKnown || app.debugPort !== null) {
|
|
125
|
+
this.seen.add(app.key);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const hasKeyboardClock = Number.isFinite(snapshot.keyboardIdleMs);
|
|
129
|
+
const keyboardIdleMs = hasKeyboardClock ? snapshot.keyboardIdleMs : snapshot.inputIdleMs;
|
|
130
|
+
const launchDeadline = this.launchCandidate?.key === app.key
|
|
131
|
+
? this.launchCandidate.deadline : app.launchedAt + MAX_LAUNCH_AGE_MS;
|
|
132
|
+
const untouched = age >= 0 && now <= launchDeadline && keyboardIdleMs >= age;
|
|
133
|
+
const inputQuiet = !hasKeyboardClock || snapshot.inputIdleMs >= INPUT_QUIET_MS;
|
|
134
|
+
const ready = this.hostReady(app);
|
|
135
|
+
// Dock and navigation clicks settle before the handoff. Typing still protects
|
|
136
|
+
// the running session, and the native helper rechecks input immediately before quit.
|
|
137
|
+
if (untouched && (!ready || snapshot.frontmostPid !== app.pid || !inputQuiet)) {
|
|
138
|
+
if (this.launchCandidate?.key !== app.key) this.launchCandidate = { key: app.key, deadline: app.launchedAt + MAX_STARTUP_WAIT_MS };
|
|
139
|
+
const reason = !app.finishedLaunching ? 'launching' : !ready ? 'host-starting'
|
|
140
|
+
: snapshot.frontmostPid !== app.pid ? 'background' : 'input-settling';
|
|
141
|
+
const waitingFor = `${app.key}:${reason}`;
|
|
142
|
+
if (this.waitingFor !== waitingFor) {
|
|
143
|
+
this.waitingFor = waitingFor;
|
|
144
|
+
await this.adapter.record('waiting-startup', { processKey: app.key, reason, ageMs: age,
|
|
145
|
+
inputIdleMs: snapshot.inputIdleMs, keyboardIdleMs });
|
|
146
|
+
}
|
|
147
|
+
this.pendingLaunch = true;
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Remember rejected candidates too, so a running window is never revisited later.
|
|
152
|
+
this.seen.add(app.key);
|
|
153
|
+
if (!untouched || snapshot.frontmostPid !== app.pid) {
|
|
154
|
+
await this.adapter.record('skipped-active-or-background', { processKey: app.key,
|
|
155
|
+
reason: age < 0 ? 'invalid-launch-time' : now > launchDeadline ? 'launch-window-expired' : 'keyboard-input',
|
|
156
|
+
ageMs: age, inputIdleMs: snapshot.inputIdleMs, keyboardIdleMs, frontmostPid: snapshot.frontmostPid });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
// Allow a genuinely new user launch to recover after a failed handoff.
|
|
160
|
+
const userReopened = Number.isFinite(this.attemptInputStamp) && this.attemptPid != null && app.pid !== this.attemptPid
|
|
161
|
+
&& snapshot.inputStamp !== this.attemptInputStamp
|
|
162
|
+
&& app.launchedAt > this.lastAttemptAt && now - snapshot.inputIdleMs > this.lastAttemptAt;
|
|
163
|
+
if (!userReopened && this.lastAttemptAt && now - this.lastAttemptAt < this.cooldownMs) {
|
|
164
|
+
await this.adapter.record('skipped-cooldown');
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (await this.adapter.portInUse()) {
|
|
168
|
+
await this.adapter.record('port-in-use');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
await this.handoff(app, snapshot);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async handoff(app, snapshot) {
|
|
175
|
+
if (this.stopped) return;
|
|
176
|
+
// The receipt must be durable before quitting, so a crash here cannot become a restart loop.
|
|
177
|
+
this.lastAttemptAt = this.now();
|
|
178
|
+
this.attemptPid = app.pid;
|
|
179
|
+
this.attemptInputStamp = snapshot.inputStamp;
|
|
180
|
+
await this.adapter.record('attempt', { lastAttemptAt: this.lastAttemptAt, processKey: app.key,
|
|
181
|
+
attemptPid: this.attemptPid, attemptInputStamp: this.attemptInputStamp });
|
|
182
|
+
if (this.stopped) return;
|
|
183
|
+
|
|
184
|
+
const quit = await this.adapter.quit(app, snapshot.inputStamp);
|
|
185
|
+
if (!quit.accepted) {
|
|
186
|
+
const deadline = this.launchCandidate?.key === app.key ? this.launchCandidate.deadline : app.launchedAt + MAX_LAUNCH_AGE_MS;
|
|
187
|
+
const retry = (quit.reason === 'input-changed' || quit.reason === 'not-ready') && this.now() <= deadline;
|
|
188
|
+
if (retry) {
|
|
189
|
+
this.seen.delete(app.key);
|
|
190
|
+
this.pendingLaunch = true;
|
|
191
|
+
this.lastAttemptAt = 0;
|
|
192
|
+
}
|
|
193
|
+
await this.adapter.record('quit-refused', { reason: quit.reason, retry, lastAttemptAt: this.lastAttemptAt });
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
this.pendingHandoff = { app, inputStamp: snapshot.inputStamp, requestedAt: this.now() };
|
|
198
|
+
await this.adapter.record('quit-accepted', { pendingHandoff: this.pendingHandoff });
|
|
199
|
+
const absent = await this.waitForExit(app, snapshot.inputStamp);
|
|
200
|
+
if (!absent) {
|
|
201
|
+
this.pendingLaunch = Boolean(this.pendingHandoff);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
await this.reopen(absent, snapshot.inputStamp);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async resumeHandoff(snapshot) {
|
|
208
|
+
const pending = this.pendingHandoff;
|
|
209
|
+
const replaced = snapshot.apps.some(app => app.key !== pending.app.key &&
|
|
210
|
+
!(app.pid === pending.app.pid && app.launchedAt === 0));
|
|
211
|
+
// An accepted OS quit request cannot be withdrawn by expiring our receipt.
|
|
212
|
+
// Keep ownership of that process until it exits or a replacement takes over.
|
|
213
|
+
if (replaced) {
|
|
214
|
+
this.remember(snapshot.apps);
|
|
215
|
+
this.pendingHandoff = null;
|
|
216
|
+
await this.adapter.record('late-exit-replaced', { pendingHandoff: null });
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const requestedAt = pending.requestedAt ?? this.lastAttemptAt;
|
|
220
|
+
const target = snapshot.apps.find(app => app.key === pending.app.key);
|
|
221
|
+
if (target) pending.windows = Number.isInteger(target.windows) ? target.windows : null;
|
|
222
|
+
// Input only means "the user is back in this app" while it still has a window: a
|
|
223
|
+
// draining, windowless app cannot be used, so clicks elsewhere keep the handoff.
|
|
224
|
+
// A later ordinary exit of a usable app must not be mistaken for this handoff.
|
|
225
|
+
const elapsed = this.now() - requestedAt;
|
|
226
|
+
const draining = pending.windows === 0;
|
|
227
|
+
if ((elapsed >= QUIT_TIMEOUT_MS && snapshot.inputStamp !== pending.inputStamp && !draining) || elapsed >= MAX_DRAIN_MS) {
|
|
228
|
+
this.remember(snapshot.apps);
|
|
229
|
+
this.pendingHandoff = null;
|
|
230
|
+
await this.adapter.record('handoff-user-resumed', { pendingHandoff: null, processKey: pending.app.key });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (snapshot.apps.length) {
|
|
234
|
+
this.pendingLaunch = true;
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
await this.adapter.record('late-exit-observed', { processKey: pending.app.key });
|
|
238
|
+
await this.reopen(snapshot, pending.inputStamp);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async reopen(absent, inputStamp) {
|
|
242
|
+
await this.adapter.record('reopening');
|
|
243
|
+
this.pendingHandoff = null;
|
|
244
|
+
if (this.stopped) return;
|
|
245
|
+
|
|
246
|
+
await this.sleep(250);
|
|
247
|
+
const beforeLaunch = await this.adapter.snapshot();
|
|
248
|
+
if (this.stopped || beforeLaunch.apps.length) {
|
|
249
|
+
this.remember(beforeLaunch.apps);
|
|
250
|
+
await this.adapter.record('reopen-canceled', { pendingHandoff: null });
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Past a successful quit, input only suppresses focus; the app itself is always reopened.
|
|
255
|
+
const opened = await this.adapter.launch();
|
|
256
|
+
if (!opened.launched) {
|
|
257
|
+
await this.adapter.record('launch-failed', { pendingHandoff: null });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (opened.key) this.seen.add(opened.key);
|
|
261
|
+
if (this.stopped) return;
|
|
262
|
+
|
|
263
|
+
const beforeShow = await this.adapter.snapshot();
|
|
264
|
+
this.remember(beforeShow.apps);
|
|
265
|
+
const undisturbed = absent.inputStamp === inputStamp
|
|
266
|
+
&& beforeLaunch.inputStamp === inputStamp
|
|
267
|
+
&& beforeShow.inputStamp === inputStamp
|
|
268
|
+
&& beforeShow.frontmostPid === beforeLaunch.frontmostPid
|
|
269
|
+
&& !beforeShow.apps.some(current => current.key !== opened.key);
|
|
270
|
+
const shown = undisturbed && !this.stopped
|
|
271
|
+
? await this.adapter.show(opened, inputStamp, beforeLaunch.frontmostPid)
|
|
272
|
+
: { shown: false };
|
|
273
|
+
await this.adapter.record('reopened', { shown: !!shown.shown, processKey: opened.key, lastAttemptAt: 0, pendingHandoff: null });
|
|
274
|
+
this.lastAttemptAt = 0;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async waitForExit(app, inputStamp) {
|
|
278
|
+
const startedAt = this.now();
|
|
279
|
+
let deadline = startedAt + QUIT_TIMEOUT_MS;
|
|
280
|
+
let waitingFor = app;
|
|
281
|
+
let followedReplacement = false;
|
|
282
|
+
let retries = 0;
|
|
283
|
+
let shownSince = null;
|
|
284
|
+
let current;
|
|
285
|
+
while (!this.stopped && this.now() < deadline) {
|
|
286
|
+
await this.sleep(200);
|
|
287
|
+
current = await this.adapter.snapshot();
|
|
288
|
+
const replacements = current.apps.filter(other => other.key !== waitingFor.key
|
|
289
|
+
&& !(other.pid === waitingFor.pid && other.launchedAt === 0));
|
|
290
|
+
if (replacements.length) {
|
|
291
|
+
const candidate = replacements[0];
|
|
292
|
+
const age = this.now() - candidate.launchedAt;
|
|
293
|
+
const untouched = current.inputStamp === inputStamp && age >= 0 && age <= MAX_STARTUP_WAIT_MS && current.inputIdleMs >= age;
|
|
294
|
+
// LaunchServices can briefly report both the retiring process and its replacement.
|
|
295
|
+
if (!followedReplacement && current.inputStamp === inputStamp && replacements.length === 1
|
|
296
|
+
&& (candidate.launchedAt === 0 || (untouched && current.apps.length > 1))) continue;
|
|
297
|
+
// Follow one automatic startup replacement as part of this same handoff. A user
|
|
298
|
+
// reopening the app changes the input stamp, so their new session stays untouched.
|
|
299
|
+
if (!followedReplacement && untouched && current.apps.length === 1 &&
|
|
300
|
+
candidate.argumentsKnown && candidate.debugPort === null &&
|
|
301
|
+
(current.frontmostPid === candidate.pid || current.frontmostPid === waitingFor.pid)) {
|
|
302
|
+
if (!this.hostReady(candidate)) continue;
|
|
303
|
+
this.seen.add(candidate.key);
|
|
304
|
+
followedReplacement = true;
|
|
305
|
+
await this.adapter.record('following-startup-replacement', {
|
|
306
|
+
previousProcessKey: waitingFor.key, processKey: candidate.key
|
|
307
|
+
});
|
|
308
|
+
if (this.stopped) return null;
|
|
309
|
+
const quit = await this.adapter.quit(candidate, inputStamp);
|
|
310
|
+
if (!quit.accepted) {
|
|
311
|
+
this.pendingHandoff = null;
|
|
312
|
+
await this.adapter.record('quit-refused', { pendingHandoff: null });
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
this.pendingHandoff.app = candidate;
|
|
316
|
+
await this.adapter.record('quit-accepted', { pendingHandoff: this.pendingHandoff });
|
|
317
|
+
waitingFor = candidate;
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
this.remember(current.apps);
|
|
321
|
+
this.pendingHandoff = null;
|
|
322
|
+
await this.adapter.record('another-instance-started', {
|
|
323
|
+
processKey: waitingFor.key, processKeys: current.apps.map(other => other.key), inputChanged: current.inputStamp !== inputStamp,
|
|
324
|
+
pendingHandoff: null
|
|
325
|
+
});
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
if (current.apps.length === 0) return current;
|
|
329
|
+
const target = current.apps.find(other => other.key === waitingFor.key);
|
|
330
|
+
if (!(target?.windows > 0)) { shownSince = null; continue; }
|
|
331
|
+
shownSince ??= this.now();
|
|
332
|
+
if (this.now() - shownSince < DECLINED_AFTER_MS || retries >= MAX_QUIT_RETRIES || current.inputStamp !== inputStamp) continue;
|
|
333
|
+
retries += 1;
|
|
334
|
+
shownSince = null;
|
|
335
|
+
if (this.stopped) return null;
|
|
336
|
+
const again = await this.adapter.quit(target, inputStamp);
|
|
337
|
+
await this.adapter.record('quit-retried', { processKey: target.key, attempt: retries, accepted: !!again.accepted, reason: again.reason ?? null });
|
|
338
|
+
if (again.accepted) {
|
|
339
|
+
this.pendingHandoff.requestedAt = this.now();
|
|
340
|
+
deadline = this.now() + QUIT_TIMEOUT_MS;
|
|
341
|
+
} else retries = MAX_QUIT_RETRIES;
|
|
342
|
+
}
|
|
343
|
+
const remaining = current?.apps.find(other => other.key === waitingFor.key);
|
|
344
|
+
if (this.pendingHandoff && remaining) this.pendingHandoff.windows = Number.isInteger(remaining.windows) ? remaining.windows : null;
|
|
345
|
+
if (!this.stopped) await this.adapter.record('quit-timeout', { processKey: waitingFor.key, pendingHandoff: this.pendingHandoff,
|
|
346
|
+
waitedMs: this.now() - startedAt, processKeys: current?.apps.map(other => other.key) || [],
|
|
347
|
+
// Zero windows means the app entered its own quit lifecycle and is draining.
|
|
348
|
+
windows: current?.apps.find(other => other.key === waitingFor.key)?.windows ?? null,
|
|
349
|
+
inputChanged: current?.inputStamp !== inputStamp });
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
module.exports = { StartupController, COOLDOWN_MS, WINDOW_SETTLE_MS };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const net = require('node:net');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const readline = require('node:readline');
|
|
6
|
+
const { execFile, spawn } = require('node:child_process');
|
|
7
|
+
const { promisify } = require('node:util');
|
|
8
|
+
const { CDP_PORT } = require('../cdp.cjs');
|
|
9
|
+
const { StartupController } = require('./controller.cjs');
|
|
10
|
+
|
|
11
|
+
const run = promisify(execFile);
|
|
12
|
+
|
|
13
|
+
function portInUse(port = CDP_PORT) {
|
|
14
|
+
return new Promise(resolve => {
|
|
15
|
+
const socket = net.createConnection({ host: '127.0.0.1', port });
|
|
16
|
+
const done = value => {
|
|
17
|
+
socket.destroy();
|
|
18
|
+
resolve(value);
|
|
19
|
+
};
|
|
20
|
+
socket.once('connect', () => done(true));
|
|
21
|
+
socket.once('error', error => done(error.code !== 'ECONNREFUSED'));
|
|
22
|
+
socket.setTimeout(350, () => done(true));
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readState(file) {
|
|
27
|
+
try {
|
|
28
|
+
const state = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
29
|
+
return Number.isFinite(state.lastAttemptAt ?? 0) ? state : {};
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (error.code === 'ENOENT') return {};
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function startWatcher({ root, settings, log, onLaunch = () => {} }) {
|
|
37
|
+
const bridgePath = path.join(root, 'bridge');
|
|
38
|
+
const stateFile = path.join(root, 'state.json');
|
|
39
|
+
const abort = new AbortController();
|
|
40
|
+
let state = readState(stateFile);
|
|
41
|
+
|
|
42
|
+
const native = async (action, ...args) => {
|
|
43
|
+
const { stdout } = await run(bridgePath, [action, settings.app, ...args.map(String)], {
|
|
44
|
+
timeout: 35000, maxBuffer: 65536, signal: abort.signal
|
|
45
|
+
});
|
|
46
|
+
return JSON.parse(stdout);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const adapter = {
|
|
50
|
+
snapshot: () => native('snapshot'),
|
|
51
|
+
quit: (app, stamp) => native('quit', app.pid, app.key, stamp),
|
|
52
|
+
launch: () => native('launch', CDP_PORT),
|
|
53
|
+
show: (app, stamp, frontmost) => native('show', app.pid, app.key, stamp, frontmost),
|
|
54
|
+
portInUse,
|
|
55
|
+
async record(event, details = {}) {
|
|
56
|
+
const { lastAttemptAt, attemptPid, attemptInputStamp, pendingHandoff } = state;
|
|
57
|
+
state = { lastAttemptAt, attemptPid, attemptInputStamp, pendingHandoff, ...details, event, updatedAt: Date.now() };
|
|
58
|
+
const temp = `${stateFile}.tmp`;
|
|
59
|
+
fs.writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
60
|
+
fs.renameSync(temp, stateFile);
|
|
61
|
+
log(`startup: ${event} ${JSON.stringify(state)}`);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const controller = new StartupController(adapter, {
|
|
66
|
+
lastAttemptAt: state.event === 'reopened' ? 0 : state.lastAttemptAt || 0,
|
|
67
|
+
attemptPid: state.attemptPid,
|
|
68
|
+
attemptInputStamp: state.attemptInputStamp,
|
|
69
|
+
pendingHandoff: state.pendingHandoff,
|
|
70
|
+
allowClientRestart: settings.allowClientRestart
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
let stopped = false;
|
|
74
|
+
let queued = false;
|
|
75
|
+
let pumping = false;
|
|
76
|
+
let pendingTimer;
|
|
77
|
+
|
|
78
|
+
async function pump() {
|
|
79
|
+
queued = true;
|
|
80
|
+
if (pumping || stopped) return;
|
|
81
|
+
pumping = true;
|
|
82
|
+
clearTimeout(pendingTimer);
|
|
83
|
+
try {
|
|
84
|
+
while (queued && !stopped) {
|
|
85
|
+
queued = false;
|
|
86
|
+
await controller.tick();
|
|
87
|
+
}
|
|
88
|
+
} finally {
|
|
89
|
+
pumping = false;
|
|
90
|
+
// Accepted quits are resumed by native termination/launch notifications.
|
|
91
|
+
// They may remain pending for minutes; avoid spawning a snapshot each second.
|
|
92
|
+
if (controller.pendingLaunch && !controller.pendingHandoff && !stopped) pendingTimer = setTimeout(pump, 300);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// NSWorkspace notifications, so nothing spawns native processes while Codex is idle.
|
|
97
|
+
const observer = spawn(bridgePath, ['watch', settings.app], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
98
|
+
const lines = readline.createInterface({ input: observer.stdout });
|
|
99
|
+
lines.on('line', line => {
|
|
100
|
+
try {
|
|
101
|
+
if (JSON.parse(line).event === 'NSWorkspaceDidLaunchApplicationNotification') onLaunch();
|
|
102
|
+
} catch { /* Ignore incomplete native notifications. */ }
|
|
103
|
+
pump();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const stop = () => {
|
|
107
|
+
if (stopped) return;
|
|
108
|
+
stopped = true;
|
|
109
|
+
controller.stop();
|
|
110
|
+
clearTimeout(pendingTimer);
|
|
111
|
+
abort.abort();
|
|
112
|
+
observer.kill('SIGTERM');
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// launchd restarts the whole agent, and the fresh baseline keeps that restart harmless.
|
|
116
|
+
const exited = new Promise(resolve => {
|
|
117
|
+
observer.once('error', resolve);
|
|
118
|
+
observer.once('exit', resolve);
|
|
119
|
+
}).then(() => {
|
|
120
|
+
if (!stopped) throw new Error('bridge watcher exited');
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
return { stop, exited };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = { portInUse, readState, startWatcher };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const { spawnSync } = require('node:child_process');
|
|
5
|
+
|
|
6
|
+
// The bundled bridge serializes PID inspection/replacement with a kernel file lock.
|
|
7
|
+
// A dead owner is reclaimed; a live owner is never expired by elapsed time.
|
|
8
|
+
function withStateFileLock(file, operation) {
|
|
9
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
10
|
+
const lock = `${file}.write-lock`;
|
|
11
|
+
const deadline = performance.now() + 3000;
|
|
12
|
+
const delay = new Int32Array(new SharedArrayBuffer(4));
|
|
13
|
+
while (true) {
|
|
14
|
+
if (tryAcquirePidLock(lock)) break;
|
|
15
|
+
if (performance.now() >= deadline) throw new Error('账本正由其他进程更新,请稍后重试');
|
|
16
|
+
Atomics.wait(delay, 0, 0, 15);
|
|
17
|
+
}
|
|
18
|
+
try { return operation(); }
|
|
19
|
+
finally { fs.unlinkSync(lock); }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let bridge;
|
|
23
|
+
function tryAcquirePidLock(file) {
|
|
24
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
25
|
+
bridge ||= require('./native-bridge.cjs').verifyBridgeBundle(path.resolve(__dirname, '..'));
|
|
26
|
+
const result = spawnSync(bridge, ['claim-lock', file, String(process.pid)], { encoding: 'utf8', timeout: 1000 });
|
|
27
|
+
if (result.error) throw result.error;
|
|
28
|
+
if (result.status !== 0) throw new Error('本机进程锁不可用,请重新同步安装组件');
|
|
29
|
+
return JSON.parse(result.stdout).acquired === true;
|
|
30
|
+
}
|
|
31
|
+
module.exports = { withStateFileLock, tryAcquirePidLock };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { progressError } = require('./progress-error.cjs');
|
|
3
|
+
const { readTurns } = require('./analysis-source.cjs');
|
|
4
|
+
const normalize = text => text.replace(/\s+/g, ' ').trim();
|
|
5
|
+
|
|
6
|
+
function messageText(item) {
|
|
7
|
+
if (item.type === 'userMessage') return (item.content || []).filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
8
|
+
if (item.type === 'agentMessage' && (item.phase === 'final_answer' || item.phase == null) &&
|
|
9
|
+
!/^\s*(?:\[external_agent_tool_|<EXTERNAL SESSION IMPORTED>)/.test(item.text || '')) return item.text;
|
|
10
|
+
return '';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function resolveTaskSources(request, key, tasks, { inferTitles = false } = {}) {
|
|
14
|
+
if (!tasks.some(task => task.source || inferTitles)) return tasks.map(() => null);
|
|
15
|
+
const [hostId, sidebarId] = JSON.parse(key);
|
|
16
|
+
const threadId = sidebarId.replace(/^local:/, '');
|
|
17
|
+
const pending = tasks.map(task => {
|
|
18
|
+
const reference = task.source || (inferTitles && task.title.length >= 10 ? { locator: task.title } : null);
|
|
19
|
+
if (reference && (typeof reference.locator !== 'string' || normalize(reference.locator).length < 10 || reference.locator.length > 240)) throw progressError('INVALID_ARGUMENT', '任务来源原文应为10至240个字符');
|
|
20
|
+
return reference;
|
|
21
|
+
});
|
|
22
|
+
const matches = tasks.map(() => []);
|
|
23
|
+
await readTurns(request, threadId, null, turn => {
|
|
24
|
+
for (const item of turn.items || []) {
|
|
25
|
+
const text = messageText(item);
|
|
26
|
+
if (!text) continue;
|
|
27
|
+
const clean = normalize(text);
|
|
28
|
+
pending.forEach((reference, index) => {
|
|
29
|
+
if (!reference || reference.turnId && reference.turnId !== turn.id || reference.itemId && reference.itemId !== item.id) return;
|
|
30
|
+
if (clean.includes(normalize(reference.locator))) matches[index].push({ hostId, threadId, turnId: turn.id, itemId: item.id,
|
|
31
|
+
locator: reference.locator.trim(), turnStartedAt: turn.startedAt ?? null, turnCompletedAt: turn.completedAt ?? null });
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
return matches.map((candidates, index) => {
|
|
36
|
+
if (candidates.length === 1) return candidates[0];
|
|
37
|
+
if (!tasks[index].source) return null;
|
|
38
|
+
throw progressError('SOURCE_NOT_FOUND', `第 ${index + 1} 项任务来源${candidates.length ? '匹配多条消息,请补充 turnId 和 itemId' : '未在本会话中找到,请核对原文'}`);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { resolveTaskSources };
|