@anureo/host 0.0.0-stage → 0.3.11
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/README.md +60 -2
- package/package.json +50 -4
- package/schema/v1/hx.schema.json +3422 -0
- package/src/catalog-store.ts +45 -0
- package/src/catalog-worker.ts +14 -0
- package/src/catalog.ts +179 -0
- package/src/compat.ts +7 -0
- package/src/errors.ts +24 -0
- package/src/host.ts +1229 -0
- package/src/index.ts +16 -0
- package/src/interaction-capture.ts +37 -0
- package/src/legacy-protocol/generated/types.ts +244 -0
- package/src/legacy-protocol/index.ts +37 -0
- package/src/native-subagent.ts +19 -0
- package/src/persistent-secrets.ts +34 -0
- package/src/protocol.ts +68 -0
- package/src/queue.ts +12 -0
- package/src/rpc.ts +43 -0
- package/src/scoped-host.ts +39 -0
- package/src/sqlite-bun.ts +12 -0
- package/src/sqlite-driver.ts +14 -0
- package/src/sqlite-node.ts +38 -0
- package/src/store.ts +408 -0
- package/src/subagents.ts +115 -0
- package/src/swarm-client.ts +113 -0
- package/src/swarm-workflows.ts +50 -0
- package/src/workspaces.ts +36 -0
- package/src/ws-bun-listener.ts +44 -0
- package/src/ws-connection.ts +127 -0
- package/src/ws-listener.ts +87 -0
- package/src/ws.ts +12 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
2
|
+
import type { OpenSqlite } from './sqlite-driver'
|
|
3
|
+
import { SqliteHostStore, type SqliteStoreHooks } from './store'
|
|
4
|
+
|
|
5
|
+
const open: OpenSqlite = (file, readOnly) => {
|
|
6
|
+
const db = new DatabaseSync(file, { readOnly })
|
|
7
|
+
let depth = 0
|
|
8
|
+
return {
|
|
9
|
+
exec: sql => db.exec(sql),
|
|
10
|
+
query: sql => db.prepare(sql),
|
|
11
|
+
transaction: run => () => {
|
|
12
|
+
const savepoint = depth ? `anureo_transaction_${depth}` : undefined
|
|
13
|
+
db.exec(savepoint ? `SAVEPOINT ${savepoint}` : 'BEGIN IMMEDIATE')
|
|
14
|
+
depth++
|
|
15
|
+
try {
|
|
16
|
+
const result = run()
|
|
17
|
+
db.exec(savepoint ? `RELEASE SAVEPOINT ${savepoint}` : 'COMMIT')
|
|
18
|
+
return result
|
|
19
|
+
} catch (error) {
|
|
20
|
+
db.exec(savepoint ? `ROLLBACK TO SAVEPOINT ${savepoint}; RELEASE SAVEPOINT ${savepoint}` : 'ROLLBACK')
|
|
21
|
+
throw error
|
|
22
|
+
} finally {
|
|
23
|
+
depth--
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
close: () => db.close(),
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class HarnessStore extends SqliteHostStore {
|
|
31
|
+
constructor(file: string, hooks?: SqliteStoreHooks) {
|
|
32
|
+
super(file, open, hooks)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createSqliteHostStorage(file: string): SqliteHostStore {
|
|
37
|
+
return new HarnessStore(file)
|
|
38
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import type { OpenSqlite, SqliteConnection } from "./sqlite-driver";
|
|
2
|
+
import { CatalogStore, type CatalogStorage } from "./catalog-store";
|
|
3
|
+
import { createHash,createHmac,randomBytes } from "node:crypto";
|
|
4
|
+
import { mkdirSync,readFileSync,writeFileSync,existsSync,realpathSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import type { AhpEvent,JsonObject,SessionBinding,SessionState,HistoryPage,McpServer,GoalState,Usage } from "@anureo/protocol";
|
|
7
|
+
import { publicEvent,publicInteraction,publicValue } from "@anureo/protocol";
|
|
8
|
+
import type { PublicSession,PublicInteraction,HostEvent,OperationResult,EventPage } from "./legacy-protocol";
|
|
9
|
+
import { HostError } from "./errors";
|
|
10
|
+
import { publicQueue,queuePending,type StoredQueueState,type StoredQueueItem } from "./queue";
|
|
11
|
+
|
|
12
|
+
export type SessionRecord=PublicSession&{inlineSubagents?:import("./subagents").StoredInlineSubagent[];nativeSubagents?:import("./subagents").StoredSubagent[];fallbackTitle?:string;nativeTitle?:string|null;binding:SessionBinding;instructions?:string;mcpServers?:McpServer[];goal?:GoalState;workspaceBinding?:import("./workspaces").WorkspaceBinding;admissionRef?:string;uncertainRuntimeConfigIds?:string[];permissionMode?:string;permissionDowngrade?:{config:JsonObject;permissionMode?:string;key:string;principalId:string;state:"pending"|"failed";error?:string}};
|
|
13
|
+
export interface PrivateAnswerHint {length:number;first:string;last:string;digest:string;scope?:string}
|
|
14
|
+
interface OperationRow {id:string;principal_id:string;method:string;target:string;idempotency_key:string;request_digest:string;phase:string;state:string;session_id:string|null;turn_id:string|null;result_json:string}
|
|
15
|
+
function canonical(value:unknown):string {
|
|
16
|
+
if(value===null||typeof value!=="object")return JSON.stringify(value)??"null";
|
|
17
|
+
if(Array.isArray(value))return `[${value.map(canonical).join(",")}]`;
|
|
18
|
+
return `{${Object.entries(value).filter(([,v])=>v!==undefined).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
19
|
+
}
|
|
20
|
+
export interface SqliteStoreHooks {beforeCommit?:()=>void;afterCommit?:()=>void}
|
|
21
|
+
export class SqliteHostStore {
|
|
22
|
+
readonly db:SqliteConnection;
|
|
23
|
+
readonly catalog:CatalogStore;
|
|
24
|
+
private readonly hmacKey:Uint8Array;
|
|
25
|
+
private readonly privateHints=new Map<string,PrivateAnswerHint[]>();
|
|
26
|
+
private readonly ownership?:SqliteConnection;
|
|
27
|
+
private closed=false;
|
|
28
|
+
constructor(readonly file:string,openSqlite:OpenSqlite,private readonly hooks:SqliteStoreHooks={}) {
|
|
29
|
+
if(file!==":memory:") {
|
|
30
|
+
mkdirSync(path.dirname(file),{recursive:true});
|
|
31
|
+
const canonicalFile=existsSync(file)?realpathSync(file):path.join(realpathSync(path.dirname(file)),path.basename(file));
|
|
32
|
+
const ownership=openSqlite(`${canonicalFile}.owner`);
|
|
33
|
+
try { ownership.exec('PRAGMA busy_timeout=0; BEGIN IMMEDIATE'); }
|
|
34
|
+
catch (error) {
|
|
35
|
+
ownership.close();
|
|
36
|
+
if(error&&typeof error==='object'&&('code' in error&&error.code==='SQLITE_BUSY'||'errcode' in error&&error.errcode===5))throw new HostError('HOST_STORAGE_IN_USE');
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
this.ownership=ownership;
|
|
40
|
+
}
|
|
41
|
+
let db:SqliteConnection|undefined;
|
|
42
|
+
try {
|
|
43
|
+
this.hmacKey=this.loadKey(openSqlite);
|
|
44
|
+
db=openSqlite(file);
|
|
45
|
+
this.db=db;
|
|
46
|
+
this.catalog=new CatalogStore(db);
|
|
47
|
+
this.migrate();
|
|
48
|
+
} catch (error) {
|
|
49
|
+
try { db?.close(); } finally { this.ownership?.close(); }
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
private loadKey(openSqlite:OpenSqlite):Uint8Array {
|
|
54
|
+
const {file}=this;
|
|
55
|
+
const keyFile=`${file}.key`;
|
|
56
|
+
if(file===":memory:")return randomBytes(32);
|
|
57
|
+
if(existsSync(file)&&!existsSync(keyFile)){
|
|
58
|
+
const existing=openSqlite(file,true);
|
|
59
|
+
try{const version=existing.query("PRAGMA user_version").get() as {user_version:number};if(version.user_version>0)throw new HostError("HOST_KEY_MISSING");}finally{existing.close();}
|
|
60
|
+
}
|
|
61
|
+
try{writeFileSync(keyFile,randomBytes(32),{flag:"wx",mode:0o600});}catch(e){if((e as NodeJS.ErrnoException).code!=="EEXIST")throw e;}
|
|
62
|
+
const key=readFileSync(keyFile);if(key.byteLength!==32)throw new HostError("HOST_KEY_INVALID");
|
|
63
|
+
return key;
|
|
64
|
+
}
|
|
65
|
+
private migrate():void {
|
|
66
|
+
const {file}=this;
|
|
67
|
+
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
|
|
68
|
+
const version=this.db.query("PRAGMA user_version").get() as {user_version:number};
|
|
69
|
+
if(version.user_version>4)throw new HostError("SCHEMA_VERSION_UNSUPPORTED");
|
|
70
|
+
if(version.user_version===0){
|
|
71
|
+
if(file!==":memory:" && existsSync(file) && !existsSync(`${file}.pre-v1.bak`) && (this.db.query("SELECT count(*) AS n FROM sqlite_master WHERE type='table'").get() as {n:number}).n>0)this.db.query("VACUUM INTO ?").run(`${file}.pre-v1.bak`);
|
|
72
|
+
this.db.transaction(()=>this.db.exec(`
|
|
73
|
+
CREATE TABLE IF NOT EXISTS hx_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
74
|
+
CREATE TABLE IF NOT EXISTS hx_sessions(id TEXT PRIMARY KEY, project_id TEXT NOT NULL,record_json TEXT NOT NULL,last_host_seq INTEGER NOT NULL DEFAULT 0);
|
|
75
|
+
CREATE TABLE IF NOT EXISTS hx_events(session_id TEXT NOT NULL,host_seq INTEGER NOT NULL,source_stream_id TEXT,source_seq INTEGER,type TEXT NOT NULL,turn_id TEXT,payload_json TEXT NOT NULL,created_at TEXT NOT NULL,PRIMARY KEY(session_id,host_seq),UNIQUE(session_id,source_stream_id,source_seq),FOREIGN KEY(session_id) REFERENCES hx_sessions(id));
|
|
76
|
+
CREATE TABLE IF NOT EXISTS hx_turns(session_id TEXT NOT NULL,turn_id TEXT NOT NULL,native_turn_id TEXT,status TEXT NOT NULL,execution_state TEXT NOT NULL,terminal_host_seq INTEGER,PRIMARY KEY(session_id,turn_id));
|
|
77
|
+
CREATE TABLE IF NOT EXISTS hx_interactions(session_id TEXT NOT NULL,id TEXT NOT NULL,revision INTEGER NOT NULL,state TEXT NOT NULL,record_json TEXT NOT NULL,PRIMARY KEY(session_id,id));
|
|
78
|
+
CREATE TABLE IF NOT EXISTS hx_operations(id TEXT PRIMARY KEY,principal_id TEXT NOT NULL,method TEXT NOT NULL,target TEXT NOT NULL,idempotency_key TEXT NOT NULL,request_digest TEXT NOT NULL,phase TEXT NOT NULL,state TEXT NOT NULL,session_id TEXT,turn_id TEXT,result_json TEXT NOT NULL,UNIQUE(principal_id,method,target,idempotency_key));
|
|
79
|
+
INSERT OR REPLACE INTO hx_meta(key,value) VALUES('schema_version','1'); PRAGMA user_version=1;
|
|
80
|
+
`))();
|
|
81
|
+
}
|
|
82
|
+
if(version.user_version<2){
|
|
83
|
+
if(version.user_version===1&&file!==":memory:"&&!existsSync(`${file}.pre-v2.bak`))this.db.query("VACUUM INTO ?").run(`${file}.pre-v2.bak`);
|
|
84
|
+
this.db.transaction(()=>{
|
|
85
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS hx_queue_states(session_id TEXT PRIMARY KEY,revision INTEGER NOT NULL,paused INTEGER NOT NULL DEFAULT 0);
|
|
86
|
+
CREATE TABLE IF NOT EXISTS hx_queue_items(session_id TEXT NOT NULL,id TEXT NOT NULL,position INTEGER NOT NULL,state TEXT NOT NULL,record_json TEXT NOT NULL,PRIMARY KEY(session_id,id));
|
|
87
|
+
CREATE TABLE IF NOT EXISTS hx_execution_evidence(session_id TEXT NOT NULL,binding_generation INTEGER NOT NULL,turn_id TEXT NOT NULL,evidence_json TEXT NOT NULL,PRIMARY KEY(session_id,binding_generation,turn_id));`);
|
|
88
|
+
const columns=this.db.query("PRAGMA table_info(hx_turns)").all() as {name:string}[];
|
|
89
|
+
if(!columns.some(column=>column.name==="binding_generation"))this.db.exec("ALTER TABLE hx_turns ADD COLUMN binding_generation INTEGER NOT NULL DEFAULT 1");
|
|
90
|
+
this.db.exec("INSERT OR REPLACE INTO hx_meta(key,value) VALUES('schema_version','2'); PRAGMA user_version=2;");
|
|
91
|
+
})();
|
|
92
|
+
}
|
|
93
|
+
if(version.user_version<3){
|
|
94
|
+
if(version.user_version===2&&file!==":memory:"&&!existsSync(`${file}.pre-v3.bak`))this.db.query("VACUUM INTO ?").run(`${file}.pre-v3.bak`);
|
|
95
|
+
this.db.transaction(()=>this.db.exec(`
|
|
96
|
+
CREATE TABLE IF NOT EXISTS hx_model_catalog_snapshots(identity_key TEXT PRIMARY KEY,runtime_config_id TEXT NOT NULL,provider_id TEXT NOT NULL,schema_version INTEGER NOT NULL,models_json TEXT NOT NULL,content_hash TEXT NOT NULL,engine_fingerprint TEXT NOT NULL,last_success_at INTEGER NOT NULL,fresh_until INTEGER NOT NULL);
|
|
97
|
+
CREATE TABLE IF NOT EXISTS hx_model_catalog_attempts(identity_key TEXT PRIMARY KEY,last_attempt_at INTEGER NOT NULL,last_error_code TEXT,failure_count INTEGER NOT NULL DEFAULT 0,next_retry_at INTEGER);
|
|
98
|
+
INSERT OR REPLACE INTO hx_meta(key,value) VALUES('schema_version','3'); PRAGMA user_version=3;
|
|
99
|
+
`))();
|
|
100
|
+
}
|
|
101
|
+
if(version.user_version<4){
|
|
102
|
+
if(version.user_version===3&&file!==":memory:"&&!existsSync(`${file}.pre-v4.bak`))this.db.query("VACUUM INTO ?").run(`${file}.pre-v4.bak`);
|
|
103
|
+
this.db.transaction(()=>this.db.exec(`
|
|
104
|
+
CREATE TABLE IF NOT EXISTS hx_projection_snapshots(session_id TEXT PRIMARY KEY,projection_version INTEGER NOT NULL,seq INTEGER NOT NULL,checkpoint_json TEXT NOT NULL,updated_at INTEGER NOT NULL);
|
|
105
|
+
INSERT OR REPLACE INTO hx_meta(key,value) VALUES('schema_version','4'); PRAGMA user_version=4;
|
|
106
|
+
`))();
|
|
107
|
+
}
|
|
108
|
+
const verifier=this.digest({kind:"cowork-hx-key-verifier",version:1});
|
|
109
|
+
const expected=this.db.query("SELECT value FROM hx_meta WHERE key='key_verifier'").get() as {value:string}|null;
|
|
110
|
+
if(expected&&expected.value!==verifier)throw new HostError("HOST_KEY_INVALID");
|
|
111
|
+
if(!expected)this.db.query("INSERT INTO hx_meta(key,value) VALUES('key_verifier',?)").run(verifier);
|
|
112
|
+
}
|
|
113
|
+
digest(value:unknown):string {return createHmac("sha256",this.hmacKey).update(canonical(value)).digest("hex");}
|
|
114
|
+
privateTag(sessionId:string,value:string):string {return this.digest({kind:"private-answer",sessionId,value});}
|
|
115
|
+
answerHints(sessionId:string):readonly PrivateAnswerHint[] {
|
|
116
|
+
let hints=this.privateHints.get(sessionId);
|
|
117
|
+
if(!hints){const row=this.db.query("SELECT value FROM hx_meta WHERE key=?").get(`private:${sessionId}`) as {value:string}|null;hints=row?JSON.parse(row.value) as PrivateAnswerHint[]:[];this.privateHints.set(sessionId,hints);}
|
|
118
|
+
return hints;
|
|
119
|
+
}
|
|
120
|
+
rememberPrivate(sessionId:string,value:string):void {
|
|
121
|
+
if(!value)return;
|
|
122
|
+
const hints=[...this.answerHints(sessionId)],digest=this.privateTag(sessionId,value);
|
|
123
|
+
if(hints.some(h=>h.length===value.length&&this.privateTag(h.scope??sessionId,value)===h.digest))return;
|
|
124
|
+
if(hints.length>=128||hints.reduce((n,h)=>n+h.length,0)+value.length>64*1024)throw new HostError("BACKPRESSURE_EXCEEDED");
|
|
125
|
+
hints.push({length:value.length,first:this.privateTag(sessionId,value[0]!),last:this.privateTag(sessionId,value.at(-1)!),digest,scope:sessionId});
|
|
126
|
+
this.db.query("INSERT INTO hx_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(`private:${sessionId}`,JSON.stringify(hints));
|
|
127
|
+
this.privateHints.set(sessionId,hints);
|
|
128
|
+
}
|
|
129
|
+
inheritPrivate(source:string,target:string):void {
|
|
130
|
+
const hints=this.answerHints(source).map(h=>({...h,scope:h.scope??source}));
|
|
131
|
+
if(!hints.length)return;
|
|
132
|
+
this.db.query("INSERT INTO hx_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(`private:${target}`,JSON.stringify(hints));this.privateHints.set(target,hints);
|
|
133
|
+
}
|
|
134
|
+
scanPrivate(sessionId:string,text:string,final=true):{text:string;pending:string} {
|
|
135
|
+
const hints=[...this.answerHints(sessionId)].sort((a,b)=>b.length-a.length);
|
|
136
|
+
if(!hints.length)return {text,pending:""};
|
|
137
|
+
const tags=new Map<string,string>();
|
|
138
|
+
const tag=(character:string,scope:string)=>{const key=scope+"\0"+character;let result=tags.get(key);if(!result){result=this.privateTag(scope,character);tags.set(key,result);}return result;};
|
|
139
|
+
const output:string[]=[];
|
|
140
|
+
for(let offset=0;offset<text.length;){
|
|
141
|
+
if(text.startsWith("[redacted]",offset)){output.push("[redacted]");offset+="[redacted]".length;continue;}
|
|
142
|
+
const candidates=hints.filter(h=>h.first===tag(text[offset]!,h.scope??sessionId));
|
|
143
|
+
// Preserve a possible longer marked value across delta frames, including after process restart.
|
|
144
|
+
if(!final&&candidates.some(h=>h.length>text.length-offset))return {text:output.join(""),pending:text.slice(offset)};
|
|
145
|
+
const match=candidates.find(h=>h.length<=text.length-offset&&tag(text[offset+h.length-1]!,h.scope??sessionId)===h.last&&this.privateTag(h.scope??sessionId,text.slice(offset,offset+h.length))===h.digest);
|
|
146
|
+
if(match){output.push("[redacted]");offset+=match.length;}else{output.push(text[offset]!);offset++;}
|
|
147
|
+
}
|
|
148
|
+
return {text:output.join(""),pending:""};
|
|
149
|
+
}
|
|
150
|
+
session(id:string):SessionRecord {
|
|
151
|
+
const row=this.db.query("SELECT record_json,last_host_seq FROM hx_sessions WHERE id=?").get(id) as {record_json:string;last_host_seq:number}|null;
|
|
152
|
+
if(!row)throw new HostError("SESSION_NOT_FOUND");
|
|
153
|
+
const record=JSON.parse(row.record_json) as SessionRecord;
|
|
154
|
+
// Existing records contain the original prompt-derived title.
|
|
155
|
+
if(record.fallbackTitle===undefined&&record.nativeTitle===undefined)record.fallbackTitle=record.title;
|
|
156
|
+
return {...record,latestSeq:row.last_host_seq};
|
|
157
|
+
}
|
|
158
|
+
saveSession(record:SessionRecord):void {
|
|
159
|
+
this.db.query("INSERT INTO hx_sessions(id,project_id,record_json,last_host_seq) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET record_json=excluded.record_json,project_id=excluded.project_id").run(record.id,record.projectId,JSON.stringify(record),record.latestSeq);
|
|
160
|
+
}
|
|
161
|
+
sessions(projectId?:string):SessionRecord[] {
|
|
162
|
+
const rows=(projectId?this.db.query("SELECT id FROM hx_sessions WHERE project_id=? ORDER BY id").all(projectId):this.db.query("SELECT id FROM hx_sessions ORDER BY id").all()) as {id:string}[];
|
|
163
|
+
return rows.map(row=>this.session(row.id));
|
|
164
|
+
}
|
|
165
|
+
sessionIdPage(projectId:string,archived:boolean,cursor:string|undefined,limit:number):{ids:string[];nextCursor:string|null} {
|
|
166
|
+
const filter="project_id=? AND COALESCE(json_extract(record_json,'$.archived'),0)=?";
|
|
167
|
+
if(cursor&&!this.db.query(`SELECT 1 FROM hx_sessions WHERE ${filter} AND id=?`).get(projectId,+archived,cursor))throw new HostError("CURSOR_INVALID");
|
|
168
|
+
const rows=this.db.query(`SELECT id FROM hx_sessions WHERE ${filter} AND id>? ORDER BY id LIMIT ?`).all(projectId,+archived,cursor??"",limit+1) as {id:string}[];
|
|
169
|
+
const ids=rows.slice(0,limit).map(row=>row.id);
|
|
170
|
+
return {ids,nextCursor:rows.length>limit?ids.at(-1)!:null};
|
|
171
|
+
}
|
|
172
|
+
publicSession(id:string):PublicSession {
|
|
173
|
+
const {inlineSubagents,nativeSubagents,binding,instructions,mcpServers,fallbackTitle,nativeTitle,workspaceBinding,admissionRef,uncertainRuntimeConfigIds,permissionDowngrade,permissionMode,...session}=this.session(id);
|
|
174
|
+
return {...session,pendingInteractions:this.interactions(id).filter(i=>i.state!=="resolved")};
|
|
175
|
+
}
|
|
176
|
+
hasLegacySubagentActivity(id:string):boolean {
|
|
177
|
+
return !!this.db.query('SELECT 1 FROM hx_events WHERE session_id=? AND type IN (?,?) AND json_extract(payload_json,?)=? LIMIT 1').get(id,'item/started','item/completed','$.event.payload.item.nativeType','subAgentActivity');
|
|
178
|
+
}
|
|
179
|
+
interactions(id:string):PublicInteraction[] {return (this.db.query("SELECT record_json FROM hx_interactions WHERE session_id=? ORDER BY id").all(id) as {record_json:string}[]).map(r=>JSON.parse(r.record_json) as PublicInteraction);}
|
|
180
|
+
interaction(id:string,interactionId:string):PublicInteraction {
|
|
181
|
+
const row=this.interactions(id).find(i=>i.interactionId===interactionId);if(!row)throw new HostError("INTERACTION_EXPIRED");return row;
|
|
182
|
+
}
|
|
183
|
+
saveInteraction(id:string,i:PublicInteraction):void {this.db.query("INSERT INTO hx_interactions(session_id,id,revision,state,record_json) VALUES(?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET revision=excluded.revision,state=excluded.state,record_json=excluded.record_json").run(id,i.interactionId,i.revision,i.state,JSON.stringify(i));}
|
|
184
|
+
append(id:string,event:HostEvent["event"],source?:{streamId:string;seq:number},scope:{turnId?:string;itemId?:string;bindingGeneration?:number}={},notifyCommit=true):HostEvent|undefined {
|
|
185
|
+
let committed:HostEvent|undefined;
|
|
186
|
+
this.db.transaction(()=>{
|
|
187
|
+
if(scope.bindingGeneration!==undefined&&scope.bindingGeneration!==(this.session(id).bindingGeneration??1))return;
|
|
188
|
+
if(source && this.db.query("SELECT 1 FROM hx_events WHERE session_id=? AND source_stream_id=? AND source_seq=?").get(id,source.streamId,source.seq))return;
|
|
189
|
+
if(source){const last=this.db.query("SELECT MAX(source_seq) AS seq FROM hx_events WHERE session_id=? AND source_stream_id=?").get(id,source.streamId) as {seq:number|null};if(source.seq!==(last.seq??0)+1)throw new HostError("SOURCE_SEQUENCE_GAP");}
|
|
190
|
+
const session=this.session(id),hostSeq=session.latestSeq+1,recordedAt=new Date().toISOString();
|
|
191
|
+
const safe=publicValue(event as unknown as JsonObject) as unknown as HostEvent["event"];
|
|
192
|
+
committed={sessionId:id,hostSeq,recordedAt,bindingGeneration:scope.bindingGeneration??session.bindingGeneration??1,...scope,...(source?{source}:{}),event:safe};
|
|
193
|
+
session.updatedAt=Date.now();
|
|
194
|
+
if(safe.type==="session/state") {
|
|
195
|
+
const state=safe.payload as SessionState;session.status=state.status;session.config=state.config;session.binding=state.binding;session.model=state.model;session.capabilities=state.capabilities;session.capabilityRevision=state.capabilityRevision;session.goal=state.goal;session.fastMode=state.fastMode;
|
|
196
|
+
this.applyMetadata(session,state.metadata);
|
|
197
|
+
} else if(safe.type==="session/metadata") {
|
|
198
|
+
this.applyMetadata(session,safe.payload);
|
|
199
|
+
} else if(safe.type==="turn/started") {
|
|
200
|
+
session.activeTurnId=safe.payload.turnId;session.status="running";
|
|
201
|
+
this.db.query("INSERT INTO hx_turns(session_id,turn_id,native_turn_id,status,execution_state) VALUES(?,?,?,'running','running') ON CONFLICT(session_id,turn_id) DO UPDATE SET native_turn_id=COALESCE(excluded.native_turn_id,hx_turns.native_turn_id)").run(id,safe.payload.turnId,safe.payload.nativeTurnId??null);
|
|
202
|
+
} else if(safe.type==="turn/completed") {
|
|
203
|
+
const old=this.db.query("SELECT terminal_host_seq FROM hx_turns WHERE session_id=? AND turn_id=?").get(id,safe.payload.turnId) as {terminal_host_seq:number|null}|null;
|
|
204
|
+
if(old?.terminal_host_seq!==null && old?.terminal_host_seq!==undefined){committed=undefined;return;}
|
|
205
|
+
const unknown=safe.payload.error?.outcomeUnknown===true;
|
|
206
|
+
this.db.query("INSERT INTO hx_turns(session_id,turn_id,status,execution_state,terminal_host_seq) VALUES(?,?,?,?,?) ON CONFLICT(session_id,turn_id) DO UPDATE SET status=excluded.status,execution_state=excluded.execution_state,terminal_host_seq=excluded.terminal_host_seq").run(id,safe.payload.turnId,safe.payload.status,unknown?"unknown":"stopped",hostSeq);
|
|
207
|
+
session.status=unknown?"recoveryRequired":"ready";delete session.activeTurnId;
|
|
208
|
+
} else if(safe.type==="interaction/requested") {
|
|
209
|
+
this.saveInteraction(id,{interactionId:safe.payload.interactionId,revision:0,state:"pending",request:publicInteraction(safe.payload)});
|
|
210
|
+
} else if(safe.type==="interaction/resolved") {
|
|
211
|
+
const row=this.interactions(id).find(i=>i.interactionId===safe.payload.interactionId);
|
|
212
|
+
if(row)this.saveInteraction(id,{...row,state:"resolved",revision:row.revision+1,resolution:safe.payload});
|
|
213
|
+
}
|
|
214
|
+
const eventTurnId=scope.turnId??("turnId"in safe.payload?String(safe.payload.turnId):undefined);
|
|
215
|
+
if(eventTurnId)this.db.query("UPDATE hx_turns SET binding_generation=? WHERE session_id=? AND turn_id=?").run(scope.bindingGeneration??session.bindingGeneration??1,id,eventTurnId);
|
|
216
|
+
this.hooks.beforeCommit?.();session.latestSeq=hostSeq;this.saveSession(session);
|
|
217
|
+
this.db.query("UPDATE hx_sessions SET last_host_seq=? WHERE id=?").run(hostSeq,id);
|
|
218
|
+
this.db.query("INSERT INTO hx_events(session_id,host_seq,source_stream_id,source_seq,type,turn_id,payload_json,created_at) VALUES(?,?,?,?,?,?,?,?)").run(id,hostSeq,source?.streamId??null,source?.seq??null,safe.type,scope.turnId??("turnId"in safe.payload?String(safe.payload.turnId):null),JSON.stringify(committed),recordedAt);
|
|
219
|
+
})();
|
|
220
|
+
if(committed&¬ifyCommit)this.hooks.afterCommit?.();return committed;
|
|
221
|
+
}
|
|
222
|
+
private applyMetadata(session:SessionRecord,metadata:SessionState["metadata"]):void {
|
|
223
|
+
if(!metadata||!Object.hasOwn(metadata,"title"))return;
|
|
224
|
+
session.nativeTitle=metadata.title;
|
|
225
|
+
session.title=session.nativeTitle?.trim()||session.fallbackTitle;
|
|
226
|
+
}
|
|
227
|
+
appendSource(event:AhpEvent,bindingGeneration?:number):HostEvent|undefined {const projected=publicEvent(event);return this.append(event.sessionId,{type:projected.type,payload:projected.payload} as HostEvent["event"],{streamId:event.streamId,seq:event.seq},{...(event.turnId?{turnId:event.turnId}:{}),...(event.itemId?{itemId:event.itemId}:{}),...(bindingGeneration?{bindingGeneration}:{})});}
|
|
228
|
+
boundary(sessionId:string,boundary:import("@anureo/protocol").Boundary):import("@anureo/protocol").Boundary {
|
|
229
|
+
const row=this.db.query("SELECT native_turn_id,binding_generation FROM hx_turns WHERE session_id=? AND turn_id=?").get(sessionId,boundary.turnId) as {native_turn_id:string|null;binding_generation:number}|null;
|
|
230
|
+
if(!row)throw new HostError("TURN_NOT_FOUND",`TURN_NOT_FOUND ${boundary.turnId} rows=${JSON.stringify(this.db.query("SELECT turn_id FROM hx_turns WHERE session_id=?").all(sessionId))}`);
|
|
231
|
+
if(row.binding_generation!==(this.session(sessionId).bindingGeneration??1))throw new HostError("BOUNDARY_GENERATION_MISMATCH");
|
|
232
|
+
return {...boundary,...(row.native_turn_id?{nativeTurnId:row.native_turn_id}:{})};
|
|
233
|
+
}
|
|
234
|
+
nativeTurn(sessionId:string,turnId?:string):string|undefined {
|
|
235
|
+
const row=(turnId?this.db.query("SELECT native_turn_id FROM hx_turns WHERE session_id=? AND turn_id=?").get(sessionId,turnId):this.db.query("SELECT native_turn_id FROM hx_turns WHERE session_id=? AND execution_state IN ('running','unknown') ORDER BY rowid DESC LIMIT 1").get(sessionId)) as {native_turn_id:string|null}|null;
|
|
236
|
+
return row?.native_turn_id??undefined;
|
|
237
|
+
}
|
|
238
|
+
executionTurnMap(sessionId: string, bindingGeneration: number): Map<string, string> {
|
|
239
|
+
// Older history reads could create extra rows for the same execution after resume.
|
|
240
|
+
// Restore only unambiguous associations recorded by the live lifecycle.
|
|
241
|
+
const rows = this.db.query(`
|
|
242
|
+
SELECT native_turn_id, MIN(turn_id) AS turn_id FROM hx_turns
|
|
243
|
+
WHERE session_id = ? AND binding_generation = ? AND execution_state <> 'history' AND native_turn_id IS NOT NULL
|
|
244
|
+
GROUP BY native_turn_id HAVING COUNT(*) = 1
|
|
245
|
+
`).all(sessionId, bindingGeneration) as { native_turn_id: string; turn_id: string }[];
|
|
246
|
+
return new Map(rows.map(row => [row.native_turn_id, row.turn_id]));
|
|
247
|
+
}
|
|
248
|
+
indexHistory(sessionId:string,page:HistoryPage):void {
|
|
249
|
+
this.db.transaction(()=>{
|
|
250
|
+
for(const entry of page.items){
|
|
251
|
+
const existing=this.db.query("SELECT native_turn_id FROM hx_turns WHERE session_id=? AND turn_id=?").get(sessionId,entry.turnId) as {native_turn_id:string|null}|null;
|
|
252
|
+
if(existing?.native_turn_id&&entry.nativeTurnId&&existing.native_turn_id!==entry.nativeTurnId)throw new HostError("HISTORY_IDENTITY_MISMATCH");
|
|
253
|
+
this.db.query("INSERT INTO hx_turns(session_id,turn_id,native_turn_id,status,execution_state,binding_generation) VALUES(?,?,?,'history','history',?) ON CONFLICT(session_id,turn_id) DO UPDATE SET native_turn_id=COALESCE(hx_turns.native_turn_id,excluded.native_turn_id)").run(sessionId,entry.turnId,entry.nativeTurnId??null,this.session(sessionId).bindingGeneration??1);
|
|
254
|
+
}
|
|
255
|
+
})();
|
|
256
|
+
}
|
|
257
|
+
events(id:string,afterSeq=0,throughSeq?:number,limit=200):EventPage {
|
|
258
|
+
const latestSeq=this.session(id).latestSeq,end=throughSeq??latestSeq;
|
|
259
|
+
if(!Number.isSafeInteger(afterSeq)||!Number.isSafeInteger(end)||afterSeq<0||afterSeq>end||end>latestSeq||!Number.isSafeInteger(limit)||limit<1||limit>1000)throw new HostError("CURSOR_INVALID");
|
|
260
|
+
const events=(this.db.query("SELECT payload_json FROM hx_events WHERE session_id=? AND host_seq>? AND host_seq<=? ORDER BY host_seq LIMIT ?").all(id,afterSeq,end,limit) as {payload_json:string}[]).map(r=>JSON.parse(r.payload_json) as HostEvent);
|
|
261
|
+
const nextAfterSeq=events.at(-1)?.hostSeq??afterSeq;
|
|
262
|
+
return {events,nextAfterSeq,hasMore:nextAfterSeq<end,latestSeq,earliestSeq:1,throughSeq:end};
|
|
263
|
+
}
|
|
264
|
+
projectionSnapshot(id:string):{projectionVersion:number;seq:number;checkpointJson:string}|undefined {
|
|
265
|
+
const row=this.db.query("SELECT projection_version,seq,checkpoint_json FROM hx_projection_snapshots WHERE session_id=?").get(id) as {projection_version:number;seq:number;checkpoint_json:string}|null;
|
|
266
|
+
return row?{projectionVersion:row.projection_version,seq:row.seq,checkpointJson:row.checkpoint_json}:undefined;
|
|
267
|
+
}
|
|
268
|
+
saveProjectionSnapshot(id:string,projectionVersion:number,seq:number,checkpointJson:string):void {
|
|
269
|
+
this.db.query("INSERT INTO hx_projection_snapshots(session_id,projection_version,seq,checkpoint_json,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(session_id) DO UPDATE SET projection_version=excluded.projection_version,seq=excluded.seq,checkpoint_json=excluded.checkpoint_json,updated_at=excluded.updated_at").run(id,projectionVersion,seq,checkpointJson,Date.now());
|
|
270
|
+
}
|
|
271
|
+
operation(id:string):{row:OperationRow;value:OperationResult}|undefined {
|
|
272
|
+
const row=this.db.query("SELECT * FROM hx_operations WHERE id=?").get(id) as OperationRow|null;
|
|
273
|
+
return row?{row,value:JSON.parse(row.result_json) as OperationResult}:undefined;
|
|
274
|
+
}
|
|
275
|
+
lookup(principal:string,method:string,target:string,key:string):ReturnType<HarnessStore["operation"]> {
|
|
276
|
+
const row=this.db.query("SELECT id FROM hx_operations WHERE principal_id=? AND method=? AND target=? AND idempotency_key=?").get(principal,method,target,key) as {id:string}|null;
|
|
277
|
+
return row?this.operation(row.id):undefined;
|
|
278
|
+
}
|
|
279
|
+
beginOperation(id:string,principal:string,method:string,target:string,key:string,digest:string,sessionId?:string,turnId?:string):OperationResult {
|
|
280
|
+
const value:OperationResult={operationId:id,state:"accepted",outcomeUnknown:false,...(sessionId?{sessionId}:{}),...(turnId?{turnId}:{})};
|
|
281
|
+
this.db.query("INSERT INTO hx_operations(id,principal_id,method,target,idempotency_key,request_digest,phase,state,session_id,turn_id,result_json) VALUES(?,?,?,?,?,?,'accepted','accepted',?,?,?)").run(id,principal,method,target,key,digest,sessionId??null,turnId??null,JSON.stringify(value));return value;
|
|
282
|
+
}
|
|
283
|
+
phase(id:string,phase:string):void {this.db.query("UPDATE hx_operations SET phase=? WHERE id=?").run(phase,id);}
|
|
284
|
+
finishOperation(value:OperationResult):OperationResult {
|
|
285
|
+
const safe=publicValue(value as unknown as JsonObject) as unknown as OperationResult;
|
|
286
|
+
this.db.query("UPDATE hx_operations SET state=?,result_json=?,session_id=COALESCE(?,session_id) WHERE id=?").run(safe.state,JSON.stringify(safe),safe.sessionId??null,safe.operationId);return safe;
|
|
287
|
+
}
|
|
288
|
+
incomplete():{row:OperationRow;value:OperationResult}[] {
|
|
289
|
+
return (this.db.query("SELECT id FROM hx_operations WHERE state='accepted' OR state='unknown'").all() as {id:string}[]).map(({id})=>this.operation(id)!);
|
|
290
|
+
}
|
|
291
|
+
recover():void {
|
|
292
|
+
for(const {row,value} of this.incomplete()) {
|
|
293
|
+
if(value.state==="unknown")continue;
|
|
294
|
+
const unknown=row.phase!=="accepted";
|
|
295
|
+
this.finishOperation({...value,state:unknown?"unknown":"failed",outcomeUnknown:unknown,error:{code:unknown?"RESULT_UNKNOWN":"NOT_DISPATCHED",message:unknown?"RESULT_UNKNOWN":"NOT_DISPATCHED",retryable:false,outcomeUnknown:unknown}});
|
|
296
|
+
if(unknown && row.session_id && this.db.query("SELECT id FROM hx_sessions WHERE id=?").get(row.session_id)){const s=this.session(row.session_id);s.status="recoveryRequired";this.saveSession(s);}
|
|
297
|
+
}
|
|
298
|
+
for(const s of this.sessions()){
|
|
299
|
+
const queue=this.queue(s.id);if(queue.items.some(item=>["dispatching","running"].includes(item.state)))this.mutateQueue(s.id,undefined,state=>{for(const item of state.items)if(["dispatching","running"].includes(item.state)){item.state="unknown";item.updatedAt=Date.now();item.error={code:"RESULT_UNKNOWN",message:"RESULT_UNKNOWN",retryable:false,outcomeUnknown:true};}state.paused=true;});
|
|
300
|
+
const wasRunning=s.status==="running"||!!s.activeTurnId;
|
|
301
|
+
if(wasRunning){s.status="recoveryRequired";this.saveSession(s);this.append(s.id,{type:"host/turnObservationEnded",payload:{turnId:s.activeTurnId??null,nativeExecutionUnknown:true}});}
|
|
302
|
+
const pending=this.interactions(s.id).filter(i=>i.state!=="resolved");
|
|
303
|
+
if(pending.length){const current=this.session(s.id);current.status="recoveryRequired";this.saveSession(current);}
|
|
304
|
+
else if(!wasRunning&&s.status!=="recoveryRequired"){s.status="closed";this.saveSession(s);}
|
|
305
|
+
for(const i of pending)this.append(s.id,{type:"interaction/resolved",payload:{interactionId:i.interactionId,outcome:"unknown",reason:"HOST_RESTARTED"}});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
reconcileStopped(observed:SessionRecord,live:boolean,evidenceRef?:string):HostEvent[] {
|
|
309
|
+
const committed=this.db.transaction(()=>{
|
|
310
|
+
const id=observed.id;
|
|
311
|
+
const current=this.session(id);
|
|
312
|
+
const generation=current.bindingGeneration??1;
|
|
313
|
+
if(generation!==(observed.bindingGeneration??1)||current.activeTurnId!==observed.activeTurnId||current.uncertainRuntimeConfigIds?.length)return [];
|
|
314
|
+
const turnId=current.activeTurnId;
|
|
315
|
+
const affected=this.queue(id).items.filter(item=>item.bindingGeneration===generation&&(item.state==="unknown"||item.turnId===turnId&&["dispatching","running"].includes(item.state)));
|
|
316
|
+
if(current.status!=="recoveryRequired"&&!affected.length)return [];
|
|
317
|
+
if(current.status!==observed.status)return [];
|
|
318
|
+
current.status=live?"ready":"closed";
|
|
319
|
+
delete current.activeTurnId;
|
|
320
|
+
this.saveSession(current);
|
|
321
|
+
const events:HostEvent[]=[];
|
|
322
|
+
const recovery=this.append(id,{type:"host/recovery",payload:{stopped:true,turnId:turnId??null,evidenceRef:evidenceRef??null}},undefined,{bindingGeneration:generation,...(turnId?{turnId}:{})},false);
|
|
323
|
+
if(recovery)events.push(recovery);
|
|
324
|
+
if(turnId&&recovery)this.db.query("UPDATE hx_turns SET status='interrupted',execution_state='stopped',terminal_host_seq=? WHERE session_id=? AND turn_id=? AND binding_generation=? AND terminal_host_seq IS NULL").run(recovery.hostSeq,id,turnId,generation);
|
|
325
|
+
if(affected.length){
|
|
326
|
+
const ids=new Set(affected.map(item=>item.id));
|
|
327
|
+
const queue=this.mutateQueue(id,undefined,state=>{
|
|
328
|
+
state.paused=true;
|
|
329
|
+
for(const item of state.items){
|
|
330
|
+
if(!ids.has(item.id))continue;
|
|
331
|
+
item.state="failed";
|
|
332
|
+
item.updatedAt=Date.now();
|
|
333
|
+
item.error={code:"RESULT_UNKNOWN_STOPPED",message:"Execution is stopped; its original result remains unknown",retryable:false,outcomeUnknown:true};
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
const queueEvent=this.append(id,{type:"host/queue",payload:{queue:publicQueue(queue) as unknown as JsonObject}},undefined,{},false);
|
|
337
|
+
if(queueEvent)events.push(queueEvent);
|
|
338
|
+
}
|
|
339
|
+
return events;
|
|
340
|
+
})();
|
|
341
|
+
for(const _event of committed)this.hooks.afterCommit?.();
|
|
342
|
+
return committed;
|
|
343
|
+
}
|
|
344
|
+
queue(id:string):StoredQueueState {
|
|
345
|
+
this.session(id);
|
|
346
|
+
const state=this.db.query("SELECT revision,paused FROM hx_queue_states WHERE session_id=?").get(id) as {revision:number;paused:number}|null;
|
|
347
|
+
const rows=this.db.query("SELECT record_json FROM hx_queue_items WHERE session_id=? AND state NOT IN ('completed','cancelled') ORDER BY position,id").all(id) as {record_json:string}[];
|
|
348
|
+
return {revision:state?.revision??0,paused:state?.paused===1,items:rows.map(row=>JSON.parse(row.record_json) as StoredQueueItem)};
|
|
349
|
+
}
|
|
350
|
+
mutateQueue(id:string,expectedRevision:number|undefined,update:(state:StoredQueueState)=>void):StoredQueueState {
|
|
351
|
+
let changed!:StoredQueueState;
|
|
352
|
+
this.db.transaction(()=>{
|
|
353
|
+
const state=this.queue(id);if(expectedRevision!==undefined&&state.revision!==expectedRevision)throw new HostError("QUEUE_REVISION_CONFLICT");
|
|
354
|
+
const previous=state.items.map(item=>item.id);update(state);state.revision++;
|
|
355
|
+
this.db.query("INSERT INTO hx_queue_states(session_id,revision,paused) VALUES(?,?,?) ON CONFLICT(session_id) DO UPDATE SET revision=excluded.revision,paused=excluded.paused").run(id,state.revision,state.paused?1:0);
|
|
356
|
+
for(const old of previous)if(!state.items.some(item=>item.id===old)){
|
|
357
|
+
const row=this.db.query("SELECT record_json FROM hx_queue_items WHERE session_id=? AND id=?").get(id,old) as {record_json:string};const item=JSON.parse(row.record_json) as StoredQueueItem;item.state="cancelled";item.updatedAt=Date.now();
|
|
358
|
+
this.db.query("UPDATE hx_queue_items SET state='cancelled',record_json=? WHERE session_id=? AND id=?").run(JSON.stringify(item),id,old);
|
|
359
|
+
}
|
|
360
|
+
state.items.forEach((item,index)=>this.db.query("INSERT INTO hx_queue_items(session_id,id,position,state,record_json) VALUES(?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET position=excluded.position,state=excluded.state,record_json=excluded.record_json").run(id,item.id,index,item.state,JSON.stringify(item)));
|
|
361
|
+
changed={...state,items:state.items.filter(queuePending)};
|
|
362
|
+
})();return changed;
|
|
363
|
+
}
|
|
364
|
+
queueItem(id:string,itemId:string):StoredQueueItem {
|
|
365
|
+
const row=this.db.query("SELECT record_json FROM hx_queue_items WHERE session_id=? AND id=?").get(id,itemId) as {record_json:string}|null;
|
|
366
|
+
if(!row)throw new HostError("QUEUE_ITEM_NOT_FOUND");return JSON.parse(row.record_json) as StoredQueueItem;
|
|
367
|
+
}
|
|
368
|
+
/** 会话是否已开始:已执行过 turn(hx_turns,含 native 历史 index)或携带继承的 turn 输入事件(fork)。>0 即 Harness 锁定。 */
|
|
369
|
+
executedTurns(id:string):boolean {
|
|
370
|
+
if(this.session(id)?.parent)return true;
|
|
371
|
+
if((this.db.query("SELECT COUNT(*) AS count FROM hx_turns WHERE session_id=?").get(id) as {count:number}).count>0)return true;
|
|
372
|
+
return ((this.db.query("SELECT COUNT(*) AS count FROM hx_events WHERE session_id=? AND type='host/turnInput'").get(id) as {count:number}).count>0);
|
|
373
|
+
}
|
|
374
|
+
clearEvidence(id:string,generation:number,key:string):void {this.db.query("DELETE FROM hx_execution_evidence WHERE session_id=? AND binding_generation=? AND turn_id=?").run(id,generation,key);}
|
|
375
|
+
recordEvidence(id:string,generation:number,turnId:string,evidence:JsonObject):void {
|
|
376
|
+
this.db.query("INSERT INTO hx_execution_evidence(session_id,binding_generation,turn_id,evidence_json) VALUES(?,?,?,?) ON CONFLICT(session_id,binding_generation,turn_id) DO UPDATE SET evidence_json=excluded.evidence_json").run(id,generation,turnId,JSON.stringify(evidence));
|
|
377
|
+
}
|
|
378
|
+
evidence(id:string,generation:number,turnId:string):JsonObject|undefined {
|
|
379
|
+
const row=this.db.query("SELECT evidence_json FROM hx_execution_evidence WHERE session_id=? AND binding_generation=? AND turn_id=?").get(id,generation,turnId) as {evidence_json:string}|null;return row?JSON.parse(row.evidence_json) as JsonObject:undefined;
|
|
380
|
+
}
|
|
381
|
+
operationStopped(id:string,operationId:string):boolean {
|
|
382
|
+
const rows=this.db.query("SELECT evidence_json FROM hx_execution_evidence WHERE session_id=? AND turn_id=?").all(id,`operation:${operationId}`) as {evidence_json:string}[];
|
|
383
|
+
return rows.some(row=>(JSON.parse(row.evidence_json) as JsonObject).quiescent===true);
|
|
384
|
+
}
|
|
385
|
+
usage(id:string):Usage|null {
|
|
386
|
+
const rows=this.db.query("SELECT payload_json FROM hx_events WHERE session_id=? AND type IN ('turn/completed','usage/updated') ORDER BY host_seq").all(id) as {payload_json:string}[];
|
|
387
|
+
const groups=new Map<number,{turns:Map<string,Usage>;cumulative?:Usage;cumulativeTurnId?:string;missing:Set<string>}>();
|
|
388
|
+
for(const row of rows){const event=JSON.parse(row.payload_json) as HostEvent,value=event.event.type==="turn/completed"?event.event.payload.usage:event.event.type==="usage/updated"?event.event.payload:undefined;
|
|
389
|
+
const generation=event.bindingGeneration??1,group=groups.get(generation)??{turns:new Map<string,Usage>(),missing:new Set<string>()};groups.set(generation,group);
|
|
390
|
+
const turnId=event.turnId??(event.event.type==="turn/completed"?event.event.payload.turnId:undefined);
|
|
391
|
+
if(value?.scope==="session"){group.cumulative=value;group.cumulativeTurnId=turnId;group.missing.clear();}else if(value&&turnId){group.turns.set(turnId,value);group.missing.delete(turnId);}else if(event.event.type==="turn/completed"&&turnId&&!group.turns.has(turnId)&&group.cumulativeTurnId!==turnId)group.missing.add(turnId);
|
|
392
|
+
}
|
|
393
|
+
const sum=(values:Usage[],key:keyof Usage)=>values.every(value=>typeof value[key]==="number")?values.reduce((n,value)=>n+(value[key] as number),0):undefined;
|
|
394
|
+
const aggregate=(values:Usage[]):Usage=>({provider:new Set(values.map(value=>value.provider)).size===1?values[0]!.provider:"mixed",scope:"session",source:"native",...Object.fromEntries((["input","output","total","cacheRead","cacheWrite"] as const).flatMap(key=>{const value=sum(values,key);return value===undefined?[]:[[key,value]];}))});
|
|
395
|
+
if([...groups.values()].some(group=>group.missing.size))return null;
|
|
396
|
+
const values=[...groups.values()].flatMap(group=>group.cumulative?[group.cumulative]:group.turns.size?[aggregate([...group.turns.values()])]:[]);
|
|
397
|
+
return values.length?aggregate(values):null;
|
|
398
|
+
}
|
|
399
|
+
checksum():string {return createHash("sha256").update(JSON.stringify(this.sessions())).digest("hex");}
|
|
400
|
+
close():void {
|
|
401
|
+
if(this.closed)return;
|
|
402
|
+
this.closed=true;
|
|
403
|
+
try { this.db.close(); } finally { this.ownership?.close(); }
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export type HostStorage=Omit<SqliteHostStore,"db"|"file"|"catalog">&{readonly catalog:CatalogStorage};
|
|
408
|
+
export type HarnessStore=HostStorage;
|
package/src/subagents.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import type { HistoryPage, Item, NativeRef } from '@anureo/protocol'
|
|
3
|
+
import type { HxSubagent } from './legacy-protocol'
|
|
4
|
+
import type { HarnessStore, SessionRecord } from './store'
|
|
5
|
+
import { HostError } from './errors'
|
|
6
|
+
|
|
7
|
+
export type StoredInlineSubagent = {
|
|
8
|
+
summary: HxSubagent
|
|
9
|
+
subagentId: string
|
|
10
|
+
bindingGeneration: number
|
|
11
|
+
assignments: Array<{ turnId: string; itemId: string }>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type StoredSubagent = {
|
|
15
|
+
summary: HxSubagent
|
|
16
|
+
nativeRef: NativeRef
|
|
17
|
+
parentNativeRef: NativeRef
|
|
18
|
+
bindingGeneration: number
|
|
19
|
+
runtimeConfigId: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A reader must verify the direct native spawn edge and must not resume the thread. */
|
|
23
|
+
export type SubagentHistoryPort = (context: {
|
|
24
|
+
parentNativeRef: NativeRef; nativeRef: NativeRef; cwd: string; cursor?: string; limit?: number
|
|
25
|
+
}) => Promise<HistoryPage>
|
|
26
|
+
|
|
27
|
+
export type SubagentDiscoveryPort = (context: { parentNativeRef: NativeRef; cwd: string }) => Promise<Array<{
|
|
28
|
+
id: string; parentThreadId?: string; name?: string; task?: string
|
|
29
|
+
}>>
|
|
30
|
+
|
|
31
|
+
export function publicSubagents(record: SessionRecord, canRead: (runtimeConfigId: string) => boolean): HxSubagent[] {
|
|
32
|
+
return [...(record.nativeSubagents ?? []).map(child => ({ ...child.summary, canOpen: canRead(child.runtimeConfigId) })), ...(record.inlineSubagents ?? []).map(child => ({ ...child.summary, canOpen: true }))]
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Register a sanitized structured identity, scoped to the parent's binding generation. */
|
|
36
|
+
export function registerSubagent(store: HarnessStore, record: SessionRecord, item: Extract<Item, { type: 'subagent' }>, canOpen: boolean, parentTurnId?: string, preserveLifecycle = false): { item: Item; summary?: HxSubagent; changed: boolean } {
|
|
37
|
+
const { coworkSubagent: _untrusted, ...extensions } = item.extensions ?? {}
|
|
38
|
+
const parentNativeRef = record.binding.nativeRef
|
|
39
|
+
if (!parentNativeRef && record.capabilities?.subagents?.events === 'nested' && !item.parentItemId && parentTurnId) {
|
|
40
|
+
const children = record.inlineSubagents ?? []
|
|
41
|
+
const generation = record.bindingGeneration ?? 1
|
|
42
|
+
const previous = children.find(child => child.subagentId === item.subagentId && child.bindingGeneration === generation)
|
|
43
|
+
const now = Date.now()
|
|
44
|
+
const summary: HxSubagent = {
|
|
45
|
+
...(previous?.summary ?? { sessionId: randomUUID(), parentSessionId: record.id, createdAt: now }),
|
|
46
|
+
parentTurnId,
|
|
47
|
+
name: item.name || previous?.summary.name || '', task: item.task ?? previous?.summary.task,
|
|
48
|
+
status: preserveLifecycle && previous ? previous.summary.status : item.state === 'pending' ? 'running' : item.state,
|
|
49
|
+
canOpen: true, updatedAt: previous?.summary.updatedAt ?? now,
|
|
50
|
+
}
|
|
51
|
+
const assignments = previous?.assignments ?? []
|
|
52
|
+
const known = assignments.some(assignment => assignment.turnId === parentTurnId && assignment.itemId === item.id)
|
|
53
|
+
const changed = !previous || !known || JSON.stringify(summary) !== JSON.stringify(previous.summary)
|
|
54
|
+
if (changed) {
|
|
55
|
+
summary.updatedAt = now
|
|
56
|
+
const child: StoredInlineSubagent = { summary, subagentId: item.subagentId, bindingGeneration: generation, assignments: known ? assignments : [...assignments, { turnId: parentTurnId, itemId: item.id }] }
|
|
57
|
+
record.inlineSubagents = [...children.filter(candidate => candidate !== previous), child]
|
|
58
|
+
store.saveSession(record)
|
|
59
|
+
}
|
|
60
|
+
return { item: { ...item, extensions: { ...extensions, coworkSubagent: { ...summary } } }, summary, changed }
|
|
61
|
+
}
|
|
62
|
+
if (!parentNativeRef || item.subagentId === parentNativeRef.value) return { item: { ...item, extensions }, changed: false }
|
|
63
|
+
const children = record.nativeSubagents ?? []
|
|
64
|
+
const bindingGeneration = record.bindingGeneration ?? 1
|
|
65
|
+
const existing = children.find(child => child.bindingGeneration === bindingGeneration && child.runtimeConfigId === record.runtimeConfigId && child.nativeRef.provider === parentNativeRef.provider && child.nativeRef.value === item.subagentId)
|
|
66
|
+
const now = Date.now()
|
|
67
|
+
const summary: HxSubagent = {
|
|
68
|
+
...(existing?.summary ?? { sessionId: randomUUID(), parentSessionId: record.id, createdAt: now }),
|
|
69
|
+
name: item.name || existing?.summary.name || '',
|
|
70
|
+
...(parentTurnId && !existing?.summary.parentTurnId ? { parentTurnId } : {}),
|
|
71
|
+
...(item.task !== undefined ? { task: item.task } : {}),
|
|
72
|
+
// Historical spawn records and repeated discovery cannot rewind a later live state.
|
|
73
|
+
status: preserveLifecycle && existing ? existing.summary.status : item.state === 'pending' ? 'running' : item.state,
|
|
74
|
+
canOpen, updatedAt: existing?.summary.updatedAt ?? now,
|
|
75
|
+
}
|
|
76
|
+
const changed = !existing || JSON.stringify(summary) !== JSON.stringify(existing.summary)
|
|
77
|
+
if (changed) {
|
|
78
|
+
summary.updatedAt = now
|
|
79
|
+
const child: StoredSubagent = { summary, nativeRef: { provider: parentNativeRef.provider, value: item.subagentId }, parentNativeRef, bindingGeneration, runtimeConfigId: record.runtimeConfigId }
|
|
80
|
+
record.nativeSubagents = [...children.filter(candidate => candidate !== existing), child]
|
|
81
|
+
store.saveSession(record)
|
|
82
|
+
}
|
|
83
|
+
return { item: { ...item, extensions: { ...extensions, coworkSubagent: { ...summary } } }, summary, changed }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Read member evidence from the parent's durable nested items, without opening a native thread. */
|
|
87
|
+
export interface SubagentTurn {
|
|
88
|
+
id: string
|
|
89
|
+
items: readonly { item: Item }[]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function inlineSubagentHistory(turns: readonly SubagentTurn[], child: StoredInlineSubagent, cursor?: string, limit = 50): HistoryPage {
|
|
93
|
+
const items: HistoryPage['items'] = []
|
|
94
|
+
for (const turn of turns) {
|
|
95
|
+
const roots = new Set(child.assignments.filter(assignment => assignment.turnId === turn.id).map(assignment => assignment.itemId))
|
|
96
|
+
if (!roots.size) continue
|
|
97
|
+
const owned = new Set(roots)
|
|
98
|
+
let changed = true
|
|
99
|
+
while (changed) {
|
|
100
|
+
changed = false
|
|
101
|
+
for (const { item } of turn.items) if (item.parentItemId && owned.has(item.parentItemId) && !owned.has(item.id)) { owned.add(item.id); changed = true }
|
|
102
|
+
}
|
|
103
|
+
for (const { item } of turn.items) {
|
|
104
|
+
if (!owned.has(item.id) || roots.has(item.id)) continue
|
|
105
|
+
const copy = { ...item }
|
|
106
|
+
if (copy.parentItemId && roots.has(copy.parentItemId)) delete copy.parentItemId
|
|
107
|
+
items.push({ turnId: turn.id, item: copy })
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (cursor !== undefined && !/^(0|[1-9][0-9]*)$/.test(cursor)) throw new HostError('CURSOR_INVALID')
|
|
111
|
+
const end = cursor === undefined ? items.length : Number(cursor)
|
|
112
|
+
if (!Number.isSafeInteger(end) || end < 0 || end > items.length) throw new HostError('CURSOR_INVALID')
|
|
113
|
+
const start = Math.max(0, end - limit)
|
|
114
|
+
return { items: items.slice(start, end), nextCursor: start > 0 ? String(start) : null }
|
|
115
|
+
}
|