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,169 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { createHmac, randomBytes, timingSafeEqual } = require('node:crypto');
5
+ const { withStateFileLock } = require('../../state-file-lock.cjs');
6
+ const { requestProgressHttp } = require('../../local-progress-http.cjs');
7
+ const { createCardEvents } = require('./codex-card-events.cjs');
8
+ const { browserSource } = require('../../ui-foundation.cjs');
9
+
10
+ const { sessionView, PROTOCOL_VERSION } = require('../../session-view.cjs');
11
+ const { errorDetails } = require('../../progress-error.cjs');
12
+ const { readConfiguredLang, getUi } = require('../../i18n.cjs');
13
+
14
+ const uri = 'ui://agent-things/codex-progress';
15
+ function getCardTools(lang = readConfiguredLang()) {
16
+ const en = lang === 'en';
17
+ const id = {
18
+ type: 'string',
19
+ description: en ? 'Real CODEX_THREAD_ID of the current Codex chat' : 'Codex 当前聊天的真实 CODEX_THREAD_ID',
20
+ };
21
+ const properties = { conversation_id: id };
22
+ const cardProperties = { ...properties, card_token: { type: 'string', pattern: '^[a-f0-9]{64}$' } };
23
+ return [
24
+ { name: 'open_session_card',
25
+ description: en
26
+ ? 'Open the Agent Things session progress card inline in the current Codex conversation. Read only.'
27
+ : 'Open the Agent Things session progress card inline in the current Codex conversation. Read only. 在 Codex 信息流打开当前会话的进度卡片。',
28
+ inputSchema: { type: 'object', properties: { ...properties, title: { type: 'string', maxLength: 160 } }, additionalProperties: false },
29
+ annotations: { readOnlyHint: true }, _meta: { ui: { resourceUri: uri, visibility: ['model'] }, 'openai/ui': { preferredModelDisplayMode: 'inline' } } },
30
+ { name: 'read_session_card',
31
+ description: en
32
+ ? 'Read card status, Git info, version updates, or wait for session changes'
33
+ : '读取卡片状态、Git 信息、版本或等待会话变更',
34
+ inputSchema: { type: 'object', properties: { ...cardProperties, action: { enum: ['analysis-state', 'project-git', 'app-update-info', 'watch-state'] }, cursor: { type: 'string', pattern: '^[a-f0-9]{64}$' } }, required: ['conversation_id', 'card_token', 'action'], additionalProperties: false },
35
+ annotations: { readOnlyHint: true }, _meta: { ui: { visibility: ['app'] } } },
36
+ { name: 'change_session_card',
37
+ description: en
38
+ ? 'Save, clear, analyze, locate source, or upgrade based on card actions'
39
+ : '按卡片上的用户操作保存、清除、分析或升级',
40
+ inputSchema: { type: 'object', properties: { ...cardProperties, action: { enum: ['update', 'analyze', 'locate-source', 'app-update-start'] },
41
+ source: { type: 'object', properties: { turnId: { type: 'string' }, itemId: { type: 'string' } }, required: ['turnId', 'itemId'], additionalProperties: false },
42
+ expectedRevision: { type: 'integer', minimum: 0 }, record: { type: ['object', 'null'] } }, required: ['conversation_id', 'card_token', 'action'], additionalProperties: false },
43
+ _meta: { ui: { visibility: ['app'] } } },
44
+ ];
45
+ }
46
+ const tools = getCardTools();
47
+ const resource = {
48
+ descriptor: { uri, name: 'Agent Things · Progress', mimeType: 'text/html;profile=mcp-app' },
49
+ read() {
50
+ const lang = readConfiguredLang();
51
+ const { t } = getUi(lang);
52
+ const renderer = fs.readFileSync(path.join(__dirname, '../../session-status.js'), 'utf8');
53
+ const bridge = fs.readFileSync(path.join(__dirname, 'codex-card-bridge.js'), 'utf8');
54
+ const htmlLang = lang === 'en' ? 'en' : 'zh-CN';
55
+ return `<!doctype html><html lang="${htmlLang}"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><body style="margin:0"><main id="progress-card" aria-live="polite">${t('loadingTitle')}</main><script>window.__agentThingsVersion = ${JSON.stringify(require('../../../package.json').version)};window.__agentThingsLang = ${JSON.stringify(lang)};\n${browserSource}\n${renderer}\n${bridge}</script></body></html>`;
56
+ },
57
+ };
58
+
59
+ function cardAnalysisState(store, key) {
60
+ const { revision, analysis, timeline } = store.analysisState(key);
61
+ const tasks = analysis?.ledger?.tasks || [];
62
+ const sources = {};
63
+ for (const task of tasks) {
64
+ for (const ref of task.evidenceRefs || []) {
65
+ const source = analysis.sources?.[ref];
66
+ if (source?.turnId) sources[ref] = { turnId: source.turnId, itemId: source.itemId, locator: source.locator };
67
+ }
68
+ }
69
+ return { revision, analysis: analysis ? { ledger: { tasks }, sources } : null,
70
+ timeline: timeline.map(({ source, status, stage, requestedAt, progress, record, error }) =>
71
+ ({ source, status, stage, requestedAt, progress, record: record && { progress: record.progress }, error })),
72
+ };
73
+ }
74
+
75
+ function cardState(store, key, lang = readConfiguredLang({ dataDir: store.file ? path.dirname(store.file) : undefined })) {
76
+ const state = store.snapshot();
77
+ return { session: sessionView(store, key, { capabilities: { locate: true }, lang }), snapshot: { revision: state.revision, lang, records: Object.hasOwn(state.records, key) ? { [key]: state.records[key] } : {} },
78
+ analysisState: cardAnalysisState(store, key), lang };
79
+ }
80
+
81
+ function loadCardSecret(file, lang = readConfiguredLang()) {
82
+ const read = () => {
83
+ const secret = fs.readFileSync(file);
84
+ if (secret.length !== 32) throw new Error(lang === 'en' ? 'Invalid card authorization secret' : '卡片授权密钥无效');
85
+ return secret;
86
+ };
87
+ try { return read(); }
88
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
89
+ return withStateFileLock(file, () => {
90
+ if (fs.existsSync(file)) return read();
91
+ const secret = randomBytes(32);
92
+ const temporary = `${file}.${process.pid}.tmp`;
93
+ try {
94
+ fs.writeFileSync(temporary, secret, { mode: 0o600 });
95
+ fs.renameSync(temporary, file);
96
+ } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
97
+ return secret;
98
+ });
99
+ }
100
+
101
+ function createCodexCard({ store, request = (message, options) => requestProgressHttp(store.file, '/rpc', message, undefined, options) }) {
102
+ let secret;
103
+ const currentLang = () => (typeof store.lang === 'function' ? store.lang() : readConfiguredLang({ dataDir: store.file ? path.dirname(store.file) : undefined }));
104
+ const cardToken = conversationId => {
105
+ secret ||= loadCardSecret(`${store.file}.codex-card-key`, currentLang());
106
+ return createHmac('sha256', secret).update(conversationId).digest();
107
+ };
108
+ const read = key => cardState(store, key, currentLang());
109
+ const events = createCardEvents({ store, read });
110
+ async function call(name, args, meta, options = {}) {
111
+ const lang = currentLang();
112
+ const { t } = getUi(lang);
113
+ const en = lang === 'en';
114
+ const hostId = meta?.thread_id || meta?.threadId;
115
+ const conversationId = args.conversation_id || hostId;
116
+ if (typeof conversationId !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(conversationId)) {
117
+ throw new Error(en ? 'Please provide the real conversation ID of the current Codex chat' : '请提供当前 Codex 聊天的真实会话 ID');
118
+ }
119
+ if (hostId && hostId !== conversationId) {
120
+ throw new Error(en ? 'Card does not match the current Codex chat' : '卡片与当前 Codex 聊天不匹配');
121
+ }
122
+ const opening = name === 'open_session_card';
123
+ if (!opening && (typeof args.card_token !== 'string' || !/^[a-f0-9]{64}$/.test(args.card_token)
124
+ || !timingSafeEqual(Buffer.from(args.card_token, 'hex'), cardToken(conversationId)))) {
125
+ throw new Error(t('cardAuthUnavailable'));
126
+ }
127
+ const key = store.resolveKey(conversationId);
128
+ const payload = { lang };
129
+ let conflict, failure;
130
+ if (name === 'open_session_card') {
131
+ payload.conversationId = conversationId;
132
+ payload.key = key;
133
+ payload.title = typeof args.title === 'string' ? args.title.trim().slice(0, 160) || t('fallbackShortTitle') : t('fallbackShortTitle');
134
+ } else if (name === 'read_session_card' && args.action === 'watch-state') {
135
+ return { content: [], structuredContent: await events.wait(key, args.cursor, options.signal) };
136
+ } else if (name === 'read_session_card' && args.action === 'analysis-state') {
137
+ // Reading the local ledger does not acquire execution ownership.
138
+ } else {
139
+ const action = args.action;
140
+ if (name === 'read_session_card' && !['project-git', 'app-update-info'].includes(action)) {
141
+ throw new Error(en ? 'Unknown card read action' : '未知卡片读取操作');
142
+ }
143
+ if (name === 'change_session_card' && !['update', 'analyze', 'locate-source', 'app-update-start'].includes(action)) {
144
+ throw new Error(en ? 'Unknown card update action' : '未知卡片更新操作');
145
+ }
146
+ if (action === 'update' && (!Number.isInteger(args.expectedRevision) || args.expectedRevision < 0 || !Object.hasOwn(args, 'record'))) {
147
+ throw new Error(en ? 'Please save using the current record revision' : '请使用当前记录版本保存');
148
+ }
149
+ let result;
150
+ try { result = await request({ protocolVersion: PROTOCOL_VERSION, type: action, key, expectedRevision: args.expectedRevision, record: args.record,
151
+ ...(action === 'locate-source' ? { source: { turnId: args.source?.turnId, itemId: args.source?.itemId } } : {}) }, options); }
152
+ catch (error) { result = { error: error.message, errorInfo: errorDetails(error, undefined, lang) }; }
153
+ if (result.error) {
154
+ failure = result.errorInfo;
155
+ if (failure && failure.code !== 'REVISION_CONFLICT') throw Object.assign(new Error(result.error), failure);
156
+ if (action !== 'update' || (store.snapshot().records[key]?.revision ?? 0) === args.expectedRevision) throw new Error(result.error);
157
+ conflict = result.error;
158
+ }
159
+ for (const field of ['projectGit', 'updateInfo', 'navigation', 'session']) if (result[field]) payload[field] = result[field];
160
+ }
161
+ if (name === 'open_session_card' || ['analysis-state', 'update', 'analyze'].includes(args.action)) Object.assign(payload, read(key));
162
+ const replyText = conflict || (opening ? (en ? 'Opened session progress card.' : '已打开会话进度。') : (en ? 'Updated card.' : '已更新卡片。'));
163
+ return { ...(opening ? { _meta: { cardToken: cardToken(conversationId).toString('hex') } } : {}),
164
+ ...(conflict ? { isError: true } : {}), content: [{ type: 'text', text: replyText }], structuredContent: { ...payload, ...(failure ? { errorInfo: failure } : {}) } };
165
+ }
166
+ return { call, stopEvents: () => events.close() };
167
+ }
168
+
169
+ module.exports = { tools, getCardTools, resource, createCodexCard };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ const path = require('node:path');
3
+ const { inspectGit, readProjectGit } = require('../../analysis-git.cjs');
4
+
5
+ async function detectCodexGit(request, threadId, probe = inspectGit) {
6
+ try {
7
+ const result = await request('thread/read', { threadId, includeTurns: false });
8
+ const cwd = result?.thread?.cwd;
9
+ if (!cwd || typeof cwd !== 'string' || !path.isAbsolute(cwd)) {
10
+ return { status: 'checked', hasRepository: false, hasRemote: false, projectKnown: true, projectPath: null, checkedAt: Date.now() };
11
+ }
12
+ const gitInfo = await probe(cwd);
13
+ return { ...gitInfo, projectPath: cwd, projectKnown: true, checkedAt: Date.now() };
14
+ } catch (error) {
15
+ if (['REQUEST_TIMEOUT', 'REQUEST_CANCELLED', 'APP_SERVER_TIMEOUT'].includes(error.code) || error.name === 'AbortError') throw error;
16
+ return { status: 'unknown', hasRepository: false, hasRemote: false, checkedAt: Date.now() };
17
+ }
18
+ }
19
+
20
+ module.exports = {
21
+ detectCodexGit,
22
+ inspectGit,
23
+ readProjectGit,
24
+ };
@@ -0,0 +1,229 @@
1
+ 'use strict';
2
+ (function () {
3
+ const getUiText = (key, fallback) => {
4
+ const p = window.__agentThingsPresentation;
5
+ const lang = window.__agentThingsLang || p?.lang || 'zh';
6
+ const ui = p?.forLang ? p.forLang(lang) : null;
7
+ return ui?.strings?.[key] ?? p?.strings?.[key] ?? fallback;
8
+ };
9
+ const codexHarness = {
10
+ globalName: '__codexSessionStatus',
11
+ createLocalCards: options => createCodexLocalCards(options),
12
+ supportsRequestCancellation: true,
13
+ attributeFilter: [
14
+ 'data-app-action-sidebar-thread-selected',
15
+ 'data-app-action-sidebar-thread-id',
16
+ 'data-app-action-sidebar-thread-host-id',
17
+ 'data-app-action-sidebar-thread-title',
18
+ 'data-app-action-sidebar-thread-kind',
19
+ 'hidden',
20
+ 'aria-expanded',
21
+ 'style',
22
+ 'class',
23
+ 'data-theme'
24
+ ],
25
+
26
+ send(payload) {
27
+ if (typeof window.__codexSessionStatusSend === 'function') {
28
+ window.__codexSessionStatusSend(payload);
29
+ }
30
+ },
31
+
32
+ isRowSelected(row) {
33
+ if (!row) return false;
34
+ return row.getAttribute('data-app-action-sidebar-thread-selected') === 'true';
35
+ },
36
+
37
+ reconcile({ mounted, unmount, attachHost, paint, paintVisibility, openPanel, closePanel, isPanelBusy, isPanelEntry }) {
38
+ for (const entry of mounted.values()) {
39
+ if (!entry.row.isConnected ||
40
+ !entry.host.isConnected ||
41
+ entry.row.getAttribute('data-app-action-sidebar-thread-id') !== entry.threadId ||
42
+ entry.row.getAttribute('data-app-action-sidebar-thread-host-id') !== entry.rawHost) {
43
+ if (entry.slot?.classList.contains('status-slot-injected')) {
44
+ entry.slot.remove();
45
+ }
46
+ unmount(entry);
47
+ }
48
+ }
49
+
50
+ // 支持匹配全部侧边栏会话项(包括项目列表项与近期普通会话项)
51
+ const rows = document.querySelectorAll('[data-app-action-sidebar-thread-row]');
52
+ for (const row of rows) {
53
+ const kind = row.getAttribute('data-app-action-sidebar-thread-kind');
54
+ if (kind !== 'local' && kind !== 'remote') continue;
55
+ const threadId = row.getAttribute('data-app-action-sidebar-thread-id');
56
+ if (!threadId) continue;
57
+
58
+ const titleNode = row.querySelector('[data-thread-title]');
59
+ const title = row.getAttribute('data-app-action-sidebar-thread-title') || titleNode?.textContent?.trim() || getUiText('fallbackThreadTitle', '会话');
60
+ const existing = mounted.get(row);
61
+ if (existing) {
62
+ if (existing.title !== title) { existing.title = title; paint(existing); }
63
+ paintVisibility(existing);
64
+ continue;
65
+ }
66
+
67
+ // 识别或挂载插槽(仅在原生前置槽位完全空置时复用;若已被原生图标占用或不存在,则插入独立防溢出插槽)
68
+ const trigger = titleNode?.closest('[data-thread-title-trigger]') || row.querySelector('button') || row.firstElementChild;
69
+ let slot = trigger?.previousElementSibling;
70
+ let emptyWrapper = false;
71
+ let placeholder = null;
72
+
73
+ if (slot && slot.classList.contains('status-slot-injected')) {
74
+ // 已存在的独立注入槽
75
+ emptyWrapper = false;
76
+ } else if (slot && slot.classList.contains('w-4')) {
77
+ placeholder = slot.firstElementChild;
78
+ emptyWrapper = slot.childElementCount === 1 && placeholder?.tagName === 'DIV' &&
79
+ placeholder.childElementCount === 0 && !placeholder.textContent.trim();
80
+ }
81
+
82
+ // 若前置槽不存在、或者虽有 w-4 但里面有原生真实图标占用,则创建并插入独立插槽
83
+ if (!slot || (!slot.classList.contains('status-slot-injected') && !emptyWrapper)) {
84
+ slot = row.querySelector('.status-slot-injected');
85
+ if (!slot) {
86
+ slot = document.createElement('div');
87
+ slot.className = 'status-slot-injected w-4';
88
+ slot.style.cssText = 'width:24px;min-width:24px;display:flex;align-items:center;justify-content:center;flex-shrink:0';
89
+ if (trigger?.parentElement) {
90
+ trigger.parentElement.insertBefore(slot, trigger);
91
+ } else {
92
+ row.prepend(slot);
93
+ }
94
+ }
95
+ emptyWrapper = false;
96
+ placeholder = null;
97
+ }
98
+
99
+ const rawHost = row.getAttribute('data-app-action-sidebar-thread-host-id');
100
+ const key = JSON.stringify([rawHost || (kind === 'remote' ? 'cloud' : 'local'), threadId]);
101
+ const { host, button, original } = attachHost(slot, emptyWrapper, placeholder);
102
+ const entry = { row, key, threadId, rawHost, title, slot, host, button, original, hovered: row.matches(':hover') };
103
+
104
+ entry.onEnter = () => { entry.hovered = true; paintVisibility(entry); };
105
+ entry.onLeave = () => { entry.hovered = false; paintVisibility(entry); };
106
+ row.addEventListener('pointerenter', entry.onEnter);
107
+ row.addEventListener('pointerleave', entry.onLeave);
108
+
109
+ mounted.set(row, entry);
110
+ paint(entry);
111
+
112
+ button.onclick = event => {
113
+ event.stopPropagation();
114
+ if (isPanelBusy()) return;
115
+ if (isPanelEntry(entry)) closePanel(true);
116
+ else { closePanel(); openPanel(entry); }
117
+ };
118
+ }
119
+ },
120
+
121
+ async locate({ entry, source, analysisMessage }) {
122
+ if (!source?.turnId || !source?.itemId) {
123
+ analysisMessage.status = 'not_found';
124
+ analysisMessage.textContent = getUiText('locateNoSource', '此记录没有可定位的消息');
125
+ return;
126
+ }
127
+
128
+ const row = entry.row;
129
+ const targetThreadId = source.threadId ? (source.threadId.startsWith('local:') ? source.threadId : 'local:' + source.threadId) : entry.threadId;
130
+
131
+ // 1. 若当前会话未激活,先自动切换打开来源会话
132
+ if (row.getAttribute('data-app-action-sidebar-thread-selected') !== 'true') {
133
+ const trigger = row.querySelector('[data-thread-title-trigger]') || row.querySelector('button') || row;
134
+ trigger.click();
135
+ }
136
+
137
+ const deadline = Date.now() + 4500;
138
+ let isCurrent = false;
139
+ while (Date.now() < deadline) {
140
+ isCurrent = row.getAttribute('data-app-action-sidebar-thread-selected') === 'true' ||
141
+ [...document.querySelectorAll('[data-app-action-sidebar-thread-row]')].some(r =>
142
+ r.getAttribute('data-app-action-sidebar-thread-selected') === 'true' &&
143
+ r.getAttribute('data-app-action-sidebar-thread-id') === targetThreadId);
144
+ if (isCurrent) break;
145
+ await new Promise(resolve => setTimeout(resolve, 80));
146
+ }
147
+ if (!isCurrent) {
148
+ analysisMessage.status = 'not_found';
149
+ analysisMessage.textContent = getUiText('locateOpenFailed', '未能打开来源会话,请重试');
150
+ return;
151
+ }
152
+
153
+ const unitKey = `${source.turnId}:${source.itemId}`;
154
+ const escapedKey = CSS.escape(unitKey);
155
+ const escapedTurn = CSS.escape(source.turnId);
156
+
157
+ // 2. 策略 1:检查目标节点是否已在当前 DOM 中挂载
158
+ let targetNode = document.querySelector(`[data-content-search-unit-key="${escapedKey}"]`) ||
159
+ document.querySelector(`[data-turn-key="history-content:turn:${escapedTurn}"]`);
160
+
161
+ // 策略 2:若当前不在 DOM 中(虚拟列表卸载),利用 Codex 官方右侧常驻 Navigation Rail 原生直达
162
+ if (!targetNode) {
163
+ const navBtn = document.querySelector(`[data-thread-user-message-navigation-item-id="${escapedKey}"]`) ||
164
+ document.querySelector(`[data-thread-user-message-navigation-item-id^="${escapedTurn}:"]`) ||
165
+ document.querySelector(`[data-thread-user-message-navigation-item-id="${escapedTurn}"]`);
166
+ if (navBtn) {
167
+ analysisMessage.textContent = getUiText('locatingMessage', '正在定位消息…');
168
+ navBtn.click();
169
+ // 等待官方虚拟列表挂载目标回合
170
+ const deadline = Date.now() + 1500;
171
+ while (Date.now() < deadline) {
172
+ targetNode = document.querySelector(`[data-content-search-unit-key="${escapedKey}"]`) ||
173
+ document.querySelector(`[data-turn-key="history-content:turn:${escapedTurn}"]`);
174
+ if (targetNode) break;
175
+ await new Promise(r => setTimeout(r, 60));
176
+ }
177
+ }
178
+ }
179
+
180
+ // 策略 3:如果包含 locator 文本,尝试在已渲染的气泡或全文中进行文本比对兜底
181
+ if (!targetNode && source.locator) {
182
+ const bubbles = [...document.querySelectorAll('[data-content-search-unit-key], [data-user-message-bubble]')];
183
+ const quote = source.locator.replace(/\s+/g, ' ').trim();
184
+ const matches = [...new Set(bubbles.filter(b => (b.textContent || '').replace(/\s+/g, ' ').includes(quote)).map(b => b.closest('[data-content-search-unit-key]') || b))];
185
+ const match = matches.length === 1 ? matches[0] : null;
186
+ if (match) targetNode = match.closest('[data-content-search-unit-key]') || match.closest('[data-turn-key]') || match;
187
+ }
188
+
189
+ // 3. 执行平滑视口居中与呼吸发光动画
190
+ if (targetNode) {
191
+ targetNode.scrollIntoView({ block: 'center', behavior: 'smooth' });
192
+
193
+ const bubble = targetNode.querySelector('[data-user-message-bubble]') || targetNode;
194
+ try {
195
+ bubble.animate?.(
196
+ [
197
+ { backgroundColor: 'color-mix(in srgb, var(--color-text, #fff) 22%, transparent)' },
198
+ { backgroundColor: 'color-mix(in srgb, var(--color-text, #fff) 22%, transparent)', offset: 0.35 },
199
+ { backgroundColor: 'transparent' }
200
+ ],
201
+ { duration: 2000, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' }
202
+ );
203
+ } catch { /* ignore */ }
204
+
205
+ const previousOutline = bubble.style.outline;
206
+ const previousBoxShadow = bubble.style.boxShadow;
207
+ bubble.style.outline = '2px solid #548eea';
208
+ bubble.style.boxShadow = '0 0 14px rgba(84, 142, 234, 0.5)';
209
+ setTimeout(() => {
210
+ if (bubble.style.outline === '2px solid rgb(84, 142, 234)') {
211
+ bubble.style.outline = previousOutline;
212
+ bubble.style.boxShadow = previousBoxShadow;
213
+ }
214
+ }, 3000);
215
+
216
+ analysisMessage.status = 'located';
217
+ analysisMessage.textContent = getUiText('locatedMessage', '已定位来源');
218
+ } else {
219
+ analysisMessage.status = 'not_found';
220
+ analysisMessage.textContent = getUiText('locateNotFound', '未找到原始消息,可能已被清理');
221
+ }
222
+ }
223
+ };
224
+
225
+ window.__sessionStatusHarness = codexHarness;
226
+ if (typeof module !== 'undefined' && module.exports) {
227
+ module.exports = { codexHarness };
228
+ }
229
+ })();
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+ // Local conversation surface; its lifetime is owned by the Codex adapter.
3
+ function createCodexLocalCards({ mount, send, snapshot, restored }) {
4
+ const getFallbackTitle = () => {
5
+ const p = window.__agentThingsPresentation;
6
+ const lang = snapshot()?.lang || window.__agentThingsLang || p?.lang || 'zh';
7
+ const ui = p?.forLang ? p.forLang(lang) : null;
8
+ return ui?.strings?.fallbackShortTitle ?? p?.strings?.fallbackShortTitle ?? '会话进度';
9
+ };
10
+ const states = new Map(restored || []);
11
+ let active = null, stopped = false, reconciling = false;
12
+ const visible = node => node?.isConnected && node.getClientRects().length > 0;
13
+ function theme(row) {
14
+ for (let node = row; node; node = node.parentElement) {
15
+ const rgba = getComputedStyle(node).backgroundColor.match(/[\d.]+/g)?.map(Number);
16
+ if (rgba && (rgba[3] ?? 1) >= .95) return rgba[0] * .2126 + rgba[1] * .7152 + rgba[2] * .0722 < 150 ? 'dark' : 'light';
17
+ }
18
+ return matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
19
+ }
20
+ function current() {
21
+ const composers = [...document.querySelectorAll('[data-codex-composer-root]')].filter(visible);
22
+ const rows = [...document.querySelectorAll('[data-app-action-sidebar-thread-row][data-app-action-sidebar-thread-selected="true"]')];
23
+ const contents = [...document.querySelectorAll('[data-thread-find-target="conversation"]')].filter(visible);
24
+ if (composers.length !== 1 || rows.length !== 1 || contents.length !== 1) return null;
25
+ const row = rows[0], kind = row.getAttribute('data-app-action-sidebar-thread-kind');
26
+ if (!['local', 'remote'].includes(kind)) return null;
27
+ const id = row.getAttribute('data-app-action-sidebar-thread-id');
28
+ if (!id) return null;
29
+ return { composer: composers[0], content: contents[0], theme: theme(row), key: JSON.stringify([row.getAttribute('data-app-action-sidebar-thread-host-id') || (kind === 'remote' ? 'cloud' : 'local'), id]),
30
+ title: row.getAttribute('data-app-action-sidebar-thread-title') || getFallbackTitle() };
31
+ }
32
+ function retain() {
33
+ if (!active) return;
34
+ states.set(active.key, { title: active.title, saved: active.api.exportForReload({ allowPending: true }) });
35
+ active.api.destroy(); active.container.remove(); active = null;
36
+ }
37
+ function open(entry) {
38
+ if (active?.key === entry.key && active.container.isConnected) return active;
39
+ retain();
40
+ const container = document.createElement('section');
41
+ container.setAttribute('data-agent-things-local-card', entry.key);
42
+ container.setAttribute('aria-label', getFallbackTitle());
43
+ container.style.cssText = 'width:340px;max-width:100%;margin:12px 0;flex:none';
44
+ entry.content.append(container);
45
+ try {
46
+ const api = mount({ container, key: entry.key, title: entry.title, snapshot: snapshot(), send,
47
+ independent: true, theme: entry.theme }, states.get(entry.key)?.saved);
48
+ active = { ...entry, container, api };
49
+ states.set(entry.key, { title: entry.title, saved: null });
50
+ return active;
51
+ } catch (error) { container.remove(); throw error; }
52
+ }
53
+ function reconcile() {
54
+ if (stopped || reconciling) return;
55
+ reconciling = true;
56
+ try {
57
+ const entry = current();
58
+ if (!entry) { retain(); return; }
59
+ if (active && (active.key !== entry.key || !active.container.isConnected || active.composer !== entry.composer || active.content !== entry.content)) retain();
60
+ if (!active && states.has(entry.key)) open(entry);
61
+ active?.api.setTheme(entry.theme);
62
+ } finally { reconciling = false; }
63
+ }
64
+ function consume(event) {
65
+ const keyboard = event.type === 'keydown';
66
+ if (keyboard && (event.key !== 'Enter' || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || event.isComposing)) return;
67
+ if (!keyboard && !/^(发送|Send)(提示|消息| prompt| message)?$/i.test(event.target.closest?.('button')?.getAttribute('aria-label') || '')) return;
68
+ const entry = current();
69
+ if (!entry || !entry.composer.contains(event.target)) return;
70
+ const editor = entry.composer.querySelector('[contenteditable="true"]');
71
+ if (!editor || editor.textContent.trim() !== '/things') return;
72
+ // Rich mentions/attachments remain host submissions.
73
+ if (editor.querySelector('[contenteditable="false"]')) return;
74
+ try { open(entry); } catch { return; }
75
+ event.preventDefault(); event.stopImmediatePropagation();
76
+ editor.focus();
77
+ const selection = document.getSelection(), range = document.createRange();
78
+ range.selectNodeContents(editor); selection.removeAllRanges(); selection.addRange(range);
79
+ document.execCommand('delete');
80
+ active?.container.scrollIntoView({ block: 'start', behavior: 'instant' });
81
+ }
82
+ document.addEventListener('keydown', consume, true);
83
+ document.addEventListener('click', consume, true);
84
+ const observer = new MutationObserver(reconcile);
85
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true,
86
+ attributeFilter: ['data-app-action-sidebar-thread-selected', 'data-app-action-sidebar-thread-id', 'hidden', 'class', 'data-theme', 'data-color-mode'] });
87
+ reconcile();
88
+ return {
89
+ receive(value) { active?.api.receive(value); },
90
+ reply(value) { active?.api.reply(value); },
91
+ exportState() {
92
+ if (active) states.set(active.key, { title: active.title, saved: active.api.exportForReload({ allowPending: true }) });
93
+ return [...states];
94
+ },
95
+ destroy() { stopped = true; observer.disconnect(); document.removeEventListener('keydown', consume, true); document.removeEventListener('click', consume, true); retain(); },
96
+ };
97
+ }
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+ const { AnalysisAppServer } = require('../../analysis-app-server.cjs');
3
+ const { detectCodexGit } = require('./codex-git.cjs');
4
+ const { resolveTaskSources } = require('../../task-provenance.cjs');
5
+ const { inspectGit } = require('../../analysis-git.cjs');
6
+ const { requestBudget } = require('../../request-budget.cjs');
7
+ const { normalizeProjectPath } = require('../../project-path.cjs');
8
+
9
+ function createCodexProgressContext({ store, timeoutMs = 5000, makeServer = () => new AnalysisAppServer({ timeoutMs }), probe = inspectGit } = {}) {
10
+ const withServer = async (operation, { signal } = {}) => {
11
+ const budget = requestBudget({ timeoutMs, signal });
12
+ let server;
13
+ try {
14
+ server = makeServer();
15
+ return await budget.run(async () => {
16
+ server.timeoutMs = budget.remaining();
17
+ await server.initialize();
18
+ return operation((method, params) => {
19
+ server.timeoutMs = budget.remaining();
20
+ return server.request(method, params);
21
+ }, budget.signal);
22
+ });
23
+ } finally { budget.dispose(); await server?.close(); }
24
+ };
25
+ const gitRequests = new Map();
26
+ const checkProject = (cwd, signal) => {
27
+ signal?.throwIfAborted();
28
+ let job = gitRequests.get(cwd);
29
+ if (!job || job.controller.signal.aborted) {
30
+ job = { controller: new AbortController(), waiting: 0 };
31
+ const current = job;
32
+ job.promise = Promise.resolve().then(() => probe(cwd, { signal: current.controller.signal })).finally(() => {
33
+ if (gitRequests.get(cwd) === current) gitRequests.delete(cwd);
34
+ });
35
+ gitRequests.set(cwd, job);
36
+ }
37
+ job.waiting++;
38
+ return new Promise((resolve, reject) => {
39
+ let settled = false;
40
+ const finish = (callback, value) => {
41
+ if (settled) return;
42
+ settled = true; signal?.removeEventListener('abort', abort);
43
+ if (--job.waiting === 0) job.controller.abort();
44
+ callback(value);
45
+ };
46
+ const abort = () => finish(reject, signal.reason);
47
+ signal?.addEventListener('abort', abort, { once: true });
48
+ job.promise.then(value => finish(resolve, value), error => finish(reject, error));
49
+ if (signal?.aborted) abort();
50
+ });
51
+ };
52
+ return {
53
+ async projectGit(key, options = {}) {
54
+ const record = store?.snapshot().records[key];
55
+ if (record?.projectSource === 'host' && record.projectPath) return {
56
+ ...await checkProject(record.projectPath, options.signal), projectKnown: true, projectPath: record.projectPath, checkedAt: Date.now(),
57
+ };
58
+ const git = await withServer((request, signal) => detectCodexGit(request, JSON.parse(key)[1].replace(/^local:/, ''), cwd => checkProject(cwd, signal)), options);
59
+ if (git.projectKnown && store) store.enrichProjects({ [key]: git.projectPath });
60
+ return git;
61
+ },
62
+ resolveSources: (key, tasks, options = {}) => withServer(request => resolveTaskSources(request, key, tasks, options), options),
63
+ async resolveProjects(keys) {
64
+ const local = keys.filter(key => { const [host, id] = JSON.parse(key); return host === 'local' && /^[0-9a-f-]{36}$/i.test(id.replace(/^local:/, '')); });
65
+ if (!local.length) return {};
66
+ return withServer(async request => {
67
+ const projects = {};
68
+ for (const key of local) {
69
+ try {
70
+ const result = await request('thread/read', { threadId: JSON.parse(key)[1].replace(/^local:/, ''), includeTurns: false });
71
+ const cwd = result?.thread?.cwd;
72
+ projects[key] = cwd ? normalizeProjectPath(cwd) : null;
73
+ } catch (error) {
74
+ if (error.code === 'APP_SERVER_TIMEOUT') throw error;
75
+ // Deleted/imported chats can retain a mark after host metadata disappears.
76
+ }
77
+ }
78
+ return projects;
79
+ });
80
+ },
81
+ };
82
+ }
83
+
84
+ module.exports = { createCodexProgressContext };