shennian 0.3.39 → 0.3.41

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 (35) hide show
  1. package/README.md +2 -1
  2. package/dist/publish-build-manifest.json +37 -37
  3. package/dist/src/agents/claude.d.ts +1 -0
  4. package/dist/src/agents/claude.js +4 -4
  5. package/dist/src/agents/codex.d.ts +9 -0
  6. package/dist/src/agents/codex.js +10 -10
  7. package/dist/src/agents/model-registry/service.js +1 -1
  8. package/dist/src/commands/room.d.ts +2 -0
  9. package/dist/src/commands/room.js +3 -3
  10. package/dist/src/index.js +3 -3
  11. package/dist/src/native-fusion/codex-parser.js +4 -4
  12. package/dist/src/native-fusion/service.d.ts +8 -0
  13. package/dist/src/native-fusion/service.js +2 -2
  14. package/dist/src/native-fusion/types.d.ts +10 -0
  15. package/dist/src/room/host-session-observations.d.ts +1 -1
  16. package/dist/src/room/host-session-observations.js +2 -2
  17. package/dist/src/room/invite-qr.d.ts +6 -0
  18. package/dist/src/room/invite-qr.js +1 -0
  19. package/dist/src/room/managed-room-binding.d.ts +1 -1
  20. package/dist/src/room/managed-room-binding.js +1 -1
  21. package/dist/src/room/public-room-client.d.ts +2 -1
  22. package/dist/src/room/public-room-client.js +1 -1
  23. package/dist/src/room/room-action-client.d.ts +5 -5
  24. package/dist/src/room/room-action-client.js +1 -1
  25. package/dist/src/room/session-registry.d.ts +1 -1
  26. package/dist/src/room/session-registry.js +2 -2
  27. package/dist/src/session/handlers/chat.js +2 -2
  28. package/node_modules/@shennian/wire/dist/agent-workspace.d.ts +3 -1
  29. package/node_modules/@shennian/wire/dist/external-message-format.js +1 -1
  30. package/node_modules/@shennian/wire/dist/room.d.ts +18 -1
  31. package/node_modules/@shennian/wire/dist/room.js +18 -1
  32. package/node_modules/@shennian/wire/dist/session.d.ts +10 -0
  33. package/package.json +3 -1
  34. package/dist/src/commands/agent.d.ts +0 -7
  35. package/dist/src/commands/agent.js +0 -3
package/README.md CHANGED
@@ -24,7 +24,8 @@
24
24
  | `shennian logs -n 100` | 查看最近日志 |
25
25
  | `shennian config` | 查看本地配置 |
26
26
  | `shennian config set server cn\|global` | 切换国内 / 海外中继节点 |
27
- | `shennian agent add/list/remove` | 管理自定义 Agent |
27
+ | `shennian room create/join/status/read/send/attachment get/leave` | 创建或参与明确的神念群聊 |
28
+ | `shennian runtime add/list/remove` | 管理自定义 Agent Runtime |
28
29
  | `shennian upgrade` | 升级 CLI |
29
30
 
30
31
  `start`、`stop`、`status` 可选加 `--json`。`logs` 输出日志文本,不支持 `--json`。
@@ -21,8 +21,8 @@
21
21
  },
22
22
  {
23
23
  "file": "src/agents/claude.js",
24
- "beforeBytes": 11715,
25
- "afterBytes": 6026
24
+ "beforeBytes": 11959,
25
+ "afterBytes": 6164
26
26
  },
27
27
  {
28
28
  "file": "src/agents/codex-utils.js",
@@ -31,8 +31,8 @@
31
31
  },
32
32
  {
33
33
  "file": "src/agents/codex.js",
34
- "beforeBytes": 43923,
35
- "afterBytes": 22006
34
+ "beforeBytes": 47055,
35
+ "afterBytes": 23670
36
36
  },
37
37
  {
38
38
  "file": "src/agents/command-spec.js",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  {
63
63
  "file": "src/agents/external-channel-instructions.js",
64
- "beforeBytes": 9456,
64
+ "beforeBytes": 9452,
65
65
  "afterBytes": 13591
66
66
  },
67
67
  {
@@ -96,8 +96,8 @@
96
96
  },
97
97
  {
98
98
  "file": "src/agents/model-registry/service.js",
99
- "beforeBytes": 3048,
100
- "afterBytes": 1321
99
+ "beforeBytes": 3262,
100
+ "afterBytes": 1409
101
101
  },
102
102
  {
103
103
  "file": "src/agents/model-registry/types.js",
@@ -139,11 +139,6 @@
139
139
  "beforeBytes": 14265,
140
140
  "afterBytes": 7150
141
141
  },
142
- {
143
- "file": "src/commands/agent.js",
144
- "beforeBytes": 7536,
145
- "afterBytes": 4438
146
- },
147
142
  {
148
143
  "file": "src/commands/daemon-process.js",
149
144
  "beforeBytes": 3288,
@@ -166,12 +161,12 @@
166
161
  },
167
162
  {
168
163
  "file": "src/commands/integration.js",
169
- "beforeBytes": 815,
164
+ "beforeBytes": 827,
170
165
  "afterBytes": 468
171
166
  },
172
167
  {
173
168
  "file": "src/commands/manager.js",
174
- "beforeBytes": 6902,
169
+ "beforeBytes": 6853,
175
170
  "afterBytes": 4479
176
171
  },
177
172
  {
@@ -196,8 +191,8 @@
196
191
  },
197
192
  {
198
193
  "file": "src/commands/room.js",
199
- "beforeBytes": 15343,
200
- "afterBytes": 8914
194
+ "beforeBytes": 16095,
195
+ "afterBytes": 9244
201
196
  },
202
197
  {
203
198
  "file": "src/commands/runtime.js",
@@ -281,8 +276,8 @@
281
276
  },
282
277
  {
283
278
  "file": "src/index.js",
284
- "beforeBytes": 21131,
285
- "afterBytes": 11117
279
+ "beforeBytes": 21040,
280
+ "afterBytes": 11051
286
281
  },
287
282
  {
288
283
  "file": "src/log-reporter.js",
@@ -291,12 +286,12 @@
291
286
  },
292
287
  {
293
288
  "file": "src/manager/prompt.js",
294
- "beforeBytes": 4352,
289
+ "beforeBytes": 4350,
295
290
  "afterBytes": 7113
296
291
  },
297
292
  {
298
293
  "file": "src/manager/registry.js",
299
- "beforeBytes": 13897,
294
+ "beforeBytes": 13895,
300
295
  "afterBytes": 6747
301
296
  },
302
297
  {
@@ -306,13 +301,13 @@
306
301
  },
307
302
  {
308
303
  "file": "src/manager/runtime.js",
309
- "beforeBytes": 71951,
304
+ "beforeBytes": 71949,
310
305
  "afterBytes": 36578
311
306
  },
312
307
  {
313
308
  "file": "src/native-fusion/codex-parser.js",
314
- "beforeBytes": 27013,
315
- "afterBytes": 11324
309
+ "beforeBytes": 27675,
310
+ "afterBytes": 11480
316
311
  },
317
312
  {
318
313
  "file": "src/native-fusion/config.js",
@@ -336,8 +331,8 @@
336
331
  },
337
332
  {
338
333
  "file": "src/native-fusion/service.js",
339
- "beforeBytes": 7841,
340
- "afterBytes": 3598
334
+ "beforeBytes": 12900,
335
+ "afterBytes": 6147
341
336
  },
342
337
  {
343
338
  "file": "src/native-fusion/state.js",
@@ -391,14 +386,19 @@
391
386
  },
392
387
  {
393
388
  "file": "src/room/host-session-observations.js",
394
- "beforeBytes": 9376,
395
- "afterBytes": 5167
389
+ "beforeBytes": 9450,
390
+ "afterBytes": 5170
396
391
  },
397
392
  {
398
393
  "file": "src/room/invite-bootstrap.js",
399
394
  "beforeBytes": 6136,
400
395
  "afterBytes": 3363
401
396
  },
397
+ {
398
+ "file": "src/room/invite-qr.js",
399
+ "beforeBytes": 888,
400
+ "afterBytes": 519
401
+ },
402
402
  {
403
403
  "file": "src/room/managed-context.js",
404
404
  "beforeBytes": 4442,
@@ -411,8 +411,8 @@
411
411
  },
412
412
  {
413
413
  "file": "src/room/managed-room-binding.js",
414
- "beforeBytes": 6069,
415
- "afterBytes": 3316
414
+ "beforeBytes": 6014,
415
+ "afterBytes": 3277
416
416
  },
417
417
  {
418
418
  "file": "src/room/managed-room-ipc.js",
@@ -431,13 +431,13 @@
431
431
  },
432
432
  {
433
433
  "file": "src/room/public-room-client.js",
434
- "beforeBytes": 5637,
435
- "afterBytes": 3101
434
+ "beforeBytes": 5771,
435
+ "afterBytes": 3197
436
436
  },
437
437
  {
438
438
  "file": "src/room/room-action-client.js",
439
- "beforeBytes": 23331,
440
- "afterBytes": 11775
439
+ "beforeBytes": 23728,
440
+ "afterBytes": 11957
441
441
  },
442
442
  {
443
443
  "file": "src/room/room-binding-client.js",
@@ -446,8 +446,8 @@
446
446
  },
447
447
  {
448
448
  "file": "src/room/session-registry.js",
449
- "beforeBytes": 27208,
450
- "afterBytes": 15357
449
+ "beforeBytes": 27201,
450
+ "afterBytes": 15360
451
451
  },
452
452
  {
453
453
  "file": "src/session/archive-zip.js",
@@ -471,8 +471,8 @@
471
471
  },
472
472
  {
473
473
  "file": "src/session/handlers/chat.js",
474
- "beforeBytes": 31111,
475
- "afterBytes": 13158
474
+ "beforeBytes": 31311,
475
+ "afterBytes": 13268
476
476
  },
477
477
  {
478
478
  "file": "src/session/handlers/control.js",
@@ -3,6 +3,7 @@ import type { ChatAttachmentMeta, ExternalChannelSessionStatus } from '@shennian
3
3
  export declare function normalizeClaudeModelId(modelId?: string | null): string;
4
4
  export declare function normalizeClaudeReasoningEffort(reasoningEffort?: string | null): string | undefined;
5
5
  export declare function resetClaudeCapabilityCacheForTests(): void;
6
+ export declare function shouldForwardClaudeStderrLine(line: string): boolean;
6
7
  export declare function supportsClaudeReasoningEffort(): boolean;
7
8
  export declare class ClaudeAdapter extends AgentAdapter {
8
9
  private readonly options;
@@ -1,8 +1,8 @@
1
- import{createInterface as f}from"node:readline";import{randomUUID as d}from"node:crypto";import{AgentAdapter as g,registerAgent as I}from"./adapter.js";import{resolveBuiltinCommand as p,spawnAgentCommand as S,spawnResolvedCommandSync as E}from"./command-spec.js";import{buildAgentProcessEnv as m}from"../agent-env.js";import{buildPlatformInstructions as c}from"./platform-instructions.js";function y(i){return i?.trim()||"default"}const x=new Set(["low","medium","high","xhigh","max"]),a=new Map;function w(i){const t=i?.trim();if(t){if(x.has(t))return t;throw new Error(`Unsupported Claude reasoning effort "${t}". Supported values: low, medium, high, xhigh, max.`)}}function R(){a.clear()}function C(){const i=p("claude");if(!i)return!1;const t=`${i.kind}:${i.path}:${i.command}:${i.args.join("\0")}`;if(a.has(t))return a.get(t)??!1;try{const e=E(i,["--help"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:3e3,env:m()}),s=`${e.stdout??""}
2
- ${e.stderr??""}`,o=/(?:^|\s)--effort(?:\s|,|<)/.test(s);return a.set(t,o),o}catch{return a.set(t,!1),!1}}class k extends g{options;type="claude";process=null;agentSessionId=null;sessionId=null;workDir=null;seq=0;runId="";hasEmittedText=!1;terminalState="open";constructor(t={}){super(),this.options=t}externalChannel=null;shennianSessionId=null;extraEnv={};configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.sessionId=t,this.workDir=e,this.seq=0,s&&(this.agentSessionId=s)}async send(t,e,s,o,u){await this.killProcess(),this.runId=d(),this.resetRunState();const n=["-p",t,"--output-format","stream-json","--verbose"],r=this.options.systemPrompt??c(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,u);r&&n.push("--append-system-prompt",r),this.options.hidden&&n.push("--name","Shennian Manager Substrate"),process.getuid?.()!==0&&n.push("--dangerously-skip-permissions"),n.push("--model",y(e));const l=w(s);l&&C()&&n.push("--effort",l),this.agentSessionId&&n.push("--resume",this.agentSessionId),this.spawnAndParse(n)}async resume(t){await this.killProcess(),this.agentSessionId=t,this.runId=d(),this.resetRunState();const e=["--resume",t,"--output-format","stream-json","--verbose"],s=this.options.systemPrompt??c(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0);s&&e.push("--append-system-prompt",s),this.options.hidden&&e.push("--name","Shennian Manager Substrate"),process.getuid?.()!==0&&e.push("--dangerously-skip-permissions"),this.spawnAndParse(e)}async stop(){await this.killProcess()}spawnAndParse(t){const e=p("claude");if(!e){this.emit("error",new Error('Command "claude" not found. Is Claude Code CLI installed?'));return}const s=S(e,t,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:m(this.extraEnv)});this.process=s,f({input:s.stdout}).on("line",n=>{if(n.trim())try{const r=JSON.parse(n);this.handleStreamEvent(r)}catch{}});let u="";s.stderr?.on("data",n=>{const r=n.toString();if(u+=r,this.terminalState==="open")for(const l of r.split(`
3
- `)){const h=l.trim();h&&this.emitEvent({state:"delta",text:h+`
1
+ import{createInterface as f}from"node:readline";import{randomUUID as h}from"node:crypto";import{AgentAdapter as g,registerAgent as S}from"./adapter.js";import{resolveBuiltinCommand as p,spawnAgentCommand as I,spawnResolvedCommandSync as E}from"./command-spec.js";import{buildAgentProcessEnv as m}from"../agent-env.js";import{buildPlatformInstructions as c}from"./platform-instructions.js";function x(i){return i?.trim()||"default"}const y=new Set(["low","medium","high","xhigh","max"]),a=new Map;function w(i){const t=i?.trim();if(t){if(y.has(t))return t;throw new Error(`Unsupported Claude reasoning effort "${t}". Supported values: low, medium, high, xhigh, max.`)}}function $(){a.clear()}function C(i){const t=i.trim();return t?!t.includes("claude.ai connectors are disabled because"):!1}function k(){const i=p("claude");if(!i)return!1;const t=`${i.kind}:${i.path}:${i.command}:${i.args.join("\0")}`;if(a.has(t))return a.get(t)??!1;try{const e=E(i,["--help"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:3e3,env:m()}),s=`${e.stdout??""}
2
+ ${e.stderr??""}`,o=/(?:^|\s)--effort(?:\s|,|<)/.test(s);return a.set(t,o),o}catch{return a.set(t,!1),!1}}class v extends g{options;type="claude";process=null;agentSessionId=null;sessionId=null;workDir=null;seq=0;runId="";hasEmittedText=!1;terminalState="open";constructor(t={}){super(),this.options=t}externalChannel=null;shennianSessionId=null;extraEnv={};configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.sessionId=t,this.workDir=e,this.seq=0,s&&(this.agentSessionId=s)}async send(t,e,s,o,u){await this.killProcess(),this.runId=h(),this.resetRunState();const n=["-p",t,"--output-format","stream-json","--verbose"],r=this.options.systemPrompt??c(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,u);r&&n.push("--append-system-prompt",r),this.options.hidden&&n.push("--name","Shennian Manager Substrate"),process.getuid?.()!==0&&n.push("--dangerously-skip-permissions"),n.push("--model",x(e));const l=w(s);l&&k()&&n.push("--effort",l),this.agentSessionId&&n.push("--resume",this.agentSessionId),this.spawnAndParse(n)}async resume(t){await this.killProcess(),this.agentSessionId=t,this.runId=h(),this.resetRunState();const e=["--resume",t,"--output-format","stream-json","--verbose"],s=this.options.systemPrompt??c(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0);s&&e.push("--append-system-prompt",s),this.options.hidden&&e.push("--name","Shennian Manager Substrate"),process.getuid?.()!==0&&e.push("--dangerously-skip-permissions"),this.spawnAndParse(e)}async stop(){await this.killProcess()}spawnAndParse(t){const e=p("claude");if(!e){this.emit("error",new Error('Command "claude" not found. Is Claude Code CLI installed?'));return}const s=I(e,t,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:m(this.extraEnv)});this.process=s,f({input:s.stdout}).on("line",n=>{if(n.trim())try{const r=JSON.parse(n);this.handleStreamEvent(r)}catch{}});let u="";s.stderr?.on("data",n=>{const r=n.toString();if(u+=r,this.terminalState==="open")for(const l of r.split(`
3
+ `)){const d=l.trim();C(d)&&this.emitEvent({state:"delta",text:d+`
4
4
  `})}}),s.on("close",n=>{this.process===s&&(this.process=null,this.handleProcessClose(n,u))}),s.on("error",n=>{this.process===s&&(this.process=null,n.code==="ENOENT"?this.emit("error",new Error('Command "claude" not found. Is Claude Code CLI installed?')):this.emit("error",n))})}handleStreamEvent(t){if(t.type==="system"&&t.subtype==="init"&&t.session_id){this.agentSessionId=t.session_id,this.emitEvent({state:"start",agentSessionId:this.agentSessionId});return}if(t.type==="system"&&t.subtype==="api_retry"&&t.error==="authentication_failed"){this.emitErrorIfOpen({state:"error",message:'Claude authentication failed. Run "claude auth login" and retry.'});return}if(t.type==="assistant"){if(t.message?.content){for(const e of t.message.content)if(e.type==="text"&&e.text){const s=this.hasEmittedText?`
5
5
 
6
6
  `:"";this.emitEvent({state:"delta",text:s+e.text}),this.hasEmittedText=!0}else e.type==="thinking"&&e.thinking?this.emitEvent({state:"delta",text:e.thinking,thinking:!0}):e.type==="tool_use"&&this.emitEvent({state:"tool-call",name:e.name,args:e.input});return}if(t.subtype==="text"&&t.text){const e=this.hasEmittedText?`
7
7
 
8
- `:"";this.emitEvent({state:"delta",text:e+t.text}),this.hasEmittedText=!0}else t.subtype==="thinking"&&t.thinking?this.emitEvent({state:"delta",text:t.thinking,thinking:!0}):t.subtype==="tool_use"&&this.emitEvent({state:"tool-call",name:t.name,args:t.input});return}if(t.type==="result")if(t.subtype==="tool_result"){const e=typeof t.content=="string"?t.content:JSON.stringify(t.content);this.emitEvent({state:"tool-result",name:t.name,result:e})}else if(t.subtype==="success"){t.session_id&&(this.agentSessionId=t.session_id);const e=t.usage??t.message?.usage;this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0,usage:e?{inputTokens:e.input_tokens,outputTokens:e.output_tokens}:void 0})}else t.subtype==="error"&&this.emitErrorIfOpen({state:"error",message:t.error??t.result??"unknown error"})}handleProcessClose(t,e){if(t!==0&&t!==null){const s=e.trim()||`claude exited with code ${t}`;this.emitErrorIfOpen({state:"error",message:s});return}this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0})}emitFinalIfOpen(t){this.terminalState==="open"&&(this.terminalState="final",this.emitEvent(t))}emitErrorIfOpen(t){this.terminalState==="open"&&(this.terminalState="error",this.emitEvent(t))}resetRunState(){this.seq=0,this.hasEmittedText=!1,this.terminalState="open"}emitEvent(t){const e={...t,runId:this.runId,seq:this.seq++};this.emit("agentEvent",e)}async killProcess(){const t=this.process;t&&(this.process=null,t.kill("SIGTERM"),await new Promise(e=>{t.on("close",e),setTimeout(()=>{t.kill("SIGKILL"),e()},3e3)}))}}I("claude",()=>new k);export{k as ClaudeAdapter,y as normalizeClaudeModelId,w as normalizeClaudeReasoningEffort,R as resetClaudeCapabilityCacheForTests,C as supportsClaudeReasoningEffort};
8
+ `:"";this.emitEvent({state:"delta",text:e+t.text}),this.hasEmittedText=!0}else t.subtype==="thinking"&&t.thinking?this.emitEvent({state:"delta",text:t.thinking,thinking:!0}):t.subtype==="tool_use"&&this.emitEvent({state:"tool-call",name:t.name,args:t.input});return}if(t.type==="result")if(t.subtype==="tool_result"){const e=typeof t.content=="string"?t.content:JSON.stringify(t.content);this.emitEvent({state:"tool-result",name:t.name,result:e})}else if(t.subtype==="success"){t.session_id&&(this.agentSessionId=t.session_id);const e=t.usage??t.message?.usage;this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0,usage:e?{inputTokens:e.input_tokens,outputTokens:e.output_tokens}:void 0})}else t.subtype==="error"&&this.emitErrorIfOpen({state:"error",message:t.error??t.result??"unknown error"})}handleProcessClose(t,e){if(t!==0&&t!==null){const s=e.trim()||`claude exited with code ${t}`;this.emitErrorIfOpen({state:"error",message:s});return}this.emitFinalIfOpen({state:"final",agentSessionId:this.agentSessionId??void 0})}emitFinalIfOpen(t){this.terminalState==="open"&&(this.terminalState="final",this.emitEvent(t))}emitErrorIfOpen(t){this.terminalState==="open"&&(this.terminalState="error",this.emitEvent(t))}resetRunState(){this.seq=0,this.hasEmittedText=!1,this.terminalState="open"}emitEvent(t){const e={...t,runId:this.runId,seq:this.seq++};this.emit("agentEvent",e)}async killProcess(){const t=this.process;t&&(this.process=null,t.kill("SIGTERM"),await new Promise(e=>{t.on("close",e),setTimeout(()=>{t.kill("SIGKILL"),e()},3e3)}))}}S("claude",()=>new v);export{v as ClaudeAdapter,x as normalizeClaudeModelId,w as normalizeClaudeReasoningEffort,$ as resetClaudeCapabilityCacheForTests,C as shouldForwardClaudeStderrLine,k as supportsClaudeReasoningEffort};
@@ -5,6 +5,14 @@ export { isCodexUnsupportedEffortError, isMissingCodexRolloutError, normalizeCod
5
5
  export declare function isCodexActiveWriterError(error: unknown): boolean;
6
6
  export declare function isCodexPaginatedHistoryUnsupportedError(error: unknown): boolean;
7
7
  export declare function isCodexExcludeTurnsUnsupportedError(error: unknown): boolean;
8
+ export declare function isCodexProjectApiUnsupportedError(error: unknown): boolean;
9
+ type CodexProject = {
10
+ id?: string;
11
+ roots?: Array<{
12
+ path?: string;
13
+ }>;
14
+ };
15
+ export declare function selectCodexProjectIdForWorkDir(projects: CodexProject[], workDir: string): string | undefined;
8
16
  export declare function buildCodexQueuedText(text: string, attachments?: ChatAttachmentMeta[]): string;
9
17
  export declare function buildCodexQueueArgs(threadId: string, text: string, attachments?: ChatAttachmentMeta[]): string[];
10
18
  export declare class CodexAdapter extends AgentAdapter {
@@ -58,6 +66,7 @@ export declare class CodexAdapter extends AgentAdapter {
58
66
  private spawnAppServer;
59
67
  private ensureAppServer;
60
68
  private initializeAppServer;
69
+ private resolveCodexProjectId;
61
70
  private startTurnWithRecovery;
62
71
  private startTurn;
63
72
  private interruptActiveTurn;
@@ -1,16 +1,16 @@
1
- import{spawnSync as C}from"node:child_process";import{createInterface as I}from"node:readline";import{randomUUID as _}from"node:crypto";import A from"node:path";import{AgentAdapter as R,registerAgent as P}from"./adapter.js";import{resolveBuiltinCommand as g,spawnAgentCommand as v}from"./command-spec.js";import{buildAgentProcessEnv as x}from"../agent-env.js";import{ensurePlatformInstructionsFile as q}from"./platform-instructions.js";import{CODEX_APP_SERVER_CLIENT_INFO as O,extractAppServerErrorMessage as $,formatCodexErrorMessage as b,formatTransientCodexStatus as L,isCodexCollabAgentItem as F,isCodexCollabAgentToolName as f,isCodexLegacyCollabAgentItem as M,isCodexUnsupportedEffortError as U,isMissingCodexRolloutError as N,isTransientCodexErrorMessage as D,looksLikeCodexInteractiveAuthPrompt as W,looksLikeFatalCodexStderr as z,makeThreadTitle as B,normalizeCodexModelId as S,normalizeCodexReasoningEffort as G,normalizeCodexStderr as T,normalizeTerminalText as J,safeStringify as w,stripGitDirectiveArtifacts as H}from"./codex-utils.js";import{isCodexUnsupportedEffortError as me,isMissingCodexRolloutError as fe,normalizeCodexModelId as ge,normalizeCodexReasoningEffort as ve}from"./codex-utils.js";function V(a){const e=a instanceof Error?a.message:String(a);return/already has an active writer|thread-store conflict/i.test(e)}function Q(a){const e=a instanceof Error?a.message:String(a);return/paginated(?:_threads|\s+(?:thread\s+)?history)?.*(?:not supported|unsupported|unavailable)/i.test(e)||/(?:not supported|unsupported|unavailable).*paginated(?:_threads|\s+(?:thread\s+)?history)?/i.test(e)}function K(a){const e=a instanceof Error?a.message:String(a);return/unknown field [`'"]?excludeTurns/i.test(e)||/excludeTurns.*(?:not supported|unsupported|unavailable)/i.test(e)}function X(a,e){const t=e?.flatMap(r=>Y(r)).filter(r=>!/^https?:\/\//i.test(r.path)).filter(r=>r.path);return{type:"text",text:j(a,e),text_elements:[],...t?.length?{local_images:t}:{}}}function Y(a){if(a.kind==="image")return a.previewData?[{path:a.path,data:a.previewData,mimeType:a.mimeType}]:[{path:a.path}];if(a.mimeType.startsWith("video/")){const e=Z(a.path);return e?[{path:e}]:[]}return[]}function Z(a){if(!a||/^https?:\/\//i.test(a))return null;const e=A.extname(a),s=`${e?a.slice(0,-e.length):a}.preview.png`;return C("ffmpeg",["-y","-ss","0","-i",a,"-frames:v","1","-vf","scale=320:-1",s],{stdio:"ignore",timeout:15e3}).status===0?s:null}function j(a,e){const t=e?.filter(i=>i.kind!=="image").filter(i=>i.path&&!/^https?:\/\//i.test(i.path));if(!t?.length||t.every(i=>a.includes(i.path)))return a;const r=t.map((i,n)=>{const o=i.name||`attachment-${n+1}`,l=i.mimeType?` (${i.mimeType})`:"";return`[${k(o)}${l}](<${i.path}>)`});return[a,"",...r].join(`
2
- `)}function ee(a,e){const t=e?.filter(r=>r.path&&!/^https?:\/\//i.test(r.path)&&!a.includes(r.path));if(!t?.length)return a;const s=t.map((r,i)=>{const n=k(r.name||`attachment-${i+1}`);return r.kind==="image"?`![${n}](<${r.path}>)`:`[${n}](<${r.path}>)`});return[a,"",...s].join(`
3
- `)}function te(a,e,t){return["queue","--thread",a,"--message",ee(e,t)]}function k(a){return a.replace(/[[\]\\]/g,"\\$&")}class se extends R{options;type="codex";process=null;workDir=null;seq=0;runId="";pendingUsage;agentSessionId=null;hasEmittedText=!1;textTail="";terminalState="open";forceCloseTimer=null;stderrBuf="";rpcSeq=1;pendingRequests=new Map;appServerReady=null;appServerStartupError=null;activeTurnId=null;namedThread=!1;deltaItemIds=new Set;lastTransientStatus="";agentSystemPrompt="";constructor(e={}){super(),this.options=e}externalChannel=null;shennianSessionId=null;extraEnv={};configure(e){this.shennianSessionId=e.sessionId??null,this.externalChannel=e.externalChannel??null,this.extraEnv=e.env??{}}async start(e,t,s){this.workDir=t,this.seq=0,s&&(this.agentSessionId=s)}async send(e,t,s,r,i){this.activeTurnId&&(await this.interruptActiveTurn().catch(()=>{}),await this.killProcess());const n=S(t),o=G(s),l=i?.trim()??"";l!==this.agentSystemPrompt&&(this.agentSystemPrompt=l,this.process&&await this.killProcess()),this.runId=_(),this.seq=0,this.resetRunState();try{await this.ensureAppServer(n)}catch(c){if(!this.agentSessionId||!V(c))throw c;return{deliveryMode:"external_owner_queue",queuedSubmissionId:await this.enqueueForExternalOwner(this.agentSessionId,e,r)}}const u=this.agentSessionId;if(!u)throw new Error("codex app-server did not create a thread");this.emitEvent({state:"start",agentSessionId:u}),this.namedThread||(await this.sendRpc("thread/name/set",{threadId:u,name:B(e)}).catch(()=>{}),this.namedThread=!0);const p=await this.startTurnWithRecovery(u,e,n,o,r);return this.activeTurnId=p.turn?.id??null,{deliveryMode:"direct"}}async enqueueForExternalOwner(e,t,s){const r=g("codex");if(!r)throw new Error('Command "codex" not found. Is OpenAI Codex CLI installed?');const i=te(e,t,s),n=v(r,i,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:x({NO_COLOR:"1",...this.extraEnv})});return await new Promise((o,l)=>{let u="",p="",c=!1;const h=(d,m)=>{c||(c=!0,clearTimeout(y),d?l(d):o(m))},y=setTimeout(()=>{n.kill("SIGTERM"),h(new Error("Codex Desktop message queue timed out"))},6e4);y.unref?.(),n.stdout?.on("data",d=>{u+=d.toString()}),n.stderr?.on("data",d=>{p+=d.toString()}),n.once("error",d=>h(d)),n.once("close",d=>{const m=`${u}
4
- ${p}`.trim();if(d!==0){h(new Error(m||`codex queue exited with code ${d??"unknown"}`));return}const E=m.match(/Queued message\s+([^\s]+)\s+for thread/i)?.[1];h(void 0,E)})})}async resume(e){await this.killProcess(),this.agentSessionId=e,this.namedThread=!0,this.resetTextState()}async setTitle(e,t,s){const r=e.trim(),i=t.replace(/\s+/g," ").trim();!r||!i||(this.agentSessionId=r,s?.trim()&&(this.workDir=s),await this.ensureAppServer(),await this.sendRpc("thread/name/set",{threadId:r,name:i}),this.namedThread=!0)}async stop(){await this.interruptActiveTurn().catch(()=>{}),await this.killProcess()}async getStatus(){const e=this.agentSessionId,t=this.activeTurnId;if(!e||!this.process)return{active:!1,runId:t,runPhase:null,canStop:!1};let s=null;try{s=(await this.sendRpc("thread/read",{threadId:e,includeTurns:!1},5e3)).thread?.status??null}catch{}const r=s?.type==="active"||!!t;return{active:r,runId:t,runPhase:r?this.mapThreadStatusToRunPhase(s):null,canStop:!!(r&&t&&this.process)}}spawnCodex(e){const t=g("codex");if(!t){this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));return}const s=v(t,e,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:x(this.extraEnv)});this.process=s,I({input:s.stdout}).on("line",n=>{if(n.trim())try{const o=JSON.parse(n);this.handleStreamEvent(o)}catch{this.emitEvent({state:"delta",text:n})}});let i="";s.stderr?.on("data",n=>{i+=n.toString()}),s.on("close",n=>{this.process===s&&(this.process=null,this.clearForceCloseTimer(),this.handleProcessClose(n,i))}),s.on("error",n=>{this.process===s&&(this.process=null,n.code==="ENOENT"?this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?')):this.emit("error",n))})}spawnAppServer(){const e=g("codex");if(!e){this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));return}const t=["app-server","--listen","stdio://"],s=this.options.modelInstructionsFile??q(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,this.agentSystemPrompt);s&&t.push("-c",`model_instructions_file=${JSON.stringify(s)}`);const r=v(e,t,{cwd:this.workDir??void 0,stdio:["pipe","pipe","pipe"],env:x({NO_COLOR:"1",...this.extraEnv})});this.process=r,this.stderrBuf="",this.appServerStartupError=null,I({input:r.stdout}).on("line",n=>{if(!n.trim())return;let o;try{o=JSON.parse(n)}catch{this.handleAppServerNonJsonStdout(n);return}this.handleAppServerMessage(o)}),r.stderr?.on("data",n=>{this.stderrBuf+=n.toString()}),r.on("close",n=>{if(this.process!==r)return;const o=this.activeTurnId!=null;this.process=null,this.appServerReady=null,this.activeTurnId=null,this.rejectAllPending(new Error(T(this.stderrBuf)||`codex app-server exited with code ${n}`)),this.terminalState==="open"&&o&&this.handleProcessClose(n,this.stderrBuf)}),r.on("error",n=>{this.process===r&&(this.process=null,this.rejectAllPending(n),n.code==="ENOENT"?this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?')):this.emit("error",n))})}async ensureAppServer(e){return this.appServerReady?this.appServerReady:(this.spawnAppServer(),this.appServerReady=this.initializeAppServer(e).catch(async t=>{throw this.appServerReady=null,await this.killProcess(),t}),this.appServerReady)}async initializeAppServer(e){const t=S(e);if(await this.sendRpc("initialize",{clientInfo:O,capabilities:{experimentalApi:!0}}),this.agentSessionId){const n={threadId:this.agentSessionId,cwd:this.workDir,approvalPolicy:"never",sandbox:"danger-full-access",persistExtendedHistory:!0,...this.options.hidden?{threadSource:"subagent"}:{},...t?{model:t}:{}};let o;try{o=await this.sendRpc("thread/resume",{...n,excludeTurns:!0})}catch(l){if(!K(l))throw l;o=await this.sendRpc("thread/resume",n)}this.agentSessionId=o.thread?.id??this.agentSessionId,this.namedThread=!!o.thread?.name;return}const s={cwd:this.workDir,approvalPolicy:"never",sandbox:"danger-full-access",serviceName:"Shennian",threadSource:this.options.hidden?"subagent":"user",experimentalRawEvents:!1,persistExtendedHistory:!0,...t?{model:t}:{}};let r;if(this.options.hidden)r=await this.sendRpc("thread/start",s);else try{r=await this.sendRpc("thread/start",{...s,historyMode:"paginated"})}catch(n){throw Q(n)?new Error("\u5F53\u524D Codex CLI \u4E0D\u652F\u6301\u521B\u5EFA\u53EF\u5728 Codex Desktop \u4E2D\u7EE7\u7EED\u7684\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u624B\u52A8\u5347\u7EA7 Codex CLI \u540E\u91CD\u8BD5\u3002\u795E\u5FF5\u4E0D\u4F1A\u81EA\u52A8\u5347\u7EA7\uFF0C\u4E5F\u4E0D\u4F1A\u964D\u7EA7\u521B\u5EFA\u4E0D\u53EF\u89C1\u7684 legacy \u4F1A\u8BDD\u3002",{cause:n}):n}const i=r.thread?.id;if(!i)throw new Error("codex app-server thread/start returned no thread id");this.agentSessionId=i,this.namedThread=!!r.thread?.name}async startTurnWithRecovery(e,t,s,r,i){try{return await this.startTurn(e,t,s,r,i)}catch(n){if(!N(n))throw n;return await this.killProcess(),await this.ensureAppServer(s),await this.startTurn(e,t,s,r,i)}}async startTurn(e,t,s,r,i){try{return await this.sendRpc("turn/start",{threadId:e,input:[X(t,i)],approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"},...s?{model:s}:{},...r?{effort:r}:{}})}catch(n){throw r&&U(n)?new Error(`Codex app-server does not accept reasoning effort "${r}" for this turn. Refresh models or upgrade Codex CLI, then retry.`,{cause:n}):n}}async interruptActiveTurn(){const e=this.agentSessionId,t=this.activeTurnId;!e||!t||!this.process||(await this.sendRpc("turn/interrupt",{threadId:e,turnId:t},5e3),this.activeTurnId=null)}sendRpc(e,t,s=6e4){if(this.appServerStartupError)return Promise.reject(this.appServerStartupError);const r=this.process;if(!r?.stdin)return Promise.reject(new Error("codex app-server is not running"));const i=this.rpcSeq++,n=JSON.stringify({id:i,method:e,params:t});return new Promise((o,l)=>{const u=setTimeout(()=>{this.pendingRequests.delete(i),l(new Error(`codex app-server request timed out: ${e}`))},s);this.pendingRequests.set(i,{resolve:o,reject:l,timer:u}),r.stdin.write(`${n}
5
- `,p=>{p&&(clearTimeout(u),this.pendingRequests.delete(i),l(p))})})}handleAppServerMessage(e){if(e.id!=null){const s=this.pendingRequests.get(e.id);s&&(clearTimeout(s.timer),this.pendingRequests.delete(e.id),e.error?s.reject(new Error(e.error.message||`codex app-server error ${e.error.code??""}`.trim())):s.resolve(e.result))}if(!e.method)return;const t=e.params??{};switch(e.method){case"turn/started":{const s=typeof t.turn=="object"&&t.turn!==null?t.turn:null,r=typeof s?.id=="string"?s.id:null;r&&(this.activeTurnId=r);break}case"thread/status/changed":{const s=typeof t.threadId=="string"?t.threadId:"";if(s&&this.agentSessionId&&s!==this.agentSessionId)break;const r=typeof t.status=="object"&&t.status!==null?t.status:null;r?.type==="active"&&this.emitEvent({state:"heartbeat",runPhase:this.mapThreadStatusToRunPhase(r)});break}case"item/agentMessage/delta":{const s=typeof t.itemId=="string"?t.itemId:"";s&&this.deltaItemIds.add(s),typeof t.delta=="string"&&this.emitText(t.delta);break}case"item/completed":this.handleAppServerCompletedItem(t);break;case"thread/tokenUsage/updated":this.handleAppServerUsage(t);break;case"turn/completed":{const s=typeof t.turn=="object"&&t.turn!==null?t.turn:null,r=typeof s?.id=="string"?s.id:null;(!this.activeTurnId||r===this.activeTurnId)&&(this.activeTurnId=null,this.emitFinalIfOpen());break}case"error":{const s=$(t);if(D(s)){this.emitTransientStatus(s);return}this.emitErrorIfOpen(s);break}}}mapThreadStatusToRunPhase(e){const t=e?.type==="active"&&Array.isArray(e.activeFlags)?e.activeFlags:[];return t.includes("waitingOnApproval")?"waiting_approval":t.includes("waitingOnUserInput")?"waiting_user_input":"thinking"}handleAppServerNonJsonStdout(e){const t=J(e);W(t)&&this.failAppServerStartup(new Error("Codex \u672A\u767B\u5F55\u3002\u8BF7\u5148\u5728\u8FD9\u53F0\u7535\u8111\u7684\u7EC8\u7AEF\u8FD0\u884C `codex`\uFF0C\u6309\u63D0\u793A\u5B8C\u6210 ChatGPT \u767B\u5F55\u6216\u914D\u7F6E API key\uFF0C\u7136\u540E\u518D\u56DE\u5230\u795E\u5FF5\u53D1\u9001\u6D88\u606F\u3002"))}failAppServerStartup(e){this.appServerStartupError||(this.appServerStartupError=e,this.rejectAllPending(e),this.process?.kill("SIGTERM"))}handleAppServerCompletedItem(e){const t=typeof e.item=="object"&&e.item!==null?e.item:null;if(!(!t||typeof t.type!="string")&&!F(t))switch(t.type){case"agentMessage":{const s=typeof t.id=="string"?t.id:"";if(s&&this.deltaItemIds.has(s))return;typeof t.text=="string"&&this.emitText(t.text,"block");break}case"commandExecution":{const s=typeof t.command=="string"?t.command:"",r=typeof t.aggregatedOutput=="string"?t.aggregatedOutput:"";s&&this.emitEvent({state:"tool-call",name:"command_execution",args:{command:s}}),this.emitEvent({state:"tool-result",name:"command_execution",result:[r,t.exitCode!=null?`
6
- (exit ${t.exitCode})`:""].join("").trim()});break}case"mcpToolCall":case"dynamicToolCall":{const s=typeof t.tool=="string"?t.tool:t.type;if(f(s))return;const r=typeof t.arguments=="object"&&t.arguments!==null?t.arguments:{};this.emitEvent({state:"tool-call",name:s,args:r}),this.emitEvent({state:"tool-result",name:s,result:w(t.error??t.result??t.contentItems??"")});break}case"fileChange":break;case"approvalRequest":case"approval_request":case"permissionRequest":case"permission_request":case"userInputRequired":case"user_input_required":{this.emitApprovalPending(t);break}}}handleAppServerUsage(e){const t=typeof e.tokenUsage=="object"&&e.tokenUsage!==null?e.tokenUsage:null,s=typeof t?.last=="object"&&t.last!==null?t.last:null,r=typeof t?.total=="object"&&t.total!==null?t.total:null,i=s??r;if(!i)return;const n=typeof i.inputTokens=="number"?i.inputTokens:void 0,o=typeof i.outputTokens=="number"?i.outputTokens:void 0;(n!=null||o!=null)&&(this.pendingUsage={inputTokens:n??0,outputTokens:o??0})}handleCodexItemLine(e){const t=e.item;if(t?.type&&!M(t))switch(t.type){case"agent_message":case"reasoning":{e.type==="item.completed"&&t.text&&this.emitText(t.text,"block");break}case"command_execution":{if(e.type==="item.started"&&t.command&&this.emitEvent({state:"tool-call",name:"command_execution",args:{command:t.command}}),e.type==="item.completed"){const s=[t.aggregated_output??"",t.exit_code!=null?`
7
- (exit ${t.exit_code})`:""];this.emitEvent({state:"tool-result",name:"command_execution",result:s.join("").trim()||String(t.status??"")})}break}case"mcp_tool_call":{if(t.tool&&f(t.tool))return;if(e.type==="item.started"&&this.emitEvent({state:"tool-call",name:t.tool??"mcp_tool",args:{server:t.server,...t.arguments&&typeof t.arguments=="object"?t.arguments:{}}}),e.type==="item.completed"){const s=t.error&&typeof t.error=="object"?t.error.message:void 0;this.emitEvent({state:"tool-result",name:t.tool??"mcp_tool",result:s??w(t.result)})}break}case"file_change":break;case"web_search":{e.type==="item.completed"&&t.query&&this.emitText(`[web_search] ${t.query}`,"block");break}case"todo_list":{if(e.type==="item.completed"&&t.items?.length){const s=t.items.map(r=>`- [${r.completed?"x":" "}] ${r.text}`).join(`
8
- `);this.emitText(s,"block")}break}case"approval_request":case"approvalRequest":case"permission_request":case"permissionRequest":case"user_input_required":case"userInputRequired":{(e.type==="item.started"||e.type==="item.completed")&&this.emitApprovalPending(t);break}case"error":{e.type==="item.completed"&&t.message&&this.emitEvent({state:"error",message:t.message});break}default:break}}handleStreamEvent(e){const t=e.type??e.event;switch(t?.startsWith("item.")&&this.handleCodexItemLine(e),t){case"turn.completed":{const r=e.usage;if(r){const i=r.input_tokens??r.prompt_tokens,n=r.output_tokens??r.completion_tokens;(i!=null||n!=null)&&(this.pendingUsage={inputTokens:i??0,outputTokens:n??0})}this.emitFinalIfOpen();return}case"turn.failed":{const r=typeof e.error=="object"&&e.error?.message?e.error.message:typeof e.error=="string"?e.error:"turn failed";this.emitErrorIfOpen(r);return}case"error":{const r=typeof e.message=="string"?e.message:"";if(r.includes("Reconnecting"))return;this.emitErrorIfOpen(r||(typeof e.error=="string"?e.error:"stream error"));return}case"thread.started":{const r=e.thread_id??e.session_id??e.id;typeof r=="string"&&r&&(this.agentSessionId=r,this.emitEvent({state:"start",agentSessionId:this.agentSessionId}));return}case"turn.started":return}if(t?.startsWith("item."))return;switch(e.type??e.event){case"message":case"text":case"content":{const r=e.content??e.text;r&&this.emitText(r);break}case"function_call":case"tool_call":{if(this.isApprovalLikeName(e.name)){this.emitApprovalPending(e);break}if(e.name&&f(e.name))return;this.emitEvent({state:"tool-call",name:e.name,args:e.arguments??e.input});break}case"function_call_output":case"tool_result":{if(e.name&&f(e.name))return;this.emitEvent({state:"tool-result",name:e.name,result:e.output??e.result});break}case"approval_request":case"approvalRequest":case"permission_request":case"permissionRequest":case"user_input_required":case"userInputRequired":{this.emitApprovalPending(e);break}case"error":break;case"done":case"completed":{e.usage&&(this.pendingUsage={inputTokens:e.usage.prompt_tokens??e.usage.input_tokens??0,outputTokens:e.usage.completion_tokens??e.usage.output_tokens??0}),this.emitFinalIfOpen();break}}}emitEvent(e){if(this.terminalState!=="open"&&e.state!=="final"&&e.state!=="error"&&e.state!=="aborted")return;const t={...e,runId:this.runId,seq:this.seq++};this.emit("agentEvent",t)}isApprovalLikeName(e){return typeof e!="string"?!1:/approval|permission|confirm|user[_-]?input|request[_-]?user/i.test(e)}emitApprovalPending(e){const t=typeof e.command=="string"?e.command:"",s=typeof e.title=="string"&&e.title.trim()?e.title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",r=typeof e.prompt=="string"?e.prompt:typeof e.reason=="string"?e.reason:typeof e.message=="string"?e.message:t?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${t}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";this.emitEvent({state:"approval-pending",approval:{title:s,content:r,source:"codex",actionHint:"\u5F53\u524D\u795E\u5FF5\u6682\u4E0D\u652F\u6301\u8FDC\u7A0B\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230\u8FD0\u884C Codex \u7684\u7535\u8111/\u7EC8\u7AEF\u5B8C\u6210\u786E\u8BA4\u3002"}})}async killProcess(){const e=this.process;if(this.appServerReady=null,this.activeTurnId=null,!e){this.rejectAllPending(new Error("codex app-server stopped"));return}this.process=null,this.clearForceCloseTimer(),e.kill("SIGTERM"),await new Promise(t=>{e.on("close",t),setTimeout(()=>{e.kill("SIGKILL"),t()},3e3)}),this.rejectAllPending(new Error("codex app-server stopped"))}rejectAllPending(e){for(const[t,s]of this.pendingRequests.entries())clearTimeout(s.timer),s.reject(e),this.pendingRequests.delete(t)}handleProcessClose(e,t){const s=T(t);if(e!==0&&e!==null){const r=s||`codex exited with code ${e}`;this.emitErrorIfOpen(r)}else z(s)?this.emitErrorIfOpen(s):this.emitFinalIfOpen();this.pendingUsage=void 0}emitFinalIfOpen(){this.terminalState==="open"&&(this.terminalState="final",this.emitEvent({state:"final",usage:this.pendingUsage,agentSessionId:this.agentSessionId??void 0}),this.killProcess().catch(()=>{}))}emitErrorIfOpen(e){this.terminalState==="open"&&(this.terminalState="error",this.emitEvent({state:"error",message:b(e)}),this.scheduleProcessClose())}resetRunState(){this.pendingUsage=void 0,this.terminalState="open",this.deltaItemIds.clear(),this.lastTransientStatus="",this.clearForceCloseTimer(),this.resetTextState()}emitTransientStatus(e){const t=L(e);!t||t===this.lastTransientStatus||this.terminalState!=="open"||(this.lastTransientStatus=t,this.emitEvent({state:"delta",text:`${t}
9
- `,thinking:!0}))}resetTextState(){this.hasEmittedText=!1,this.textTail=""}emitText(e,t="delta"){if(!e)return;let s=H(e);s&&(t==="block"&&this.hasEmittedText&&!s.startsWith(`
1
+ import{spawnSync as _}from"node:child_process";import{createInterface as S}from"node:readline";import{createHash as A,randomUUID as R}from"node:crypto";import p from"node:path";import{AgentAdapter as P,registerAgent as q}from"./adapter.js";import{resolveBuiltinCommand as v,spawnAgentCommand as x}from"./command-spec.js";import{buildAgentProcessEnv as I}from"../agent-env.js";import{ensurePlatformInstructionsFile as O}from"./platform-instructions.js";import{CODEX_APP_SERVER_CLIENT_INFO as b,extractAppServerErrorMessage as $,formatCodexErrorMessage as L,formatTransientCodexStatus as D,isCodexCollabAgentItem as F,isCodexCollabAgentToolName as g,isCodexLegacyCollabAgentItem as M,isCodexUnsupportedEffortError as U,isMissingCodexRolloutError as N,isTransientCodexErrorMessage as W,looksLikeCodexInteractiveAuthPrompt as z,looksLikeFatalCodexStderr as B,makeThreadTitle as G,normalizeCodexModelId as T,normalizeCodexReasoningEffort as H,normalizeCodexStderr as w,normalizeTerminalText as J,safeStringify as k,stripGitDirectiveArtifacts as V}from"./codex-utils.js";import{isCodexUnsupportedEffortError as ve,isMissingCodexRolloutError as xe,normalizeCodexModelId as Ie,normalizeCodexReasoningEffort as ye}from"./codex-utils.js";function K(o){const e=o instanceof Error?o.message:String(o);return/already has an active writer|thread-store conflict/i.test(e)}function Q(o){const e=o instanceof Error?o.message:String(o);return/paginated(?:_threads|\s+(?:thread\s+)?history)?.*(?:not supported|unsupported|unavailable)/i.test(e)||/(?:not supported|unsupported|unavailable).*paginated(?:_threads|\s+(?:thread\s+)?history)?/i.test(e)}function X(o){const e=o instanceof Error?o.message:String(o);return/unknown field [`'"]?excludeTurns/i.test(e)||/excludeTurns.*(?:not supported|unsupported|unavailable)/i.test(e)}function Y(o){const e=o instanceof Error?o.message:String(o);return/(?:method not found|unknown method).*(?:project\/list|project\/create)/i.test(e)||/(?:project\/list|project\/create).*(?:not supported|unsupported|unavailable)/i.test(e)}function Z(o,e){const t=p.resolve(e);let s;for(const r of o)if(r.id)for(const i of r.roots??[]){if(!i.path)continue;const n=p.resolve(i.path),a=p.relative(n,t);!(a===""||!a.startsWith("..")&&!p.isAbsolute(a))||n.length<=(s?.rootLength??-1)||(s={id:r.id,rootLength:n.length})}return s?.id}function j(o,e){const t=e?.flatMap(r=>ee(r)).filter(r=>!/^https?:\/\//i.test(r.path)).filter(r=>r.path);return{type:"text",text:se(o,e),text_elements:[],...t?.length?{local_images:t}:{}}}function ee(o){if(o.kind==="image")return o.previewData?[{path:o.path,data:o.previewData,mimeType:o.mimeType}]:[{path:o.path}];if(o.mimeType.startsWith("video/")){const e=te(o.path);return e?[{path:e}]:[]}return[]}function te(o){if(!o||/^https?:\/\//i.test(o))return null;const e=p.extname(o),s=`${e?o.slice(0,-e.length):o}.preview.png`;return _("ffmpeg",["-y","-ss","0","-i",o,"-frames:v","1","-vf","scale=320:-1",s],{stdio:"ignore",timeout:15e3}).status===0?s:null}function se(o,e){const t=e?.filter(i=>i.kind!=="image").filter(i=>i.path&&!/^https?:\/\//i.test(i.path));if(!t?.length||t.every(i=>o.includes(i.path)))return o;const r=t.map((i,n)=>{const a=i.name||`attachment-${n+1}`,d=i.mimeType?` (${i.mimeType})`:"";return`[${C(a)}${d}](<${i.path}>)`});return[o,"",...r].join(`
2
+ `)}function re(o,e){const t=e?.filter(r=>r.path&&!/^https?:\/\//i.test(r.path)&&!o.includes(r.path));if(!t?.length)return o;const s=t.map((r,i)=>{const n=C(r.name||`attachment-${i+1}`);return r.kind==="image"?`![${n}](<${r.path}>)`:`[${n}](<${r.path}>)`});return[o,"",...s].join(`
3
+ `)}function ne(o,e,t){return["queue","--thread",o,"--message",re(e,t)]}function C(o){return o.replace(/[[\]\\]/g,"\\$&")}class ie extends P{options;type="codex";process=null;workDir=null;seq=0;runId="";pendingUsage;agentSessionId=null;hasEmittedText=!1;textTail="";terminalState="open";forceCloseTimer=null;stderrBuf="";rpcSeq=1;pendingRequests=new Map;appServerReady=null;appServerStartupError=null;activeTurnId=null;namedThread=!1;deltaItemIds=new Set;lastTransientStatus="";agentSystemPrompt="";constructor(e={}){super(),this.options=e}externalChannel=null;shennianSessionId=null;extraEnv={};configure(e){this.shennianSessionId=e.sessionId??null,this.externalChannel=e.externalChannel??null,this.extraEnv=e.env??{}}async start(e,t,s){this.workDir=t,this.seq=0,s&&(this.agentSessionId=s)}async send(e,t,s,r,i){this.activeTurnId&&(await this.interruptActiveTurn().catch(()=>{}),await this.killProcess());const n=T(t),a=H(s),d=i?.trim()??"";d!==this.agentSystemPrompt&&(this.agentSystemPrompt=d,this.process&&await this.killProcess()),this.runId=R(),this.seq=0,this.resetRunState();try{await this.ensureAppServer(n)}catch(h){if(!this.agentSessionId||!K(h))throw h;return{deliveryMode:"external_owner_queue",queuedSubmissionId:await this.enqueueForExternalOwner(this.agentSessionId,e,r)}}const l=this.agentSessionId;if(!l)throw new Error("codex app-server did not create a thread");this.emitEvent({state:"start",agentSessionId:l}),this.namedThread||(await this.sendRpc("thread/name/set",{threadId:l,name:G(e)}).catch(()=>{}),this.namedThread=!0);const u=await this.startTurnWithRecovery(l,e,n,a,r);return this.activeTurnId=u.turn?.id??null,{deliveryMode:"direct"}}async enqueueForExternalOwner(e,t,s){const r=v("codex");if(!r)throw new Error('Command "codex" not found. Is OpenAI Codex CLI installed?');const i=ne(e,t,s),n=x(r,i,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:I({NO_COLOR:"1",...this.extraEnv})});return await new Promise((a,d)=>{let l="",u="",h=!1;const m=(c,f)=>{h||(h=!0,clearTimeout(y),c?d(c):a(f))},y=setTimeout(()=>{n.kill("SIGTERM"),m(new Error("Codex Desktop message queue timed out"))},6e4);y.unref?.(),n.stdout?.on("data",c=>{l+=c.toString()}),n.stderr?.on("data",c=>{u+=c.toString()}),n.once("error",c=>m(c)),n.once("close",c=>{const f=`${l}
4
+ ${u}`.trim();if(c!==0){m(new Error(f||`codex queue exited with code ${c??"unknown"}`));return}const E=f.match(/Queued message\s+([^\s]+)\s+for thread/i)?.[1];m(void 0,E)})})}async resume(e){await this.killProcess(),this.agentSessionId=e,this.namedThread=!0,this.resetTextState()}async setTitle(e,t,s){const r=e.trim(),i=t.replace(/\s+/g," ").trim();!r||!i||(this.agentSessionId=r,s?.trim()&&(this.workDir=s),await this.ensureAppServer(),await this.sendRpc("thread/name/set",{threadId:r,name:i}),this.namedThread=!0)}async stop(){await this.interruptActiveTurn().catch(()=>{}),await this.killProcess()}async getStatus(){const e=this.agentSessionId,t=this.activeTurnId;if(!e||!this.process)return{active:!1,runId:t,runPhase:null,canStop:!1};let s=null;try{s=(await this.sendRpc("thread/read",{threadId:e,includeTurns:!1},5e3)).thread?.status??null}catch{}const r=s?.type==="active"||!!t;return{active:r,runId:t,runPhase:r?this.mapThreadStatusToRunPhase(s):null,canStop:!!(r&&t&&this.process)}}spawnCodex(e){const t=v("codex");if(!t){this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));return}const s=x(t,e,{cwd:this.workDir??void 0,stdio:["ignore","pipe","pipe"],env:I(this.extraEnv)});this.process=s,S({input:s.stdout}).on("line",n=>{if(n.trim())try{const a=JSON.parse(n);this.handleStreamEvent(a)}catch{this.emitEvent({state:"delta",text:n})}});let i="";s.stderr?.on("data",n=>{i+=n.toString()}),s.on("close",n=>{this.process===s&&(this.process=null,this.clearForceCloseTimer(),this.handleProcessClose(n,i))}),s.on("error",n=>{this.process===s&&(this.process=null,n.code==="ENOENT"?this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?')):this.emit("error",n))})}spawnAppServer(){const e=v("codex");if(!e){this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?'));return}const t=["app-server","--listen","stdio://"],s=this.options.modelInstructionsFile??O(this.workDir??process.cwd(),this.externalChannel,this.shennianSessionId??void 0,this.agentSystemPrompt);s&&t.push("-c",`model_instructions_file=${JSON.stringify(s)}`);const r=x(e,t,{cwd:this.workDir??void 0,stdio:["pipe","pipe","pipe"],env:I({NO_COLOR:"1",...this.extraEnv})});this.process=r,this.stderrBuf="",this.appServerStartupError=null,S({input:r.stdout}).on("line",n=>{if(!n.trim())return;let a;try{a=JSON.parse(n)}catch{this.handleAppServerNonJsonStdout(n);return}this.handleAppServerMessage(a)}),r.stderr?.on("data",n=>{this.stderrBuf+=n.toString()}),r.on("close",n=>{if(this.process!==r)return;const a=this.activeTurnId!=null;this.process=null,this.appServerReady=null,this.activeTurnId=null,this.rejectAllPending(new Error(w(this.stderrBuf)||`codex app-server exited with code ${n}`)),this.terminalState==="open"&&a&&this.handleProcessClose(n,this.stderrBuf)}),r.on("error",n=>{this.process===r&&(this.process=null,this.rejectAllPending(n),n.code==="ENOENT"?this.emit("error",new Error('Command "codex" not found. Is OpenAI Codex CLI installed?')):this.emit("error",n))})}async ensureAppServer(e){return this.appServerReady?this.appServerReady:(this.spawnAppServer(),this.appServerReady=this.initializeAppServer(e).catch(async t=>{throw this.appServerReady=null,await this.killProcess(),t}),this.appServerReady)}async initializeAppServer(e){const t=T(e);if(await this.sendRpc("initialize",{clientInfo:b,capabilities:{experimentalApi:!0}}),this.agentSessionId){const a={threadId:this.agentSessionId,cwd:this.workDir,approvalPolicy:"never",sandbox:"danger-full-access",persistExtendedHistory:!0,...this.options.hidden?{threadSource:"subagent"}:{},...t?{model:t}:{}};let d;try{d=await this.sendRpc("thread/resume",{...a,excludeTurns:!0})}catch(l){if(!X(l))throw l;d=await this.sendRpc("thread/resume",a)}this.agentSessionId=d.thread?.id??this.agentSessionId,this.namedThread=!!d.thread?.name;return}const s=this.options.hidden?void 0:await this.resolveCodexProjectId(),r={cwd:this.workDir,approvalPolicy:"never",sandbox:"danger-full-access",serviceName:"Shennian",threadSource:this.options.hidden?"subagent":"user",experimentalRawEvents:!1,persistExtendedHistory:!0,...s?{projectId:s}:{},...t?{model:t}:{}};let i;if(this.options.hidden)i=await this.sendRpc("thread/start",r);else try{i=await this.sendRpc("thread/start",{...r,historyMode:"paginated"})}catch(a){throw Q(a)?new Error("\u5F53\u524D Codex CLI \u4E0D\u652F\u6301\u521B\u5EFA\u53EF\u5728 Codex Desktop \u4E2D\u7EE7\u7EED\u7684\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u624B\u52A8\u5347\u7EA7 Codex CLI \u540E\u91CD\u8BD5\u3002\u795E\u5FF5\u4E0D\u4F1A\u81EA\u52A8\u5347\u7EA7\uFF0C\u4E5F\u4E0D\u4F1A\u964D\u7EA7\u521B\u5EFA\u4E0D\u53EF\u89C1\u7684 legacy \u4F1A\u8BDD\u3002",{cause:a}):a}const n=i.thread?.id;if(!n)throw new Error("codex app-server thread/start returned no thread id");this.agentSessionId=n,this.namedThread=!!i.thread?.name}async resolveCodexProjectId(){const e=this.workDir?.trim();if(e)try{const t=[];let s;do{const l=await this.sendRpc("project/list",{limit:100,...s?{cursor:s}:{}});t.push(...l.data??[]),s=l.nextCursor}while(s);const r=Z(t,e);if(r)return r;const i=p.resolve(e),n=`shennian-project-${A("sha256").update(i).digest("hex")}`,d=(await this.sendRpc("project/create",{idempotencyKey:n,name:p.basename(i)||i,roots:[{path:i}],metadata:{createdBy:"Shennian"}})).project?.id;if(!d)throw new Error("codex app-server project/create returned no project id");return d}catch(t){throw Y(t)?new Error("\u5F53\u524D Codex CLI \u4E0D\u652F\u6301\u521B\u5EFA\u53EF\u5F52\u5C5E\u5230 Codex Desktop \u9879\u76EE\u7684\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u624B\u52A8\u5347\u7EA7 Codex CLI \u540E\u91CD\u8BD5\u3002\u795E\u5FF5\u4E0D\u4F1A\u81EA\u52A8\u5347\u7EA7\uFF0C\u4E5F\u4E0D\u4F1A\u76F4\u63A5\u4FEE\u6539 Codex Desktop \u7684\u79C1\u6709\u4FA7\u680F\u7D22\u5F15\u3002",{cause:t}):t}}async startTurnWithRecovery(e,t,s,r,i){try{return await this.startTurn(e,t,s,r,i)}catch(n){if(!N(n))throw n;return await this.killProcess(),await this.ensureAppServer(s),await this.startTurn(e,t,s,r,i)}}async startTurn(e,t,s,r,i){try{return await this.sendRpc("turn/start",{threadId:e,input:[j(t,i)],approvalPolicy:"never",sandboxPolicy:{type:"dangerFullAccess"},...s?{model:s}:{},...r?{effort:r}:{}})}catch(n){throw r&&U(n)?new Error(`Codex app-server does not accept reasoning effort "${r}" for this turn. Refresh models or upgrade Codex CLI, then retry.`,{cause:n}):n}}async interruptActiveTurn(){const e=this.agentSessionId,t=this.activeTurnId;!e||!t||!this.process||(await this.sendRpc("turn/interrupt",{threadId:e,turnId:t},5e3),this.activeTurnId=null)}sendRpc(e,t,s=6e4){if(this.appServerStartupError)return Promise.reject(this.appServerStartupError);const r=this.process;if(!r?.stdin)return Promise.reject(new Error("codex app-server is not running"));const i=this.rpcSeq++,n=JSON.stringify({id:i,method:e,params:t});return new Promise((a,d)=>{const l=setTimeout(()=>{this.pendingRequests.delete(i),d(new Error(`codex app-server request timed out: ${e}`))},s);this.pendingRequests.set(i,{resolve:a,reject:d,timer:l}),r.stdin.write(`${n}
5
+ `,u=>{u&&(clearTimeout(l),this.pendingRequests.delete(i),d(u))})})}handleAppServerMessage(e){if(e.id!=null){const s=this.pendingRequests.get(e.id);s&&(clearTimeout(s.timer),this.pendingRequests.delete(e.id),e.error?s.reject(new Error(e.error.message||`codex app-server error ${e.error.code??""}`.trim())):s.resolve(e.result))}if(!e.method)return;const t=e.params??{};switch(e.method){case"turn/started":{const s=typeof t.turn=="object"&&t.turn!==null?t.turn:null,r=typeof s?.id=="string"?s.id:null;r&&(this.activeTurnId=r);break}case"thread/status/changed":{const s=typeof t.threadId=="string"?t.threadId:"";if(s&&this.agentSessionId&&s!==this.agentSessionId)break;const r=typeof t.status=="object"&&t.status!==null?t.status:null;r?.type==="active"&&this.emitEvent({state:"heartbeat",runPhase:this.mapThreadStatusToRunPhase(r)});break}case"item/agentMessage/delta":{const s=typeof t.itemId=="string"?t.itemId:"";s&&this.deltaItemIds.add(s),typeof t.delta=="string"&&this.emitText(t.delta);break}case"item/completed":this.handleAppServerCompletedItem(t);break;case"thread/tokenUsage/updated":this.handleAppServerUsage(t);break;case"turn/completed":{const s=typeof t.turn=="object"&&t.turn!==null?t.turn:null,r=typeof s?.id=="string"?s.id:null;(!this.activeTurnId||r===this.activeTurnId)&&(this.activeTurnId=null,this.emitFinalIfOpen());break}case"error":{const s=$(t);if(W(s)){this.emitTransientStatus(s);return}this.emitErrorIfOpen(s);break}}}mapThreadStatusToRunPhase(e){const t=e?.type==="active"&&Array.isArray(e.activeFlags)?e.activeFlags:[];return t.includes("waitingOnApproval")?"waiting_approval":t.includes("waitingOnUserInput")?"waiting_user_input":"thinking"}handleAppServerNonJsonStdout(e){const t=J(e);z(t)&&this.failAppServerStartup(new Error("Codex \u672A\u767B\u5F55\u3002\u8BF7\u5148\u5728\u8FD9\u53F0\u7535\u8111\u7684\u7EC8\u7AEF\u8FD0\u884C `codex`\uFF0C\u6309\u63D0\u793A\u5B8C\u6210 ChatGPT \u767B\u5F55\u6216\u914D\u7F6E API key\uFF0C\u7136\u540E\u518D\u56DE\u5230\u795E\u5FF5\u53D1\u9001\u6D88\u606F\u3002"))}failAppServerStartup(e){this.appServerStartupError||(this.appServerStartupError=e,this.rejectAllPending(e),this.process?.kill("SIGTERM"))}handleAppServerCompletedItem(e){const t=typeof e.item=="object"&&e.item!==null?e.item:null;if(!(!t||typeof t.type!="string")&&!F(t))switch(t.type){case"agentMessage":{const s=typeof t.id=="string"?t.id:"";if(s&&this.deltaItemIds.has(s))return;typeof t.text=="string"&&this.emitText(t.text,"block");break}case"commandExecution":{const s=typeof t.command=="string"?t.command:"",r=typeof t.aggregatedOutput=="string"?t.aggregatedOutput:"";s&&this.emitEvent({state:"tool-call",name:"command_execution",args:{command:s}}),this.emitEvent({state:"tool-result",name:"command_execution",result:[r,t.exitCode!=null?`
6
+ (exit ${t.exitCode})`:""].join("").trim()});break}case"mcpToolCall":case"dynamicToolCall":{const s=typeof t.tool=="string"?t.tool:t.type;if(g(s))return;const r=typeof t.arguments=="object"&&t.arguments!==null?t.arguments:{};this.emitEvent({state:"tool-call",name:s,args:r}),this.emitEvent({state:"tool-result",name:s,result:k(t.error??t.result??t.contentItems??"")});break}case"fileChange":break;case"approvalRequest":case"approval_request":case"permissionRequest":case"permission_request":case"userInputRequired":case"user_input_required":{this.emitApprovalPending(t);break}}}handleAppServerUsage(e){const t=typeof e.tokenUsage=="object"&&e.tokenUsage!==null?e.tokenUsage:null,s=typeof t?.last=="object"&&t.last!==null?t.last:null,r=typeof t?.total=="object"&&t.total!==null?t.total:null,i=s??r;if(!i)return;const n=typeof i.inputTokens=="number"?i.inputTokens:void 0,a=typeof i.outputTokens=="number"?i.outputTokens:void 0;(n!=null||a!=null)&&(this.pendingUsage={inputTokens:n??0,outputTokens:a??0})}handleCodexItemLine(e){const t=e.item;if(t?.type&&!M(t))switch(t.type){case"agent_message":case"reasoning":{e.type==="item.completed"&&t.text&&this.emitText(t.text,"block");break}case"command_execution":{if(e.type==="item.started"&&t.command&&this.emitEvent({state:"tool-call",name:"command_execution",args:{command:t.command}}),e.type==="item.completed"){const s=[t.aggregated_output??"",t.exit_code!=null?`
7
+ (exit ${t.exit_code})`:""];this.emitEvent({state:"tool-result",name:"command_execution",result:s.join("").trim()||String(t.status??"")})}break}case"mcp_tool_call":{if(t.tool&&g(t.tool))return;if(e.type==="item.started"&&this.emitEvent({state:"tool-call",name:t.tool??"mcp_tool",args:{server:t.server,...t.arguments&&typeof t.arguments=="object"?t.arguments:{}}}),e.type==="item.completed"){const s=t.error&&typeof t.error=="object"?t.error.message:void 0;this.emitEvent({state:"tool-result",name:t.tool??"mcp_tool",result:s??k(t.result)})}break}case"file_change":break;case"web_search":{e.type==="item.completed"&&t.query&&this.emitText(`[web_search] ${t.query}`,"block");break}case"todo_list":{if(e.type==="item.completed"&&t.items?.length){const s=t.items.map(r=>`- [${r.completed?"x":" "}] ${r.text}`).join(`
8
+ `);this.emitText(s,"block")}break}case"approval_request":case"approvalRequest":case"permission_request":case"permissionRequest":case"user_input_required":case"userInputRequired":{(e.type==="item.started"||e.type==="item.completed")&&this.emitApprovalPending(t);break}case"error":{e.type==="item.completed"&&t.message&&this.emitEvent({state:"error",message:t.message});break}default:break}}handleStreamEvent(e){const t=e.type??e.event;switch(t?.startsWith("item.")&&this.handleCodexItemLine(e),t){case"turn.completed":{const r=e.usage;if(r){const i=r.input_tokens??r.prompt_tokens,n=r.output_tokens??r.completion_tokens;(i!=null||n!=null)&&(this.pendingUsage={inputTokens:i??0,outputTokens:n??0})}this.emitFinalIfOpen();return}case"turn.failed":{const r=typeof e.error=="object"&&e.error?.message?e.error.message:typeof e.error=="string"?e.error:"turn failed";this.emitErrorIfOpen(r);return}case"error":{const r=typeof e.message=="string"?e.message:"";if(r.includes("Reconnecting"))return;this.emitErrorIfOpen(r||(typeof e.error=="string"?e.error:"stream error"));return}case"thread.started":{const r=e.thread_id??e.session_id??e.id;typeof r=="string"&&r&&(this.agentSessionId=r,this.emitEvent({state:"start",agentSessionId:this.agentSessionId}));return}case"turn.started":return}if(t?.startsWith("item."))return;switch(e.type??e.event){case"message":case"text":case"content":{const r=e.content??e.text;r&&this.emitText(r);break}case"function_call":case"tool_call":{if(this.isApprovalLikeName(e.name)){this.emitApprovalPending(e);break}if(e.name&&g(e.name))return;this.emitEvent({state:"tool-call",name:e.name,args:e.arguments??e.input});break}case"function_call_output":case"tool_result":{if(e.name&&g(e.name))return;this.emitEvent({state:"tool-result",name:e.name,result:e.output??e.result});break}case"approval_request":case"approvalRequest":case"permission_request":case"permissionRequest":case"user_input_required":case"userInputRequired":{this.emitApprovalPending(e);break}case"error":break;case"done":case"completed":{e.usage&&(this.pendingUsage={inputTokens:e.usage.prompt_tokens??e.usage.input_tokens??0,outputTokens:e.usage.completion_tokens??e.usage.output_tokens??0}),this.emitFinalIfOpen();break}}}emitEvent(e){if(this.terminalState!=="open"&&e.state!=="final"&&e.state!=="error"&&e.state!=="aborted")return;const t={...e,runId:this.runId,seq:this.seq++};this.emit("agentEvent",t)}isApprovalLikeName(e){return typeof e!="string"?!1:/approval|permission|confirm|user[_-]?input|request[_-]?user/i.test(e)}emitApprovalPending(e){const t=typeof e.command=="string"?e.command:"",s=typeof e.title=="string"&&e.title.trim()?e.title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",r=typeof e.prompt=="string"?e.prompt:typeof e.reason=="string"?e.reason:typeof e.message=="string"?e.message:t?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${t}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";this.emitEvent({state:"approval-pending",approval:{title:s,content:r,source:"codex",actionHint:"\u5F53\u524D\u795E\u5FF5\u6682\u4E0D\u652F\u6301\u8FDC\u7A0B\u786E\u8BA4\uFF0C\u8BF7\u56DE\u5230\u8FD0\u884C Codex \u7684\u7535\u8111/\u7EC8\u7AEF\u5B8C\u6210\u786E\u8BA4\u3002"}})}async killProcess(){const e=this.process;if(this.appServerReady=null,this.activeTurnId=null,!e){this.rejectAllPending(new Error("codex app-server stopped"));return}this.process=null,this.clearForceCloseTimer(),e.kill("SIGTERM"),await new Promise(t=>{e.on("close",t),setTimeout(()=>{e.kill("SIGKILL"),t()},3e3)}),this.rejectAllPending(new Error("codex app-server stopped"))}rejectAllPending(e){for(const[t,s]of this.pendingRequests.entries())clearTimeout(s.timer),s.reject(e),this.pendingRequests.delete(t)}handleProcessClose(e,t){const s=w(t);if(e!==0&&e!==null){const r=s||`codex exited with code ${e}`;this.emitErrorIfOpen(r)}else B(s)?this.emitErrorIfOpen(s):this.emitFinalIfOpen();this.pendingUsage=void 0}emitFinalIfOpen(){this.terminalState==="open"&&(this.terminalState="final",this.emitEvent({state:"final",usage:this.pendingUsage,agentSessionId:this.agentSessionId??void 0}),this.killProcess().catch(()=>{}))}emitErrorIfOpen(e){this.terminalState==="open"&&(this.terminalState="error",this.emitEvent({state:"error",message:L(e)}),this.scheduleProcessClose())}resetRunState(){this.pendingUsage=void 0,this.terminalState="open",this.deltaItemIds.clear(),this.lastTransientStatus="",this.clearForceCloseTimer(),this.resetTextState()}emitTransientStatus(e){const t=D(e);!t||t===this.lastTransientStatus||this.terminalState!=="open"||(this.lastTransientStatus=t,this.emitEvent({state:"delta",text:`${t}
9
+ `,thinking:!0}))}resetTextState(){this.hasEmittedText=!1,this.textTail=""}emitText(e,t="delta"){if(!e)return;let s=V(e);s&&(t==="block"&&this.hasEmittedText&&!s.startsWith(`
10
10
  `)&&(this.textTail.endsWith(`
11
11
  `)?s=`
12
12
  ${s}`:this.textTail.endsWith(`
13
13
 
14
14
  `)||(s=`
15
15
 
16
- ${s}`)),this.hasEmittedText=!0,this.textTail=(this.textTail+s).slice(-4),this.emitEvent({state:"delta",text:s}))}scheduleProcessClose(){const e=this.process;!e||this.forceCloseTimer||(this.forceCloseTimer=setTimeout(()=>{this.forceCloseTimer=null,this.process===e&&(e.kill("SIGTERM"),setTimeout(()=>{this.process===e&&e.kill("SIGKILL")},1e3))},250))}clearForceCloseTimer(){this.forceCloseTimer&&(clearTimeout(this.forceCloseTimer),this.forceCloseTimer=null)}}P("codex",()=>new se);export{se as CodexAdapter,te as buildCodexQueueArgs,ee as buildCodexQueuedText,V as isCodexActiveWriterError,K as isCodexExcludeTurnsUnsupportedError,Q as isCodexPaginatedHistoryUnsupportedError,me as isCodexUnsupportedEffortError,fe as isMissingCodexRolloutError,ge as normalizeCodexModelId,ve as normalizeCodexReasoningEffort};
16
+ ${s}`)),this.hasEmittedText=!0,this.textTail=(this.textTail+s).slice(-4),this.emitEvent({state:"delta",text:s}))}scheduleProcessClose(){const e=this.process;!e||this.forceCloseTimer||(this.forceCloseTimer=setTimeout(()=>{this.forceCloseTimer=null,this.process===e&&(e.kill("SIGTERM"),setTimeout(()=>{this.process===e&&e.kill("SIGKILL")},1e3))},250))}clearForceCloseTimer(){this.forceCloseTimer&&(clearTimeout(this.forceCloseTimer),this.forceCloseTimer=null)}}q("codex",()=>new ie);export{ie as CodexAdapter,ne as buildCodexQueueArgs,re as buildCodexQueuedText,K as isCodexActiveWriterError,X as isCodexExcludeTurnsUnsupportedError,Q as isCodexPaginatedHistoryUnsupportedError,Y as isCodexProjectApiUnsupportedError,ve as isCodexUnsupportedEffortError,xe as isMissingCodexRolloutError,Ie as normalizeCodexModelId,ye as normalizeCodexReasoningEffort,Z as selectCodexProjectIdForWorkDir};
@@ -1 +1 @@
1
- import{getAgentConfigSummary as m}from"../config-status.js";import{isCacheFresh as g,readCache as d,writeCache as l}from"./cache.js";import{discoverModelsForAgent as h}from"./discovery.js";import{getAgentRuntimeSummary as y}from"../runtime-compatibility.js";function v(n){const s=new Set,e=[];for(const t of n)!t.id||s.has(t.id)||(s.add(t.id),e.push(t));return e}function w(n){const s=d();return n.map(e=>{const t=m(e.type),r=y(e);return{type:e.type,models:s.agents[e.type]?.models??e.models??[],supportsManagerMode:e.type==="codex"||e.type==="claude",...t?{config:t}:{},...r?{runtime:r}:{}}})}async function I(n,s){const e=d();for(const t of n)delete e.agents[t.type];return l(e),x(n,s)}async function x(n,s){const e=d();let t=!1;const r=[];for(const o of n){const c=e.agents[o.type];let i;if(g(c,o.version))i=c.models;else{let f=null;try{f=v(await h(o,s)),i=f.length>0?f:c?.models??o.models??[]}catch{i=c?.models??o.models??[]}if(f&&f.length>0){const u={version:o.version,refreshedAt:Date.now(),models:i};JSON.stringify(c)!==JSON.stringify(u)&&(e.agents[o.type]=u,t=!0)}}const a=m(o.type),p=y(o);r.push({type:o.type,models:i,supportsManagerMode:o.type==="codex"||o.type==="claude",...a?{config:a}:{},...p?{runtime:p}:{}})}return t&&l(e),r}export{w as getCachedAgentInfos,I as refreshAgentInfos,x as resolveAgentInfos};
1
+ import{getAgentConfigSummary as l}from"../config-status.js";import{isCacheFresh as g,readCache as f,writeCache as m}from"./cache.js";import{discoverModelsForAgent as A}from"./discovery.js";import{getAgentRuntimeSummary as y}from"../runtime-compatibility.js";function v(t){const s=new Set,e=[];for(const o of t)!o.id||s.has(o.id)||(s.add(o.id),e.push(o));return e}function h(t){return{supportsManagedAgent:t.type!=="pi"&&t.type!=="openclaw",supportsWorker:t.type!=="pi"&&t.type!=="openclaw",supportsManagerMode:t.type==="codex"||t.type==="claude"}}function I(t){const s=f();return t.map(e=>{const o=l(e.type),r=y(e);return{type:e.type,models:s.agents[e.type]?.models??e.models??[],...h(e),...o?{config:o}:{},...r?{runtime:r}:{}}})}async function q(t,s){const e=f();for(const o of t)delete e.agents[o.type];return m(e),w(t,s)}async function w(t,s){const e=f();let o=!1;const r=[];for(const n of t){const c=e.agents[n.type];let i;if(g(c,n.version))i=c.models;else{let p=null;try{p=v(await A(n,s)),i=p.length>0?p:c?.models??n.models??[]}catch{i=c?.models??n.models??[]}if(p&&p.length>0){const a={version:n.version,refreshedAt:Date.now(),models:i};JSON.stringify(c)!==JSON.stringify(a)&&(e.agents[n.type]=a,o=!0)}}const u=l(n.type),d=y(n);r.push({type:n.type,models:i,...h(n),...u?{config:u}:{},...d?{runtime:d}:{}})}return o&&m(e),r}export{I as getCachedAgentInfos,q as refreshAgentInfos,w as resolveAgentInfos};
@@ -1,6 +1,7 @@
1
1
  import type { Command } from 'commander';
2
2
  import { PublicAttachmentCache } from '../room/public-attachment-cache.js';
3
3
  import { PublicRoomClient } from '../room/public-room-client.js';
4
+ import { type RoomInviteQr } from '../room/invite-qr.js';
4
5
  type RoomCommandIo = {
5
6
  write: (text: string) => void;
6
7
  fail: () => void;
@@ -9,6 +10,7 @@ type RoomCommandOptions = {
9
10
  client?: PublicRoomClient;
10
11
  cache?: PublicAttachmentCache;
11
12
  io?: RoomCommandIo;
13
+ createInviteQr?: (inviteUrl: string) => Promise<RoomInviteQr>;
12
14
  };
13
15
  export declare function registerRoomCommand(program: Command, options?: RoomCommandOptions): void;
14
16
  export {};
@@ -1,3 +1,3 @@
1
- import g from"node:crypto";import x from"node:fs";import R from"node:path";import{PublicAttachmentCache as L}from"../room/public-attachment-cache.js";import{PublicRoomClient as j,PublicRoomClientError as U}from"../room/public-room-client.js";import{callDaemonIpc as z}from"../daemon-ipc/client.js";import{DaemonIpcError as q}from"../daemon-ipc/protocol.js";import{MANAGED_ROOM_CONTEXT_ENV as D}from"../room/managed-context.js";const M="https://shennian.net/install.md",$={write:t=>{process.stdout.write(t)},fail:()=>{process.exitCode=1}};function K(t,e={}){const a=e.client??new j,r=e.cache??new L({client:a}),s=e.io??$,d=t.command("room").description("Use one explicitly referenced Shennian Room");d.command("create").description("Create a Room as the paired user").requiredOption("--name <name>","Room name").action(async o=>p("room.create",s,async()=>{b("create");const n=o.name.trim();(!n||n.length>80)&&i("invalid_room_name","Room name must contain 1 to 80 characters.");const c=await a.create(n),m=u(c.room,"invalid_room_response");return typeof m.inviteUrl!="string"&&i("invalid_room_response","Shennian returned an invalid Room invitation."),{...c,sharing:{inviteUrl:m.inviteUrl,installGuideUrl:M}}})),d.command("join <invite-url>").description("Join or request access through an official Room invitation").action(async o=>p("room.join",s,async()=>(b("join"),a.join(k(o))))),d.command("status [room-ref]").description("Show the managed Room, or one explicitly referenced Room").action(async o=>p("room.status",s,()=>{const n=_();return n?(o&&i("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),y(n,"status",{})):a.status(w(o))})),d.command("read [room-ref]").description("Read recent, older, or newer messages from one Room").option("--before <sequence>","Read messages before this sequence").option("--after <sequence>","Read messages after this sequence").option("--limit <count>","Maximum messages, 1 to 50","50").action(async(o,n)=>{await p("room.read",s,async()=>{n.before&&n.after&&i("ambiguous_sequence_cursor","--before and --after are mutually exclusive."),n.before&&!S(n.before)&&i("invalid_sequence","--before sequence is invalid."),n.after&&!S(n.after)&&i("invalid_sequence","--after sequence is invalid.");const c=Number(n.limit);(!Number.isInteger(c)||c<1||c>50)&&i("invalid_limit","--limit must be between 1 and 50.");const m=_();if(m)return o&&i("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),y(m,"read",{...n.before?{before:n.before}:{},...n.after?{after:n.after}:{},limit:c});const l=w(o),f=await a.read(l,{before:n.before,after:n.after,limit:c});return T(f,l,r)})}),d.command("send [room-ref]").description("Send text and up to 10 files as the paired user").option("--text <text>","Message text").option("--file <path>","Local file path; repeat for multiple files",C,[]).action(async(o,n)=>{await p("room.send",s,async()=>{const c=n.text?.trim()??"";!c&&n.file.length===0&&i("room_message_empty","Provide --text or at least one --file."),n.file.length>10&&i("room_attachments_too_many","A message can contain at most 10 files.");const m=_();if(m)return o&&i("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),y(m,"send",{clientMessageId:`managed:${g.randomUUID()}`,text:c,files:n.file});const l=w(o),f=[];for(const I of n.file)f.push(await N(a,l,I));return a.send(l,{clientMessageId:`cli:${g.randomUUID()}`,...c?{text:c}:{},...f.length>0?{attachmentIds:f}:{}})})}),d.command("attachment").description("Download Room attachments through Shennian").command("get [room-ref] [attachment-id]").description("Download and verify one Room attachment").action(async(o,n)=>{await p("room.attachment.get",s,async()=>{const c=_(),m=c?o:n;return(!m||!/^ratt_[A-Za-z0-9_-]{1,191}$/.test(m))&&i("invalid_attachment_ref","attachment-id is invalid."),c?y(c,"attachment.get",{attachmentId:m}):r.materialize(w(o),m)})}),d.command("leave <room-ref>").description("Leave one explicitly referenced Room").action(async o=>p("room.leave",s,()=>(b("leave"),a.leave(A(o))))),d.command("list",{hidden:!0}).action(()=>h(s,"command_removed","Room listing is not available to Agents.",null)),d.command("search",{hidden:!0}).allowUnknownOption(!0).action(()=>h(s,"command_removed","Room search is not available to Agents.",null)),d.command("agent",{hidden:!0}).allowUnknownOption(!0).action(()=>h(s,"command_removed","Managed Agents are created in the Shennian App or Web interface.",null))}async function p(t,e,a){try{const r=await a();e.write(`${JSON.stringify({ok:!0,command:t,result:r})}
2
- `)}catch(r){if(r instanceof U){h(e,r.code,r.message,r.nextAction);return}if(r instanceof q){h(e,r.code,r.message,null);return}h(e,"room_command_failed","Shennian Room command failed.",null)}}function _(){return process.env[D]?.trim()||null}async function y(t,e,a){return z({method:"managed-room.execute",params:{context:t,action:e,...a},timeoutMs:e==="send"||e==="attachment.get"?18e4:15e3})}function b(t){_()&&i("managed_room_action_forbidden",`${t} is not available in managed Room context.`)}function w(t){return t||i("room_ref_required","Use an official Room URL returned by Shennian."),A(t)}function A(t){let e;try{e=new URL(t)}catch{i("invalid_room_ref","Use an official Room URL returned by Shennian.")}const a=e.pathname.match(/^\/spaces\/([A-Za-z0-9_-]{1,191})$/);return(e.protocol!=="https:"||e.hostname!=="app.shennian.net"&&e.hostname!=="shennian.net"||e.port||e.username||e.password||e.search||e.hash||!a)&&i("invalid_room_ref","Use an official Room URL returned by Shennian."),a[1]}function k(t){let e;try{e=new URL(t)}catch{i("invalid_invite_url","Use an official Shennian Room invitation URL.")}const a=e.pathname.match(/^\/spaces\/join\/([A-Za-z0-9_-]{32,256})$/);return(e.protocol!=="https:"||e.hostname!=="shennian.net"||e.port||e.username||e.password||e.search||e.hash||!a)&&i("invalid_invite_url","Use an official Shennian Room invitation URL."),a[1]}function S(t){return/^(0|[1-9]\d{0,19})$/.test(t)}function C(t,e){return[...e,t]}async function N(t,e,a){const r=R.resolve(a);let s;try{s=await x.promises.lstat(r)}catch{i("file_not_found",`File does not exist: ${a}`)}(!s.isFile()||s.isSymbolicLink())&&i("invalid_file",`Not a regular file: ${a}`),(s.size<1||s.size>100*1024*1024)&&i("invalid_file_size","Each file must be between 1 byte and 100 MB.");const d=await x.promises.readFile(r),v=g.createHash("sha256").update(d).digest("hex"),o=O(r),n=await t.initializeAttachment(e,{clientUploadId:`cli:${g.randomUUID()}`,name:R.basename(r),mediaKind:o.startsWith("image/")?"image":o.startsWith("audio/")?"audio":"file",mimeType:o,byteSize:s.size,sha256:v}),c=u(n.attachment,"invalid_attachment_response"),m=u(n.upload,"invalid_attachment_response");(typeof c.id!="string"||typeof m.url!="string"||m.method!=="PUT")&&i("invalid_attachment_response","Shennian returned an invalid attachment response.");const l=u(m.headers,"invalid_attachment_response");return Object.values(l).some(f=>typeof f!="string")&&i("invalid_attachment_response","Shennian returned invalid upload headers."),E(m.url),await t.upload(m.url,l,d),await t.completeAttachment(e,c.id),c.id}function O(t){const e=R.extname(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".mp4":"video/mp4",".mov":"video/quicktime",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[e]??"application/octet-stream"}function T(t,e,a){return Array.isArray(t.messages)||i("invalid_server_response","Shennian returned invalid messages."),{messages:t.messages.map(r=>{const s=u(r,"invalid_server_response"),d=Array.isArray(s.attachments)?s.attachments:[];return{...s,attachments:d.map(v=>{const o=u(v,"invalid_server_response");return(typeof o.attachmentId!="string"||typeof o.name!="string"||typeof o.mimeType!="string"||typeof o.byteSize!="string"||typeof o.sha256!="string")&&i("invalid_server_response","Shennian returned invalid attachment metadata."),{...o,...a.lookup(e,o)}})}})}}function u(t,e){return(!t||typeof t!="object"||Array.isArray(t))&&i(e,"Invalid structured response."),t}function E(t){let e;try{e=new URL(t)}catch{i("invalid_attachment_response","Invalid upload URL.")}const a=e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1");(e.protocol!=="https:"&&!a||e.username||e.password||e.hash)&&i("invalid_attachment_response","Invalid upload URL.")}function i(t,e){throw new U(t,e)}function h(t,e,a,r){t.write(`${JSON.stringify({ok:!1,error:e,message:a,nextAction:r})}
3
- `),t.fail()}export{K as registerRoomCommand};
1
+ import y from"node:crypto";import I from"node:fs";import x from"node:path";import{PublicAttachmentCache as j}from"../room/public-attachment-cache.js";import{PublicRoomClient as k,PublicRoomClientError as A}from"../room/public-room-client.js";import{callDaemonIpc as q}from"../daemon-ipc/client.js";import{DaemonIpcError as D}from"../daemon-ipc/protocol.js";import{MANAGED_ROOM_CONTEXT_ENV as M}from"../room/managed-context.js";import{createRoomInviteQr as $}from"../room/invite-qr.js";const T="https://shennian.net/install.md",O={write:e=>{process.stdout.write(e)},fail:()=>{process.exitCode=1}};function X(e,t={}){const a=t.client??new k,r=t.cache??new j({client:a}),i=t.io??O,p=t.createInviteQr??$,c=e.command("room").description("Use one explicitly referenced Shennian Room");c.command("create").description("Create a Room as the paired user").requiredOption("--name <name>","Room name").action(async m=>f("room.create",i,async()=>{w("create");const n=m.name.trim();(!n||n.length>80)&&o("invalid_room_name","Room name must contain 1 to 80 characters.");const s=await a.create(n),d=h(s.room,"invalid_room_response");typeof d.inviteUrl!="string"&&o("invalid_room_response","Shennian returned an invalid Room invitation.");const u=await p(d.inviteUrl).catch(()=>({imagePath:null,mimeType:"image/png",payload:d.inviteUrl}));return{...s,sharing:{inviteUrl:d.inviteUrl,inviteQr:u,installGuideUrl:T}}})),c.command("join <invite-url>").description("Join or request access through an official Room invitation").action(async m=>f("room.join",i,async()=>{w("join");const n=U(m,"invite");return a.join(n.roomId,n.inviteToken)})),c.command("open <room-url>").description("Open one Room where the paired user is already a member").action(async m=>f("room.open",i,async()=>{w("open");const n=U(m,"stable");return a.open(n.roomId)})),c.command("status [room-ref]").description("Show the managed Room, or one explicitly referenced Room").action(async m=>f("room.status",i,()=>{const n=g();return n?(m&&o("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),b(n,"status",{})):a.status(R(m))})),c.command("read [room-ref]").description("Read recent, older, or newer messages from one Room").option("--before <sequence>","Read messages before this sequence").option("--after <sequence>","Read messages after this sequence").option("--limit <count>","Maximum messages, 1 to 50","50").action(async(m,n)=>{await f("room.read",i,async()=>{n.before&&n.after&&o("ambiguous_sequence_cursor","--before and --after are mutually exclusive."),n.before&&!L(n.before)&&o("invalid_sequence","--before sequence is invalid."),n.after&&!L(n.after)&&o("invalid_sequence","--after sequence is invalid.");const s=Number(n.limit);(!Number.isInteger(s)||s<1||s>50)&&o("invalid_limit","--limit must be between 1 and 50.");const d=g();if(d)return m&&o("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),b(d,"read",{...n.before?{before:n.before}:{},...n.after?{after:n.after}:{},limit:s});const u=R(m),_=await a.read(u,{before:n.before,after:n.after,limit:s});return P(_,u,r)})}),c.command("send [room-ref]").description("Send text and up to 10 files as the paired user").option("--text <text>","Message text").option("--file <path>","Local file path; repeat for multiple files",C,[]).action(async(m,n)=>{await f("room.send",i,async()=>{const s=n.text?.trim()??"";!s&&n.file.length===0&&o("room_message_empty","Provide --text or at least one --file."),n.file.length>10&&o("room_attachments_too_many","A message can contain at most 10 files.");const d=g();if(d)return m&&o("managed_room_ref_forbidden","Do not pass a Room reference in managed Room context."),b(d,"send",{clientMessageId:`managed:${y.randomUUID()}`,text:s,files:n.file});const u=R(m),_=[];for(const z of n.file)_.push(await N(a,u,z));return a.send(u,{clientMessageId:`cli:${y.randomUUID()}`,...s?{text:s}:{},..._.length>0?{attachmentIds:_}:{}})})}),c.command("attachment").description("Download Room attachments through Shennian").command("get [room-ref] [attachment-id]").description("Download and verify one Room attachment").action(async(m,n)=>{await f("room.attachment.get",i,async()=>{const s=g(),d=s?m:n;return(!d||!/^ratt_[A-Za-z0-9_-]{1,191}$/.test(d))&&o("invalid_attachment_ref","attachment-id is invalid."),s?b(s,"attachment.get",{attachmentId:d}):r.materialize(R(m),d)})}),c.command("leave <room-ref>").description("Leave one explicitly referenced Room").action(async m=>f("room.leave",i,()=>(w("leave"),a.leave(S(m))))),c.command("list",{hidden:!0}).action(()=>v(i,"command_removed","Room listing is not available to Agents.",null)),c.command("search",{hidden:!0}).allowUnknownOption(!0).action(()=>v(i,"command_removed","Room search is not available to Agents.",null)),c.command("agent",{hidden:!0}).allowUnknownOption(!0).action(()=>v(i,"command_removed","Managed Agents are created in the Shennian mobile App.",null))}async function f(e,t,a){try{const r=await a();t.write(`${JSON.stringify({ok:!0,command:e,result:r})}
2
+ `)}catch(r){if(r instanceof A){v(t,r.code,r.message,r.nextAction);return}if(r instanceof D){v(t,r.code,r.message,null);return}v(t,"room_command_failed","Shennian Room command failed.",null)}}function g(){return process.env[M]?.trim()||null}async function b(e,t,a){return q({method:"managed-room.execute",params:{context:e,action:t,...a},timeoutMs:t==="send"||t==="attachment.get"?18e4:15e3})}function w(e){g()&&o("managed_room_action_forbidden",`${e} is not available in managed Room context.`)}function R(e){return e||o("room_ref_required","Use an official Room URL returned by Shennian."),S(e)}function S(e){return U(e,"stable").roomId}function U(e,t){let a;const r=t==="invite"?"invalid_invite_url":"invalid_room_ref",i=t==="invite"?"Use an official Shennian Room invitation URL.":"Use an official Room URL returned by Shennian.";try{a=new URL(e)}catch{o(r,i)}const p=a.pathname.match(/^\/spaces\/([A-Za-z0-9_-]{1,191})$/),c=a.searchParams.get("invite");return(a.protocol!=="https:"||a.hostname!=="app.shennian.net"||a.port||a.username||a.password||a.hash||!p||a.searchParams.has("access")||[...a.searchParams.keys()].some(l=>l!=="invite")||t==="stable"&&c!=null||t==="invite"&&(c==null||!/^[A-Za-z0-9_-]{32,256}$/.test(c)))&&o(r,i),{roomId:p[1],...c?{inviteToken:c}:{}}}function L(e){return/^(0|[1-9]\d{0,19})$/.test(e)}function C(e,t){return[...t,e]}async function N(e,t,a){const r=x.resolve(a);let i;try{i=await I.promises.lstat(r)}catch{o("file_not_found",`File does not exist: ${a}`)}(!i.isFile()||i.isSymbolicLink())&&o("invalid_file",`Not a regular file: ${a}`),(i.size<1||i.size>100*1024*1024)&&o("invalid_file_size","Each file must be between 1 byte and 100 MB.");const p=await I.promises.readFile(r),c=y.createHash("sha256").update(p).digest("hex"),l=E(r),m=await e.initializeAttachment(t,{clientUploadId:`cli:${y.randomUUID()}`,name:x.basename(r),mediaKind:l.startsWith("image/")?"image":l.startsWith("audio/")?"audio":"file",mimeType:l,byteSize:i.size,sha256:c}),n=h(m.attachment,"invalid_attachment_response"),s=h(m.upload,"invalid_attachment_response");(typeof n.id!="string"||typeof s.url!="string"||s.method!=="PUT")&&o("invalid_attachment_response","Shennian returned an invalid attachment response.");const d=h(s.headers,"invalid_attachment_response");return Object.values(d).some(u=>typeof u!="string")&&o("invalid_attachment_response","Shennian returned invalid upload headers."),F(s.url),await e.upload(s.url,d,p),await e.completeAttachment(t,n.id),n.id}function E(e){const t=x.extname(e).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".mp3":"audio/mpeg",".wav":"audio/wav",".m4a":"audio/mp4",".mp4":"video/mp4",".mov":"video/quicktime",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[t]??"application/octet-stream"}function P(e,t,a){return Array.isArray(e.messages)||o("invalid_server_response","Shennian returned invalid messages."),{messages:e.messages.map(r=>{const i=h(r,"invalid_server_response"),p=Array.isArray(i.attachments)?i.attachments:[];return{...i,attachments:p.map(c=>{const l=h(c,"invalid_server_response");return(typeof l.attachmentId!="string"||typeof l.name!="string"||typeof l.mimeType!="string"||typeof l.byteSize!="string"||typeof l.sha256!="string")&&o("invalid_server_response","Shennian returned invalid attachment metadata."),{...l,...a.lookup(t,l)}})}})}}function h(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&o(t,"Invalid structured response."),e}function F(e){let t;try{t=new URL(e)}catch{o("invalid_attachment_response","Invalid upload URL.")}const a=t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1");(t.protocol!=="https:"&&!a||t.username||t.password||t.hash)&&o("invalid_attachment_response","Invalid upload URL.")}function o(e,t){throw new A(e,t)}function v(e,t,a,r){e.write(`${JSON.stringify({ok:!1,error:t,message:a,nextAction:r})}
3
+ `),e.fail()}export{X as registerRoomCommand};
package/dist/src/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import{Command as oe}from"commander";import v from"chalk";import ne from"node:os";import $ from"node:fs";import{loadConfig as d,saveConfig as te,getConfigPath as re,getShennianDir as ie,resolveShennianPath as B,normalizeAutoUpgradePolicy as se}from"./config/index.js";import{CliRelayClient as ae}from"./relay/client.js";import{registerPairCommand as ce,runSmartStart as me}from"./commands/pair.js";import{clearDaemonPidIfOwner as F,createDaemonInstanceId as le,clearDaemonLauncher as G,findRunningDaemonProcessIds as de,isRemoteAccessDisabled as pe,isIsolatedDaemonE2eInstance as ge,registerDaemonCommand as ue,writeDaemonPid as J,writeDaemonLauncher as j}from"./commands/daemon.js";import{registerAgentCommand as he}from"./commands/agent.js";import{registerRuntimeCommand as fe}from"./commands/runtime.js";import{registerManagerCommand as ve}from"./commands/manager.js";import{registerUpgradeCommand as Se}from"./commands/upgrade.js";import{registerToolsCommand as we}from"./commands/tools.js";import{registerIntegrationCommand as Ie}from"./commands/integration.js";import{registerRoomCommand as Re}from"./commands/room.js";import{SessionManager as ye}from"./session/manager.js";import{SERVERS as A,regionToUrl as ke,urlToRegion as Ce}from"./region.js";import{getCurrentVersion as K,handleStartupCrashCheck as De}from"./upgrade/engine.js";import{AutoUpgradeScheduler as Te}from"./upgrade/scheduler.js";import{detectAgents as Ue}from"./agents/detect.js";import{augmentProcessPath as z}from"./env-path.js";z();const W=K();import{getCachedAgentInfos as Ee,resolveAgentInfos as $e}from"./agents/model-registry.js";import{initCliLogReporter as Ae,reportLog as S}from"./log-reporter.js";import{isNativeFusionEnabled as be}from"./native-fusion/config.js";import{NativeSessionFusionService as Oe}from"./native-fusion/service.js";import{startDaemonLogRetention as Ne}from"./daemon-log.js";import{startDaemonIpcServer as Pe}from"./daemon-ipc/server.js";import{RoomSessionRegistry as Me}from"./room/session-registry.js";import{HttpRoomBindingClient as Le}from"./room/room-binding-client.js";import{TrustedManagedRoomBinder as _e}from"./room/managed-room-binding.js";import{RoomHostSessionObservationStore as xe}from"./room/host-session-observations.js";import{RoomMirrorSyncService as Ve}from"./room/mirror-sync-service.js";import{RoomActivationService as He}from"./room/activation-service.js";import{RoomActivationAudit as Be}from"./room/activation-audit.js";import{RoomAttachmentCache as Fe}from"./room/attachment-cache.js";import{RoomAttachmentUploader as Ge}from"./room/attachment-upload.js";import{ManagedRoomContextAuthority as Je}from"./room/managed-context.js";import{createManagedRoomIpcHandlers as je}from"./room/managed-room-ipc.js";const q=ie(),Ke=B("daemon.pid");function ze(){try{const o=$.readFileSync(Ke,"utf-8").trim();if(o.startsWith("{")){const r=JSON.parse(o),s=Number(r.pid);return Number.isInteger(s)&&s>0?s:null}const n=parseInt(o,10);return Number.isInteger(n)&&n>0?n:null}catch{return null}}function We(o){return o.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function b(){process.stdout.write(`${JSON.stringify({ok:!1,error:"integration_command_retired",message:"Room MCP and Hooks were retired. Use the Shennian Skill and CLI.",nextAction:{type:"open_install_guide",url:"https://shennian.net/install.md"}})}
2
- `),process.exitCode=1}function qe(o){const n=[`trigger=${o.trigger??"unknown"}`,`phase=${o.phase}`,`code=${o.code??"unknown"}`,`attempt=${o.reconnectAttempt}`];return o.reason&&n.push(`reason=${o.reason}`),o.error&&n.push(`error=${o.error}`),n.join(" ")}async function Q(o,n=5e3){const r=Date.now();for(;Date.now()-r<n;){try{process.kill(o,0)}catch{return!0}await new Promise(s=>setTimeout(s,100))}try{return process.kill(o,0),!1}catch{return!0}}const t=new oe;t.name("shennian").description("Shennian \u2014 AI Agent Control Plane").version(W),t.enablePositionalOptions(),Ie(t),Re(t),t.option("--api <url>","Server URL override").option("--name <name>","Machine name",ne.hostname()).action(async o=>{const n=d(),r=o.api??process.env.SHENNIAN_DESKTOP_SERVER_URL??n.serverUrl??void 0;await me(r,o.name)}),t.command("run-service",{hidden:!0}).description("(internal) Connect to relay server, called by the background service").option("--api <url>","Server URL override").action(async o=>{const n=B("env.json");try{const e=JSON.parse($.readFileSync(n,"utf-8"));for(const[i,c]of Object.entries(e))process.env[i]||(process.env[i]=c);z()}catch{}const r=Ne();pe()&&(console.log(`[${new Date().toISOString()}] remote access disabled, service start skipped`),clearInterval(r),process.exit(0));const s=!!(process.env.INVOCATION_ID||process.env.JOURNAL_STREAM||process.env.SHENNIAN_DESKTOP_SERVER_URL),O=async(e,i)=>{console.log(`[${new Date().toISOString()}] ${i} (PID ${e})`),process.kill(e,"SIGTERM"),await Q(e)||(process.kill(e,"SIGKILL"),await Q(e,2e3))};try{const e=ze();if(e&&e!==process.pid)try{process.kill(e,0),s?await O(e,"managed start taking over from existing daemon"):(console.log(`[${new Date().toISOString()}] daemon already running (PID ${e}), skipping duplicate start`),process.exit(0))}catch{}}catch{}const D=ge(process.env,q)?[]:de(process.pid);if(D.length>0)if(s)for(const e of D)try{await O(e,"managed start taking over from orphan daemon")}catch{}else console.log(`[${new Date().toISOString()}] daemon already running (PID ${D[0]}), skipping duplicate start`),process.exit(0);const m=le();J(process.pid,m,{version:W}),j(process.pid,void 0,m),process.on("exit",()=>{F(process.pid,m),G(m)}),await De()&&(console.log(`[${new Date().toISOString()}] Rolled back to previous version, restarting...`),process.exit(0));const a=d(),g=o.api??process.env.SHENNIAN_DESKTOP_SERVER_URL??a.serverUrl??A.cn.url,p=K(),T=Ue(),u=T.map(e=>e.type),U=Ee(T),w=new Me,I=new xe,N=new Je(w),h=new Le(g),Y=new Fe({actionClient:h}),Z=new Ge({actionClient:h});let P=null;const E=await Pe({handlers:{...je({authority:N,actionClient:h,attachmentCache:Y,attachmentUploader:Z,observations:I,getMachineCredentials:()=>({machineToken:d().machineToken})})}});let M=!1;const R=()=>{M||(M=!0,E.close().finally(()=>process.exit(0)))};if(process.once("SIGINT",R),process.once("SIGTERM",R),!a.machineToken){console.error('Shennian CLI is not paired. Run "shennian pair --browser" or "shennian pair --token" first.'),await E.close(),process.exitCode=1;return}process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R);const L=`${We(g)}/relay/machine`,_=a.machineToken;if(!_)return;a.machineId&&Ae(g,a.machineId),console.log(`[${new Date().toISOString()}] Connecting to ${L}... (v${p}) agents: ${u.join(",")}`),S({level:"info",wsEvent:"daemon.start",metadata:{version:p,agents:u}});let y=null,k=null;const x=se(a.autoUpgrade),l=new ae({serverUrl:L,machineToken:_,cliVersion:p,agentList:u,autoUpgradePolicy:x,onConnected:()=>{console.log(`[${new Date().toISOString()}] \u2713 Connected`),S({level:"info",wsEvent:"daemon.connected"}),U.some(e=>e.models.length>0)&&l.sendEvent({type:"event",event:"machine.agents",payload:{agentList:u,agents:U}}),$e(T,{serverUrl:a.serverUrl??g,authToken:a.machineToken??a.accessToken}).then(e=>{JSON.stringify(e)!==JSON.stringify(U)&&l.sendEvent({type:"event",event:"machine.agents",payload:{agentList:u,agents:e}})}).catch(()=>{}),import("./upgrade/engine.js").then(({readUpgradeAttempt:e,clearUpgradeAttempt:i})=>{const c=e();i(),c&&(console.log(`[${new Date().toISOString()}] [upgrade] Reporting success: ${c.from} \u2192 ${c.to}`),l.sendEvent({type:"event",event:"upgrade",payload:{state:"success",machineId:"self",from:c.from,to:c.to}}))}).catch(()=>{}),C.start(),y?.handleConnected(),k?.start()},onDisconnected:e=>{k?.stop(),console.log(`[${new Date().toISOString()}] \u26A0 Disconnected, reconnecting... ${qe(e)}`),S({level:"warn",wsEvent:"daemon.disconnected",metadata:{code:e.code,reason:e.reason,error:e.error,phase:e.phase,trigger:e.trigger,reconnectAttempt:e.reconnectAttempt}})},onReq:e=>{console.log(`[${new Date().toISOString()}] [req] ${e.method}`),S({level:"info",type:"ws",wsEvent:e.method,wsDirection:"in",traceId:e.traceId}),f.handleReq(e)}});y=be()?new Oe(l):null,k=new Ve({registry:w,observations:I,actionClient:h,getMachineCredentials:()=>({machineToken:d().machineToken}),onMessages:async(e,i,c,ee)=>{await P?.processMessages(e,i,c,ee)}});const C=new Te({currentVersion:p,machineId:a.machineId??"unknown-machine",serverUrl:a.serverUrl??g,getIdleState:()=>f.getUpgradeIdleState(),startUpgrade:async e=>{const{handleUpgradeStart:i}=await import("./commands/upgrade.js");await i(l,"auto-upgrade",e,{currentVersion:p})}});C.setPolicy(x);const f=new ye(l,y,p,C,new _e({registry:w,observations:I,bindingClient:h,getMachineCredentials:()=>{const e=d();return{machineId:e.machineId,machineToken:e.machineToken}},hostProcessIdentity:()=>`daemon:${m}`}));P=new He({registry:w,observations:I,activate:e=>f.activateRoomSession(e),issueManagedRoomContext:e=>{const i=d().machineToken;if(!i)throw new Error("machine_not_authorized");return N.issue({registryKey:e,machineCredential:i})},abort:e=>f.abortRoomSession(e),audit:new Be}),$.mkdirSync(q,{recursive:!0}),J(process.pid,m,{version:p}),j(process.pid,void 0,m),l.connect(),process.stdin.resume();let V=!1;const H=async()=>{if(!V){V=!0,console.log(v.gray(`
3
- Disconnecting...`)),S({level:"info",wsEvent:"daemon.stop"}),clearInterval(r);try{await f.cleanup(),C.stop(),y?.stop(),k?.stop(),l.disconnect(),await E.close(),F(process.pid,m),G(m)}finally{process.exit(0)}}};process.on("SIGINT",()=>{H()}),process.on("SIGTERM",()=>{H()})}),t.command("workbuddy-session-hook",{hidden:!0}).description("(retired) WorkBuddy Room Hook").allowUnknownOption(!0).action(()=>b()),t.command("room-session-hook",{hidden:!0}).description("(internal) Authorize the official Room tool for one trusted Agent Session").argument("<runtime>","Trusted runtime adapter").allowUnknownOption(!0).action(()=>b()),t.command("room-tool-server",{hidden:!0}).description("(internal) Run the official Shennian Room MCP tool").allowUnknownOption(!0).action(()=>b());const X=t.command("config").description("View or modify configuration");X.command("show",{isDefault:!0}).description("Show current configuration").action(()=>{console.log(`Config file: ${re()}`);const n={...d()};if(n.machineToken&&(n.machineToken=n.machineToken.slice(0,12)+"..."),n.serverUrl){const r=Ce(n.serverUrl);console.log(`Region: ${r} (${A[r].label})`)}console.log(JSON.stringify(n,null,2))}),X.command("set").description("Update a config value").argument("<key>",'Config key (e.g. "server")').argument("<value>",'Config value (e.g. "cn" or "global")').action((o,n)=>{const r=d();if(o==="server"){n!=="cn"&&n!=="global"&&(console.error(v.red('\u2717 Value must be "cn" or "global"')),process.exit(1));const s=n;r.serverUrl=ke(s),te(r),console.log(v.green(`\u2713 Server set to ${A[s].label}`)),console.log(v.yellow(" Restart the background service for this to take effect: shennian stop && shennian start"));return}console.error(v.red(`\u2717 Unknown config key: ${o}. Supported: server`)),process.exit(1)}),ce(t),ue(t),he(t),fe(t),ve(t),Se(t),we(t),t.parse();
1
+ import{Command as oe}from"commander";import v from"chalk";import ne from"node:os";import $ from"node:fs";import{loadConfig as d,saveConfig as te,getConfigPath as re,getShennianDir as ie,resolveShennianPath as B,normalizeAutoUpgradePolicy as se}from"./config/index.js";import{CliRelayClient as ae}from"./relay/client.js";import{registerPairCommand as ce,runSmartStart as me}from"./commands/pair.js";import{clearDaemonPidIfOwner as F,createDaemonInstanceId as le,clearDaemonLauncher as G,findRunningDaemonProcessIds as de,isRemoteAccessDisabled as pe,isIsolatedDaemonE2eInstance as ge,registerDaemonCommand as ue,writeDaemonPid as J,writeDaemonLauncher as j}from"./commands/daemon.js";import{registerRuntimeCommand as he}from"./commands/runtime.js";import{registerManagerCommand as fe}from"./commands/manager.js";import{registerUpgradeCommand as ve}from"./commands/upgrade.js";import{registerToolsCommand as Se}from"./commands/tools.js";import{registerIntegrationCommand as we}from"./commands/integration.js";import{registerRoomCommand as Ie}from"./commands/room.js";import{SessionManager as Re}from"./session/manager.js";import{SERVERS as A,regionToUrl as ye,urlToRegion as ke}from"./region.js";import{getCurrentVersion as K,handleStartupCrashCheck as Ce}from"./upgrade/engine.js";import{AutoUpgradeScheduler as De}from"./upgrade/scheduler.js";import{detectAgents as Te}from"./agents/detect.js";import{augmentProcessPath as z}from"./env-path.js";z();const W=K();import{getCachedAgentInfos as Ue,resolveAgentInfos as Ee}from"./agents/model-registry.js";import{initCliLogReporter as $e,reportLog as S}from"./log-reporter.js";import{isNativeFusionEnabled as Ae}from"./native-fusion/config.js";import{NativeSessionFusionService as be}from"./native-fusion/service.js";import{startDaemonLogRetention as Oe}from"./daemon-log.js";import{startDaemonIpcServer as Ne}from"./daemon-ipc/server.js";import{RoomSessionRegistry as Pe}from"./room/session-registry.js";import{HttpRoomBindingClient as Me}from"./room/room-binding-client.js";import{TrustedManagedRoomBinder as Le}from"./room/managed-room-binding.js";import{RoomHostSessionObservationStore as _e}from"./room/host-session-observations.js";import{RoomMirrorSyncService as xe}from"./room/mirror-sync-service.js";import{RoomActivationService as Ve}from"./room/activation-service.js";import{RoomActivationAudit as He}from"./room/activation-audit.js";import{RoomAttachmentCache as Be}from"./room/attachment-cache.js";import{RoomAttachmentUploader as Fe}from"./room/attachment-upload.js";import{ManagedRoomContextAuthority as Ge}from"./room/managed-context.js";import{createManagedRoomIpcHandlers as Je}from"./room/managed-room-ipc.js";const q=ie(),je=B("daemon.pid");function Ke(){try{const o=$.readFileSync(je,"utf-8").trim();if(o.startsWith("{")){const r=JSON.parse(o),s=Number(r.pid);return Number.isInteger(s)&&s>0?s:null}const n=parseInt(o,10);return Number.isInteger(n)&&n>0?n:null}catch{return null}}function ze(o){return o.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function b(){process.stdout.write(`${JSON.stringify({ok:!1,error:"integration_command_retired",message:"Room MCP and Hooks were retired. Use the Shennian Skill and CLI.",nextAction:{type:"open_install_guide",url:"https://shennian.net/install.md"}})}
2
+ `),process.exitCode=1}function We(o){const n=[`trigger=${o.trigger??"unknown"}`,`phase=${o.phase}`,`code=${o.code??"unknown"}`,`attempt=${o.reconnectAttempt}`];return o.reason&&n.push(`reason=${o.reason}`),o.error&&n.push(`error=${o.error}`),n.join(" ")}async function Q(o,n=5e3){const r=Date.now();for(;Date.now()-r<n;){try{process.kill(o,0)}catch{return!0}await new Promise(s=>setTimeout(s,100))}try{return process.kill(o,0),!1}catch{return!0}}const t=new oe;t.name("shennian").description("Shennian \u2014 AI Agent Control Plane").version(W),t.enablePositionalOptions(),we(t),Ie(t),t.option("--api <url>","Server URL override").option("--name <name>","Machine name",ne.hostname()).action(async o=>{const n=d(),r=o.api??process.env.SHENNIAN_DESKTOP_SERVER_URL??n.serverUrl??void 0;await me(r,o.name)}),t.command("run-service",{hidden:!0}).description("(internal) Connect to relay server, called by the background service").option("--api <url>","Server URL override").action(async o=>{const n=B("env.json");try{const e=JSON.parse($.readFileSync(n,"utf-8"));for(const[i,c]of Object.entries(e))process.env[i]||(process.env[i]=c);z()}catch{}const r=Oe();pe()&&(console.log(`[${new Date().toISOString()}] remote access disabled, service start skipped`),clearInterval(r),process.exit(0));const s=!!(process.env.INVOCATION_ID||process.env.JOURNAL_STREAM||process.env.SHENNIAN_DESKTOP_SERVER_URL),O=async(e,i)=>{console.log(`[${new Date().toISOString()}] ${i} (PID ${e})`),process.kill(e,"SIGTERM"),await Q(e)||(process.kill(e,"SIGKILL"),await Q(e,2e3))};try{const e=Ke();if(e&&e!==process.pid)try{process.kill(e,0),s?await O(e,"managed start taking over from existing daemon"):(console.log(`[${new Date().toISOString()}] daemon already running (PID ${e}), skipping duplicate start`),process.exit(0))}catch{}}catch{}const D=ge(process.env,q)?[]:de(process.pid);if(D.length>0)if(s)for(const e of D)try{await O(e,"managed start taking over from orphan daemon")}catch{}else console.log(`[${new Date().toISOString()}] daemon already running (PID ${D[0]}), skipping duplicate start`),process.exit(0);const m=le();J(process.pid,m,{version:W}),j(process.pid,void 0,m),process.on("exit",()=>{F(process.pid,m),G(m)}),await Ce()&&(console.log(`[${new Date().toISOString()}] Rolled back to previous version, restarting...`),process.exit(0));const a=d(),g=o.api??process.env.SHENNIAN_DESKTOP_SERVER_URL??a.serverUrl??A.cn.url,p=K(),T=Te(),u=T.map(e=>e.type),U=Ue(T),w=new Pe,I=new _e,N=new Ge(w),h=new Me(g),Y=new Be({actionClient:h}),Z=new Fe({actionClient:h});let P=null;const E=await Ne({handlers:{...Je({authority:N,actionClient:h,attachmentCache:Y,attachmentUploader:Z,observations:I,getMachineCredentials:()=>({machineToken:d().machineToken})})}});let M=!1;const R=()=>{M||(M=!0,E.close().finally(()=>process.exit(0)))};if(process.once("SIGINT",R),process.once("SIGTERM",R),!a.machineToken){console.error('Shennian CLI is not paired. Run "shennian pair --browser" or "shennian pair --token" first.'),await E.close(),process.exitCode=1;return}process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R);const L=`${ze(g)}/relay/machine`,_=a.machineToken;if(!_)return;a.machineId&&$e(g,a.machineId),console.log(`[${new Date().toISOString()}] Connecting to ${L}... (v${p}) agents: ${u.join(",")}`),S({level:"info",wsEvent:"daemon.start",metadata:{version:p,agents:u}});let y=null,k=null;const x=se(a.autoUpgrade),l=new ae({serverUrl:L,machineToken:_,cliVersion:p,agentList:u,autoUpgradePolicy:x,onConnected:()=>{console.log(`[${new Date().toISOString()}] \u2713 Connected`),S({level:"info",wsEvent:"daemon.connected"}),U.some(e=>e.models.length>0)&&l.sendEvent({type:"event",event:"machine.agents",payload:{agentList:u,agents:U}}),Ee(T,{serverUrl:a.serverUrl??g,authToken:a.machineToken??a.accessToken}).then(e=>{JSON.stringify(e)!==JSON.stringify(U)&&l.sendEvent({type:"event",event:"machine.agents",payload:{agentList:u,agents:e}})}).catch(()=>{}),import("./upgrade/engine.js").then(({readUpgradeAttempt:e,clearUpgradeAttempt:i})=>{const c=e();i(),c&&(console.log(`[${new Date().toISOString()}] [upgrade] Reporting success: ${c.from} \u2192 ${c.to}`),l.sendEvent({type:"event",event:"upgrade",payload:{state:"success",machineId:"self",from:c.from,to:c.to}}))}).catch(()=>{}),C.start(),y?.handleConnected(),k?.start()},onDisconnected:e=>{k?.stop(),console.log(`[${new Date().toISOString()}] \u26A0 Disconnected, reconnecting... ${We(e)}`),S({level:"warn",wsEvent:"daemon.disconnected",metadata:{code:e.code,reason:e.reason,error:e.error,phase:e.phase,trigger:e.trigger,reconnectAttempt:e.reconnectAttempt}})},onReq:e=>{console.log(`[${new Date().toISOString()}] [req] ${e.method}`),S({level:"info",type:"ws",wsEvent:e.method,wsDirection:"in",traceId:e.traceId}),f.handleReq(e)}});y=Ae()?new be(l):null,k=new xe({registry:w,observations:I,actionClient:h,getMachineCredentials:()=>({machineToken:d().machineToken}),onMessages:async(e,i,c,ee)=>{await P?.processMessages(e,i,c,ee)}});const C=new De({currentVersion:p,machineId:a.machineId??"unknown-machine",serverUrl:a.serverUrl??g,getIdleState:()=>f.getUpgradeIdleState(),startUpgrade:async e=>{const{handleUpgradeStart:i}=await import("./commands/upgrade.js");await i(l,"auto-upgrade",e,{currentVersion:p})}});C.setPolicy(x);const f=new Re(l,y,p,C,new Le({registry:w,observations:I,bindingClient:h,getMachineCredentials:()=>{const e=d();return{machineId:e.machineId,machineToken:e.machineToken}},hostProcessIdentity:()=>`daemon:${m}`}));P=new Ve({registry:w,observations:I,activate:e=>f.activateRoomSession(e),issueManagedRoomContext:e=>{const i=d().machineToken;if(!i)throw new Error("machine_not_authorized");return N.issue({registryKey:e,machineCredential:i})},abort:e=>f.abortRoomSession(e),audit:new He}),$.mkdirSync(q,{recursive:!0}),J(process.pid,m,{version:p}),j(process.pid,void 0,m),l.connect(),process.stdin.resume();let V=!1;const H=async()=>{if(!V){V=!0,console.log(v.gray(`
3
+ Disconnecting...`)),S({level:"info",wsEvent:"daemon.stop"}),clearInterval(r);try{await f.cleanup(),C.stop(),y?.stop(),k?.stop(),l.disconnect(),await E.close(),F(process.pid,m),G(m)}finally{process.exit(0)}}};process.on("SIGINT",()=>{H()}),process.on("SIGTERM",()=>{H()})}),t.command("workbuddy-session-hook",{hidden:!0}).description("(retired) WorkBuddy Room Hook").allowUnknownOption(!0).action(()=>b()),t.command("room-session-hook",{hidden:!0}).description("(internal) Authorize the official Room tool for one trusted Agent Session").argument("<runtime>","Trusted runtime adapter").allowUnknownOption(!0).action(()=>b()),t.command("room-tool-server",{hidden:!0}).description("(internal) Run the official Shennian Room MCP tool").allowUnknownOption(!0).action(()=>b());const X=t.command("config").description("View or modify configuration");X.command("show",{isDefault:!0}).description("Show current configuration").action(()=>{console.log(`Config file: ${re()}`);const n={...d()};if(n.machineToken&&(n.machineToken=n.machineToken.slice(0,12)+"..."),n.serverUrl){const r=ke(n.serverUrl);console.log(`Region: ${r} (${A[r].label})`)}console.log(JSON.stringify(n,null,2))}),X.command("set").description("Update a config value").argument("<key>",'Config key (e.g. "server")').argument("<value>",'Config value (e.g. "cn" or "global")').action((o,n)=>{const r=d();if(o==="server"){n!=="cn"&&n!=="global"&&(console.error(v.red('\u2717 Value must be "cn" or "global"')),process.exit(1));const s=n;r.serverUrl=ye(s),te(r),console.log(v.green(`\u2713 Server set to ${A[s].label}`)),console.log(v.yellow(" Restart the background service for this to take effect: shennian stop && shennian start"));return}console.error(v.red(`\u2717 Unknown config key: ${o}. Supported: server`)),process.exit(1)}),ce(t),ue(t),he(t),fe(t),ve(t),Se(t),t.parse();