shennian 0.2.6 → 0.2.7

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 (85) hide show
  1. package/dist/bin/shennian.d.ts +2 -0
  2. package/dist/bin/shennian.js +2 -0
  3. package/dist/src/agents/adapter.d.ts +35 -0
  4. package/dist/src/agents/adapter.js +19 -0
  5. package/dist/src/agents/claude.d.ts +25 -0
  6. package/dist/src/agents/claude.js +234 -0
  7. package/dist/src/agents/codex.d.ts +52 -0
  8. package/dist/src/agents/codex.js +829 -0
  9. package/dist/src/agents/command-spec.d.ts +36 -0
  10. package/dist/src/agents/command-spec.js +303 -0
  11. package/dist/src/agents/cursor.d.ts +22 -0
  12. package/dist/src/agents/cursor.js +248 -0
  13. package/dist/src/agents/custom.d.ts +30 -0
  14. package/dist/src/agents/custom.js +210 -0
  15. package/dist/src/agents/detect.d.ts +9 -0
  16. package/dist/src/agents/detect.js +46 -0
  17. package/dist/src/agents/gemini.d.ts +17 -0
  18. package/dist/src/agents/gemini.js +172 -0
  19. package/dist/src/agents/model-registry/cache.d.ts +4 -0
  20. package/dist/src/agents/model-registry/cache.js +37 -0
  21. package/dist/src/agents/model-registry/discovery.d.ts +4 -0
  22. package/dist/src/agents/model-registry/discovery.js +166 -0
  23. package/dist/src/agents/model-registry/parsers.d.ts +11 -0
  24. package/dist/src/agents/model-registry/parsers.js +349 -0
  25. package/dist/src/agents/model-registry/runner.d.ts +6 -0
  26. package/dist/src/agents/model-registry/runner.js +29 -0
  27. package/dist/src/agents/model-registry/service.d.ts +6 -0
  28. package/dist/src/agents/model-registry/service.js +71 -0
  29. package/dist/src/agents/model-registry/types.d.ts +30 -0
  30. package/dist/src/agents/model-registry/types.js +8 -0
  31. package/dist/src/agents/model-registry.d.ts +13 -0
  32. package/dist/src/agents/model-registry.js +15 -0
  33. package/dist/src/agents/openclaw.d.ts +20 -0
  34. package/dist/src/agents/openclaw.js +273 -0
  35. package/dist/src/agents/pi.d.ts +51 -0
  36. package/dist/src/agents/pi.js +793 -0
  37. package/dist/src/commands/agent.d.ts +2 -0
  38. package/dist/src/commands/agent.js +131 -0
  39. package/dist/src/commands/daemon.d.ts +35 -0
  40. package/dist/src/commands/daemon.js +612 -0
  41. package/dist/src/commands/pair-qr.d.ts +4 -0
  42. package/dist/src/commands/pair-qr.js +6 -0
  43. package/dist/src/commands/pair.d.ts +8 -0
  44. package/dist/src/commands/pair.js +162 -0
  45. package/dist/src/commands/upgrade.d.ts +5 -0
  46. package/dist/src/commands/upgrade.js +145 -0
  47. package/dist/src/config/index.d.ts +32 -0
  48. package/dist/src/config/index.js +31 -0
  49. package/dist/src/fs/handler.d.ts +26 -0
  50. package/dist/src/fs/handler.js +130 -0
  51. package/dist/src/fs/security.d.ts +2 -0
  52. package/dist/src/fs/security.js +32 -0
  53. package/dist/src/index.d.ts +1 -0
  54. package/dist/src/index.js +277 -0
  55. package/dist/src/log-reporter.d.ts +18 -0
  56. package/dist/src/log-reporter.js +16 -0
  57. package/dist/src/native-fusion/parsers.d.ts +12 -0
  58. package/dist/src/native-fusion/parsers.js +687 -0
  59. package/dist/src/native-fusion/service.d.ts +25 -0
  60. package/dist/src/native-fusion/service.js +176 -0
  61. package/dist/src/native-fusion/state.d.ts +3 -0
  62. package/dist/src/native-fusion/state.js +22 -0
  63. package/dist/src/native-fusion/types.d.ts +24 -0
  64. package/dist/src/native-fusion/types.js +1 -0
  65. package/dist/src/region.d.ts +15 -0
  66. package/dist/src/region.js +99 -0
  67. package/dist/src/relay/client.d.ts +62 -0
  68. package/dist/src/relay/client.js +311 -0
  69. package/dist/src/session/handlers/agents.d.ts +4 -0
  70. package/dist/src/session/handlers/agents.js +55 -0
  71. package/dist/src/session/handlers/chat.d.ts +4 -0
  72. package/dist/src/session/handlers/chat.js +326 -0
  73. package/dist/src/session/handlers/control.d.ts +5 -0
  74. package/dist/src/session/handlers/control.js +57 -0
  75. package/dist/src/session/handlers/fs.d.ts +10 -0
  76. package/dist/src/session/handlers/fs.js +256 -0
  77. package/dist/src/session/manager.d.ts +28 -0
  78. package/dist/src/session/manager.js +174 -0
  79. package/dist/src/session/store.d.ts +7 -0
  80. package/dist/src/session/store.js +46 -0
  81. package/dist/src/session/types.d.ts +35 -0
  82. package/dist/src/session/types.js +4 -0
  83. package/dist/src/upgrade/engine.d.ts +64 -0
  84. package/dist/src/upgrade/engine.js +238 -0
  85. package/package.json +2 -2
@@ -0,0 +1,829 @@
1
+ // @arch docs/architecture/cli/agent-adapters.md
2
+ // @test src/__tests__/codex-adapter.test.ts
3
+ import { createInterface } from 'node:readline';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { AgentAdapter, registerAgent } from './adapter.js';
6
+ import { resolveBuiltinCommand, spawnResolvedCommand } from './command-spec.js';
7
+ export class CodexAdapter extends AgentAdapter {
8
+ type = 'codex';
9
+ process = null;
10
+ workDir = null;
11
+ seq = 0;
12
+ runId = '';
13
+ pendingUsage;
14
+ agentSessionId = null;
15
+ hasEmittedText = false;
16
+ textTail = '';
17
+ terminalState = 'open';
18
+ forceCloseTimer = null;
19
+ stderrBuf = '';
20
+ rpcSeq = 1;
21
+ pendingRequests = new Map();
22
+ appServerReady = null;
23
+ appServerStartupError = null;
24
+ activeTurnId = null;
25
+ namedThread = false;
26
+ deltaItemIds = new Set();
27
+ lastTransientStatus = '';
28
+ async start(_sessionId, workDir, agentSessionId) {
29
+ this.workDir = workDir;
30
+ this.seq = 0;
31
+ if (agentSessionId)
32
+ this.agentSessionId = agentSessionId;
33
+ }
34
+ async send(text, modelId) {
35
+ if (this.activeTurnId) {
36
+ await this.killProcess();
37
+ }
38
+ const codexModelId = normalizeCodexModelId(modelId);
39
+ this.runId = randomUUID();
40
+ this.seq = 0;
41
+ this.resetRunState();
42
+ await this.ensureAppServer(codexModelId);
43
+ const threadId = this.agentSessionId;
44
+ if (!threadId)
45
+ throw new Error('codex app-server did not create a thread');
46
+ this.emitEvent({ state: 'start', agentSessionId: threadId });
47
+ if (!this.namedThread) {
48
+ await this.sendRpc('thread/name/set', {
49
+ threadId,
50
+ name: makeThreadTitle(text),
51
+ }).catch(() => { });
52
+ this.namedThread = true;
53
+ }
54
+ const response = await this.sendRpc('turn/start', {
55
+ threadId,
56
+ input: [{ type: 'text', text, text_elements: [] }],
57
+ approvalPolicy: 'never',
58
+ sandboxPolicy: { type: 'dangerFullAccess' },
59
+ ...(codexModelId ? { model: codexModelId } : {}),
60
+ });
61
+ this.activeTurnId = response.turn?.id ?? null;
62
+ }
63
+ async resume(agentSessionId) {
64
+ await this.killProcess();
65
+ this.agentSessionId = agentSessionId;
66
+ this.namedThread = true;
67
+ this.resetTextState();
68
+ }
69
+ async stop() {
70
+ await this.killProcess();
71
+ }
72
+ spawnCodex(args) {
73
+ const spec = resolveBuiltinCommand('codex');
74
+ if (!spec) {
75
+ this.emit('error', new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));
76
+ return;
77
+ }
78
+ const proc = spawnResolvedCommand(spec, args, {
79
+ cwd: this.workDir ?? undefined,
80
+ stdio: ['ignore', 'pipe', 'pipe'],
81
+ env: { ...process.env },
82
+ });
83
+ this.process = proc;
84
+ const rl = createInterface({ input: proc.stdout });
85
+ rl.on('line', (line) => {
86
+ if (!line.trim())
87
+ return;
88
+ try {
89
+ const obj = JSON.parse(line);
90
+ this.handleStreamEvent(obj);
91
+ }
92
+ catch {
93
+ this.emitEvent({ state: 'delta', text: line });
94
+ }
95
+ });
96
+ let stderrBuf = '';
97
+ proc.stderr?.on('data', (chunk) => {
98
+ stderrBuf += chunk.toString();
99
+ });
100
+ proc.on('close', (code) => {
101
+ if (this.process !== proc)
102
+ return;
103
+ this.process = null;
104
+ this.clearForceCloseTimer();
105
+ this.handleProcessClose(code, stderrBuf);
106
+ });
107
+ proc.on('error', (err) => {
108
+ if (this.process !== proc)
109
+ return;
110
+ this.process = null;
111
+ if (err.code === 'ENOENT') {
112
+ this.emit('error', new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));
113
+ }
114
+ else {
115
+ this.emit('error', err);
116
+ }
117
+ });
118
+ }
119
+ spawnAppServer() {
120
+ const spec = resolveBuiltinCommand('codex');
121
+ if (!spec) {
122
+ this.emit('error', new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));
123
+ return;
124
+ }
125
+ const proc = spawnResolvedCommand(spec, ['app-server', '--listen', 'stdio://'], {
126
+ cwd: this.workDir ?? undefined,
127
+ stdio: ['pipe', 'pipe', 'pipe'],
128
+ env: { ...process.env, NO_COLOR: '1' },
129
+ });
130
+ this.process = proc;
131
+ this.stderrBuf = '';
132
+ this.appServerStartupError = null;
133
+ const rl = createInterface({ input: proc.stdout });
134
+ rl.on('line', (line) => {
135
+ if (!line.trim())
136
+ return;
137
+ let msg;
138
+ try {
139
+ msg = JSON.parse(line);
140
+ }
141
+ catch {
142
+ this.handleAppServerNonJsonStdout(line);
143
+ return;
144
+ }
145
+ this.handleAppServerMessage(msg);
146
+ });
147
+ proc.stderr?.on('data', (chunk) => {
148
+ this.stderrBuf += chunk.toString();
149
+ });
150
+ proc.on('close', (code) => {
151
+ if (this.process !== proc)
152
+ return;
153
+ const hadActiveTurn = this.activeTurnId != null;
154
+ this.process = null;
155
+ this.appServerReady = null;
156
+ this.activeTurnId = null;
157
+ this.rejectAllPending(new Error(normalizeCodexStderr(this.stderrBuf) || `codex app-server exited with code ${code}`));
158
+ if (this.terminalState === 'open' && hadActiveTurn) {
159
+ this.handleProcessClose(code, this.stderrBuf);
160
+ }
161
+ });
162
+ proc.on('error', (err) => {
163
+ if (this.process !== proc)
164
+ return;
165
+ this.process = null;
166
+ this.rejectAllPending(err);
167
+ if (err.code === 'ENOENT') {
168
+ this.emit('error', new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));
169
+ }
170
+ else {
171
+ this.emit('error', err);
172
+ }
173
+ });
174
+ }
175
+ async ensureAppServer(modelId) {
176
+ if (this.appServerReady)
177
+ return this.appServerReady;
178
+ this.spawnAppServer();
179
+ this.appServerReady = this.initializeAppServer(modelId).catch(async (error) => {
180
+ this.appServerReady = null;
181
+ await this.killProcess();
182
+ throw error;
183
+ });
184
+ return this.appServerReady;
185
+ }
186
+ async initializeAppServer(modelId) {
187
+ const codexModelId = normalizeCodexModelId(modelId);
188
+ await this.sendRpc('initialize', {
189
+ clientInfo: { name: 'shennian', title: 'Shennian', version: '0.0.0' },
190
+ capabilities: { experimentalApi: true },
191
+ });
192
+ if (this.agentSessionId) {
193
+ const response = await this.sendRpc('thread/resume', {
194
+ threadId: this.agentSessionId,
195
+ cwd: this.workDir,
196
+ approvalPolicy: 'never',
197
+ sandbox: 'danger-full-access',
198
+ persistExtendedHistory: true,
199
+ ...(codexModelId ? { model: codexModelId } : {}),
200
+ });
201
+ this.agentSessionId = response.thread?.id ?? this.agentSessionId;
202
+ this.namedThread = !!response.thread?.name;
203
+ return;
204
+ }
205
+ const response = await this.sendRpc('thread/start', {
206
+ cwd: this.workDir,
207
+ approvalPolicy: 'never',
208
+ sandbox: 'danger-full-access',
209
+ serviceName: 'Shennian',
210
+ experimentalRawEvents: false,
211
+ persistExtendedHistory: true,
212
+ ...(codexModelId ? { model: codexModelId } : {}),
213
+ });
214
+ const threadId = response.thread?.id;
215
+ if (!threadId)
216
+ throw new Error('codex app-server thread/start returned no thread id');
217
+ this.agentSessionId = threadId;
218
+ this.namedThread = !!response.thread?.name;
219
+ }
220
+ sendRpc(method, params, timeoutMs = 60_000) {
221
+ if (this.appServerStartupError)
222
+ return Promise.reject(this.appServerStartupError);
223
+ const proc = this.process;
224
+ if (!proc?.stdin)
225
+ return Promise.reject(new Error('codex app-server is not running'));
226
+ const id = this.rpcSeq++;
227
+ const payload = JSON.stringify({ id, method, params });
228
+ return new Promise((resolve, reject) => {
229
+ const timer = setTimeout(() => {
230
+ this.pendingRequests.delete(id);
231
+ reject(new Error(`codex app-server request timed out: ${method}`));
232
+ }, timeoutMs);
233
+ this.pendingRequests.set(id, { resolve, reject, timer });
234
+ proc.stdin.write(`${payload}\n`, (error) => {
235
+ if (!error)
236
+ return;
237
+ clearTimeout(timer);
238
+ this.pendingRequests.delete(id);
239
+ reject(error);
240
+ });
241
+ });
242
+ }
243
+ handleAppServerMessage(msg) {
244
+ if (msg.id != null) {
245
+ const pending = this.pendingRequests.get(msg.id);
246
+ if (pending) {
247
+ clearTimeout(pending.timer);
248
+ this.pendingRequests.delete(msg.id);
249
+ if (msg.error) {
250
+ pending.reject(new Error(msg.error.message || `codex app-server error ${msg.error.code ?? ''}`.trim()));
251
+ }
252
+ else {
253
+ pending.resolve(msg.result);
254
+ }
255
+ }
256
+ }
257
+ if (!msg.method)
258
+ return;
259
+ const params = msg.params ?? {};
260
+ switch (msg.method) {
261
+ case 'item/agentMessage/delta': {
262
+ const itemId = typeof params.itemId === 'string' ? params.itemId : '';
263
+ if (itemId)
264
+ this.deltaItemIds.add(itemId);
265
+ if (typeof params.delta === 'string')
266
+ this.emitText(params.delta);
267
+ break;
268
+ }
269
+ case 'item/completed':
270
+ this.handleAppServerCompletedItem(params);
271
+ break;
272
+ case 'thread/tokenUsage/updated':
273
+ this.handleAppServerUsage(params);
274
+ break;
275
+ case 'turn/completed': {
276
+ const turn = typeof params.turn === 'object' && params.turn !== null
277
+ ? params.turn
278
+ : null;
279
+ const turnId = typeof turn?.id === 'string' ? turn.id : null;
280
+ if (!this.activeTurnId || turnId === this.activeTurnId) {
281
+ this.activeTurnId = null;
282
+ this.emitFinalIfOpen();
283
+ }
284
+ break;
285
+ }
286
+ case 'error': {
287
+ const message = extractAppServerErrorMessage(params);
288
+ if (isTransientCodexErrorMessage(message)) {
289
+ this.emitTransientStatus(message);
290
+ return;
291
+ }
292
+ this.emitErrorIfOpen(message);
293
+ break;
294
+ }
295
+ }
296
+ }
297
+ handleAppServerNonJsonStdout(line) {
298
+ const normalized = normalizeTerminalText(line);
299
+ if (!looksLikeCodexInteractiveAuthPrompt(normalized))
300
+ return;
301
+ this.failAppServerStartup(new Error('Codex 未登录。请先在这台电脑的终端运行 `codex`,按提示完成 ChatGPT 登录或配置 API key,然后再回到神念发送消息。'));
302
+ }
303
+ failAppServerStartup(error) {
304
+ if (this.appServerStartupError)
305
+ return;
306
+ this.appServerStartupError = error;
307
+ this.rejectAllPending(error);
308
+ this.process?.kill('SIGTERM');
309
+ }
310
+ handleAppServerCompletedItem(params) {
311
+ const item = typeof params.item === 'object' && params.item !== null
312
+ ? params.item
313
+ : null;
314
+ if (!item || typeof item.type !== 'string')
315
+ return;
316
+ switch (item.type) {
317
+ case 'agentMessage': {
318
+ const id = typeof item.id === 'string' ? item.id : '';
319
+ if (id && this.deltaItemIds.has(id))
320
+ return;
321
+ if (typeof item.text === 'string')
322
+ this.emitText(item.text, 'block');
323
+ break;
324
+ }
325
+ case 'commandExecution': {
326
+ const command = typeof item.command === 'string' ? item.command : '';
327
+ const output = typeof item.aggregatedOutput === 'string' ? item.aggregatedOutput : '';
328
+ if (command) {
329
+ this.emitEvent({ state: 'tool-call', name: 'command_execution', args: { command } });
330
+ }
331
+ this.emitEvent({
332
+ state: 'tool-result',
333
+ name: 'command_execution',
334
+ result: [output, item.exitCode != null ? `\n(exit ${item.exitCode})` : ''].join('').trim(),
335
+ });
336
+ break;
337
+ }
338
+ case 'mcpToolCall':
339
+ case 'dynamicToolCall': {
340
+ const tool = typeof item.tool === 'string' ? item.tool : item.type;
341
+ const args = typeof item.arguments === 'object' && item.arguments !== null
342
+ ? item.arguments
343
+ : {};
344
+ this.emitEvent({ state: 'tool-call', name: tool, args });
345
+ this.emitEvent({
346
+ state: 'tool-result',
347
+ name: tool,
348
+ result: safeStringify(item.error ?? item.result ?? item.contentItems ?? ''),
349
+ });
350
+ break;
351
+ }
352
+ case 'fileChange': {
353
+ const changes = Array.isArray(item.changes) ? item.changes : [];
354
+ const summary = changes
355
+ .map((change) => {
356
+ if (typeof change !== 'object' || change === null)
357
+ return '';
358
+ const c = change;
359
+ const path = typeof c.path === 'string' ? c.path : typeof c.file === 'string' ? c.file : '';
360
+ const kind = typeof c.kind === 'string' ? c.kind : typeof c.type === 'string' ? c.type : 'change';
361
+ return path ? `${kind}: ${path}` : '';
362
+ })
363
+ .filter(Boolean)
364
+ .join('\n');
365
+ if (summary)
366
+ this.emitText(summary, 'block');
367
+ break;
368
+ }
369
+ }
370
+ }
371
+ handleAppServerUsage(params) {
372
+ const tokenUsage = typeof params.tokenUsage === 'object' && params.tokenUsage !== null
373
+ ? params.tokenUsage
374
+ : null;
375
+ const last = typeof tokenUsage?.last === 'object' && tokenUsage.last !== null
376
+ ? tokenUsage.last
377
+ : null;
378
+ const total = typeof tokenUsage?.total === 'object' && tokenUsage.total !== null
379
+ ? tokenUsage.total
380
+ : null;
381
+ const usage = last ?? total;
382
+ if (!usage)
383
+ return;
384
+ const input = typeof usage.inputTokens === 'number' ? usage.inputTokens : undefined;
385
+ const output = typeof usage.outputTokens === 'number' ? usage.outputTokens : undefined;
386
+ if (input != null || output != null) {
387
+ this.pendingUsage = {
388
+ inputTokens: input ?? 0,
389
+ outputTokens: output ?? 0,
390
+ };
391
+ }
392
+ }
393
+ handleCodexItemLine(obj) {
394
+ const item = obj.item;
395
+ if (!item?.type)
396
+ return;
397
+ switch (item.type) {
398
+ case 'agent_message':
399
+ case 'reasoning': {
400
+ if (obj.type === 'item.completed' && item.text) {
401
+ this.emitText(item.text, 'block');
402
+ }
403
+ break;
404
+ }
405
+ case 'command_execution': {
406
+ if (obj.type === 'item.started' && item.command) {
407
+ this.emitEvent({
408
+ state: 'tool-call',
409
+ name: 'command_execution',
410
+ args: { command: item.command },
411
+ });
412
+ }
413
+ if (obj.type === 'item.completed') {
414
+ const parts = [
415
+ item.aggregated_output ?? '',
416
+ item.exit_code != null ? `\n(exit ${item.exit_code})` : '',
417
+ ];
418
+ this.emitEvent({
419
+ state: 'tool-result',
420
+ name: 'command_execution',
421
+ result: parts.join('').trim() || String(item.status ?? ''),
422
+ });
423
+ }
424
+ break;
425
+ }
426
+ case 'mcp_tool_call': {
427
+ if (obj.type === 'item.started') {
428
+ this.emitEvent({
429
+ state: 'tool-call',
430
+ name: item.tool ?? 'mcp_tool',
431
+ args: {
432
+ server: item.server,
433
+ ...(item.arguments && typeof item.arguments === 'object' ? item.arguments : {}),
434
+ },
435
+ });
436
+ }
437
+ if (obj.type === 'item.completed') {
438
+ const errMsg = item.error && typeof item.error === 'object' ? item.error.message : undefined;
439
+ this.emitEvent({
440
+ state: 'tool-result',
441
+ name: item.tool ?? 'mcp_tool',
442
+ result: errMsg ?? safeStringify(item.result),
443
+ });
444
+ }
445
+ break;
446
+ }
447
+ case 'file_change': {
448
+ if (obj.type === 'item.completed' && item.changes?.length) {
449
+ const summary = item.changes.map((c) => `${c.kind}: ${c.path}`).join('\n');
450
+ this.emitText(summary, 'block');
451
+ }
452
+ break;
453
+ }
454
+ case 'web_search': {
455
+ if (obj.type === 'item.completed' && item.query) {
456
+ this.emitText(`[web_search] ${item.query}`, 'block');
457
+ }
458
+ break;
459
+ }
460
+ case 'todo_list': {
461
+ if (obj.type === 'item.completed' && item.items?.length) {
462
+ const lines = item.items.map((t) => `- [${t.completed ? 'x' : ' '}] ${t.text}`).join('\n');
463
+ this.emitText(lines, 'block');
464
+ }
465
+ break;
466
+ }
467
+ case 'error': {
468
+ if (obj.type === 'item.completed' && item.message) {
469
+ this.emitEvent({ state: 'error', message: item.message });
470
+ }
471
+ break;
472
+ }
473
+ default:
474
+ break;
475
+ }
476
+ }
477
+ handleStreamEvent(obj) {
478
+ const topType = obj.type ?? obj.event;
479
+ if (topType?.startsWith('item.')) {
480
+ this.handleCodexItemLine(obj);
481
+ }
482
+ switch (topType) {
483
+ case 'turn.completed': {
484
+ const u = obj.usage;
485
+ if (u) {
486
+ const input = u.input_tokens ?? u.prompt_tokens;
487
+ const output = u.output_tokens ?? u.completion_tokens;
488
+ if (input != null || output != null) {
489
+ this.pendingUsage = {
490
+ inputTokens: input ?? 0,
491
+ outputTokens: output ?? 0,
492
+ };
493
+ }
494
+ }
495
+ this.emitFinalIfOpen();
496
+ return;
497
+ }
498
+ case 'turn.failed': {
499
+ const msg = typeof obj.error === 'object' && obj.error?.message
500
+ ? obj.error.message
501
+ : typeof obj.error === 'string'
502
+ ? obj.error
503
+ : 'turn failed';
504
+ this.emitErrorIfOpen(msg);
505
+ return;
506
+ }
507
+ case 'error': {
508
+ const m = typeof obj.message === 'string' ? obj.message : '';
509
+ if (m.includes('Reconnecting'))
510
+ return;
511
+ this.emitErrorIfOpen(m || (typeof obj.error === 'string' ? obj.error : 'stream error'));
512
+ return;
513
+ }
514
+ case 'thread.started': {
515
+ const sid = obj.thread_id ?? obj.session_id ?? obj.id;
516
+ if (typeof sid === 'string' && sid) {
517
+ this.agentSessionId = sid;
518
+ this.emitEvent({ state: 'start', agentSessionId: this.agentSessionId });
519
+ }
520
+ return;
521
+ }
522
+ case 'turn.started':
523
+ return;
524
+ }
525
+ if (topType?.startsWith('item.'))
526
+ return;
527
+ const eventType = obj.type ?? obj.event;
528
+ switch (eventType) {
529
+ case 'message':
530
+ case 'text':
531
+ case 'content': {
532
+ const text = obj.content ?? obj.text;
533
+ if (text) {
534
+ this.emitText(text);
535
+ }
536
+ break;
537
+ }
538
+ case 'function_call':
539
+ case 'tool_call': {
540
+ this.emitEvent({
541
+ state: 'tool-call',
542
+ name: obj.name,
543
+ args: obj.arguments ?? obj.input,
544
+ });
545
+ break;
546
+ }
547
+ case 'function_call_output':
548
+ case 'tool_result': {
549
+ this.emitEvent({
550
+ state: 'tool-result',
551
+ name: obj.name,
552
+ result: obj.output ?? obj.result,
553
+ });
554
+ break;
555
+ }
556
+ case 'error': {
557
+ break;
558
+ }
559
+ case 'done':
560
+ case 'completed': {
561
+ if (obj.usage) {
562
+ this.pendingUsage = {
563
+ inputTokens: obj.usage.prompt_tokens ?? obj.usage.input_tokens ?? 0,
564
+ outputTokens: obj.usage.completion_tokens ?? obj.usage.output_tokens ?? 0,
565
+ };
566
+ }
567
+ this.emitFinalIfOpen();
568
+ break;
569
+ }
570
+ }
571
+ }
572
+ emitEvent(partial) {
573
+ const event = {
574
+ ...partial,
575
+ runId: this.runId,
576
+ seq: this.seq++,
577
+ };
578
+ this.emit('agentEvent', event);
579
+ }
580
+ async killProcess() {
581
+ const proc = this.process;
582
+ this.appServerReady = null;
583
+ this.activeTurnId = null;
584
+ if (!proc) {
585
+ this.rejectAllPending(new Error('codex app-server stopped'));
586
+ return;
587
+ }
588
+ this.process = null;
589
+ this.clearForceCloseTimer();
590
+ proc.kill('SIGTERM');
591
+ await new Promise((resolve) => {
592
+ proc.on('close', resolve);
593
+ setTimeout(() => {
594
+ proc.kill('SIGKILL');
595
+ resolve();
596
+ }, 3000);
597
+ });
598
+ this.rejectAllPending(new Error('codex app-server stopped'));
599
+ }
600
+ rejectAllPending(error) {
601
+ for (const [id, pending] of this.pendingRequests.entries()) {
602
+ clearTimeout(pending.timer);
603
+ pending.reject(error);
604
+ this.pendingRequests.delete(id);
605
+ }
606
+ }
607
+ handleProcessClose(code, stderrBuf) {
608
+ const stderr = normalizeCodexStderr(stderrBuf);
609
+ if (code !== 0 && code !== null) {
610
+ const msg = stderr || `codex exited with code ${code}`;
611
+ this.emitErrorIfOpen(msg);
612
+ }
613
+ else if (looksLikeFatalCodexStderr(stderr)) {
614
+ // Codex sometimes surfaces fatal API/auth errors on stderr without
615
+ // emitting a protocol-level `turn.failed`, and may still exit 0.
616
+ this.emitErrorIfOpen(stderr);
617
+ }
618
+ else {
619
+ this.emitFinalIfOpen();
620
+ }
621
+ this.pendingUsage = undefined;
622
+ }
623
+ emitFinalIfOpen() {
624
+ if (this.terminalState !== 'open')
625
+ return;
626
+ this.terminalState = 'final';
627
+ this.emitEvent({
628
+ state: 'final',
629
+ usage: this.pendingUsage,
630
+ agentSessionId: this.agentSessionId ?? undefined,
631
+ });
632
+ }
633
+ emitErrorIfOpen(message) {
634
+ if (this.terminalState !== 'open')
635
+ return;
636
+ this.terminalState = 'error';
637
+ this.emitEvent({ state: 'error', message: formatCodexErrorMessage(message) });
638
+ this.scheduleProcessClose();
639
+ }
640
+ resetRunState() {
641
+ this.pendingUsage = undefined;
642
+ this.terminalState = 'open';
643
+ this.deltaItemIds.clear();
644
+ this.lastTransientStatus = '';
645
+ this.clearForceCloseTimer();
646
+ this.resetTextState();
647
+ }
648
+ emitTransientStatus(message) {
649
+ const formatted = formatTransientCodexStatus(message);
650
+ if (!formatted || formatted === this.lastTransientStatus || this.terminalState !== 'open')
651
+ return;
652
+ this.lastTransientStatus = formatted;
653
+ this.emitEvent({ state: 'delta', text: `${formatted}\n`, thinking: true });
654
+ }
655
+ resetTextState() {
656
+ this.hasEmittedText = false;
657
+ this.textTail = '';
658
+ }
659
+ emitText(text, mode = 'delta') {
660
+ if (!text)
661
+ return;
662
+ let next = stripGitDirectiveArtifacts(text);
663
+ if (!next)
664
+ return;
665
+ if (mode === 'block' && this.hasEmittedText && !next.startsWith('\n')) {
666
+ if (this.textTail.endsWith('\n')) {
667
+ next = `\n${next}`;
668
+ }
669
+ else if (!this.textTail.endsWith('\n\n')) {
670
+ next = `\n\n${next}`;
671
+ }
672
+ }
673
+ this.hasEmittedText = true;
674
+ this.textTail = (this.textTail + next).slice(-4);
675
+ this.emitEvent({ state: 'delta', text: next });
676
+ }
677
+ scheduleProcessClose() {
678
+ const proc = this.process;
679
+ if (!proc || this.forceCloseTimer)
680
+ return;
681
+ this.forceCloseTimer = setTimeout(() => {
682
+ this.forceCloseTimer = null;
683
+ if (this.process !== proc)
684
+ return;
685
+ proc.kill('SIGTERM');
686
+ setTimeout(() => {
687
+ if (this.process === proc) {
688
+ proc.kill('SIGKILL');
689
+ }
690
+ }, 1000);
691
+ }, 250);
692
+ }
693
+ clearForceCloseTimer() {
694
+ if (!this.forceCloseTimer)
695
+ return;
696
+ clearTimeout(this.forceCloseTimer);
697
+ this.forceCloseTimer = null;
698
+ }
699
+ }
700
+ function makeThreadTitle(text) {
701
+ const firstLine = normalizeTitleText(text).split('\n').find((line) => line.trim()) ?? 'Shennian';
702
+ const title = firstLine.trim().slice(0, 80);
703
+ return title || 'Shennian';
704
+ }
705
+ function normalizeTitleText(text) {
706
+ return text
707
+ .replace(/!\[[^\]]*]\([^)]+\)/g, '')
708
+ .replace(/\s+/g, ' ')
709
+ .trim();
710
+ }
711
+ export function normalizeCodexModelId(modelId) {
712
+ const trimmed = modelId?.trim();
713
+ if (!trimmed)
714
+ return undefined;
715
+ return trimmed.toLowerCase() === 'openai' ? undefined : trimmed;
716
+ }
717
+ function extractAppServerErrorMessage(params) {
718
+ if (typeof params.message === 'string' && params.message.trim())
719
+ return params.message.trim();
720
+ const error = params.error;
721
+ if (typeof error === 'string' && error.trim())
722
+ return error.trim();
723
+ if (typeof error === 'object' && error !== null) {
724
+ const message = error.message;
725
+ if (typeof message === 'string' && message.trim())
726
+ return message.trim();
727
+ }
728
+ return 'codex app-server error';
729
+ }
730
+ function isTransientCodexErrorMessage(message) {
731
+ return /\bReconnecting\.\.\.\s*\d+\/\d+/i.test(message);
732
+ }
733
+ function formatTransientCodexStatus(message) {
734
+ const match = message.match(/\bReconnecting\.\.\.\s*(\d+\/\d+)/i);
735
+ if (!match)
736
+ return '';
737
+ return `Codex API 暂时不可用,正在重试 ${match[1]}...`;
738
+ }
739
+ function formatCodexErrorMessage(message) {
740
+ const statusMatch = message.match(/unexpected status\s+(\d+)\s+([^:,]+)(?::\s*([^,]+))?(?:,\s*url:\s*([^,\s]+))?(?:,\s*request id:\s*([^\s,]+))?/i);
741
+ if (!statusMatch)
742
+ return message;
743
+ const [, status, statusText, detail, url, requestId] = statusMatch;
744
+ const parts = [
745
+ `Codex API 返回 ${status} ${statusText.trim()}`,
746
+ detail?.trim() ? `:${detail.trim()}` : '',
747
+ url ? `\n上游地址:${url}` : '',
748
+ requestId ? `\nrequest id:${requestId}` : '',
749
+ ];
750
+ return parts.join('');
751
+ }
752
+ const GIT_DIRECTIVE_LINE_RE = /^\s*::git-[a-z-]+\{[^\n]*\}\s*$/gm;
753
+ function stripGitDirectiveArtifacts(text) {
754
+ if (!text)
755
+ return '';
756
+ const normalized = text.replace(/\r\n/g, '\n');
757
+ const hadDirective = /(^|\n)\s*::git-[a-z-]+\{[^\n]*\}\s*(?=\n|$)/.test(normalized);
758
+ const stripped = normalized
759
+ .replace(GIT_DIRECTIVE_LINE_RE, '')
760
+ .replace(/\n{3,}/g, '\n\n');
761
+ if (!stripped.trim())
762
+ return '';
763
+ return hadDirective
764
+ ? stripped.replace(/[ \t]+\n/g, '\n').replace(/\n+$/g, '')
765
+ : stripped;
766
+ }
767
+ function safeStringify(value) {
768
+ if (value == null)
769
+ return '';
770
+ if (typeof value === 'string')
771
+ return value;
772
+ try {
773
+ return JSON.stringify(value);
774
+ }
775
+ catch {
776
+ return String(value);
777
+ }
778
+ }
779
+ function normalizeCodexStderr(stderr) {
780
+ return stderr
781
+ .split(/\r?\n/)
782
+ .map((line) => line.trim())
783
+ .filter(Boolean)
784
+ .filter((line) => !isIgnorableCodexStderrLine(line))
785
+ .join('\n');
786
+ }
787
+ function normalizeTerminalText(text) {
788
+ return text
789
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ' ')
790
+ .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, ' ')
791
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ' ')
792
+ .replace(/\s+/g, ' ')
793
+ .trim();
794
+ }
795
+ function looksLikeCodexInteractiveAuthPrompt(text) {
796
+ if (!text)
797
+ return false;
798
+ const normalized = text.toLowerCase();
799
+ return (normalized.includes('welcome to codex') ||
800
+ normalized.includes('sign in with chatgpt') ||
801
+ normalized.includes('provide your own api key') ||
802
+ normalized.includes('press enter to continue'));
803
+ }
804
+ function isIgnorableCodexStderrLine(line) {
805
+ return [
806
+ /WARNING: proceeding, even though we could not update PATH:/i,
807
+ /Reading additional input from stdin\.\.\./i,
808
+ /failed to record rollout items: failed to queue rollout items: channel closed/i,
809
+ ].some((pattern) => pattern.test(line));
810
+ }
811
+ function looksLikeFatalCodexStderr(stderr) {
812
+ if (!stderr)
813
+ return false;
814
+ return [
815
+ /\bunauthorized\b/i,
816
+ /\bforbidden\b/i,
817
+ /\bpermission denied\b/i,
818
+ /\brate limit\b/i,
819
+ /\binsufficient quota\b/i,
820
+ /\bapi key\b/i,
821
+ /\bauth/i,
822
+ /\bnetwork\b/i,
823
+ /\btimeout\b/i,
824
+ /\bnot found\b/i,
825
+ /\berror\b/i,
826
+ /\bfailed\b/i,
827
+ ].some((pattern) => pattern.test(stderr));
828
+ }
829
+ registerAgent('codex', () => new CodexAdapter());