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.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +221 -2
  4. package/README.zh-CN.md +222 -0
  5. package/bin/agent-things.cjs +8 -0
  6. package/bin/antigravity-session-status.cjs +96 -0
  7. package/bin/claude-session-status.cjs +55 -0
  8. package/bin/codex-session-status.cjs +287 -0
  9. package/mods/agent-things-ui/.claude-plugin/plugin.json +12 -0
  10. package/mods/agent-things-ui/SKILL.md +10 -0
  11. package/mods/agent-things-ui/hooks/controls.js +112 -0
  12. package/mods/agent-things-ui/hooks/foundation.js +431 -0
  13. package/mods/agent-things-ui/hooks/hooks.json +1 -0
  14. package/mods/agent-things-ui/hooks/presentation.js +223 -0
  15. package/mods/agent-things-ui/hooks/progress.js +1 -0
  16. package/mods/agent-things-ui/hooks/register.js +382 -0
  17. package/native/bin/bridge +0 -0
  18. package/native/bin/bridge.json +20 -0
  19. package/native/session-status-bridge.swift +280 -0
  20. package/outputs/antigravity-session-status.js +2476 -0
  21. package/outputs/codex-session-status.js +1761 -0
  22. package/package.json +75 -4
  23. package/scripts/build-antigravity-bundle.cjs +35 -0
  24. package/scripts/build-codex-bundle.cjs +31 -0
  25. package/scripts/build-native-bridge.cjs +55 -0
  26. package/scripts/build-shared-ui.cjs +16 -0
  27. package/scripts/setup-antigravity-service.cjs +71 -0
  28. package/scripts/setup-claude-service.cjs +21 -0
  29. package/skills/agent-things/SKILL.en.md +95 -0
  30. package/skills/agent-things/SKILL.md +99 -0
  31. package/skills/codex/things/SKILL.en.md +10 -0
  32. package/skills/codex/things/SKILL.md +10 -0
  33. package/skills/things/SKILL.en.md +10 -0
  34. package/skills/things/SKILL.md +10 -0
  35. package/skills/things/checklist.en.md +91 -0
  36. package/skills/things/checklist.md +95 -0
  37. package/src/analysis-app-server.cjs +74 -0
  38. package/src/analysis-assets/output.en.schema.json +93 -0
  39. package/src/analysis-assets/output.schema.json +93 -0
  40. package/src/analysis-assets/prompt.en.txt +17 -0
  41. package/src/analysis-assets/prompt.zh-CN.txt +18 -0
  42. package/src/analysis-budget.cjs +105 -0
  43. package/src/analysis-git.cjs +38 -0
  44. package/src/analysis-history.cjs +150 -0
  45. package/src/analysis-ledger.cjs +82 -0
  46. package/src/analysis-log.cjs +62 -0
  47. package/src/analysis-runner.cjs +203 -0
  48. package/src/analysis-service.cjs +197 -0
  49. package/src/analysis-source.cjs +72 -0
  50. package/src/antigravity-card.cjs +2063 -0
  51. package/src/antigravity-hook.cjs +138 -0
  52. package/src/antigravity-mcp-config.cjs +36 -0
  53. package/src/app-server.cjs +96 -0
  54. package/src/cdp.cjs +115 -0
  55. package/src/claude-inline-install.cjs +38 -0
  56. package/src/claude-mcp-config.cjs +29 -0
  57. package/src/cli/arguments.cjs +30 -0
  58. package/src/cli/environment-probe.cjs +130 -0
  59. package/src/cli/integration-state.cjs +15 -0
  60. package/src/cli/interactive-cli.cjs +236 -0
  61. package/src/cli/prompt-tui.cjs +420 -0
  62. package/src/cli/setup-orchestrator.cjs +449 -0
  63. package/src/codex-mcp-config.cjs +67 -0
  64. package/src/harnesses/antigravity/analysis-profile.cjs +41 -0
  65. package/src/harnesses/antigravity/antigravity-git.cjs +89 -0
  66. package/src/harnesses/antigravity/antigravity-harness.js +1477 -0
  67. package/src/harnesses/antigravity/antigravity-injector.cjs +104 -0
  68. package/src/harnesses/antigravity/antigravity-migration.cjs +235 -0
  69. package/src/harnesses/antigravity/antigravity-service.cjs +357 -0
  70. package/src/harnesses/antigravity/antigravity-title.cjs +155 -0
  71. package/src/harnesses/antigravity/gemini-runner.cjs +304 -0
  72. package/src/harnesses/antigravity/transcript-cleaner.cjs +129 -0
  73. package/src/harnesses/antigravity/transcript-source.cjs +100 -0
  74. package/src/harnesses/claude/claude-harness.js +93 -0
  75. package/src/harnesses/claude/claude-host-helper.cjs +176 -0
  76. package/src/harnesses/claude/claude-injector.cjs +95 -0
  77. package/src/harnesses/claude/claude-local-source.cjs +106 -0
  78. package/src/harnesses/claude/claude-navigation.cjs +99 -0
  79. package/src/harnesses/claude/claude-runner.cjs +74 -0
  80. package/src/harnesses/claude/claude-service.cjs +313 -0
  81. package/src/harnesses/claude/claude-source.cjs +70 -0
  82. package/src/harnesses/codex/codex-analysis.cjs +10 -0
  83. package/src/harnesses/codex/codex-card-bridge.js +123 -0
  84. package/src/harnesses/codex/codex-card-events.cjs +76 -0
  85. package/src/harnesses/codex/codex-card.cjs +169 -0
  86. package/src/harnesses/codex/codex-git.cjs +24 -0
  87. package/src/harnesses/codex/codex-harness.js +229 -0
  88. package/src/harnesses/codex/codex-local-card.js +97 -0
  89. package/src/harnesses/codex/codex-progress-context.cjs +84 -0
  90. package/src/harnesses/codex/codex-service.cjs +502 -0
  91. package/src/i18n.cjs +174 -0
  92. package/src/launchd.cjs +105 -0
  93. package/src/lifecycle-lock.cjs +13 -0
  94. package/src/local-progress-http.cjs +267 -0
  95. package/src/manual-status-agent.cjs +12 -0
  96. package/src/manual-status-startup.cjs +66 -0
  97. package/src/manual-status-store.cjs +466 -0
  98. package/src/mcp-stdio.cjs +67 -0
  99. package/src/model-router.cjs +63 -0
  100. package/src/native-bridge.cjs +17 -0
  101. package/src/npm-updates.cjs +228 -0
  102. package/src/plugins/things/assets/logo.svg +13 -0
  103. package/src/plugins/things/plugin.json +6 -0
  104. package/src/plugins/things/sidecars/things_board/app.js +447 -0
  105. package/src/plugins/things/sidecars/things_board/index.html +2141 -0
  106. package/src/plugins/things/sidecars/things_board/main.mjs +652 -0
  107. package/src/plugins/things/sidecars/things_board/package.json +6 -0
  108. package/src/plugins/things/sidecars/things_board/sidecar.json +21 -0
  109. package/src/plugins/things/sidecars/things_board/styles.css +560 -0
  110. package/src/plugins/things/sidecars/things_board/ui-i18n.mjs +434 -0
  111. package/src/progress-error.cjs +54 -0
  112. package/src/progress-tools.cjs +145 -0
  113. package/src/project-path.cjs +15 -0
  114. package/src/renderer-resource.cjs +17 -0
  115. package/src/request-budget.cjs +24 -0
  116. package/src/resolve.cjs +51 -0
  117. package/src/runtime-install.cjs +635 -0
  118. package/src/session-status-filter.cjs +136 -0
  119. package/src/session-status.js +992 -0
  120. package/src/session-view.cjs +34 -0
  121. package/src/startup/controller.cjs +354 -0
  122. package/src/startup/watch.cjs +126 -0
  123. package/src/state-file-lock.cjs +31 -0
  124. package/src/task-provenance.cjs +42 -0
  125. package/src/ui-foundation.cjs +435 -0
@@ -0,0 +1,502 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { createHash } = require('node:crypto');
5
+ const { readRendererResource } = require('../../renderer-resource.cjs');
6
+ const { createAnalysisLog, diagnosticFields } = require('../../analysis-log.cjs');
7
+ const { CdpSession, listTargets, isMainWindow, CDP_PORT } = require('../../cdp.cjs');
8
+ const npmUpdates = require('../../npm-updates.cjs');
9
+ const { requireGitRemote } = require('../../analysis-git.cjs');
10
+ const { startProgressHttp } = require('../../local-progress-http.cjs');
11
+ const { callProgressTool } = require('../../progress-tools.cjs');
12
+ const { createCodexProgressContext } = require('./codex-progress-context.cjs');
13
+
14
+ const { sessionView, PROTOCOL_VERSION } = require('../../session-view.cjs');
15
+ const { progressError, errorDetails } = require('../../progress-error.cjs');
16
+ const { readConfiguredLang, getUi } = require('../../i18n.cjs');
17
+
18
+ const BINDING = '__codexSessionStatusSend';
19
+ const HARNESS_FILE = path.join(__dirname, 'codex-harness.js');
20
+ const RENDERER_FILE = path.join(__dirname, '..', '..', 'session-status.js');
21
+
22
+ class CodexService {
23
+ constructor({
24
+ store,
25
+ port = CDP_PORT,
26
+ onError = console.error,
27
+ rendererFile = RENDERER_FILE,
28
+ harnessFile = HARNESS_FILE,
29
+ logFile = path.join(path.dirname(store.file), 'analysis.jsonl'),
30
+ updates = npmUpdates,
31
+ }) {
32
+ this.store = store;
33
+ this.port = port;
34
+ this.onError = onError;
35
+ this.rendererFile = rendererFile;
36
+ this.harnessFile = harnessFile;
37
+ this.sessions = new Map();
38
+ this.stopped = false;
39
+ this.scanning = false;
40
+ this.analysisService = null;
41
+ this.logFile = logFile;
42
+ this.log = createAnalysisLog(logFile);
43
+ this.updates = updates;
44
+ this.progressContext = createCodexProgressContext({ store });
45
+ this.control = null;
46
+ this.uiReads = new Map();
47
+ this.stateWatcher = null;
48
+ this.stateWatchTimer = null;
49
+ this.snapshotLang = null;
50
+ this.watchStateFile();
51
+ }
52
+
53
+ currentLang() {
54
+ if (typeof this.store?.lang === 'function') return this.store.lang();
55
+ return readConfiguredLang({ dataDir: this.store?.file ? path.dirname(this.store.file) : undefined });
56
+ }
57
+
58
+ watchStateFile() {
59
+ if (this.stateWatcher || !this.store?.file) return;
60
+ const dir = path.dirname(this.store.file);
61
+ const basename = path.basename(this.store.file);
62
+ try {
63
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
64
+ this.stateWatcher = fs.watch(dir, (eventType, filename) => {
65
+ if (!filename || filename === basename || filename.startsWith(basename) || filename === 'config.json') {
66
+ if (this.stateWatchTimer) clearTimeout(this.stateWatchTimer);
67
+ this.stateWatchTimer = setTimeout(async () => {
68
+ if (this.stopped) return;
69
+ const modified = this.store.reloadIfModified();
70
+ const langChanged = this.currentLang() !== this.snapshotLang;
71
+ if (modified || langChanged) {
72
+ await this.broadcast().catch(() => {});
73
+ }
74
+ }, 60);
75
+ }
76
+ });
77
+ } catch { /* 忽略监听环境异常,依赖常规扫描轮询保底 */ }
78
+ }
79
+
80
+ evaluate(session, expression, timeoutMs = 5000) {
81
+ return session.request('Runtime.evaluate', {
82
+ expression,
83
+ contextId: session.contextId,
84
+ returnByValue: true,
85
+ awaitPromise: true,
86
+ }, timeoutMs);
87
+ }
88
+
89
+ resource() {
90
+ return readRendererResource({ harnessFile: this.harnessFile, rendererFile: this.rendererFile, lang: this.currentLang() });
91
+ }
92
+
93
+ snapshot() {
94
+ this.store.reloadIfModified();
95
+ const lang = this.currentLang();
96
+ if (this.snapshotData === this.store.data && this.snapshotLang === lang) return this.snapshotCache;
97
+ const snapshot = this.store.snapshot();
98
+ const data = this.store.data;
99
+ const timelines = new Map();
100
+ for (const event of data.timeline || []) {
101
+ if (!timelines.has(event.key)) timelines.set(event.key, []);
102
+ timelines.get(event.key).push(event);
103
+ }
104
+ const keys = new Set([...Object.keys(snapshot.records), ...Object.keys(data.analysis || {}), ...timelines.keys()]);
105
+ const keyVersions = Object.fromEntries([...keys].map(key => [
106
+ key, createHash('sha256').update(JSON.stringify([snapshot.records[key], data.analysis?.[key], timelines.get(key)])).digest('hex'),
107
+ ]));
108
+ this.snapshotData = data;
109
+ this.snapshotLang = lang;
110
+ return this.snapshotCache = { ...snapshot, lang, keyVersions };
111
+ }
112
+
113
+ async updateRenderer(session, resource = this.resource()) {
114
+ if (session.failedVersion === resource.version) return 'failed';
115
+ const previous = session.lastRenderer;
116
+ const snapshot = this.snapshot();
117
+ const { result } = await this.evaluate(session, `(() => {
118
+ const old = window.__codexSessionStatus;
119
+ if (old?.status()?.version === ${JSON.stringify(resource.version)}) {
120
+ const synced = old.status().revision !== ${snapshot.revision};
121
+ if (synced) old.receive(${JSON.stringify(snapshot)});
122
+ return { state: 'current', synced };
123
+ }
124
+ if (old && !old.exportForReload && old.status()?.panelOpen) return { state: 'deferred' };
125
+ const saved = old?.exportForReload?.() ?? window.__codexSessionStatusReloadDraft;
126
+ if (saved?.busy) return { state: 'deferred' };
127
+ let load;
128
+ try { load = new Function(${JSON.stringify(resource.source)} + '\\nreturn installCodexSessionStatus;'); }
129
+ catch (error) { return { state: 'failed', permanent: true, error: String(error) }; }
130
+
131
+ const oldVersion = old?.status()?.version;
132
+ if (saved) window.__codexSessionStatusReloadDraft = saved;
133
+ old?.destroy();
134
+ try {
135
+ load()(${JSON.stringify(resource.version)}, saved);
136
+ window.__codexSessionStatus.receive(${JSON.stringify(snapshot)});
137
+ delete window.__codexSessionStatusReloadDraft;
138
+ return { state: 'updated' };
139
+ } catch (error) {
140
+ try {
141
+ window.__codexSessionStatus?.destroy();
142
+ const rollback = ${previous ? `new Function(${JSON.stringify(previous.source)} + '\\nreturn installCodexSessionStatus;')()` : 'window.installCodexSessionStatus'};
143
+ if (rollback) {
144
+ rollback(oldVersion, saved);
145
+ window.__codexSessionStatus.receive(${JSON.stringify(snapshot)});
146
+ delete window.__codexSessionStatusReloadDraft;
147
+ }
148
+ return { state: 'failed', error: String(error) };
149
+ } catch (rollbackError) {
150
+ const rollbackPrefix = this.currentLang() === 'en' ? 'rollback failed: ' : '恢复失败:';
151
+ return { state: 'failed', error: String(error) + '; ' + rollbackPrefix + String(rollbackError) };
152
+ }
153
+ }
154
+ })()`);
155
+ const outcome = result.value;
156
+ if (outcome.synced || outcome.state === 'updated') {
157
+ this.log('ui.snapshot_sync', { revision: snapshot.revision, resourceVersion: resource.version });
158
+ }
159
+ if (outcome.state === 'failed') {
160
+ session.failedVersion = outcome.permanent ? resource.version : null;
161
+ const errMsg = this.currentLang() === 'en'
162
+ ? `Renderer ${resource.version} update failed: ${outcome.error}`
163
+ : `渲染资源 ${resource.version} 更新失败:${outcome.error}`;
164
+ this.onError(new Error(errMsg));
165
+ } else if (outcome.state === 'updated' || outcome.state === 'current') {
166
+ session.lastRenderer = resource;
167
+ session.failedVersion = null;
168
+ }
169
+ return outcome.state;
170
+ }
171
+
172
+ async attach(target) {
173
+ const session = new CdpSession(target, this.port);
174
+ try {
175
+ await session.connect();
176
+ const { frameTree } = await session.request('Page.getFrameTree');
177
+ const { executionContextId } = await session.request('Page.createIsolatedWorld', {
178
+ frameId: frameTree.frame.id,
179
+ worldName: 'agent-things-codex',
180
+ });
181
+ session.contextId = executionContextId;
182
+ session.onBinding = params => {
183
+ if (params.name === BINDING && params.executionContextId === session.contextId) {
184
+ this.handleMessage(session, params.payload).catch(this.onError);
185
+ }
186
+ };
187
+ await session.request('Runtime.addBinding', { name: BINDING, executionContextId });
188
+ await this.updateRenderer(session);
189
+ return session;
190
+ } catch (error) {
191
+ session.close();
192
+ throw error;
193
+ }
194
+ }
195
+
196
+ async handleMessage(session, payload) {
197
+ let message;
198
+ try { message = JSON.parse(payload); } catch { return; }
199
+ if (typeof message.requestId !== 'string') return;
200
+ let identity;
201
+ try { identity = JSON.parse(message.key); } catch { identity = []; }
202
+ const context = {
203
+ requestId: message.requestId,
204
+ requestType: message.type,
205
+ hostId: identity?.[0],
206
+ threadId: typeof identity?.[1] === 'string' ? identity[1].replace(/^local:/, '') : undefined,
207
+ };
208
+ if (message.type === 'panel-event') {
209
+ if (this.store.validKey(message.key) && ['open', 'close', 'dispose'].includes(message.action)) {
210
+ this.log(`panel.${message.action}`, context);
211
+ }
212
+ return;
213
+ }
214
+ if (message.type === 'cancel-request') {
215
+ this.uiReads.get(session)?.get(message.cancelRequestId)?.abort(progressError('REQUEST_CANCELLED', undefined, undefined, this.currentLang()));
216
+ return;
217
+ }
218
+ this.log('ui.request', context);
219
+ const controller = new AbortController();
220
+ if (!this.uiReads.has(session)) this.uiReads.set(session, new Map());
221
+ const reads = this.uiReads.get(session);
222
+ if (['project-git', 'analysis-state', 'app-update-info'].includes(message.type)) reads.set(message.requestId, controller);
223
+ try {
224
+ const reply = await this.request(message, session, { signal: controller.signal });
225
+ await this.evaluate(session, `window.__codexSessionStatus.reply(${JSON.stringify(reply)})`);
226
+ this.log('ui.reply', { ...context, ok: !reply.error, ...(reply.error ? diagnosticFields(reply.error) : {}) });
227
+ } finally { reads.delete(message.requestId); if (!reads.size) this.uiReads.delete(session); }
228
+ }
229
+
230
+ async startControl() {
231
+ if (this.control) return;
232
+ this.control = await startProgressHttp({ port: 0, stateFile: this.store.file, handle: async (method, route, body, options) => {
233
+ const lang = this.currentLang();
234
+ if (this.stopped) throw progressError('SERVICE_STOPPING', undefined, undefined, lang);
235
+ if (body?.protocolVersion != null && body.protocolVersion !== PROTOCOL_VERSION) throw progressError('PROTOCOL_MISMATCH', undefined, undefined, lang);
236
+ if (method === 'GET' && route === '/snapshot') return { snapshot: this.snapshot() };
237
+ if (method === 'GET' && route === '/session/snapshot') {
238
+ const cleanId = (body?.conversationId || '').replace(/^local:/, '');
239
+ const key = this.store.resolveKey(cleanId);
240
+ return {
241
+ session: sessionView(this.store, key, { capabilities: { locate: this.sessions.size > 0 }, lang }),
242
+ snapshotRevision: this.snapshot()?.revision,
243
+ };
244
+ }
245
+ if (method === 'POST' && route === '/rpc') return this.request(body, null, options);
246
+ if (method === 'POST' && route === '/tools') {
247
+ const value = await callProgressTool(this.store, body.name, body.args, {
248
+ ...this.progressContext, projectGit: key => this.projectGit(key, options),
249
+ resolveSources: (key, tasks) => this.progressContext.resolveSources(key, tasks, options), onChange: () => { void this.broadcast().catch(this.onError); },
250
+ lang,
251
+ });
252
+ return { value };
253
+ }
254
+ throw new Error(lang === 'en' ? 'Unknown Codex background request' : '未知 Codex 后台请求');
255
+ } });
256
+ }
257
+
258
+ async request(message, session, options = {}) {
259
+ const lang = this.currentLang();
260
+ const { t } = getUi(lang);
261
+ let errorInfo = null, error = null, analysisState = null, projectGit = null, updateInfo = null, navigation = null;
262
+ try {
263
+ if (this.stopped) throw progressError('SERVICE_STOPPING', undefined, undefined, lang);
264
+ if (message.type === 'panel-event') {
265
+ if (this.store.validKey(message.key) && ['open', 'close', 'dispose'].includes(message.action)) {
266
+ this.log(`panel.${message.action}`, { requestId: message.requestId, action: message.action });
267
+ }
268
+ return { protocolVersion: PROTOCOL_VERSION, requestId: message.requestId, ok: true, error: null };
269
+ }
270
+ if (!this.store.validKey(message.key) && !message.type?.startsWith('app-update-')) throw progressError('INVALID_ARGUMENT', undefined, undefined, lang);
271
+ if (message.type === 'app-update-info') {
272
+ updateInfo = await this.updates.getUpdateInfo({ force: message.force === true });
273
+ } else if (message.type === 'app-update-start') {
274
+ await this.updates.startUpdate();
275
+ updateInfo = await this.updates.getUpdateInfo();
276
+ } else if (message.type === 'update') {
277
+ if (message.record?.state === 'pushed') requireGitRemote(await this.projectGit(message.key, options), lang);
278
+ this.store.update(message);
279
+ } else if (message.type === 'clear') {
280
+ this.store.update({ key: message.key, expectedRevision: message.expectedRevision, record: null });
281
+ } else if (message.type === 'project-git') {
282
+ projectGit = await this.projectGit(message.key, options);
283
+ } else if (message.type === 'analysis-state') {
284
+ if (!this.store.validKey(message.key)) throw progressError('INVALID_ARGUMENT', undefined, undefined, lang);
285
+ analysisState = this.store.analysisState(message.key);
286
+ } else if (message.type === 'locate-source') {
287
+ navigation = await this.navigateSource(message.key, message.source, session);
288
+ } else if (message.type === 'analyze') {
289
+ if (!this.analysisService) {
290
+ const { createCodexAnalysis } = require('./codex-analysis.cjs');
291
+ this.analysisService = createCodexAnalysis({
292
+ store: this.store,
293
+ logFile: this.logFile,
294
+ onChange: () => this.broadcast().catch(this.onError),
295
+ });
296
+ }
297
+ const { promise, runId, actionSequence } = this.analysisService.start(message.key, { requestId: message.requestId });
298
+ this.log('analysis.request', { requestId: message.requestId, runId, actionSequence });
299
+ promise.catch(this.onError);
300
+ analysisState = this.store.analysisState(message.key);
301
+ } else {
302
+ throw progressError('CAPABILITY_UNAVAILABLE', undefined, undefined, lang);
303
+ }
304
+ } catch (e) { errorInfo = errorDetails(e, undefined, lang); error = errorInfo.message; }
305
+ if (!error && ['update', 'analyze', 'clear'].includes(message.type)) void this.broadcast().catch(this.onError);
306
+ return { protocolVersion: PROTOCOL_VERSION, requestId: message.requestId, error, errorInfo,
307
+ ...(this.store.validKey(message.key) ? { session: sessionView(this.store, message.key, { projectGit, capabilities: { locate: this.sessions.size > 0 }, lang }) } : {}), snapshot: this.snapshot(), analysisState, projectGit, updateInfo, navigation };
308
+ }
309
+
310
+ async navigateSource(key, pointer, session) {
311
+ const lang = this.currentLang();
312
+ const { t } = getUi(lang);
313
+ const deadline = performance.now() + 10000;
314
+ const saved = Object.values(this.store.analysisState(key).analysis?.sources || {}).find(source =>
315
+ typeof pointer?.turnId === 'string' && typeof pointer?.itemId === 'string' && source.turnId === pointer.turnId && source.itemId === pointer.itemId);
316
+ if (!saved) throw progressError('SOURCE_NOT_FOUND', lang === 'en' ? 'This source does not belong to the current session task record' : '此来源不属于当前会话的任务记录', undefined, lang);
317
+ const source = { ...saved, threadId: JSON.parse(key)[1].replace(/^local:/, '') };
318
+ if (!session) {
319
+ for (const candidate of this.sessions.values()) {
320
+ const { result } = await this.evaluate(candidate, `Array.from(document.querySelectorAll('[data-app-action-sidebar-thread-selected="true"]')).some(row => row.getAttribute('data-app-action-sidebar-thread-id')?.replace(/^local:/, '') === ${JSON.stringify(source.threadId)})`, Math.max(1, deadline - performance.now()));
321
+ if (result.value) { session = candidate; break; }
322
+ }
323
+ session ||= this.sessions.values().next().value;
324
+ }
325
+ if (!session) {
326
+ throw progressError('HOST_UNAVAILABLE', lang === 'en' ? 'No Codex window available for locating; please open the thread first' : '当前没有可定位的 Codex 窗口,请先打开对应会话', undefined, lang);
327
+ }
328
+ const remaining = deadline - performance.now();
329
+ if (remaining <= 0) throw progressError('REQUEST_TIMEOUT', t('locateTimeout'), undefined, lang);
330
+ return this.locateSource(session, source, remaining);
331
+ }
332
+
333
+ async projectGit(key, options) {
334
+ const lang = this.currentLang();
335
+ if (!this.store.validKey(key)) throw progressError('INVALID_ARGUMENT', undefined, undefined, lang);
336
+ const [hostId] = JSON.parse(key);
337
+ if (hostId !== 'local') return { status: 'unknown', hasRemote: false };
338
+ try { return await this.progressContext.projectGit(key, options); }
339
+ catch (error) { if (options?.signal?.aborted) throw options.signal.reason; return { status: 'unknown', hasRemote: false }; }
340
+ }
341
+
342
+ async locateSource(session, source, timeoutMs = 10000) {
343
+ const lang = this.currentLang();
344
+ const { t } = getUi(lang);
345
+ const locatedLabel = t('locatedMessage');
346
+ const notFoundLabel = t('locateNotFound');
347
+ const missingTextMsg = lang === 'en' ? 'Source lacks searchable text' : '来源缺少可搜索的文本';
348
+ if (!source || typeof source.turnId !== 'string' || typeof source.itemId !== 'string' ||
349
+ typeof source.threadId !== 'string' || typeof source.locator !== 'string' || source.locator.length < 10) {
350
+ throw new Error(missingTextMsg);
351
+ }
352
+ const expression = `(async () => {
353
+ const source = ${JSON.stringify(source)};
354
+ const harness = window.__sessionStatusHarness;
355
+ if (harness?.locate) {
356
+ const dummyMsg = { textContent: '', status: '' };
357
+ await harness.locate({ entry: { threadId: 'local:' + source.threadId, row: Array.from(document.querySelectorAll('[data-app-action-sidebar-thread-row]')).find(row => row.getAttribute('data-app-action-sidebar-thread-id')?.replace(/^local:/, '') === source.threadId) || document.body }, source, analysisMessage: dummyMsg });
358
+ if (dummyMsg.status !== 'located' && dummyMsg.textContent !== ${JSON.stringify(locatedLabel)}) return { status: 'not_found', message: dummyMsg.textContent || ${JSON.stringify(notFoundLabel)} };
359
+ return { status: 'located', message: dummyMsg.textContent || ${JSON.stringify(locatedLabel)} };
360
+ }
361
+ const unitKey = CSS.escape(source.turnId + ':' + source.itemId);
362
+ const node = document.querySelector('[data-content-search-unit-key="' + unitKey + '"]') ||
363
+ document.querySelector('[data-turn-key="history-content:turn:' + CSS.escape(source.turnId) + '"]');
364
+ if (node) {
365
+ node.scrollIntoView({ block: 'center', behavior: 'smooth' });
366
+ const bubble = node.querySelector('[data-user-message-bubble]') || node;
367
+ bubble.style.outline = '2px solid #548eea';
368
+ setTimeout(() => { if (bubble.style.outline === '2px solid rgb(84, 142, 234)') bubble.style.outline = ''; }, 3000);
369
+ return { status: 'located', message: ${JSON.stringify(locatedLabel)} };
370
+ }
371
+ return { status: 'not_found', message: ${JSON.stringify(notFoundLabel)} };
372
+ })()`;
373
+ const { result } = await this.evaluate(session, expression, timeoutMs);
374
+ if (result.value?.status !== 'located') throw progressError('SOURCE_NOT_FOUND', result.value?.message || notFoundLabel, undefined, lang);
375
+ return result.value;
376
+ }
377
+
378
+ async broadcast() {
379
+ const expression = `window.__codexSessionStatus.receive(${JSON.stringify(this.snapshot())})`;
380
+ await Promise.all([...this.sessions].map(async ([id, session]) => {
381
+ try {
382
+ await this.evaluate(session, expression);
383
+ } catch {
384
+ session.close();
385
+ this.sessions.delete(id);
386
+ }
387
+ }));
388
+ if (this.control?.broadcast) {
389
+ const snap = this.snapshot();
390
+ const targetKeys = new Set(Object.keys(snap?.records || {}));
391
+ for (const recordKey of targetKeys) {
392
+ try {
393
+ const [, id] = JSON.parse(recordKey);
394
+ const cleanId = String(id).replace(/^local:/, '');
395
+ const key = this.store.resolveKey(cleanId);
396
+ this.control.broadcast(cleanId, {
397
+ type: 'session_update',
398
+ session: sessionView(this.store, key, { capabilities: { locate: this.sessions.size > 0 }, lang: this.currentLang() }),
399
+ snapshotRevision: snap?.revision,
400
+ });
401
+ } catch (_) {}
402
+ }
403
+ }
404
+ }
405
+
406
+ async scan() {
407
+ if (this.scanning || this.stopped) return;
408
+ this.scanning = true;
409
+ try {
410
+ const targets = (await listTargets(this.port)).filter(isMainWindow);
411
+ const live = new Set(targets.map(t => t.id));
412
+ for (const [id, session] of this.sessions) {
413
+ if (!live.has(id)) {
414
+ session.close();
415
+ this.sessions.delete(id);
416
+ }
417
+ }
418
+ for (const target of targets) {
419
+ if (this.stopped) break;
420
+ const existing = this.sessions.get(target.id);
421
+ if (existing) {
422
+ try {
423
+ await this.updateRenderer(existing);
424
+ continue;
425
+ } catch { /* Navigation can replace context */ }
426
+ existing.close();
427
+ this.sessions.delete(target.id);
428
+ }
429
+ try {
430
+ const session = await this.attach(target);
431
+ if (this.stopped) {
432
+ await this.evaluate(session, 'window.__codexSessionStatus?.destroy()').catch(() => {});
433
+ session.close();
434
+ } else {
435
+ this.sessions.set(target.id, session);
436
+ }
437
+ } catch (error) {
438
+ this.onError(error);
439
+ }
440
+ }
441
+ } finally {
442
+ this.scanning = false;
443
+ }
444
+ }
445
+
446
+ async stop() {
447
+ this.stopped = true;
448
+ for (const reads of this.uiReads.values()) for (const controller of reads.values()) controller.abort(progressError('SERVICE_STOPPING'));
449
+ this.uiReads.clear();
450
+ if (this.stateWatchTimer) clearTimeout(this.stateWatchTimer);
451
+ if (this.stateWatcher) {
452
+ try { this.stateWatcher.close(); } catch {}
453
+ this.stateWatcher = null;
454
+ }
455
+ this.log('agent.stop');
456
+ await this.analysisService?.stop();
457
+ await this.control?.close();
458
+ this.control = null;
459
+ await Promise.all([...this.sessions.values()].map(async session => {
460
+ await this.evaluate(session, 'window.__codexSessionStatus?.destroy()').catch(() => {});
461
+ session.close();
462
+ }));
463
+ this.sessions.clear();
464
+ }
465
+ }
466
+
467
+ async function attachmentStatus(port = CDP_PORT) {
468
+ let targets;
469
+ try {
470
+ targets = (await listTargets(port, 1000)).filter(isMainWindow);
471
+ } catch {
472
+ return { portOpen: false, windows: [], mountedConversations: 0 };
473
+ }
474
+ const windows = await Promise.all(targets.map(async target => {
475
+ const session = new CdpSession(target, port);
476
+ try {
477
+ await session.connect();
478
+ const { frameTree } = await session.request('Page.getFrameTree');
479
+ const { executionContextId } = await session.request('Page.createIsolatedWorld', {
480
+ frameId: frameTree.frame.id,
481
+ worldName: 'agent-things-codex',
482
+ });
483
+ const { result } = await session.request('Runtime.evaluate', {
484
+ expression: 'window.__codexSessionStatus?.status() ?? null',
485
+ contextId: executionContextId,
486
+ returnByValue: true,
487
+ });
488
+ return { id: target.id, ...(result.value || { mounted: 0, panelOpen: false }) };
489
+ } catch (error) {
490
+ return { id: target.id, mounted: 0, error: error.message };
491
+ } finally {
492
+ session.close();
493
+ }
494
+ }));
495
+ return {
496
+ portOpen: true,
497
+ windows,
498
+ mountedConversations: windows.reduce((sum, window) => sum + window.mounted, 0),
499
+ };
500
+ }
501
+
502
+ module.exports = { CodexService, BINDING, attachmentStatus };
package/src/i18n.cjs ADDED
@@ -0,0 +1,174 @@
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
+ const { createPresentation } = require('./ui-foundation.cjs');
7
+
8
+ const SUPPORTED_LANGS = ['zh', 'en'];
9
+ const configCache = new Map();
10
+
11
+ function normalizeLang(value) {
12
+ if (typeof value !== 'string') return null;
13
+ const trimmed = value.trim().toLowerCase();
14
+ if (!trimmed) return null;
15
+ if (trimmed === 'zh' || /^zh(?:[-_]|$)/.test(trimmed)) return 'zh';
16
+ if (trimmed === 'en' || /^en(?:[-_]|$)/.test(trimmed)) return 'en';
17
+ return null;
18
+ }
19
+
20
+ function localeToSupportedLang(locale) {
21
+ if (typeof locale !== 'string') return null;
22
+ const trimmed = locale.trim();
23
+ if (!trimmed || /^(?:c|posix)(?:\.|$)|^utf-?8$/i.test(trimmed)) return null;
24
+ if (/^zh(?:[-_.]|$)/i.test(trimmed)) return 'zh';
25
+ if (/^[a-z]{2,3}(?:[-_.@]|$)/i.test(trimmed)) return 'en';
26
+ return null;
27
+ }
28
+
29
+ function readMacOsDefault(key) {
30
+ if (process.platform !== 'darwin') return null;
31
+ try {
32
+ return execFileSync('/usr/bin/defaults', ['read', '-g', key], {
33
+ encoding: 'utf8',
34
+ timeout: 500,
35
+ stdio: ['ignore', 'pipe', 'ignore'],
36
+ });
37
+ } catch { return null; }
38
+ }
39
+
40
+ // System UI language (System Settings → Language & Region → Preferred Languages).
41
+ function readAppleLanguage() {
42
+ const out = readMacOsDefault('AppleLanguages');
43
+ if (!out) return null;
44
+ const first = out.match(/"([^"]+)"/)?.[1] || out.split(/[\r\n,()]+/).map(s => s.trim()).find(Boolean);
45
+ return localeToSupportedLang(first);
46
+ }
47
+
48
+ // Region setting; Terminal derives LANG from it, so it says little about the UI language.
49
+ function readAppleLocale() {
50
+ const out = readMacOsDefault('AppleLocale');
51
+ return out ? localeToSupportedLang(out.trim()) : null;
52
+ }
53
+
54
+ function langFromEnv(env, keys) {
55
+ for (const key of keys) {
56
+ const raw = env?.[key];
57
+ if (!raw) continue;
58
+ for (const part of String(raw).split(':')) {
59
+ const mapped = localeToSupportedLang(part);
60
+ if (mapped) return mapped;
61
+ }
62
+ }
63
+ return null;
64
+ }
65
+
66
+ // Priority: explicit override, explicit LC_ALL / LC_MESSAGES, the macOS UI language, then
67
+ // LANG / LANGUAGE (Terminal sets LANG from the region, not the UI language), the region and Intl.
68
+ function detectSystemLang(env = process.env, { readDefaults = true, appleLanguage = readAppleLanguage, appleLocale = readAppleLocale } = {}) {
69
+ const override = normalizeLang(env?.AGENT_THINGS_LANG);
70
+ if (override) return override;
71
+
72
+ const explicit = langFromEnv(env, ['LC_ALL', 'LC_MESSAGES']);
73
+ if (explicit) return explicit;
74
+
75
+ if (readDefaults) {
76
+ const uiLang = appleLanguage();
77
+ if (uiLang) return uiLang;
78
+ }
79
+
80
+ const fromLang = langFromEnv(env, ['LANG', 'LANGUAGE']);
81
+ if (fromLang) return fromLang;
82
+
83
+ if (readDefaults) {
84
+ const regionLang = appleLocale();
85
+ if (regionLang) return regionLang;
86
+ }
87
+
88
+ try {
89
+ const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale;
90
+ const mapped = localeToSupportedLang(intlLocale);
91
+ if (mapped) return mapped;
92
+ } catch {}
93
+
94
+ return 'en';
95
+ }
96
+
97
+ function getDataDir(env = process.env) {
98
+ const home = env?.HOME || os.homedir();
99
+ return path.join(home, 'Library', 'Application Support', 'CodexSessionStatus');
100
+ }
101
+
102
+ function resolveConfigPath({ file, dataDir, homeDirectory, env = process.env } = {}) {
103
+ if (file) return file;
104
+ if (env?.SESSION_STATUS_CONFIG) return env.SESSION_STATUS_CONFIG;
105
+ if (dataDir) {
106
+ const base = path.basename(dataDir);
107
+ if (base === 'CodexSessionStatus') return path.join(dataDir, 'config.json');
108
+ const siblingConfig = path.join(dataDir, 'config.json');
109
+ if (fs.existsSync(siblingConfig)) return siblingConfig;
110
+ }
111
+ if (homeDirectory) {
112
+ return path.join(homeDirectory, 'Library', 'Application Support', 'CodexSessionStatus', 'config.json');
113
+ }
114
+ return path.join(getDataDir(env), 'config.json');
115
+ }
116
+
117
+ function readConfiguredLang(options = {}) {
118
+ const env = options.env || process.env;
119
+ const envLang = normalizeLang(env?.AGENT_THINGS_LANG);
120
+ if (envLang) return envLang;
121
+
122
+ const fallback = normalizeLang(options.fallback) || 'zh';
123
+ const configFile = resolveConfigPath(options);
124
+ try {
125
+ const stat = fs.statSync(configFile);
126
+ const cached = configCache.get(configFile);
127
+ if (cached && cached.mtimeMs === stat.mtimeMs) {
128
+ return cached.lang || fallback;
129
+ }
130
+ const parsed = JSON.parse(fs.readFileSync(configFile, 'utf8'));
131
+ const lang = normalizeLang(parsed?.lang);
132
+ configCache.set(configFile, { mtimeMs: stat.mtimeMs, lang });
133
+ return lang || fallback;
134
+ } catch {
135
+ configCache.delete(configFile);
136
+ return fallback;
137
+ }
138
+ }
139
+
140
+ function getUi(lang = readConfiguredLang()) {
141
+ return createPresentation(normalizeLang(lang) || 'zh');
142
+ }
143
+
144
+ function formatSessionMarkdownSummary({ lang = readConfiguredLang(), progressData = null, embedTag = '' } = {}) {
145
+ const ui = getUi(lang);
146
+ const s = ui.strings;
147
+ const isEmptySession = progressData == null;
148
+ const stateText = isEmptySession
149
+ ? s.unrecordedSummary
150
+ : (progressData?.state === 'completed' || progressData?.progress === 100
151
+ ? s.mdStateDone
152
+ : (progressData?.progress != null ? `${progressData.progress}%` : s.mdStateUnstarted));
153
+ const total = progressData?.totalTasks || 0;
154
+ const done = progressData?.completedTasks || 0;
155
+ const tasksText = total > 0 ? ui.t('totalsPattern', { done, total }) : s.mdTasksEmpty;
156
+ const noteText = progressData?.note
157
+ ? (ui.lang === 'zh' ? `\n- **${s.mdNotesLabel}**:${progressData.note}` : `\n- **${s.mdNotesLabel}**: ${progressData.note}`)
158
+ : '';
159
+ const summaryText = isEmptySession ? s.unrecordedSummary : (progressData?.summary || '');
160
+ const sep = ui.lang === 'zh' ? ':' : ': ';
161
+ const userMarkdown = `${embedTag}\n\n**${s.mdProgressHeading}${sep}${stateText}**\n- **${s.mdTasksOverview}**${sep}${tasksText}${noteText}\n- **${s.mdQuickActionsLabel}**${sep}${s.mdQuickActionsText}`;
162
+ return { stateText, tasksText, summaryText, userMarkdown };
163
+ }
164
+
165
+ module.exports = {
166
+ SUPPORTED_LANGS,
167
+ normalizeLang,
168
+ detectSystemLang,
169
+ getDataDir,
170
+ resolveConfigPath,
171
+ readConfiguredLang,
172
+ getUi,
173
+ formatSessionMarkdownSummary,
174
+ };