agent-things 0.0.0-stage → 1.2.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.
Files changed (124) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +221 -2
  4. package/bin/agent-things.cjs +8 -0
  5. package/bin/antigravity-session-status.cjs +96 -0
  6. package/bin/claude-session-status.cjs +55 -0
  7. package/bin/codex-session-status.cjs +287 -0
  8. package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
  9. package/mods/agent-things-ui/SKILL.md +10 -0
  10. package/mods/agent-things-ui/hooks/controls.js +112 -0
  11. package/mods/agent-things-ui/hooks/foundation.js +431 -0
  12. package/mods/agent-things-ui/hooks/hooks.json +1 -0
  13. package/mods/agent-things-ui/hooks/presentation.js +223 -0
  14. package/mods/agent-things-ui/hooks/progress.js +1 -0
  15. package/mods/agent-things-ui/hooks/register.js +382 -0
  16. package/native/bin/bridge +0 -0
  17. package/native/bin/bridge.json +20 -0
  18. package/native/session-status-bridge.swift +280 -0
  19. package/outputs/antigravity-session-status.js +2476 -0
  20. package/outputs/codex-session-status.js +1761 -0
  21. package/package.json +75 -4
  22. package/scripts/build-antigravity-bundle.cjs +35 -0
  23. package/scripts/build-codex-bundle.cjs +31 -0
  24. package/scripts/build-native-bridge.cjs +55 -0
  25. package/scripts/build-shared-ui.cjs +16 -0
  26. package/scripts/setup-antigravity-service.cjs +71 -0
  27. package/scripts/setup-claude-service.cjs +21 -0
  28. package/skills/agent-things/SKILL.en.md +95 -0
  29. package/skills/agent-things/SKILL.md +99 -0
  30. package/skills/codex/things/SKILL.en.md +10 -0
  31. package/skills/codex/things/SKILL.md +10 -0
  32. package/skills/things/SKILL.en.md +10 -0
  33. package/skills/things/SKILL.md +10 -0
  34. package/skills/things/checklist.en.md +91 -0
  35. package/skills/things/checklist.md +95 -0
  36. package/src/analysis-app-server.cjs +74 -0
  37. package/src/analysis-assets/output.en.schema.json +93 -0
  38. package/src/analysis-assets/output.schema.json +93 -0
  39. package/src/analysis-assets/prompt.en.txt +17 -0
  40. package/src/analysis-assets/prompt.zh-CN.txt +18 -0
  41. package/src/analysis-budget.cjs +105 -0
  42. package/src/analysis-git.cjs +38 -0
  43. package/src/analysis-history.cjs +150 -0
  44. package/src/analysis-ledger.cjs +82 -0
  45. package/src/analysis-log.cjs +62 -0
  46. package/src/analysis-runner.cjs +203 -0
  47. package/src/analysis-service.cjs +197 -0
  48. package/src/analysis-source.cjs +72 -0
  49. package/src/antigravity-card.cjs +2063 -0
  50. package/src/antigravity-hook.cjs +138 -0
  51. package/src/antigravity-mcp-config.cjs +36 -0
  52. package/src/app-server.cjs +96 -0
  53. package/src/cdp.cjs +115 -0
  54. package/src/claude-inline-install.cjs +38 -0
  55. package/src/claude-mcp-config.cjs +29 -0
  56. package/src/cli/arguments.cjs +30 -0
  57. package/src/cli/environment-probe.cjs +130 -0
  58. package/src/cli/integration-state.cjs +15 -0
  59. package/src/cli/interactive-cli.cjs +236 -0
  60. package/src/cli/prompt-tui.cjs +420 -0
  61. package/src/cli/setup-orchestrator.cjs +449 -0
  62. package/src/codex-mcp-config.cjs +67 -0
  63. package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
  64. package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
  65. package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
  66. package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
  67. package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
  68. package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
  69. package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
  70. package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
  71. package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
  72. package/src/harnesses/antigravity/transcript-source.cjs +100 -0
  73. package/src/harnesses/claude/claude-harness.js +93 -0
  74. package/src/harnesses/claude/claude-host-helper.cjs +176 -0
  75. package/src/harnesses/claude/claude-injector.cjs +95 -0
  76. package/src/harnesses/claude/claude-local-source.cjs +106 -0
  77. package/src/harnesses/claude/claude-navigation.cjs +99 -0
  78. package/src/harnesses/claude/claude-runner.cjs +74 -0
  79. package/src/harnesses/claude/claude-service.cjs +313 -0
  80. package/src/harnesses/claude/claude-source.cjs +70 -0
  81. package/src/harnesses/codex/codex-analysis.cjs +10 -0
  82. package/src/harnesses/codex/codex-card-bridge.js +123 -0
  83. package/src/harnesses/codex/codex-card-events.cjs +76 -0
  84. package/src/harnesses/codex/codex-card.cjs +169 -0
  85. package/src/harnesses/codex/codex-git.cjs +24 -0
  86. package/src/harnesses/codex/codex-harness.js +229 -0
  87. package/src/harnesses/codex/codex-local-card.js +97 -0
  88. package/src/harnesses/codex/codex-progress-context.cjs +84 -0
  89. package/src/harnesses/codex/codex-service.cjs +502 -0
  90. package/src/i18n.cjs +174 -0
  91. package/src/launchd.cjs +105 -0
  92. package/src/lifecycle-lock.cjs +13 -0
  93. package/src/local-progress-http.cjs +267 -0
  94. package/src/manual-status-agent.cjs +12 -0
  95. package/src/manual-status-startup.cjs +66 -0
  96. package/src/manual-status-store.cjs +466 -0
  97. package/src/mcp-stdio.cjs +67 -0
  98. package/src/model-router.cjs +63 -0
  99. package/src/native-bridge.cjs +17 -0
  100. package/src/npm-updates.cjs +228 -0
  101. package/src/plugins/things/assets/logo.svg +13 -0
  102. package/src/plugins/things/plugin.json +6 -0
  103. package/src/plugins/things/sidecars/things_board/app.js +447 -0
  104. package/src/plugins/things/sidecars/things_board/index.html +2141 -0
  105. package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
  106. package/src/plugins/things/sidecars/things_board/package.json +6 -0
  107. package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
  108. package/src/plugins/things/sidecars/things_board/styles.css +560 -0
  109. package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
  110. package/src/progress-error.cjs +54 -0
  111. package/src/progress-tools.cjs +145 -0
  112. package/src/project-path.cjs +15 -0
  113. package/src/renderer-resource.cjs +17 -0
  114. package/src/request-budget.cjs +24 -0
  115. package/src/resolve.cjs +51 -0
  116. package/src/runtime-install.cjs +635 -0
  117. package/src/session-status-filter.cjs +136 -0
  118. package/src/session-status.js +992 -0
  119. package/src/session-view.cjs +34 -0
  120. package/src/startup/controller.cjs +354 -0
  121. package/src/startup/watch.cjs +126 -0
  122. package/src/state-file-lock.cjs +31 -0
  123. package/src/task-provenance.cjs +42 -0
  124. package/src/ui-foundation.cjs +435 -0
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const { execFileSync } = require('node:child_process');
6
+
7
+ const LABEL = 'com.codexsessionstatus.agent';
8
+ const UPDATE_LABEL = 'com.codexsessionstatus.update';
9
+ const home = os.homedir();
10
+ const paths = {
11
+ installDir: path.join(home, 'Library/Application Support/CodexSessionStatus'),
12
+ logDir: path.join(home, 'Library/Logs/CodexSessionStatus'),
13
+ plist: path.join(home, 'Library/LaunchAgents', `${LABEL}.plist`)
14
+ };
15
+ const LEGACY_LABEL = 'com.codexplus.agent';
16
+ const legacyPaths = {
17
+ installDir: path.join(home, 'Library/Application Support/CodexPlus'),
18
+ logDir: path.join(home, 'Library/Logs/CodexPlus'),
19
+ plist: path.join(home, 'Library/LaunchAgents', `${LEGACY_LABEL}.plist`)
20
+ };
21
+ const domain = () => `gui/${process.getuid()}`;
22
+
23
+ // [installed path, name inside the Trash folder]. The two directories share a basename.
24
+ const trashItems = (locations = paths) => [
25
+ [locations.installDir, 'Application Support'],
26
+ [locations.logDir, 'Logs'],
27
+ [locations.plist, path.basename(locations.plist)]
28
+ ];
29
+
30
+ const escapeXml = value => String(value)
31
+ .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
32
+
33
+ function xml(value) {
34
+ if (typeof value === 'boolean') return value ? '<true/>' : '<false/>';
35
+ if (typeof value === 'number') return `<integer>${value}</integer>`;
36
+ if (Array.isArray(value)) return `<array>${value.map(xml).join('')}</array>`;
37
+ if (value && typeof value === 'object') {
38
+ const entries = Object.entries(value).map(([key, item]) => `<key>${escapeXml(key)}</key>${xml(item)}`);
39
+ return `<dict>${entries.join('')}</dict>`;
40
+ }
41
+ return `<string>${escapeXml(value)}</string>`;
42
+ }
43
+
44
+ function plistXml(value) {
45
+ return '<?xml version="1.0" encoding="UTF-8"?>\n'
46
+ + '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
47
+ + `<plist version="1.0">${xml(value)}</plist>\n`;
48
+ }
49
+
50
+ function agentConfig({ node, installDir = paths.installDir, logDir = paths.logDir, label = LABEL }) {
51
+ return {
52
+ Label: label,
53
+ ProgramArguments: [node, path.join(installDir, 'src/agent.cjs')],
54
+ RunAtLoad: true,
55
+ KeepAlive: { SuccessfulExit: false },
56
+ ThrottleInterval: 10,
57
+ ProcessType: 'Background',
58
+ StandardOutPath: path.join(logDir, 'agent.log'),
59
+ StandardErrorPath: path.join(logDir, 'agent.err.log')
60
+ };
61
+ }
62
+
63
+ // An independent, one-shot job survives bootout of the agent it is upgrading.
64
+ function updateConfig({ node, installDir = paths.installDir, logDir = paths.logDir }) {
65
+ return {
66
+ Label: UPDATE_LABEL,
67
+ ProgramArguments: [node, path.join(installDir, 'src/update.cjs'), '--auto'],
68
+ RunAtLoad: true,
69
+ ProcessType: 'Background',
70
+ EnvironmentVariables: { NODE_OPTIONS: '', NODE_PATH: '' },
71
+ StandardOutPath: path.join(logDir, 'update.log'),
72
+ StandardErrorPath: path.join(logDir, 'update.err.log')
73
+ };
74
+ }
75
+
76
+ const launchctl = (...args) => execFileSync('/bin/launchctl', args, {
77
+ encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'pipe']
78
+ });
79
+
80
+ function printJob(label = LABEL) {
81
+ try {
82
+ return launchctl('print', `${domain()}/${label}`);
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function bootstrap(plist = paths.plist) {
89
+ launchctl('bootstrap', domain(), plist);
90
+ }
91
+
92
+ async function bootout(label = LABEL) {
93
+ if (!printJob(label)) return;
94
+ launchctl('bootout', `${domain()}/${label}`);
95
+ for (let i = 0; i < 50 && printJob(label); i++) await new Promise(resolve => setTimeout(resolve, 100));
96
+ if (printJob(label)) throw new Error(`后台任务未退出:${label}`);
97
+ }
98
+
99
+ function writePlist(config, file = paths.plist) {
100
+ fs.mkdirSync(path.dirname(file), { recursive: true });
101
+ fs.writeFileSync(file, plistXml(config), { mode: 0o644 });
102
+ execFileSync('/usr/bin/plutil', ['-lint', file], { stdio: 'ignore' });
103
+ }
104
+
105
+ module.exports = { LABEL, UPDATE_LABEL, LEGACY_LABEL, legacyPaths, agentConfig, updateConfig, bootout, bootstrap, paths, plistXml, printJob, trashItems, writePlist };
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { tryAcquirePidLock } = require('./state-file-lock.cjs');
5
+ const { progressError } = require('./progress-error.cjs');
6
+ async function withLifecycleLock(directory, operation) {
7
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
8
+ const file = path.join(directory, 'installation.lock');
9
+ if (!tryAcquirePidLock(file)) throw progressError('SERVICE_STOPPING', '安装、升级或卸载正在执行,请稍后重试');
10
+ try { return await operation(); }
11
+ finally { if (fs.existsSync(file) && fs.readFileSync(file, 'utf8').trim() === String(process.pid)) fs.unlinkSync(file); }
12
+ }
13
+ module.exports = { withLifecycleLock };
@@ -0,0 +1,267 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const http = require('node:http');
4
+ const crypto = require('node:crypto');
5
+ const path = require('node:path');
6
+
7
+ const { errorDetails, progressError } = require('./progress-error.cjs');
8
+ const { readConfiguredLang } = require('./i18n.cjs');
9
+
10
+ const MAX_BODY_BYTES = 1024 * 1024;
11
+ const nativeOrigin = origin => !origin || origin === 'null' || origin === 'vscode-file://vscode-app' || /^vscode-webview:\/\/[a-z0-9-]+$/.test(origin) || /^plugin:\/\/[a-z0-9_-]+$/.test(origin);
12
+
13
+ async function startProgressHttp({ port, stateFile, handle, brainDir }) {
14
+ const token = crypto.randomBytes(32).toString('hex');
15
+ const stateId = crypto.createHash('sha256').update(path.resolve(stateFile)).digest('hex');
16
+ const credentialFile = `${stateFile}.http.json`;
17
+ const defaultBrain = brainDir || path.resolve(path.dirname(stateFile), '../brain');
18
+ const allowedOrigins = new Set();
19
+ const subscribeTickets = new Map();
20
+ const sseClients = new Set();
21
+ const activeLang = () => readConfiguredLang({ dataDir: stateFile ? path.dirname(stateFile) : undefined });
22
+ const msg = (zh, en) => (activeLang() === 'en' ? en : zh);
23
+
24
+ function pruneTickets() {
25
+ const now = Date.now();
26
+ for (const [ticket, info] of subscribeTickets) {
27
+ if (info.expiresAt <= now) subscribeTickets.delete(ticket);
28
+ }
29
+ }
30
+
31
+ function issueTicket(conversationId) {
32
+ pruneTickets();
33
+ if (!conversationId || typeof conversationId !== 'string') throw new Error(msg('请指定会话标识', 'Please specify a conversation ID'));
34
+ const ticket = crypto.randomBytes(16).toString('hex');
35
+ const expiresAt = Date.now() + 60000;
36
+ subscribeTickets.set(ticket, { conversationId, expiresAt });
37
+ return { ticket, expiresAt };
38
+ }
39
+
40
+ function broadcast(conversationId, eventData) {
41
+ const payload = `event: change\ndata: ${JSON.stringify(eventData)}\n\n`;
42
+ for (const client of sseClients) {
43
+ if (!conversationId || client.conversationId === conversationId) {
44
+ try { client.res.write(payload); }
45
+ catch (_) { sseClients.delete(client); }
46
+ }
47
+ }
48
+ }
49
+
50
+ const server = http.createServer(async (req, res) => {
51
+ const send = (status, value) => {
52
+ res.writeHead(status, { 'Content-Type': 'application/json' });
53
+ res.end(JSON.stringify(value));
54
+ };
55
+ const origin = req.headers.origin;
56
+ if (!nativeOrigin(origin) && !allowedOrigins.has(origin)) {
57
+ send(403, { error: msg('请求来源未授权', 'Unauthorized request origin') });
58
+ return;
59
+ }
60
+ if (origin) {
61
+ res.setHeader('Access-Control-Allow-Origin', origin);
62
+ res.setHeader('Vary', 'Origin');
63
+ }
64
+ if (req.method === 'OPTIONS') {
65
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
66
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
67
+ send(204, {});
68
+ return;
69
+ }
70
+
71
+ let url;
72
+ try { url = new URL(req.url, 'http://127.0.0.1'); }
73
+ catch { send(400, { error: msg('请求路径无效', 'Invalid request URL') }); return; }
74
+
75
+ // 1. SSE 订阅通道:专属于单会话的短期只读票据验证
76
+ if (req.method === 'GET' && url.pathname === '/session/events') {
77
+ pruneTickets();
78
+ const ticket = url.searchParams.get('ticket');
79
+ const convId = url.searchParams.get('id');
80
+ const ticketInfo = ticket ? subscribeTickets.get(ticket) : null;
81
+ if (!ticketInfo || ticketInfo.expiresAt <= Date.now() || ticketInfo.conversationId !== convId) {
82
+ send(403, { error: msg('订阅票据无效、已过期或会话不匹配', 'Subscription ticket is invalid, expired, or does not match the session') });
83
+ return;
84
+ }
85
+ res.writeHead(200, {
86
+ 'Content-Type': 'text/event-stream',
87
+ 'Cache-Control': 'no-cache, no-transform',
88
+ 'Connection': 'keep-alive',
89
+ 'Access-Control-Allow-Origin': origin || '*',
90
+ });
91
+ res.flushHeaders?.();
92
+
93
+ const client = { res, conversationId: convId, since: Number(url.searchParams.get('since') || 0) };
94
+ sseClients.add(client);
95
+
96
+ // 建立连接后立即补发当前会话完整最新快照
97
+ try {
98
+ const snapshot = await handle('GET', '/session/snapshot', { conversationId: convId });
99
+ res.write(`event: snapshot\ndata: ${JSON.stringify(snapshot)}\n\n`);
100
+ } catch (e) {
101
+ res.write(`event: error\ndata: ${JSON.stringify({ error: e.message })}\n\n`);
102
+ }
103
+
104
+ req.on('close', () => { sseClients.delete(client); });
105
+ return;
106
+ }
107
+
108
+ // 2. 主服务需要 Master Token
109
+ if (req.headers.authorization !== `Bearer ${token}`) {
110
+ send(401, { error: msg('请求凭据无效', 'Invalid authorization token') });
111
+ return;
112
+ }
113
+
114
+ if (req.method === 'GET' && url.pathname === '/health') {
115
+ send(200, { service: 'agent-things', version: 1, stateId });
116
+ return;
117
+ }
118
+
119
+ // 3. 签发单会话短期订阅票据(仅供持 Master Token 的可信宿主使用)
120
+ if (req.method === 'POST' && url.pathname === '/session/ticket') {
121
+ let chunks = [], bytes = 0;
122
+ req.on('data', chunk => { bytes += chunk.length; if (bytes <= MAX_BODY_BYTES) chunks.push(chunk); });
123
+ req.on('end', () => {
124
+ try {
125
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
126
+ const result = issueTicket(body.conversationId);
127
+ send(200, { ok: true, ...result });
128
+ } catch (e) {
129
+ send(400, { error: e.message });
130
+ }
131
+ });
132
+ return;
133
+ }
134
+
135
+ // 4. 校验工件真实性与内容摘要(仅供持 Master Token 的可信宿主使用)
136
+ if (req.method === 'POST' && url.pathname === '/session/verify-artifact') {
137
+ let chunks = [], bytes = 0;
138
+ req.on('data', chunk => { bytes += chunk.length; if (bytes <= MAX_BODY_BYTES) chunks.push(chunk); });
139
+ req.on('end', () => {
140
+ try {
141
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
142
+ const { conversationId, digest, content: reqContent, brainDir: reqBrain } = body;
143
+ if (!conversationId || typeof conversationId !== 'string' || (!digest && typeof reqContent !== 'string')) {
144
+ send(400, { error: msg('参数无效', 'Invalid arguments'), valid: false });
145
+ return;
146
+ }
147
+ const targetBrain = (reqBrain && fs.existsSync(reqBrain)) ? path.resolve(reqBrain) : defaultBrain;
148
+ const artifactPath = path.join(targetBrain, conversationId, 'things-card.html');
149
+ if (!fs.existsSync(artifactPath)) {
150
+ send(404, { error: msg('会话工件不存在', 'Session artifact not found'), artifactPath, valid: false });
151
+ return;
152
+ }
153
+ const diskContent = fs.readFileSync(artifactPath, 'utf8');
154
+ const expectedDigest = crypto.createHash('sha256').update(diskContent).digest('hex');
155
+ let valid = false;
156
+ if (digest) {
157
+ valid = (digest === expectedDigest);
158
+ } else if (typeof reqContent === 'string') {
159
+ valid = (reqContent === diskContent);
160
+ }
161
+ send(200, { ok: true, valid, conversationId, expectedDigest });
162
+ } catch (e) {
163
+ send(400, { error: e.message, valid: false });
164
+ }
165
+ });
166
+ return;
167
+ }
168
+
169
+ // 5. 获取法定工件内容摘要(仅供持 Master Token 的可信宿主使用)
170
+ if (req.method === 'GET' && url.pathname === '/session/artifact-digest') {
171
+ const convId = url.searchParams.get('conversationId');
172
+ const reqBrain = url.searchParams.get('brainDir');
173
+ if (!convId) { send(400, { error: msg('请指定会话标识', 'Please specify a conversation ID') }); return; }
174
+ const targetBrain = (reqBrain && fs.existsSync(reqBrain)) ? path.resolve(reqBrain) : defaultBrain;
175
+ const artifactPath = path.join(targetBrain, convId, 'things-card.html');
176
+ if (!fs.existsSync(artifactPath)) {
177
+ send(404, { error: msg('会话工件不存在', 'Session artifact not found'), artifactPath });
178
+ return;
179
+ }
180
+ try {
181
+ const content = fs.readFileSync(artifactPath, 'utf8');
182
+ const digest = crypto.createHash('sha256').update(content).digest('hex');
183
+ send(200, { ok: true, digest, conversationId: convId });
184
+ } catch (e) {
185
+ send(500, { error: e.message });
186
+ }
187
+ return;
188
+ }
189
+
190
+ const controller = new AbortController();
191
+ const disconnected = () => { if (!res.writableEnded) controller.abort(progressError('REQUEST_CANCELLED', undefined, undefined, activeLang())); };
192
+ res.once('close', disconnected);
193
+ const dispatch = async body => {
194
+ try { const reply = await handle(req.method, url.pathname, body, { signal: controller.signal }); if (!res.destroyed) send(200, reply); }
195
+ catch (error) { const errorInfo = errorDetails(error, 'HOST_UNAVAILABLE', activeLang()); send(errorInfo.code === 'REVISION_CONFLICT' ? 409 : 400, { error: error.message, errorInfo }); }
196
+ finally { res.removeListener('close', disconnected); }
197
+ };
198
+
199
+ if (req.method === 'GET') { void dispatch(null); return; }
200
+ if (req.method !== 'POST') { send(405, { error: msg('请求方法无效', 'Method not allowed') }); return; }
201
+
202
+ let bytes = 0, chunks = [], oversized = false;
203
+ req.on('data', chunk => {
204
+ if (oversized) return;
205
+ bytes += chunk.length;
206
+ if (bytes > MAX_BODY_BYTES) { oversized = true; chunks = []; send(413, { error: msg('请求内容超过限制', 'Request payload exceeds limit') }); return; }
207
+ chunks.push(chunk);
208
+ });
209
+ req.on('end', () => {
210
+ if (oversized) return;
211
+ let body;
212
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
213
+ catch { send(400, { error: msg('JSON 格式无效', 'Invalid JSON body') }); return; }
214
+ void dispatch(body);
215
+ });
216
+ req.on('error', () => res.destroy());
217
+ });
218
+
219
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
220
+ const address = server.address();
221
+ const credentials = { service: 'agent-things', version: 1, stateId, port: address.port, token, pid: process.pid };
222
+ fs.mkdirSync(path.dirname(credentialFile), { recursive: true, mode: 0o700 });
223
+ try {
224
+ const temporary = `${credentialFile}.${process.pid}.tmp`;
225
+ fs.writeFileSync(temporary, JSON.stringify(credentials), { mode: 0o600 });
226
+ fs.renameSync(temporary, credentialFile);
227
+ } catch (error) { await new Promise(resolve => server.close(resolve)); throw error; }
228
+
229
+ return {
230
+ server, credentials, issueTicket, broadcast,
231
+ allowOrigin(origin) {
232
+ const parsed = new URL(origin);
233
+ if (!['http:', 'https:'].includes(parsed.protocol) || !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname)) throw new Error(msg('宿主来源无效', 'Invalid host origin'));
234
+ allowedOrigins.add(parsed.origin);
235
+ },
236
+ async close() {
237
+ for (const client of sseClients) {
238
+ try { client.res.end(); } catch (_) {}
239
+ }
240
+ sseClients.clear();
241
+ if (typeof server.closeAllConnections === 'function') {
242
+ server.closeAllConnections();
243
+ }
244
+ await new Promise(resolve => server.close(resolve));
245
+ if (fs.existsSync(credentialFile) && JSON.parse(fs.readFileSync(credentialFile)).token === token) fs.unlinkSync(credentialFile);
246
+ },
247
+ };
248
+ }
249
+
250
+ async function requestProgressHttp(stateFile, route, body, port, { signal, timeoutMs = 15000 } = {}) {
251
+ const lang = readConfiguredLang({ dataDir: stateFile ? path.dirname(stateFile) : undefined });
252
+ const msg = (zh, en) => (lang === 'en' ? en : zh);
253
+ const credentials = JSON.parse(fs.readFileSync(`${stateFile}.http.json`, 'utf8'));
254
+ if (credentials.service !== 'agent-things' || credentials.version !== 1 || port && credentials.port !== port) throw new Error(msg('端口已由其他服务占用', 'Port is occupied by another service'));
255
+ const expectedId = crypto.createHash('sha256').update(path.resolve(stateFile)).digest('hex');
256
+ if (credentials.stateId !== expectedId) throw new Error(msg('账本服务身份不匹配', 'Ledger service identity mismatch'));
257
+ const response = await fetch(`http://127.0.0.1:${credentials.port}${route}`, {
258
+ method: body === undefined ? 'GET' : 'POST', headers: { Authorization: `Bearer ${credentials.token}`, 'Content-Type': 'application/json' },
259
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
260
+ });
261
+ const value = await response.json();
262
+ if (!response.ok || value.error) throw Object.assign(new Error(value.error || (lang === 'en' ? `Local service returned HTTP ${response.status}` : `本地服务返回 ${response.status}`)), value.errorInfo || {});
263
+ if (route === '/health' && (value.service !== 'agent-things' || value.version !== 1 || value.stateId !== expectedId)) throw new Error(msg('本地服务身份不匹配', 'Local service identity mismatch'));
264
+ return value;
265
+ }
266
+
267
+ module.exports = { startProgressHttp, requestProgressHttp, MAX_BODY_BYTES };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+ const path = require('node:path');
3
+ const fs = require('node:fs');
4
+ const { CodexService, BINDING, attachmentStatus } = require('./harnesses/codex/codex-service.cjs');
5
+
6
+ module.exports = {
7
+ ManualStatusAgent: CodexService,
8
+ CodexService,
9
+ BINDING,
10
+ attachmentStatus,
11
+ renderer: () => fs.readFileSync(path.join(__dirname, 'session-status.js'), 'utf8'),
12
+ };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const os = require('node:os');
5
+ const launchd = require('./launchd.cjs');
6
+ const { DEFAULT_APP, resolveCodexBin, resolveNode } = require('./resolve.cjs');
7
+ const { installRuntime, prepareStartup, commitInstallation, recoverPendingTransaction } = require('./runtime-install.cjs');
8
+ const { withLifecycleLock } = require('./lifecycle-lock.cjs');
9
+
10
+ const LABEL = 'com.codexsessionstatus.agent';
11
+ const plistFile = () => path.join(os.homedir(), 'Library/LaunchAgents', `${LABEL}.plist`);
12
+ const logDirectory = () => path.join(os.homedir(), 'Library/Logs/CodexSessionStatus');
13
+
14
+ function startupStatus(directory) {
15
+ let state = null;
16
+ const file = path.join(directory, 'state.json');
17
+ if (fs.existsSync(file)) state = JSON.parse(fs.readFileSync(file, 'utf8'));
18
+ return { enabled: Boolean(launchd.printJob(LABEL)), event: state?.event ?? null,
19
+ updatedAt: state?.updatedAt ?? null, lastAttemptAt: state?.lastAttemptAt ?? null, logDirectory: logDirectory() };
20
+ }
21
+
22
+ async function installAutostartUnlocked(directory) {
23
+ if (process.platform !== 'darwin') throw new Error('自动挂载目前支持 macOS');
24
+ resolveCodexBin(DEFAULT_APP);
25
+ const node = resolveNode();
26
+ const source = path.resolve(__dirname, '..');
27
+ const runtime = path.join(directory, 'runtime');
28
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
29
+ prepareStartup(source, directory);
30
+ await launchd.bootout(LABEL);
31
+ try {
32
+ installRuntime(source, runtime, { enabledApps: ['codex'], dataDir: directory, homeDirectory: process.env.HOME || os.homedir() });
33
+ commitInstallation(directory, [runtime]);
34
+ } catch (err) {
35
+ try { recoverPendingTransaction(directory); } catch (_) {}
36
+ throw err;
37
+ }
38
+ fs.writeFileSync(path.join(directory, 'autostart.json'), JSON.stringify({ app: DEFAULT_APP, allowClientRestart: true }) + '\n', { mode: 0o600 });
39
+ fs.mkdirSync(logDirectory(), { recursive: true, mode: 0o700 });
40
+ launchd.writePlist({
41
+ Label: LABEL,
42
+ ProgramArguments: [node, path.join(runtime, 'bin/codex-session-status.cjs'), 'run', '--watch-startup', '--data-dir', directory],
43
+ RunAtLoad: true, KeepAlive: { SuccessfulExit: false }, ThrottleInterval: 10, ProcessType: 'Interactive',
44
+ EnvironmentVariables: { NODE_OPTIONS: '', NODE_PATH: '' },
45
+ StandardOutPath: path.join(logDirectory(), 'agent.log'), StandardErrorPath: path.join(logDirectory(), 'agent.err.log')
46
+ }, plistFile());
47
+ const started = Date.now();
48
+ launchd.bootstrap(plistFile());
49
+ for (let i = 0; i < 100; i++) {
50
+ const status = startupStatus(directory);
51
+ if (status.updatedAt >= started && ['watching', 'observing'].includes(status.event)) return status;
52
+ await new Promise(resolve => setTimeout(resolve, 150));
53
+ }
54
+ throw new Error(`自动挂载未就绪,请查看 ${logDirectory()}/agent.err.log`);
55
+ }
56
+
57
+ const installAutostart = directory => withLifecycleLock(directory, () => installAutostartUnlocked(directory));
58
+
59
+ async function disableAutostartUnlocked() {
60
+ await launchd.bootout(LABEL);
61
+ if (fs.existsSync(plistFile())) fs.unlinkSync(plistFile());
62
+ }
63
+
64
+ const disableAutostart = (directory = path.join(os.homedir(), 'Library/Application Support/CodexSessionStatus')) => withLifecycleLock(directory, disableAutostartUnlocked);
65
+
66
+ module.exports = { installAutostart, disableAutostart, startupStatus, installRuntime };