@anureo/host 0.0.0-stage → 0.3.12

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/src/host.ts ADDED
@@ -0,0 +1,1229 @@
1
+ import { HarnessCatalogService } from "./catalog";
2
+ import { createOwnedSwarmClient } from "./swarm-client";
3
+ import { swarmWorkflowOptions } from "./swarm-workflows";
4
+ import type { SwarmWorkflowOptions } from "@anureo/adapter-swarm";
5
+ import { publicSubagents, registerSubagent, inlineSubagentHistory, type SubagentTurn, type SubagentHistoryPort, type SubagentDiscoveryPort } from './subagents';
6
+ import type { CatalogWorker,CatalogDiagnostic } from "./catalog-worker";
7
+ import { randomUUID } from "node:crypto";
8
+ import { realpathSync } from "node:fs";
9
+ import path from "node:path";
10
+ import { SecretRedactor,type Client,type Session } from "@anureo/sdk";
11
+ import { HarnessSdkError } from "@anureo/sdk";
12
+ import { clientInteractionCapture } from "./interaction-capture";
13
+ import { assertDefinition,publicValue,assertInteractionResponse,assertResult, type Item,type Capabilities,type JsonObject,type JsonValue,type AhpEvent,type SessionOpenParams,type InteractionResponse,type Boundary,type RevertScope,type InputBlock,type McpServer,type JsonSchema } from "@anureo/protocol";
14
+ import { isHxMethod,validateHxRequest,validateHxResult,type HxMethod,type HxRequestMap,type HxResultMap,type OperationResult,type HostEvent,type HxContextReference,type HxHarnessChangedNotification,type HxQueueState } from "./legacy-protocol";
15
+ import type { HarnessStore, SessionRecord } from "./store";
16
+ import { nativeSubagentActivity } from "./native-subagent";
17
+ import type { RpcRequest, RpcResponse } from "./rpc";
18
+ import { sessionSummary, type SessionListParams, type SessionListResult } from "./protocol";
19
+ import type { HostActor } from "./scoped-host";
20
+ import { HostError,historyReadError,hostError,rpcError } from "./errors";
21
+ import { PersistentSecretRedactor } from "./persistent-secrets";
22
+ import { publicQueue,type StoredQueueItem } from "./queue";
23
+ import { assertWorkspaceMutable,type WorkspacePort,type WorkspaceRequest,type WorkspaceAllocation,type WorkspaceStopEvidence } from "./workspaces";
24
+
25
+ export type Role="viewer"|"member"|"maintainer";
26
+ export interface Principal {userId:string;mode:"on"|"off";isAdmin?:boolean;service?:boolean}
27
+ export type HostConnection = import("./rpc").HostConnection<Principal>;
28
+ export type RuntimeAuthStatus="unknown"|"required"|"ready";
29
+ export interface RuntimeRegistration {
30
+ discoverSubagents?:SubagentDiscoveryPort;
31
+ readSubagentHistory?:SubagentHistoryPort;
32
+ id:string;adapterId:string;providerId?:string;name?:string;authStatus?:RuntimeAuthStatus;version?:string;capabilities?:Capabilities;available?:boolean;reason?:string;maxConcurrency?:number;ownedRuntime?:boolean;
33
+ /** Builds one Client per live session; createClient initializes and negotiates native-lifecycle before anything opens on it. */
34
+ create:(context?:{commandOutputPrivacy:SecretRedactor})=>Client|Promise<Client>;
35
+ catalogScope?:string;catalogFingerprint?:string;catalogWorker?:()=>CatalogWorker;
36
+ models?:()=>Promise<{id:string;name:string;isDefault?:boolean;group?:"primary"|"more";effortLevels?:string[];defaultEffort?:string;supportsFast?:boolean}[]>;
37
+ getAuthStatus?:()=>Promise<RuntimeAuthStatus>;
38
+ /** Provider query only: return evidence, never resubmit or mutate an execution. */
39
+ inspectExecution?:(binding:SessionRecord["binding"],turnId?:string)=>Promise<{stopped:boolean;status?:"completed"|"interrupted"|"failed";turnId?:string}>;
40
+ }
41
+ export interface PermissionPolicyPort {
42
+ isFullAccess(context:{adapterId:string;config:JsonObject;overrides?:JsonObject}):boolean;
43
+ downgrade(context:{adapterId:string;config:JsonObject;overrides?:JsonObject}):{config:JsonObject;overrides?:JsonObject;permissionMode?:string};
44
+ }
45
+ export interface HostProjection {
46
+ readonly lastSeq: number;
47
+ apply(event: HostEvent): void;
48
+ restore(checkpoint: unknown): boolean;
49
+ reset(): void;
50
+ serialize(): JsonValue;
51
+ snapshot(): readonly SubagentTurn[];
52
+ }
53
+ export type FullAccessSession={sessionId:string;projectId:string;agentId:string;title:string;running:boolean;connected:boolean};
54
+ export type PermissionDowngradeResult={downgraded:string[];deferred:string[];failed:{sessionId:string;message:string}[]};
55
+ export interface HostOptions {
56
+ store:HarnessStore;runtimes:RuntimeRegistration[];
57
+ projection?: {version:number;create():HostProjection};
58
+ /** Rebuild an independent catalog; failure preserves the installed catalog. */
59
+ loadRuntimes?:()=>Promise<RuntimeRegistration[]>;
60
+ projectRoot:(id:string)=>string|undefined|Promise<string|undefined>;
61
+ can:(principal:Principal,projectId:string,minimum:Role)=>boolean|Promise<boolean>;
62
+ applicationAuthorization?:boolean;
63
+ maxNotificationEvents?:number;maxNotificationBytes?:number;
64
+ shutdownTimeoutMs?:number;
65
+ /** Product may temporarily suspend the shared gate; capacity reports limit=0 (unlimited). */
66
+ enforceConcurrencyLimits?:boolean;
67
+ onCatalogDiagnostic?:(event:CatalogDiagnostic)=>void;
68
+ catalogPolicy?:{freshMs?:number;refreshTimeoutMs?:number;concurrency?:number};
69
+ onError?:(code:string)=>void;
70
+ /** Observability fan-out: every persisted durable event, at the single publish point. Must not throw; never used for control flow. */
71
+ onEvent?:(event:HostEvent)=>void;
72
+ /**
73
+ * A live session event stream failed; surfaced for forensics. `recoveryRequired` tells whether the session was moved to
74
+ * recovery (uncertain execution) or merely closed (idle, safe to reopen). `message` is the raw source error message.
75
+ */
76
+ onEventStreamError?:(context:{sessionId:string;code:string;message?:string;outcomeUnknown?:boolean;recoveryRequired?:boolean})=>void;
77
+ /** Resolve product defaults before opening a switched binding; never changes create inputs. */
78
+ resolveHarnessConfiguration?:(context:{principal:Principal;session:ReturnType<HarnessHost['publicSession']>;runtimeConfigId:string})=>Promise<{model?:string;config:JsonObject}|undefined>;
79
+ /** Product preference synchronization; failures never change a committed operation result. */
80
+ onConfigurationCommitted?:(context:{principal:Principal;session:ReturnType<HarnessHost['publicSession']>;changed:string[]})=>Promise<void>|void;
81
+ workspaces?:WorkspacePort;
82
+ permissionPolicy?:PermissionPolicyPort;
83
+ onBeforeTurn?:(context:{sessionId:string;turnId:string;projectId:string;cwd:string})=>Promise<void>|void;
84
+ onTurnSettled?:(context:{sessionId:string;turnId:string;projectId:string;cwd:string;status:"completed"|"interrupted"|"failed"})=>Promise<void>|void;
85
+ /** Product policy is injected by the authenticated Server, never imported by the SDK. */
86
+ resolveSessionContext?:(context:{principal:Principal;projectId:string;agentId?:string;adapterId:string;runtimeConfigId?:string;providerId?:string})=>Promise<{instructions?:string;mcpServers?:McpServer[]}>;
87
+ /** Adds per-runtime MCP credentials. The Host does not persist these servers or their headers. */
88
+ bindRuntimeMcp?:(context:{sessionId:string;projectId:string;ownerId:string;adapterId:string;providerId?:string;mode:"new"|"resume"|"fork"})=>RuntimeMcpBinding|undefined|Promise<RuntimeMcpBinding|undefined>;
89
+ validateConfig?:(context:{principal:Principal;sessionId?:string;projectId:string;runtimeConfigId:string;adapterId:string;config:JsonObject;overrides?:JsonObject})=>Promise<void>|void;
90
+ prepareItem?:(context:{sessionId:string;projectId:string;cwd:string;item:Item})=>Promise<Item>;
91
+ resolveInput?:(context:{sessionId:string;projectId:string;cwd:string;input:InputBlock[];references:HxContextReference[]})=>Promise<InputBlock[]>;
92
+ }
93
+ interface RuntimeMcpBinding {servers:readonly McpServer[];release():void}
94
+ interface LiveSession {client:Client;session:Session;reader:AsyncIterator<AhpEvent>;pump:Promise<void>;runtimeConfigId:string;registration:RuntimeRegistration;bindingGeneration:number;nativeTurnToCanonical:Map<string,string>;pendingCanonical:string[];streamSeqs:Map<string,number>;mcp?:RuntimeMcpBinding}
95
+ interface Subscription {id:string;sessionId:string;connection:HostConnection;lastSeq:number;pending:number;bytes:number;tail:Promise<void>;active:boolean}
96
+ type Values=Record<string,unknown>;
97
+ const writes=new Set(["hx.session.create","hx.session.open","hx.session.close","hx.session.fork","hx.session.revert","hx.session.config.set","hx.session.archive","hx.session.restore","hx.turn.start","hx.turn.steer","hx.turn.interrupt","hx.interaction.respond","hx.interaction.cancel","hx.goal.set","hx.goal.clear","hx.compact.start","hx.review.start","hx.session.harness.set","hx.workspace.integrate","hx.workspace.discard",...Array.from(["enqueue","update","remove","reorder","clear","pause","resume","run","steer","retry"],action=>`hx.queue.${action}`)]);
98
+ const metadataWrites=new Set(["hx.session.open","hx.session.close","hx.session.revert","hx.session.config.set","hx.session.archive","hx.session.restore","hx.goal.set","hx.goal.clear","hx.session.harness.set","hx.workspace.integrate","hx.workspace.discard"]);
99
+ const revisionRequired=new Set([...metadataWrites,"hx.session.fork","hx.turn.start","hx.compact.start","hx.review.start"]);
100
+ const str=(p:Values,key:string)=>{const v=p[key];if(typeof v!=="string"||!v)throw new HostError("INVALID_PARAMS");return v;};
101
+ const optionalStr=(p:Values,key:string)=>typeof p[key]==="string"?p[key] as string:undefined;
102
+
103
+ export class HarnessHost {
104
+ readonly store:HarnessStore;
105
+ private runtimes:RuntimeRegistration[];
106
+ private catalogRevision=1;
107
+ private catalogRefresh:Promise<void>=Promise.resolve();
108
+ private readonly catalogScopes=new Map<string,{connection:HostConnection;projects:Set<string>}>();
109
+ private readonly catalogAuthChecks=new WeakMap<RuntimeRegistration,{pending:boolean;checkedAt:number}>();
110
+ readonly catalog:HarnessCatalogService;
111
+ private readonly catalogEpoch=randomUUID();
112
+ private readonly snapshotScopes=new Map<string,{connection:HostConnection;projects:Set<string>}>();
113
+ private readonly manualRefreshes=new Map<string,number>();
114
+ private bootstrap?:Promise<void>;
115
+ private backgroundStarted=false;
116
+ private bootstrapRetry?:ReturnType<typeof setTimeout>;
117
+ private readonly initialized=new Set<string>();
118
+ private readonly live=new Map<string,LiveSession>();
119
+ private readonly subscriptions=new Map<string,Subscription>();
120
+ private readonly locks=new Map<string,Promise<void>>();
121
+ private readonly privateInteractions=new Map<string,JsonObject>();
122
+ private readonly secrets=new Map<string,SecretRedactor>();
123
+ private readonly activeCounts=new Map<string,number>();
124
+ private readonly controlBusy=new Set<string>();
125
+ private readonly bindingBusy=new Set<string>();
126
+ private readonly queuePumps=new Map<string,Promise<void>>();
127
+ private readonly queueAgain=new Set<string>();
128
+ private readonly admissions=new Map<string,string>();
129
+ private shuttingDown=false;
130
+ private storageClosed=false;
131
+ private readonly inFlight=new Set<Promise<unknown>>();
132
+ private readonly subagentDiscovery=new Map<string,Promise<void>>();
133
+ private readonly repairedSubagentSessions=new Set<string>();
134
+ private readonly closedResults=new Map<string,OperationResult>();
135
+ private closing?:Promise<void>;
136
+ constructor(private readonly options:HostOptions){this.store=options.store;this.runtimes=[...options.runtimes];this.catalog=new HarnessCatalogService({store:this.store.catalog,digest:value=>this.store.digest(value),...options.catalogPolicy,onDiagnostic:options.onCatalogDiagnostic,onChanged:(id,changes)=>{void this.notifyCatalogSnapshot([id],changes);if(changes.includes("models"))void this.notifyCatalogChanged();}});this.catalog.replace(this.runtimes);this.store.recover();queueMicrotask(()=>{if(!this.shuttingDown)for(const session of this.store.sessions())this.scheduleQueue(session.id);});}
137
+
138
+ private async authorizeSessionList(principal:Principal,params:HxRequestMap['hx.session.list']):Promise<void> {
139
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
140
+ try { validateHxRequest('hx.session.list',params); } catch { throw new HostError("INVALID_PARAMS"); }
141
+ await this.access(this.trustedConnection(principal),params.projectId,"viewer");
142
+ }
143
+
144
+ readonly sessions = {
145
+ list: async ({actor}:{actor:HostActor}, params:SessionListParams):Promise<SessionListResult> => {
146
+ const {scopeId,...page}=params;
147
+ await this.authorizeSessionList({userId:actor.userId,mode:"on"},{...page,projectId:scopeId});
148
+ const {ids,nextCursor}=this.store.sessionIdPage(scopeId,page.archived===true,page.cursor,page.limit??100);
149
+ return {
150
+ sessions:ids.map(id=>sessionSummary(this.store.session(id))),
151
+ nextCursor,
152
+ };
153
+ },
154
+ };
155
+
156
+ private readSessionPage(params:HxRequestMap['hx.session.list']):HxResultMap['hx.session.list'] {
157
+ const {projectId,archived,cursor,limit=100}=params;
158
+ const {ids,nextCursor}=this.store.sessionIdPage(projectId,archived===true,cursor,limit);
159
+ return {sessions:ids.map(id=>this.publicSession(id)),nextCursor};
160
+ }
161
+ publicSession(id:string) {
162
+ this.repairLegacySubagents(id);
163
+ const value=this.store.publicSession(id),options=value.capabilities?.config?.options;
164
+ // Older persisted Codex capabilities predate the adapter's permission preset.
165
+ // Upgrade only a dormant, still-configurable binding from its verified catalog;
166
+ // never override a live capability downgrade or reopen a process for a read.
167
+ if(value.adapterId==="codex"&&!this.live.has(id)&&options?.some(option=>option.id==="approvalPolicy")&&!options.some(option=>option.id==="permissionMode")){
168
+ const preset=this.runtimes.find(runtime=>runtime.id===value.runtimeConfigId&&runtime.adapterId==="codex"&&runtime.available!==false)?.capabilities?.config?.options.find(option=>option.id==="permissionMode");
169
+ if(preset)value.capabilities={...value.capabilities,config:{options:[structuredClone(preset),...options]}};
170
+ }
171
+ const subagents=publicSubagents(this.store.session(id),runtimeConfigId=>!!this.runtimes.find(runtime=>runtime.id===runtimeConfigId&&runtime.available!==false)?.readSubagentHistory);
172
+ return {...value,executionMode:value.executionMode??"normal",subagents,bindingGeneration:value.bindingGeneration??1,hostCapabilities:{queue:true,worktree:!!this.options.workspaces,harnessSwitch:true,managed:true,subagents:true}};
173
+ }
174
+ catalogSnapshot():HxResultMap["hx.harness.list"]["harnesses"] {
175
+ return this.runtimes.map(r=>({runtimeConfigId:r.id,adapterId:r.adapterId,providerId:r.providerId??(r.adapterId==="claude"?"claude-code":r.adapterId),name:r.name??r.id,authStatus:r.authStatus??"unknown",available:r.available!==false,...(r.reason?{reason:r.reason}:{}),...(r.version?{version:r.version}:{}),capabilities:structuredClone(r.capabilities??{})}));
176
+ }
177
+ async modelCatalog(runtimeConfigId:string):Promise<HxResultMap["hx.harness.models"]> {
178
+ await this.prepareRuntime(runtimeConfigId);
179
+ const descriptor=this.runtimes.find(runtime=>runtime.id===runtimeConfigId&&runtime.available!==false);if(!descriptor)throw new HostError("HARNESS_UNAVAILABLE");
180
+ return descriptor.models||descriptor.catalogWorker?{models:await this.catalog.legacyModels(runtimeConfigId),source:"live"}:{models:[],source:"unavailable"};
181
+ }
182
+ startBackground():void {
183
+ if(this.backgroundStarted||this.shuttingDown)return;this.backgroundStarted=true;
184
+ this.bootstrapBackground();
185
+ }
186
+ private bootstrapBackground():void {
187
+ if(this.shuttingDown)return;
188
+ this.bootstrap=this.refreshCatalog().catch(cause=>{
189
+ if(this.shuttingDown)return;
190
+ try{this.options.onError?.(hostError(cause).code);}catch{}
191
+ this.bootstrapRetry=setTimeout(()=>this.bootstrapBackground(),30_000);this.bootstrapRetry.unref?.();
192
+ }).finally(()=>{if(!this.shuttingDown)this.catalog.startBackground();});
193
+ }
194
+ private async prepareRuntime(id:string):Promise<void> {
195
+ const candidate=this.runtimes.find(r=>r.id===id);
196
+ if(candidate?.reason!=="HARNESS_PREPARING")return;
197
+ if(!this.bootstrap)throw new HostError("HARNESS_PREPARING","HARNESS_PREPARING",true,false);
198
+ let timer:ReturnType<typeof setTimeout>|undefined;
199
+ try{await Promise.race([this.bootstrap,new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new HostError("HARNESS_PREPARING","HARNESS_PREPARING",true,false)),10_000);})]);}finally{if(timer)clearTimeout(timer);}
200
+ if(this.runtimes.find(r=>r.id===id)?.reason==="HARNESS_PREPARING")throw new HostError("HARNESS_PREPARING","HARNESS_PREPARING",true,false);
201
+ }
202
+ resolveRuntimeConfigId(providerId:string):string {
203
+ const matches=this.runtimes.filter(runtime=>(runtime.available!==false||runtime.reason==="HARNESS_PREPARING")&&(runtime.providerId??(runtime.adapterId==="claude"?"claude-code":runtime.adapterId))===providerId);
204
+ const preferred=({codex:"codex-native","claude-code":"claude-native",anureo:"anureo-acp"} as Record<string,string>)[providerId];
205
+ if(preferred&&matches.some(runtime=>runtime.id===preferred))return preferred;
206
+ if(matches.length===1)return matches[0]!.id;
207
+ throw new HostError(matches.length?"HARNESS_SELECTION_REQUIRED":"HARNESS_UNAVAILABLE");
208
+ }
209
+ capacity(runtimeConfigId:string):{busy:number;limit:number} {
210
+ const registration=this.runtimes.find(runtime=>runtime.id===runtimeConfigId);if(!registration)throw new HostError("HARNESS_UNAVAILABLE");
211
+ const uncertain=this.store.sessions().filter(record=>record.uncertainRuntimeConfigIds?.includes(runtimeConfigId)||(record.runtimeConfigId===runtimeConfigId&&!this.live.has(record.id)&&record.status==="recoveryRequired"&&this.store.evidence(record.id,record.bindingGeneration??1,"session")?.quiescent!==true)).length;
212
+ return{busy:(this.activeCounts.get(runtimeConfigId)??0)+uncertain+[...this.admissions.values()].filter(id=>id===runtimeConfigId).length,limit:this.concurrencyLimit(registration)};
213
+ }
214
+ private concurrencyLimit(registration:RuntimeRegistration):number {return this.options.enforceConcurrencyLimits===false?0:registration.maxConcurrency??4;}
215
+ queueSnapshot(id:string):HxQueueState {return publicQueue(this.store.queue(id));}
216
+ transcript(id:string,seen=new Set<string>()):HostEvent[] {
217
+ const session=this.store.session(id);if(seen.has(id)||seen.size>=64)throw new HostError("TRANSCRIPT_ANCESTRY_INVALID");seen.add(id);
218
+ let inherited:HostEvent[]=[];
219
+ if(session.parent){const parent=this.store.session(session.parent.sessionId);if(parent.projectId!==session.projectId)throw new HostError("PROJECT_FORBIDDEN");const records=this.transcript(parent.id,seen),boundary=session.parent.boundary;
220
+ const indexes=records.map((event,index)=>({event,index})).filter(({event})=>(event.turnId??("turnId"in event.event.payload?event.event.payload.turnId:undefined))===boundary.turnId);
221
+ if(!indexes.length)throw new HostError("TURN_NOT_FOUND");const first=indexes[0]!.index;const terminal=indexes.find(({event})=>event.event.type==="turn/completed")?.index??indexes.at(-1)!.index;
222
+ inherited=records.slice(0,boundary.relation==="before"?first:terminal+1);
223
+ }
224
+ const current:HostEvent[]=[];let cursor=0;const through=this.store.session(id).latestSeq;while(cursor<through){const page=this.store.events(id,cursor,through,1000);current.push(...page.events);if(page.nextAfterSeq<=cursor)throw new HostError("CURSOR_INVALID");cursor=page.nextAfterSeq;}
225
+ return [...inherited,...current];
226
+ }
227
+ /** Trusted product port. This is intentionally absent from the browser protocol. */
228
+ reserveAdmission(input:{admissionRef:string;runtimeConfigId:string}):void {
229
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
230
+ const old=this.admissions.get(input.admissionRef);if(old){if(old!==input.runtimeConfigId)throw new HostError("ADMISSION_CONFLICT");return;}
231
+ const runtime=this.runtimes.find(value=>value.id===input.runtimeConfigId&&value.available!==false);if(!runtime)throw new HostError("HARNESS_UNAVAILABLE");
232
+ const capacity=this.capacity(runtime.id);
233
+ if(capacity.limit>0&&capacity.busy>=capacity.limit)throw new HostError("HARNESS_CAPACITY_EXCEEDED");
234
+ this.admissions.set(input.admissionRef,runtime.id);
235
+ }
236
+ releaseAdmission(ref:string):void {this.admissions.delete(ref);}
237
+ private trustedConnection(principal:Principal):HostConnection {return {id:`trusted:${principal.userId}`,principal:()=>principal,send:()=>{}};}
238
+ async createManagedSession(input:{principal:Principal;projectId:string;agentId?:string;scopeId:string;executionKey:string;runtimeConfigId:string;instructions:string;config?:JsonObject;model?:string;mcpServers?:McpServer[];admissionRef?:string;workspace?:WorkspaceRequest;directory?:{cwd:string;allowedRoots:string[]}}):Promise<OperationResult> {
239
+ if(!input.scopeId||!input.executionKey)throw new HostError("INVALID_PARAMS");
240
+ const {principal,...context}=input;
241
+ return this.write(this.trustedConnection(principal),"hx.session.create",{projectId:context.projectId,runtimeConfigId:context.runtimeConfigId,idempotencyKey:`managed:${context.scopeId}:${context.executionKey}`,config:context.config??{},...(context.agentId?{agentId:context.agentId}:{}),...(context.model?{model:context.model}:{}),...(context.workspace?{workspace:context.workspace}:{}),_trusted:true,_managed:{scopeId:context.scopeId,executionKey:context.executionKey},_fixedContext:{instructions:context.instructions,mcpServers:context.mcpServers??[]},...(context.admissionRef?{_admissionRef:context.admissionRef}:{}),...(context.directory?{_directory:context.directory}:{})});
242
+ }
243
+ async startManagedTurn(input:{principal:Principal;sessionId:string;executionKey:string;input:InputBlock[];outputSchema?:JsonSchema}):Promise<OperationResult> {
244
+ const record=this.store.session(input.sessionId);if(!record.managed||record.managed.executionKey!==input.executionKey)throw new HostError("MANAGED_CONTEXT_MISMATCH");
245
+ return this.write(this.trustedConnection(input.principal),"hx.turn.start",{sessionId:record.id,expectedRevision:record.revision,idempotencyKey:`managed-turn:${input.executionKey}`,input:input.input,...(input.outputSchema!==undefined?{outputSchema:input.outputSchema}:{}),_trusted:true});
246
+ }
247
+ async managedSessionOperation(input:{principal:Principal;projectId:string;scopeId:string;executionKey:string}):Promise<OperationResult|undefined> {
248
+ await this.access(this.trustedConnection(input.principal),input.projectId,"viewer");
249
+ return this.store.lookup(input.principal.userId,"hx.session.create",input.projectId,`managed:${input.scopeId}:${input.executionKey}`)?.value;
250
+ }
251
+ async managedOperation(input:{principal:Principal;sessionId:string;executionKey:string}):Promise<OperationResult|undefined> {
252
+ const record=await this.authorizedSession(this.trustedConnection(input.principal),{sessionId:input.sessionId},"viewer");
253
+ if(record.managed?.executionKey!==input.executionKey)throw new HostError("MANAGED_CONTEXT_MISMATCH");
254
+ return this.store.lookup(record.ownerId,"hx.turn.start",record.id,`managed-turn:${input.executionKey}`)?.value;
255
+ }
256
+ async stopManagedExecution(input:{principal:Principal;sessionId:string;turnId?:string}):Promise<{quiescent:boolean;evidenceRef?:string}> {
257
+ const record=await this.authorizedSession(this.trustedConnection(input.principal),{sessionId:input.sessionId},"maintainer");if(!record.managed)throw new HostError("MANAGED_CONTEXT_MISMATCH");
258
+ const turnId=input.turnId??record.activeTurnId;
259
+ if(turnId&&this.live.has(record.id)){try{await this.write(this.trustedConnection(input.principal),"hx.turn.interrupt",{sessionId:record.id,turnId,idempotencyKey:`managed-stop:${record.managed.executionKey}:${turnId}`,_trusted:true});}catch{/* Only independent evidence below can report quiescence. */}}
260
+ const evidence=await this.executionEvidence(record.id,turnId,true);return{quiescent:evidence.quiescent,...(evidence.evidenceRef?{evidenceRef:evidence.evidenceRef}:{})};
261
+ }
262
+ private async turnHook(kind:"before"|"settled",id:string,turnId:string,status?:"completed"|"interrupted"|"failed"):Promise<void> {
263
+ const record=this.store.session(id),generation=record.bindingGeneration??1,key=`hook:${kind}:${turnId}`;
264
+ if(this.store.evidence(id,generation,key))return;
265
+ this.store.recordEvidence(id,generation,key,{attempted:true});
266
+ try{const context={sessionId:id,turnId,projectId:record.projectId,cwd:record.cwd};if(kind==="before")await this.options.onBeforeTurn?.(context);else await this.options.onTurnSettled?.({...context,status:status!});}catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
267
+ }
268
+ private async policyAccess(principal:Principal,projectId?:string):Promise<void> {
269
+ if(projectId)await this.access(this.trustedConnection(principal),projectId,"maintainer");
270
+ else if(principal.mode!=="off"&&!principal.isAdmin&&!principal.service)throw new HostError("PROJECT_FORBIDDEN");
271
+ }
272
+ async fullAccessSessions(principal:Principal,projectId?:string):Promise<FullAccessSession[]> {
273
+ await this.policyAccess(principal,projectId);const policy=this.options.permissionPolicy;if(!policy)throw new HostError("PERMISSION_POLICY_UNAVAILABLE");
274
+ return this.store.sessions(projectId).filter(record=>!!record.permissionDowngrade||policy.isFullAccess({adapterId:record.adapterId,config:record.config})).map(record=>({sessionId:record.id,projectId:record.projectId,agentId:record.agentId??"",title:record.title??record.id,running:!!record.activeTurnId||record.status==="running",connected:this.live.has(record.id)}));
275
+ }
276
+ async requestPermissionDowngrades(principal:Principal,projectId?:string):Promise<PermissionDowngradeResult> {
277
+ const targets=await this.fullAccessSessions(principal,projectId),policy=this.options.permissionPolicy!,result:PermissionDowngradeResult={downgraded:[],deferred:[],failed:[]};
278
+ for(const target of targets)try{
279
+ await this.serial(target.sessionId,async()=>{
280
+ const record=this.store.session(target.sessionId),safe=policy.downgrade({adapterId:record.adapterId,config:structuredClone(record.config)});
281
+ if(policy.isFullAccess({adapterId:record.adapterId,...safe}))throw new HostError("PERMISSION_DOWNGRADE_UNVERIFIED");
282
+ record.permissionDowngrade={config:safe.config,...(safe.permissionMode?{permissionMode:safe.permissionMode}:{}),key:record.permissionDowngrade?.state==="pending"?record.permissionDowngrade.key:randomUUID(),principalId:principal.userId,state:"pending"};this.store.saveSession(record);
283
+ if(this.store.queue(record.id).items.some(item=>["queued","failed"].includes(item.state)))this.store.mutateQueue(record.id,undefined,state=>{for(const item of state.items)if(["queued","failed"].includes(item.state)){
284
+ const safeItem=policy.downgrade({adapterId:record.adapterId,config:item.configSnapshot,overrides:item.overrides});if(policy.isFullAccess({adapterId:record.adapterId,...safeItem}))throw new HostError("PERMISSION_DOWNGRADE_UNVERIFIED");item.configSnapshot=safeItem.config;item.overrides=safeItem.overrides;
285
+ }});this.publishQueue(record.id);
286
+ });
287
+ if(await this.applyPermissionDowngrade(target.sessionId))result.downgraded.push(target.sessionId);
288
+ else {const pending=this.store.session(target.sessionId).permissionDowngrade;if(pending?.state==="failed")result.failed.push({sessionId:target.sessionId,message:pending.error??"PERMISSION_DOWNGRADE_FAILED"});else result.deferred.push(target.sessionId);}
289
+ }catch(cause){const record=this.store.session(target.sessionId);if(record.permissionDowngrade){record.permissionDowngrade.state="failed";record.permissionDowngrade.error=hostError(cause).code;this.store.saveSession(record);}result.failed.push({sessionId:target.sessionId,message:hostError(cause).code});}
290
+ return result;
291
+ }
292
+ private async applyPermissionDowngrade(id:string):Promise<boolean> {
293
+ const reserved=await this.serial(id,async()=>{const record=this.store.session(id),pending=record.permissionDowngrade;if(!pending)return undefined;
294
+ if(pending.state==="failed"||this.controlBusy.has(id)||this.bindingBusy.has(id)||record.activeTurnId||["running","opening","recoveryRequired"].includes(record.status)||record.goal?.status==="active"||this.store.interactions(id).some(item=>item.state!=="resolved"))return undefined;
295
+ const previous=this.store.lookup(pending.principalId,"host.permissions.downgrade",id,pending.key);
296
+ if(previous){if(previous.value.state==="completed"){delete record.permissionDowngrade;this.store.saveSession(record);}else{pending.state="failed";pending.error=previous.value.outcomeUnknown?"RESULT_UNKNOWN":previous.value.error?.code??"PERMISSION_DOWNGRADE_FAILED";record.permissionDowngrade=pending;if(previous.value.outcomeUnknown)record.status="recoveryRequired";this.store.saveSession(record);}return undefined;}
297
+ const initial=this.store.beginOperation(randomUUID(),pending.principalId,"host.permissions.downgrade",id,pending.key,this.store.digest({config:pending.config,permissionMode:pending.permissionMode??null}),id);
298
+ this.controlBusy.add(id);return{record,pending,initial};
299
+ });
300
+ if(!reserved)return !this.store.session(id).permissionDowngrade;
301
+ try{
302
+ this.store.phase(reserved.initial.operationId,"dispatching");
303
+ const {pending}=reserved,live=this.live.get(id);
304
+ if(live){
305
+ if(!live.session.capabilities.session?.resume)throw new HostError("CAPABILITY_UNSUPPORTED");
306
+ const proof=await this.executionEvidence(id,undefined,true);if(!proof.quiescent)throw new HostError("RESULT_UNKNOWN","Native execution stop is unverified",false,true);
307
+ await this.closeLive(id);
308
+ }
309
+ const next=this.store.session(id);next.config=structuredClone(pending.config);next.permissionMode=pending.permissionMode;this.store.saveSession(next);
310
+ if(live)await this.open(next,"resume");
311
+ const confirmed=this.store.session(id);if(this.options.permissionPolicy!.isFullAccess({adapterId:confirmed.adapterId,config:confirmed.config}))throw new HostError("PERMISSION_DOWNGRADE_UNVERIFIED");
312
+ confirmed.revision++;this.store.finishOperation({...reserved.initial,state:"completed",outcomeUnknown:false,revision:confirmed.revision,result:{downgraded:true}});delete confirmed.permissionDowngrade;this.store.saveSession(confirmed);
313
+ const event=this.store.append(id,{type:"host/permissions",payload:{state:"downgraded",revision:confirmed.revision}});if(event)this.publish(event);return true;
314
+ }catch(cause){const error=hostError(cause);this.store.finishOperation({...reserved.initial,state:error.outcomeUnknown?"unknown":"failed",outcomeUnknown:error.outcomeUnknown,error});const record=this.store.session(id);if(record.permissionDowngrade){record.permissionDowngrade.state="failed";record.permissionDowngrade.error=error.code;if(error.outcomeUnknown)record.status="recoveryRequired";this.store.saveSession(record);}return false;}
315
+ finally{this.controlBusy.delete(id);}
316
+ }
317
+ private redactor(id:string):SecretRedactor {let value=this.secrets.get(id);if(!value){value=new PersistentSecretRedactor(this.store,id);this.secrets.set(id,value);}return value;}
318
+ private projectResult(method:HxMethod,id:string,result:JsonValue):JsonValue {
319
+ const privacy=this.redactor(id);
320
+ if(method==="hx.session.config.set")return privacy.state(result as unknown as Parameters<SecretRedactor["state"]>[0]) as unknown as JsonValue;
321
+ if(method==="hx.goal.set"||method==="hx.goal.clear")return privacy.goal(result as unknown as Parameters<SecretRedactor["goal"]>[0]) as unknown as JsonValue;
322
+ if(result&&typeof result==="object"&&!Array.isArray(result)&&result.config&&typeof result.config==="object")return {...result,config:privacy.json(result.config)};
323
+ return result;
324
+ }
325
+ private principal(connection:HostConnection):Principal {const p=connection.principal();if(!p)throw new HostError("AUTH_REQUIRED");return p;}
326
+ private async access(connection:HostConnection,projectId:string,minimum:Role):Promise<Principal> {
327
+ const p=this.principal(connection);
328
+ const delegated=this.options.applicationAuthorization||p.mode!=="off"&&!p.isAdmin&&!p.service;
329
+ if(delegated&&!await this.options.can(p,projectId,minimum))throw new HostError("PROJECT_FORBIDDEN");
330
+ return p;
331
+ }
332
+ private async authorizedSession(connection:HostConnection,p:Values,minimum:Role):Promise<SessionRecord> {
333
+ const record=this.store.session(str(p,"sessionId"));
334
+ if(p.projectId!==undefined&&p.projectId!==record.projectId)throw new HostError("PROJECT_FORBIDDEN");
335
+ await this.access(connection,record.projectId,minimum);return record;
336
+ }
337
+ private runtime(record:SessionRecord):RuntimeRegistration {
338
+ const descriptor=this.live.get(record.id)?.registration??this.runtimes.find(r=>r.id===record.runtimeConfigId&&r.adapterId===record.adapterId);
339
+ if(!descriptor||descriptor.available===false)throw new HostError("HARNESS_UNAVAILABLE");return descriptor;
340
+ }
341
+ private async serial<T>(key:string,run:()=>Promise<T>):Promise<T> {
342
+ const previous=this.locks.get(key)??Promise.resolve();
343
+ let release!:()=>void;const next=new Promise<void>(resolve=>release=resolve);this.locks.set(key,next);
344
+ await previous.catch(()=>{});
345
+ try{return await run();}finally{release();if(this.locks.get(key)===next)this.locks.delete(key);}
346
+ }
347
+ async request<M extends HxMethod>(connection:HostConnection,method:M,params:HxRequestMap[M]):Promise<HxResultMap[M]>;
348
+ async request(connection:HostConnection,method:string,params:unknown):Promise<unknown> {
349
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
350
+ const pending=this.dispatch(connection,method,params);this.inFlight.add(pending);
351
+ try{return await pending;}finally{this.inFlight.delete(pending);}
352
+ }
353
+ /** 服务端投影快照(方案C):同会话并发请求合并为一次推进。 */
354
+ private projectionJobs=new Map<string,Promise<HxResultMap["hx.projection.snapshot"]>>();
355
+ private projectionSnapshotRequest(record:SessionRecord):Promise<HxResultMap["hx.projection.snapshot"]> {
356
+ const existing=this.projectionJobs.get(record.id);
357
+ if(existing)return existing;
358
+ const job=this.advanceProjection(record).finally(()=>this.projectionJobs.delete(record.id));
359
+ this.projectionJobs.set(record.id,job);
360
+ return job;
361
+ }
362
+ /** 按需推进:持久快照 + gap 分页 apply;读路径实现,不挂 append 钩子(无 stale 风险,天然自愈)。 */
363
+ private async advanceProjection(record:SessionRecord):Promise<HxResultMap["hx.projection.snapshot"]> {
364
+ const latestSeq=this.store.session(record.id).latestSeq;
365
+ // fork 会话的 inherited transcript 不在 durable 流内,P1 不物化,由浏览器 seed 路径回退。
366
+ const projector=this.options.projection;
367
+ if(!projector||record.parent||latestSeq===0)return {checkpoint:null,seq:0,latestSeq};
368
+ const projection=projector.create();
369
+ let from=0;
370
+ const stored=this.store.projectionSnapshot(record.id);
371
+ if(stored&&stored.projectionVersion===projector.version) {
372
+ try{if(projection.restore(JSON.parse(stored.checkpointJson)))from=projection.lastSeq;}catch{/* Replay damaged checkpoints from the log. */}
373
+ }
374
+ if(from<latestSeq) {
375
+ try{from=this.applyEventRange(projection,record.id,from,latestSeq);}
376
+ catch(error) {
377
+ if(from===0)throw error;
378
+ // 旧快照与事件流不衔接:丢弃快照,从零重放自愈
379
+ projection.reset();
380
+ from=this.applyEventRange(projection,record.id,0,latestSeq);
381
+ }
382
+ }
383
+ if(projection.lastSeq!==latestSeq)throw new HostError("EVENT_STREAM_RECOVERY_FAILED");
384
+ const checkpoint=projection.serialize();
385
+ try{this.store.saveProjectionSnapshot(record.id,projector.version,projection.lastSeq,JSON.stringify(checkpoint));}catch{/* A cache write cannot block a read. */}
386
+ return {checkpoint,seq:projection.lastSeq,latestSeq};
387
+ }
388
+ private applyEventRange(projection:HostProjection,sessionId:string,from:number,to:number):number {
389
+ let cursor=from;
390
+ while(cursor<to) {
391
+ const page=this.store.events(sessionId,cursor,to,1000);
392
+ if(!page.events.length)throw new HostError("EVENT_STREAM_RECOVERY_FAILED");
393
+ for(const event of page.events)projection.apply(event);
394
+ if(projection.lastSeq===cursor)throw new HostError("EVENT_STREAM_RECOVERY_FAILED");
395
+ cursor=projection.lastSeq;
396
+ }
397
+ return cursor;
398
+ }
399
+ private async dispatch(connection:HostConnection,method:string,params:unknown):Promise<unknown> {
400
+ if(!isHxMethod(method))throw new HostError("METHOD_NOT_FOUND");
401
+ try{validateHxRequest(method,params);}catch{throw new HostError("INVALID_PARAMS");}
402
+ this.principal(connection);
403
+ const p=params as Values;
404
+ if(method==="hx.initialize") {
405
+ if(!(p.protocolVersions as number[]).includes(1))throw new HostError("PROTOCOL_VERSION_UNSUPPORTED");
406
+ this.initialized.add(connection.id);
407
+ return {protocolVersion:1,features:["durable-events","operations","private-interactions","catalog-snapshots-v1"],limits:{maxEventPage:1000}};
408
+ }
409
+ if(!this.initialized.has(connection.id))throw new HostError("NOT_INITIALIZED");
410
+ const result=writes.has(method)?await this.write(connection,method,p):await this.read(connection,method,p);
411
+ if(this.storageClosed&&!writes.has(method))throw new HostError("HOST_CLOSED");
412
+ validateHxResult(method,result);return result;
413
+ }
414
+ private async read(connection:HostConnection,method:HxMethod,p:Values):Promise<unknown> {
415
+ if(method==="hx.events.unsubscribe") {
416
+ const id=str(p,"subscriptionId"),sub=this.subscriptions.get(id);
417
+ if(sub&&sub.connection.id!==connection.id)throw new HostError("PROJECT_FORBIDDEN");
418
+ if(sub){sub.active=false;this.subscriptions.delete(id);}return {removed:!!sub};
419
+ }
420
+ if(method==="hx.operation.get") {
421
+ const principal=this.principal(connection);
422
+ const found=typeof p.operationId==="string"?this.store.operation(p.operationId):this.store.lookup(principal.userId,str(p,"method"),str(p,"target"),str(p,"idempotencyKey"));
423
+ if(!found)throw new HostError("OPERATION_NOT_FOUND");
424
+ if(found.row.principal_id!==principal.userId&&!principal.isAdmin&&!principal.service)throw new HostError("PROJECT_FORBIDDEN");
425
+ const projectId=found.row.method==="hx.session.create"?found.row.target:found.row.session_id?this.store.session(found.row.session_id).projectId:found.row.target;
426
+ await this.access(connection,projectId,"viewer");return found.value;
427
+ }
428
+ if(method==="hx.catalog.get"||method==="hx.catalog.refresh"){
429
+ const projectId=str(p,"projectId"),principal=await this.access(connection,projectId,method==="hx.catalog.refresh"?"maintainer":"viewer");
430
+ let scope=this.snapshotScopes.get(connection.id);if(!scope){scope={connection,projects:new Set()};this.snapshotScopes.set(connection.id,scope);}scope.connection=connection;scope.projects.add(projectId);
431
+ if(method==="hx.catalog.refresh"){
432
+ const runtimeConfigId=str(p,"runtimeConfigId"),key=JSON.stringify([principal.userId,runtimeConfigId]),last=this.manualRefreshes.get(key);
433
+ const existing=this.catalog.coalescedRefresh(runtimeConfigId);if(existing)return existing;
434
+ if(last!==undefined&&Date.now()-last<5_000)throw new HostError("CATALOG_REFRESH_RATE_LIMITED","CATALOG_REFRESH_RATE_LIMITED",true);
435
+ for(const [id,at] of this.manualRefreshes)if(Date.now()-at>=5_000)this.manualRefreshes.delete(id);
436
+ this.manualRefreshes.set(key,Date.now());return this.catalog.schedule(runtimeConfigId,"manual");
437
+ }
438
+ this.refreshCatalogAuth();
439
+ const requested=optionalStr(p,"runtimeConfigId"),rows=this.catalogSnapshot().filter(r=>!requested||r.runtimeConfigId===requested);
440
+ if(requested&&!rows.length)throw new HostError("HARNESS_UNAVAILABLE");
441
+ return {epoch:this.catalogEpoch,revision:this.catalogRevision,runtimes:rows.map(row=>({...row,readiness:row.reason==="HARNESS_PREPARING"?"preparing":row.available?"ready":"unavailable",...this.catalog.view(row.runtimeConfigId,!!requested)}))};
442
+ }
443
+ if(method.startsWith("hx.harness.")||method==="hx.session.list"||method==="hx.usage.get") {
444
+ const projectId=str(p,"projectId");await this.access(connection,projectId,"viewer");
445
+ if(method==="hx.usage.get"){
446
+ const rows=this.store.sessions(projectId).filter(row=>(p.includeArchived===true||!row.archived)&&(!p.agentId||row.agentId===p.agentId)).map(row=>({sessionId:row.id,...(row.agentId?{agentId:row.agentId}:{}),usage:this.store.usage(row.id)}));
447
+ const sum=(key:"input"|"output"|"total")=>rows.length&&rows.every(row=>typeof row.usage?.[key]==="number")?rows.reduce((n,row)=>n+row.usage![key]!,0):null;
448
+ return {sessions:rows,totals:{input:sum("input"),output:sum("output"),total:sum("total")}};
449
+ }
450
+ if(method==="hx.session.list")return this.readSessionPage(p as HxRequestMap['hx.session.list']);
451
+ if(method==="hx.harness.list"){
452
+ let scope=this.catalogScopes.get(connection.id);if(!scope){scope={connection,projects:new Set()};this.catalogScopes.set(connection.id,scope);}scope.connection=connection;scope.projects.add(projectId);
453
+ this.refreshCatalogAuth();
454
+ return {harnesses:this.catalogSnapshot()};
455
+ }
456
+ await this.prepareRuntime(str(p,"runtimeConfigId"));
457
+ const descriptor=this.runtimes.find(r=>r.id===p.runtimeConfigId);
458
+ if(!descriptor||descriptor.available===false)throw new HostError("HARNESS_UNAVAILABLE");
459
+ return this.modelCatalog(descriptor.id);
460
+ }
461
+ const minimum=method==="hx.interaction.private.get"||method==="hx.session.reconcile"?"maintainer":"viewer";
462
+ const record=await this.authorizedSession(connection,p,minimum);
463
+ switch(method) {
464
+ case "hx.session.get":return this.publicSession(record.id);
465
+ case "hx.subagents.list":{
466
+ await this.discoverSubagents(record);
467
+ await this.authorizedSession(connection,p,'viewer');
468
+ return {subagents:this.publicSession(record.id).subagents};
469
+ }
470
+ case "hx.subagents.history":{
471
+ const inline=record.inlineSubagents?.find(child=>child.summary.sessionId===p.childSessionId&&child.summary.parentSessionId===record.id);
472
+ if(inline){
473
+ const projection=this.options.projection?.create();
474
+ if(!projection)throw new HostError("CAPABILITY_UNSUPPORTED");
475
+ const snapshot=await this.projectionSnapshotRequest(record);
476
+ if(snapshot.checkpoint)projection.restore(snapshot.checkpoint);
477
+ else this.applyEventRange(projection,record.id,0,this.store.session(record.id).latestSeq);
478
+ const history=inlineSubagentHistory(projection.snapshot(),inline,optionalStr(p,'cursor'),typeof p.limit==='number'?p.limit:50);
479
+ await this.authorizedSession(connection,p,'viewer');
480
+ return {subagent:{...inline.summary,canOpen:true},history:this.redactor(record.id).history(history)};
481
+ }
482
+ const child=record.nativeSubagents?.find(child=>child.summary.sessionId===p.childSessionId&&child.summary.parentSessionId===record.id);
483
+ if(!child)throw new HostError('SUBAGENT_UNAVAILABLE');
484
+ const runtime=this.runtimes.find(runtime=>runtime.id===child.runtimeConfigId&&runtime.available!==false);
485
+ if(!runtime?.readSubagentHistory)throw new HostError('CAPABILITY_UNSUPPORTED');
486
+ const history=await runtime.readSubagentHistory({parentNativeRef:child.parentNativeRef,nativeRef:child.nativeRef,cwd:record.cwd,...(typeof p.cursor==='string'?{cursor:p.cursor}:{}),...(typeof p.limit==='number'?{limit:p.limit}:{})}).catch(cause=>{throw historyReadError(cause);});
487
+ // Access may have been revoked while the native reader was in flight.
488
+ await this.authorizedSession(connection,p,'viewer');
489
+ assertResult('history/read',history);
490
+ const safe=this.redactor(record.id).history(history);
491
+ const prepared={...safe,source:undefined,items:await Promise.all(safe.items.map(async entry=>({...entry,item:await this.prepareItem(record.id,entry.item,undefined,false)})))};
492
+ return {subagent:{...child.summary,canOpen:true},history:prepared};
493
+ }
494
+ case "hx.queue.get":return this.queueSnapshot(record.id);
495
+ case "hx.transcript.read":{const own=this.store.session(record.id).latestSeq,all=this.transcript(record.id);return {inherited:all.filter(event=>event.sessionId!==record.id||event.hostSeq>own)};}
496
+ case "hx.workspace.get":return record.workspace??{kind:"project"};
497
+ case "hx.events.read":return this.store.events(record.id,p.afterSeq as number|undefined,p.throughSeq as number|undefined,p.limit as number|undefined);
498
+ case "hx.projection.snapshot":return this.projectionSnapshotRequest(record);
499
+ case "hx.events.subscribe": {
500
+ const after=p.afterSeq as number,cutoverSeq=this.store.session(record.id).latestSeq;
501
+ if(after>cutoverSeq)throw new HostError("CURSOR_INVALID");
502
+ const id=randomUUID();this.subscriptions.set(id,{id,sessionId:record.id,connection,lastSeq:cutoverSeq,pending:0,bytes:0,tail:Promise.resolve(),active:true});
503
+ return {subscriptionId:id,cutoverSeq,earliestSeq:1};
504
+ }
505
+ case "hx.interaction.list":return {interactions:this.store.interactions(record.id).filter(i=>p.state===undefined||i.state===p.state)};
506
+ case "hx.interaction.private.get": {
507
+ const item=this.store.interaction(record.id,str(p,"interactionId"));
508
+ const liveInteraction=this.live.get(record.id);
509
+ const privateData=this.privateInteractions.get(`${record.id}:${item.interactionId}`)??clientInteractionCapture(liveInteraction!.client)?.requests.get(item.interactionId)?.privatePayload;
510
+ if(item.state!=="pending"||!privateData)throw new HostError("INTERACTION_EXPIRED");return privateData;
511
+ }
512
+ case "hx.history.read": {
513
+ const live=this.requireLive(record.id);
514
+ const history=await live.session.request("history/read",{requestId:randomUUID(),sessionId:record.id,...(typeof p.cursor==="string"?{cursor:p.cursor}:{}),...(typeof p.limit==="number"?{limit:p.limit}:{}),...(typeof p.snapshotToken==="string"?{snapshotToken:p.snapshotToken}:{})}).catch((cause:unknown)=>{throw historyReadError(cause);});
515
+ if(this.storageClosed)throw new HostError("HOST_CLOSED");assertResult("history/read",history);
516
+ const prepared={...history,items:await Promise.all(history.items.map(async entry=>{
517
+ const canonical=live.nativeTurnToCanonical.get(entry.turnId);
518
+ const turnId=canonical??entry.turnId;
519
+ // Claude history reports the prompt UUID. The live turn map links its execution ID to the Host turn.
520
+ const nativeTurnId=record.adapterId==='claude'&&canonical?entry.turnId:entry.nativeTurnId;
521
+ return {...entry,turnId,...(nativeTurnId?{nativeTurnId}:{}),item:await this.prepareItem(record.id,entry.item,turnId,'history')};
522
+ }))};
523
+ this.store.indexHistory(record.id,prepared);return this.redactor(record.id).history(prepared);
524
+ }
525
+ case "hx.session.reconcile":return this.reconcile(record);
526
+ default:throw new HostError("METHOD_NOT_FOUND");
527
+ }
528
+ }
529
+ private async write(connection:HostConnection,method:HxMethod,p:Values):Promise<OperationResult> {
530
+ const create=method==="hx.session.create";
531
+ const record=create?undefined:await this.authorizedSession(connection,p,["hx.session.archive","hx.session.restore"].includes(method)?"member":"maintainer");
532
+ if(record?.managed&&!p._trusted&&!["hx.interaction.respond","hx.interaction.cancel"].includes(method))throw new HostError("MANAGED_SESSION_IMMUTABLE");
533
+ const projectId=record?.projectId??str(p,"projectId");
534
+ const principal=await this.access(connection,projectId,create?"maintainer":["hx.session.archive","hx.session.restore"].includes(method)?"member":"maintainer");
535
+ const target=record?.id??projectId,key=str(p,"idempotencyKey"),digest=this.store.digest(p);
536
+ const reservation=await this.serial(target,async()=>{
537
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
538
+ const old=this.store.lookup(principal.userId,method,target,key);
539
+ if(old){if(old.row.request_digest!==digest)throw new HostError("IDEMPOTENCY_CONFLICT");return {existing:old.value};}
540
+ const current=record?this.store.session(record.id):undefined;
541
+ if(current&&revisionRequired.has(method)&&p.expectedRevision!==current.revision)throw new HostError("REVISION_CONFLICT");
542
+ if(current&&method.startsWith("hx.queue.")&&p.expectedQueueRevision!==this.store.queue(current.id).revision)throw new HostError("QUEUE_REVISION_CONFLICT");
543
+ if(current&&method.startsWith("hx.queue.")&&this.bindingBusy.has(current.id))throw new HostError("SESSION_BUSY");
544
+ if(current&&["hx.session.harness.set","hx.workspace.integrate","hx.workspace.discard"].includes(method))this.assertProductIdle(current);
545
+ if(current?.permissionDowngrade&&!p._trusted&&!["hx.turn.interrupt","hx.interaction.respond","hx.interaction.cancel","hx.session.close","hx.queue.clear","hx.queue.remove","hx.queue.pause"].includes(method)&&!(current.permissionDowngrade.state==="failed"&&method==="hx.session.harness.set"))throw new HostError("PERMISSION_DOWNGRADE_PENDING");
546
+ if(current?.archived&&method!=="hx.session.restore")throw new HostError("SESSION_ARCHIVED");
547
+ const queueControl=!!current&&["hx.queue.run","hx.queue.steer"].includes(method);
548
+ if(queueControl&&this.controlBusy.has(target))throw new HostError("SESSION_BUSY");
549
+ const livePermissionChange=method==="hx.session.config.set"&&!!p.patch&&typeof p.patch==="object"&&!Array.isArray(p.patch)&&Object.keys(p.patch as Values).length===1&&typeof (p.patch as Values).permissionMode==="string";
550
+ const exclusive=!!current&&(metadataWrites.has(method)||["hx.session.fork","hx.turn.start","hx.compact.start","hx.review.start"].includes(method));
551
+ if(exclusive&&(this.controlBusy.has(target)||!livePermissionChange&&(current!.activeTurnId||current!.status==="running"||this.store.interactions(current!.id).some(i=>i.state!=="resolved"))))throw new HostError("SESSION_BUSY");
552
+ if(method==="hx.interaction.respond"||method==="hx.interaction.cancel") {
553
+ const item=this.store.interaction(current!.id,str(p,"interactionId"));
554
+ if(item.state!=="pending")throw new HostError(item.resolution?.reason==="HOST_RESTARTED"?"INTERACTION_EXPIRED":"INTERACTION_ALREADY_RESOLVED");
555
+ if(p.expectedInteractionRevision!==item.revision)throw new HostError("REVISION_CONFLICT");
556
+ if(method==="hx.interaction.respond"){try{assertInteractionResponse(item.request,p.response);}catch{throw new HostError("INVALID_PARAMS");}this.redactor(current!.id).rememberResponse(item.request,p.response as InteractionResponse);}
557
+ }
558
+ if(current&&method==="hx.turn.start"&&!p._trustedQueue&&this.store.queue(current.id).items.length)throw new HostError("SESSION_BUSY");
559
+ if(current?.status==="recoveryRequired"&&method!=="hx.turn.interrupt")throw new HostError("RECOVERY_REQUIRED");
560
+ const sessionId=method==="hx.session.fork"?randomUUID():current?.id??randomUUID();const turnId=["hx.turn.start","hx.review.start","hx.queue.enqueue","hx.queue.retry"].includes(method)?optionalStr(p,"_turnId")??randomUUID():method==="hx.turn.steer"?str(p,"expectedTurnId"):optionalStr(p,"turnId");
561
+ const initial=this.store.beginOperation(randomUUID(),principal.userId,method,target,key,digest,sessionId,turnId);
562
+ if(exclusive||queueControl)this.controlBusy.add(target);
563
+ if(["hx.session.harness.set","hx.workspace.integrate","hx.workspace.discard"].includes(method))this.bindingBusy.add(target);
564
+ if(current&&["hx.turn.start","hx.review.start"].includes(method)){this.store.clearEvidence(current.id,current.bindingGeneration??1,"session");current.activeTurnId=turnId;current.status="running";this.store.saveSession(current);}
565
+ if(current&&["hx.interaction.respond","hx.interaction.cancel"].includes(method)){const item=this.store.interaction(current.id,str(p,"interactionId"));this.store.saveInteraction(current.id,{...item,state:"responding"});}
566
+ return {initial,current,sessionId,turnId,exclusive,queueControl};
567
+ });
568
+ if("existing"in reservation)return reservation.existing!;
569
+ const {initial,current,sessionId,turnId,exclusive,queueControl}=reservation;
570
+ // Native calls may require an interaction before returning their start acknowledgement.
571
+ // Never hold the command reservation lock while waiting for a backend response.
572
+ try {
573
+ this.store.phase(initial.operationId,"dispatching");
574
+ const result=await this.perform(method,p,current,sessionId,projectId,principal,turnId,initial.operationId);
575
+ if(this.storageClosed)return this.closedResults.get(initial.operationId)??this.unknownResult(initial);
576
+ if(method==="hx.compact.start"&&result&&typeof result==="object"&&!Array.isArray(result)&&result.status==="accepted"){
577
+ const latest=this.store.session(sessionId);latest.status="running";this.store.saveSession(latest);
578
+ }
579
+ if(current&&metadataWrites.has(method)) {
580
+ const latest=this.store.session(current.id);latest.revision++;this.store.saveSession(latest);
581
+ }
582
+ const resultSessionId=method==="hx.session.fork" && typeof result==="object" && result!==null && !Array.isArray(result) && typeof result.id==="string"?result.id:sessionId;
583
+ const revision=this.store.session(resultSessionId).revision;
584
+ const completed=this.store.finishOperation({...initial,sessionId:resultSessionId,state:"completed",outcomeUnknown:false,revision,result:publicValue(this.projectResult(method,resultSessionId,result))});
585
+ if (["hx.session.config.set","hx.session.harness.set"].includes(method)) {
586
+ try { await this.options.onConfigurationCommitted?.({principal,session:this.publicSession(resultSessionId),changed:method==="hx.session.config.set"?Object.keys((p.patch as Values)??{}):[]}); }
587
+ catch { try { this.options.onError?.("PREFERENCE_SYNC_FAILED"); } catch {} }
588
+ }
589
+ this.publishTurnOperation(method,completed);return completed;
590
+ }catch(cause){
591
+ if(this.storageClosed)return this.closedResults.get(initial.operationId)??this.unknownResult(initial);
592
+ const error=hostError(cause);
593
+ if(error.details)error.details=this.redactor(sessionId).json(error.details) as JsonObject;
594
+ if(this.hasSession(sessionId)){
595
+ const s=this.store.session(sessionId);
596
+ if(error.outcomeUnknown)s.status="recoveryRequired";
597
+ else if(turnId&&s.activeTurnId===turnId&&["hx.turn.start","hx.review.start"].includes(method)){delete s.activeTurnId;s.status="ready";}
598
+ this.store.saveSession(s);
599
+ if(!error.outcomeUnknown&&["hx.interaction.respond","hx.interaction.cancel"].includes(method)){const item=this.store.interaction(sessionId,str(p,"interactionId"));if(item.state==="responding")this.store.saveInteraction(sessionId,{...item,state:"pending"});}
600
+ }
601
+ const failed=this.store.finishOperation({...initial,state:error.outcomeUnknown?"unknown":"failed",outcomeUnknown:error.outcomeUnknown,error});
602
+ this.publishTurnOperation(method,failed);return failed;
603
+ }finally{if(exclusive||queueControl)this.controlBusy.delete(target);this.bindingBusy.delete(target);this.scheduleQueue(sessionId);}
604
+ }
605
+ private publishTurnOperation(method:HxMethod,result:OperationResult):void {
606
+ if(!["hx.turn.start","hx.turn.steer","hx.session.revert"].includes(method)||!result.sessionId||!this.hasSession(result.sessionId))return;
607
+ const event=this.store.append(result.sessionId,{type:"host/operation",payload:{method,operationId:result.operationId,state:result.state,outcomeUnknown:result.outcomeUnknown,...(method==="hx.session.revert"&&result.result!==undefined?{result:result.result}:{}),...(result.turnId?{turnId:result.turnId}:{}),...(result.error?{error:result.error as unknown as JsonValue}:{})}},undefined,{turnId:result.turnId});
608
+ if(event)this.publish(event);
609
+ }
610
+ private hasSession(id:string):boolean {try{this.store.session(id);return true;}catch{return false;}}
611
+ private unknownResult(initial:OperationResult):OperationResult{return {...initial,state:"unknown",outcomeUnknown:true,error:{code:"RESULT_UNKNOWN",message:"RESULT_UNKNOWN",retryable:false,outcomeUnknown:true}};}
612
+ private requireLive(id:string):LiveSession {const live=this.live.get(id);if(!live)throw new HostError("SESSION_CLOSED");return live;}
613
+ private async perform(method:HxMethod,p:Values,current:SessionRecord|undefined,id:string,projectId:string,principal:Principal,turnId?:string,operationId?:string):Promise<JsonValue> {
614
+ const ownerId=principal.userId;
615
+ const requestId=randomUUID(),common={requestId,sessionId:id};
616
+ if(method==="hx.session.create") {
617
+ await this.prepareRuntime(str(p,"runtimeConfigId"));
618
+ const descriptor=this.runtimes.find(r=>r.id===p.runtimeConfigId);if(!descriptor||descriptor.available===false)throw new HostError("HARNESS_UNAVAILABLE");
619
+ const root=await this.options.projectRoot(projectId);if(!root)throw new HostError("PROJECT_NOT_FOUND");
620
+ if(descriptor.getAuthStatus){try{descriptor.authStatus=await descriptor.getAuthStatus();}catch(cause){const failure=hostError(cause);throw new HostError(failure.code,failure.message,failure.retryable,false,failure.details);}if(descriptor.authStatus==="required")throw new HostError("AUTH_REQUIRED");}
621
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
622
+ const context=p._trusted&&p._fixedContext?p._fixedContext as {instructions:string;mcpServers:McpServer[]}:await this.options.resolveSessionContext?.({principal,projectId,agentId:optionalStr(p,"agentId"),adapterId:descriptor.adapterId,runtimeConfigId:descriptor.id,providerId:descriptor.providerId});
623
+ if(p.agentId&&!p._fixedContext&&!this.options.resolveSessionContext)throw new HostError("AGENT_CONTEXT_UNAVAILABLE");
624
+ await this.options.validateConfig?.({principal,sessionId:id,projectId,runtimeConfigId:descriptor.id,adapterId:descriptor.adapterId,config:structuredClone((p.config as JsonObject|undefined)??{})});
625
+ const instructions=[context?.instructions,optionalStr(p,"instructions")].filter(Boolean).join("\n\n");
626
+ let allocation:WorkspaceAllocation|undefined;
627
+ if(this.options.workspaces&&!p._directory)allocation=await this.options.workspaces.allocate({principal,projectId,sessionId:id,request:p.workspace as WorkspaceRequest|undefined});
628
+ else if(p.workspace&&((p.workspace as Values).kind!=="project"))throw new HostError("WORKSPACE_UNAVAILABLE");
629
+ let cwd:string;try{
630
+ const directory=p._trusted?p._directory as {cwd:string;allowedRoots:string[]}|undefined:undefined;
631
+ cwd=realpathSync(directory?.cwd??allocation?.binding.cwd??root);
632
+ if(directory&&!directory.allowedRoots.some(root=>{const relative=path.relative(realpathSync(root),cwd);return !path.isAbsolute(relative)&&relative!==".."&&!relative.startsWith(`..${path.sep}`);}))throw new HostError("WORKING_DIRECTORY_FORBIDDEN");
633
+ }catch(cause){if(allocation?.created)await allocation.rollback().catch(()=>{});throw cause;}
634
+ const binding={sessionId:id,adapterId:descriptor.adapterId,runtimeConfigId:descriptor.id};
635
+ const record:SessionRecord={id,projectId,ownerId,adapterId:binding.adapterId,runtimeConfigId:binding.runtimeConfigId,cwd,binding,config:(p.config as JsonObject|undefined)??{},revision:1,latestSeq:0,status:"opening",archived:false,bindingGeneration:1,...(p._trusted&&p._managed?{managed:p._managed as {scopeId:string;executionKey:string}}:{}),...(p._admissionRef?{admissionRef:String(p._admissionRef)}:{}),...(allocation?{workspaceBinding:allocation.binding,workspace:this.workspacePublic(allocation.binding)}:{workspace:{kind:"project"}}),createdAt:Date.now(),updatedAt:Date.now(),...(typeof p.agentId==="string"?{agentId:p.agentId}:{}),...(context?.mcpServers?{mcpServers:context.mcpServers}:{}),...(typeof p.model==="string"?{model:p.model}:{}),...(instructions?{instructions}:{})};
636
+ record.executionMode=p.executionMode==='swarm'?'swarm':'normal';
637
+ this.store.saveSession(record);try{await this.open(record,"new");}catch(cause){if(allocation?.created)await allocation.rollback().catch(()=>{});throw cause;}return this.publicSession(id) as unknown as JsonValue;
638
+ }
639
+ if(!current)throw new HostError("SESSION_NOT_FOUND");
640
+ if(["hx.review.start","hx.goal.set","hx.compact.start"].includes(method))await this.validateConfig(principal,current,current.config);
641
+ if(method.startsWith("hx.queue."))return await this.performQueue(method,p,current,principal,turnId,operationId!) as unknown as JsonValue;
642
+ switch(method) {
643
+ case "hx.session.harness.set":return await this.switchHarness(current,p,principal) as unknown as JsonValue;
644
+ case "hx.workspace.integrate":case "hx.workspace.discard":return await this.mutateWorkspace(current,method,p,principal) as unknown as JsonValue;
645
+ case "hx.session.open":await this.validateConfig(principal,current,current.config);await this.open(current,"resume");return this.publicSession(id) as unknown as JsonValue;
646
+ case "hx.session.close": {
647
+ const live=this.live.get(id);if(live){await live.session.close();await live.reader.return?.();await this.disposeLive(live);await live.pump;}
648
+ const next=this.store.session(id);next.status="closed";this.store.saveSession(next);return {closed:true};
649
+ }
650
+ case "hx.session.archive":case "hx.session.restore": {
651
+ const next=this.store.session(id);next.archived=method==="hx.session.archive";this.store.saveSession(next);return this.publicSession(id) as unknown as JsonValue;
652
+ }
653
+ case "hx.session.fork": {
654
+ const nextId=id,binding={...current.binding,sessionId:nextId};
655
+ const next={...current,id:nextId,binding,ownerId,latestSeq:0,revision:1,parent:{sessionId:current.id,boundary:p.boundary as Boundary,bindingGeneration:current.bindingGeneration??1},createdAt:Date.now(),updatedAt:Date.now(),status:"opening" as const};delete next.activeTurnId;delete next.nativeTitle;delete next.nativeSubagents;delete next.inlineSubagents;next.title=next.fallbackTitle;
656
+ // The adapter-side boundary carries the native turn id; next.parent keeps the canonical one for the product.
657
+ const resolvedBoundary=this.store.boundary(current.id,p.boundary as Boundary);
658
+ const boundary={...resolvedBoundary,turnId:resolvedBoundary.nativeTurnId??resolvedBoundary.turnId};
659
+ let allocation:WorkspaceAllocation|undefined;
660
+ if(this.options.workspaces){allocation=await this.options.workspaces.allocate({principal,projectId,sessionId:nextId,request:p.workspace as WorkspaceRequest|undefined});next.cwd=realpathSync(allocation.binding.cwd);next.workspaceBinding=allocation.binding;next.workspace=this.workspacePublic(allocation.binding);}
661
+ else if(p.workspace&&(p.workspace as Values).kind!=="project")throw new HostError("WORKSPACE_UNAVAILABLE");
662
+ this.store.saveSession(next);this.store.inheritPrivate(current.id,nextId);try{await this.open(next,"fork",{sourceSessionId:current.id,nativeRef:current.binding.nativeRef,boundary});}catch(cause){if(allocation?.created)await allocation.rollback().catch(()=>{});throw cause;}return this.publicSession(nextId) as unknown as JsonValue;
663
+ }
664
+ }
665
+ const live=this.requireLive(id);
666
+ let input=p.input as InputBlock[];
667
+ if(method==="hx.turn.start"||method==="hx.turn.steer") {
668
+ await this.validateConfig(principal,current,current.config,p.overrides as JsonObject|undefined);
669
+ const references=(p.references as HxContextReference[]|undefined)??[];
670
+ if(references.length&&!this.options.resolveInput)throw new HostError("CONTEXT_REFERENCE_UNAVAILABLE");
671
+ if(p._resolvedInput)input=p._resolvedInput as InputBlock[];else if(this.options.resolveInput)input=await this.options.resolveInput({sessionId:id,projectId,cwd:current.cwd,input,references});
672
+ const canonicalTurnId=turnId??str(p,"expectedTurnId");
673
+ const safeInput=this.redactor(id).json(p.input as JsonValue) as unknown as InputBlock[];
674
+ const safeReferences=this.redactor(id).json(references as unknown as JsonValue);
675
+ const next=this.store.session(id);
676
+ if(!next.fallbackTitle){const text=safeInput.filter(b=>b.type==="text").map(b=>b.text).join(" ").trim();if(text){next.fallbackTitle=Array.from(text).slice(0,100).join("");next.title=next.nativeTitle?.trim()||next.fallbackTitle;this.store.saveSession(next);}}
677
+ const event=this.store.append(id,{type:"host/turnInput",payload:{turnId:canonicalTurnId,input:safeInput as unknown as JsonValue,...(references.length?{references:safeReferences}:{}),operationId:operationId!,kind:method==="hx.turn.start"?"start":"steer",state:"dispatching"}},undefined,{turnId:canonicalTurnId});
678
+ if(event)this.publish(event);
679
+ }
680
+ switch(method) {
681
+ case "hx.session.config.set": {
682
+ await this.validateConfig(principal,current,{...current.config,...p.patch as JsonObject});
683
+ const state=await live.session.request("session/config/set",{...common,patch:p.patch as JsonObject});
684
+ if(this.storageClosed)throw new HostError("RESULT_UNKNOWN","RESULT_UNKNOWN",false,true);
685
+ const safe=this.redactor(id).state(state);const next=this.store.session(id);next.config=safe.config;next.model=safe.model;this.store.saveSession(next);return safe as unknown as JsonValue;
686
+ }
687
+ case "hx.session.revert": {
688
+ // The wire boundary must carry the native turn id (native-lifecycle adapters only know native ids); the durable control record keeps the canonical one.
689
+ const resolved=this.store.boundary(id,p.boundary as Boundary);
690
+ const result=await live.session.request("session/revert",{...common,boundary:{...resolved,turnId:resolved.nativeTurnId??resolved.turnId},scope:p.scope as RevertScope});
691
+ if(this.storageClosed)throw new HostError("RESULT_UNKNOWN","RESULT_UNKNOWN",false,true);
692
+ if(result.nativeRef){const next=this.store.session(id);next.binding={...next.binding,nativeRef:result.nativeRef};this.store.saveSession(next);}
693
+ return {appliedScope:result.appliedScope,boundary:p.boundary as Boundary} as unknown as JsonValue;
694
+ }
695
+ case "hx.turn.start":{
696
+ // Hermes has no session-instruction channel. Explicit submissions carry current
697
+ // context; Host operation idempotency covers uncertain/retried submissions.
698
+ if(current.adapterId==="hermes"&&current.instructions)input=[{type:"text",text:`<cowork_context>\n${current.instructions}\n</cowork_context>`},...input];
699
+ await this.turnHook("before",id,turnId!);live.pendingCanonical.push(turnId!);try{await live.session.submit({input,...(p.overrides?{overrides:p.overrides as JsonObject}:{}),...(p.outputSchema!==undefined?{outputSchema:p.outputSchema as JsonObject|boolean}:{})});console.error('[turn-debug] submitted',id,turnId);await this.waitForTurnRow(id,turnId!);console.error('[turn-debug] row registered',id,turnId);return {turnId:turnId!} as unknown as JsonValue;}catch(cause){console.error('[turn-debug] submit failed',id,turnId,cause instanceof Error?cause.message:String(cause));const index=live.pendingCanonical.indexOf(turnId!);if(index>=0)live.pendingCanonical.splice(index,1);throw cause;}}
700
+ case "hx.turn.steer":{const native=this.store.nativeTurn(id,str(p,"expectedTurnId"));return await live.session.request("turn/steer",{...common,expectedTurnId:native??str(p,"expectedTurnId"),input,submissionId:operationId??requestId}) as unknown as JsonValue;}
701
+ case "hx.turn.interrupt":{
702
+ // 适配器在 input.interrupt.targets 下声明中断目标:含 turn 走 turn/interrupt(SDK guard 校验
703
+ // atomicMatch 语义);仅含 session 的 Harness(Claude/ACP)拒绝 turn/interrupt,翻译为
704
+ // session/interrupt 停止当前生成(不传 cancelQueued,排队项由队列端口管理)。
705
+ const targets=live.session.capabilities.input?.interrupt?.targets;
706
+ if(targets?.includes("session")&&!targets.includes("turn"))return await live.session.request("session/interrupt",{...common}) as unknown as JsonValue;
707
+ const native=this.store.nativeTurn(id,str(p,"turnId"));
708
+ return await live.session.request("turn/interrupt",{...common,turnId:native??str(p,"turnId")}) as unknown as JsonValue;
709
+ }
710
+ case "hx.interaction.respond":{const capture=clientInteractionCapture(live.client);const parked=capture?.pending.get(str(p,"interactionId"));if(parked){capture!.pending.delete(str(p,"interactionId"));parked.resolve(p.response as InteractionResponse);return {interactionId:str(p,"interactionId"),outcome:"responded"} as unknown as JsonValue;}return await live.session.request("interaction/respond",{...common,interactionId:str(p,"interactionId"),response:p.response as InteractionResponse}) as unknown as JsonValue;}
711
+ case "hx.interaction.cancel":{const reason=optionalStr(p,"reason");const capture=clientInteractionCapture(live.client);const parked=capture?.pending.get(str(p,"interactionId"));if(parked){capture!.pending.delete(str(p,"interactionId"));parked.reject(new HarnessSdkError("INTERACTION_CANCELLED"));return {interactionId:str(p,"interactionId"),outcome:"cancelled"} as unknown as JsonValue;}return await live.session.request("interaction/cancel",{...common,interactionId:str(p,"interactionId"),...(reason?{reason}:{})}) as unknown as JsonValue;}
712
+ case "hx.goal.set":{ const goal=await live.session.request("goal/set",{...common,goal:p.goal as JsonObject});const next=this.store.session(id);next.goal=goal;this.store.saveSession(next);return goal as unknown as JsonValue;}
713
+ case "hx.goal.clear":{ const goal=await live.session.request("goal/clear",{...common});const next=this.store.session(id);next.goal=goal;this.store.saveSession(next);return goal as unknown as JsonValue;}
714
+ case "hx.compact.start":return await live.session.request("compact/start",{...common}) as unknown as JsonValue;
715
+ case "hx.review.start":{live.pendingCanonical.push(turnId!);try{await live.session.review({target:p.target as JsonObject});await this.waitForTurnRow(id,turnId!);return {turnId:turnId!} as unknown as JsonValue;}catch(cause){const index=live.pendingCanonical.indexOf(turnId!);if(index>=0)live.pendingCanonical.splice(index,1);throw cause;}}
716
+ default:throw new HostError("METHOD_NOT_FOUND");
717
+ }
718
+ }
719
+ private async validateConfig(principal:Principal,record:SessionRecord,config:JsonObject,overrides?:JsonObject):Promise<void> {
720
+ await this.options.validateConfig?.({principal,sessionId:record.id,projectId:record.projectId,runtimeConfigId:record.runtimeConfigId,adapterId:record.adapterId,config:structuredClone(config),...(overrides?{overrides:structuredClone(overrides)}:{})});
721
+ }
722
+ private workspacePublic(binding:import('./workspaces').WorkspaceBinding) {const {cwd,...metadata}=binding;return metadata;}
723
+ private assertProductIdle(record:SessionRecord):void {
724
+ assertWorkspaceMutable({status:record.status,activeTurnId:record.activeTurnId,pendingInteractions:this.store.interactions(record.id).some(item=>item.state!=="resolved"),pendingQueue:this.store.queue(record.id).items.length>0,unknownOperation:this.store.evidence(record.id,record.bindingGeneration??1,"session")?.quiescent!==true&&this.store.incomplete().some(item=>item.row.session_id===record.id&&item.value.outcomeUnknown&&!this.store.operationStopped(record.id,item.value.operationId)),activeGoal:record.goal?.status==="active",managed:!!record.managed,executedTurns:this.store.executedTurns(record.id)});
725
+ }
726
+ private publishQueue(id:string):void {const event=this.store.append(id,{type:"host/queue",payload:{queue:this.queueSnapshot(id) as unknown as JsonValue}});if(event)this.publish(event);}
727
+ private async performQueue(method:HxMethod,p:Values,current:SessionRecord,principal:Principal,turnId:string|undefined,operationId:string):Promise<HxQueueState> {
728
+ const id=current.id,action=method.slice("hx.queue.".length),now=Date.now();
729
+ let input:InputBlock[]|undefined;
730
+ if(action==="enqueue"||action==="update"){
731
+ await this.validateConfig(principal,current,current.config,p.overrides as JsonObject|undefined);
732
+ const references=(p.references as HxContextReference[]|undefined)??[];
733
+ if(references.length&&!this.options.resolveInput)throw new HostError("CONTEXT_REFERENCE_UNAVAILABLE");
734
+ input=this.options.resolveInput?await this.options.resolveInput({sessionId:id,projectId:current.projectId,cwd:current.cwd,input:p.input as InputBlock[],references}):p.input as InputBlock[];
735
+ // A private answer cannot become a durable retry payload. Reject rather than silently changing model input.
736
+ if(JSON.stringify(this.redactor(id).json(input as unknown as JsonValue))!==JSON.stringify(input))throw new HostError("PRIVATE_QUEUE_INPUT");
737
+ }
738
+ if(action==="steer")await this.validateConfig(principal,current,current.config);
739
+ if(action==="run"&&this.store.interactions(id).some(item=>item.state!=="resolved"))throw new HostError("SESSION_BUSY");
740
+ let steering:StoredQueueItem|undefined;
741
+ const changed=this.store.mutateQueue(id,p.expectedQueueRevision as number,state=>{
742
+ if((this.store.session(id).bindingGeneration??1)!==(current.bindingGeneration??1))throw new HostError("BINDING_GENERATION_MISMATCH");
743
+ const item=typeof p.itemId==="string"?state.items.find(item=>item.id===p.itemId):undefined;
744
+ if(["update","remove","run","steer","retry"].includes(action)&&!item)throw new HostError("QUEUE_ITEM_NOT_FOUND");
745
+ if(item&&["dispatching","running","unknown"].includes(item.state))throw new HostError(item.state==="unknown"?"RECOVERY_REQUIRED":"QUEUE_ITEM_BUSY");
746
+ if(action==="enqueue"){
747
+ state.items.push({id:operationId,turnId:turnId!,state:"queued",input:this.redactor(id).json(p.input as JsonValue) as unknown as InputBlock[],...(Array.isArray(p.references)?{references:p.references as HxContextReference[]}:{}),executionInput:input!,configSnapshot:structuredClone(current.config),...(current.model?{modelSnapshot:current.model}:{}),runtimeConfigId:current.runtimeConfigId,ownerId:principal.userId,bindingGeneration:current.bindingGeneration??1,createdAt:now,updatedAt:now,...(p.overrides?{overrides:p.overrides as JsonObject}:{}),...(p.outputSchema!==undefined?{outputSchema:p.outputSchema as boolean|JsonObject}:{})});
748
+ }else if(action==="update"){
749
+ if(item!.state!=="queued"&&item!.state!=="failed")throw new HostError("QUEUE_ITEM_BUSY");
750
+ Object.assign(item!,{input:p.input,executionInput:input,references:p.references??[],configSnapshot:structuredClone(current.config),modelSnapshot:current.model,updatedAt:now,...(p.overrides?{overrides:p.overrides}:{}),...(p.outputSchema!==undefined?{outputSchema:p.outputSchema}:{})});
751
+ }else if(action==="remove")state.items=state.items.filter(value=>value.id!==item!.id);
752
+ else if(action==="clear"){
753
+ if(state.items.some(value=>value.state==="unknown"))throw new HostError("RECOVERY_REQUIRED");state.items=state.items.filter(value=>value.state==="dispatching"||value.state==="running");state.paused=false;
754
+ }else if(action==="reorder"){
755
+ const ids=p.itemIds as string[],queued=state.items.filter(value=>value.state==="queued"),fixed=state.items.filter(value=>value.state!=="queued");
756
+ if(new Set(ids).size!==ids.length||ids.length!==queued.length||ids.some(itemId=>!queued.some(value=>value.id===itemId)))throw new HostError("QUEUE_ORDER_INVALID");state.items=[...fixed,...ids.map(itemId=>queued.find(value=>value.id===itemId)!)];
757
+ }else if(action==="pause")state.paused=true;
758
+ else if(action==="resume"){if(state.items.some(value=>value.state==="unknown"))throw new HostError("RECOVERY_REQUIRED");state.paused=false;}
759
+ else if(action==="retry"){
760
+ if(item!.state!=="failed")throw new HostError("QUEUE_ITEM_NOT_FAILED");Object.assign(item!,{state:"queued",turnId:turnId!,updatedAt:now});delete item!.error;delete item!.operationId;
761
+ }else if(action==="run"){
762
+ if(item!.state!=="queued")throw new HostError("QUEUE_ITEM_BUSY");state.items=[item!,...state.items.filter(value=>value.id!==item!.id)];state.paused=false;
763
+ }else if(action==="steer"){
764
+ if(item!.state!=="queued")throw new HostError("QUEUE_ITEM_BUSY");item!.state="dispatching";item!.operationId=operationId;item!.updatedAt=now;steering=structuredClone(item!);
765
+ }
766
+ });
767
+ this.publishQueue(id);
768
+ if(action==="run"&&this.store.session(id).activeTurnId){const active=this.store.session(id).activeTurnId!;const native=this.store.nativeTurn(id,active);await this.requireLive(id).session.request("turn/interrupt",{requestId:operationId,sessionId:id,turnId:native??active});}
769
+ if(steering){
770
+ try{
771
+ const native=this.store.nativeTurn(id,str(p,"expectedTurnId"));const result=await this.requireLive(id).session.request("turn/steer",{requestId:operationId,sessionId:id,expectedTurnId:native??str(p,"expectedTurnId"),input:steering.executionInput,submissionId:operationId});
772
+ const event=this.store.append(id,{type:"host/turnInput",payload:{turnId:str(p,"expectedTurnId"),input:steering.input as unknown as JsonValue,...(steering.references?{references:steering.references as unknown as JsonValue}:{}),kind:"steer",state:"completed",operationId}},undefined,{turnId:str(p,"expectedTurnId")});
773
+ if(event)this.publish(event);this.store.mutateQueue(id,undefined,state=>{const item=state.items.find(value=>value.id===steering!.id);if(item)item.state="completed";});
774
+ void result;
775
+ }catch(cause){const error=hostError(cause);this.store.mutateQueue(id,undefined,state=>{const item=state.items.find(value=>value.id===steering!.id);if(item){item.state=error.outcomeUnknown?"unknown":"queued";item.error=error;}if(error.outcomeUnknown)state.paused=true;});this.publishQueue(id);throw cause;}
776
+ this.publishQueue(id);return this.queueSnapshot(id);
777
+ }
778
+ return publicQueue(changed);
779
+ }
780
+ private scheduleQueue(id:string):void {
781
+ if(this.shuttingDown||this.storageClosed)return;if(this.queuePumps.has(id)){this.queueAgain.add(id);return;}
782
+ const pending=Promise.resolve().then(()=>this.drainQueue(id)).catch(cause=>{try{this.options.onError?.(hostError(cause).code);}catch{}}).finally(()=>{if(this.queuePumps.get(id)===pending)this.queuePumps.delete(id);if(this.queueAgain.delete(id))this.scheduleQueue(id);});this.queuePumps.set(id,pending);
783
+ }
784
+ private async drainQueue(id:string):Promise<void> {
785
+ if(this.shuttingDown||!this.hasSession(id)||this.controlBusy.has(id)||this.bindingBusy.has(id))return;
786
+ if(this.store.session(id).permissionDowngrade){await this.applyPermissionDowngrade(id);if(this.store.session(id).permissionDowngrade)return;}
787
+ const queue=this.store.queue(id),record=this.store.session(id);
788
+ if(queue.paused||record.archived||record.managed||record.status==="recoveryRequired"||record.status==="running"||record.activeTurnId||record.goal?.status==="active"||queue.items.some(item=>["dispatching","running","unknown"].includes(item.state))||this.store.interactions(id).some(item=>item.state!=="resolved"))return;
789
+ const item=queue.items.find(item=>item.state==="queued");if(!item)return;
790
+ const connection:HostConnection={id:`queue:${id}`,principal:()=>({userId:item.ownerId,mode:"on"}),send:()=>{}};
791
+ try{await this.access(connection,record.projectId,"maintainer");}catch(cause){this.store.mutateQueue(id,undefined,state=>{state.paused=true;const current=state.items.find(value=>value.id===item.id);if(current){current.state="failed";current.error=hostError(cause);}});this.publishQueue(id);return;}
792
+ try{
793
+ await this.validateConfig(this.principal(connection),record,item.configSnapshot,item.overrides);
794
+ if((record.bindingGeneration??1)!==item.bindingGeneration||record.runtimeConfigId!==item.runtimeConfigId)throw new HostError("BINDING_GENERATION_MISMATCH");
795
+ if(!this.live.has(id))await this.open(record,record.binding.nativeRef?"resume":"new");
796
+ }catch(cause){
797
+ const error=hostError(cause);this.store.mutateQueue(id,undefined,state=>{const current=state.items.find(value=>value.id===item.id);if(current){current.state=error.outcomeUnknown?"unknown":"failed";current.error=error;current.updatedAt=Date.now();}state.paused=true;});
798
+ if(error.outcomeUnknown){const next=this.store.session(id);next.status="recoveryRequired";this.store.saveSession(next);}this.publishQueue(id);return;
799
+ }
800
+ if(this.shuttingDown||this.controlBusy.has(id))return;
801
+ this.store.mutateQueue(id,undefined,state=>{const current=state.items.find(value=>value.id===item.id);if(!current||current.state!=="queued")throw new HostError("QUEUE_ITEM_BUSY");current.state="dispatching";current.updatedAt=Date.now();});this.publishQueue(id);
802
+ let result:OperationResult;
803
+ try{
804
+ const live=this.requireLive(id).session;
805
+ const modelChanged=this.store.session(id).model!==item.modelSnapshot,capturedConfig={...item.configSnapshot,...(modelChanged&&item.modelSnapshot?{model:item.modelSnapshot}:{})},currentConfig=this.store.session(id).config;
806
+ if(Object.keys(currentConfig).some(key=>!(key in capturedConfig)))throw new HostError("QUEUE_CONFIG_CHANGED","The captured configuration cannot be restored by a patch; explicitly edit the queued item to capture the current settings");
807
+ if(this.store.digest(currentConfig)!==this.store.digest(capturedConfig)||modelChanged){
808
+ const state=await live.request("session/config/set",{requestId:randomUUID(),sessionId:id,patch:capturedConfig});
809
+ const safe=this.redactor(id).state(state),next=this.store.session(id);next.config=safe.config;next.model=safe.model;this.store.saveSession(next);
810
+ if(this.store.digest(safe.config)!==this.store.digest(capturedConfig))throw new HostError("QUEUE_CONFIG_CHANGED","The runtime did not restore the captured configuration");
811
+ }
812
+ result=await this.write(connection,"hx.turn.start",{sessionId:id,projectId:record.projectId,idempotencyKey:`queue:${item.id}:${item.turnId}`,expectedRevision:this.store.session(id).revision,input:item.input,references:item.references,_resolvedInput:item.executionInput,_turnId:item.turnId,_trustedQueue:true,...(item.overrides?{overrides:item.overrides}:{}),...(item.outputSchema!==undefined?{outputSchema:item.outputSchema}:{})});
813
+ }catch(cause){const error=hostError(cause);result={operationId:"",sessionId:id,turnId:item.turnId,state:error.outcomeUnknown?"unknown":"failed",outcomeUnknown:error.outcomeUnknown,error};}
814
+ if(this.storageClosed)return;
815
+ this.store.mutateQueue(id,undefined,state=>{const current=state.items.find(value=>value.id===item.id);if(!current||current.state!=="dispatching")return;current.state=result.outcomeUnknown||result.state==="unknown"?"unknown":result.state==="failed"?"failed":"running";current.updatedAt=Date.now();if(result.operationId)current.operationId=result.operationId;if(result.error)current.error=result.error;if(current.state==="unknown"||current.state==="failed")state.paused=true;});this.publishQueue(id);
816
+ if(!this.store.queue(id).items.some(value=>["dispatching","running","unknown"].includes(value.state))&&!this.store.queue(id).paused)queueMicrotask(()=>this.scheduleQueue(id));
817
+ }
818
+ private completeQueuedTurn(id:string,turnId:string,status:string,error?:import('@anureo/protocol').HarnessError):void {
819
+ if(!this.store.queue(id).items.some(item=>item.turnId===turnId))return;
820
+ this.store.mutateQueue(id,undefined,state=>{const item=state.items.find(value=>value.turnId===turnId);if(item){item.state=error?.outcomeUnknown?"unknown":status==="failed"?"failed":"completed";item.updatedAt=Date.now();if(error)item.error=error;if(item.state==="failed"||item.state==="unknown")state.paused=true;}});this.publishQueue(id);
821
+ }
822
+ private async closeLive(id:string):Promise<void> {
823
+ const live=this.live.get(id);if(!live)return;
824
+ try{await live.session.close();await live.reader.return?.();await this.disposeLive(live);await live.pump;}catch{const current=this.store.session(id);current.status="recoveryRequired";this.store.saveSession(current);throw new HostError("RESULT_UNKNOWN","Native runtime shutdown could not be verified",false,true);}
825
+ }
826
+ private async switchHarness(record:SessionRecord,p:Values,principal:Principal):Promise<unknown> {
827
+ await this.prepareRuntime(str(p,"runtimeConfigId"));
828
+ const descriptor=this.runtimes.find(item=>item.id===p.runtimeConfigId&&item.available!==false);if(!descriptor)throw new HostError("HARNESS_UNAVAILABLE");
829
+ this.assertProductIdle(this.store.session(record.id));
830
+ await this.options.validateConfig?.({principal,sessionId:record.id,projectId:record.projectId,runtimeConfigId:descriptor.id,adapterId:descriptor.adapterId,config:{}});
831
+ if(descriptor.getAuthStatus){try{descriptor.authStatus=await descriptor.getAuthStatus();}catch(cause){const error=hostError(cause);throw new HostError(error.code,error.message,error.retryable,false,error.details);}if(descriptor.authStatus==="required")throw new HostError("AUTH_REQUIRED");}
832
+ const context=await this.options.resolveSessionContext?.({principal,projectId:record.projectId,agentId:record.agentId,adapterId:descriptor.adapterId,runtimeConfigId:descriptor.id,providerId:descriptor.providerId});
833
+ const preferred=await this.options.resolveHarnessConfiguration?.({principal,session:this.publicSession(record.id),runtimeConfigId:descriptor.id});
834
+ if(preferred)await this.options.validateConfig?.({principal,sessionId:record.id,projectId:record.projectId,runtimeConfigId:descriptor.id,adapterId:descriptor.adapterId,config:preferred.config});
835
+ const next=structuredClone(this.store.session(record.id));next.adapterId=descriptor.adapterId;next.runtimeConfigId=descriptor.id;next.bindingGeneration=(next.bindingGeneration??1)+1;next.binding={sessionId:next.id,adapterId:descriptor.adapterId,runtimeConfigId:descriptor.id};next.config=preferred?.config??{};next.status="opening";next.model=optionalStr(p,"model")??preferred?.model;delete next.goal;delete next.capabilities;delete next.activeTurnId;delete next.permissionDowngrade;delete next.nativeTitle;next.title=next.fallbackTitle;
836
+ if(context){next.instructions=context.instructions;next.mcpServers=context.mcpServers;}
837
+ // Negotiate/open the target in isolation. Its buffered initial events cannot mutate the old binding.
838
+ const staged=await this.prepareLive(next,descriptor,"new");
839
+ try{await this.closeLive(record.id);if(this.shuttingDown)throw new HostError("HOST_CLOSED");this.installLive(next,staged);}
840
+ catch(cause){try{await this.disposeLive(staged);await staged.reader.return?.();}catch{
841
+ const current=this.store.session(record.id);current.status="recoveryRequired";current.uncertainRuntimeConfigIds=[...new Set([...(current.uncertainRuntimeConfigIds??[]),descriptor.id])];this.store.saveSession(current);
842
+ throw new HostError("RESULT_UNKNOWN","Staged runtime termination could not be verified",false,true);
843
+ }finally{this.releaseRuntime(descriptor.id);}throw cause;}
844
+ const event=this.store.append(next.id,{type:"host/binding",payload:{bindingGeneration:next.bindingGeneration,runtimeConfigId:next.runtimeConfigId,adapterId:next.adapterId}});if(event)this.publish(event);
845
+ return this.publicSession(next.id);
846
+ }
847
+ private async mutateWorkspace(record:SessionRecord,method:HxMethod,p:Values,principal:Principal):Promise<JsonValue> {
848
+ const port=this.options.workspaces;if(!port||!record.workspaceBinding?.worktreeId)throw new HostError("WORKSPACE_UNAVAILABLE");
849
+ this.assertProductIdle(this.store.session(record.id));const proof=await this.executionEvidence(record.id,undefined,true);if(!proof.quiescent||!proof.source)throw new HostError("RESULT_UNKNOWN","Native execution stop has not been verified",false,true);
850
+ const context={principal,projectId:record.projectId,sessionId:record.id,worktreeId:record.workspaceBinding.worktreeId,evidence:{stopped:true as const,source:proof.source,bindingGeneration:record.bindingGeneration??1}};
851
+ if(method==="hx.workspace.integrate"){
852
+ const result=await port.integrate({...context,mode:p.mode as "merge"|"patch",message:optionalStr(p,"message"),force:p.force===true});
853
+ if(!this.live.has(record.id))await this.open(this.store.session(record.id),"resume");
854
+ const event=this.store.append(record.id,{type:"host/workspace",payload:{workspace:this.store.session(record.id).workspace as unknown as JsonValue,action:"integrate"}});if(event)this.publish(event);
855
+ return result as unknown as JsonValue;
856
+ }
857
+ await this.closeLive(record.id);
858
+ const binding=await port.discard({...context,force:p.force===true});const next=this.store.session(record.id);next.cwd=realpathSync(binding.cwd);next.workspaceBinding=binding;next.workspace=this.workspacePublic(binding);next.binding={sessionId:next.id,adapterId:next.adapterId,runtimeConfigId:next.runtimeConfigId};next.bindingGeneration=(next.bindingGeneration??1)+1;next.status="closed";this.store.saveSession(next);await this.open(next,"new");const event=this.store.append(next.id,{type:"host/workspace",payload:{workspace:next.workspace as unknown as JsonValue,action:"discard"}});if(event)this.publish(event);return next.workspace as unknown as JsonValue;
859
+ }
860
+ private recordWholeStop(id:string,generation:number,evidence:{quiescent:true;evidenceRef:string;source:WorkspaceStopEvidence['source']}):void {
861
+ this.store.recordEvidence(id,generation,"session",evidence);
862
+ for(const operation of this.store.incomplete())if(operation.row.session_id===id)this.store.recordEvidence(id,generation,`operation:${operation.value.operationId}`,evidence);
863
+ }
864
+ async executionEvidence(id:string,turnId?:string,disposeOwned=false):Promise<{quiescent:boolean;evidenceRef?:string;source?:WorkspaceStopEvidence['source']}> {
865
+ const record=this.store.session(id),generation=record.bindingGeneration??1,key=turnId??"session";
866
+ if(record.uncertainRuntimeConfigIds?.length)return{quiescent:false};
867
+ const saved=this.store.evidence(id,generation,key);
868
+ if(saved?.quiescent===true)return {quiescent:true,evidenceRef:String(saved.evidenceRef),source:saved.source as WorkspaceStopEvidence['source']};
869
+ if(turnId&&record.activeTurnId===turnId){
870
+ const wholeStop=this.store.evidence(id,generation,"session");
871
+ if(wholeStop?.quiescent===true&&wholeStop.source==="owned-runtime-disposed"&&!this.live.has(id)){
872
+ return {quiescent:true,evidenceRef:String(wholeStop.evidenceRef),source:"owned-runtime-disposed"};
873
+ }
874
+ }
875
+ const live=this.live.get(id);let descriptor:RuntimeRegistration;try{descriptor=this.runtime(record);}catch{return{quiescent:false};}const nativeId=turnId?this.store.nativeTurn(id,turnId):this.store.nativeTurn(id);
876
+ if(descriptor.inspectExecution)try{const result=await descriptor.inspectExecution(record.binding,nativeId);if(result.stopped){const evidenceRef=`hx-native-inspect:${id}:${generation}:${key}`;this.store.recordEvidence(id,generation,key,{quiescent:true,evidenceRef,source:"native-inspect"});if(!turnId||record.activeTurnId===turnId)this.recordWholeStop(id,generation,{quiescent:true,evidenceRef,source:"native-inspect"});return {quiescent:true,evidenceRef,source:"native-inspect"};}}catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
877
+ if(disposeOwned&&live&&descriptor.ownedRuntime){
878
+ try{await this.disposeLive(live);await live.reader.return?.();await live.pump;}catch{const current=this.store.session(id);current.status="recoveryRequired";this.store.saveSession(current);throw new HostError("RESULT_UNKNOWN","Owned runtime termination could not be verified",false,true);}
879
+ const evidenceRef=`hx-owned-runtime-disposed:${id}:${generation}:${key}`;this.store.recordEvidence(id,generation,key,{quiescent:true,evidenceRef,source:"owned-runtime-disposed"});this.recordWholeStop(id,generation,{quiescent:true,evidenceRef,source:"owned-runtime-disposed"});return {quiescent:true,evidenceRef,source:"owned-runtime-disposed"};
880
+ }
881
+ return {quiescent:false};
882
+ }
883
+ private async prepareLive(record:SessionRecord,descriptor:RuntimeRegistration,mode:"new"|"resume"|"fork",fork?:SessionOpenParams["fork"]):Promise<LiveSession> {
884
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
885
+ const active=this.activeCounts.get(descriptor.id)??0,reservation=record.admissionRef&&this.admissions.get(record.admissionRef);
886
+ if(record.admissionRef&&reservation!==descriptor.id)throw new HostError("ADMISSION_EXPIRED");
887
+ const otherReservations=[...this.admissions.entries()].filter(([ref,id])=>id===descriptor.id&&ref!==record.admissionRef).length;
888
+ const uncertain=this.store.sessions().filter(value=>value.uncertainRuntimeConfigIds?.includes(descriptor.id)||(value.id!==record.id&&value.runtimeConfigId===descriptor.id&&!this.live.has(value.id)&&value.status==="recoveryRequired"&&this.store.evidence(value.id,value.bindingGeneration??1,"session")?.quiescent!==true)).length;
889
+ const limit=this.concurrencyLimit(descriptor);
890
+ if(limit>0&&active+otherReservations+uncertain>=limit)throw new HostError("HARNESS_CAPACITY_EXCEEDED");
891
+ if(record.admissionRef){this.admissions.delete(record.admissionRef);delete record.admissionRef;this.store.saveSession(record);}
892
+ this.activeCounts.set(descriptor.id,active+1);
893
+ const context=descriptor.adapterId==="codex"?{commandOutputPrivacy:new PersistentSecretRedactor(this.store,record.id)}:undefined;
894
+ let client:Client;try{
895
+ const cached=record.executionMode==='swarm'?this.catalog.view(descriptor.id,true):undefined;
896
+ const backend=await descriptor.create(context);
897
+ if(record.executionMode==='swarm') {
898
+ // Workspace workflow files load per open; a broken file reports through onError and
899
+ // leaves the session usable without workflows instead of failing the open.
900
+ let workflows:SwarmWorkflowOptions|undefined;try{workflows=await swarmWorkflowOptions(record.cwd);}catch{this.options.onError?.("SWARM_WORKFLOW_LOAD_FAILED");}
901
+ client=await createOwnedSwarmClient(backend,cached&&cached.cache.state!=='empty'?{default:{status:'available',models:(cached.models??[]).map(model=>({id:model.id,name:model.name,isDefault:model.isDefault,efforts:model.effortLevels?.map(id=>({id})),defaultEffort:model.defaultEffort})),...(descriptor.adapterId==='codex'?{effortConfigKey:'effort' as const}:{})}}:undefined,workflows,()=>descriptor.create(context));
902
+ } else client=backend;
903
+ }catch(cause){this.releaseRuntime(descriptor.id);throw cause;}
904
+ let mcp:RuntimeMcpBinding|undefined;
905
+ try{
906
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
907
+ const mcpEnabled=!(descriptor.adapterId==="hermes"&&mode==="resume");
908
+ if(mcpEnabled&&this.options.bindRuntimeMcp)mcp=await this.options.bindRuntimeMcp({sessionId:record.id,projectId:record.projectId,ownerId:record.ownerId,adapterId:descriptor.adapterId,providerId:descriptor.providerId,mode});
909
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
910
+ const boundServers=mcp?.servers;
911
+ const mcpServers=boundServers?[...boundServers,...(record.mcpServers??[]).filter(server=>!boundServers.some(bound=>bound.name===server.name))]:record.mcpServers;
912
+ // @anureo/sdk 0.3.2 将 SessionOpenParams 收紧为按 mode 判别的联合(fork 必带 fork 明细);host 侧 wire 形状不变,此处断言过渡。
913
+ const session=await client.openSession({requestId:randomUUID(),mode,binding:record.binding,cwd:record.cwd,config:record.config,...(mcpServers&&mcpEnabled?{mcpServers}:{}),...(record.model?{model:record.model}:{}),...(record.permissionMode?{permissionMode:record.permissionMode}:{}),...(record.instructions&&descriptor.adapterId!=="hermes"?{instructions:record.instructions}:{}),...(fork?{fork}:{})} as Parameters<typeof client.openSession>[0]);
914
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");if(record.executionMode!=='swarm')descriptor.capabilities={...session.capabilities};
915
+ const nativeTurnToCanonical = mode === "resume"
916
+ ? this.store.executionTurnMap(record.id, record.bindingGeneration ?? 1)
917
+ : new Map<string, string>();
918
+ if(fork&&fork.sourceSessionId){const origin=this.live.get(fork.sourceSessionId);if(origin)for(const [nativeId,canonicalId] of origin.nativeTurnToCanonical)nativeTurnToCanonical.set(nativeId,canonicalId);}
919
+ return{client,session,reader:session.events()[Symbol.asyncIterator](),pump:Promise.resolve(),runtimeConfigId:descriptor.id,registration:descriptor,bindingGeneration:record.bindingGeneration??1,nativeTurnToCanonical,pendingCanonical:[],streamSeqs:new Map(),mcp};
920
+ }catch(cause){
921
+ this.releaseMcp(mcp);
922
+ try{await client.dispose();}catch{
923
+ if(!this.storageClosed&&this.hasSession(record.id)){const current=this.store.session(record.id);current.status="recoveryRequired";current.uncertainRuntimeConfigIds=[...new Set([...(current.uncertainRuntimeConfigIds??[]),descriptor.id])];this.store.saveSession(current);}
924
+ throw new HostError("RESULT_UNKNOWN","Target runtime termination could not be verified",false,true);
925
+ }finally{this.releaseRuntime(descriptor.id);}throw cause;
926
+ }
927
+ }
928
+ private releaseMcp(binding:RuntimeMcpBinding|undefined):void {
929
+ try{binding?.release();}catch{try{this.options.onError?.("RUNTIME_MCP_RELEASE_FAILED");}catch{}}
930
+ }
931
+ private disposeLive(live:LiveSession):Promise<void> {
932
+ this.releaseMcp(live.mcp);
933
+ delete live.mcp;
934
+ return live.client.dispose();
935
+ }
936
+ /** The pump registers canonical turn rows asynchronously while submit resolves at association; boundary consumers need the row, so give it a bounded window before the operation result lands. */
937
+ private async waitForTurnRow(id:string,turnId:string,ms=1000):Promise<void> {
938
+ for(let deadline=Date.now()+ms;Date.now()<deadline;){if(this.store.nativeTurn(id,turnId)!==undefined)return;await new Promise(r=>setTimeout(r,10));}
939
+ }
940
+ /** Rewrite native turn identities into the product's canonical contract: envelope scope and turn payloads carry the canonical id while the native id lands in nativeTurnId; source seq renumbers from the store ledger because 0.3 native streams skip the ledger's reserved first slot. */
941
+ private async *translate(_id:string,reader:AsyncIterator<AhpEvent>,live:LiveSession):AsyncGenerator<AhpEvent> {
942
+ for(;;){let item:IteratorResult<AhpEvent>;try{item=await reader.next();}catch(cause){if(hostError(cause).code==="OBSERVATION_CLOSED")return;throw cause;}if(item.done)return;const source=item.value;
943
+ if(source.type==="turn/started"){const native=source.payload.turnId;if(native&&!live.nativeTurnToCanonical.has(native)){const bound=live.pendingCanonical.shift()??native;live.nativeTurnToCanonical.set(native,bound);}}
944
+ let canonical=source.turnId?live.nativeTurnToCanonical.get(source.turnId)??source.turnId:source.turnId;
945
+ if(!canonical&&(source.type==="turn/started"||source.type==="turn/completed")&&typeof source.payload.turnId==="string")canonical=live.nativeTurnToCanonical.get(source.payload.turnId)??source.payload.turnId;
946
+ const payload=source.type==="turn/started"||source.type==="turn/completed"?{...source.payload,turnId:canonical,nativeTurnId:source.payload.turnId}:source.type==='interaction/requested'&&canonical?{...source.payload,turnId:canonical}:source.payload;
947
+ const streamSeq=(live.streamSeqs.get(source.streamId)??0)+1;live.streamSeqs.set(source.streamId,streamSeq);
948
+ yield {...source,seq:streamSeq,turnId:canonical,payload} as AhpEvent;
949
+ }
950
+ }
951
+ private installLive(record:SessionRecord,live:LiveSession):void {
952
+ this.store.clearEvidence(record.id,record.bindingGeneration??1,"session");
953
+ record.binding={...live.session.binding};record.status="ready";record.capabilities=this.redactor(record.id).capabilities(live.session.capabilities);record.capabilityRevision=record.capabilityRevision??1;this.store.saveSession(record);
954
+ this.live.set(record.id,live);live.pump=this.pump(record.id,this.translate(record.id,live.reader,live),live).catch(cause=>{try{this.options.onError?.(hostError(cause).code);}catch{}});
955
+ }
956
+ private async open(record:SessionRecord,mode:"new"|"resume"|"fork",fork?:SessionOpenParams["fork"]):Promise<void> {
957
+ if(this.live.has(record.id))throw new HostError("SESSION_ALREADY_OPEN");
958
+ this.store.clearEvidence(record.id,record.bindingGeneration??1,"session");
959
+ try{this.installLive(record,await this.prepareLive(record,this.runtime(record),mode,fork));}
960
+ catch(cause){if(!this.shuttingDown&&!this.storageClosed){const current=this.store.session(record.id);if(current.status!=="recoveryRequired"){current.status="closed";this.store.saveSession(current);}}throw cause;}
961
+ }
962
+ private releaseRuntime(id:string):void {this.activeCounts.set(id,Math.max(0,(this.activeCounts.get(id)??1)-1));}
963
+ /** Append explicit corrections for structured fallback items saved by older Codex adapters. */
964
+ private repairLegacySubagents(id:string):void {
965
+ if(this.repairedSubagentSessions.has(id))return;
966
+ this.repairedSubagentSessions.add(id);
967
+ const record=this.store.session(id);
968
+ if(record.adapterId!=='codex'||!record.binding.nativeRef)return;
969
+ // Most sessions need no repair. Avoid replaying their transcripts during session-list reads.
970
+ if(!this.store.hasLegacySubagentActivity(id))return;
971
+ const candidates=new Map<string,{source:HostEvent;item:Item}>();
972
+ const repaired=new Set<string>(),latestNativeState=new Map<string,number>();
973
+ let cursor=0;const through=record.latestSeq;
974
+ while(cursor<through){
975
+ const page=this.store.events(id,cursor,through,1000);
976
+ for(const source of page.events){
977
+ const event=source.event;
978
+ if(event.type==='host/subagent'){
979
+ const activity=event.payload.activity;
980
+ if(activity&&typeof activity==='object'&&!Array.isArray(activity)&&typeof activity.turnId==='string'&&activity.item&&typeof activity.item==='object'&&!Array.isArray(activity.item)&&typeof activity.item.id==='string')repaired.add(`${activity.turnId}\0${activity.item.id}`);
981
+ }
982
+ if((event.type!=='item/started'&&event.type!=='item/completed')||!source.turnId||(source.bindingGeneration??1)!==(record.bindingGeneration??1))continue;
983
+ const item=event.payload.item;
984
+ if(item.type==='subagent')latestNativeState.set(item.subagentId,source.hostSeq);
985
+ else if(nativeSubagentActivity(item))candidates.set(`${source.turnId}\0${item.id}`,{source,item});
986
+ }
987
+ if(page.nextAfterSeq<=cursor)break;
988
+ cursor=page.nextAfterSeq;
989
+ }
990
+ for(const [key,{source,item}] of [...candidates].sort((a,b)=>a[1].source.hostSeq-b[1].source.hostSeq)){
991
+ if(repaired.has(key))continue;
992
+ const native=nativeSubagentActivity(item)!;
993
+ const result=registerSubagent(this.store,this.store.session(id),native,!!this.runtimes.find(runtime=>runtime.id===record.runtimeConfigId&&runtime.available!==false)?.readSubagentHistory,source.turnId,(latestNativeState.get(native.subagentId)??0)>source.hostSeq);
994
+ if(!result.summary)continue;
995
+ const event=this.store.append(id,{type:'host/subagent',payload:{subagent:{...result.summary},activity:{turnId:source.turnId!,item:result.item as unknown as JsonObject}}});
996
+ if(event)this.publish(event);
997
+ }
998
+ }
999
+ private async discoverSubagents(record:SessionRecord):Promise<void> {
1000
+ const parentNativeRef=record.binding.nativeRef;
1001
+ const discover=this.runtimes.find(runtime=>runtime.id===record.runtimeConfigId&&runtime.available!==false)?.discoverSubagents;
1002
+ if(!parentNativeRef||!discover)return;
1003
+ const key=`${record.id}:${record.bindingGeneration??1}`;
1004
+ let pending=this.subagentDiscovery.get(key);
1005
+ if(!pending){
1006
+ pending=(async()=>{
1007
+ let children:Awaited<ReturnType<SubagentDiscoveryPort>>;
1008
+ try{children=await discover({parentNativeRef,cwd:record.cwd});}
1009
+ catch(cause){if(hostError(cause).code==='CAPABILITY_UNSUPPORTED')return;throw historyReadError(cause);}
1010
+ const current=this.store.session(record.id);
1011
+ if((current.bindingGeneration??1)!==(record.bindingGeneration??1)||current.binding.nativeRef?.value!==parentNativeRef.value)return;
1012
+ for(const child of children){
1013
+ if(!child.id||child.id===parentNativeRef.value||child.parentThreadId!==parentNativeRef.value)continue;
1014
+ const previous=current.nativeSubagents?.find(entry=>entry.nativeRef.value===child.id&&entry.runtimeConfigId===current.runtimeConfigId&&entry.bindingGeneration===(current.bindingGeneration??1));
1015
+ this.observeSubagent(current,{id:`discovered:${child.id}`,type:'subagent',subagentId:child.id,state:previous?.summary.status==='disconnected'?'running':previous?.summary.status??'running',...(child.name?{name:child.name}:{}),...(child.task?{task:child.task}:{})});
1016
+ }
1017
+ })().finally(()=>this.subagentDiscovery.delete(key));
1018
+ this.subagentDiscovery.set(key,pending);
1019
+ }
1020
+ await pending;
1021
+ }
1022
+ private observeSubagent(record:SessionRecord,item:Extract<Item,{type:'subagent'}>,parentTurnId?:string,preserveLifecycle=false) {
1023
+ const result=registerSubagent(this.store,record,this.redactor(record.id).item(item) as Extract<Item,{type:'subagent'}>,!!this.runtimes.find(runtime=>runtime.id===record.runtimeConfigId&&runtime.available!==false)?.readSubagentHistory,parentTurnId,preserveLifecycle);
1024
+ if(result.changed&&result.summary){const event=this.store.append(record.id,{type:'host/subagent',payload:{subagent:{...result.summary}}});if(event)this.publish(event);}
1025
+ return result;
1026
+ }
1027
+ private async prepareItem(id:string,item:Item,parentTurnId?:string,register:boolean|'history'=true):Promise<Item> {
1028
+ const record=this.store.session(id);
1029
+ let prepared=this.options.prepareItem?await this.options.prepareItem({sessionId:id,projectId:record.projectId,cwd:record.cwd,item}):item;
1030
+ // Binary source payloads must never enter durable events or public history.
1031
+ if(prepared.type==="toolCall"&&prepared.image?.data!==undefined){const {data:_data,...image}=prepared.image;prepared={...prepared,image:{...image,unavailable:image.unavailable??"notProvided"}};}
1032
+ assertDefinition<Item>("Item",prepared);
1033
+ if(prepared.id!==item.id||prepared.type!==item.type)throw new HostError("PROTOCOL_ERROR");
1034
+ if(prepared.type==='subagent'){
1035
+ const current=this.store.session(id);
1036
+ if(register&&(record.bindingGeneration??1)===(current.bindingGeneration??1)){
1037
+ const registered=this.observeSubagent(current,prepared,parentTurnId,register==='history');
1038
+ prepared=registered.item;
1039
+ }else{const {coworkSubagent:_ignored,...extensions}=prepared.extensions??{};prepared={...prepared,extensions};}
1040
+ }
1041
+ return prepared;
1042
+ }
1043
+ private async pump(id:string,reader:AsyncIterator<AhpEvent>,live:LiveSession):Promise<void> {
1044
+ try{
1045
+ for(;;){const item=await reader.next();if(item.done||this.storageClosed)break;
1046
+ if(item.value.sessionId!==id)throw new HostError("SOURCE_SESSION_MISMATCH");
1047
+ if(live.bindingGeneration!==(this.store.session(id).bindingGeneration??1))continue;
1048
+ if(item.value.type==="interaction/requested"&&item.value.payload.privatePayload)this.privateInteractions.set(`${id}:${item.value.payload.interactionId}`,item.value.payload.privatePayload);
1049
+ if(item.value.type==="interaction/resolved")this.privateInteractions.delete(`${id}:${item.value.payload.interactionId}`);
1050
+ let source=item.value;
1051
+ if(source.type==='notice'&&source.payload.code==='SUBAGENT_THREAD_STARTED'){
1052
+ const evidence=source.payload.extensions;
1053
+ const current=this.store.session(id);
1054
+ if(evidence&&typeof evidence.nativeThreadId==='string'&&evidence.parentThreadId===current.binding.nativeRef?.value){
1055
+ this.observeSubagent(current,{id:`discovered:${evidence.nativeThreadId}`,type:'subagent',subagentId:evidence.nativeThreadId,state:'running',...(typeof evidence.agentNickname==='string'?{name:evidence.agentNickname}:{})},undefined,true);
1056
+ }
1057
+ }
1058
+ if(source.type==="item/started"||source.type==="item/completed")source={...source,payload:{item:await this.prepareItem(id,source.payload.item,source.turnId?live.nativeTurnToCanonical.get(source.turnId)??source.turnId:undefined)}};
1059
+ else if(source.type==="item/delta"&&source.payload.kind==="patch"&&source.payload.value&&typeof source.payload.value==="object"&&"type" in source.payload.value){assertDefinition<Item>("Item",source.payload.value);source={...source,payload:{...source.payload,value:await this.prepareItem(id,source.payload.value) as unknown as JsonValue}};}
1060
+ const safe=this.redactor(id).event({type:source.type,payload:source.payload} as Parameters<SecretRedactor["event"]>[0]);
1061
+ const event=this.store.appendSource({...item.value,...safe} as AhpEvent,live.bindingGeneration);if(event)this.publish(event);
1062
+ if(item.value.type==="turn/completed"){this.completeQueuedTurn(id,item.value.payload.turnId,item.value.payload.status,item.value.payload.error);if(!item.value.payload.error?.outcomeUnknown)await this.turnHook("settled",id,item.value.payload.turnId,item.value.payload.status);}
1063
+ if(item.value.type==="turn/completed"||item.value.type==="interaction/resolved"||item.value.type==="session/state")this.scheduleQueue(id);
1064
+ }
1065
+ }catch(cause){
1066
+
1067
+ const failure=hostError(cause);
1068
+ // Only an uncertain execution needs explicit recovery. An idle session (no active turn, unresolved interaction or
1069
+ // in-flight queue item) just closes in the `finally` below and is reopened transparently on the next use.
1070
+ // `failure.outcomeUnknown` is deliberately not consulted: the SDK marks every observation failure as outcome-unknown
1071
+ // ("native stop unconfirmed"), which would make this check vacuous. An unverified runtime stop is still escalated to
1072
+ // recovery by the `finally` (dispose failure). Fail safe: if the durable state cannot be read, require recovery.
1073
+ let needsRecovery=true;
1074
+ try{if(this.hasSession(id)){const current=this.store.session(id);needsRecovery=!!current.activeTurnId||this.store.interactions(id).some(i=>i.state!=="resolved")||this.store.queue(id).items.some(item=>["dispatching","running","unknown"].includes(item.state));}}catch{}
1075
+ try{this.options.onError?.(failure.code);}catch{}
1076
+ try{this.options.onEventStreamError?.({sessionId:id,code:failure.code,...(cause instanceof Error&&cause.message?{message:cause.message.slice(0,500)}:{}),outcomeUnknown:failure.outcomeUnknown,recoveryRequired:needsRecovery});}catch{}
1077
+ for(const [key,sub] of this.subscriptions){if(sub.sessionId===id){sub.active=false;this.subscriptions.delete(key);let lastAvailableSeq=0;try{lastAvailableSeq=this.store.session(id).latestSeq;}catch{}
1078
+ try{await sub.connection.send({jsonrpc:"2.0",method:"hx.subscription.error",params:{subscriptionId:sub.id,code:"EVENT_STREAM_FAILED",lastAvailableSeq}});}catch{}
1079
+ }}
1080
+ if(needsRecovery)try{if(this.hasSession(id)){const s=this.store.session(id);s.status="recoveryRequired";this.store.saveSession(s);}}catch{}
1081
+ // Stop the source on storage failure; never acknowledge unpersisted events as delivered.
1082
+ await Promise.resolve().then(()=>reader.return?.()).catch(()=>{});await this.disposeLive(live).catch(()=>{});
1083
+ }finally{
1084
+ let disposed=false;try{await this.disposeLive(live);disposed=true;}catch{}
1085
+ if(this.live.get(id)===live){
1086
+ // Preserve verified owned-process cleanup before transferring the live owner
1087
+ // to recovery. A failed turn can remain unknown without retaining a seat.
1088
+ if(disposed&&live.registration.ownedRuntime&&!this.storageClosed)try{
1089
+ if(this.hasSession(id))this.recordWholeStop(id,live.bindingGeneration,{quiescent:true,evidenceRef:`hx-owned-runtime-disposed:${id}:${live.bindingGeneration}:session`,source:"owned-runtime-disposed"});
1090
+ }catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
1091
+ // Transfer a failed live owner to the durable recovery capacity hold before releasing its live count.
1092
+ if(!disposed)try{if(this.hasSession(id)){const current=this.store.session(id);current.status="recoveryRequired";this.store.saveSession(current);}}catch{}
1093
+ this.live.delete(id);this.releaseRuntime(live.runtimeConfigId);
1094
+ try{if(this.hasSession(id)){
1095
+ const current=this.store.session(id);
1096
+ if(current.status!=="recoveryRequired"){
1097
+ current.status=current.activeTurnId||this.store.interactions(id).some(i=>i.state!=="resolved")?"recoveryRequired":"closed";this.store.saveSession(current);
1098
+ }
1099
+ }}catch{}
1100
+ }
1101
+ }
1102
+ }
1103
+ private publish(event:HostEvent):void {
1104
+ try{this.options.onEvent?.(event);}catch{}
1105
+ for(const sub of this.subscriptions.values()) {
1106
+ if(!sub.active||sub.sessionId!==event.sessionId||event.hostSeq<=sub.lastSeq)continue;
1107
+ const bytes=new TextEncoder().encode(JSON.stringify(event)).byteLength;
1108
+ if(sub.pending+1>(this.options.maxNotificationEvents??2048)||sub.bytes+bytes>(this.options.maxNotificationBytes??16*1024*1024)) {
1109
+ sub.active=false;this.subscriptions.delete(sub.id);
1110
+ void Promise.resolve(sub.connection.send({jsonrpc:"2.0",method:"hx.subscription.error",params:{subscriptionId:sub.id,code:"SUBSCRIPTION_OVERFLOW",lastAvailableSeq:event.hostSeq}})).catch(()=>sub.connection.close?.());continue;
1111
+ }
1112
+ sub.pending++;sub.bytes+=bytes;
1113
+ sub.tail=sub.tail.then(async()=>{
1114
+ if(!sub.active)return;
1115
+ await this.access(sub.connection,this.store.session(event.sessionId).projectId,"viewer");
1116
+ await sub.connection.send({jsonrpc:"2.0",method:"hx.event",params:{subscriptionId:sub.id,...event}});sub.lastSeq=event.hostSeq;
1117
+ }).catch(()=>{sub.active=false;this.subscriptions.delete(sub.id);sub.connection.close?.();}).finally(()=>{sub.pending--;sub.bytes-=bytes;});
1118
+ }
1119
+ }
1120
+ private async reconcile(record:SessionRecord):Promise<unknown> {
1121
+ // Explicit reconciliation may terminate an independently owned runtime, but never resubmits.
1122
+ if(record.status==="recoveryRequired"||this.store.queue(record.id).items.some(item=>item.state==="unknown")){
1123
+ const evidence=await this.executionEvidence(record.id,record.activeTurnId,true);
1124
+ if(evidence.quiescent){
1125
+ const events=this.store.reconcileStopped(record,this.live.has(record.id),evidence.evidenceRef);
1126
+ for(const event of events)this.publish(event);
1127
+ }
1128
+ }
1129
+ // Original operation results stay unknown. Retry is a separate explicit intent with a new turn ID.
1130
+ return {session:this.publicSession(record.id),operations:this.store.incomplete().filter(o=>o.row.session_id===record.id).map(o=>o.value)};
1131
+ }
1132
+ /** Replaces discovery metadata and future factories; running sessions retain their original registration. */
1133
+ refreshRuntimes(runtimes:RuntimeRegistration[]):Promise<void> {
1134
+ return this.queueCatalogRefresh(async()=>runtimes);
1135
+ }
1136
+ authChanged(providerId:string):void {
1137
+ if(this.shuttingDown)return;
1138
+ const ids=this.runtimes.filter(r=>(r.providerId??r.adapterId)===providerId).map(r=>r.id);
1139
+ this.catalog.resetIdentity(ids);
1140
+ void this.notifyCatalogSnapshot(ids,["auth"]);
1141
+ }
1142
+ /** Re-read the configured source. Explicit empty and invalid files never fall back to discovery. */
1143
+ refreshCatalog():Promise<void> {
1144
+ if(!this.options.loadRuntimes)return Promise.resolve();
1145
+ return this.queueCatalogRefresh(this.options.loadRuntimes);
1146
+ }
1147
+ /** Catalog reads never wait for a native process. Session creation still checks auth live. */
1148
+ private refreshCatalogAuth():void {
1149
+ for(const runtime of this.runtimes){
1150
+ if(runtime.available===false||!runtime.getAuthStatus)continue;
1151
+ const previous=this.catalogAuthChecks.get(runtime);
1152
+ if(previous&&(previous.pending||Date.now()-previous.checkedAt<30_000))continue;
1153
+ const check={pending:true,checkedAt:0};this.catalogAuthChecks.set(runtime,check);
1154
+ const initial=runtime.authStatus;
1155
+ void Promise.resolve().then(()=>runtime.getAuthStatus!()).catch(()=>"unknown" as const).then(async status=>{
1156
+ // A replaced registration or a newer live auth check owns its own status.
1157
+ if(this.shuttingDown||!this.runtimes.includes(runtime)||runtime.authStatus!==initial)return;
1158
+ if((runtime.authStatus??"unknown")===status)return;
1159
+ runtime.authStatus=status;
1160
+ await this.notifyCatalogChanged();await this.notifyCatalogSnapshot([runtime.id],["auth"]);
1161
+ }).finally(()=>{check.pending=false;check.checkedAt=Date.now();});
1162
+ }
1163
+ }
1164
+ private async notifyCatalogSnapshot(runtimeConfigIds:string[],changes:Array<"runtime"|"models"|"auth"|"refresh">):Promise<void>{
1165
+ if(this.shuttingDown)return;const revision=++this.catalogRevision;
1166
+ await Promise.all([...this.snapshotScopes.entries()].map(async([id,scope])=>{
1167
+ if(!this.initialized.has(id))return;
1168
+ for(const projectId of [...scope.projects])try{
1169
+ await this.access(scope.connection,projectId,"viewer");if(this.shuttingDown||this.snapshotScopes.get(id)!==scope)break;
1170
+ await scope.connection.send({jsonrpc:"2.0",method:"hx.catalog.changed",params:{projectId,epoch:this.catalogEpoch,revision,runtimeConfigIds,changes}});
1171
+ }catch{scope.projects.delete(projectId);}
1172
+ }));
1173
+ }
1174
+ private async notifyCatalogChanged():Promise<void> {
1175
+ const revision=++this.catalogRevision;
1176
+ await Promise.all([...this.catalogScopes.entries()].map(async([connectionId,scope])=>{
1177
+ if(!this.initialized.has(connectionId))return;
1178
+ for(const projectId of [...scope.projects]){
1179
+ try{
1180
+ await this.access(scope.connection,projectId,"viewer");
1181
+ if(this.shuttingDown||this.catalogScopes.get(connectionId)!==scope||!this.initialized.has(connectionId))break;
1182
+ const notification:HxHarnessChangedNotification={jsonrpc:"2.0",method:"hx.harness.changed",params:{projectId,revision}};
1183
+ await scope.connection.send(notification);
1184
+ }catch{scope.projects.delete(projectId);}
1185
+ }
1186
+ if(!scope.projects.size&&this.catalogScopes.get(connectionId)===scope)this.catalogScopes.delete(connectionId);
1187
+ }));
1188
+ }
1189
+ private queueCatalogRefresh(load:()=>Promise<RuntimeRegistration[]>|RuntimeRegistration[]):Promise<void> {
1190
+ const refreshed=this.catalogRefresh.catch(()=>{}).then(async()=>{
1191
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
1192
+ const next=await load();
1193
+ if(this.shuttingDown)throw new HostError("HOST_CLOSED");
1194
+ const ids=new Set<string>();
1195
+ for(const registration of next){if(!registration.id||ids.has(registration.id)||!registration.adapterId||typeof registration.create!=="function")throw new HostError("HOST_CONFIG_INVALID");ids.add(registration.id);}
1196
+ this.runtimes=[...next];this.catalog.replace(this.runtimes);await this.notifyCatalogChanged();await this.notifyCatalogSnapshot(this.runtimes.map(r=>r.id),["runtime"]);
1197
+ });
1198
+ this.catalogRefresh=refreshed;return refreshed;
1199
+ }
1200
+ disconnect(connectionId:string):void {this.snapshotScopes.delete(connectionId);this.catalogScopes.delete(connectionId);this.initialized.delete(connectionId);for(const [id,sub] of this.subscriptions){if(sub.connection.id===connectionId){sub.active=false;this.subscriptions.delete(id);}}}
1201
+ close():Promise<void> {this.shuttingDown=true;if(this.bootstrapRetry)clearTimeout(this.bootstrapRetry);return this.closing??=this.performClose();}
1202
+ private async performClose():Promise<void> {
1203
+ for(const sub of this.subscriptions.values())sub.active=false;this.subscriptions.clear();this.initialized.clear();this.catalogScopes.clear();this.snapshotScopes.clear();await this.catalog.close();
1204
+ const limit=this.options.shutdownTimeoutMs??10_000;
1205
+ const drain=async(pending:Promise<unknown>[])=>{
1206
+ let timer:ReturnType<typeof setTimeout>|undefined;
1207
+ try{await Promise.race([Promise.allSettled(pending),new Promise<void>(resolve=>{timer=setTimeout(resolve,limit);})]);}finally{if(timer)clearTimeout(timer);}
1208
+ };
1209
+ await drain([...this.live.values()].map(async live=>{await this.disposeLive(live).catch(()=>{});await live.reader.return?.();await live.pump.catch(()=>{});}));
1210
+ await drain([...this.inFlight]);
1211
+ try{for(const {row,value} of this.store.incomplete()){
1212
+ const ended:OperationResult=row.phase==="accepted"&&value.state==="accepted"?{...value,state:"failed",outcomeUnknown:false,error:{code:"NOT_DISPATCHED",message:"NOT_DISPATCHED",retryable:false,outcomeUnknown:false}}:this.unknownResult(value);
1213
+ this.closedResults.set(value.operationId,ended);
1214
+ try{this.store.finishOperation(ended);}catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
1215
+ }}catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
1216
+ finally{
1217
+ this.storageClosed=true;this.live.clear();this.privateInteractions.clear();this.secrets.clear();
1218
+ try{this.store.close();}catch(cause){try{this.options.onError?.(hostError(cause).code);}catch{}}
1219
+ }
1220
+ }
1221
+ async handle(connection:HostConnection,request:RpcRequest):Promise<RpcResponse> {
1222
+ if(typeof request.id!=="number"||!Number.isSafeInteger(request.id))return {jsonrpc:"2.0",id:null,error:{code:-32600,message:"Invalid Request",data:{code:"INVALID_REQUEST",message:"Invalid Request",retryable:false,outcomeUnknown:false}}};
1223
+ try{if(!isHxMethod(request.method))throw new HostError("METHOD_NOT_FOUND");return {jsonrpc:"2.0",id:request.id,result:await this.request(connection,request.method,(request.params??{}) as HxRequestMap[HxMethod])};}catch(cause){
1224
+ const error=rpcError(cause),params=request.params as Values|undefined;
1225
+ if(error.data.details&&params&&typeof params.sessionId==="string"){const privacy=this.secrets.get(params.sessionId);if(privacy)error.data.details=privacy.json(error.data.details) as JsonObject;}
1226
+ return {jsonrpc:"2.0",id:request.id,error};
1227
+ }
1228
+ }
1229
+ }