shennian 0.5.36 → 0.5.37
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.
- package/dist/publish-build-manifest.json +29 -9
- package/dist/src/commands/steward.js +6 -3
- package/dist/src/personal-workspace/service.js +1 -0
- package/dist/src/session/handlers/personal-workspace.js +1 -0
- package/dist/src/session/manager.js +1 -1
- package/dist/src/steward/configure.js +1 -0
- package/dist/src/steward/settings.js +2 -0
- package/dist/src/steward/templates.js +7 -0
- package/dist/src/steward/workspace.js +1 -1
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"schemaVersion": 1,
|
|
3
3
|
"jsMinified": true,
|
|
4
4
|
"minifier": "esbuild",
|
|
5
|
-
"fileCount":
|
|
5
|
+
"fileCount": 298,
|
|
6
6
|
"files": [
|
|
7
7
|
{
|
|
8
8
|
"file": "bin/shennian-adapter-host.js",
|
|
@@ -596,8 +596,8 @@
|
|
|
596
596
|
},
|
|
597
597
|
{
|
|
598
598
|
"file": "src/commands/steward.js",
|
|
599
|
-
"beforeBytes":
|
|
600
|
-
"afterBytes":
|
|
599
|
+
"beforeBytes": 4750,
|
|
600
|
+
"afterBytes": 2727
|
|
601
601
|
},
|
|
602
602
|
{
|
|
603
603
|
"file": "src/commands/support.js",
|
|
@@ -884,6 +884,11 @@
|
|
|
884
884
|
"beforeBytes": 910,
|
|
885
885
|
"afterBytes": 479
|
|
886
886
|
},
|
|
887
|
+
{
|
|
888
|
+
"file": "src/personal-workspace/service.js",
|
|
889
|
+
"beforeBytes": 6845,
|
|
890
|
+
"afterBytes": 3885
|
|
891
|
+
},
|
|
887
892
|
{
|
|
888
893
|
"file": "src/region.js",
|
|
889
894
|
"beforeBytes": 3029,
|
|
@@ -1194,6 +1199,11 @@
|
|
|
1194
1199
|
"beforeBytes": 676,
|
|
1195
1200
|
"afterBytes": 392
|
|
1196
1201
|
},
|
|
1202
|
+
{
|
|
1203
|
+
"file": "src/session/handlers/personal-workspace.js",
|
|
1204
|
+
"beforeBytes": 519,
|
|
1205
|
+
"afterBytes": 366
|
|
1206
|
+
},
|
|
1197
1207
|
{
|
|
1198
1208
|
"file": "src/session/handlers/project-fs.js",
|
|
1199
1209
|
"beforeBytes": 3778,
|
|
@@ -1251,8 +1261,8 @@
|
|
|
1251
1261
|
},
|
|
1252
1262
|
{
|
|
1253
1263
|
"file": "src/session/manager.js",
|
|
1254
|
-
"beforeBytes":
|
|
1255
|
-
"afterBytes":
|
|
1264
|
+
"beforeBytes": 42660,
|
|
1265
|
+
"afterBytes": 22450
|
|
1256
1266
|
},
|
|
1257
1267
|
{
|
|
1258
1268
|
"file": "src/session/native-cleanup-outbox.js",
|
|
@@ -1384,6 +1394,11 @@
|
|
|
1384
1394
|
"beforeBytes": 19384,
|
|
1385
1395
|
"afterBytes": 9616
|
|
1386
1396
|
},
|
|
1397
|
+
{
|
|
1398
|
+
"file": "src/steward/configure.js",
|
|
1399
|
+
"beforeBytes": 1799,
|
|
1400
|
+
"afterBytes": 1027
|
|
1401
|
+
},
|
|
1387
1402
|
{
|
|
1388
1403
|
"file": "src/steward/failover.js",
|
|
1389
1404
|
"beforeBytes": 4394,
|
|
@@ -1399,15 +1414,20 @@
|
|
|
1399
1414
|
"beforeBytes": 3433,
|
|
1400
1415
|
"afterBytes": 2758
|
|
1401
1416
|
},
|
|
1417
|
+
{
|
|
1418
|
+
"file": "src/steward/settings.js",
|
|
1419
|
+
"beforeBytes": 1649,
|
|
1420
|
+
"afterBytes": 1015
|
|
1421
|
+
},
|
|
1402
1422
|
{
|
|
1403
1423
|
"file": "src/steward/templates.js",
|
|
1404
|
-
"beforeBytes":
|
|
1405
|
-
"afterBytes":
|
|
1424
|
+
"beforeBytes": 6079,
|
|
1425
|
+
"afterBytes": 10546
|
|
1406
1426
|
},
|
|
1407
1427
|
{
|
|
1408
1428
|
"file": "src/steward/workspace.js",
|
|
1409
|
-
"beforeBytes":
|
|
1410
|
-
"afterBytes":
|
|
1429
|
+
"beforeBytes": 3740,
|
|
1430
|
+
"afterBytes": 1903
|
|
1411
1431
|
},
|
|
1412
1432
|
{
|
|
1413
1433
|
"file": "src/support/support-client.js",
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
`)}
|
|
3
|
-
`)
|
|
1
|
+
import m from"node:fs";import{configurePersonalPaths as y}from"../steward/configure.js";import{readPersonalPaths as h}from"../steward/settings.js";import{getStewardDir as p}from"../steward/workspace.js";import{callDaemonIpc as g}from"../daemon-ipc/client.js";import{DaemonIpcError as i}from"../daemon-ipc/protocol.js";import{STEWARD_SAY_MAX_CHARS as f,STEWARD_SESSION_ID_ENV as S}from"../steward/session.js";const _={write:o=>process.stdout.write(o),fail:()=>{process.exitCode=1}};function O(o,e={}){const r=e.io??_,l=e.callDaemon??g,t=e.env??process.env,u=e.readStdin??(()=>m.readFileSync(0,"utf8")),d=o.command("steward").description("Talk to the user as the Shennian steward");d.command("paths").description("Show Personal Agent and diary directories (no credentials)").action(()=>{r.write(`${JSON.stringify({ok:!0,workspace:p(),diary:h().diary??null})}
|
|
2
|
+
`)}),d.command("configure").description("Set local Personal Agent / diary directories; restart Client after changing workspace").option("--workspace <directory>","Absolute Personal Agent directory").option("--diary <directory>","Absolute diary directory").action(c=>{try{r.write(`${JSON.stringify({ok:!0,...y(c),restartRequired:!0})}
|
|
3
|
+
`)}catch{r.write(`${JSON.stringify({ok:!1,error:"personal_configuration_failed",message:"Use absolute, non-symlink directories separate from Client credentials."})}
|
|
4
|
+
`),r.fail()}}),d.command("say [text]").description("Send a message the user will see on their phone; in a steward session everything else you output stays hidden from them").option("--file <path>","Read the message from a file").option("--stdin","Read the message from standard input").action(async(c,w)=>{try{const n=t[S]?.trim(),a=k(c,w,u),s=await l({method:"steward.say",params:n?{sessionId:n,text:a}:{text:a}});r.write(`${JSON.stringify({ok:!0,command:"steward.say",result:s})}
|
|
5
|
+
`)}catch(n){const a=n instanceof i,s=!a&&n?.code==="ENOENT";r.write(`${JSON.stringify({ok:!1,error:a?n.code:s?"daemon_unavailable":"steward_command_failed",message:a?n.message:s?"Shennian is not running on this computer.":"Shennian steward command failed.",nextAction:null})}
|
|
6
|
+
`),r.fail()}})}function k(o,e,r){if([o!==void 0,e.file!==void 0,e.stdin===!0].filter(Boolean).length!==1)throw new i("steward_say_invalid","Provide exactly one of: text, --file, --stdin.");let t;if(e.file!==void 0)try{t=m.readFileSync(e.file,"utf8")}catch{throw new i("steward_say_invalid","The message file could not be read.")}else if(e.stdin)try{t=r()}catch{throw new i("steward_say_invalid","Standard input could not be read.")}else t=o??"";if(t=t.trim(),!t||t.length>f)throw new i("steward_say_invalid",`Provide a non-empty message of at most ${f} characters.`);return t}export{O as registerStewardCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import a from"node:fs";import p from"node:path";import{getStewardDir as b,assertPathsSeparate as k}from"../steward/workspace.js";import{readPersonalPaths as x}from"../steward/settings.js";import{getShennianDir as h}from"../config/index.js";const S=512*1024,O=/\.(md|txt|json|yaml|yml|csv|tsv|log)$/i,$=t=>!t||t.startsWith(".")||/(?:^|[-_])(credentials?|secrets?|tokens?|passwords?|private[-_]?key)(?:[._-]|$)/i.test(t)||/\.(pem|key|p12|pfx|keystore)$/i.test(t),r=t=>{throw new Error(`personal_${t}`)};function N(t){return t===void 0||t===""?"":typeof t!="string"||t.length>2e3||/[\\\u0000-\u001f:]/.test(t)||t.startsWith("/")||t.split("/").some($)?r("path_forbidden"):t}function F(t){const e=t==="memory"?b():t==="diary"?x().diary:void 0;if(!e)return r("directory_not_configured");k(e,h());let n=e;for(;;){if(a.lstatSync(n).isSymbolicLink())return r("path_forbidden");const o=p.dirname(n);if(o===n)break;n=o}const s=a.realpathSync(e);return k(s,a.existsSync(h())?a.realpathSync(h()):h()),a.statSync(s).isDirectory()?s:r("directory_unavailable")}function _(t,e){let n=t;for(const f of e?e.split("/"):[])if(n=p.join(n,f),a.lstatSync(n).isSymbolicLink())return r("path_forbidden");const s=a.realpathSync(n),o=p.relative(t,s);return o.startsWith("..")||p.isAbsolute(o)?r("path_forbidden"):s}function D(t,e){if(!O.test(e))return r("text_only");const n=_(t,e),s=a.openSync(n,a.constants.O_RDONLY|(a.constants.O_NOFOLLOW??0));try{const o=a.fstatSync(s);if(!o.isFile())return r("text_only");if(o.size>S)return r("file_too_large");const f=Buffer.alloc(S+1),d=a.readSync(s,f,0,f.length,0);if(d>S)return r("file_too_large");if(_(t,e)!==n||a.statSync(n).ino!==o.ino)return r("file_changed");const i=f.subarray(0,d).toString("utf8");return i.includes("\0")?r("text_only"):i}finally{a.closeSync(s)}}function T(t){return t===void 0?0:!Number.isSafeInteger(t)||Number(t)<0||Number(t)>1e5?r("invalid_request"):Number(t)}function g(t){const e=/^(\d{4})\/(\d{4}-\d{2}-\d{2})\.md$/.exec(t);if(!e||e[1]!==e[2].slice(0,4))return null;const n=new Date(`${e[2]}T00:00:00Z`);return Number.isNaN(n.getTime())||n.toISOString().slice(0,10)!==e[2]?null:e[2]}function v(t){if(!t||typeof t!="object"||Array.isArray(t))return r("invalid_request");const e=t;if(Object.keys(e).some(i=>!["action","kind","path","offset"].includes(i)))return r("invalid_request");if(e.action==="info")return{workspace:b(),diary:x().diary??null,readOnly:!0};if(!["list","read","diary"].includes(String(e.action))||e.kind!=="memory"&&e.kind!=="diary")return r("invalid_request");const n=F(e.kind),s=N(e.path),o=T(e.offset);if(e.action==="read")return e.kind==="diary"&&!g(s)?r("path_forbidden"):{path:s,content:D(n,s)};if(e.action==="diary"){if(e.kind!=="diary"||s)return r("invalid_request");const i=a.readdirSync(n,{withFileTypes:!0}).filter(c=>c.isDirectory()&&/^\d{4}$/.test(c.name));if(i.length>300)return r("directory_too_large");const l=[];for(const c of i){const u=a.readdirSync(_(n,c.name),{withFileTypes:!0});if(u.length>500)return r("directory_too_large");for(const y of u){const m=`${c.name}/${y.name}`;y.isFile()&&g(m)&&l.push(m)}}return l.sort().reverse(),{entries:l.slice(o,o+30).map(c=>{let u="",y="";try{const m=D(n,c);u=/^#\s+(.+)$/m.exec(m)?.[1]?.slice(0,200)??"",y=/^>\s*概要[::]\s*(.+)$/m.exec(m)?.[1]?.slice(0,300)??""}catch{}return{path:c,date:g(c),title:u,summary:y}}),nextOffset:o+30<l.length?o+30:null}}if(e.kind!=="memory")return r("invalid_request");const f=a.readdirSync(_(n,s),{withFileTypes:!0});if(f.length>1e4)return r("directory_too_large");const d=f.filter(i=>!$(i.name)&&!i.isSymbolicLink()&&(i.isDirectory()||i.isFile())).sort((i,l)=>Number(l.isDirectory())-Number(i.isDirectory())||i.name.localeCompare(l.name));return{path:s,entries:d.slice(o,o+100).map(i=>({name:i.name,path:s?`${s}/${i.name}`:i.name,isDir:i.isDirectory()})),nextOffset:o+100<d.length?o+100:null}}export{v as personalWorkspace};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{personalWorkspace as o}from"../../personal-workspace/service.js";async function t(r,e){try{r.client.sendRes({type:"res",id:e.id,ok:!0,payload:o(e.params)})}catch(s){const a=s instanceof Error?s.message:"";r.client.sendRes({type:"res",id:e.id,ok:!1,error:/^personal_[a-z_]+$/.test(a)?a:"personal_directory_unavailable"})}}export{t as handlePersonalWorkspace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import b from"node:crypto";import{getRegisteredAgents as S,unregisterAgent as k}from"../agents/adapter.js";import{resetCommandSpecCache as w}from"../agents/command-spec.js";import{loadConfig as I}from"../config/index.js";import{handleUpgradeStart as A,handleUpgradeStatus as T}from"../commands/upgrade.js";import{handleAgentsRefresh as P,handleModelsRefresh as C,refreshMachineAgents as M}from"./handlers/agents.js";import{AcpDiscoveryWatcher as x}from"../agents/acp/watcher.js";import{handleAgentCapabilitiesList as D}from"./handlers/agent-capabilities.js";import{handleAgentConfigClear as F,handleAgentConfigGet as E,handleAgentConfigTest as Q,handleAgentConfigUpsert as j}from"./handlers/agent-config.js";import{handleCodexSettings as z}from"./handlers/codex-settings.js";import{handleChatAbort as O,handleChatSend as B}from"./handlers/chat.js";import{recoverJournaledRun as H}from"./handlers/chat-recovery.js";import{handleSessionRefresh as W}from"./handlers/session-refresh.js";import{handleSessionToolDetail as _}from"./handlers/tool-detail.js";import{handleSessionTitleSet as U}from"./handlers/title.js";import{handleSessionMessageStatus as J}from"./handlers/message-status.js";import{handleAgentWorkspaceValidation as $}from"./handlers/agent-workspace-validation.js";import{handleVoiceSessionBodyWindow as L}from"./handlers/voice-window.js";import{commitStewardSay as V,commitTerminalStewardSay as N}from"./handlers/steward.js";import{handleLocalApps as G}from"./handlers/local-apps.js";import{handleRemoteAccessPause as K}from"./handlers/remote-access.js";import{cleanupPendingTransfers as X,handleFsLs as Z,handleFsRead as Y,handleFsRename as q,handleFsWrite as ee,handleFsTransferAbort as se,handleFsTransferChunk as te,handleFsTransferFinish as ae,handleFsTransferStart as re,handleFsExportMarkdownPdf as ne,handleFsExportMarkdownPdfSetup as ie,handleFsArchiveZip as oe}from"./handlers/fs.js";import{handleRegionProbe as ce,handleRegionSwitch as le,handleUpgradeSetPolicy as ue}from"./handlers/control.js";import{ManagerRuntimeService as he,setManagerRuntimeService as d}from"../manager/runtime.js";import{ChatQueueManager as de}from"./queue.js";import{createAuthorizedFsRoot as me,createAuthorizedFsRootAsync as pe,resolveAuthorizedPath as ge,resolveAuthorizedPathAsync as fe,resolveSessionWorkDir as ve}from"../fs/boundary.js";import"../agents/claude.js";import"../agents/codex.js";import"../agents/workbuddy.js";import"../agents/gemini.js";import"../agents/cursor.js";import"../agents/opencode.js";import"../agents/pi-coding-agent.js";import"../agents/manager.js";import{registerCustomAgent as ye}from"../agents/custom.js";import{listNodeAdapters as Re}from"../adapter-kit/registry.js";import{syncNodeAdapterAgents as be}from"../agents/node-adapter.js";import{bindManagedRoom as Se,handleManagedRoomBind as ke,handleManagedRoomRestart as we,discardPreBindingSession as Ie}from"./handlers/room-managed.js";import{getDaemonInstallationId as m,listSessionRecords as u,purgeCanonicalSession as Ae,purgeSessionRecord as Te,recordSession as Pe,upsertMessage as Ce}from"./store.js";import{requestSessionIndexPublish as p}from"./index-publisher.js";import{checkRunStalls as Me}from"./run-stall.js";import{reportUpgradeAggregateMetric as xe}from"../log-reporter.js";import{PersonalHistorySubscriptions as De}from"./history-subscriptions.js";import{sweepAttachmentTransfers as Fe}from"./attachment-transfer-store.js";import{NativeSourceDeletionStore as Ee}from"../native-fusion/native-source-deletions.js";import{collectLocalNativeSources as Qe}from"../native-fusion/session-native-sources.js";import{purgeToolDetails as je}from"./tool-detail-store.js";import{NativeSessionCleanupOutbox as ze}from"./native-cleanup-outbox.js";import{assertPersonalSyncIdentity as c}from"../personal-sync/epoch.js";import{ActiveRunJournal as Oe}from"./run-recovery/journal.js";import{RunRecoveryBarrier as Be}from"./run-recovery/barrier.js";import{RunRecoveryCoordinator as He}from"./run-recovery/coordinator.js";import{ProjectFsHandleStore as We}from"./project-fs-store.js";import{handleProjectFsRequest as _e}from"./handlers/project-fs.js";import{handleAgentPermissionResponse as Ue,handleAcpAgentRequest as Je}from"./handlers/agent-control.js";import{SessionDeletionSynchronizer as $e}from"./deletion-synchronizer.js";import{dispatchManagedChat as Le,dispatchQueuedChat as Ve,interruptQueuedChat as Ne}from"./queued-chat-dispatch.js";const Ge=50;import{resolveSessionWorkDir as at}from"../fs/boundary.js";function Ke(){return"\u795E\u5FF5\u5347\u7EA7\u4E2D\u65AD\u4E86\u672C\u6B21\u8FD0\u884C\u3002\u5DF2\u5B8C\u6210\u7684\u56DE\u590D\u6216\u64CD\u4F5C\u4ECD\u7136\u6709\u6548\uFF0C\u672A\u5B8C\u6210\u90E8\u5206\u53EF\u91CD\u8BD5\u3002\u539F\u4F1A\u8BDD\u5DF2\u4FDD\u7559\u3002"}class et{client;nativeFusion;cliVersion;upgradePolicyController;managedRoomBinder;remoteAccessPauseController;managedRoomContextRevoker;managedRoomExecutor;trustedProjectFsRequestResolver;getAgentSnapshot;scheduleHandler;getScheduleQueue(){return this.chatQueue}sessions=new Map;processedReqIds=new Set;runTextAcc=new Map;pendingTransfers=new Map;managerRuntime;chatQueue;historySubscriptions;nativeCleanupOutbox;activityProbeTimer=null;attachmentCleanupTimer=null;activeRequests=0;acpDiscoveryWatcher;runJournal;recoveryBarrier=new Be;recoveryCoordinator;recoveryPass=null;prepareManagedRecovery;projectFsHandleStore=new We;deletionSynchronizer;constructor(e,t=null,s,r=null,n=null,o=null,h=null,g=null,f=null,v=null,y=null){this.client=e,this.nativeFusion=t,this.cliVersion=s,this.upgradePolicyController=r,this.managedRoomBinder=n,this.remoteAccessPauseController=o,this.managedRoomContextRevoker=h,this.managedRoomExecutor=g,this.trustedProjectFsRequestResolver=v,this.getAgentSnapshot=y,this.runJournal=f??new Oe(m());for(const a of this.runJournal.loadPendingReconciliation().records)this.recoveryBarrier.begin(a.sessionId);this.recoveryCoordinator=new He({journal:this.runJournal,barrier:this.recoveryBarrier,recover:(a,i)=>H(this.getRuntime(),a,i),commitTerminal:(a,i)=>this.commitRecoveryTerminal(a,i),isCanonicalTerminal:a=>{const i=u().find(R=>R.sessionId===a.sessionId),l=`terminal:${b.createHash("sha256").update(`${a.runId}\0`).digest("hex")}`;return i?.lastAttentionId===l},onOutcome:a=>xe({kind:"recovery",adapterType:a.adapterType,result:a.result,stage:a.result==="continued"?"continue":a.result==="reattached"?"reattach":a.result==="resumed"?"resume":a.result==="terminal_reconciled"?"inspect":"terminal",durationMs:a.durationMs,retries:Math.max(0,a.attempts-1),...a.reason?{errorCode:a.reason}:{}})}),this.managerRuntime=new he({getRuntime:()=>this.getRuntime(),getAgentSnapshot:this.getAgentSnapshot??void 0,dispatchReq:a=>this.handleReq(a,{propagateErrors:!0})}),this.chatQueue=new de({getRuntime:()=>this.getRuntime(),dispatchReq:a=>this.handleReq(a),dispatchManagedReq:(a,i)=>Le(this.getRuntime(),a,i),dispatchQueuedReq:(a,i)=>Ve(this.getRuntime(),a,i),interruptQueuedSession:a=>Ne(this.getRuntime(),a)}),this.deletionSynchronizer=new $e(e,a=>this.applySessionDeletion(a)),this.historySubscriptions=new De(this.client),this.nativeCleanupOutbox=new ze({logger:console.info}),this.acpDiscoveryWatcher=new x(async()=>{w(),await M(this.getRuntime())}),this.nativeFusion?.setExternalTerminalHandler?.(a=>{this.handleExternalTerminal(a)}),this.nativeFusion?.setExternalClaimHandler?.((a,i)=>{this.chatQueue.noteExternalClaim(a,i)}),this.nativeCleanupOutbox.start(),d(this.managerRuntime),this.managerRuntime.start(),this.reloadCustomAgents();try{this.acpDiscoveryWatcher.start()}catch(a){console.warn(`[acp.discovery] watcher unavailable: ${a instanceof Error?a.message:String(a)}`)}this.activityProbeTimer=setInterval(()=>{Me(this.sessions.entries(),()=>p(this.client)),this.publishManagedActivitySnapshots().catch(a=>{console.error("[session.activity] managed probe failed",a)})},15e3),this.activityProbeTimer.unref?.(),this.attachmentCleanupTimer=setInterval(()=>{const a=new Set([...u().map(i=>i.workDir),...Array.from(this.pendingTransfers.values()).map(i=>i.rootPath)]);for(const i of a)try{Fe(this.resolvePath(i))}catch(l){console.error("[attachment.cleanup] failed",l instanceof Error?l.message:String(l))}},6e4),this.attachmentCleanupTimer.unref?.()}executeManagedManagerAction(e){return this.managerRuntime.executeScopedWorkerAction(e.managerSessionId,e.action,e.params,e.roomOrigin)}noteManagedRoomSendOutcome(e){for(const t of this.sessions.values()){if(t.managedRoomContextToken!==e.token)continue;const s=t.roomSendOutcome??(t.roomSendOutcome={successes:0,failureCodes:[]});e.ok?s.successes+=1:s.failureCodes.length<20&&s.failureCodes.push(e.errorCode??"managed_room_action_failed");return}}getManagedRoomActiveRunId(e,t){const s=this.sessions.get(t);if(s?.currentRunId)return s.currentRunId;for(const r of this.sessions.values())if(r.managedRoomContextToken===e)return r.currentRunId??null;return null}getRuntime(){return{client:this.client,pendingTransfers:this.pendingTransfers,processedReqIds:this.processedReqIds,reloadCustomAgents:()=>this.reloadCustomAgents(),getAgentSnapshot:this.getAgentSnapshot??void 0,resolvePath:e=>this.resolvePath(e),resolveAuthorizedPath:(e,t)=>this.resolveAuthorizedPath(e,t),resolveAuthorizedPathAsync:(e,t)=>this.resolveAuthorizedPathAsync(e,t),runTextAcc:this.runTextAcc,sessions:this.sessions,evictIdleSessions:()=>this.evictIdleSessions(),nativeFusion:this.nativeFusion,managerRuntime:this.managerRuntime,chatQueue:this.chatQueue,activityPublisher:{publish:(e,t)=>this.publishSessionActivity(e,t)},upgradePolicyController:this.upgradePolicyController,revokeManagedRoomContextToken:this.managedRoomContextRevoker,managedRoomExecutor:this.managedRoomExecutor,runJournal:this.runJournal,recoveryBarrier:this.recoveryBarrier,prepareManagedRecovery:this.prepareManagedRecovery}}async resumePendingAcpAuthentication(e){const t=[...this.sessions.values()].find(s=>s.agentType===e&&s.adapter.hasPendingAuthenticationRetry?.());return t?.adapter.resumeAfterExternalAuthentication?(await t.adapter.resumeAfterExternalAuthentication(),!0):!1}getUpgradeIdleState(){const e=[];return[...this.sessions.values()].some(t=>t.currentRunId!==null)&&e.push("active-agent-turn"),this.pendingTransfers.size>0&&e.push("file-transfer"),this.activeRequests>0&&e.push("active-daemon-request"),{idle:e.length===0,reasons:e}}bindManagedRoomFromLocal(e){return Se(this.getRuntime(),this.managedRoomBinder,e)}stewardSayFromLocal(e){const t=typeof e.sessionId=="string"?e.sessionId:"",s=typeof e.text=="string"?e.text:"";return t?V(this.getRuntime(),t,s):N(this.getRuntime(),s)}prepareForUpgrade(e){this.recoveryBarrier.freezeDispatch();const t=this.runJournal.markPlannedUpgrade(e);return this.runJournal.sync(),{activeRunCount:t}}cancelUpgradePreparation(){this.recoveryBarrier.unfreezeDispatch()}async recoverInterruptedRuns(){this.recoveryPass??=this.recoveryCoordinator.recoverAll(),await this.recoveryPass}getPendingRecoveryCount(){return this.runJournal.loadPendingReconciliation().records.length}revokeProjectFsHandles(){this.projectFsHandleStore.revokeAll()}async commitRecoveryTerminal(e,t){const s=this.sessions.get(e.sessionId);s&&(s.currentRunId=null,s.currentRunPhase=null,s.journalRunId=null,s.heartbeatTimer&&(clearInterval(s.heartbeatTimer),s.heartbeatTimer=null)),this.runTextAcc.delete(`${e.sessionId}:${e.providerRunId??e.runId}`),this.publishSessionActivity(e.sessionId,null);const r=Ke();Ce(e.sessionId,{id:`upgrade-recovery-terminal-${e.runId}`,sessionId:e.sessionId,role:"agent",ts:Date.now(),payload:JSON.stringify({v:1,type:"error",content:r,error:!0,recoveryState:t.result,recoveryReason:t.reason})}),Pe({sessionId:e.sessionId,agentType:e.agentType,sessionMode:e.sessionMode,workDir:e.workDir,agentSessionId:e.agentSessionId,modelId:e.modelId,status:"failed",attentionId:`upgrade-recovery:${e.runId}`,lastActivityAt:new Date().toISOString()}),this.managerRuntime.noteAgentEvent(e.sessionId,{state:"error",runId:e.providerRunId??e.runId,seq:e.lastObservedEventSeq+1,message:r}),p(this.client);const n=e.lastObservedEventSeq+1;this.client.sendAgentEvent({type:"event",event:"agent",payload:t.result==="interrupted_by_upgrade"?{state:"interrupted_by_upgrade",sessionId:e.sessionId,runId:e.providerRunId??e.runId,seq:n,reason:t.reason}:{state:"recovery_failed",sessionId:e.sessionId,runId:e.providerRunId??e.runId,seq:n,reason:t.reason,...t.message?{message:t.message}:{}},seq:n,id:`agent-recovery-terminal-${e.runId}`}),this.chatQueue.noteTerminal(e.sessionId)}setManagedRoomTurnPreparer(e){this.chatQueue.setManagedRoomTurnPreparer(e)}setManagedAgentDirectTurnPreparer(e){this.chatQueue.setManagedAgentDirectTurnPreparer(e)}setManagedRecoveryPreparer(e){this.prepareManagedRecovery=e}async enqueueManagedRoomBatch(e){const t=e.map(s=>{const r=u().find(n=>n.sessionId===s.params.sessionId);return{context:s.context,params:{...s.params,modelId:r?.modelId??s.params.modelId,sessionMode:r?.sessionMode??s.params.sessionMode,managerConfig:r?.managerConfig??s.params.managerConfig,managerDefaultWorkerAgentType:r?.managerDefaultWorkerAgentType??s.params.managerDefaultWorkerAgentType,managerDefaultWorkerModelId:r?.managerDefaultWorkerModelId??s.params.managerDefaultWorkerModelId}}});await this.chatQueue.enqueueManagedRoomBatch(t)}async retireManagedRoomSession(e){this.chatQueue.purgeSession(e),await Ie(this.getRuntime(),e)}discardPendingManagedRoomMessages(e){return this.chatQueue.discardPendingManagedRoomMessages(e)}async synchronizeSessionDeletions(){await this.deletionSynchronizer.synchronize()}async applySessionDeletion(e){const t=new Ee({daemonInstallationId:m()}),s=u().find(o=>o.sessionId===e.sessionId)?.codexSettings?.codexHome;let r=[];try{r=Qe(e.sessionId,{records:u()})}catch(o){console.warn("[session.deletions] local native source lookup failed",{error:o instanceof Error?o.message:String(o)})}t.recordSession(e);for(const o of[...e.sources,...r]){const h=t.find(o.agentType,o.sourceSessionKey);h&&h.sessionId!==e.sessionId||t.record({...e,...o})}this.runJournal.markSessionAborted(e.sessionId),this.recoveryBarrier.end(e.sessionId);const n=this.sessions.get(e.sessionId);if(n){this.revokeManagedRoomToken(n);try{await n.adapter.stop()}catch{}this.sessions.delete(e.sessionId)}this.historySubscriptions.closeSession(e.sessionId),this.nativeFusion?.handleSessionDeleted(e.sessionId),this.chatQueue.purgeSession(e.sessionId),je(e.sessionId),Ae(e.sessionId),Te(e.sessionId),this.runTextAcc.delete(e.sessionId),this.publishSessionActivity(e.sessionId,null),this.nativeCleanupOutbox.enqueue(e,s),this.nativeCleanupOutbox.kick()}publishSessionActivity(e,t){this.client.sendEvent({type:"event",event:"session.activity",payload:{sessionId:e,activity:t}})}async handleExternalTerminal(e){const t=this.sessions.get(e);t&&(t.journalRunId&&(this.recoveryCoordinator.completeFromProvider(e,t.journalRunId),t.journalRunId=null),this.sessions.delete(e),this.revokeManagedRoomToken(t),t.heartbeatTimer&&clearInterval(t.heartbeatTimer),t.adapter.removeAllListeners(),await t.adapter.stop().catch(()=>{})),this.chatQueue.noteTerminal(e)}async publishManagedActivitySnapshots(){for(const[e,t]of this.sessions.entries()){if(t.heartbeatTimer||!t.currentRunId||!t.adapter.getStatus)continue;const s=await t.adapter.getStatus().catch(()=>null);if(!s?.active||!s.runPhase)continue;const r=new Date().toISOString();this.publishSessionActivity(e,{sessionId:e,runId:s.runId||t.currentRunId,runPhase:s.runPhase,startedAt:new Date(t.lastActiveAt).toISOString(),updatedAt:r,canStop:s.canStop??!0});const n=t.heartbeatSeq++;this.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:e,runId:s.runId||t.currentRunId,seq:n,runPhase:s.runPhase,canStop:s.canStop??!0},seq:n,id:`agent-status-${s.runId||t.currentRunId}-${Date.now()}`})}}reloadCustomAgents(){for(const t of S())t.startsWith("custom:")&&k(t);const e=I();for(const[t,s]of Object.entries(e.customAgents??{}))ye(t,s);be(Re(),new Set(Object.keys(e.customAgents??{})))}async handleReq(e,t={}){const s=this.getRuntime();let r;this.activeRequests++;try{switch(e.method){case"schedule.deliver":if(!this.scheduleHandler)throw new Error("schedules_unavailable");await this.scheduleHandler(e);break;case"chat.send":if(e.params.scheduledDelivery)throw new Error("schedule_source_untrusted");c(e.params),this.recoveryBarrier.isDispatchFrozen()||this.recoveryBarrier.isRecovering(String(e.params.sessionId??""))?r={durableQueueHandoff:await this.chatQueue.handleEnqueue({...e,method:"chat.enqueue"})}:await B(s,e);break;case"chat.enqueue":c(e.params),r={durableQueueHandoff:await this.chatQueue.handleEnqueue(e)};break;case"chat.codex.settings.get":case"chat.codex.settings.set":z(s,e);break;case"chat.queue.get":c(e.params),await this.chatQueue.handleGet(e);break;case"chat.queue.edit":c(e.params),await this.chatQueue.handleEdit(e);break;case"chat.queue.delete":c(e.params),await this.chatQueue.handleDelete(e);break;case"chat.queue.promote":c(e.params),await this.chatQueue.handlePromote(e);break;case"chat.abort":c(e.params),await O(s,e);break;case"session.refresh":c(e.params),await W(s,e);break;case"session.history.open":this.historySubscriptions.handleOpen(e);break;case"session.history.sync":this.historySubscriptions.handleSync(e);break;case"session.history.page":this.historySubscriptions.handlePage(e);break;case"session.history.close":this.historySubscriptions.handleClose(e);break;case"session.body.replica.subscribe":this.historySubscriptions.handleReplicaSubscribe(e);break;case"session.body.replica.unsubscribe":this.historySubscriptions.handleReplicaUnsubscribe(e);break;case"session.history":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"upgrade_required"});break;case"session.message.status":J(s,e);break;case"session.tool.detail":await _(s,e);break;case"voice.session.body.window":L(s,e);break;case"session.title.set":await U(s,e);break;case"room.agent.bind-managed":await ke(s,this.managedRoomBinder,e);break;case"room.agent.restart-managed":await we(s,this.managedRoomBinder,e);break;case"personal.apps.list":case"personal.apps.register":case"personal.apps.remove":case"personal.service":await G(s,e);break;case"fs.ls":await Z(s,e);break;case"project.fs.open":case"project.fs.list":case"project.fs.read":case"project.fs.close":await _e(this.client,this.projectFsHandleStore,e,this.trustedProjectFsRequestResolver);break;case"fs.read":await Y(s,e);break;case"fs.write":await ee(s,e);break;case"fs.export.markdown-pdf":await ne(s,e);break;case"fs.export.markdown-pdf.setup":await ie(s,e);break;case"fs.archive.zip":await oe(s,e);break;case"fs.rename":await q(s,e);break;case"fs.transfer.start":await re(s,e);break;case"fs.transfer.chunk":await te(s,e);break;case"fs.transfer.finish":await ae(s,e);break;case"fs.transfer.abort":await se(s,e);break;case"region.probe":await ce(s,e);break;case"region.switch":await le(s,e);break;case"upgrade.start":await A(this.client,e.id,e.params.version,{currentVersion:this.cliVersion,confirmedMajor:e.params.confirmedMajor===!0,prepareForUpgrade:n=>this.prepareForUpgrade(n),cancelUpgradePreparation:()=>this.cancelUpgradePreparation(),shutdownAfterHandoff:()=>{setTimeout(()=>process.kill(process.pid,"SIGTERM"),100).unref?.()}});break;case"upgrade.status":await T(this.client,e.id,{currentVersion:this.cliVersion});break;case"upgrade.set-policy":await ue(s,e);break;case"machine.remote-access.pause":await K(this.client,this.remoteAccessPauseController,e);break;case"agents.refresh":await P(s,e);break;case"agent.permission.respond":await Ue(s,e);break;case"agent.auth.start":case"agent.auth.logout":case"agent.session-options.get":case"agent.external-sessions.list":case"agent.external-sessions.import":case"agent.external-sessions.close":case"agent.external-sessions.delete":await Je(s,e);break;case"models.refresh":await C(s,e);break;case"agent.config.get":await E(s,e);break;case"agent.config.upsert":await j(s,e);break;case"agent.config.clear":await F(s,e);break;case"agent.config.test":await Q(s,e);break;case"agent.workspace.validate":await $(s,e);break;case"agent.capabilities.list":await D(s,e);break;case"skill.list":case"skill.install":case"skill.doctor":case"skill.setup":case"skill.use":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;case"session.wechat-rpa.channel.get":case"session.wechat-rpa.channel.upsert":case"session.wechat-rpa.channel.sync":case"manager.wechat-rpa.channel.get":case"manager.wechat-rpa.channel.upsert":case"manager.wechat-rpa.channel.sync":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;default:this.client.sendRes({type:"res",id:e.id,ok:!1,error:`Unknown method: ${e.method}`})}}catch(n){if(t.propagateErrors)throw n;this.client.sendRes({type:"res",id:e.id,ok:!1,error:n instanceof Error?n.message:String(n)})}finally{this.activeRequests--}return r}evictIdleSessions(){if(this.sessions.size<Ge)return;let e=null;for(const[t,s]of this.sessions)(!e||s.lastActiveAt<e.session.lastActiveAt)&&(e={key:t,session:s});e&&(this.revokeManagedRoomToken(e.session),e.session.heartbeatTimer&&(clearInterval(e.session.heartbeatTimer),e.session.heartbeatTimer=null),e.session.adapter.removeAllListeners(),e.session.adapter.stop().catch(()=>{}),this.sessions.delete(e.key))}resolvePath(e){return ve(e)}resolveAuthorizedPath(e,t){return ge(e,me(t))}async resolveAuthorizedPathAsync(e,t){return fe(e,await pe(t))}async cleanup(){this.chatQueue.stop(),this.projectFsHandleStore.revokeAll(),this.acpDiscoveryWatcher.stop(),this.nativeFusion?.setExternalTerminalHandler?.(null),this.nativeCleanupOutbox.stop(),this.historySubscriptions.closeAll(),this.activityProbeTimer&&(clearInterval(this.activityProbeTimer),this.activityProbeTimer=null),this.attachmentCleanupTimer&&(clearInterval(this.attachmentCleanupTimer),this.attachmentCleanupTimer=null);for(const[,e]of this.sessions)this.revokeManagedRoomToken(e),e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null),e.adapter.removeAllListeners(),await e.adapter.stop().catch(()=>{});this.sessions.clear(),this.runTextAcc.clear(),X(this.getRuntime()),await this.managerRuntime.stop(),d(null)}revokeManagedRoomToken(e){const t=e.managedRoomContextToken;e.managedRoomContextToken=null,t&&this.managedRoomContextRevoker?.(t)}}export{et as SessionManager,at as resolveSessionWorkDir,Ke as upgradeRecoveryVisibleMessage};
|
|
1
|
+
import b from"node:crypto";import{getRegisteredAgents as S,unregisterAgent as k}from"../agents/adapter.js";import{resetCommandSpecCache as w}from"../agents/command-spec.js";import{loadConfig as I}from"../config/index.js";import{handleUpgradeStart as A,handleUpgradeStatus as T}from"../commands/upgrade.js";import{handleAgentsRefresh as P,handleModelsRefresh as C,refreshMachineAgents as M}from"./handlers/agents.js";import{AcpDiscoveryWatcher as x}from"../agents/acp/watcher.js";import{handleAgentCapabilitiesList as D}from"./handlers/agent-capabilities.js";import{handleAgentConfigClear as F,handleAgentConfigGet as E,handleAgentConfigTest as Q,handleAgentConfigUpsert as j}from"./handlers/agent-config.js";import{handleCodexSettings as z}from"./handlers/codex-settings.js";import{handleChatAbort as O,handleChatSend as B}from"./handlers/chat.js";import{recoverJournaledRun as H}from"./handlers/chat-recovery.js";import{handleSessionRefresh as W}from"./handlers/session-refresh.js";import{handleSessionToolDetail as _}from"./handlers/tool-detail.js";import{handleSessionTitleSet as U}from"./handlers/title.js";import{handleSessionMessageStatus as J}from"./handlers/message-status.js";import{handleAgentWorkspaceValidation as $}from"./handlers/agent-workspace-validation.js";import{handleVoiceSessionBodyWindow as L}from"./handlers/voice-window.js";import{commitStewardSay as V,commitTerminalStewardSay as N}from"./handlers/steward.js";import{handlePersonalWorkspace as G}from"./handlers/personal-workspace.js";import{handleLocalApps as K}from"./handlers/local-apps.js";import{handleRemoteAccessPause as X}from"./handlers/remote-access.js";import{cleanupPendingTransfers as Z,handleFsLs as Y,handleFsRead as q,handleFsRename as ee,handleFsWrite as se,handleFsTransferAbort as te,handleFsTransferChunk as ae,handleFsTransferFinish as re,handleFsTransferStart as ne,handleFsExportMarkdownPdf as ie,handleFsExportMarkdownPdfSetup as oe,handleFsArchiveZip as ce}from"./handlers/fs.js";import{handleRegionProbe as le,handleRegionSwitch as ue,handleUpgradeSetPolicy as he}from"./handlers/control.js";import{ManagerRuntimeService as de,setManagerRuntimeService as d}from"../manager/runtime.js";import{ChatQueueManager as me}from"./queue.js";import{createAuthorizedFsRoot as pe,createAuthorizedFsRootAsync as ge,resolveAuthorizedPath as fe,resolveAuthorizedPathAsync as ve,resolveSessionWorkDir as ye}from"../fs/boundary.js";import"../agents/claude.js";import"../agents/codex.js";import"../agents/workbuddy.js";import"../agents/gemini.js";import"../agents/cursor.js";import"../agents/opencode.js";import"../agents/pi-coding-agent.js";import"../agents/manager.js";import{registerCustomAgent as Re}from"../agents/custom.js";import{listNodeAdapters as be}from"../adapter-kit/registry.js";import{syncNodeAdapterAgents as Se}from"../agents/node-adapter.js";import{bindManagedRoom as ke,handleManagedRoomBind as we,handleManagedRoomRestart as Ie,discardPreBindingSession as Ae}from"./handlers/room-managed.js";import{getDaemonInstallationId as m,listSessionRecords as u,purgeCanonicalSession as Te,purgeSessionRecord as Pe,recordSession as Ce,upsertMessage as Me}from"./store.js";import{requestSessionIndexPublish as p}from"./index-publisher.js";import{checkRunStalls as xe}from"./run-stall.js";import{reportUpgradeAggregateMetric as De}from"../log-reporter.js";import{PersonalHistorySubscriptions as Fe}from"./history-subscriptions.js";import{sweepAttachmentTransfers as Ee}from"./attachment-transfer-store.js";import{NativeSourceDeletionStore as Qe}from"../native-fusion/native-source-deletions.js";import{collectLocalNativeSources as je}from"../native-fusion/session-native-sources.js";import{purgeToolDetails as ze}from"./tool-detail-store.js";import{NativeSessionCleanupOutbox as Oe}from"./native-cleanup-outbox.js";import{assertPersonalSyncIdentity as c}from"../personal-sync/epoch.js";import{ActiveRunJournal as Be}from"./run-recovery/journal.js";import{RunRecoveryBarrier as He}from"./run-recovery/barrier.js";import{RunRecoveryCoordinator as We}from"./run-recovery/coordinator.js";import{ProjectFsHandleStore as _e}from"./project-fs-store.js";import{handleProjectFsRequest as Ue}from"./handlers/project-fs.js";import{handleAgentPermissionResponse as Je,handleAcpAgentRequest as $e}from"./handlers/agent-control.js";import{SessionDeletionSynchronizer as Le}from"./deletion-synchronizer.js";import{dispatchManagedChat as Ve,dispatchQueuedChat as Ne,interruptQueuedChat as Ge}from"./queued-chat-dispatch.js";const Ke=50;import{resolveSessionWorkDir as nt}from"../fs/boundary.js";function Xe(){return"\u795E\u5FF5\u5347\u7EA7\u4E2D\u65AD\u4E86\u672C\u6B21\u8FD0\u884C\u3002\u5DF2\u5B8C\u6210\u7684\u56DE\u590D\u6216\u64CD\u4F5C\u4ECD\u7136\u6709\u6548\uFF0C\u672A\u5B8C\u6210\u90E8\u5206\u53EF\u91CD\u8BD5\u3002\u539F\u4F1A\u8BDD\u5DF2\u4FDD\u7559\u3002"}class tt{client;nativeFusion;cliVersion;upgradePolicyController;managedRoomBinder;remoteAccessPauseController;managedRoomContextRevoker;managedRoomExecutor;trustedProjectFsRequestResolver;getAgentSnapshot;scheduleHandler;getScheduleQueue(){return this.chatQueue}sessions=new Map;processedReqIds=new Set;runTextAcc=new Map;pendingTransfers=new Map;managerRuntime;chatQueue;historySubscriptions;nativeCleanupOutbox;activityProbeTimer=null;attachmentCleanupTimer=null;activeRequests=0;acpDiscoveryWatcher;runJournal;recoveryBarrier=new He;recoveryCoordinator;recoveryPass=null;prepareManagedRecovery;projectFsHandleStore=new _e;deletionSynchronizer;constructor(e,t=null,s,r=null,n=null,o=null,h=null,g=null,f=null,v=null,y=null){this.client=e,this.nativeFusion=t,this.cliVersion=s,this.upgradePolicyController=r,this.managedRoomBinder=n,this.remoteAccessPauseController=o,this.managedRoomContextRevoker=h,this.managedRoomExecutor=g,this.trustedProjectFsRequestResolver=v,this.getAgentSnapshot=y,this.runJournal=f??new Be(m());for(const a of this.runJournal.loadPendingReconciliation().records)this.recoveryBarrier.begin(a.sessionId);this.recoveryCoordinator=new We({journal:this.runJournal,barrier:this.recoveryBarrier,recover:(a,i)=>H(this.getRuntime(),a,i),commitTerminal:(a,i)=>this.commitRecoveryTerminal(a,i),isCanonicalTerminal:a=>{const i=u().find(R=>R.sessionId===a.sessionId),l=`terminal:${b.createHash("sha256").update(`${a.runId}\0`).digest("hex")}`;return i?.lastAttentionId===l},onOutcome:a=>De({kind:"recovery",adapterType:a.adapterType,result:a.result,stage:a.result==="continued"?"continue":a.result==="reattached"?"reattach":a.result==="resumed"?"resume":a.result==="terminal_reconciled"?"inspect":"terminal",durationMs:a.durationMs,retries:Math.max(0,a.attempts-1),...a.reason?{errorCode:a.reason}:{}})}),this.managerRuntime=new de({getRuntime:()=>this.getRuntime(),getAgentSnapshot:this.getAgentSnapshot??void 0,dispatchReq:a=>this.handleReq(a,{propagateErrors:!0})}),this.chatQueue=new me({getRuntime:()=>this.getRuntime(),dispatchReq:a=>this.handleReq(a),dispatchManagedReq:(a,i)=>Ve(this.getRuntime(),a,i),dispatchQueuedReq:(a,i)=>Ne(this.getRuntime(),a,i),interruptQueuedSession:a=>Ge(this.getRuntime(),a)}),this.deletionSynchronizer=new Le(e,a=>this.applySessionDeletion(a)),this.historySubscriptions=new Fe(this.client),this.nativeCleanupOutbox=new Oe({logger:console.info}),this.acpDiscoveryWatcher=new x(async()=>{w(),await M(this.getRuntime())}),this.nativeFusion?.setExternalTerminalHandler?.(a=>{this.handleExternalTerminal(a)}),this.nativeFusion?.setExternalClaimHandler?.((a,i)=>{this.chatQueue.noteExternalClaim(a,i)}),this.nativeCleanupOutbox.start(),d(this.managerRuntime),this.managerRuntime.start(),this.reloadCustomAgents();try{this.acpDiscoveryWatcher.start()}catch(a){console.warn(`[acp.discovery] watcher unavailable: ${a instanceof Error?a.message:String(a)}`)}this.activityProbeTimer=setInterval(()=>{xe(this.sessions.entries(),()=>p(this.client)),this.publishManagedActivitySnapshots().catch(a=>{console.error("[session.activity] managed probe failed",a)})},15e3),this.activityProbeTimer.unref?.(),this.attachmentCleanupTimer=setInterval(()=>{const a=new Set([...u().map(i=>i.workDir),...Array.from(this.pendingTransfers.values()).map(i=>i.rootPath)]);for(const i of a)try{Ee(this.resolvePath(i))}catch(l){console.error("[attachment.cleanup] failed",l instanceof Error?l.message:String(l))}},6e4),this.attachmentCleanupTimer.unref?.()}executeManagedManagerAction(e){return this.managerRuntime.executeScopedWorkerAction(e.managerSessionId,e.action,e.params,e.roomOrigin)}noteManagedRoomSendOutcome(e){for(const t of this.sessions.values()){if(t.managedRoomContextToken!==e.token)continue;const s=t.roomSendOutcome??(t.roomSendOutcome={successes:0,failureCodes:[]});e.ok?s.successes+=1:s.failureCodes.length<20&&s.failureCodes.push(e.errorCode??"managed_room_action_failed");return}}getManagedRoomActiveRunId(e,t){const s=this.sessions.get(t);if(s?.currentRunId)return s.currentRunId;for(const r of this.sessions.values())if(r.managedRoomContextToken===e)return r.currentRunId??null;return null}getRuntime(){return{client:this.client,pendingTransfers:this.pendingTransfers,processedReqIds:this.processedReqIds,reloadCustomAgents:()=>this.reloadCustomAgents(),getAgentSnapshot:this.getAgentSnapshot??void 0,resolvePath:e=>this.resolvePath(e),resolveAuthorizedPath:(e,t)=>this.resolveAuthorizedPath(e,t),resolveAuthorizedPathAsync:(e,t)=>this.resolveAuthorizedPathAsync(e,t),runTextAcc:this.runTextAcc,sessions:this.sessions,evictIdleSessions:()=>this.evictIdleSessions(),nativeFusion:this.nativeFusion,managerRuntime:this.managerRuntime,chatQueue:this.chatQueue,activityPublisher:{publish:(e,t)=>this.publishSessionActivity(e,t)},upgradePolicyController:this.upgradePolicyController,revokeManagedRoomContextToken:this.managedRoomContextRevoker,managedRoomExecutor:this.managedRoomExecutor,runJournal:this.runJournal,recoveryBarrier:this.recoveryBarrier,prepareManagedRecovery:this.prepareManagedRecovery}}async resumePendingAcpAuthentication(e){const t=[...this.sessions.values()].find(s=>s.agentType===e&&s.adapter.hasPendingAuthenticationRetry?.());return t?.adapter.resumeAfterExternalAuthentication?(await t.adapter.resumeAfterExternalAuthentication(),!0):!1}getUpgradeIdleState(){const e=[];return[...this.sessions.values()].some(t=>t.currentRunId!==null)&&e.push("active-agent-turn"),this.pendingTransfers.size>0&&e.push("file-transfer"),this.activeRequests>0&&e.push("active-daemon-request"),{idle:e.length===0,reasons:e}}bindManagedRoomFromLocal(e){return ke(this.getRuntime(),this.managedRoomBinder,e)}stewardSayFromLocal(e){const t=typeof e.sessionId=="string"?e.sessionId:"",s=typeof e.text=="string"?e.text:"";return t?V(this.getRuntime(),t,s):N(this.getRuntime(),s)}prepareForUpgrade(e){this.recoveryBarrier.freezeDispatch();const t=this.runJournal.markPlannedUpgrade(e);return this.runJournal.sync(),{activeRunCount:t}}cancelUpgradePreparation(){this.recoveryBarrier.unfreezeDispatch()}async recoverInterruptedRuns(){this.recoveryPass??=this.recoveryCoordinator.recoverAll(),await this.recoveryPass}getPendingRecoveryCount(){return this.runJournal.loadPendingReconciliation().records.length}revokeProjectFsHandles(){this.projectFsHandleStore.revokeAll()}async commitRecoveryTerminal(e,t){const s=this.sessions.get(e.sessionId);s&&(s.currentRunId=null,s.currentRunPhase=null,s.journalRunId=null,s.heartbeatTimer&&(clearInterval(s.heartbeatTimer),s.heartbeatTimer=null)),this.runTextAcc.delete(`${e.sessionId}:${e.providerRunId??e.runId}`),this.publishSessionActivity(e.sessionId,null);const r=Xe();Me(e.sessionId,{id:`upgrade-recovery-terminal-${e.runId}`,sessionId:e.sessionId,role:"agent",ts:Date.now(),payload:JSON.stringify({v:1,type:"error",content:r,error:!0,recoveryState:t.result,recoveryReason:t.reason})}),Ce({sessionId:e.sessionId,agentType:e.agentType,sessionMode:e.sessionMode,workDir:e.workDir,agentSessionId:e.agentSessionId,modelId:e.modelId,status:"failed",attentionId:`upgrade-recovery:${e.runId}`,lastActivityAt:new Date().toISOString()}),this.managerRuntime.noteAgentEvent(e.sessionId,{state:"error",runId:e.providerRunId??e.runId,seq:e.lastObservedEventSeq+1,message:r}),p(this.client);const n=e.lastObservedEventSeq+1;this.client.sendAgentEvent({type:"event",event:"agent",payload:t.result==="interrupted_by_upgrade"?{state:"interrupted_by_upgrade",sessionId:e.sessionId,runId:e.providerRunId??e.runId,seq:n,reason:t.reason}:{state:"recovery_failed",sessionId:e.sessionId,runId:e.providerRunId??e.runId,seq:n,reason:t.reason,...t.message?{message:t.message}:{}},seq:n,id:`agent-recovery-terminal-${e.runId}`}),this.chatQueue.noteTerminal(e.sessionId)}setManagedRoomTurnPreparer(e){this.chatQueue.setManagedRoomTurnPreparer(e)}setManagedAgentDirectTurnPreparer(e){this.chatQueue.setManagedAgentDirectTurnPreparer(e)}setManagedRecoveryPreparer(e){this.prepareManagedRecovery=e}async enqueueManagedRoomBatch(e){const t=e.map(s=>{const r=u().find(n=>n.sessionId===s.params.sessionId);return{context:s.context,params:{...s.params,modelId:r?.modelId??s.params.modelId,sessionMode:r?.sessionMode??s.params.sessionMode,managerConfig:r?.managerConfig??s.params.managerConfig,managerDefaultWorkerAgentType:r?.managerDefaultWorkerAgentType??s.params.managerDefaultWorkerAgentType,managerDefaultWorkerModelId:r?.managerDefaultWorkerModelId??s.params.managerDefaultWorkerModelId}}});await this.chatQueue.enqueueManagedRoomBatch(t)}async retireManagedRoomSession(e){this.chatQueue.purgeSession(e),await Ae(this.getRuntime(),e)}discardPendingManagedRoomMessages(e){return this.chatQueue.discardPendingManagedRoomMessages(e)}async synchronizeSessionDeletions(){await this.deletionSynchronizer.synchronize()}async applySessionDeletion(e){const t=new Qe({daemonInstallationId:m()}),s=u().find(o=>o.sessionId===e.sessionId)?.codexSettings?.codexHome;let r=[];try{r=je(e.sessionId,{records:u()})}catch(o){console.warn("[session.deletions] local native source lookup failed",{error:o instanceof Error?o.message:String(o)})}t.recordSession(e);for(const o of[...e.sources,...r]){const h=t.find(o.agentType,o.sourceSessionKey);h&&h.sessionId!==e.sessionId||t.record({...e,...o})}this.runJournal.markSessionAborted(e.sessionId),this.recoveryBarrier.end(e.sessionId);const n=this.sessions.get(e.sessionId);if(n){this.revokeManagedRoomToken(n);try{await n.adapter.stop()}catch{}this.sessions.delete(e.sessionId)}this.historySubscriptions.closeSession(e.sessionId),this.nativeFusion?.handleSessionDeleted(e.sessionId),this.chatQueue.purgeSession(e.sessionId),ze(e.sessionId),Te(e.sessionId),Pe(e.sessionId),this.runTextAcc.delete(e.sessionId),this.publishSessionActivity(e.sessionId,null),this.nativeCleanupOutbox.enqueue(e,s),this.nativeCleanupOutbox.kick()}publishSessionActivity(e,t){this.client.sendEvent({type:"event",event:"session.activity",payload:{sessionId:e,activity:t}})}async handleExternalTerminal(e){const t=this.sessions.get(e);t&&(t.journalRunId&&(this.recoveryCoordinator.completeFromProvider(e,t.journalRunId),t.journalRunId=null),this.sessions.delete(e),this.revokeManagedRoomToken(t),t.heartbeatTimer&&clearInterval(t.heartbeatTimer),t.adapter.removeAllListeners(),await t.adapter.stop().catch(()=>{})),this.chatQueue.noteTerminal(e)}async publishManagedActivitySnapshots(){for(const[e,t]of this.sessions.entries()){if(t.heartbeatTimer||!t.currentRunId||!t.adapter.getStatus)continue;const s=await t.adapter.getStatus().catch(()=>null);if(!s?.active||!s.runPhase)continue;const r=new Date().toISOString();this.publishSessionActivity(e,{sessionId:e,runId:s.runId||t.currentRunId,runPhase:s.runPhase,startedAt:new Date(t.lastActiveAt).toISOString(),updatedAt:r,canStop:s.canStop??!0});const n=t.heartbeatSeq++;this.client.sendAgentEvent({type:"event",event:"agent",payload:{state:"heartbeat",sessionId:e,runId:s.runId||t.currentRunId,seq:n,runPhase:s.runPhase,canStop:s.canStop??!0},seq:n,id:`agent-status-${s.runId||t.currentRunId}-${Date.now()}`})}}reloadCustomAgents(){for(const t of S())t.startsWith("custom:")&&k(t);const e=I();for(const[t,s]of Object.entries(e.customAgents??{}))Re(t,s);Se(be(),new Set(Object.keys(e.customAgents??{})))}async handleReq(e,t={}){const s=this.getRuntime();let r;this.activeRequests++;try{switch(e.method){case"schedule.deliver":if(!this.scheduleHandler)throw new Error("schedules_unavailable");await this.scheduleHandler(e);break;case"chat.send":if(e.params.scheduledDelivery)throw new Error("schedule_source_untrusted");c(e.params),this.recoveryBarrier.isDispatchFrozen()||this.recoveryBarrier.isRecovering(String(e.params.sessionId??""))?r={durableQueueHandoff:await this.chatQueue.handleEnqueue({...e,method:"chat.enqueue"})}:await B(s,e);break;case"chat.enqueue":c(e.params),r={durableQueueHandoff:await this.chatQueue.handleEnqueue(e)};break;case"chat.codex.settings.get":case"chat.codex.settings.set":z(s,e);break;case"chat.queue.get":c(e.params),await this.chatQueue.handleGet(e);break;case"chat.queue.edit":c(e.params),await this.chatQueue.handleEdit(e);break;case"chat.queue.delete":c(e.params),await this.chatQueue.handleDelete(e);break;case"chat.queue.promote":c(e.params),await this.chatQueue.handlePromote(e);break;case"chat.abort":c(e.params),await O(s,e);break;case"session.refresh":c(e.params),await W(s,e);break;case"session.history.open":this.historySubscriptions.handleOpen(e);break;case"session.history.sync":this.historySubscriptions.handleSync(e);break;case"session.history.page":this.historySubscriptions.handlePage(e);break;case"session.history.close":this.historySubscriptions.handleClose(e);break;case"session.body.replica.subscribe":this.historySubscriptions.handleReplicaSubscribe(e);break;case"session.body.replica.unsubscribe":this.historySubscriptions.handleReplicaUnsubscribe(e);break;case"session.history":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"upgrade_required"});break;case"session.message.status":J(s,e);break;case"session.tool.detail":await _(s,e);break;case"voice.session.body.window":L(s,e);break;case"session.title.set":await U(s,e);break;case"room.agent.bind-managed":await we(s,this.managedRoomBinder,e);break;case"room.agent.restart-managed":await Ie(s,this.managedRoomBinder,e);break;case"personal.workspace":await G(s,e);break;case"personal.apps.list":case"personal.apps.register":case"personal.apps.remove":case"personal.service":await K(s,e);break;case"fs.ls":await Y(s,e);break;case"project.fs.open":case"project.fs.list":case"project.fs.read":case"project.fs.close":await Ue(this.client,this.projectFsHandleStore,e,this.trustedProjectFsRequestResolver);break;case"fs.read":await q(s,e);break;case"fs.write":await se(s,e);break;case"fs.export.markdown-pdf":await ie(s,e);break;case"fs.export.markdown-pdf.setup":await oe(s,e);break;case"fs.archive.zip":await ce(s,e);break;case"fs.rename":await ee(s,e);break;case"fs.transfer.start":await ne(s,e);break;case"fs.transfer.chunk":await ae(s,e);break;case"fs.transfer.finish":await re(s,e);break;case"fs.transfer.abort":await te(s,e);break;case"region.probe":await le(s,e);break;case"region.switch":await ue(s,e);break;case"upgrade.start":await A(this.client,e.id,e.params.version,{currentVersion:this.cliVersion,confirmedMajor:e.params.confirmedMajor===!0,prepareForUpgrade:n=>this.prepareForUpgrade(n),cancelUpgradePreparation:()=>this.cancelUpgradePreparation(),shutdownAfterHandoff:()=>{setTimeout(()=>process.kill(process.pid,"SIGTERM"),100).unref?.()}});break;case"upgrade.status":await T(this.client,e.id,{currentVersion:this.cliVersion});break;case"upgrade.set-policy":await he(s,e);break;case"machine.remote-access.pause":await X(this.client,this.remoteAccessPauseController,e);break;case"agents.refresh":await P(s,e);break;case"agent.permission.respond":await Je(s,e);break;case"agent.auth.start":case"agent.auth.logout":case"agent.session-options.get":case"agent.external-sessions.list":case"agent.external-sessions.import":case"agent.external-sessions.close":case"agent.external-sessions.delete":await $e(s,e);break;case"models.refresh":await C(s,e);break;case"agent.config.get":await E(s,e);break;case"agent.config.upsert":await j(s,e);break;case"agent.config.clear":await F(s,e);break;case"agent.config.test":await Q(s,e);break;case"agent.workspace.validate":await $(s,e);break;case"agent.capabilities.list":await D(s,e);break;case"skill.list":case"skill.install":case"skill.doctor":case"skill.setup":case"skill.use":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;case"session.wechat-rpa.channel.get":case"session.wechat-rpa.channel.upsert":case"session.wechat-rpa.channel.sync":case"manager.wechat-rpa.channel.get":case"manager.wechat-rpa.channel.upsert":case"manager.wechat-rpa.channel.sync":this.client.sendRes({type:"res",id:e.id,ok:!1,error:"feature_retired"});break;default:this.client.sendRes({type:"res",id:e.id,ok:!1,error:`Unknown method: ${e.method}`})}}catch(n){if(t.propagateErrors)throw n;this.client.sendRes({type:"res",id:e.id,ok:!1,error:n instanceof Error?n.message:String(n)})}finally{this.activeRequests--}return r}evictIdleSessions(){if(this.sessions.size<Ke)return;let e=null;for(const[t,s]of this.sessions)(!e||s.lastActiveAt<e.session.lastActiveAt)&&(e={key:t,session:s});e&&(this.revokeManagedRoomToken(e.session),e.session.heartbeatTimer&&(clearInterval(e.session.heartbeatTimer),e.session.heartbeatTimer=null),e.session.adapter.removeAllListeners(),e.session.adapter.stop().catch(()=>{}),this.sessions.delete(e.key))}resolvePath(e){return ye(e)}resolveAuthorizedPath(e,t){return fe(e,pe(t))}async resolveAuthorizedPathAsync(e,t){return ve(e,await ge(t))}async cleanup(){this.chatQueue.stop(),this.projectFsHandleStore.revokeAll(),this.acpDiscoveryWatcher.stop(),this.nativeFusion?.setExternalTerminalHandler?.(null),this.nativeCleanupOutbox.stop(),this.historySubscriptions.closeAll(),this.activityProbeTimer&&(clearInterval(this.activityProbeTimer),this.activityProbeTimer=null),this.attachmentCleanupTimer&&(clearInterval(this.attachmentCleanupTimer),this.attachmentCleanupTimer=null);for(const[,e]of this.sessions)this.revokeManagedRoomToken(e),e.heartbeatTimer&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=null),e.adapter.removeAllListeners(),await e.adapter.stop().catch(()=>{});this.sessions.clear(),this.runTextAcc.clear(),Z(this.getRuntime()),await this.managerRuntime.stop(),d(null)}revokeManagedRoomToken(e){const t=e.managedRoomContextToken;e.managedRoomContextToken=null,t&&this.managedRoomContextRevoker?.(t)}}export{tt as SessionManager,nt as resolveSessionWorkDir,Xe as upgradeRecoveryVisibleMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import o from"node:fs";import a from"node:path";import{getShennianDir as s}from"../config/index.js";import{assertPathsSeparate as d}from"./workspace.js";import{readPersonalPaths as l,savePersonalPaths as y}from"./settings.js";function f(e){if(!a.isAbsolute(e)||/[\u0000-\u001f]/.test(e))throw new Error("personal_absolute_directory_required");const r=a.resolve(e);d(r,s());let t=r;for(;;){try{if(o.lstatSync(t).isSymbolicLink())throw new Error("personal_symlink_forbidden")}catch(c){if(c.code!=="ENOENT")throw c}const n=a.dirname(t);if(n===t)break;t=n}if(o.existsSync(r)&&!o.statSync(r).isDirectory())throw new Error("personal_directory_required");o.mkdirSync(r,{recursive:!0,mode:448});const i=o.realpathSync(r);return d(i,o.existsSync(s())?o.realpathSync(s()):s()),i}function _(e){if(!e.workspace&&!e.diary)throw new Error("personal_directory_required");const r={...l()};return e.workspace&&(r.workspace=f(e.workspace)),e.diary&&(r.diary=f(e.diary)),y(r),r}export{_ as configurePersonalPaths,f as validatePersonalDirectory};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import o from"node:fs";import s from"node:os";import n from"node:path";import{randomUUID as a}from"node:crypto";import{getShennianDir as t}from"../config/index.js";const i=()=>n.join(t(),"personal-paths.json");function m(){try{const r=JSON.parse(o.readFileSync(i(),"utf8"));if(!r||typeof r!="object"||Array.isArray(r))throw new Error;for(const e of["workspace","diary"])if(r[e]!==void 0&&(typeof r[e]!="string"||!n.isAbsolute(r[e])))throw new Error;return{workspace:r.workspace,diary:r.diary}}catch(r){if(r.code==="ENOENT")return{};throw new Error("personal_settings_invalid")}}function d(){const r=`${t()}-steward`;return o.existsSync(r)||process.env.SHENNIAN_HOME||process.env.VITEST?r:n.join(s.homedir(),"shennian_agent")}function u(r){o.mkdirSync(t(),{recursive:!0,mode:448});const e=`${i()}.${a()}.tmp`;try{o.writeFileSync(e,JSON.stringify(r,null,2)+`
|
|
2
|
+
`,{mode:384,flag:"wx"}),o.renameSync(e,i())}finally{try{o.unlinkSync(e)}catch{}}}export{d as defaultWorkspace,m as readPersonalPaths,u as savePersonalPaths};
|
|
@@ -45,6 +45,13 @@ import{STEWARD_INDEX_ONBOARDING as n}from"./onboarding.js";const e=4,s=`<!-- she
|
|
|
45
45
|
|
|
46
46
|
${n}
|
|
47
47
|
|
|
48
|
+
## \u65E5\u8BB0\u4E0E\u8BB0\u5FC6
|
|
49
|
+
|
|
50
|
+
- Personal Agent \u5DE5\u4F5C\u533A\u4E0E\u65E5\u8BB0\u76EE\u5F55\u7531 Client \u5206\u522B\u914D\u7F6E\u3002\u7528 shennian steward paths \u67E5\u770B\u5B9E\u9645\u8DEF\u5F84\uFF0C\u4E0D\u5199\u6B7B\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u628A\u672A\u914D\u7F6E\u89E3\u91CA\u4E3A\u7A7A\u65E5\u8BB0\u3002
|
|
51
|
+
- \u53EA\u6709\u7528\u6237\u660E\u786E\u8981\u6C42\u8BB0\u65E5\u8BB0\u3001\u8865\u8BB0\u6216\u7FFB\u770B\u65F6\u624D\u8FDB\u5165\u65E5\u8BB0\u76EE\u5F55\uFF1B\u4E00\u5929\u4E00\u7BC7\uFF0C\u4EE5\u7528\u6237\u8BBE\u5B9A\u7684\u65F6\u533A\uFF08\u672A\u8BBE\u65F6\u5148\u786E\u8BA4\uFF09\u4FDD\u5B58\u4E3A YYYY/YYYY-MM-DD.md\u3002
|
|
52
|
+
- \u6B63\u6587\u4F7F\u7528 # \u65E5\u671F\uFF5C\u4E00\u53E5\u8BDD\u5C0F\u6807\u9898\uFF0C\u4E0B\u4E00\u884C > \u6982\u8981\uFF1A\u2026\uFF1B\u53EA\u4F9D\u636E\u7528\u6237\u63D0\u4F9B\u7684\u7ECF\u5386\u8BB0\u5F55\uFF0C\u4E0D\u7F16\u9020\uFF0C\u5DF2\u6709\u6B63\u6587\u5148\u8BFB\u518D\u8865\u5145\uFF0C\u4E0D\u8986\u76D6\u3002
|
|
53
|
+
- \u65E5\u8BB0\u6807\u9898\u3001\u6982\u8981\u548C\u6B63\u6587\u4E0D\u8FDB\u5165\u5168\u5C40\u8D44\u6599\u7D22\u5F15\u3002\u624B\u673A\u65E5\u8BB0\u548C\u8BB0\u5FC6\u9996\u7248\u53EA\u8BFB\uFF0C\u4E0D\u56E0\u6D4F\u89C8\u8BF7\u6C42\u7F16\u8F91\u6216\u81EA\u52A8\u751F\u6210\u6587\u4EF6\u3002
|
|
54
|
+
|
|
48
55
|
## \u8BB0\u5F55
|
|
49
56
|
|
|
50
57
|
- \u53EA\u5728\u7528\u6237\u8981\u6C42\uFF0C\u6216\u51FA\u73B0\u957F\u671F\u6709\u7528\u7684\u4FE1\u606F\uFF08\u65B0\u9879\u76EE\u7684\u7528\u9014\u3001\u5E38\u7528\u7FA4\u7684\u7EA6\u5B9A\uFF09\u65F6\uFF0C\u624D\u66F4\u65B0 index.md \u7B49\u6587\u4EF6\u3002\u4E0D\u8981\u5199\u6D88\u606F\u6570\u3001\u5728\u7EBF\u72B6\u6001\u3001\u6210\u5458\u540D\u5355\u8FD9\u7C7B\u5B9E\u65F6\u5185\u5BB9\u3002
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"node:fs";import n from"node:path";import{getShennianDir as
|
|
1
|
+
import o from"node:fs";import n from"node:path";import{getShennianDir as i}from"../config/index.js";import{readPersonalPaths as u,defaultWorkspace as h}from"./settings.js";import{STEWARD_AGENTS_MD as l,STEWARD_CLAUDE_MD as m,STEWARD_INDEX_MD as S}from"./templates.js";class a extends Error{code;constructor(r,t){super(t),this.code=r}}function y(){return u().workspace??h()}const E=[["AGENTS.md",l],["index.md",S],["CLAUDE.md",m]];function W(){const e=y();w(e,i()),_(e),w(o.realpathSync.native(e),k(i()));const r=[];for(const[t,s]of E){const f=n.join(e,t);try{o.writeFileSync(f,s,{encoding:"utf8",mode:384,flag:"wx"}),r.push(t)}catch(c){if(c.code!=="EEXIST")throw c}}return{dir:o.realpathSync.native(e),created:r}}function _(e){let r=null;try{r=o.lstatSync(e)}catch(s){if(s.code!=="ENOENT")throw s}if(r?.isSymbolicLink())throw new a("steward_workspace_symlink","The steward workspace path must not be a symbolic link.");if(r&&!r.isDirectory())throw new a("steward_workspace_not_directory","The steward workspace path is not a directory.");if(r||o.mkdirSync(e,{mode:448}),process.platform==="win32")return;const t=o.lstatSync(e);if(typeof process.getuid=="function"&&t.uid!==process.getuid())throw new a("steward_workspace_owner","The steward workspace is owned by another user.");(t.mode&63)!==0&&o.chmodSync(e,448)}function k(e){try{return o.realpathSync.native(e)}catch{return n.resolve(e)}}function p(e){const r=n.resolve(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function d(e,r){const t=n.relative(p(r),p(e));return t===""||!t.startsWith("..")&&!n.isAbsolute(t)}function w(e,r){if(d(e,r)||d(r,e))throw new a("steward_workspace_overlaps_credentials","The steward workspace must be separate from the Shennian credential directory.")}export{E as STEWARD_FILES,a as StewardWorkspaceError,w as assertPathsSeparate,W as ensureStewardWorkspace,y as getStewardDir};
|