shennian 0.3.42 → 0.3.43

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 (73) hide show
  1. package/dist/publish-build-manifest.json +91 -41
  2. package/dist/src/agents/adapter.d.ts +1 -0
  3. package/dist/src/index.js +3 -3
  4. package/dist/src/native-fusion/codex-parser.d.ts +1 -0
  5. package/dist/src/native-fusion/codex-parser.js +4 -4
  6. package/dist/src/native-fusion/file-watcher.d.ts +18 -0
  7. package/dist/src/native-fusion/file-watcher.js +1 -0
  8. package/dist/src/native-fusion/local-repository.d.ts +52 -0
  9. package/dist/src/native-fusion/local-repository.js +2 -0
  10. package/dist/src/native-fusion/opencode-parser.js +2 -2
  11. package/dist/src/native-fusion/parser-common.d.ts +7 -1
  12. package/dist/src/native-fusion/parser-common.js +4 -4
  13. package/dist/src/native-fusion/parsers.d.ts +2 -1
  14. package/dist/src/native-fusion/parsers.js +2 -2
  15. package/dist/src/native-fusion/service.d.ts +10 -2
  16. package/dist/src/native-fusion/service.js +2 -2
  17. package/dist/src/native-fusion/session-header.d.ts +9 -0
  18. package/dist/src/native-fusion/session-header.js +2 -0
  19. package/dist/src/native-fusion/state.d.ts +1 -1
  20. package/dist/src/native-fusion/state.js +2 -1
  21. package/dist/src/native-fusion/types.d.ts +29 -5
  22. package/dist/src/native-fusion/types.js +1 -1
  23. package/dist/src/personal-sync/paths.d.ts +2 -0
  24. package/dist/src/personal-sync/paths.js +1 -0
  25. package/dist/src/relay/client.d.ts +4 -1
  26. package/dist/src/relay/client.js +1 -1
  27. package/dist/src/session/attachment-reference.d.ts +2 -0
  28. package/dist/src/session/attachment-reference.js +1 -0
  29. package/dist/src/session/attachment-transfer-store.d.ts +38 -0
  30. package/dist/src/session/attachment-transfer-store.js +2 -0
  31. package/dist/src/session/canonical-store.d.ts +101 -0
  32. package/dist/src/session/canonical-store.js +5 -0
  33. package/dist/src/session/handlers/chat.js +2 -2
  34. package/dist/src/session/handlers/fs.d.ts +0 -1
  35. package/dist/src/session/handlers/fs.js +1 -1
  36. package/dist/src/session/handlers/message-status.d.ts +3 -0
  37. package/dist/src/session/handlers/message-status.js +1 -0
  38. package/dist/src/session/handlers/title.js +1 -1
  39. package/dist/src/session/handlers/tool-detail.js +1 -1
  40. package/dist/src/session/handlers/voice-window.d.ts +3 -0
  41. package/dist/src/session/handlers/voice-window.js +1 -0
  42. package/dist/src/session/history-subscriptions.d.ts +17 -0
  43. package/dist/src/session/history-subscriptions.js +1 -0
  44. package/dist/src/session/index-publisher.d.ts +3 -0
  45. package/dist/src/session/index-publisher.js +1 -0
  46. package/dist/src/session/manager.d.ts +2 -0
  47. package/dist/src/session/manager.js +1 -1
  48. package/dist/src/session/queue.d.ts +1 -1
  49. package/dist/src/session/queue.js +4 -3
  50. package/dist/src/session/store.d.ts +33 -3
  51. package/dist/src/session/store.js +2 -3
  52. package/dist/src/session/tool-detail-store.d.ts +16 -0
  53. package/dist/src/session/tool-detail-store.js +2 -0
  54. package/dist/src/session/types.d.ts +3 -13
  55. package/node_modules/@shennian/wire/dist/events.d.ts +2 -0
  56. package/node_modules/@shennian/wire/dist/fs.d.ts +45 -0
  57. package/node_modules/@shennian/wire/dist/fs.js +7 -1
  58. package/node_modules/@shennian/wire/dist/index.d.ts +1 -0
  59. package/node_modules/@shennian/wire/dist/index.js +1 -0
  60. package/node_modules/@shennian/wire/dist/machine.d.ts +6 -0
  61. package/node_modules/@shennian/wire/dist/message-payload.d.ts +2 -0
  62. package/node_modules/@shennian/wire/dist/message-payload.js +15 -1
  63. package/node_modules/@shennian/wire/dist/methods.d.ts +1 -1
  64. package/node_modules/@shennian/wire/dist/session-sync.d.ts +197 -0
  65. package/node_modules/@shennian/wire/dist/session-sync.js +49 -0
  66. package/node_modules/@shennian/wire/dist/session.d.ts +24 -13
  67. package/node_modules/@shennian/wire/dist/tool-detail.d.ts +18 -11
  68. package/node_modules/@shennian/wire/dist/tool-detail.js +7 -1
  69. package/package.json +1 -1
  70. package/dist/src/session/remote-attachments.d.ts +0 -15
  71. package/dist/src/session/remote-attachments.js +0 -1
  72. package/dist/src/session/tool-summary.d.ts +0 -1
  73. package/dist/src/session/tool-summary.js +0 -1
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "jsMinified": true,
4
4
  "minifier": "esbuild",
5
- "fileCount": 111,
5
+ "fileCount": 121,
6
6
  "files": [
7
7
  {
8
8
  "file": "bin/shennian.js",
@@ -276,8 +276,8 @@
276
276
  },
277
277
  {
278
278
  "file": "src/index.js",
279
- "beforeBytes": 21040,
280
- "afterBytes": 11051
279
+ "beforeBytes": 21396,
280
+ "afterBytes": 11301
281
281
  },
282
282
  {
283
283
  "file": "src/log-reporter.js",
@@ -306,43 +306,63 @@
306
306
  },
307
307
  {
308
308
  "file": "src/native-fusion/codex-parser.js",
309
- "beforeBytes": 27675,
310
- "afterBytes": 11480
309
+ "beforeBytes": 28990,
310
+ "afterBytes": 12133
311
311
  },
312
312
  {
313
313
  "file": "src/native-fusion/config.js",
314
314
  "beforeBytes": 225,
315
315
  "afterBytes": 109
316
316
  },
317
+ {
318
+ "file": "src/native-fusion/file-watcher.js",
319
+ "beforeBytes": 2954,
320
+ "afterBytes": 1278
321
+ },
322
+ {
323
+ "file": "src/native-fusion/local-repository.js",
324
+ "beforeBytes": 11197,
325
+ "afterBytes": 5755
326
+ },
317
327
  {
318
328
  "file": "src/native-fusion/opencode-parser.js",
319
- "beforeBytes": 4849,
320
- "afterBytes": 2575
329
+ "beforeBytes": 5208,
330
+ "afterBytes": 2743
321
331
  },
322
332
  {
323
333
  "file": "src/native-fusion/parser-common.js",
324
- "beforeBytes": 7754,
325
- "afterBytes": 3606
334
+ "beforeBytes": 7739,
335
+ "afterBytes": 3552
326
336
  },
327
337
  {
328
338
  "file": "src/native-fusion/parsers.js",
329
- "beforeBytes": 5325,
330
- "afterBytes": 2730
339
+ "beforeBytes": 5543,
340
+ "afterBytes": 3005
331
341
  },
332
342
  {
333
343
  "file": "src/native-fusion/service.js",
334
- "beforeBytes": 12900,
335
- "afterBytes": 6147
344
+ "beforeBytes": 20039,
345
+ "afterBytes": 9441
346
+ },
347
+ {
348
+ "file": "src/native-fusion/session-header.js",
349
+ "beforeBytes": 3498,
350
+ "afterBytes": 1657
336
351
  },
337
352
  {
338
353
  "file": "src/native-fusion/state.js",
339
- "beforeBytes": 808,
340
- "afterBytes": 467
354
+ "beforeBytes": 3258,
355
+ "afterBytes": 1598
341
356
  },
342
357
  {
343
358
  "file": "src/native-fusion/types.js",
344
- "beforeBytes": 11,
345
- "afterBytes": 1
359
+ "beforeBytes": 54,
360
+ "afterBytes": 60
361
+ },
362
+ {
363
+ "file": "src/personal-sync/paths.js",
364
+ "beforeBytes": 364,
365
+ "afterBytes": 223
346
366
  },
347
367
  {
348
368
  "file": "src/region.js",
@@ -351,8 +371,8 @@
351
371
  },
352
372
  {
353
373
  "file": "src/relay/client.js",
354
- "beforeBytes": 11985,
355
- "afterBytes": 5934
374
+ "beforeBytes": 12612,
375
+ "afterBytes": 6310
356
376
  },
357
377
  {
358
378
  "file": "src/room/activation-audit.js",
@@ -454,6 +474,21 @@
454
474
  "beforeBytes": 8037,
455
475
  "afterBytes": 3438
456
476
  },
477
+ {
478
+ "file": "src/session/attachment-reference.js",
479
+ "beforeBytes": 1717,
480
+ "afterBytes": 914
481
+ },
482
+ {
483
+ "file": "src/session/attachment-transfer-store.js",
484
+ "beforeBytes": 18717,
485
+ "afterBytes": 9372
486
+ },
487
+ {
488
+ "file": "src/session/canonical-store.js",
489
+ "beforeBytes": 28665,
490
+ "afterBytes": 14062
491
+ },
457
492
  {
458
493
  "file": "src/session/handlers/agent-capabilities.js",
459
494
  "beforeBytes": 767,
@@ -471,8 +506,8 @@
471
506
  },
472
507
  {
473
508
  "file": "src/session/handlers/chat.js",
474
- "beforeBytes": 31311,
475
- "afterBytes": 13268
509
+ "beforeBytes": 33758,
510
+ "afterBytes": 14377
476
511
  },
477
512
  {
478
513
  "file": "src/session/handlers/control.js",
@@ -481,8 +516,13 @@
481
516
  },
482
517
  {
483
518
  "file": "src/session/handlers/fs.js",
484
- "beforeBytes": 29785,
485
- "afterBytes": 13579
519
+ "beforeBytes": 20840,
520
+ "afterBytes": 10026
521
+ },
522
+ {
523
+ "file": "src/session/handlers/message-status.js",
524
+ "beforeBytes": 561,
525
+ "afterBytes": 313
486
526
  },
487
527
  {
488
528
  "file": "src/session/handlers/room-managed.js",
@@ -496,18 +536,33 @@
496
536
  },
497
537
  {
498
538
  "file": "src/session/handlers/title.js",
499
- "beforeBytes": 2225,
500
- "afterBytes": 1113
539
+ "beforeBytes": 3013,
540
+ "afterBytes": 1583
501
541
  },
502
542
  {
503
543
  "file": "src/session/handlers/tool-detail.js",
504
- "beforeBytes": 10763,
505
- "afterBytes": 4812
544
+ "beforeBytes": 6010,
545
+ "afterBytes": 3159
546
+ },
547
+ {
548
+ "file": "src/session/handlers/voice-window.js",
549
+ "beforeBytes": 2324,
550
+ "afterBytes": 1105
551
+ },
552
+ {
553
+ "file": "src/session/history-subscriptions.js",
554
+ "beforeBytes": 6272,
555
+ "afterBytes": 3181
556
+ },
557
+ {
558
+ "file": "src/session/index-publisher.js",
559
+ "beforeBytes": 1469,
560
+ "afterBytes": 731
506
561
  },
507
562
  {
508
563
  "file": "src/session/manager.js",
509
- "beforeBytes": 18103,
510
- "afterBytes": 9204
564
+ "beforeBytes": 20168,
565
+ "afterBytes": 10430
511
566
  },
512
567
  {
513
568
  "file": "src/session/projection.js",
@@ -516,23 +571,18 @@
516
571
  },
517
572
  {
518
573
  "file": "src/session/queue.js",
519
- "beforeBytes": 15015,
520
- "afterBytes": 7165
521
- },
522
- {
523
- "file": "src/session/remote-attachments.js",
524
- "beforeBytes": 2999,
525
- "afterBytes": 1492
574
+ "beforeBytes": 17298,
575
+ "afterBytes": 8175
526
576
  },
527
577
  {
528
578
  "file": "src/session/store.js",
529
- "beforeBytes": 4333,
530
- "afterBytes": 2212
579
+ "beforeBytes": 13169,
580
+ "afterBytes": 7349
531
581
  },
532
582
  {
533
- "file": "src/session/tool-summary.js",
534
- "beforeBytes": 1401,
535
- "afterBytes": 731
583
+ "file": "src/session/tool-detail-store.js",
584
+ "beforeBytes": 2690,
585
+ "afterBytes": 1307
536
586
  },
537
587
  {
538
588
  "file": "src/session/types.js",
@@ -10,6 +10,7 @@ export type AgentEvent = {
10
10
  name?: string;
11
11
  args?: Record<string, unknown>;
12
12
  result?: string;
13
+ durationMs?: number;
13
14
  message?: string;
14
15
  approval?: {
15
16
  title?: string;
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{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();
1
+ import{Command as oe}from"commander";import v from"chalk";import ne from"node:os";import O from"node:fs";import{loadConfig as d,saveConfig as te,getConfigPath as re,getShennianDir as ie,resolveShennianPath as H,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 Ce}from"./region.js";import{getCurrentVersion as K,handleStartupCrashCheck as ke}from"./upgrade/engine.js";import{AutoUpgradeScheduler as De}from"./upgrade/scheduler.js";import{detectAgents as Ee}from"./agents/detect.js";import{augmentProcessPath as z}from"./env-path.js";z();const W=K();import{getCachedAgentInfos as Te,resolveAgentInfos as Ue}from"./agents/model-registry.js";import{initCliLogReporter as Oe,reportLog as S}from"./log-reporter.js";import{isNativeFusionEnabled as Ae}from"./native-fusion/config.js";import{NativeSessionFusionService as $e}from"./native-fusion/service.js";import{startDaemonLogRetention as Ne}from"./daemon-log.js";import{startDaemonIpcServer as be}from"./daemon-ipc/server.js";import{RoomSessionRegistry as Pe}from"./room/session-registry.js";import{HttpRoomBindingClient as _e}from"./room/room-binding-client.js";import{TrustedManagedRoomBinder as Me}from"./room/managed-room-binding.js";import{RoomHostSessionObservationStore as Le}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 Be}from"./room/activation-audit.js";import{RoomAttachmentCache as He}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";import{SESSION_SYNC_PROTOCOL_VERSION as je,SESSION_SYNC_REQUIRED_CAPABILITIES as Ke}from"@shennian/wire";import{getDaemonInstallationId as ze}from"./session/store.js";const Y=ie(),We=H("daemon.pid");function Ye(){try{const o=O.readFileSync(We,"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 Qe(o){return o.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function $(){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(),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=H("env.json");try{const e=JSON.parse(O.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),N=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=Ye();if(e&&e!==process.pid)try{process.kill(e,0),s?await N(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,Y)?[]:de(process.pid);if(D.length>0)if(s)for(const e of D)try{await N(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 ke()&&(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(),E=Ee(),u=E.map(e=>e.type),T=Te(E),w=new Pe,I=new Le,b=new Ge(w),h=new _e(g),X=new He({actionClient:h}),Z=new Fe({actionClient:h});let P=null;const U=await be({handlers:{...Je({authority:b,actionClient:h,attachmentCache:X,attachmentUploader:Z,observations:I,getMachineCredentials:()=>({machineToken:d().machineToken})})}});let _=!1;const R=()=>{_||(_=!0,U.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 U.close(),process.exitCode=1;return}process.removeListener("SIGINT",R),process.removeListener("SIGTERM",R);const M=`${Qe(g)}/relay/machine`,L=a.machineToken;if(!L)return;a.machineId&&Oe(g,a.machineId),console.log(`[${new Date().toISOString()}] Connecting to ${M}... (v${p}) agents: ${u.join(",")}`),S({level:"info",wsEvent:"daemon.start",metadata:{version:p,agents:u}});let y=null,C=null;const x=se(a.autoUpgrade),l=new ae({serverUrl:M,machineToken:L,cliVersion:p,agentList:u,autoUpgradePolicy:x,sessionSyncProtocolVersion:je,sessionSyncCapabilities:Ke,daemonInstallationId:ze(),onConnected:()=>{console.log(`[${new Date().toISOString()}] \u2713 Connected`),S({level:"info",wsEvent:"daemon.connected"}),T.some(e=>e.models.length>0)&&l.sendEvent({type:"event",event:"machine.agents",payload:{agentList:u,agents:T}}),Ue(E,{serverUrl:a.serverUrl??g,authToken:a.machineToken??a.accessToken}).then(e=>{JSON.stringify(e)!==JSON.stringify(T)&&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(()=>{}),k.start(),y?.handleConnected(),C?.start()},onDisconnected:e=>{C?.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=Ae()?new $e(l):null,C=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 k=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})}});k.setPolicy(x);const f=new Re(l,y,p,k,new Me({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 b.issue({registryKey:e,machineCredential:i})},abort:e=>f.abortRoomSession(e),audit:new Be}),O.mkdirSync(Y,{recursive:!0}),J(process.pid,m,{version:p}),j(process.pid,void 0,m),l.connect(),process.stdin.resume();let V=!1;const B=async()=>{if(!V){V=!0,console.log(v.gray(`
3
+ Disconnecting...`)),S({level:"info",wsEvent:"daemon.stop"}),clearInterval(r);try{await f.cleanup(),k.stop(),y?.stop(),C?.stop(),l.disconnect(),await U.close(),F(process.pid,m),G(m)}finally{process.exit(0)}}};process.on("SIGINT",()=>{B()}),process.on("SIGTERM",()=>{B()})}),t.command("workbuddy-session-hook",{hidden:!0}).description("(retired) WorkBuddy Room Hook").allowUnknownOption(!0).action(()=>$()),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(()=>$()),t.command("room-tool-server",{hidden:!0}).description("(internal) Run the official Shennian Room MCP tool").allowUnknownOption(!0).action(()=>$());const q=t.command("config").description("View or modify configuration");q.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))}),q.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();
@@ -1,4 +1,5 @@
1
1
  import type { ParsedNativeEvent } from './types.js';
2
+ export declare function lookupCodexThreadName(sourceSessionKey: string): string | null;
2
3
  export declare function listCodexRolloutFiles(): string[];
3
4
  export declare function parseCodexRolloutChunk(filePath: string, startOffset: number): {
4
5
  nextOffset: number;
@@ -1,6 +1,6 @@
1
- import T from"node:fs";import v from"node:os";import b from"node:path";import{buildApprovalPendingPayload as Q,buildUserMessagePayload as k,isSystemControlPayload as j,isToolPayload as q}from"@shennian/wire";import{buildImagePayload as V,buildToolPayload as X,inferMimeType as E,makeCursor as Y,makeEventKey as Z,normalizeText as d,parseStructuredString as P,readJsonlLines as N,readTimestamp as D,safeParse as I}from"./parser-common.js";function O(e){if(typeof e=="string"){const i=e.trim();return i?{path:i,name:b.basename(i)||"image.png",mimeType:E(i),kind:"image"}:null}if(typeof e!="object"||e===null)return null;const r=e,n=typeof r.path=="string"?r.path:typeof r.file_path=="string"?r.file_path:typeof r.saved_path=="string"?r.saved_path:"";if(!n.trim())return null;const t=typeof r.name=="string"&&r.name.trim()?r.name:b.basename(n)||"image.png",o=typeof r.mimeType=="string"&&r.mimeType.trim()?r.mimeType:E(n);return{path:n,name:t,mimeType:o,kind:"image"}}function R(e){return Array.isArray(e)?e.map(n=>{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){const t=n;return typeof t.text=="string"?t.text:""}return""}).map(n=>d(n)).filter(Boolean).join(`
1
+ import b from"node:fs";import I from"node:os";import C from"node:path";import{buildApprovalPendingPayload as Z,buildUserMessagePayload as N,isSystemControlPayload as v,isToolPayload as q}from"@shennian/wire";import{buildImagePayload as P,buildToolPayload as D,inferMimeType as W,makeCursor as U,makeEventKey as $,normalizeText as h,parseStructuredString as K,readJsonlLines as w,readTimestamp as O,safeParse as k}from"./parser-common.js";function tt(t){if(typeof t=="string"){const i=t.trim();return i?{path:i,name:C.basename(i)||"image.png",mimeType:W(i),kind:"image"}:null}if(typeof t!="object"||t===null)return null;const r=t,n=typeof r.path=="string"?r.path:typeof r.file_path=="string"?r.file_path:typeof r.saved_path=="string"?r.saved_path:"";if(!n.trim())return null;const e=typeof r.name=="string"&&r.name.trim()?r.name:C.basename(n)||"image.png",o=typeof r.mimeType=="string"&&r.mimeType.trim()?r.mimeType:W(n);return{path:n,name:e,mimeType:o,kind:"image"}}function F(t){return Array.isArray(t)?t.map(n=>{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){const e=n;return typeof e.text=="string"?e.text:""}return""}).map(n=>h(n)).filter(Boolean).join(`
2
2
 
3
- `):""}function U(e){const r=d(e);if(!r)return{text:"",strippedWrapper:!1};const n=r.match(/My request for Codex:\s*([\s\S]*)$/i);return n&&n[1]?{text:K(n[1]),strippedWrapper:!0}:{text:r,strippedWrapper:!1}}function K(e){return d(e.replace(/<image>\s*<\/image>/gi,""))}function w(e){const r=d(e);if(!r)return!1;if(j(r)||/^<environment_context>[\s\S]*<\/environment_context>$/i.test(r)&&r.includes("<current_date>")&&r.includes("<timezone>")&&r.includes("<workspace_roots>"))return!0;const n=r.startsWith("# AGENTS.md instructions for ")&&r.includes("<INSTRUCTIONS>")&&r.includes("</INSTRUCTIONS>"),t=r.includes("<environment_context>")&&r.includes("</environment_context>");return n&&t}function F(e){const r=R(e.text_elements),n=Array.isArray(e.input)?R(e.input):"",t=typeof e.message=="string"?U(e.message):{text:"",strippedWrapper:!1},o=t.text,i=r||n||o,c=t.strippedWrapper?"codex_app_context_wrapper":void 0,f=Array.isArray(e.local_images)?e.local_images.map(O).filter(a=>a!=null):[];return!i&&f.length===0||j(i)&&f.length===0||w(i)&&f.length===0?null:f.length>0?{payload:k(i,f),titleText:i,repairHint:c}:{payload:i,titleText:i,repairHint:c}}function tt(e){return e==="turn_completed"||e==="turn_complete"||e==="task_complete"}function et(e){return/approval|permission|confirm|user[_-]?input|input[_-]?required/i.test(e)}function nt(e){const r=typeof e.command=="string"?e.command:Array.isArray(e.command)?e.command.join(" "):"",n=typeof e.prompt=="string"?e.prompt:typeof e.reason=="string"?e.reason:typeof e.message=="string"?e.message:r?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${r}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";return Q({title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:n,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"})}function $(e,r){return Array.isArray(e)?d(e.map(n=>{if(typeof n=="string")return n;if(typeof n!="object"||n===null)return"";const t=n;return t.type!==r?"":typeof t.text=="string"?t.text:""}).filter(Boolean).join(`
3
+ `):""}function z(t){const r=h(t);if(!r)return{text:"",strippedWrapper:!1};const n=r.match(/My request for Codex:\s*([\s\S]*)$/i);return n&&n[1]?{text:et(n[1]),strippedWrapper:!0}:{text:r,strippedWrapper:!1}}function et(t){return h(t.replace(/<image>\s*<\/image>/gi,""))}function B(t){const r=h(t);if(!r)return!1;if(v(r)||/^<environment_context>[\s\S]*<\/environment_context>$/i.test(r)&&r.includes("<current_date>")&&r.includes("<timezone>")&&r.includes("<workspace_roots>"))return!0;const n=r.startsWith("<recommended_plugins>")&&r.includes("</recommended_plugins>"),e=r.includes("# AGENTS.md instructions for ")&&r.includes("<INSTRUCTIONS>")&&r.includes("</INSTRUCTIONS>"),o=r.includes("<environment_context>")&&r.includes("</environment_context>");return e&&o&&(r.startsWith("# AGENTS.md instructions for ")||n)}function H(t){const r=F(t.text_elements),n=Array.isArray(t.input)?F(t.input):"",e=typeof t.message=="string"?z(t.message):{text:"",strippedWrapper:!1},o=e.text,i=r||n||o,c=e.strippedWrapper?"codex_app_context_wrapper":void 0,f=Array.isArray(t.local_images)?t.local_images.map(tt).filter(a=>a!=null):[];return!i&&f.length===0||v(i)&&f.length===0||B(i)&&f.length===0?null:f.length>0?{payload:N(i,f),titleText:i,repairHint:c}:{payload:i,titleText:i,repairHint:c}}function nt(t){return t==="turn_completed"||t==="turn_complete"||t==="task_complete"}function rt(t){return/approval|permission|confirm|user[_-]?input|input[_-]?required/i.test(t)}function ot(t){const r=typeof t.command=="string"?t.command:Array.isArray(t.command)?t.command.join(" "):"",n=typeof t.prompt=="string"?t.prompt:typeof t.reason=="string"?t.reason:typeof t.message=="string"?t.message:r?`Codex \u8BF7\u6C42\u6267\u884C\u547D\u4EE4\uFF1A${r}`:"Codex \u6B63\u5728\u7B49\u5F85\u7528\u6237\u786E\u8BA4\u540E\u7EE7\u7EED\u3002";return Z({title:"\u9700\u8981\u7528\u6237\u786E\u8BA4",content:n,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"})}function L(t,r){return Array.isArray(t)?h(t.map(n=>{if(typeof n=="string")return n;if(typeof n!="object"||n===null)return"";const e=n;return e.type!==r?"":typeof e.text=="string"?e.text:""}).filter(Boolean).join(`
4
4
 
5
- `)):""}function rt(e){if(!Array.isArray(e))return[];const r=[];for(const n of e){if(typeof n!="object"||n===null)continue;const t=n;if(t.type!=="input_image")continue;const o=typeof t.path=="string"?t.path:typeof t.file_path=="string"?t.file_path:typeof t.saved_path=="string"?t.saved_path:typeof t.image_path=="string"?t.image_path:"";o.trim()&&r.push({path:o,name:b.basename(o)||"image.png",mimeType:E(o),kind:"image"})}return r}function z(e){if(e.type!=="message")return null;const r=e.role==="assistant"?"agent":e.role==="user"?"user":null;if(!r)return null;if(r==="agent"){const i=$(e.content,"output_text");return j(i)?null:i?{role:r,payload:i,titleText:i}:null}const n=U($(e.content,"input_text")),t=n.text,o=rt(e.content);return!t&&o.length===0||j(t)&&o.length===0||w(t)&&o.length===0?null:{role:r,payload:o.length>0?k(t,o):t,titleText:t,repairHint:n.strippedWrapper?"codex_app_context_wrapper":void 0}}function B(e){if(!e)return"";try{const r=JSON.parse(e);if(typeof r=="object"&&r!==null){const n=r;if(n.type==="user"&&typeof n.content=="string")return d(n.content)}}catch{}return d(e)}function ot(e,r,n,t){return e.agentType!=="codex"||e.role!==r||q(e.payload)||Math.abs(e.ts-t)>300*1e3?!1:B(e.payload)===B(n)}function W(e,r,n,t){for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(i){if(ot(i,r,n,t))return o;if(i.agentType==="codex"&&Math.abs(i.ts-t)>300*1e3)break}}return-1}function C(e,r,n,t,o,i,c,f,a,u,s="agent",m=!1,p){c&&e.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:Z(r,n,t),cursor:Y(r,n),role:s,ts:i,payload:c,title:f,modelId:a,workDir:u,terminal:m,repairHint:p})}function x(e,r,n,t,o,i,c,f,a,u,s,m){C(e,r,n,t,o,i,X(c,s,m),f,a,u)}function it(e,r,n,t,o,i,c,f,a){const u=typeof t.type=="string"?t.type:"";if(u){if(u==="message"){const s=z(t);if(!s||W(e,s.role,s.payload,i)>=0)return;C(e,r,n,`${u}:${s.role}`,o,i,s.payload,c,f,a,s.role,!1,s.repairHint);return}if(u==="function_call"){const s=typeof t.name=="string"?t.name:"function_call";x(e,r,n,u,o,i,s,c,f,a,P(t.arguments));return}if(u==="function_call_output"){x(e,r,n,u,o,i,"function_call_output",c,f,a,t.call_id,t.output);return}if(u==="custom_tool_call"){const s=typeof t.name=="string"?t.name:"custom_tool_call",m=t.input!==void 0?{input:t.input}:void 0;x(e,r,n,u,o,i,s,c,f,a,m);return}if(u==="custom_tool_call_output"){const s=typeof t.name=="string"?t.name:"custom_tool_call_output",m=t.output??t.result??t.content;x(e,r,n,u,o,i,s,c,f,a,t.call_id,m);return}if(u==="web_search_call"){const s=typeof t.action=="object"&&t.action!==null?t.action:null;x(e,r,n,u,o,i,"web_search",c,f,a,s??t.query);return}}}function st(e,r,n,t,o,i,c,f,a){const u=typeof t.type=="string"?t.type:"";if(u){if(u==="user_message"){const s=F(t);if(!s)return;C(e,r,n,u,o,i,s.payload,c,f,a,"user",!1,s.repairHint);return}if(u==="agent_message"){const s=typeof t.message=="string"?d(t.message):"";if(!s||j(s))return;C(e,r,n,u,o,i,s,c,f,a);return}if(u==="turn_aborted"||u==="error"){const s=typeof t.message=="string"?d(t.message):typeof t.error=="string"?d(t.error):"";if(!s)return;C(e,r,n,u,o,i,s,c,f,a,"agent",!0);return}if(et(u)){C(e,r,n,u,o,i,nt(t),c,f,a,"agent");return}if(u==="exec_command_end"){const s=Array.isArray(t.command)?t.command:t.parsed_cmd??t.command,m=t.exit_code??t.exitCode,p=[typeof t.aggregated_output=="string"?t.aggregated_output:"",m!=null?`
6
- (exit ${String(m)})`:""].join("");x(e,r,n,u,o,i,"command_execution",c,f,a,{command:s},p);return}if(u==="patch_apply_end"){x(e,r,n,u,o,i,"apply_patch",c,f,a,t.changes,{success:t.success,stdout:t.stdout,stderr:t.stderr});return}if(u==="mcp_tool_call_end"){const s=typeof t.invocation=="object"&&t.invocation!==null?t.invocation:null,m=typeof s?.tool=="string"?s.tool:"mcp_tool_call",p={server:s?.server,...typeof s?.arguments=="object"&&s.arguments!==null?s.arguments:{}};x(e,r,n,u,o,i,m,c,f,a,p,t.result);return}if(u==="dynamic_tool_call_request"){const s=typeof t.tool=="string"?t.tool:"dynamic_tool_call";x(e,r,n,u,o,i,s,c,f,a,t.arguments);return}if(u==="dynamic_tool_call_response"){const s=typeof t.tool=="string"?t.tool:"dynamic_tool_call";x(e,r,n,u,o,i,s,c,f,a,t.callId??t.call_id,t.result??t.output);return}if(u==="web_search_end"){const s=typeof t.action=="object"&&t.action!==null?t.action:null;x(e,r,n,u,o,i,"web_search",c,f,a,s??t.query,t.query);return}if(u==="image_generation_end"){const s=typeof t.saved_path=="string"?t.saved_path.trim():"";if(!s)return;C(e,r,n,u,o,i,V(s),c,f,a);return}u==="view_image_tool_call"&&x(e,r,n,u,o,i,"view_image",c,f,a,t.path??t.image_path??t)}}function A(e=!1){return{sourceSessionKey:"",workDir:"",modelId:null,title:"",skipImport:e}}function H(e){if((typeof e.thread_source=="string"?e.thread_source.trim().toLowerCase():"")==="subagent")return!0;const n=typeof e.source=="object"&&e.source!==null?e.source:null;if(n&&typeof n.subagent=="object"&&n.subagent!==null)return!0;const t=typeof e.parent_thread_id=="string"&&e.parent_thread_id.trim().length>0,o=typeof e.agent_nickname=="string"||typeof e.agent_role=="string"||typeof e.multi_agent_version=="string";return t&&o}function ut(e){const r=T.openSync(e,"r");try{const n=[];let t=0,o="";for(;t<1024*1024;){const a=Buffer.alloc(16384),u=T.readSync(r,a,0,a.length,t);if(u<=0)break;const s=a.subarray(0,u);n.push(s),t+=u;const m=Buffer.concat(n),p=m.indexOf(10);if(p>=0){o=m.subarray(0,p).toString("utf8");break}}!o&&n.length>0&&(o=Buffer.concat(n).toString("utf8"));const i=I(o);if(!i||i.type!=="session_meta")return A();const c=typeof i.payload=="object"&&i.payload!==null?i.payload:null;if(!c)return A();if(H(c))return A(!0);const f=typeof c.id=="string"?c.id:"";return{sourceSessionKey:f,workDir:typeof c.cwd=="string"?c.cwd:"",modelId:L(c),title:J(f)??"",skipImport:!1}}finally{T.closeSync(r)}return A()}function L(e){return(typeof e.model=="string"?e.model.trim():"")||null}function ct(e,r){if((typeof e.id=="string"?e.id:typeof e.thread_id=="string"?e.thread_id:typeof e.session_id=="string"?e.session_id:"")!==r)return null;const o=(typeof e.thread_name=="string"?e.thread_name:typeof e.title=="string"?e.title:"").trim();return o?o.slice(0,120):null}function J(e){if(!e)return null;const r=b.join(v.homedir(),".codex","session_index.jsonl");if(!T.existsSync(r))return null;let n=null;return N(r,0,t=>{if(!t.trim())return;const o=I(t);if(!o)return;const i=ct(o,e);i&&(n=i)}),n}function gt(){const e=[b.join(v.homedir(),".codex","sessions"),b.join(v.homedir(),".codex","archived_sessions")],r=[],n=t=>{for(const o of T.readdirSync(t,{withFileTypes:!0})){const i=b.join(t,o.name);o.isDirectory()?n(i):o.isFile()&&o.name.endsWith(".jsonl")&&r.push(i)}};for(const t of e)T.existsSync(t)&&n(t);return[...new Set(r)].sort()}function _t(e,r){const n=[];let{sourceSessionKey:t,workDir:o,modelId:i,title:c,skipImport:f}=ut(e);if(f)return{nextOffset:T.statSync(e).size,events:[]};let a=!1;return{nextOffset:N(e,r,(s,m)=>{const p=I(s);if(!p)return;const S=typeof p.type=="string"?p.type:"",l=typeof p.payload=="object"&&p.payload!==null?p.payload:null,M=D(p.timestamp);if(!(!l||!M)){if(S==="session_meta"){if(H(l)){n.length=0,f=!0;return}t=typeof l.id=="string"?l.id:t,o=typeof l.cwd=="string"?l.cwd:o,i=L(l)??i,c||(c=J(t)??"");return}if(!f&&t){if(S==="response_item"){const y=z(l);y?.role==="user"&&y.titleText&&!c&&(c=y.titleText.slice(0,80)),it(n,e,m,l,t,M,c,i,o);return}if(S==="event_msg"){const y=typeof l.type=="string"?l.type:"";if(tt(y)){let g=!1;for(let _=n.length-1;_>=0;_-=1){const h=n[_];if(h?.agentType==="codex"&&h.role==="agent"&&!q(h.payload)){h.terminal=!0,g=!0,a=!1;break}}if(!g)for(let _=n.length-1;_>=0;_-=1){const h=n[_];if(!(h?.agentType!=="codex"||h.role!=="agent")){h.terminal=!0,g=!0,a=!1;break}}g||(a=!0);return}if(y==="user_message"){const g=F(l);if(g?.titleText&&!c&&(c=g.titleText.slice(0,80)),g){const _=W(n,"user",g.payload,M);_>=0&&n.splice(_,1)}}else if(y==="agent_message"){const g=typeof l.message=="string"?d(l.message):"";if(g&&!j(g)){const _=W(n,"agent",g,M);_>=0&&n.splice(_,1)}}const G=n.length;st(n,e,m,l,t,M,c,i,o),a&&n.length>G&&(n[n.length-1].terminal=!0,a=!1)}}}}),events:n}}export{gt as listCodexRolloutFiles,_t as parseCodexRolloutChunk};
5
+ `)):""}function it(t){if(!Array.isArray(t))return[];const r=[];for(const n of t){if(typeof n!="object"||n===null)continue;const e=n;if(e.type!=="input_image")continue;const o=typeof e.path=="string"?e.path:typeof e.file_path=="string"?e.file_path:typeof e.saved_path=="string"?e.saved_path:typeof e.image_path=="string"?e.image_path:"";o.trim()&&r.push({path:o,name:C.basename(o)||"image.png",mimeType:W(o),kind:"image"})}return r}function G(t){if(t.type!=="message")return null;const r=t.role==="assistant"?"agent":t.role==="user"?"user":null;if(!r)return null;if(r==="agent"){const i=L(t.content,"output_text");return v(i)?null:i?{role:r,payload:i,titleText:i}:null}const n=z(L(t.content,"input_text")),e=n.text,o=it(t.content);return!e&&o.length===0||v(e)&&o.length===0||B(e)&&o.length===0?null:{role:r,payload:o.length>0?N(e,o):e,titleText:e,repairHint:n.strippedWrapper?"codex_app_context_wrapper":void 0}}function J(t){if(!t)return"";try{const r=JSON.parse(t);if(typeof r=="object"&&r!==null){const n=r;if(n.type==="user"&&typeof n.content=="string")return h(n.content)}}catch{}return h(t)}function st(t,r,n,e){return t.agentType!=="codex"||t.role!==r||q(t.payload)||Math.abs(t.ts-e)>300*1e3?!1:J(t.payload)===J(n)}function R(t,r,n,e){for(let o=t.length-1;o>=0;o-=1){const i=t[o];if(i){if(st(i,r,n,e))return o;if(i.agentType==="codex"&&Math.abs(i.ts-e)>300*1e3)break}}return-1}function M(t,r,n,e,o,i,c,f,a,u,s="agent",m=!1,l){c&&t.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:$(r,n,e),cursor:U(r,n),role:s,ts:i,payload:c,title:f,modelId:a,workDir:u,terminal:m,repairHint:l})}function _(t,r,n,e,o,i,c,f,a,u,s,m){const l=$(r,n,e),A=`native:${l}`,y=1,j=m!==void 0?"completed":"running";t.push({agentType:"codex",sourceMode:"codex_rollout_import",sourceSessionKey:o,sourceEventKey:l,cursor:U(r,n),role:"agent",ts:i,payload:D({name:c,toolCallId:A,detailRevision:y,status:j}),title:f,modelId:a,workDir:u,localToolDetail:{toolCallId:A,detailRevision:y,name:c,...s!==void 0?{args:s}:{},...m!==void 0?{result:m}:{},status:j}})}function ut(t,r,n,e,o,i,c,f,a){const u=typeof e.type=="string"?e.type:"";if(u){if(u==="message"){const s=G(e);if(!s||R(t,s.role,s.payload,i)>=0)return;M(t,r,n,`${u}:${s.role}`,o,i,s.payload,c,f,a,s.role,!1,s.repairHint);return}if(u==="function_call"){const s=typeof e.name=="string"?e.name:"function_call";_(t,r,n,u,o,i,s,c,f,a,K(e.arguments));return}if(u==="function_call_output"){_(t,r,n,u,o,i,"function_call_output",c,f,a,e.call_id,e.output);return}if(u==="custom_tool_call"){const s=typeof e.name=="string"?e.name:"custom_tool_call",m=e.input!==void 0?{input:e.input}:void 0;_(t,r,n,u,o,i,s,c,f,a,m);return}if(u==="custom_tool_call_output"){const s=typeof e.name=="string"?e.name:"custom_tool_call_output",m=e.output??e.result??e.content;_(t,r,n,u,o,i,s,c,f,a,e.call_id,m);return}if(u==="web_search_call"){const s=typeof e.action=="object"&&e.action!==null?e.action:null;_(t,r,n,u,o,i,"web_search",c,f,a,s??e.query);return}}}function ct(t,r,n,e,o,i,c,f,a){const u=typeof e.type=="string"?e.type:"";if(u){if(u==="user_message"){const s=H(e);if(!s)return;M(t,r,n,u,o,i,s.payload,c,f,a,"user",!1,s.repairHint);return}if(u==="agent_message"){const s=typeof e.message=="string"?h(e.message):"";if(!s||v(s))return;M(t,r,n,u,o,i,s,c,f,a);return}if(u==="turn_aborted"||u==="error"){const s=typeof e.message=="string"?h(e.message):typeof e.error=="string"?h(e.error):"";if(!s)return;M(t,r,n,u,o,i,s,c,f,a,"agent",!0);return}if(rt(u)){M(t,r,n,u,o,i,ot(e),c,f,a,"agent");return}if(u==="exec_command_end"){const s=Array.isArray(e.command)?e.command:e.parsed_cmd??e.command,m=e.exit_code??e.exitCode,l=[typeof e.aggregated_output=="string"?e.aggregated_output:"",m!=null?`
6
+ (exit ${String(m)})`:""].join("");_(t,r,n,u,o,i,"command_execution",c,f,a,{command:s},l);return}if(u==="patch_apply_end"){_(t,r,n,u,o,i,"apply_patch",c,f,a,e.changes,{success:e.success,stdout:e.stdout,stderr:e.stderr});return}if(u==="mcp_tool_call_end"){const s=typeof e.invocation=="object"&&e.invocation!==null?e.invocation:null,m=typeof s?.tool=="string"?s.tool:"mcp_tool_call",l={server:s?.server,...typeof s?.arguments=="object"&&s.arguments!==null?s.arguments:{}};_(t,r,n,u,o,i,m,c,f,a,l,e.result);return}if(u==="dynamic_tool_call_request"){const s=typeof e.tool=="string"?e.tool:"dynamic_tool_call";_(t,r,n,u,o,i,s,c,f,a,e.arguments);return}if(u==="dynamic_tool_call_response"){const s=typeof e.tool=="string"?e.tool:"dynamic_tool_call";_(t,r,n,u,o,i,s,c,f,a,e.callId??e.call_id,e.result??e.output);return}if(u==="web_search_end"){const s=typeof e.action=="object"&&e.action!==null?e.action:null;_(t,r,n,u,o,i,"web_search",c,f,a,s??e.query,e.query);return}if(u==="image_generation_end"){const s=typeof e.saved_path=="string"?e.saved_path.trim():"";if(!s)return;M(t,r,n,u,o,i,P(s),c,f,a);return}u==="view_image_tool_call"&&_(t,r,n,u,o,i,"view_image",c,f,a,e.path??e.image_path??e)}}function E(t=!1){return{sourceSessionKey:"",workDir:"",modelId:null,title:"",skipImport:t}}function Q(t){if((typeof t.thread_source=="string"?t.thread_source.trim().toLowerCase():"")==="subagent")return!0;const n=typeof t.source=="object"&&t.source!==null?t.source:null;if(n&&typeof n.subagent=="object"&&n.subagent!==null)return!0;const e=typeof t.parent_thread_id=="string"&&t.parent_thread_id.trim().length>0,o=typeof t.agent_nickname=="string"||typeof t.agent_role=="string"||typeof t.multi_agent_version=="string";return e&&o}function ft(t){const r=b.openSync(t,"r");try{const n=[];let e=0,o="";for(;e<1024*1024;){const a=Buffer.alloc(16384),u=b.readSync(r,a,0,a.length,e);if(u<=0)break;const s=a.subarray(0,u);n.push(s),e+=u;const m=Buffer.concat(n),l=m.indexOf(10);if(l>=0){o=m.subarray(0,l).toString("utf8");break}}!o&&n.length>0&&(o=Buffer.concat(n).toString("utf8"));const i=k(o);if(!i||i.type!=="session_meta")return E();const c=typeof i.payload=="object"&&i.payload!==null?i.payload:null;if(!c)return E();if(Q(c))return E(!0);const f=typeof c.id=="string"?c.id:"";return{sourceSessionKey:f,workDir:typeof c.cwd=="string"?c.cwd:"",modelId:V(c),title:X(f)??"",skipImport:!1}}finally{b.closeSync(r)}return E()}function V(t){return(typeof t.model=="string"?t.model.trim():"")||null}function at(t,r){if((typeof t.id=="string"?t.id:typeof t.thread_id=="string"?t.thread_id:typeof t.session_id=="string"?t.session_id:"")!==r)return null;const o=(typeof t.thread_name=="string"?t.thread_name:typeof t.title=="string"?t.title:"").trim();return o?o.slice(0,120):null}function X(t){if(!t)return null;const r=C.join(I.homedir(),".codex","session_index.jsonl");if(!b.existsSync(r))return null;let n=null;return w(r,0,e=>{if(!e.trim())return;const o=k(e);if(!o)return;const i=at(o,t);i&&(n=i)}),n}function _t(){const t=[C.join(I.homedir(),".codex","sessions"),C.join(I.homedir(),".codex","archived_sessions")],r=[],n=e=>{for(const o of b.readdirSync(e,{withFileTypes:!0})){const i=C.join(e,o.name);o.isDirectory()?n(i):o.isFile()&&o.name.endsWith(".jsonl")&&r.push(i)}};for(const e of t)b.existsSync(e)&&n(e);return[...new Set(r)].sort()}function xt(t,r){const n=[],e=ft(t);let{sourceSessionKey:o,workDir:i,modelId:c,title:f,skipImport:a}=e,u=e.title;if(a)return{nextOffset:b.statSync(t).size,events:[]};let s=!1;const m=w(t,r,(l,A)=>{const y=k(l);if(!y)return;const j=typeof y.type=="string"?y.type:"",p=typeof y.payload=="object"&&y.payload!==null?y.payload:null,S=O(y.timestamp);if(!(!p||!S)){if(j==="session_meta"){if(Q(p)){n.length=0,a=!0;return}o=typeof p.id=="string"?p.id:o,i=typeof p.cwd=="string"?p.cwd:i,c=V(p)??c;const x=X(o);x&&(u=x,f=x);return}if(!a&&o){if(j==="response_item"){const x=G(p);x?.role==="user"&&x.titleText&&!f&&(f=x.titleText.slice(0,80)),ut(n,t,A,p,o,S,f,c,i);return}if(j==="event_msg"){const x=typeof p.type=="string"?p.type:"";if(nt(x)){let g=!1;for(let d=n.length-1;d>=0;d-=1){const T=n[d];if(T?.agentType==="codex"&&T.role==="agent"&&!q(T.payload)){T.terminal=!0,g=!0,s=!1;break}}if(!g)for(let d=n.length-1;d>=0;d-=1){const T=n[d];if(!(T?.agentType!=="codex"||T.role!=="agent")){T.terminal=!0,g=!0,s=!1;break}}g||(s=!0);return}if(x==="user_message"){const g=H(p);if(g?.titleText&&!f&&(f=g.titleText.slice(0,80)),g){const d=R(n,"user",g.payload,S);d>=0&&n.splice(d,1)}}else if(x==="agent_message"){const g=typeof p.message=="string"?h(p.message):"";if(g&&!v(g)){const d=R(n,"agent",g,S);d>=0&&n.splice(d,1)}}const Y=n.length;ct(n,t,A,p,o,S,f,c,i),s&&n.length>Y&&(n[n.length-1].terminal=!0,s=!1)}}}});for(const l of n)l.titleSource=u&&l.title===u?"agent_native":"first_user_fallback";return{nextOffset:m,events:n}}export{_t as listCodexRolloutFiles,X as lookupCodexThreadName,xt as parseCodexRolloutChunk};
@@ -0,0 +1,18 @@
1
+ type WatchHandle = {
2
+ close(): void;
3
+ };
4
+ type WatchListener = (eventType: string, filename: string | Buffer | null) => void;
5
+ type WatchFactory = (directory: string, listener: WatchListener) => WatchHandle;
6
+ export declare class NativeFusionFileWatcher {
7
+ private onChanged;
8
+ private watchFactory;
9
+ private watchers;
10
+ private filesByDirectory;
11
+ private debounceTimers;
12
+ constructor(onChanged: (filePaths: string[]) => void, watchFactory?: WatchFactory);
13
+ refresh(filePaths: readonly string[]): void;
14
+ stop(): void;
15
+ private handleChange;
16
+ private schedule;
17
+ }
18
+ export {};
@@ -0,0 +1 @@
1
+ import h from"node:fs";import i from"node:path";const a=250;class f{onChanged;watchFactory;watchers=new Map;filesByDirectory=new Map;debounceTimers=new Map;constructor(t,s=(e,o)=>h.watch(e,o)){this.onChanged=t,this.watchFactory=s}refresh(t){const s=new Map;for(const e of t){const o=i.dirname(e),r=s.get(o)??new Set;r.add(e),s.set(o,r)}for(const[e,o]of this.watchers.entries())s.has(e)||(o.close(),this.watchers.delete(e));this.filesByDirectory=s;for(const e of s.keys())if(!this.watchers.has(e))try{const o=this.watchFactory(e,(r,n)=>{this.handleChange(e,n)});this.watchers.set(e,o)}catch(o){console.warn(`[native-fusion] unable to watch ${e}`,o)}}stop(){for(const t of this.watchers.values())t.close();this.watchers.clear(),this.filesByDirectory.clear();for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear()}handleChange(t,s){const e=s?i.join(t,s.toString()):null,o=e&&d(e)?[e]:[...this.filesByDirectory.get(t)??[]];for(const r of o)this.schedule(r)}schedule(t){const s=this.debounceTimers.get(t);s&&clearTimeout(s);const e=setTimeout(()=>{this.debounceTimers.delete(t),this.onChanged([t])},a);this.debounceTimers.set(t,e)}}function d(c){return c.endsWith(".jsonl")||c.endsWith(".opencode-session.json")}export{f as NativeFusionFileWatcher};
@@ -0,0 +1,52 @@
1
+ import type { CanonicalSessionStore } from '../session/canonical-store.js';
2
+ import { listSessionRecords, recordSession } from '../session/store.js';
3
+ import type { ParsedNativeEvent } from './types.js';
4
+ import { type LocalToolDetail } from '../session/tool-detail-store.js';
5
+ declare const SCHEMA_VERSION: 1;
6
+ export declare class MissingUserBoundaryError extends Error {
7
+ readonly code = "missing_user_boundary";
8
+ constructor(sourceSessionKey: string);
9
+ }
10
+ type SourceBinding = {
11
+ schemaVersion: typeof SCHEMA_VERSION;
12
+ daemonInstallationId: string;
13
+ sessionId: string;
14
+ agentType: ParsedNativeEvent['agentType'];
15
+ sourceSessionKey: string;
16
+ sourceMode: ParsedNativeEvent['sourceMode'];
17
+ lastCursor: string | null;
18
+ bodyRevision: number;
19
+ createdAt: string;
20
+ updatedAt: string;
21
+ };
22
+ export type NativeLocalCommitResult = {
23
+ sessionId: string;
24
+ messageId: string;
25
+ bodyRevision: number;
26
+ duplicate: boolean;
27
+ claimed: boolean;
28
+ };
29
+ type RecordSessionInput = Parameters<typeof recordSession>[0];
30
+ export declare class NativeFusionLocalRepository {
31
+ private options;
32
+ constructor(options?: {
33
+ rootDir?: string;
34
+ daemonInstallationId?: string;
35
+ canonicalStore?: CanonicalSessionStore;
36
+ recordLocalSession?: (input: RecordSessionInput) => unknown;
37
+ listLocalSessions?: typeof listSessionRecords;
38
+ writeLocalToolDetail?: (detail: Omit<LocalToolDetail, 'schemaVersion'>) => void;
39
+ });
40
+ commitEvents(events: readonly ParsedNativeEvent[]): NativeLocalCommitResult[];
41
+ commitEvent(event: ParsedNativeEvent): NativeLocalCommitResult;
42
+ listSourceBindings(): SourceBinding[];
43
+ observeNativeTitle(agentType: ParsedNativeEvent['agentType'], sourceSessionKey: string, titleValue: string): boolean;
44
+ private recordIndex;
45
+ private readSources;
46
+ private installationId;
47
+ private canonicalStore;
48
+ private rootDir;
49
+ private sourcesFile;
50
+ private ledgerFile;
51
+ }
52
+ export {};
@@ -0,0 +1,2 @@
1
+ import d from"node:crypto";import a from"node:fs";import w from"node:path";import{resolvePersonalSyncV1Path as M}from"../personal-sync/paths.js";import{getCanonicalSessionStore as F,getDaemonInstallationId as _,listSessionRecords as k,recordSession as K}from"../session/store.js";import{writeToolDetail as B}from"../session/tool-detail-store.js";const S=1;class C extends Error{code="missing_user_boundary";constructor(e){super(`native source ${e} does not start at a visible user boundary`),this.name="MissingUserBoundaryError"}}class W{options;constructor(e={}){this.options=e}commitEvents(e){return[...e].sort((o,t)=>o.ts-t.ts).map(o=>this.commitEvent(o))}commitEvent(e){O(e);const o=this.installationId(),t=this.readSources(),i=x(e.agentType,e.sourceSessionKey),r=t.sources[i],l=A(e),u=this.ledgerFile(e.agentType,e.sourceEventKey),n=a.existsSync(u)?D(u):null;if(n&&n.eventFingerprint!==l)throw new Error(`native event identity conflict: ${e.sourceEventKey}`);if(!r&&!n&&e.role!=="user")throw new C(e.sourceSessionKey);const g=e.claimSessionId??null,c=r?.sessionId??n?.sessionId??g??H(o,e.agentType,e.sourceSessionKey);if(g&&r&&r.sessionId!==g)throw new Error(`managed claim session conflicts with source binding ${e.sourceSessionKey}`);const f=this.canonicalStore(),p=e.claimCanonicalMessageId??R(o,e.agentType,e.sourceEventKey);let y=f.getManifest(c)?.bodyRevision??0,E=!!n;const m=!!e.claimCanonicalMessageId;if(m){const h=f.getMessageState(c,p);if(!h||h.tombstoned)throw new Error(`managed echo claim target is not durable: ${p}`)}if(!n&&!m){const h={id:p,sessionId:c,role:e.role,ts:e.ts,payload:e.payload},$=f.append(c,h);y=$.bodyRevision,E=$.duplicate,e.localToolDetail&&(this.options.writeLocalToolDetail??B)({sessionId:c,...e.localToolDetail,ts:e.ts,detailRef:{toolIndex:0}})}n||this.recordIndex(e,c);const I=new Date().toISOString();return n||b(u,{schemaVersion:S,daemonInstallationId:o,sessionId:c,agentType:e.agentType,sourceSessionKey:e.sourceSessionKey,sourceEventKey:e.sourceEventKey,eventFingerprint:l,canonicalMessageId:p,canonicalRevision:y,cursor:e.cursor??null,mappedBy:m?"managed_echo_claim":e.sourceMode,eventTs:e.ts,createdAt:I}),t.sources[i]={schemaVersion:S,daemonInstallationId:o,sessionId:c,agentType:e.agentType,sourceSessionKey:e.sourceSessionKey,sourceMode:n?r?.sourceMode??e.sourceMode:e.sourceMode,lastCursor:n?r?.lastCursor??n.cursor:e.cursor??r?.lastCursor??null,bodyRevision:y,createdAt:r?.createdAt??I,updatedAt:I},b(this.sourcesFile(),t),{sessionId:c,messageId:p,bodyRevision:y,duplicate:E,claimed:m}}listSourceBindings(){return Object.values(this.readSources().sources)}observeNativeTitle(e,o,t){const i=t.trim().slice(0,120);if(!i)return!1;const r=this.readSources().sources[x(e,o)];if(!r)return!1;const l=(this.options.listLocalSessions??k)().find(g=>g.sessionId===r.sessionId);if(l?.titleLockedByUser||l?.titleSource==="agent_native"&&l.title===i)return!1;const u=d.createHash("sha256").update(`${e}\0${o}\0${i}`).digest("hex");return(this.options.recordLocalSession??K)({sessionId:r.sessionId,agentType:r.agentType,workDir:l?.workDir??"",agentSessionId:o,title:i,titleSource:"agent_native",titleOriginEventId:`agent-native:${u}`}),!0}recordIndex(e,o){(this.options.recordLocalSession??K)({sessionId:o,agentType:e.agentType,workDir:e.workDir??"",agentSessionId:e.sourceSessionKey,modelId:e.modelId??null,status:e.terminal?"completed":"active",lastActivityAt:new Date(e.ts).toISOString(),lastMessagePreview:e.role==="user"?T(e.payload):void 0,title:e.title?.trim()||(e.role==="user"?T(e.payload)??"":void 0),titleSource:e.title?.trim()?e.titleSource??"first_user_fallback":"first_user_fallback",titleOriginEventId:e.sourceEventKey})}readSources(){const e=this.sourcesFile();if(!a.existsSync(e))return{schemaVersion:S,daemonInstallationId:this.installationId(),sources:{}};const o=D(e);if(o.schemaVersion!==S||o.daemonInstallationId!==this.installationId()||!o.sources)throw new Error("invalid native source binding store");return o}installationId(){return this.options.daemonInstallationId??_()}canonicalStore(){return this.options.canonicalStore??F()}rootDir(){return this.options.rootDir??M("native-fusion")}sourcesFile(){return w.join(this.rootDir(),"sources.json")}ledgerFile(e,o){const t=d.createHash("sha256").update(`${e}\0${o}`).digest("hex");return w.join(this.rootDir(),"ledger",`${t}.json`)}}function O(s){if(!s.agentType||!s.sourceSessionKey||!s.sourceEventKey||!s.payload)throw new Error("invalid native event");if(!Number.isFinite(s.ts))throw new Error("invalid native event timestamp")}function x(s,e){return d.createHash("sha256").update(`${s}\0${e}`).digest("hex")}function H(s,e,o){return`native-session-${d.createHash("sha256").update(`${s}\0${e}\0${o}`).digest("hex").slice(0,32)}`}function R(s,e,o){return`native-${d.createHash("sha256").update(`${s}\0${e}\0${o}`).digest("hex").slice(0,32)}`}function A(s){return d.createHash("sha256").update(JSON.stringify({agentType:s.agentType,sourceSessionKey:s.sourceSessionKey,sourceEventKey:s.sourceEventKey,role:s.role,ts:s.ts,payload:s.payload,claimCanonicalMessageId:s.claimCanonicalMessageId??null,claimSessionId:s.claimSessionId??null})).digest("hex")}function T(s){const e=s.replace(/\s+/g," ").trim();return e?e.length>120?`${e.slice(0,120)}...`:e:null}function b(s,e){const o=w.dirname(s);a.mkdirSync(o,{recursive:!0,mode:448});const t=`${s}.tmp-${process.pid}-${d.randomBytes(6).toString("hex")}`;let i;try{i=a.openSync(t,"wx",384),a.writeFileSync(i,`${JSON.stringify(e,null,2)}
2
+ `,"utf8"),a.fsyncSync(i),a.closeSync(i),i=void 0,a.renameSync(t,s)}finally{i!==void 0&&a.closeSync(i);try{a.unlinkSync(t)}catch{}}}function D(s){return JSON.parse(a.readFileSync(s,"utf8"))}export{C as MissingUserBoundaryError,W as NativeFusionLocalRepository};
@@ -1,3 +1,3 @@
1
- import d from"node:fs";import g from"node:os";import p from"node:path";import{resolveBuiltinCommand as _,spawnResolvedCommandSync as S}from"../agents/command-spec.js";function m(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}function O(t){return t.filter(e=>e.type==="text"||e.type==="reasoning").map(e=>typeof e.text=="string"?e.text:"").filter(Boolean).join(`
1
+ import d from"node:fs";import _ from"node:os";import u from"node:path";import{resolveBuiltinCommand as S,spawnResolvedCommandSync as v}from"../agents/command-spec.js";import{normalizeNativeTimestamp as f}from"./session-header.js";function l(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null?e:null}catch{return null}}function O(t){return t.filter(e=>e.type==="text"||e.type==="reasoning").map(e=>typeof e.text=="string"?e.text:"").filter(Boolean).join(`
2
2
 
3
- `).trim()}function h(t,e,s,r,c,n,i,o){n&&t.push({agentType:"opencode",sourceMode:"opencode_session_import",sourceSessionKey:s.id,sourceEventKey:`opencode:${s.id}:${r.id}:${c}`,cursor:`${e}:${r.time_created}:${r.id}`,role:c,ts:r.time_created,payload:n,title:s.title,modelId:i,workDir:s.directory,terminal:o})}function v(t,e){const s=[],r=new Map(e.sessions.map(n=>[n.id,n])),c=new Map;for(const n of e.parts){const i=m(n.data);if(!i)continue;const o=c.get(n.message_id)??[];o.push(i),c.set(n.message_id,o)}for(const n of[...e.messages].sort((i,o)=>i.time_created-o.time_created)){const i=r.get(n.session_id);if(!i)continue;const o=m(n.data);if(!o)continue;const a=o.role==="user"?"user":o.role==="assistant"?"agent":null;if(!a)continue;const f=c.get(n.id)??[],l=O(f),y=typeof o.modelID=="string"?`${typeof o.providerID=="string"?`${o.providerID}/`:""}${o.modelID}`:null;h(s,t,i,n,a,l,y,a==="agent")}return s}function w(){const t=p.join(g.homedir(),".local","share","opencode"),e=p.join(t,"shennian-opencode-session-snapshot.opencode-session.json");return x(e),d.existsSync(e)?[e]:[]}function u(t){const e=_("opencode");if(!e)return[];const s=S(e,["db",t,"--format","json"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e4});if(s.status!==0)return[];try{const r=JSON.parse(String(s.stdout??""));return Array.isArray(r)?r:[]}catch{return[]}}function x(t){try{const e=u("select id, title, directory, time_created, time_updated from session where time_archived is null order by time_updated asc");if(e.length===0)return;const s=u("select id, session_id, time_created, data from message order by time_created asc, id asc"),r=u("select id, message_id, session_id, time_created, data from part order by message_id asc, id asc");d.mkdirSync(p.dirname(t),{recursive:!0}),d.writeFileSync(t,JSON.stringify({sessions:e,messages:s,parts:r}))}catch{}}function D(t,e){const s=d.statSync(t);if(e>=s.size)return{nextOffset:s.size,events:[]};if(e>0)return{nextOffset:s.size,events:[]};const r=JSON.parse(d.readFileSync(t,"utf8"));return{nextOffset:s.size,events:v(t,r)}}export{w as listOpenCodeSessionFiles,D as parseOpenCodeSessionFile,v as parseOpenCodeSessionSnapshot};
3
+ `).trim()}function h(t,e,s,r,c,n,i,o){if(!n)return;const a=f(r.time_created),p=f(s.time_created);!a||!p||t.push({agentType:"opencode",sourceMode:"opencode_session_import",sourceSessionKey:s.id,sourceEventKey:`opencode:${s.id}:${r.id}:${c}`,cursor:`${e}:${r.time_created}:${r.id}`,role:c,ts:a,payload:n,title:s.title,titleSource:"agent_native",modelId:i,workDir:s.directory,terminal:o,sourceSessionCreatedAtMs:p})}function x(t,e){const s=[],r=new Map(e.sessions.map(n=>[n.id,n])),c=new Map;for(const n of e.parts){const i=l(n.data);if(!i)continue;const o=c.get(n.message_id)??[];o.push(i),c.set(n.message_id,o)}for(const n of[...e.messages].sort((i,o)=>i.time_created-o.time_created)){const i=r.get(n.session_id);if(!i)continue;const o=l(n.data);if(!o)continue;const a=o.role==="user"?"user":o.role==="assistant"?"agent":null;if(!a)continue;const p=c.get(n.id)??[],y=O(p),g=typeof o.modelID=="string"?`${typeof o.providerID=="string"?`${o.providerID}/`:""}${o.modelID}`:null;h(s,t,i,n,a,y,g,a==="agent")}return s}function I(){const t=u.join(_.homedir(),".local","share","opencode"),e=u.join(t,"shennian-opencode-session-snapshot.opencode-session.json");return C(e),d.existsSync(e)?[e]:[]}function m(t){const e=S("opencode");if(!e)return[];const s=v(e,["db",t,"--format","json"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1e4});if(s.status!==0)return[];try{const r=JSON.parse(String(s.stdout??""));return Array.isArray(r)?r:[]}catch{return[]}}function C(t){try{const e=m("select id, title, directory, time_created, time_updated from session where time_archived is null order by time_updated asc");if(e.length===0)return;const s=m("select id, session_id, time_created, data from message order by time_created asc, id asc"),r=m("select id, message_id, session_id, time_created, data from part order by message_id asc, id asc");d.mkdirSync(u.dirname(t),{recursive:!0}),d.writeFileSync(t,JSON.stringify({sessions:e,messages:s,parts:r}))}catch{}}function z(t,e){const s=d.statSync(t);if(e>=s.size)return{nextOffset:s.size,events:[]};if(e>0)return{nextOffset:s.size,events:[]};const r=JSON.parse(d.readFileSync(t,"utf8"));return{nextOffset:s.size,events:x(t,r)}}export{I as listOpenCodeSessionFiles,z as parseOpenCodeSessionFile,x as parseOpenCodeSessionSnapshot};
@@ -15,7 +15,13 @@ export declare function makeEventKey(filePath: string, offset: number, kind: str
15
15
  export declare function safeStringify(value: unknown): string;
16
16
  export declare function normalizeToolText(text: string): string;
17
17
  export declare function parseStructuredString(value: unknown): unknown;
18
- export declare function buildToolPayload(name: string, args?: unknown, result?: unknown): string;
18
+ export declare function buildToolPayload(input: {
19
+ name: string;
20
+ toolCallId: string;
21
+ detailRevision: number;
22
+ status: 'running' | 'completed' | 'failed';
23
+ durationMs?: number;
24
+ }): string;
19
25
  export declare function escapeMarkdownLabel(label: string): string;
20
26
  export declare function buildMarkdownImageRef(filePath: string, label?: string): string;
21
27
  export declare function buildImagePayload(filePath: string): string;
@@ -1,4 +1,4 @@
1
- import{createHash as N}from"node:crypto";import m from"node:fs";import C from"node:os";import n from"node:path";import{buildToolArgsSummary as E}from"../session/tool-summary.js";const h=64*1024*1024,x=["/root/.claude-mem/observer-session"],I=x.map(D);function R(e){return w(e.replace(/\r\n/g,`
2
- `).trim())}const _=/^\s*::git-[a-z-]+\{[^\n]*\}\s*$/gm;function w(e){if(!e)return"";if(!/(^|\n)\s*::git-[a-z-]+\{[^\n]*\}\s*(?=\n|$)/.test(e))return e;const r=e.replace(_,"");return r.trim()?r.replace(/[ \t]+\n/g,`
3
- `).replace(/\n+$/g,""):""}function v(e){if(typeof e!="string")return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function F(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}function G(e,t,r){const s=m.statSync(e).size;if(t>=s)return s;const y=m.openSync(e,"r");try{const S=Buffer.allocUnsafe(262144);let l=t,p=t,o=Buffer.alloc(0),f=!1;for(;l<s;){const g=m.readSync(y,S,0,Math.min(262144,s-l),l);if(g<=0)break;l+=g;let c=S.subarray(0,g);o.length>0&&(c=Buffer.concat([o,c]),o=Buffer.alloc(0));let u=0;for(;u<c.length;){const a=c.indexOf(10,u);if(a<0)break;const d=c.subarray(u,a),T=p;p+=a-u+1,u=a+1,!f&&d.length>0&&d.length<=h&&r(d.toString("utf8"),T),f=!1}if(u<c.length){const a=c.subarray(u);f||a.length>h?(f=!0,p+=a.length,o=Buffer.alloc(0)):o=Buffer.from(a)}}return!f&&o.length>0&&o.length<=h&&r(o.toString("utf8"),p),s}finally{m.closeSync(y)}}function M(e){return typeof e.cwd=="string"&&e.cwd.trim()?e.cwd:null}function U(e){return n.basename(n.dirname(e))==="subagents"}function b(e){const t=n.resolve(e);return process.platform==="win32"?t.toLowerCase():t}function z(e,t){const r=b(e),i=b(t);return r===i||r.startsWith(i+n.sep)}function D(e){return n.resolve(e).replace(/\//g,"-")}function V(e){return x.some(t=>z(e,t))}function O(e){return I.includes(e)}function H(e){const t=n.join(C.homedir(),".claude","projects"),r=n.relative(t,e);if(!r||r.startsWith("..")||n.isAbsolute(r))return!1;const[i]=r.split(n.sep);return i?O(i):!1}function W(e,t){return`${e}:${t}`}function K(e,t,r){return`${N("sha1").update(e).digest("hex").slice(0,16)}:${t}:${r}`}function X(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Y(e){return e.replace(/\r\n/g,`
4
- `).trim()}function q(e){if(typeof e!="string")return e;const t=e.trim();if(!t)return"";try{return JSON.parse(t)}catch{return e}}function Q(e,t,r){const i=E(t),s={v:1,type:"tool",name:e,status:r!==void 0?"completed":"running",resultOmitted:!0,...i!==void 0?{argsSummary:i}:{}};return JSON.stringify(s)}function k(e){return e.replace(/[[\]\\]/g,"\\$&")}function A(e,t="Generated image"){return`![${k(t)}](<${e}>)`}function Z(e){const t=n.basename(e)||"generated-image.png";return JSON.stringify({v:1,type:"image",content:A(e,t),attachments:[{path:e,name:t,mimeType:"image/png",kind:"image"}]})}function ee(e){const t=n.extname(e).toLowerCase();return t===".png"?"image/png":t===".jpg"||t===".jpeg"?"image/jpeg":t===".webp"?"image/webp":t===".gif"?"image/gif":"application/octet-stream"}export{Z as buildImagePayload,A as buildMarkdownImageRef,Q as buildToolPayload,D as encodeClaudeProjectDir,k as escapeMarkdownLabel,ee as inferMimeType,U as isClaudeSubagentTranscript,z as isSameOrChildPath,W as makeCursor,K as makeEventKey,b as normalizePathForCompare,R as normalizeText,Y as normalizeToolText,q as parseStructuredString,M as readClaudeEventCwd,G as readJsonlLines,v as readTimestamp,F as safeParse,X as safeStringify,O as shouldIgnoreClaudeProjectDir,H as shouldIgnoreClaudeTranscriptPath,V as shouldIgnoreNativeScanPath};
1
+ import{createHash as I}from"node:crypto";import m from"node:fs";import T from"node:os";import n from"node:path";const x=64*1024*1024,S=["/root/.claude-mem/observer-session"],N=S.map(z);function j(e){return _(e.replace(/\r\n/g,`
2
+ `).trim())}const E=/^\s*::git-[a-z-]+\{[^\n]*\}\s*$/gm;function _(e){if(!e)return"";if(!/(^|\n)\s*::git-[a-z-]+\{[^\n]*\}\s*(?=\n|$)/.test(e))return e;const r=e.replace(E,"");return r.trim()?r.replace(/[ \t]+\n/g,`
3
+ `).replace(/\n+$/g,""):""}function v(e){if(typeof e!="string")return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function B(e){try{const t=JSON.parse(e);return typeof t=="object"&&t!==null?t:null}catch{return null}}function J(e,t,r){const u=m.statSync(e).size;if(t>=u)return u;const h=m.openSync(e,"r");try{const y=Buffer.allocUnsafe(262144);let l=t,f=t,c=Buffer.alloc(0),p=!1;for(;l<u;){const d=m.readSync(h,y,0,Math.min(262144,u-l),l);if(d<=0)break;l+=d;let a=y.subarray(0,d);c.length>0&&(a=Buffer.concat([c,a]),c=Buffer.alloc(0));let s=0;for(;s<a.length;){const i=a.indexOf(10,s);if(i<0)break;const g=a.subarray(s,i),C=f;f+=i-s+1,s=i+1,!p&&g.length>0&&g.length<=x&&r(g.toString("utf8"),C),p=!1}if(s<a.length){const i=a.subarray(s);p||i.length>x?(p=!0,f+=i.length,c=Buffer.alloc(0)):c=Buffer.from(i)}}return f}finally{m.closeSync(h)}}function M(e){return typeof e.cwd=="string"&&e.cwd.trim()?e.cwd:null}function F(e){return n.basename(n.dirname(e))==="subagents"}function b(e){const t=n.resolve(e);return process.platform==="win32"?t.toLowerCase():t}function w(e,t){const r=b(e),o=b(t);return r===o||r.startsWith(o+n.sep)}function z(e){return n.resolve(e).replace(/\//g,"-")}function G(e){return S.some(t=>w(e,t))}function D(e){return N.includes(e)}function U(e){const t=n.join(T.homedir(),".claude","projects"),r=n.relative(t,e);if(!r||r.startsWith("..")||n.isAbsolute(r))return!1;const[o]=r.split(n.sep);return o?D(o):!1}function V(e,t){return`${e}:${t}`}function H(e,t,r){return`${I("sha1").update(e).digest("hex").slice(0,16)}:${t}:${r}`}function W(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function K(e){return e.replace(/\r\n/g,`
4
+ `).trim()}function X(e){if(typeof e!="string")return e;const t=e.trim();if(!t)return"";try{return JSON.parse(t)}catch{return e}}function Y(e){const t={v:1,type:"tool",name:e.name,toolCallId:e.toolCallId,detailRevision:e.detailRevision,status:e.status,resultOmitted:!0,detailAvailable:!0,...e.durationMs!==void 0?{durationMs:e.durationMs}:{}};return JSON.stringify(t)}function O(e){return e.replace(/[[\]\\]/g,"\\$&")}function k(e,t="Generated image"){return`![${O(t)}](<${e}>)`}function q(e){const t=n.basename(e)||"generated-image.png";return JSON.stringify({v:1,type:"image",content:k(e,t),attachments:[{path:e,name:t,mimeType:"image/png",kind:"image"}]})}function Q(e){const t=n.extname(e).toLowerCase();return t===".png"?"image/png":t===".jpg"||t===".jpeg"?"image/jpeg":t===".webp"?"image/webp":t===".gif"?"image/gif":"application/octet-stream"}export{q as buildImagePayload,k as buildMarkdownImageRef,Y as buildToolPayload,z as encodeClaudeProjectDir,O as escapeMarkdownLabel,Q as inferMimeType,F as isClaudeSubagentTranscript,w as isSameOrChildPath,V as makeCursor,H as makeEventKey,b as normalizePathForCompare,j as normalizeText,K as normalizeToolText,X as parseStructuredString,M as readClaudeEventCwd,J as readJsonlLines,v as readTimestamp,B as safeParse,W as safeStringify,D as shouldIgnoreClaudeProjectDir,U as shouldIgnoreClaudeTranscriptPath,G as shouldIgnoreNativeScanPath};
@@ -1,5 +1,6 @@
1
1
  import type { ParsedNativeEvent } from './types.js';
2
- export { listCodexRolloutFiles, parseCodexRolloutChunk } from './codex-parser.js';
2
+ export { listCodexRolloutFiles, lookupCodexThreadName, parseCodexRolloutChunk, } from './codex-parser.js';
3
+ export { inspectNativeSessionFile, normalizeNativeTimestamp } from './session-header.js';
3
4
  export { listOpenCodeSessionFiles, parseOpenCodeSessionFile, parseOpenCodeSessionSnapshot, type OpenCodeSnapshot, } from './opencode-parser.js';
4
5
  export declare function listClaudeTranscriptFiles(): string[];
5
6
  export declare function lookupClaudeTranscriptCwd(sourceSessionKey: string): string | null;
@@ -1,3 +1,3 @@
1
- import g from"node:fs";import C from"node:os";import c from"node:path";import{listCodexRolloutFiles as q,parseCodexRolloutChunk as G}from"./codex-parser.js";import{listOpenCodeSessionFiles as Q,parseOpenCodeSessionFile as U,parseOpenCodeSessionSnapshot as V}from"./opencode-parser.js";import{makeCursor as j,makeEventKey as h,normalizeText as k,readClaudeEventCwd as v,readJsonlLines as S,readTimestamp as F,safeParse as T,isClaudeSubagentTranscript as E,shouldIgnoreClaudeProjectDir as I,shouldIgnoreClaudeTranscriptPath as O,shouldIgnoreNativeScanPath as b}from"./parser-common.js";function _(e){const r=C.homedir();return e.startsWith(r)?e.slice(r.length).replace(/^\//,"")||"~":e.replace(/\//g,"-")}function z(){const e=c.join(C.homedir(),".claude","projects");if(!g.existsSync(e))return[];const r=[],o=t=>{for(const n of g.readdirSync(t,{withFileTypes:!0})){const i=c.join(t,n.name);if(n.isDirectory()){if(t===e&&I(n.name))continue;o(i)}else n.isFile()&&n.name.endsWith(".jsonl")&&r.push(i)}};return o(e),r.sort()}function B(e){if(!e)return null;const r=z().find(t=>c.basename(t,".jsonl")===e);if(!r)return null;let o=null;return S(r,0,t=>{if(o||!t.trim())return;const n=T(t);if(!n)return;const i=v(n);i&&(o=i)}),o}function J(e,r){const o=g.statSync(e).size;if(E(e)||O(e))return{nextOffset:o,events:[]};const t=[],n=c.basename(e,".jsonl"),i=_(c.dirname(e).replace(c.join(C.homedir(),".claude","projects")+c.sep,""));if(b(i))return{nextOffset:o,events:[]};let l="";return{nextOffset:S(e,r,(w,p)=>{const s=T(w);if(!s)return;const f=F(s.timestamp),y=typeof s.type=="string"?s.type:"";if(!f||!y)return;const d=v(s);if(!(d&&b(d))){if(y==="user"){const a=typeof s.message=="object"&&s.message!==null?s.message:null,u=typeof a?.content=="string"?k(a.content):"";if(!u)return;l||(l=u.slice(0,80)),t.push({agentType:"claude",sourceMode:"claude_transcript_import",sourceSessionKey:n,sourceEventKey:h(e,p,"user"),cursor:j(e,p),role:"user",ts:f,payload:u,title:l,workDir:d??i})}else if(y==="assistant"){const a=typeof s.message=="object"&&s.message!==null?s.message:null,u=Array.isArray(a?.content)?a.content:[],x=k(u.map(m=>typeof m=="object"&&m!==null&&typeof m.text=="string"?m.text:"").filter(Boolean).join(`
1
+ import g from"node:fs";import x from"node:os";import l from"node:path";import{listCodexRolloutFiles as q,lookupCodexThreadName as G,parseCodexRolloutChunk as H}from"./codex-parser.js";import{inspectNativeSessionFile as U,normalizeNativeTimestamp as V}from"./session-header.js";import{listOpenCodeSessionFiles as Y,parseOpenCodeSessionFile as Z,parseOpenCodeSessionSnapshot as $}from"./opencode-parser.js";import{makeCursor as j,makeEventKey as h,normalizeText as k,readClaudeEventCwd as S,readJsonlLines as v,readTimestamp as w,safeParse as T,isClaudeSubagentTranscript as D,shouldIgnoreClaudeProjectDir as z,shouldIgnoreClaudeTranscriptPath as E,shouldIgnoreNativeScanPath as b}from"./parser-common.js";function I(e){const n=x.homedir();return e.startsWith(n)?e.slice(n.length).replace(/^\//,"")||"~":e.replace(/\//g,"-")}function N(){const e=l.join(x.homedir(),".claude","projects");if(!g.existsSync(e))return[];const n=[],o=t=>{for(const r of g.readdirSync(t,{withFileTypes:!0})){const i=l.join(t,r.name);if(r.isDirectory()){if(t===e&&z(r.name))continue;o(i)}else r.isFile()&&r.name.endsWith(".jsonl")&&n.push(i)}};return o(e),n.sort()}function R(e){if(!e)return null;const n=N().find(t=>l.basename(t,".jsonl")===e);if(!n)return null;let o=null;return v(n,0,t=>{if(o||!t.trim())return;const r=T(t);if(!r)return;const i=S(r);i&&(o=i)}),o}function B(e,n){const o=g.statSync(e).size;if(D(e)||E(e))return{nextOffset:o,events:[]};const t=[],r=l.basename(e,".jsonl"),i=I(l.dirname(e).replace(l.join(x.homedir(),".claude","projects")+l.sep,""));if(b(i))return{nextOffset:o,events:[]};let u="";return{nextOffset:v(e,n,(_,p)=>{const s=T(_);if(!s)return;const d=w(s.timestamp),y=typeof s.type=="string"?s.type:"";if(!d||!y)return;const m=S(s);if(!(m&&b(m))){if(y==="user"){const a=typeof s.message=="object"&&s.message!==null?s.message:null,c=typeof a?.content=="string"?k(a.content):"";if(!c)return;u||(u=c.slice(0,80)),t.push({agentType:"claude",sourceMode:"claude_transcript_import",sourceSessionKey:r,sourceEventKey:h(e,p,"user"),cursor:j(e,p),role:"user",ts:d,payload:c,title:u,titleSource:"first_user_fallback",workDir:m??i})}else if(y==="assistant"){const a=typeof s.message=="object"&&s.message!==null?s.message:null,c=Array.isArray(a?.content)?a.content:[],C=k(c.map(f=>typeof f=="object"&&f!==null&&typeof f.text=="string"?f.text:"").filter(Boolean).join(`
2
2
 
3
- `));if(!x)return;const D=typeof a?.model=="string"?a.model:null;t.push({agentType:"claude",sourceMode:"claude_transcript_import",sourceSessionKey:n,sourceEventKey:h(e,p,"assistant"),cursor:j(e,p),role:"agent",ts:f,payload:x,title:l,modelId:D,workDir:d??i})}}}),events:t}}export{z as listClaudeTranscriptFiles,q as listCodexRolloutFiles,Q as listOpenCodeSessionFiles,B as lookupClaudeTranscriptCwd,J as parseClaudeTranscriptChunk,G as parseCodexRolloutChunk,U as parseOpenCodeSessionFile,V as parseOpenCodeSessionSnapshot};
3
+ `));if(!C)return;const F=typeof a?.model=="string"?a.model:null;t.push({agentType:"claude",sourceMode:"claude_transcript_import",sourceSessionKey:r,sourceEventKey:h(e,p,"assistant"),cursor:j(e,p),role:"agent",ts:d,payload:C,title:u,titleSource:"first_user_fallback",modelId:F,workDir:m??i})}}}),events:t}}export{U as inspectNativeSessionFile,N as listClaudeTranscriptFiles,q as listCodexRolloutFiles,Y as listOpenCodeSessionFiles,R as lookupClaudeTranscriptCwd,G as lookupCodexThreadName,V as normalizeNativeTimestamp,B as parseClaudeTranscriptChunk,H as parseCodexRolloutChunk,Z as parseOpenCodeSessionFile,$ as parseOpenCodeSessionSnapshot};