shennian 0.2.5 → 0.2.6

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