@asaidimu/utils-workspace 6.6.9 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/index.d.mts +2728 -2614
  2. package/index.d.ts +2728 -2614
  3. package/index.js +1 -1
  4. package/index.mjs +1 -1
  5. package/package.json +3 -2
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("@asaidimu/utils-events"),t=require("uuid"),s=Object.defineProperty,i=[async e=>{const t=await e.workspaceStore.list();if(0===t.length)return{};const s=t[0];return{id:s.id,settings:s.settings,project:s.project}},async e=>{const t=await e.roles.list(),s={};for(const i of t)s[i.name]=e.roles.summarize(i);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const i of t)s[i.id]=e.preferences.summarize(i);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const i of t)s[i.key]=e.context.summarize(i);return{index:{context:s}}},async e=>{const t=await e.artifacts.list(),s={};for(const i of t)s[i.key]=e.artifacts.summarize(i);return{index:{artifacts:s}}},async e=>{const t=await e.sessions.list(),s={};for(const i of t)s[i.id]=e.sessions.summarize(i);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const i of t)s[i.name]=e.topics.summarize(i);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],r=[{name:"workspace",version:"1.0.0",description:"Workspace root containing global settings and project metadata.",fields:{id:{name:"id",type:"string",required:!0},settings:{name:"settings",type:"record",required:!0},project:{name:"project",type:"record",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"}],constraints:[],migrations:[]},{name:"role",version:"1.0.0",description:"AI persona with a system prompt and associated preference defaults.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},topics:{name:"topics",type:"array",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_label",fields:["label"],type:"normal"}],constraints:[],migrations:[]},{name:"preference",version:"1.0.0",description:"A user behavioural instruction, scoped to zero or more topics.",fields:{id:{name:"id",type:"string",required:!0},content:{name:"content",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},timestamp:{name:"timestamp",type:"string",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"context",version:"1.0.0",description:"Injected background knowledge, scoped to topics. Content is a discriminated union.",fields:{key:{name:"key",type:"string",required:!0},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},content:{name:"content",type:"record",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_timestamp",fields:["timestamp"],type:"btree"}],constraints:[],migrations:[]},{name:"session",version:"1.0.0",description:"Session metadata. The head field tracks the current tip of the turn DAG.",fields:{id:{name:"id",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!0,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!1,itemsType:"string"},context:{name:"context",type:"array",required:!1,itemsType:"string"},artifacts:{name:"artifacts",type:"array",required:!1,itemsType:"string"},metadata:{name:"metadata",type:"record",required:!1},head:{name:"head",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"}],constraints:[],migrations:[]},{name:"turn",version:"1.0.0",description:["A single message in a session transcript, stored as a flat document.","The DAG is reconstructed in memory by TurnTree.buildNodeGraph() at session open time."].join(" "),fields:{id:{name:"id",type:"string",required:!0},session:{name:"session",type:"string",required:!0},version:{name:"version",type:"number",required:!0},actor:{name:"actor",type:"enum",required:!0,values:["user","assistant","tool"]},blocks:{name:"blocks",type:"array",required:!0},timestamp:{name:"timestamp",type:"string",required:!0},role:{name:"role",type:"string",required:!1},model:{name:"model",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1},constraints:{name:"constraints",type:"record",required:!1},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_session",fields:["session"],type:"normal"},{name:"by_session_parent",fields:["session","parent"],type:"composite"},{name:"by_session_id_ver",fields:["session","id","version"],type:"composite",unique:!0}],constraints:[],migrations:[]},{name:"topic",version:"1.0.0",description:"A categorization for context and preferences, used for retrieval.",fields:{name:{name:"name",type:"string",required:!0},label:{name:"label",type:"string",required:!1},description:{name:"description",type:"string",required:!1},metadata:{name:"metadata",type:"record",required:!1},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0}},indexes:[{name:"by_name",fields:["name"],type:"unique"}],constraints:[],migrations:[]},{name:"artifact",version:"1.0.0",description:"A first-class content block produced during a conversation.",fields:{id:{name:"id",type:"string",required:!0},type:{name:"type",type:"string",required:!0},key:{name:"key",type:"string",required:!0},version:{name:"version",type:"number",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!0},content:{name:"content",type:"record",required:!0},status:{name:"status",type:"enum",required:!0,values:["complete","draft"]},topics:{name:"topics",type:"array",required:!1,itemsType:"string"},created:{name:"created",type:"string",required:!1},updated:{name:"updated",type:"string",required:!1},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_key",fields:["key"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"},{name:"by_updated",fields:["updated"],type:"btree"}],constraints:[],migrations:[]}],n={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},o=new Map;var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const s={...function(e){const t=Object.values(n).find((t=>t.code===e));if(t)return t;return o.get(e)||{code:e,name:e.replace(/-/g,"_"),description:`Unknown error: ${e}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}(t.code),...t.metadata,code:t.code};super(t.message??s.description),this.name="SystemError",this.code=t.code,this.codeMetadata=s,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}toLogEntry(){return{name:this.name,code:this.code,category:this.codeMetadata.category,message:this.message,path:this.path,operation:this.operation,issues:this.issues,cause:this.cause instanceof Error?this.cause.message:this.cause,stack:this.stack,timestamp:(new Date).toISOString()}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map(((e,t)=>` ${t+1}. ${e.message} [${e.code}]`)).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}},c=class e extends a{constructor(t,s){super({code:"SYNC_ERROR",message:t,cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},d=class e extends c{constructor(t){super(`[ArtifactContainer] Operation timed out: ${t}`),this.name="TimeoutError",Object.setPrototypeOf(this,e.prototype)}},l=class e extends c{constructor(t){super("[Serializer] The serializer has been marked as done!",t),this.name="SerializerExecutionDone",Object.setPrototypeOf(this,e.prototype)}},u=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const s=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await s;let i;await Promise.race([s.then((()=>clearTimeout(i))),new Promise(((s,r)=>{i=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),r(new d("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},p=class{mutex=new u({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,s="Operation timed out"){if(null==t)return e;let i;return Promise.race([e.then((e=>(clearTimeout(i),e))),new Promise(((e,r)=>{i=setTimeout((()=>r(new d(s))),t)}))])}},h=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new u({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new l};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,i=null;try{if(this._done)throw new l;i=await e(),this._lastValue=i,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:i,error:s}}peek(){return{value:this._lastValue,error:this._lastError}}hasRun(){return this._hasRun}close(){this._done=!0}pending(){return this.mutex.pending()}running(){return this.mutex.locked()}};function m(e){const t=new p({retry:!0,throws:!0}),s=new p({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...r,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var f={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic",ARTIFACT:"artifact"},y=Symbol.for("delete"),g=e=>Array.isArray(e)?[...e]:{...e};function w(e){return{ok:!0,value:e}}function b(e){return{ok:!1,error:e}}var k=function(e){const t=e?.deleteMarker||y;function s(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:s(e)));if("object"==typeof e){const i={};for(const[r,n]of Object.entries(e))if(n!==t)if("object"==typeof n&&null!==n){const e=s(n);void 0!==e&&(i[r]=e)}else i[r]=n;return i}return e===t?void 0:e}return function(e,i){if("object"!=typeof e||null===e)return"object"==typeof i&&null!==i?s(i):i===t?{}:i;if("object"!=typeof i||null===i)return e;const r=g(e),n=[{target:r,source:i}];for(;n.length>0;){const{target:e,source:s}=n.pop();for(const i of Object.keys(s)){const r=s[i];if(r!==t)if(Array.isArray(r))e[i]=r;else if("object"==typeof r&&null!==r){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=g(t),n.push({target:e[i],source:r})}else e[i]=r;else delete e[i]}}return r}}({deleteMarker:y});async function v(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}function x(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let s=0;s<e.length;s+=32768){const i=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(i)))}return btoa(t.join(""))}function O(e,t=4){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return((s>>>0)%36**t).toString(36).padStart(t,"0")}function S(e){let t="# CHECKPOINT";const s=(e,s)=>{s&&s.length>0&&(t+=`## ${e}\n\n`,s.forEach((e=>{t+=`- ${e}\n`})),t+="\n")};return s("Summary",[e.summary]),s("Objectives",e.objectives),s("Facts",e.facts),s("Constraints",e.constraints),s("Decisions",e.decisions),s("Assumptions",e.assumptions),s("Unresolved",e.unresolved),s("Notes",e.notes),t}var _=class{registry=new Map;middlewares=[];serializer=new h;bus;_getWorkspace;updateWorkspace;guard;_ctx;constructor(e){this._ctx=e.ctx,this._getWorkspace=e.getWorkspace,this.updateWorkspace=e.updateWorkspace,this.guard=e.guard,this.bus=e.bus}register(e,t){return this.registry.set(e,t),this}use(e){return this.middlewares.push(e),this}workspace(){return this._getWorkspace()}async dispatch(e){const t=await this.serializer.do((async()=>{if(this.guard){const t=await this.guard.authenticate({type:"command",payload:e});if(!t.ok)return b(t.error)}const t=this.registry.get(e.type);if(!t)return b({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),i=await t({workspace:s,...this._ctx},e.payload);if(!i.ok)return i;let r=i.value;for(const t of this.middlewares){const i=await t({workspace:s,command:e,patch:r,...this._ctx});r=k(r,i)}return await this.updateWorkspace(r),this.bus.emit({name:"workspace:changed",payload:r}),"workspace:sync"===e.type&&this.bus.emit({name:"workspace:synced",payload:void 0}),w(r)}));if(t.error)throw t.error;return t.value}subscribe(e,t){return this.bus.subscribe(e,t)}ctx(){return{workspace:this._getWorkspace(),...this._ctx}}},T=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async getMany(e){if(0===e.length)return[];const t=[],s=[];for(const i of e){const e=this.cache.get(i);e?t.push(e):s.push(i)}if(s.length>0){const e=await this.collection.filter({operator:"or",conditions:s.map((e=>({field:"name",operator:"eq",value:e})))});for(const s of e){const e=s.state();this.cache.set(e.name,e),t.push(e)}}return t}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}referencedBy(e,t){for(const s in t.roles)if(t.roles[s].topics?.includes(e))return!0;for(const s in t.sessions)if(t.sessions[s].topics?.includes(e))return!0;for(const s in t.context)if(t.context[s].topics?.includes(e))return!0;for(const s in t.preferences)if(t.preferences[s].topics?.includes(e))return!0;return!1}summarize(e){return{topic:e.name,contextKeys:[],preferences:[],metadata:{created:e.created,updated:e.updated,entries:0}}}};function N(e,t,s,i,r,n){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==r||!n)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},n.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[i],d=c.includes(s);if("add"!==r||d){if("remove"===r&&d){const e=Math.max(0,(t.metadata.entries||0)-1);o[a]={...t,[i]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[i]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function R(e,t,s,i){return N(e,t,s,"contextKeys","add",i)}function D(e,t,s){return N(e,t,s,"contextKeys","remove")}function E(e,t,s,i){return N(e,t,s,"preferences","add",i)}function I(e,t,s){return N(e,t,s,"preferences","remove")}var A=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,i=t.index.topics;let r={};const n=e=>{const t=e?.index?.topics;t&&(r=k(r,t))};if(s.index?.context)for(const[r,o]of Object.entries(s.index.context)){const s=t.index.context[r];if(void 0===o&&s)n(D(i,s.topics,s.key));else if(s||!o){if(s&&o){const t=s.topics??[],r=o.topics??t,a=r.filter((e=>!t.includes(e))),c=t.filter((e=>!r.includes(e)));c.length&&n(D(i,c,s.key)),a.length&&n(R(i,a,s.key,e.topics))}}else n(R(i,o.topics??[],o.key,e.topics))}if(s.index?.preferences)for(const[r,o]of Object.entries(s.index.preferences)){const s=t.index.preferences[r];if(void 0===o&&s)n(I(i,s.topics,s.id));else if(s||!o){if(s&&o){const t=s.topics??[],r=o.topics??t,a=r.filter((e=>!t.includes(e))),c=t.filter((e=>!r.includes(e)));c.length&&n(I(i,c,s.id)),a.length&&n(E(i,a,s.id,e.topics))}}else n(E(i,o.topics??[],o.id,e.topics))}return Object.keys(r).length?{index:{topics:r}}:{}},j=async e=>{const{command:t,workspace:s}=e;if("artifact:add"!==t.type)return{};const{sessionId:i,key:r}=t.payload,n=s.index.sessions[i];if(!n)return console.warn(`[sessionArtifactMiddleware] Session ${i} not found in index`),{};const o=n.artifacts||[];if(o.includes(r))return{};const a=[...o,r];return await e.sessions.update(i,{artifacts:a}),{index:{sessions:{[i]:{artifacts:a}}}}},C="\n# WORKSPACE OPERATING SYSTEM\nYou are operating within a structured workspace. Your output MUST be a JSON object matching the provided schema.\nYour entire response MUST be valid JSON. Nothing else.\n".trim();function U(e){if(!e||0===e.length)return"";return`# Artifacts\n\n${e.map((e=>{const{extension:t,value:s}=e.content,i=`\`\`\`${t||""}\n${s.trim()}\n\`\`\``;return`[${e.key}] (v${e.version}, ${e.status})\nDescription: ${e.description}\n${i}`})).join("\n\n")}`}function q(e){if(!e||"append"===e)return{placement:"append",label:null};if("prepend"===e)return{placement:"prepend",label:null};const[t,...s]=e.split(":");return("before"===t||"after"===t)&&s.length>0?{placement:t,label:s.join(":")}:(console.warn(`[SystemPromptAssembler] Unrecognised position "${e}", defaulting to "append".`),{placement:"append",label:null})}var B=class{constructor(e,t){this.resolver=t,this.registry=e}registry;async build(e,t,s,i=[]){const r=this.buildSections(t,i);return{system:this.join(r),sections:r,transcript:await Promise.all(t.transcript.map((async t=>{const i=[];for(const s of t.blocks){const t=this.registry.get(s.type);if(!t){console.warn(`[PromptAssembler] build: block type "${s.type}" is not registered — skipping.`);continue}if(!1===t.consumable)continue;const r=t.mappings?.[e];if(!r){console.log({definition:t}),console.warn(`[PromptAssembler] build: no active mapping for block type "${s.type}" — skipping.`);continue}const n=await Promise.resolve(r.to({block:s,resolve:t=>this.resolver(t,e)}));null!=n&&i.push(n)}return s({turn:t,parts:i})})))}}buildSections(e,t=[]){const s=[...e.system.extensions||[],...t],i=[];var r,n,o;i.push({label:"operating-system",content:C}),i.push({label:"block-architecture",content:this.registry.description()}),e.role.persona&&i.push({label:"persona",content:(r=e.role.persona,`# Persona\n${r}`)}),e.system.preferences.length>0&&i.push({label:"preferences",content:(n=e.system.preferences,`# User Preferences\n${n.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&i.push({label:"context",content:(o=e.system.context,`# Context\n\n${o.map((e=>{switch(e.content.kind){case"text":return`[${e.key}]\n${e.content.value}`;case"json":return`[${e.key}]\n\`\`\`json\n${JSON.stringify(e.content.value,null,2)}\n\`\`\``;case"blob":return`[${e.key}] Blob: ${e.content.filename??"unnamed"} (${e.content.mediaType}, ${e.content.sizeBytes} bytes)`;case"remote":return`[${e.key}] Remote: ${e.content.uri}`;default:return`[${e.key}] Unsupported context type`}})).join("\n\n")}`),metadata:{count:e.system.context.length}}),e.system.artifacts&&e.system.artifacts.length>0&&i.push({label:"artifacts",content:U(e.system.artifacts),metadata:{count:e.system.artifacts.length}}),e.system.instructions&&i.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const a=[...i],c=[];for(const e of s){const{position:t,...s}=e,i=q(t);if("prepend"===i.placement){c.push(s);continue}if("append"===i.placement){a.push(s);continue}const r=a.findIndex((e=>e.label===i.label));if(-1===r){console.warn(`[SystemPromptAssembler] Anchor target "${i.label}" not found in sections. Extension "${e.label}" will be appended.`),a.push(s);continue}const n="before"===i.placement?r:r+1;a.splice(n,0,s)}return[...c,...a]}parse(e,t){const s=[];for(const i of t){const t=this.registry.parse(i,e);t&&s.push(t)}return s}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};function M(e){return e.replace(/\s+/g," ").trim()}function $(e){return e.split("\n").map((e=>e.trim())).join("\n").trim()}function F(e,t){if(0===t.length)return 0;let s=0,i=0;for(;s<2;){const r=e.indexOf(t,i);if(-1===r)break;s++,i=r+t.length}return s}function P(e,t){{const s=F(e,t);if(s>1)return{ambiguous:!0,tier:"exact"};if(1===s){const s=e.indexOf(t);return{start:s,end:s+t.length,tier:"exact"}}}{const s=M(e),i=M(t);if(i.length>0){const t=F(s,i);if(t>1)return{ambiguous:!0,tier:"ws-normalised"};if(1===t){const t=z(e,s,i,M);if(t)return{...t,tier:"ws-normalised"}}}}{const s=$(e),i=$(t);if(i.length>0){const t=F(s,i);if(t>1)return{ambiguous:!0,tier:"line-trimmed"};if(1===t){const t=z(e,s,i,$);if(t)return{...t,tier:"line-trimmed"}}}}return null}function z(e,t,s,i){const r=t.indexOf(s);if(-1===r)return null;const n=r+s.length,o=new Array(t.length+1).fill(-1);let a=0;const c=i===M,d=c?/(\s+|\S+)/g:/([^\n]+|\n)/g;let l;for(;null!==(l=d.exec(e));){const e=l.index,s=l[0],i=c?/^\s+$/.test(s)?" ":s:"\n"===s?"\n":s.trim();for(let r=0;r<i.length;r++)a<t.length&&(o[a]=e+Math.min(r,s.length-1)),a++}if(o[a]=e.length,-1===o[r])return null;const u=o[r];let p=-1!==o[n]?o[n]:e.length;for(let t=0;t<=20&&p+t<=e.length;t++)if(i(e.slice(u,p+t))===s)return{start:u,end:p+t};return null}var L={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:i,settings:r,project:n}=t,o=await s.get(i);return o?w({id:o.id,settings:o.settings,project:o.project}):(await s.add({id:i,settings:r,project:n}),w({id:i,settings:r,project:n,index:{roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}}}))},"workspace:sync":async function(e,t){let s={};for(const t of e.indexers){const i=await t(e);s=k(s,i)}return t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=k(s.settings||{},t.settings)),t.project&&(s.project=k(s.project||{},t.project))),w(s)},"role:add":async function(e,t){const{workspace:s,roles:i}=e,r=t;return s.index.roles[r.name]?b({code:"DUPLICATE_KEY",resource:"Role",key:r.name}):(await i.add(r),w({index:{roles:{[r.name]:i.summarize(r)}}}))},"role:update":async function(e,t){const{workspace:s,roles:i}=e,{name:r,...n}=t;if(!s.index.roles[r])return b({code:"NOT_FOUND",resource:"Role",id:r});const o=await i.update(r,n);return o?w({index:{roles:{[r]:i.summarize(o)}}}):b({code:"BACKEND_ERROR",reason:`Failed to update role ${r} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:i}=e,{name:r}=t;return s.index.roles[r]?await i.delete(r)?w({index:{roles:{[r]:y}}}):b({code:"BACKEND_ERROR",reason:`Failed to delete role ${r} from store.`}):b({code:"NOT_FOUND",resource:"Role",id:r})},"preference:add":async function(e,t){const{workspace:s,preferences:i}=e,r=t;return s.index.preferences[r.id]?b({code:"DUPLICATE_KEY",resource:"Preference",key:r.id}):(await i.add(r),w({index:{preferences:{[r.id]:i.summarize(r)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:i}=e,{id:r,...n}=t;if(!s.index.preferences[r])return b({code:"NOT_FOUND",resource:"Preference",id:r});const o=await i.update(r,n);return o?w({index:{preferences:{[r]:i.summarize(o)}}}):b({code:"BACKEND_ERROR",reason:`Failed to update preference ${r} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:i}=e,{id:r}=t;return s.index.preferences[r]?await i.delete(r)?w({index:{preferences:{[r]:y}}}):b({code:"BACKEND_ERROR",reason:`Failed to delete preference ${r} from store.`}):b({code:"NOT_FOUND",resource:"Preference",id:r})},"context:add":async function(e,t){const{workspace:s,context:i}=e,r=t;return s.index.context[r.key]?b({code:"DUPLICATE_KEY",resource:"Context",key:r.key}):(await i.add(r),w({index:{context:{[r.key]:i.summarize(r)}}}))},"context:update":async function(e,t){const{workspace:s,context:i}=e,{key:r,...n}=t,o=s.index.context[r];if(!o)return b({code:"NOT_FOUND",resource:"Context",id:r});const a=await i.update(r,n,o.kind);return a?w({index:{context:{[r]:i.summarize(a)}}}):b({code:"BACKEND_ERROR",reason:`Failed to update context ${r} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:i}=e,{key:r}=t,n=s.index.context[r];return n?await i.delete(r,n.kind)?w({index:{context:{[r]:y}}}):b({code:"BACKEND_ERROR",reason:`Failed to delete context ${r} from store.`}):b({code:"NOT_FOUND",resource:"Context",id:r})},"artifact:add":async function(e,s){const{workspace:i,artifacts:r}=e,{sessionId:n,...o}=s;if(i.index.artifacts[o.key])return b({code:"DUPLICATE_KEY",resource:"Artifact",key:o.key});const a={...o,type:"artifact",id:t.v7()};return await r.add(a),w({index:{artifacts:{[o.key]:r.summarize(o)}}})},"artifact:update":async function(e,t){const{workspace:s,artifacts:i}=e,{sessionId:r,...n}=t,o=n.key;if(!s.index.artifacts[o])return b({code:"NOT_FOUND",resource:"Artifact",id:o});const a=await i.get(o);if(!a)return b({code:"NOT_FOUND",resource:"Artifact",id:o});let c=a.content;if(n.content)c=n.content;else if(n.patch){if("unified-diff"===n.patch.format)return b({code:"BACKEND_ERROR",reason:"unified-diff is deprecated; use search-replace"});if("search-replace"===n.patch.format){const e=function(e,t){for(let s=0;s<t.length;s++){const{oldText:i}=t[s],r=i.slice(0,120);if(0===i.trim().length)return{code:"RECONCILIATION_ERROR",format:"search-replace",operationIndex:s,reason:"empty_search",searchSnippet:r};const n=P(e,i);if(null===n)return{code:"RECONCILIATION_ERROR",format:"search-replace",operationIndex:s,reason:"not_found",searchSnippet:r};if("ambiguous"in n)return{code:"RECONCILIATION_ERROR",format:"search-replace",operationIndex:s,reason:"ambiguous",searchSnippet:r}}let s=e;for(let e=0;e<t.length;e++){const{oldText:i,newText:r}=t[e],n=P(s,i);if(null===n||"ambiguous"in n)return{code:"RECONCILIATION_ERROR",format:"search-replace",operationIndex:e,reason:null===n?"not_found":"ambiguous",searchSnippet:i.slice(0,120)};s=s.slice(0,n.start)+r+s.slice(n.end)}return s}(a.content.value,n.patch.operations);if("string"!=typeof e)return b(e);c={...c,value:e}}}const d={...a,content:c,status:n.status,version:a.version+1,updated:(new Date).toISOString()};return await i.update(o,d),w({index:{artifacts:{[o]:i.summarize(d)}}})},"artifact:delete":async function(e,t){const{workspace:s,artifacts:i}=e,{key:r}=t;return s.index.artifacts[r]?await i.delete(r)?w({index:{artifacts:{[r]:y}}}):b({code:"BACKEND_ERROR",reason:`Failed to delete artifact ${r} from store.`}):b({code:"NOT_FOUND",resource:"Artifact",id:r})},"topic:add":async function(e,t){const{workspace:s,topics:i}=e,r=t;return s.index.topics[r.name]?b({code:"DUPLICATE_KEY",resource:"Topic",key:r.name}):(await i.add(r),w({index:{topics:{[r.name]:i.summarize(r)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:i}=e,{name:r,...n}=t;if(!s.index.topics[r])return b({code:"NOT_FOUND",resource:"Topic",id:r});const o=await i.update(r,n);return o?w({index:{topics:{[r]:{metadata:{updated:o.updated}}}}}):b({code:"BACKEND_ERROR",reason:`Failed to update topic ${r} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:i,roles:r,sessions:n}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return b({code:"NOT_FOUND",resource:"Topic",id:o});if(i.referencedBy(o,s.index)&&!a)return b({code:"INVALID_COMMAND",reason:`Topic '${o}' is referenced by other entities. Use 'cascade: true' to force deletion.`});if(a){for(const e in s.index.roles){const t=s.index.roles[e];if(t.topics?.includes(o)){const t=await r.get(e);t&&await r.update(e,{topics:t.topics.filter((e=>e!==o))})}}for(const e in s.index.sessions){const t=s.index.sessions[e];t.topics?.includes(o)&&await n.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await i.delete(o)?w({index:{topics:{[o]:y}}}):b({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:i,roles:r,sessions:n}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return b({code:"NOT_FOUND",resource:"Topic",id:s.index.topics[o]?a:o});for(const e in s.index.roles){const t=s.index.roles[e];if(t.topics?.includes(o)){const t=await r.get(e);if(t){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await r.update(e,{topics:s})}}}for(const e in s.index.sessions){const t=s.index.sessions[e];if(t.topics?.includes(o)){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await n.update(e,{topics:s})}}return await i.delete(o),w({index:{topics:{[o]:y}}})},"session:create":async function(e,t){const{workspace:s,sessions:i}=e,r=t;return s.index.sessions[r.id]?b({code:"DUPLICATE_KEY",resource:"Session",key:r.id}):(await i.add(r),w({index:{sessions:{[r.id]:i.summarize(r)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r,...n}=t;if(!s.index.sessions[r])return b({code:"NOT_FOUND",resource:"Session",id:r});const o=await i.update(r,n);return o?w({index:{sessions:{[r]:i.summarize(o)}}}):b({code:"BACKEND_ERROR",reason:`Failed to update session ${r} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r,newSessionId:n,label:o}=t,a=s.index.sessions[r];if(!a)return b({code:"NOT_FOUND",resource:"Session",id:r});const c={...a,id:n,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await i.add(c),w({index:{sessions:{[n]:i.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r}=t;return s.index.sessions[r]?(await i.delete(r),w({index:{sessions:{[r]:y}}})):b({code:"NOT_FOUND",resource:"Session",id:r})},"session:role:switch":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r,roleName:n}=t;return s.index.sessions[r]?(await i.update(r,{role:n}),w({index:{sessions:{[r]:{role:n}}}})):b({code:"NOT_FOUND",resource:"Session",id:r})},"session:topics:add":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r,topics:n}=t,o=s.index.sessions[r];if(!o)return b({code:"NOT_FOUND",resource:"Session",id:r});const a=Array.from(new Set([...o.topics,...n]));return await i.update(r,{topics:a}),w({index:{sessions:{[r]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:i}=e,{sessionId:r,preferences:n}=t;return s.index.sessions[r]?(await i.update(r,{preferences:n}),w({index:{sessions:{[r]:{preferences:n}}}})):b({code:"NOT_FOUND",resource:"Session",id:r})},"turn:add":async function(e,t){const{workspace:s,sessions:i,turns:r}=e,{sessionId:n,turn:o}=t;if(!s.index.sessions[n])return b({code:"NOT_FOUND",resource:"Session",id:n});await r.add(o);const a={id:o.id,version:o.version};return await i.update(n,{head:a}),w({index:{sessions:{[n]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,turns:i}=e,{sessionId:r,turn:n}=t;if(!s.index.sessions[r])return b({code:"NOT_FOUND",resource:"Session",id:r});const{id:o,session:a,version:c,...d}=n;return await i.update({id:o,session:a,version:c},d),w({})},"turn:edit":async function(e,t){const{workspace:s,sessions:i,turns:r}=e,{sessionId:n,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d,modelSnapshot:l}=t,u=s.index.sessions[n];if(!u)return b({code:"NOT_FOUND",resource:"Session",id:n});let p={};const h=await r.get({id:o,version:c-1,session:n});h&&(p=h);const m={...p,id:o,version:c,blocks:a,role:d??p.role,model:l??p.model,timestamp:(new Date).toISOString(),parent:p.parent,actor:p.actor||"user",session:n};if(await r.add(m),u.head?.id===o){const e={id:o,version:c};return await i.update(n,{head:e}),w({index:{sessions:{[n]:{head:e}}}})}return w({})},"turn:branch":async function(e,t){const{workspace:s,sessions:i,turns:r}=e,{sessionId:n,turn:o}=t;if(!s.index.sessions[n])return b({code:"NOT_FOUND",resource:"Session",id:n});await r.add(o);const a={id:o.id,version:o.version};return await i.update(n,{head:a}),w({index:{sessions:{[n]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:i,turns:r}=e,{sessionId:n,turnId:o,newHead:a}=t;return s.index.sessions[n]?(await r.delete({session:n,id:o,version:t.version}),a?(await i.update(n,{head:a}),w({index:{sessions:{[n]:{head:a}}}})):w({})):b({code:"NOT_FOUND",resource:"Session",id:n})},"blob:register":async function(e,t){const{blobs:s}=e,i=await s.register(t.data,t.mediaType,t.filename);if(!i.ok)return i;const r=await s.getRecord(i.value.sha256);return r?w({index:{blobs:{[r.sha256]:r}}}):b({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${i.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,i=await s.retain(t.sha256);if(!i.ok)return i;const r=await s.getRecord(t.sha256);return w({index:{blobs:{[t.sha256]:r}}})},"blob:release":async function(e,t){const{blobs:s}=e,i=await s.release(t.sha256);if(!i.ok)return i;const r=await s.getRecord(t.sha256);return w({index:{blobs:{[t.sha256]:r||y}}})},"blob:purge":async function(e,t){const{blobs:s}=e,i=await s.purge(t.sha256);return i.ok?w({index:{blobs:{[t.sha256]:y}}}):i},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:i,providerId:r,fileId:n,timestamp:o}=t,a=await s.recordRemoteId(i,r,n,o);if(!a.ok)return a;const c=await s.getRecord(i);return w({index:{blobs:{[i]:c}}})},"tool:call":async function(e,t){return w({})}},K=class{profiles;constructor(e=[]){this.profiles=new Map;for(const t of e)this.profiles.set(t.name,t)}get(e){return this.profiles.get(e)}list(e){const t=Array.from(this.profiles.values());return e?t.filter((t=>t.provider===e)):t}register(e){this.profiles.set(e.name,e)}},W={type:"text",emittable:!0,description:["## Block: `text`","Primary communication block. Use for all conversational responses, explanations, and prose.","A response may contain multiple `text` blocks interleaved with other block types."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string",description:"The raw markdown or plain text content of the response."},format:{type:"string",description:"Optional field to specify the format of the `text` content."}},required:["type","text"]}},V={type:"checkpoint",emittable:!0,consumable:!0,description:["## Block: `checkpoint`","Canonical conversational state used for inference","continuation, session restoration, and cross-context handover.","A checkpoint MUST preserve all durable conversational state","required to continue the interaction with high semantic fidelity","after prior turns have been discarded.","Checkpoints are cumulative.","Each emitted checkpoint supersedes all previous checkpoints","and represents the authoritative state of the conversation","up to the moment immediately before the current response.",""].join("\n"),rules:["Emit checkpoints only when instructed by the user or the system.","Emit at most one checkpoint block per turn.","Include only information established in prior turns or prior checkpoints.","Preserve references and artifacts from prior checkpoints unless they are confirmed irrelevant to continuation.","Store each piece of durable state in its most appropriate field unless cross-reference is required for continuation fidelity.","Summarize only conversation state established prior to the request for checkpoint generation.","Optimise for continuation fidelity rather than brevity.","The `summary` field should contain, in prose, a concise digest of the conversation history.","The `summary` field is meant to enable quick understanding of the checkpoint's context; The `state` object contains the detailed, machine-consumable data for faithful continuation of a session.","`insights` MUST contain derived understanding or realizations, not raw facts, decisions, or speculative assumptions.","Prefer structured state over narrative prose for other state properties.","Use precise language and avoid interpretive rewriting.","Clearly separate facts, assumptions, plans, and unresolved issues.","A checkpoint MUST contain all durable information required to continue the conversation faithfully.","A checkpoint MUST preserve the semantic meaning of prior turns, including prior checkpoints.","A checkpoint MUST be self-sufficient and MUST NOT require access to discarded conversation history.","A checkpoint MUST accurately represent established facts, constraints, decisions, and unresolved work.","A checkpoint MUST distinguish between confirmed facts, assumptions, proposals, and open questions.","A checkpoint MUST preserve active intent and conversational trajectory.","A checkpoint MUST avoid lossy compression of critical reasoning state.","Every checkpoint fully supersedes earlier checkpoints.","Transient phrasing and rhetorical detail may be omitted.","Information uncertainty MUST be preserved explicitly.","Contradictions or unresolved ambiguities MUST be recorded.","Record all context items that materially influenced the conversation in `references`.","Record all artifacts produced during the conversation in `artifacts`; include enough description to understand the artifact without re-reading it.","A `ContextReference` in `references` or `artifacts` MUST include a `key` if the item exists in the Context system."],schema:{type:"object",properties:{type:{type:"string",enum:["checkpoint"]},state:{type:"object",properties:{summary:{type:"string",description:"A concise, human-readable summary of the conversational state captured by this checkpoint, intended for quick overview and context."},objectives:{type:"array",description:"Active user goals and intended outcomes.",items:{type:"string"}},facts:{type:"array",description:"Facts established or accepted during the conversation.",items:{type:"string"}},constraints:{type:"array",description:"Requirements, prohibitions, preferences, or boundaries.",items:{type:"string"}},decisions:{type:"array",description:"Choices, conclusions, or committed directions.",items:{type:"string"}},assumptions:{type:"array",description:"Tentative or inferred premises not yet confirmed.",items:{type:"string"}},unresolved:{type:"array",description:"Open questions, pending work, or incomplete reasoning.",items:{type:"string"}},insights:{type:"array",description:["Derived realizations, synthesized understanding, reframings, or emergent patterns discovered during the conversation.","These are not raw facts or decisions, but higher-level understanding gained by either party."].join("\n"),items:{type:"string"}},notes:{type:"array",description:"Additional state required for faithful continuation.",items:{type:"string"}},references:{type:"array",description:"External documents, URLs, or context items brought into the conversation by the user or referenced during reasoning. These are inputs - things that informed the conversation.",items:{type:"object",properties:{key:{type:"string",description:"The Context.key of the injected context item. Allows the runtime to re-inject the same context on resume. Omit if the reference was never part of the Context system."},label:{type:"string",description:"Short human-readable label for the reference."},description:{type:"string",description:"Why this reference matters for conversational continuity."}},required:["label","description"]}},artifacts:{type:"array",description:"Artifacts produced during the conversation. These are outputs - things created as a result of the conversation. Each entry is a lightweight pointer; full artifact content lives in the turn history.",items:{type:"object",properties:{key:{type:"string",description:"The Artifact.key identifying the artifact in the turn history. Allows the runtime to locate and re-inject the artifact on resume."},label:{type:"string",description:"Short human-readable label for the artifact."},description:{type:"string",description:"What was produced, its structure, and its role in the conversation. Enough detail to understand the artifact without re-reading it."}},required:["label","description"]}}},required:["summary","objectives","facts","constraints","decisions","unresolved"]}},required:["type","state"]}},G=[W,{type:"summary",emittable:!0,description:["## Block: `summary`","Context compression block. Replaces older conversation history with a concise digest."].join("\n"),rules:["Only emit when explicitly instructed by the system to summarise.","Never emit more than one summary block per turn.","Preserve key decisions, outcomes, and unresolved questions.","Do not summarise the current turn - only prior history."],schema:{type:"object",properties:{type:{type:"string",enum:["summary"]},text:{type:"string",description:"A concise summary replacing older conversation context."}},required:["type","text"]}},{type:"thinking",emittable:!1,consumable:!1,description:["## Block: `thinking`","Internal chain-of-thought produced by the model before its final response.","Injected by the workspace from provider reasoning tokens - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["thinking"]},thinking:{type:"string",description:"The internal reasoning text produced before the final response."}},required:["type","thinking"]}},{type:"tool:use",emittable:!1,description:["## Block: `tool:use`","Captures a model request to execute a registered tool.","Constructed by the workspace from the provider native function-call response - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:use"]},name:{type:"string",description:"The exact registered name of the tool to execute."},input:{type:"object",description:"The parameter arguments for the tool execution.",additionalProperties:!0}},required:["type","name","input"]}},{type:"tool:result",emittable:!1,description:["## Block: `tool:result`","Contains the output of a tool execution, including any errors.","Injected by the workspace after a tool runs - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["tool:result"]},useId:{type:"string",description:"The UUID of the ToolUseBlock that triggered this execution."},content:{oneOf:[{type:"string"},{type:"object",additionalProperties:!0}],description:"The serialized output of the tool, or a structured JSON response."},isError:{type:"boolean",description:"True if the tool execution resulted in an error."}},required:["type","useId","content"]}},{type:"image",emittable:!1,description:["## Block: `image`","An image asset attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["image"]},altText:{type:"string",description:"Accessible description of the image content."}},required:["type"]}},{type:"document",emittable:!1,description:["## Block: `document`","A document asset (PDF, DOCX, etc.) attached to a turn, resolved from the workspace blob store.","Constructed by the workspace from user uploads - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["document"]},title:{type:"string",description:"Human-readable title or filename of the document."}},required:["type"]}},{type:"role:transition",emittable:!1,consumable:!1,description:["## Block: `role:transition`","Marks that the active session persona has switched from one role to another.","Emitted by the workspace when the active persona changes - never emit it yourself."].join("\n"),rules:[],schema:{type:"object",properties:{type:{type:"string",enum:["role:transition"]},previousRole:{type:"string",description:"The name of the role the session is leaving."},newRole:{type:"string",description:"The name of the role the session is adopting."}},required:["type","newRole"]}},V,{type:"artifact",emittable:!0,consumable:!1,description:["## Block: `artifact`","","Represents a durable, standalone output generated during a conversation.","Artifacts are versioned content objects intended to persist beyond the current turn.","They model things the user would reasonably treat as files, documents, assets,","or reusable deliverables rather than transient conversational text.","","Artifacts are first-class blocks and may appear anywhere in the turn block array.","The system owns lifecycle metadata.","You are only responsible only for semantic intent and content quality.","","Artifacts should be rare, high-signal outputs.","Every artifact introduces cognitive and organizational overhead:","users may revisit it, compare revisions, rename it, or maintain it over time.","Overproducing artifacts reduces clarity and weakens the value of persistence.","","Artifacts are tracked via a stable, system-provided `key`.","","### Context Format","Active artifacts are listed under the `Artifacts` section using the following structure:","```text","[key] (version, status)","Description: <description>","<content>","```","","### Example","For an existing artifact identified by the key `main-program.js`:","```text","[main-program.js] (v1, draft)","Description: A JavaScript program that prints out Hello, World."," ```","```javascript",'console.log("Hello, World!\\n");'," ```","","### Characteristics of a good artifact","- Has a clear standalone identity.","- Would reasonably be saved, exported, reused, reviewed, or shared.","- Represents meaningful work product rather than conversational assistance.","- Benefits from version history or iterative refinement.","- Remains understandable outside the immediate chat context.","","### Strong candidates for artifacts","- Full scripts, modules, components, or multi-file implementations.","- Design docs, RFCs, architecture proposals, specifications, or plans.","- Configurations, schemas, templates, policies, prompts, or workflows.","- Structured long-form writing intended for continued editing.","- Deliverables the user explicitly asks to 'create', 'draft', 'generate', or 'produce'.","- Outputs likely to undergo future revisions.","","### Poor candidates for artifacts","- Tiny edits or localized fixes.","- Short examples or illustrative snippets.","- Explanations where the prose matters more than the exact text output.","- One-off answers that do not need persistence.","- Small patches, diffs, or replacements that fit naturally inline.","- Simple helper functions or snippets under roughly 10–20 lines.","","### Decision heuristic","Ask:","'Would the user reasonably expect this to exist as its own file or managed object?'","","If the answer is unclear, do not create an artifact.","Prefer normal markdown/code fences unless persistence is clearly valuable.","Users can always later request:","'turn this into an artifact',","'save this separately', or","'expand this into a full document'.","","### Artifact lifecycle","- `artifact` creates a new durable object.","- `artifact:update` revises an existing object while preserving identity/history.","- Revisions should meaningfully evolve the artifact rather than duplicate it.","","### Cognitive load principle","Most sessions should produce few or no artifacts.","Artifacts are not formatting conveniences.","They are intentional, persistent deliverables."].join("\n"),rules:["When the desired format is neither explicit nor clearly implied by the user request, default to Markdown (.md) or plain text (.txt) based on the capabilities required by the artifact.","Assign each artifact a concise, semantically meaningful key that resembles a real file name.","The key should communicate the artifact’s purpose and format at a glance, using conventional extensions when applicable (for example: report.md, UserService.java, clock-module.ts, api-schema.json).","Keys should be stable, human-readable, and specific enough to distinguish related artifacts.","Create artifacts only for durable, standalone deliverables with clear long-term value.","Favor inline markdown/code fences for minor edits, quick fixes, illustrative snippets, and conversational examples.","Prioritize inline responses unless persistence or versioning provides clear additional value.","Maintain a low artifact count to reduce workspace clutter and cognitive overhead.","Use `artifact:update` when evolving an existing artifact rather than creating a new duplicate.","Consolidate iterative work into existing artifacts when they represent the same underlying deliverable.","Ensure artifacts remain self-contained and understandable outside the immediate conversational context.","Write concise, human-readable labels that identify the artifact at a glance.","Write descriptions that explain the artifact's purpose, scope, and intended use.","Set `status` to `draft` when the artifact is incomplete, provisional, or awaiting review.","Set `status` to `complete` when the artifact is ready for practical use.","Omit system-managed metadata fields such as `id`, `created`, `updated`, or version identifiers from your output.","Treat content length alone as insufficient justification for creating an artifact; prioritize persistence value instead.","Allow multiple artifacts in a single turn only when each represents a distinct, meaningful deliverable."],schema:{type:"object",properties:{type:{type:"string",enum:["artifact"]},key:{type:"string",description:"Concise, stable, human-readable identifier for the artifact, modeled after a file name. Should clearly reflect the artifact’s purpose and format (for example: `report.md`, `auth-service.ts`, `schema.json`)."},label:{type:"string",description:"Stable, short title for the artifact. Should be 2–4 words, optimized for quick recognition in lists."},description:{type:"string",description:"What was produced, its structure, and its role in the conversation. Enough detail to understand the artifact without reading its content."},status:{type:"string",enum:["complete","draft"],description:"Artifact lifecycle state. 'draft' indicates incomplete or evolving work. 'complete' indicates the artifact is stable, reviewable, and ready for use. Status should reflect content maturity, not length."},content:{type:"object",description:"The artifact payload.",properties:{kind:{type:"string",enum:["text"]},format:{type:"string",description:"Optional field to specify the format of the `text` content."},value:{type:"string",description:"The raw text content of the artifact."},extension:{type:"string",description:"A file extension for the text content based on the format."}},required:["kind","value"]}},required:["type","label","description","status","content","key"]}},{type:"artifact:update",emittable:!0,consumable:!1,description:["## Block: `artifact:update`","","This block represents a mutation to an existing artifact previously introduced in the conversation.","","### Update Strategies","","**`content`** — full replacement. Use for new artifacts, wholesale rewrites, or","when the surviving content is shorter than the changes themselves.","","**`patch` with `search-replace`** — targeted edits. Use for localised changes to","large artifacts. Each operation locates a unique block of existing text and","replaces it. The system applies a three-tier matching strategy (exact →","whitespace-normalised → line-trimmed) so minor indentation drift is tolerated,","but each `oldText` must be unique within the artifact."].join("\n"),rules:["Use `artifact:update` exclusively to modify an existing artifact present in the current context.","Target the artifact using its exact, case-sensitive `key` as the stable reference.","Do not invent new keys; only reference keys explicitly provided in the active artifact list.","Provide one of `content` or `patch` to express the update; these properties are mutually exclusive.","Use `content` for full replacements or when the surviving content is shorter than the diff would be.","Use `patch` with `format: 'search-replace'` for targeted edits to large artifacts.","Each `patch` operation must supply an `oldText` that appears exactly once in the current artifact content.","Make `oldText` large enough to be unambiguous — include surrounding lines if the target line is repeated elsewhere.","Do not split a single logical change across multiple operations when one operation would suffice.","Set `status` to `draft` if the artifact requires further iteration, or `complete` if it is finalized.","The system automatically manages created, updated, and version fields, so you can safely omit them.","Multiple independent artifact updates may be emitted in a single turn.","Prefer updating an existing artifact over creating a new one to maintain continuity."],schema:{type:"object",properties:{type:{type:"string",enum:["artifact:update"]},key:{type:"string",description:"The system-assigned key of the artifact to update. Must reference a key seen in prior conversation context. e.g. [ghdy.txt]"},status:{type:"string",enum:["complete","draft"],description:"Updated status of the artifact."},content:{type:"object",description:"Full text replacement payload. Provide this OR `patch`, never both.",properties:{kind:{type:"string",enum:["text"]},value:{type:"string",description:"The complete replacement text content."}},required:["kind","value"]},patch:{type:"object",description:"A targeted patch to apply to the existing artifact content. Provide this OR `content`, never both. Preferred for large artifacts with localised changes.",properties:{format:{type:"string",enum:["search-replace"],description:"The patch format. Must be `search-replace`."},operations:{type:"array",description:"Ordered list of search-replace operations. All operations are validated against the current artifact content before any are applied. If any operation fails, the artifact is left unchanged.",minItems:1,items:{type:"object",properties:{oldText:{type:"string",description:"The exact text to locate in the artifact. Must be unique within the artifact — include sufficient surrounding lines to disambiguate if needed. Must not be empty."},newText:{type:"string",description:"The text to substitute in place of `oldText`. May be an empty string to delete the matched block."}},required:["oldText","newText"]}}},required:["format","operations"]}},required:["type","key","status"],oneOf:[{required:["content"]},{required:["patch"]}]}}];function Y(e,t){let s=e.filter((e=>!0===e.emittable));if(!t)return s;if(t.only&&t.only.length>0){const e=new Set(t.only);return s.filter((t=>e.has(t.type)))}if(t.exclude&&t.exclude.length>0){const e=new Set(t.exclude);return s.filter((t=>!e.has(t.type)))}return s}var H=class{store=new Map;constructor(){for(const e of G)this.store.set(e.type,e)}defs(){return Array.from(this.store.values())}register(e){if(this.store.has(e.type))throw new Error(`[BlockRegistry] Block type "${e.type}" is already registered. Use update() to modify it.`);this.store.set(e.type,{...e,emittable:e.emittable??!0,rules:e.rules??[]})}unregister(e){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot unregister unknown block type "${e}".`);this.store.delete(e)}update(e,t){const s=this.store.get(e);s?this.store.set(e,{...s,...t,type:e}):this.store.set(e,{emittable:!0,rules:[],...t,type:e})}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}isType(e,t){return e.type===t}guard(e){return t=>t.type===e}schema(e){return{type:"object",description:"The model's structured response, containing an ordered sequence of content blocks.",properties:{blocks:{type:"array",description:"An ordered array of content blocks comprising the model's response.",items:{anyOf:Y(this.defs(),e).map((e=>e.schema))}}},required:["blocks"]}}description(e){return["# BLOCK TYPES & USAGE RULES","Your response MUST be a JSON object with a `blocks` array.","Each element of `blocks` must be one of the following types:","",Y(this.defs(),e).map((e=>{const t=[e.description];return e.rules.length>0&&(t.push("**Rules:**"),t.push(...e.rules.map((e=>`- ${e}`)))),t.join("\n")})).join("\n\n"),"","## GLOBAL CONSTRAINTS","- Output must be **valid JSON only** — no prose before or after the JSON object.","- Responses may contain multiple blocks. Blocks are rendered in order.","- **Do NOT generate IDs.** The workspace is solely responsible for block ID assignment.","- Do not infer or invent fields not defined in the block schemas above."].join("\n")}rules(e){const t=Y(this.defs(),e);return Object.fromEntries(t.map((e=>[e.type,[...e.rules]])))}setRules(e,t){const s=this.store.get(e);if(!s)throw new Error(`[BlockRegistry] Cannot set rules on unknown block type "${e}".`);this.store.set(e,{...s,rules:t})}parse(e,s){const i=this.store.get(e.type);if(!i)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&i.mappings?.[s])return i.mappings[s].from(e);const{id:r,...n}=e;return{id:t.v7(),...n}}create(e,s){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot create block of unknown type "${e}".`);return{...s,id:t.v7(),type:e}}clone(e,s){return{...structuredClone(e),...s,id:t.v7()}}},J=class{store=new Map;constructor(){this.registerDefaults()}registerDefaults(){this.register({kind:"text",target:"system",render:e=>({id:e.key,type:"text",text:e.content.value}),toString:e=>e.content.value,summarize:e=>({key:e.key,kind:"text",topics:e.topics,timestamp:e.timestamp,preview:e.content.value.slice(0,100)})}),this.register({kind:"json",target:"system",render:e=>({id:e.key,type:"text",text:JSON.stringify(e.content.value,null,2)}),toString:e=>JSON.stringify(e.content.value),summarize:e=>({key:e.key,kind:"json",topics:e.topics,timestamp:e.timestamp,preview:"JSON Data"})}),this.register({kind:"blob",target:"transcript",render:e=>{const{sha256:t,mediaType:s,sizeBytes:i,filename:r}=e.content,n={sha256:t,mediaType:s,sizeBytes:i,filename:r};return s.startsWith("image/")?{id:e.key,type:"image",ref:n}:{id:e.key,type:"document",ref:n,title:r}},toString:e=>e.content.filename||"unnamed blob",summarize:e=>({key:e.key,kind:"blob",topics:e.topics,timestamp:e.timestamp,mime:e.content.mediaType,size:e.content.sizeBytes,preview:e.content.filename})})}register(e){if(this.store.has(e.kind))throw new Error(`[ContextRegistry] Context kind "${e.kind}" is already registered.`);this.store.set(e.kind,e)}get(e){return this.store.get(e)}list(){return Array.from(this.store.values())}},X="__system__",Q=class{constructor(e,s,i){this._actor=e,this._turn=i?JSON.parse(JSON.stringify(i)):{id:t.v7(),session:s,version:0,actor:this._actor,blocks:[],timestamp:(new Date).toISOString(),role:void 0,model:void 0}}_turn;addText(e){const s={id:t.v7(),type:"text",text:e};return this._turn.blocks.push(s),this}addImage(e,s){const i={id:t.v7(),type:"image",ref:e,altText:s};return this._turn.blocks.push(i),this}addDocument(e,s){const i={id:t.v7(),type:"document",ref:e,title:s};return this._turn.blocks.push(i),this}addToolUse(e,s){const i={id:t.v7(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(i),this}addToolResult(e,s,i){const r={id:t.v7(),type:"tool:result",useId:e,content:s,isError:i};return this._turn.blocks.push(r),this}addSummary(e){const s={id:t.v7(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const i={id:t.v7(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(i),this}addThinking(e){const s={id:t.v7(),type:"thinking",thinking:e};return this._turn.blocks.push(s),this}addBlock(e){return e.id||(e.id=t.v7()),this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}editTextBlock(e,t){const s=this._turn.blocks.findIndex((t=>t.id===e));if(-1===s)throw new Error(`Block with ID ${e} not found.`);const i=this._turn.blocks[s];if("text"!==i.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...i,text:t},this}withId(e){return this._turn.id=e,this}withVersion(e){return this._turn.version=e,this}withTimestamp(e){return this._turn.timestamp=e,this}withParent(e){return this._turn.parent=e,this}withRoleSnapshot(e){return this._turn.role=e,this}withRole(e){return this._turn.role=e,this}withModel(e){return this._turn.model=e,this}build(){return JSON.parse(JSON.stringify(this._turn))}node(){const e=this.build();return{id:e.id,versions:{[e.version]:e},activeVersion:e.version,actor:e.actor,blocks:e.blocks,timestamp:e.timestamp,roleSnapshot:e.role,modelSnapshot:e.model,parent:e.parent,children:{}}}},Z=class{constructor(e,t){this.turnStore=e,this.sessionStore=t}async loadAllTurns(e){return this.turnStore.listBySession(e)}async loadHead(e){const t=await this.sessionStore.get(e);return t?.head??null}},ee=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s,i){const[r,n]=await Promise.all([s.loadAllTurns(t),void 0!==i?Promise.resolve(i):s.loadHead(t)]),o=function(e,t){const s=function(e,t){if(!t)return new Set;const s=new Map;for(const t of e)s.set(`${t.id}:${t.version}`,t);const i=new Set;let r=t;for(;r;){const e=`${r.id}:${r.version}`;if(i.has(e))break;i.add(e);const t=s.get(e);if(!t)break;r=t.parent}return i}(e,t),i={},r={};for(const t of e){i[t.id]||(i[t.id]={id:t.id,versions:{},activeVersion:t.version,actor:t.actor,blocks:t.blocks,timestamp:t.timestamp,roleSnapshot:t.role,modelSnapshot:t.model,parent:t.parent,children:{}},r[t.id]=new Set);const e=i[t.id];e.versions[t.version]=t;const n=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(n&&(!o||t.version>=e.activeVersion)&&(e.activeVersion=t.version,e.blocks=t.blocks,e.timestamp=t.timestamp,e.roleSnapshot=t.role,e.modelSnapshot=t.model,e.parent=t.parent),t.parent){const e=`${t.parent.id}:${t.parent.version}`;if(r[t.parent.id]||(r[t.parent.id]=new Set),!r[t.parent.id].has(e+":"+t.id)){r[t.parent.id].add(e+":"+t.id),i[t.parent.id]||(i[t.parent.id]={id:t.parent.id,versions:{},activeVersion:t.parent.version,actor:"user",blocks:[],timestamp:"",roleSnapshot:void 0,modelSnapshot:void 0,children:{}});const s=i[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return i}(r,n);return new e(o,n)}head(){return this._head}chain(){return this._head?this.chainFrom(this._head.id):[]}chainFrom(e){const t=[];let s=e;for(;s;){const e=this.nodes[s];if(!e)break;t.push(e),s=e.parent?.id??null}return t.reverse()}getTurnSiblings(e){const t=this.nodes[e];if(!t)return[];if(!t.parent)return Object.values(this.nodes).filter((e=>!e.parent));const s=this.nodes[t.parent.id];if(!s)return[t];const i=s.children[t.parent.version];return i?i.map((e=>this.nodes[e])).filter((e=>!!e)):[t]}branchInfo(e){const t=this.nodes[e];if(!t)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const s=Object.keys(t.versions).map(Number).sort(((e,t)=>e-t)),i=s.indexOf(t.activeVersion);return{versions:s,currentIndex:i,total:s.length,hasPrev:i>0,hasNext:i<s.length-1}}graph(){return{...this.nodes}}};var te=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:100,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},se=class{cache;maxSize;constructor(e){this.cache=new Map,this.maxSize=e}get(e){const t=this.cache.get(e);return void 0!==t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}},ie=class{constructor(e){this.manager=e}get workspace(){return this.manager.workspace()}roles(){return this.manager.ctx().roles.list()}role(e){return this.manager.ctx().roles.get(e)}async createRole(e,t,s,i,r=[]){if(this.workspace.index.roles[e])return b({code:"DUPLICATE_KEY",resource:"role",key:e});const n={name:e,label:t,description:i,persona:s,preferences:r,topics:[]};return this.manager.dispatch({type:"role:add",payload:n,timestamp:(new Date).toISOString()})}async updateRole(e,t){return this.workspace.index.roles[e]?this.manager.dispatch({type:"role:update",payload:{name:e,...t},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return b({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?b({code:"INVALID_COMMAND",reason:`Cannot delete role "${e}" — it is still referenced by one or more sessions`}):this.manager.dispatch({type:"role:delete",payload:{name:e},timestamp:(new Date).toISOString()})}async addPreference(e,t){const s={id:crypto.randomUUID(),content:e,topics:t,timestamp:(new Date).toISOString()};return this.manager.dispatch({type:"preference:add",payload:s,timestamp:s.timestamp})}preferences(){return this.manager.ctx().preferences.list()}async addContext(e,t,s,i){const r={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:i};return this.manager.dispatch({type:"context:add",payload:r,timestamp:r.timestamp})}context(){return this.manager.ctx().context.list()}async registerBlob(e,t,s){const i=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!i.ok)return b(i.error);const r=i.value,n=r?.index?.blobs;if(!n)return b({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(n)[0];if(!o)return b({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=n[o];if(!a)return b({code:"BACKEND_ERROR",reason:"Blob record missing"});return w({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},re=class e{constructor(e,t,s,i){this._id=e,this.manager=t,this.processor=s,this.turnRepository=i,this.workspace=new ie(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,i){s.ctx().workspace;const r=new Z(s.ctx().turns,s.ctx().sessions),n=new e(t,s,i,r);return await n.sync(),n}async sync(){await this._setRole(),await this._setPreference(),await this.refreshTurnTree()}close(){this.unsubscribe?.()}async _setRole(){const e=this.meta();if(!e)return;const t=await this.manager.ctx().roles.get(e.role);this._role=t||{name:e.role,label:e.role,persona:"",preferences:[],topics:[]}}async _setPreference(){const e=this.meta();e&&(this._preferences=await this.manager.ctx().preferences.load(e.preferences||[]))}id(){return this._id}ws(){return this.manager.workspace()}meta(){return this.ws().index.sessions[this._id]}label(){return this.meta()?.label}role(){return this._role}topics(){return this.meta()?.topics??[]}preferences(){return this._preferences}head(){return this.meta()?.head??null}turns(){return this.tree.chain()}async siblings(e){return this.tree.getTurnSiblings(e)}async branchInfo(e){return this.tree.branchInfo(e)}async getTurn(e){return this.tree.graph()[e]}async rename(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,label:e},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async setTopics(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async setModel(e){return this.meta()?this.updateMetadata({model:e}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async updateMetadata(e){const t=this.meta();if(!t)return b({code:"NOT_FOUND",resource:"session",id:this._id});const s={...t.metadata||{},...e};return this.dispatch({type:"session:update",payload:{sessionId:this._id,metadata:s},timestamp:(new Date).toISOString()})}async addTopics(e){return this.meta()?this.dispatch({type:"session:topics:add",payload:{sessionId:this._id,topics:e},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});const t=await this.dispatch({type:"session:preferences:override",payload:{sessionId:this._id,preferences:e},timestamp:(new Date).toISOString()});return t.ok&&await this._setPreference(),t}async setContext(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,context:e},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async addContext(e){const t=this.meta();if(!t)return b({code:"NOT_FOUND",resource:"session",id:this._id});const s=Array.from(new Set([...t.context||[],...e]));return this.setContext(s)}async removeContext(e){const t=this.meta();if(!t)return b({code:"NOT_FOUND",resource:"session",id:this._id});const s=(t.context||[]).filter((t=>!e.includes(t)));return this.setContext(s)}async setArtifacts(e){return this.meta()?this.dispatch({type:"session:update",payload:{sessionId:this._id,artifacts:e},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async fork(e,t,s,i){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:i},timestamp:(new Date).toISOString()}):b({code:"NOT_FOUND",resource:"session",id:this._id})}async dispatch(e){return this.manager.dispatch(e)}async switchRole(e){const t=this.ws();if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==X&&!t.index.roles[e])return b({code:"NOT_FOUND",resource:"role",id:e});const s=await this.dispatch({type:"session:update",payload:{sessionId:this._id,role:e},timestamp:(new Date).toISOString()});return s.ok&&await this._setRole(),s}async addTurn(e){if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});const t=this.meta(),s={...e,session:this._id,version:e.version??0,parent:e.parent??this.head()??void 0,role:e.role??t?.role,model:e.model??t?.metadata?.model},i=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:s},timestamp:s.timestamp});if(i.ok){const e={id:s.id,version:s.version};await this.refreshTurnTree(e)}return i}async recordUserTurn(e){return this.meta()?this.addTurn(e):b({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return b({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return b({code:"NOT_FOUND",resource:"session",id:this._id});const i=this.processor.process(e,this._id);let r={};const n=[];let o;for(const e of i){const t=await this.manager.dispatch(e);if(t.ok)r=k(r,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic){o=t.error;break}{const t=this.describeCommand(e);n.push({cmd:e,description:t})}}}e.metadata=o?{...e.metadata,status:"unsuccessful",error:o}:{...e.metadata,status:"success"};const a=await this.addTurn(e);if(!a.ok)return a;if(r=k(r,a.value),t&&n.length>0){const e=this.buildDenialTurn(n),t=await this.addTurn(e);t.ok&&(r=k(r,t.value))}return o?b(o):w(r)}buildDenialTurn(e){const t=new Q("user",this._id);for(const s of e)t.addText(`[System] User denied: ${s.description}.`);return t.build()}describeCommand(e){return"tool:call"===e.type?`tool execution: ${e.payload.tool}`:`command: ${e.type}`}async editTurn(e,t,s,i){if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph()[e];if(!r)return b({code:"NOT_FOUND",resource:"turn",id:e});const n=r.versions[r.activeVersion],o=Object.keys(r.versions).length,a=await this.dispatch({type:"turn:edit",payload:{sessionId:this._id,turnId:e,newBlocks:t,roleSnapshot:s??n.role,modelSnapshot:i??n.model,newVersion:o},timestamp:(new Date).toISOString()});if(a.ok){const t={id:e,version:o};await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:t},timestamp:(new Date).toISOString()}),await this.refreshTurnTree(t)}return a}async branch(e){if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return b({code:"INVALID_COMMAND",reason:"branch requires turn.parent to be set"});const t=await this.dispatch({type:"turn:branch",payload:{sessionId:this._id,turn:{...e,session:this._id}},timestamp:e.timestamp});if(t.ok){const t={id:e.id,version:e.version};await this.refreshTurnTree(t)}return t}async deleteTurn(e,t,s){if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});const i=this.tree.graph();if(!i[e]?.versions[t])return b({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const r=await this.dispatch({type:"turn:delete",payload:{sessionId:this._id,turnId:e,version:t,newHead:s},timestamp:(new Date).toISOString()});return r.ok&&await this.refreshTurnTree(s),r}async updateTurnStatus(e,t,s){const i=this.tree.graph()[e];if(!i)return b({code:"NOT_FOUND",resource:"turn",id:e});const r=i.versions[t];if(!r)return b({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const n={...r,metadata:{...r.metadata,status:s.ok?"success":"unsuccessful",error:s.ok?void 0:s.error}},o=await this.dispatch({type:"turn:update",payload:{sessionId:this._id,turn:n},timestamp:(new Date).toISOString()});return o.ok&&await this.refreshTurnTree(this.head()),o}async switchVersionLeft(e){return this.switchVersion(e,-1)}async switchVersionRight(e){return this.switchVersion(e,1)}async switchVersion(e,t){if(!this.ws())return b({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return b({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return b({code:"NOT_FOUND",resource:"turn",id:e});const i=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),r=i.indexOf(s.activeVersion);if(-1===r)return b({code:"INVALID_COMMAND",reason:"Active version not found"});const n=r+t;if(n<0||n>=i.length)return b({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=i[n],a=this.findSubtreeTip(this.tree.graph(),e,o),c=await this.dispatch({type:"session:update",payload:{sessionId:this._id,head:a},timestamp:(new Date).toISOString()});return c.ok&&await this.refreshTurnTree(a),c}async snapshot(e){const t=this,s=t.meta();if(!s)return;const i=t.ws(),r=t._role;if(!r)return;const n=await t.manager.ctx().context.getByTopics(i.index,s.topics),o=s.context?await Promise.all(s.context.map((e=>t.manager.ctx().context.get(e)))):[],a=Array.from(new Map([...n,...o].filter((e=>!!e)).map((e=>[e.key,e]))).values()),c=s.artifacts?(await Promise.all(s.artifacts.map((e=>t.manager.ctx().artifacts.get(e))))).filter((e=>!!e)):[],d=Array.from(new Set([...r.preferences,...s.preferences])),l=d.length>0?await t.manager.ctx().preferences.load(d):t._preferences;let u=[];if(e&&"string"!=typeof e){const s=e.parent?.id??t.head()?.id;u=(s?t.tree.chainFrom(s):[]).map((e=>e.versions[e.activeVersion])).filter((e=>!!e)),u.push(e)}else{u=(e?t.tree.chainFrom(e):t.tree.chain()).map((e=>e.versions[e.activeVersion])).filter((e=>!!e))}const p=[...u].reverse().find((e=>"user"===e.actor));return{id:t._id,meta:s,role:r,preferences:l,context:a,artifacts:c,model:s.metadata?.model,transcript:u,topics:s.topics,instructions:i.settings?.prompt,constraints:{role:r.constraints,session:s.constraints,turn:p?.constraints}}}async refreshTurnTree(e){this.tree=await ee.build(this._id,this.turnRepository,e)}findSubtreeTip(e,t,s){let i=t,r=s;for(;;){const t=e[i];if(!t)break;const s=t.children[r];if(!s||0===s.length)break;const n=s[0],o=e[n];if(!o)break;i=n,r=o.activeVersion}return{id:i,version:r}}},ne=class{constructor(e,t){this.manager=e,this.processor=t}openOnce=new Map;async open(e){let t=this.openOnce.get(e);t||(t=new p,this.openOnce.set(e,t));const s=await t.do((async()=>{if(!this.manager.workspace().index.sessions[e])throw new Error(`Session ${e} not found in workspace index`);return re.create(e,this.manager,this.processor)}));if(s.error)throw s.error;return s.value}close(e){this.openOnce.delete(e)}async delete(e){const t=await this.manager.dispatch({type:"session:delete",payload:{sessionId:e},timestamp:(new Date).toISOString()});if(t.ok)return this.close(e),t.value=void 0,t;throw t.error}async has(e){return!this.manager.workspace().index.sessions[e]}async create(e){const s=t.v7(),i=e.metadata??{},r=await this.manager.dispatch({type:"session:create",payload:{id:s,label:e.label,role:e.role,topics:e.topics,preferences:e.preferences??[],metadata:{...i,created:(new Date).toISOString()}},timestamp:(new Date).toISOString()});if(r.ok)return this.open(s);throw r.error}list(){return Object.values(this.manager.workspace().index.sessions)}metadata(e){return this.manager.workspace().index.sessions[e]}},oe=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const i=await v(e),r=await this.getRecord(i);if(r){const e={...r,refCount:r.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(i,e),w(this.reference(e))}const n={sha256:i,mediaType:t,sizeBytes:e.byteLength,filename:s,refCount:1,remoteIds:{},createdAt:(new Date).toISOString(),lastUsedAt:(new Date).toISOString()};return this.storage.registerBlob?await this.storage.registerBlob(n,e):(await this.storage.storeBytes(i,e),await this.storage.saveRecord(n)),this.cache.set(i,n),this.bus.emit({name:"blobs:changed",payload:{sha256:i,record:n}}),w(this.reference(n))}async retain(e){const t=await this.getRecord(e);if(!t)return b({code:"NOT_FOUND",resource:"blob",id:e});const s={...t,refCount:t.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(s),this.cache.set(e,s),w(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return b({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),i={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),w(void 0)}async purge(e){return await this.storage.deleteBytes(e),await this.storage.deleteRecord(e),this.cache.delete(e),this.bus.emit({name:"blobs:changed",payload:{sha256:e}}),w(void 0)}async recordRemoteId(e,t,s,i){const r=await this.getRecord(e);if(!r)return b({code:"NOT_FOUND",resource:"blob",id:e});const n={...r,remoteIds:{...r.remoteIds,[t]:{id:s,timestamp:i||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(n),this.cache.set(e,n),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:n}}),w(void 0)}async getRecord(e){const t=this.cache.get(e);if(t)return t;const s=await this.storage.loadRecord(e);return s&&this.cache.set(e,s),s}async getAllRecords(){const e=await this.storage.listRecords(),t={};for(const s of e)t[s.sha256]=s,this.cache.set(s.sha256,s);return t}reference(e){return{sha256:e.sha256,mediaType:e.mediaType,sizeBytes:e.sizeBytes,filename:e.filename}}async resolve(e,t){const s=await this.getRecord(e.sha256);if(!s)return w(null);if(t){const e=s.remoteIds[t];if(e)return w({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const i=await this.storage.loadBytes(s.sha256);return w(i?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:i}:null)}const i=await this.storage.loadBytes(s.sha256);return w(i?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:i}:null)}async resolveMany(e,t){const s=new Map;for(const i of e){const e=await this.resolve(i,t);if(!e.ok)return b(e.error);if(null===e.value)return b({code:"BLOB_ERROR",reason:`Unable to resolve blob ${i.sha256}${t?` with adapter ${t}`:""}`});s.set(i.sha256,e.value)}return w(s)}},ae=class{constructor(e,t,s){this.collection=e,this.cache=t,this.registry=s}delegates=new Map;registerDelegate(e,t){this.delegates.set(e,t)}async get(e,t){const s=this.cache.get(e);if(s)return s;if(t){const s=this.delegates.get(t);if(s){const t=await s.get(e);return t&&this.cache.set(e,t),t}}const i=await this.collection.find({field:"key",operator:"eq",value:e});if(!i)return null;const r=i.state();return this.cache.set(e,r),r}async add(e){const t=this.delegates.get(e.content.kind);t?await t.add(e):await this.collection.create(e),this.cache.set(e.key,e)}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"}),t=((await e.next()).value||[]).map((e=>e.state()));for(const e of this.delegates.values()){const s=await e.list();t.push(...s)}return t}async update(e,t,s){if(s){const i=this.delegates.get(s);if(i){const s=await i.update(e,t);return s&&this.cache.set(e,s),s}}const i=await this.collection.find({field:"key",operator:"eq",value:e});if(!i)return null;await i.update(t);const r=i.state();return this.cache.set(e,r),r}async delete(e,t){if(t){const s=this.delegates.get(t);if(s){const t=await s.delete(e);return t&&this.cache.delete(e),t}}const s=await this.collection.find({field:"key",operator:"eq",value:e});if(!s)return!1;const i=await s.delete();return i&&this.cache.delete(e),i}async getByTopics(e,t){const s=new Map;for(const i of t){const t=e.topics[i];t&&t.contextKeys.forEach((t=>{const i=e.context[t],r=i?.kind||"unknown";s.has(r)||s.set(r,new Set),s.get(r).add(t)}))}if(0===s.size)return[];const i=[],r=[];for(const[e,t]of s.entries()){if(this.delegates.get(e))for(const s of t){const t=await this.get(s,e);t&&i.push(t)}else t.forEach((e=>r.push(e)))}if(r.length>0){const e=[];for(const t of r){const s=this.cache.get(t);s?i.push(s):e.push(t)}if(e.length>0){const t=await this.collection.filter({operator:"or",conditions:e.map((e=>({field:"key",operator:"eq",value:e})))});for(const e of t){const t=e.state();this.cache.set(t.key,t),i.push(t)}}}return i.sort(((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime()))}summarize(e){const t=this.registry?.get(e.content.kind);return t?t.summarize(e):{kind:e.content.kind,key:e.key,topics:e.topics,timestamp:e.timestamp,metadata:e.metadata}}},ce=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"key",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.key,e)}async update(e,t){const s=await this.collection.find({field:"key",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"key",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}async getByTopics(e,t){for(const e of t);return[]}summarize(e){return{key:e.key,version:e.version,topics:e.topics||[],timestamp:e.updated||e.created||(new Date).toISOString(),label:e.label,status:e.status}}},de=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async load(e){if(0===e.length)return[];const t=[],s=[];for(const i of e){const e=this.cache.get(i);e?s.push(e):t.push(i)}if(t.length>0){const e=await this.collection.filter({operator:"or",conditions:t.map((e=>({field:"id",operator:"eq",value:e})))});for(const t of e){const e=t.state();this.cache.set(e.id,e),s.push(e)}}return s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{id:e.id,topics:e.topics,timestamp:e.timestamp,snippet:e.content.slice(0,100)}}},le=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.name,e)}async update(e,t){const s=await this.collection.find({field:"name",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"name",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return{name:e.name,label:e.label,description:e.description,preferences:e.preferences?.length??0,topics:e.topics??[],constraints:e.constraints}}},ue=class{constructor(e,t){this.collection=e,this.cache=t}async get(e){const t=this.cache.get(e);if(t)return t;const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;const i=s.state();return this.cache.set(e,i),i}async add(e){await this.collection.create(e),this.cache.set(e.id,e)}async update(e,t){const s=await this.collection.find({field:"id",operator:"eq",value:e});if(!s)return null;await s.update(t);const i=s.state();return this.cache.set(e,i),i}async delete(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(e),s}async list(){const e=await this.collection.list({limit:1e3,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}},pe=class{constructor(e,t){this.collection=e,this.cache=t}key({id:e,session:t,version:s}){return`${t}:${s}:${e}`}async find({id:e,session:t,version:s},i=!0){const r=this.key({id:e,session:t,version:s});this.cache.get(r)&&this.cache.get(r);const n=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e},{field:"session",operator:"eq",value:t},{field:"version",operator:"eq",value:s}]});return n?(i&&this.cache.set(r,n),n):null}async get(e){return this.find(e)}async add(e){const t=await this.collection.create(e);this.cache.set(this.key(e),t)}async update(e,t){const s=await this.find(e);return s?(await s.update(t),s.state()):null}async listBySession(e){return(await this.collection.filter({field:"session",operator:"eq",value:e})).map((e=>e.state()))}async delete(e){const t=await this.find(e,!1);if(!t)return!1;const s=await t.delete();return s&&this.cache.delete(this.key(e)),s}},he=(e={})=>({id:e.id??t.v7(),settings:k({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:k({id:t.v7(),name:"Unnamed Project"},e.project),index:k({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}},e.index)});function me(){return(new Date).toISOString()}function fe(e,t,s){const i=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(s??{})]),r={};for(const n of i){const i=e?.[n]??{},o=t?.[n]??{},a=s?.[n]??{};r[n]={temperature:a.temperature??o.temperature??i.temperature,tokens:{max:a.tokens?.max??o.tokens?.max??i.tokens?.max,stops:a.tokens?.stops??o.tokens?.stops??i.tokens?.stops,thought:a.tokens?.thought??o.tokens?.thought??i.tokens?.thought}}}return r}var ye="blob_bytes",ge="blob_records";function we(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function be(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var ke={};function ve(e){let t=e;return(t.match(/```/g)||[]).length%2!=0&&(t+="\n```"),t.includes('\\"')&&!t.includes('"')&&(t=t.replace(/\\"/g,'"')),t}((e,t)=>{for(var i in t)s(e,i,{get:t[i],enumerable:!0})})(ke,{GOOGLE_MODELS:()=>Oe,GOOGLE_MODELS_COMMON:()=>_e,GOOGLE_MODELS_EMBEDDING:()=>Ne,GOOGLE_MODELS_PRO:()=>Te,GoogleGenAIAdapter:()=>Ee,extractModelResponse:()=>Re,mappings:()=>xe});var xe={text:{to:({block:e})=>({text:e.text}),from:e=>({id:t.v4(),type:"text",text:e.text})},summary:{to:({block:e})=>({text:`[Summary]: ${e.text}`}),from:e=>({id:t.v4(),type:"summary",text:e.text})},thinking:{to:({block:e})=>({text:e.thinking}),from:e=>({id:t.v4(),type:"thinking",thinking:e.thinking})},checkpoint:{to:({block:e})=>({text:S(e.state)}),from:e=>({id:t.v4(),type:"checkpoint",state:e.state})},"tool:use":{to:({block:e})=>({functionCall:{name:e.name,args:e.input}}),from:e=>({id:t.v4(),type:"tool:use",name:e.functionCall?.name??e.name,input:e.functionCall?.args??e.input??{}})},"tool:result":{to:({block:e})=>({functionResponse:{name:e.useId,response:{result:e.content}}}),from:e=>({id:t.v4(),type:"tool:result",useId:e.useId,content:e.content,isError:e.isError})},"role:transition":{to:({block:e})=>({text:`[Role transition: ${e.previousRole??"none"} → ${e.newRole}]`}),from:e=>({id:t.v4(),type:"role:transition",previousRole:e.previousRole,newRole:e.newRole})},artifact:{to:({block:e})=>({text:`[artifact:${e.key||"new"}] (${e.label})\n${e.content?.text||""}`}),from:e=>({id:t.v4(),type:"artifact",key:e.key,label:e.label,description:e.description,status:e.status,content:e.content})},"artifact:update":{to:({block:e})=>({text:`[Artifact Update: ${e.key}]`}),from:e=>({id:t.v4(),type:"artifact:update",key:e.key,status:e.status,content:e.content,patch:e.patch})},image:{to:async({block:e,resolve:t})=>{const s=e.ref;if(!s)return null;const i=await t(s);if(!i.ok||!i.value)return null;const{value:r}=i;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:x(r.data),mimeType:r.mediaType}}},from:e=>e},document:{to:async({resolve:e,block:t})=>{const s=t.ref;if(!s)return null;const i=await e(s);if(!i.ok||!i.value)return null;const{value:r}=i;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:x(r.data),mimeType:r.mediaType}}},from:e=>e}},Oe=[{provider:"google",name:"gemini-3.1-pro",label:"Gemini 3.1 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3-flash-preview",label:"Gemini 3 Flash Preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3,cache:{read:.05,write:1}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3.1-flash-lite",label:"Gemini 3.1 Flash Lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-pro",label:"Gemini 2.5 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10,cache:{read:.125,write:4.5}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash",label:"Gemini 2.5 Flash",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.3,output:2.5,cache:{read:.03,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-lite",label:"Gemini 2.5 Flash Lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4,cache:{read:.01,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-3-pro",label:"Gemini 3 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-image",label:"Gemini 2.5 Flash Image",window:{size:4096,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"image",scale:0,cost:{input:.02,output:0}}],capacity:[{unit:"call",max:100,period:60}]},{provider:"google",name:"gemini-2.5-flash-live",label:"Gemini 2.5 Flash Live",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-3.1-flash-live",label:"Gemini 3.1 Flash Live",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-2.5-computer-use",label:"Gemini 2.5 Computer Use",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10}}],capacity:[{unit:"call",max:200,period:60},{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-001",label:"Gemini Embedding 001",window:{size:2048,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.5,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-2",label:"Gemini Embedding 2",window:{size:8192,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.3,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-e2b-it",label:"Gemma 4 E2B",window:{size:131072,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-e4b-it",label:"Gemma 4 E4B",window:{size:131072,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-26b-a4b-it",label:"Gemma 4 26B A4B",window:{size:262144,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-31b-it",label:"Gemma 4 31B",window:{size:262144,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]}],Se=new Set(["gemini-2.5-flash","gemini-2.5-flash-lite","gemini-3-flash-preview","gemini-3.1-flash-lite","gemma-4-26b-a4b-it","gemma-4-31b-it"]),_e=Oe.filter((e=>Se.has(e.name))),Te=Oe.filter((e=>e.name.includes("pro"))),Ne=Oe.filter((e=>e.name.includes("embedding")));function Re(e){const s=e.candidates?.[0],i=[];if(!s?.content?.parts)return{ok:!1,thinking:i,error:{code:"BACKEND_ERROR",reason:"No valid content parts in response"}};let r;for(const e of s.content.parts)if(e.thought)i.push((n=e.text??"",{id:t.v7(),type:"thinking",thinking:n}));else if(e.text){r=e;break}var n;if(!r)return i.length>0?{ok:!0,thinking:i,rawBlocks:[]}:{ok:!1,thinking:i,error:{code:"BACKEND_ERROR",reason:"Response missing JSON part"}};const o=function(e){try{const t=JSON.parse(e);return t.blocks&&Array.isArray(t.blocks)?w(t.blocks):b({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return b({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(r.text);return o.ok?{ok:!0,thinking:i,rawBlocks:o.value}:{ok:!0,thinking:i,fallback:r.text}}function De(e){return Math.ceil(e.length/4)}var Ee=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const i=this._models.get(s.model);if(!i)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=i,this.registerMappings()}model;_models;registerMappings(){const{assembler:t}=this.services;for(const[s,i]of Object.entries(xe))t.registry.update(s,{mappings:{[e.provider()]:i}})}async status(t){return{provider:e.provider(),model:this.model.name,ready:!0,window:this.model.window,feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4}}],rate:{load:0,capacity:[{unit:"call",max:1e3,period:60},{unit:"token",max:4e6,period:60}]}}}async resolve(s){const{prompt:i}=s,{assembler:r,blockRegistry:n}=this.services,o=i.model&&this._models.get(i.model)||this.model,{system:a,sections:c,transcript:d}=await r.build(e.provider(),i,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t}))),l={role:"system",parts:[{text:a}]},u=i.constraints[o.name]??{tokens:{}},p=n.schema(),h={model:o.name,contents:d,config:{systemInstruction:l,thinkingConfig:{includeThoughts:!0},responseMimeType:"application/json",responseSchema:p,...void 0!==u.temperature&&{temperature:u.temperature},...void 0!==u.tokens.max&&{maxOutputTokens:u.tokens.max},...u.tokens.stops?.length&&{stopSequences:u.tokens.stops},...void 0!==u.tokens.thought&&{thinkingConfig:{includeThoughts:!0,thinkingBudget:u.tokens.thought}}}},m=d.flatMap((e=>e.parts??[])).map((e=>e.text??"")).join(""),f=De(a),y=De(m),g=f+y,k=this;return{model:o.name,role:i.role.name,instructions:c,transcript:i.transcript,context:i.system.context,artifacts:i.system.artifacts,preferences:i.system.preferences,constraints:u,tokens:{breakdown:{system:f,transcript:y},total:g,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-g},async execute(){let s;try{s=await k.client.models.generateContent(h)}catch(e){return b({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const r=Re(s);if(!r.ok)return b(r.error);let n;var a;n="fallback"in r?[...r.thinking,(a=r.fallback,{id:t.v7(),type:"text",text:ve(a)})]:[...r.thinking,...k.services.assembler.parse(e.provider(),r.rawBlocks)];const c=new Q("assistant",i.session);c.withModel(o.name),c.withRole(i.role.name);for(const e of n)c.addBlock(e);return w({turn:c.build(),effects:[]})},async*executeStream(){let e;try{e=await k.client.models.generateContentStream(h)}catch(e){const s=e instanceof Error?e.message:String(e),r=new Q("assistant",i.session);return r.addBlock({id:t.v7(),type:"text",text:`[Stream error: ${s}]`}),void(yield{turn:r.build(),effects:[]})}const s=[];for await(const i of e){const e=i.candidates?.[0];if(e?.content?.parts)for(const i of e.content.parts)i.thought||i.text&&(s.push(i.text),yield{blocks:[{id:t.v7(),type:"text",text:i.text}]})}const r=s.join(""),n=new Q("assistant",i.session);n.addBlock({id:t.v7(),type:"text",text:r}),yield{turn:n.build(),effects:[]}}}}static provider(){return"google"}static models(){return _e}};exports.COLLECTIONS=f,exports.CoreTurnProcessor=class{process(e,t){const s=[],i=(new Date).toISOString();for(const r of e.blocks)"artifact"===r.type?s.push(this.handleAddArtifact(r,t,i)):"artifact:update"===r.type&&s.push(this.handleUpdateArtifact(r,t,i));return s}handleAddArtifact(e,s,i){const r=e.id||t.v7(),n=e.label||`Untitled Artifact ${O(r)}`,o=e.content.extension||"txt",a=n.split(" ").join("-").replace(new RegExp(`\\.${o}$`),"");return{type:"artifact:add",timestamp:i,payload:{...{id:r,label:n,type:"artifact",key:(e.key?e.key:`${a||O(n)}.${o}`).toLowerCase(),version:1,description:e.description||"",content:e.content,status:e.status||"complete",created:i,updated:i},sessionId:s}}}handleUpdateArtifact(e,t,s){return{type:"artifact:update",timestamp:s,payload:{sessionId:t,key:e.key,status:e.status,content:e.content,patch:e.patch}}}},exports.DefaultPromptBuilder=class{constructor(e,t,s){this.contextRegistry=e,this.retriever=t,this._summarizer=s}NOISE_BLOCK_TYPES=new Set(["thinking","role:transition","artifact","artifact:update"]);addNoiseBlock(e){this.NOISE_BLOCK_TYPES.add(e)}removeNoiseBlock(e){this.NOISE_BLOCK_TYPES.delete(e)}stripNoiseBlocks(e){return e.map((e=>{const t=e.blocks.filter((e=>!this.NOISE_BLOCK_TYPES.has(e.type)));return t.length===e.blocks.length?e:{...e,blocks:t}})).filter((e=>e.blocks.length>0))}async build(e,s,i={}){const r=[],{resolved:n}=function(e){const t=[],s=new Map;for(const i of e)for(const e of i.topics){const r=s.get(e);if(!r){s.set(e,i);continue}const n=new Date(r.timestamp).getTime(),o=new Date(i.timestamp).getTime();o>n?(t.push({topic:e,kept:i.id,dropped:r.id}),s.set(e,i)):n>o&&t.push({topic:e,kept:r.id,dropped:i.id})}const i=new Map,r=new Map;for(const t of e)r.set(t.id,t.topics.length);for(const e of t)i.set(e.dropped,(i.get(e.dropped)??0)+1);const n=new Set;for(const t of e){const e=i.get(t.id)??0,s=r.get(t.id)??0;s>0&&e>=s&&n.add(t.id)}return{resolved:e.filter((e=>!n.has(e.id))),conflicts:Array.from(new Map(t.map((e=>[`${e.topic}:${e.dropped}`,e]))).values())}}(e.preferences),o=function(e,t=3){return e.filter((e=>"user"===e.actor)).slice(-t).flatMap((e=>e.blocks.filter((e=>"text"===e.type)).map((e=>e.text)).filter(Boolean)))}(e.transcript),a=this.retriever.rank({entries:e.context,recentMessages:o,topics:e.topics,config:i.retrieverConfig}),c=[],d=[];for(const e of a){const t=this.contextRegistry.get(e.content.kind);if(!t){r.push(`No ContextDefinition found for kind: ${e.content.kind}`);continue}const s=t.render(e),i=Array.isArray(s)?s:[s];"system"===t.target?c.push({label:`context:${e.content.kind}:${e.key}`,content:i.map((t=>"text"===t.type?t.text:`[${e.content.kind}] ${JSON.stringify(t,null,2)}`)).join("\n"),position:"after:context"}):d.push(...i)}const l=e.transcript.map((e=>({...e,blocks:e.blocks.filter((e=>"artifact"!==e.type&&"artifact:update"!==e.type&&!this.NOISE_BLOCK_TYPES.has(e.type)))}))).filter((e=>e.blocks.length>0));let u=l;i.compress&&(u=function(e){let t=-1;for(let s=0;s<e.length;s++)e[s].blocks.some((e=>"checkpoint"===e.type))&&(t=s);return-1===t?e:e.slice(t)}(l));const p=[];if(d.length>0){const s=u.length>0?u[0].timestamp:me();p.push((h=e.id,m="system",f=d,y=s,{id:t.v7(),session:h,version:0,actor:m,blocks:f,timestamp:y??me()}))}var h,m,f,y;const g=[...p,...u],b=function(e,t){const s=new Map;for(const t of e)if("blob"===t.content.kind){const{sha256:e,mediaType:i,sizeBytes:r,filename:n,previewUrl:o}=t.content;s.has(e)||s.set(e,{sha256:e,mediaType:i,sizeBytes:r,filename:n,previewUrl:o})}for(const e of t)for(const t of e.blocks)if("image"===t.type||"document"===t.type){const e=t.ref;e&&!s.has(e.sha256)&&s.set(e.sha256,e)}return s}(a,g);return w({session:e.id,model:e.model,system:{persona:e.role.persona,instructions:e.instructions,preferences:n,context:[],artifacts:e.artifacts,extensions:c},transcript:g,blobs:b,role:e.role,constraints:fe(e.constraints.role,e.constraints.session,e.constraints.turn),warnings:r})}},exports.EMPTY_SYSTEM_ROLE=X,exports.GoogleAdapter=ke,exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const s=indexedDB.open(this.dbName,1);s.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},s.onsuccess=()=>e(s.result),s.onerror=()=>t(s.error),s.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains(ye)||e.createObjectStore(ye,{keyPath:"sha256"}),e.objectStoreNames.contains(ge)||e.createObjectStore(ge,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const s=indexedDB.deleteDatabase(this.dbName);s.onsuccess=()=>e(),s.onerror=()=>t(s.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const s=this.readTx(ye);if(await we(s.objectStore(ye).get(e)))return;const i=this.writeTx(ye);i.objectStore(ye).put({sha256:e,data:t}),await be(i)}async loadBytes(e){const t=this.readTx(ye),s=await we(t.objectStore(ye).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(ye);return await we(t.objectStore(ye).count(e))>0}async deleteBytes(e){const t=this.writeTx(ye);t.objectStore(ye).delete(e),await be(t)}async saveRecord(e){const t=this.writeTx(ge);t.objectStore(ge).put(e),await be(t)}async loadRecord(e){const t=this.readTx(ge);return await we(t.objectStore(ge).get(e))??null}async deleteRecord(e){const t=this.writeTx(ge);t.objectStore(ge).delete(e),await be(t)}async listRecords(){return we(this.readTx(ge).objectStore(ge).getAll())}async exportAllBytes(){const e=this.readTx(ye);return(await we(e.objectStore(ye).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,i)=>{const r=this.getDB().transaction([ye,ge],"readwrite"),n=r.objectStore(ye),o=r.objectStore(ge),a=n.count(e.sha256);a.onsuccess=()=>{0===a.result&&n.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>i(a.error),r.oncomplete=()=>s(),r.onerror=()=>i(r.error),r.onabort=()=>i(new Error("registerBlob transaction aborted"))}))}},exports.JaccardContextRetriever=class{constructor(e){this.contextRegistry=e}rank(e){const{entries:t,recentMessages:s,config:i={}}=e,r=i.minScore??0,n=i.freshnessHalfLifeDays??30,o=i.recentMessageWindow??3;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,n)-this.freshnessWeight(e.timestamp,n)));const a=this.tokenize(s.slice(-o).join(" "));return t.map((e=>{const t=function(e,t){const s=t.get(e.content.kind);return s?s.toString(e):""}(e,this.contextRegistry);return{entry:e,score:.7*this.jaccardSimilarity(a,this.tokenize(t))+.3*this.freshnessWeight(e.timestamp,n)}})).filter((e=>e.score>r)).sort(((e,t)=>t.score-e.score)).map((e=>e.entry))}tokenize(e){return new Set(e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter((e=>e.length>2)))}jaccardSimilarity(e,t){if(0===e.size&&0===t.size)return 0;let s=0;for(const i of e)t.has(i)&&s++;const i=e.size+t.size-s;return 0===i?0:s/i}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},exports.LRUCache=se,exports.MemoryBlobStorage=class{bytes=new Map;records=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async saveRecord(e){this.records.set(e.sha256,{...e})}async loadRecord(e){return this.records.get(e)??null}async deleteRecord(e){this.records.delete(e)}async listRecords(){return Array.from(this.records.values()).map((e=>({...e})))}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}async registerBlob(e,t){this.bytes.has(e.sha256)||this.bytes.set(e.sha256,t),this.records.set(e.sha256,{...e})}},exports.PromptAssembler=B,exports.Session=re,exports.SessionManager=ne,exports.TurnBuilder=Q,exports.TurnTree=ee,exports.WorkspaceApi=ie,exports.WorkspaceManager=_,exports.WorkspaceRegistry=class{constructor(e){this.db=e}async list(){const e=m(this.db);await e.open();const t=await e.collection(f.WORKSPACE);return new te(t,new se(100)).list()}async delete(e){const t=m(this.db);await t.open();const s=await t.collection(f.WORKSPACE);return new te(s,new se(1)).delete(e)}async purge(){this.db.clear()}},exports.bufferToBase64=x,exports.computeSHA256=v,exports.createDefaultAssembler=function(e,t){return new B(e,t)},exports.createEmptySession=(e={})=>({id:t.v7(),label:"New Conversation",role:"assistant-default",topics:[],preferences:[],metadata:{created:(new Date).toString(),updated:(new Date).toString()},...e,head:e.head?e.head:void 0}),exports.createEmptyTurn=(e={},s)=>({id:e.id??t.v7(),version:e.version??0,session:e.session??s?.id??t.v7(),actor:"user",blocks:[{id:t.v7(),type:"text",text:"Hello, world!"}],timestamp:(new Date).toString(),role:s?.role,...e,parent:e.parent?e.parent:void 0}),exports.createEmptyWorkspace=he,exports.createWorkspace=async function(t){const{blobStorage:s,eventBus:r=e.createEventBus(),getWorkspace:n,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:l=[],extensions:u=[]}=t,p=m(t.db),h=[...u.flatMap((e=>e.schemas??[]))],y={...u.reduce(((e,t)=>({...e,...t.reducers})),{})},g=[...u.flatMap((e=>e.middleware??[]))],w=[...u.flatMap((e=>e.indexers??[]))],b=u.flatMap((e=>e.blocks??[]));await p.open(h);const k={workspace:await p.collection(f.WORKSPACE),role:await p.collection(f.ROLE),preference:await p.collection(f.PREFERENCE),context:await p.collection(f.CONTEXT),session:await p.collection(f.SESSION),topic:await p.collection(f.TOPIC),turn:await p.collection(f.TURN),artifact:await p.collection(f.ARTIFACT)},v=new oe(s,new se(200),r),x=new J,O={workspaceStore:new te(k.workspace,new se(1)),roles:new le(k.role,new se(100)),preferences:new de(k.preference,new se(500)),context:new ae(k.context,new se(500),x),artifacts:new ce(k.artifact,new se(100)),topics:new T(k.topic,new se(100)),sessions:new ue(k.session,new se(50)),turns:new pe(k.turn,new se(50)),blobs:v,tools:d,db:p,indexers:[...i,...w]};await Promise.all(u.map((async e=>{if(e.stores){const t=await e.stores(O);Object.assign(O,t)}})));const S=new _({ctx:O,getWorkspace:n,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=n();await O.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:r});Object.entries(L).forEach((([e,t])=>{S.register(e,t)})),Object.entries(y).forEach((([e,t])=>{S.register(e,t)})),S.use(A),S.use(j),g.forEach((e=>{S.use(e)}));const N=new ne(S,a),R=new H;b.forEach((e=>R.register(e))),u.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(x.register(e),e.store){const t=e.store(O);O.context.registerDelegate(e.kind,t)}}))}));const D=new K(l),E=O.blobs.resolve.bind(O.blobs),I={assembler:new B(R,E),processor:a,blobResolver:E,blockRegistry:R,contextRegistry:x,models:D},C=async e=>{await S.dispatch({type:"workspace:sync",payload:void 0,timestamp:(new Date).toISOString()});let t=n();await S.dispatch({type:"workspace:create",payload:e.workspace,timestamp:(new Date).toISOString()}),t=n();const s=[];if(e.roles)for(const i of e.roles)t.index.roles[i.name]||(await S.dispatch({type:"role:add",payload:i,timestamp:(new Date).toISOString()}),s.push(i.name));return e.workspace.settings.defaultRole&&t.settings.defaultRole!==e.workspace.settings.defaultRole&&await S.dispatch({type:"workspace:sync",payload:{settings:{...t.settings,defaultRole:e.workspace.settings.defaultRole}},timestamp:(new Date).toISOString()}),{workspace:n(),roles:s}};if(t.bootstrap){const e=n();if(!e||!e.index){const e=he({id:t.bootstrap.workspace.id,settings:t.bootstrap.workspace.settings,project:t.bootstrap.workspace.project});await o(e)}await C(t.bootstrap)}return{manager:S,sessions:N,ctx:O,services:I,bootstrap:C}},exports.createWorkspaceDatabase=m,exports.del=function(){return y},exports.error=b,exports.getExtension=function(e,t){return e.extensions[t]},exports.merge=k,exports.omitNullUndefined=function(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))},exports.sessionStateToMarkdown=S,exports.shortHash=O,exports.success=w;
1
+ "use strict";var e=require("uuid"),t=require("@asaidimu/utils-database"),r=require("ai"),s=Object.defineProperty,i=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},n={VALIDATION_FAILED:{code:"VAL-001",name:"VALIDATION_FAILED",description:"Input validation failed due to one or more invalid fields",category:"validation",httpStatus:400,logLevel:"warn"},REQUIRED_FIELD_MISSING:{code:"VAL-002",name:"REQUIRED_FIELD_MISSING",description:"A required field was not provided in the request",category:"validation",httpStatus:400,logLevel:"warn"},INVALID_FORMAT:{code:"VAL-003",name:"INVALID_FORMAT",description:"Field value does not match expected format",category:"validation",httpStatus:400,logLevel:"warn"},NOT_FOUND:{code:"DB-001-NF",name:"NOT_FOUND",description:"The requested resource could not be found",category:"database",httpStatus:404,logLevel:"info",action:"Verify the resource identifier exists before accessing"},DUPLICATE_KEY:{code:"DB-002-DUP",name:"DUPLICATE_KEY",description:"A unique constraint violation occurred",category:"database",httpStatus:409,logLevel:"warn",action:"Check if the resource already exists before creation"},RESOURCE_LOCKED:{code:"DB-003-LOCK",name:"RESOURCE_LOCKED",description:"The resource is currently locked by another operation",category:"database",httpStatus:409,logLevel:"warn",action:"Retry the operation after a brief delay"},PERMISSION_DENIED:{code:"AUTH-001-DENIED",name:"PERMISSION_DENIED",description:"The authenticated user lacks permission for this operation",category:"auth",httpStatus:403,logLevel:"warn",action:"Check user roles and permissions"},UNAUTHENTICATED:{code:"AUTH-002-UNAUTH",name:"UNAUTHENTICATED",description:"Authentication is required for this operation",category:"auth",httpStatus:401,logLevel:"info",action:"Provide valid authentication credentials"},INVALID_COMMAND:{code:"BUS-001",name:"INVALID_COMMAND",description:"The command or operation is invalid for the current state",category:"business",httpStatus:400,logLevel:"warn"},OPERATION_ABORTED:{code:"BUS-002-ABORT",name:"OPERATION_ABORTED",description:"The operation was explicitly aborted",category:"business",httpStatus:409,logLevel:"info"},INTERNAL_ERROR:{code:"SYS-001",name:"INTERNAL_ERROR",description:"An unexpected internal error occurred",category:"system",httpStatus:500,logLevel:"error",action:"Check system logs for stack traces and diagnostic information"},BACKEND_ERROR:{code:"SYS-002",name:"BACKEND_ERROR",description:"An error occurred in a backend service",category:"system",httpStatus:502,logLevel:"error"},CONCURRENCY_ERROR:{code:"CON-001",name:"CONCURRENCY_ERROR",description:"A concurrency conflict occurred during the operation",category:"concurrency",httpStatus:409,logLevel:"warn",action:"Retry the operation with updated data"}},o=new Map;var a=class e extends Error{code;codeMetadata;severity;path;operation;issues;cause;constructor(t){const r={...function(e){const t=Object.values(n).find((t=>t.code===e));if(t)return t;return o.get(e)||{code:e,name:e.replace(/-/g,"_"),description:`Unknown error: ${e}`,category:"custom",httpStatus:500,logLevel:"error",action:"Check if this error code is properly registered or handle as unknown error"}}(t.code),...t.metadata,code:t.code};super(t.message??r.description),this.name="SystemError",this.code=t.code,this.codeMetadata=r,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,e)}withPath(t){return new e({code:this.code,message:this.message,severity:this.severity,path:t,operation:this.operation,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withOperation(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:t,issues:this.issues,cause:this.cause,metadata:this.codeMetadata})}withIssue(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,t],cause:this.cause,metadata:this.codeMetadata})}withIssues(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:[...this.issues,...t],cause:this.cause,metadata:this.codeMetadata})}withCause(t){return new e({code:this.code,message:this.message,severity:this.severity,path:this.path,operation:this.operation,issues:this.issues,cause:t,metadata:this.codeMetadata})}getHttpStatus(){return this.codeMetadata.httpStatus}toLogEntry(){return{name:this.name,code:this.code,category:this.codeMetadata.category,message:this.message,path:this.path,operation:this.operation,issues:this.issues,cause:this.cause instanceof Error?this.cause.message:this.cause,stack:this.stack,timestamp:(new Date).toISOString()}}toString(){let e=`[${this.code}] ${this.message} (${this.codeMetadata.category})`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map(((e,t)=>` ${t+1}. ${e.message} [${e.code}]`)).join("\n")),this.cause&&(e+=`\nCause: ${this.cause instanceof Error?this.cause.message:String(this.cause)}`),e}},c=class e extends a{constructor(t,r){super({code:"SYNC_ERROR",message:t,cause:r}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},d=class e extends c{constructor(t){super(`[ArtifactContainer] Operation timed out: ${t}`),this.name="TimeoutError",Object.setPrototypeOf(this,e.prototype)}},l=class e extends c{constructor(t){super("[Serializer] The serializer has been marked as done!",t),this.name="SerializerExecutionDone",Object.setPrototypeOf(this,e.prototype)}},u=class{_locked=!1;_capacity;_yieldMode;waiters=[];constructor(e){this._capacity=e?.capacity??1/0,this._yieldMode=e?.yieldMode??"macrotask"}async lock(e){if(!this._locked)return void(this._locked=!0);if(this.waiters.length>=this._capacity)throw new Error(`Mutex queue is full (capacity: ${this._capacity})`);let t;const r=new Promise((e=>t=e));if(this.waiters.push(t),null==e)return void await r;let s;await Promise.race([r.then((()=>clearTimeout(s))),new Promise(((r,i)=>{s=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),i(new d("Mutex lock timed out"))}),e)}))])}tryLock(){return!this._locked&&(this._locked=!0,!0)}unlock(){if(!this._locked)throw new Error("Mutex is not locked");const e=this.waiters.shift();e?"microtask"===this._yieldMode?queueMicrotask(e):setTimeout(e,0):this._locked=!1}locked(){return this._locked}pending(){return this.waiters.length}},p=class{mutex=new u({yieldMode:"microtask"});promise=null;_value=null;_error;_done=!1;retry;throws;constructor({retry:e,throws:t}={}){this.retry=Boolean(e),this.throws=Boolean(t)}async do(e,t){return this._done?this.peek():this.promise?this._awaitWithTimeout(this.promise,t,"Once do() timed out"):(await this.mutex.lock(),this.promise?(this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")):(this.promise=(async()=>{try{this._value=await e(),this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.retry&&!this._done&&(this.promise=null)}return this.peek()})(),this.mutex.unlock(),this._awaitWithTimeout(this.promise,t,"Once do() timed out")))}doSync(e){if(this._done){if(this.throws&&this._error)throw this._error;return this.peek()}if(this.promise){const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}if(!this.mutex.tryLock()){const e=new Error("Cannot execute doSync: lock is currently held.");if(this.throws)throw e;return{value:null,error:e}}if(this.promise||this._done){if(this.mutex.unlock(),this._done){if(this.throws&&this._error)throw this._error;return this.peek()}const e=new Error("Cannot execute doSync while an async operation is pending.");if(this.throws)throw e;return{value:null,error:e}}try{const t=e();this._value=t,this._done=!0}catch(e){if(this._error=e,this.retry||(this._done=!0),this.throws)throw e}finally{this.mutex.unlock()}return this.peek()}running(){return null!==this.promise&&!this.done()}peek(){return{value:this._value,error:this._error}}get(){if(!this._done)throw new Error("Once operation is not yet complete");if(this._error)throw this._error;return this._value}reset(){if(this.running())throw new Error("Cannot reset Once while an operation is in progress.");this._done=!1,this.promise=null,this._value=null,this._error=void 0}done(){return this._done}current(){return this.promise}_awaitWithTimeout(e,t,r="Operation timed out"){if(null==t)return e;let s;return Promise.race([e.then((e=>(clearTimeout(s),e))),new Promise(((e,i)=>{s=setTimeout((()=>i(new d(r))),t)}))])}},h=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new u({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new l};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let r,s=null;try{if(this._done)throw new l;s=await e(),this._lastValue=s,this._lastError=void 0,this._hasRun=!0}catch(e){r=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:s,error:r}}peek(){return{value:this._lastValue,error:this._lastError}}hasRun(){return this._hasRun}close(){this._done=!0}pending(){return this.mutex.pending()}running(){return this.mutex.locked()}},m={uuid:e=>e,timestamp:e=>e,uri:e=>e,sha256:e=>e},g=class e extends Error{code;severity;path;operation;issues;cause;constructor(t){super(t.message),this.name="SystemError",this.code=t.code,this.severity=t.severity??"error",this.path=t.path,this.operation=t.operation,this.issues=t.issues??[],this.cause=t.cause,Object.setPrototypeOf(this,e.prototype)}withPath(t){return new e({...this,path:t})}withOperation(t){return new e({...this,operation:t})}withIssue(t){return new e({...this,issues:[...this.issues,t]})}withIssues(t){return new e({...this,issues:[...this.issues,...t]})}withCause(t){return new e({...this,cause:t})}toString(){let e=`[${this.code}] ${this.message}`;return this.path&&(e+=` at '${this.path}'`),this.operation&&(e+=` during '${this.operation}'`),this.issues.length>0&&(e+="\nIssues:\n"+this.issues.map(((e,t)=>` ${t+1}. ${e.message} [${e.code}]`)).join("\n")),e}};var f={NOT_FOUND:"NOT_FOUND",DUPLICATE_KEY:"DUPLICATE_KEY",INVALID_COMMAND:"INVALID_COMMAND",PERMISSION_DENIED:"PERMISSION_DENIED",BACKEND_ERROR:"BACKEND_ERROR",INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_FAILED:"VALIDATION_FAILED",CONCURRENCY_ERROR:"CONCURRENCY_ERROR",RESOURCE_LOCKED:"RESOURCE_LOCKED",OPERATION_ABORTED:"OPERATION_ABORTED"},y={ok:e=>({ok:!0,value:e}),fail:e=>({ok:!1,error:e})},w=class e{constructor(e,t){this.context=e,this.muted=t?.muted??!1}muted;debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t,r){const s={...r,...t instanceof Error?{error:{message:t.message,stack:t.stack}}:{error:t}};this.log("error",e,s)}child(t){const r=this.context?`${this.context}:${t}`:t;return new e(r,{muted:this.muted})}static muted(t){return new e(t,{muted:!0})}isMuted(){return this.muted}log(e,t,r){if(this.muted)return;const s=(new Date).toISOString(),i=this.context?`[${this.context}] `:"",n=r&&Object.keys(r).length>0?` | ${JSON.stringify(r)}`:"",o=`${s} ${e.toUpperCase().padEnd(5)} ${i}${t}${n}`;switch(e){case"debug":console.debug(o);break;case"info":console.info(o);break;case"warn":console.warn(o);break;case"error":console.error(o)}}},b=new w;var k=class{constructor(e,t){this.engine=e,this.serializer=t}get authorizer(){return this.engine.authorizer}async dispatch(e,t){const r=await this.serializer.do((()=>this.engine.dispatch(e,t)));return r.error?y.fail(new g({code:f.CONCURRENCY_ERROR,message:"Coordinator: Dispatch failed due to concurrency error.",cause:r.error}).withOperation("dispatch")):r.value}async transact(e,t){const r=await this.serializer.do((()=>this.engine.transact(e,t)));return r.error?y.fail(new g({code:f.CONCURRENCY_ERROR,message:"Coordinator: Transaction failed due to concurrency error.",cause:r.error}).withOperation("transact")):r.value}};function v(e){if(null==e)return e;if("object"!=typeof e&&"function"!=typeof e)return e;if("function"==typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;for(const[r,s]of e.entries())t.set(v(r),v(s));return t}if(e instanceof Set){const t=new Set;for(const r of e.values())t.add(v(r));return t}if(Array.isArray(e))return e.map(v);const t={};for(const[r,s]of Object.entries(e))t[r]=v(s);return t}var S=Symbol.for("delete"),x=e=>Array.isArray(e)?[...e]:{...e};function _(){return S}var O=function(e){const t=e?.deleteMarker||S;function r(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e:r(e)));if("object"==typeof e){const s={};for(const[i,n]of Object.entries(e))if(n!==t)if("object"==typeof n&&null!==n){const e=r(n);void 0!==e&&(s[i]=e)}else s[i]=n;return s}return e===t?void 0:e}return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?r(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=x(e),n=[{target:i,source:s}];for(;n.length>0;){const{target:e,source:r}=n.pop();for(const s of Object.keys(r)){const i=r[s];if(i!==t)if(Array.isArray(i))e[s]=i;else if("object"==typeof i&&null!==i){const t=s in e&&"object"==typeof e[s]&&null!==e[s]?e[s]:{};e[s]=x(t),n.push({target:e[s],source:i})}else e[s]=i;else delete e[s]}}return i}}({deleteMarker:S}),E=class{_type;_actor;_scopes;_meta;constructor(e,t){this._type=e,this._actor=t,this._scopes=[],this._meta={}}withScope(e){return this._scopes.push(e),this}withScopes(...e){return this._scopes.push(...e),this}setScopes(e){return this._scopes=[...e],this}withMeta(e){return Object.assign(this._meta,e),this}build(){const e={type:this._type,actor:this._actor,scopes:Object.freeze([...this._scopes]),...this._meta};return Object.freeze(e)}};function T(e,t){return new E(e,t)}var A={create:(e=m.uuid("00000000-0000-0000-0000-000000000000"))=>T("system",e).withScope("*").build(),default:T("system",m.uuid("00000000-0000-0000-0000-000000000000")).withScope("*").build(),createScoped:(e,...t)=>T("system",e).withScopes(...t).build()};function R(e,t=[],r){const s=T("user",e).withScopes(...t);return r&&s.withMeta(r),s.build()}var D=class{localState;constructor(e){this.localState=v(e.get())}get(){return this.localState}async set(e){return this.localState=O(this.localState,e),this.localState}getFinalState(){return this.localState}},N=class{constructor(e,t,r,s){this.stateManager=e,this._authorizer=t,this.reducers=r,this.logger=s}middlewares=[];get authorizer(){return this._authorizer}register(e,t,r){return this.reducers.register(t,{namespace:e,action:r})}use(e){this.middlewares.push(e)}async dispatch(e,t){return this.runDispatch(e,t,this.stateManager)}async transact(e,t){const r=new D(this.stateManager),s=t=>this.runDispatch(e,t,r),i=[];for(const r of t){const t=await s(r.do);if(!t.ok)return await this.rollbackExternalSideEffects(e,i),t;i.push(r)}return await this.stateManager.set(r.getFinalState()),y.ok(void 0)}async runDispatch(e,t,r){const s=this.reducers.get(t.type);if(!s)return y.fail(new g({code:f.INVALID_COMMAND,message:`No reducer registered for command type: ${t.type}`}).withOperation("dispatch"));const i={namespace:s.namespace,state:()=>r.get(),dispatch:t=>this.runDispatch(e,t,r)},n=this.middlewares.map((e=>e(i))).reduceRight(((e,t)=>t(e)),(async t=>{const i=await this._authorizer.authorize(e,t,r.get());if(!i.ok)return i;try{const e=await s.action(r.get(),t);return y.ok(e)}catch(e){return y.fail(new g({code:f.INTERNAL_ERROR,message:`Execution failed for command: ${t.type}`,cause:e}).withOperation("dispatch"))}})),o=await n(t);return o.ok?(await r.set(o.value),y.ok(void 0)):o}async rollbackExternalSideEffects(e,t){for(let r=t.length-1;r>=0;r--){const s=t[r],i=await this.dispatch(e,s.undo);i.ok||this.logger.error(`PANIC: External rollback failed for step: ${s.name}`,i.error)}}},I=class e{items=new Map;logger;constructor({logger:e}){this.logger=e.child("Registry")}register(e,t){if(this.logger.debug(`Attempting to register key '${e}'`,{key:e,itemType:typeof t,currentSize:this.items.size}),this.items.has(e)){const t=new g({code:f.DUPLICATE_KEY,message:`Registry error: Key '${e}' is already registered.`}).withPath(e);return this.logger.warn(`Duplicate key registration attempt: '${e}'`,{key:e,errorCode:f.DUPLICATE_KEY}),y.fail(t)}return this.items.set(e,t),this.logger.info(`Successfully registered key '${e}'`,{key:e,newSize:this.items.size}),y.ok(void 0)}unregister(e){if(this.logger.debug(`Attempting to unregister key '${e}'`,{key:e,currentSize:this.items.size}),!this.items.has(e)){const t=new g({code:f.NOT_FOUND,message:`Registry error: Key '${e}' is not registered.`}).withPath(e);return this.logger.warn(`Unregister attempt for non-existent key: '${e}'`,{key:e,errorCode:f.NOT_FOUND}),y.fail(t)}return this.items.delete(e),this.logger.info(`Successfully unregistered key '${e}'`,{key:e,newSize:this.items.size}),y.ok(void 0)}update(e,t){this.logger.debug(`Attempting to update key '${e}'`,{key:e});const r=this.items.get(e);if(!r){const t=new g({code:f.NOT_FOUND,message:`Registry error: Key '${e}' is not registered.`}).withPath(e);return this.logger.warn(`Update attempt for non-existent key: '${e}'`,{key:e,errorCode:f.NOT_FOUND}),y.fail(t)}const s={...r,...t};return this.items.set(e,s),this.logger.info(`Successfully updated key '${e}'`,{key:e}),y.ok(void 0)}get(e){const t=this.items.get(e);return void 0!==t?this.logger.debug(`Retrieved item for key '${e}'`,{key:e,found:!0}):this.logger.debug(`Item not found for key '${e}'`,{key:e,found:!1}),t}list(){const e=Array.from(this.items.values());return this.logger.debug("Listing all registry items",{count:e.length,keys:Array.from(this.items.keys())}),e}has(e){const t=this.items.has(e);return this.logger.debug(`Checking existence of key '${e}'`,{key:e,exists:t}),t}clear(){const e=this.items.size;this.items.clear(),this.logger.info("Registry cleared",{previousSize:e,clearedAt:(new Date).toISOString()})}clone(){this.logger.debug("Cloning registry",{originalSize:this.items.size});const t=new e({logger:this.logger});for(const[e,r]of this.items.entries())t.items.set(e,v(r));return this.logger.info("Registry cloned successfully",{originalSize:this.items.size,clonedSize:t.items.size}),t}entries(){const e=Object.fromEntries(this.items);return this.logger.debug("Converting registry to entries object",{keyCount:Object.keys(e).length}),e}},C=class{lock;engine;coordinator;state;registries;logger;constructor(e){this.logger=e.logger??b.child("kernel");const t=e.actions??new I({logger:this.logger});this.lock=new h,this.state=e.state,this.registries=e.registries,this.engine=new N(this.state,e.authorizer,t,this.logger.child("engine")),this.coordinator=new k(this.engine,this.lock)}get actions(){return this.engine}async rebuildIndex(){this.logger.debug("Rebuilding index...");const e=await this.registries.index();await this.state.set({index:e}),this.logger.debug("Index rebuilt successfully.")}},$=class{constructor(e,t){this.stateManager=e,this.logger=t??b.child("aggregator")}modules=[];_registries={};logger;use(e){if(this.modules.push(e),e.registries)for(const[t,r]of Object.entries(e.registries))this._registries[t]&&this.logger.warn(`Registry collision for key: "${t}". Module "${e.name}" is overriding a previous registration.`),this._registries[t]=r}get registries(){return this._registries}schemas(){return this.modules.flatMap((e=>e.schemas??[]))}middleware(){return this.modules.flatMap((e=>e.middleware??[]))}async index(){const e=this.stateManager.get();return(await Promise.all(this.modules.filter((e=>e.index)).map((t=>t.index(e))))).reduce(((e,t)=>t?O(e,t):e),{})}async instantiateStores(e){const t={},r=await Promise.all(this.modules.filter((e=>e.stores)).map((t=>t.stores(e))));for(const e of r)Object.assign(t,e);return t}list(){return[...this.modules]}},j=class{constructor(e,t="id",r=1e3){this.collection=e,this.pkField=t,this.limit=r}async get(e){const t=await this.collection.find({field:this.pkField,operator:"eq",value:e});return t?t.state():null}async add(e){await this.collection.create(e)}async update(e,t){const r=await this.collection.find({field:this.pkField,operator:"eq",value:e});return r?(await r.update(t),r.state()):null}async delete(e){const t=await this.collection.find({field:this.pkField,operator:"eq",value:e});return!!t&&await t.delete()}async list(){const e=await this.collection.list({limit:this.limit,type:"cursor",direction:"forward"});return((await e.next()).value||[]).map((e=>e.state()))}summarize(e){return e}};function B(e){return e&&Array.isArray(e.topics)}function M(e,t,r){const s=e?.index?.topics?.[t];if(!s)return[];for(const[e,t]of Object.entries(s))if(Array.isArray(t)&&t.includes(r))return[...new Set([...q(e,t,r)])];return[]}function q(e,t,r){return t.includes(r)?[e]:[]}var U={name:"workspace",middleware:[({state:e,namespace:t})=>r=>async s=>{const i=await r(s);if(!i.ok)return i;const n=i.value,{payload:o}=s,a=e();if(!B(o))return i;const c=function(e,t){const r=[];if(e.id&&B(e)&&r.push({id:e.id,topics:e.topics}),t?.entities)for(const[e,s]of Object.entries(t.entities))s&&"object"==typeof s&&"topics"in s&&r.push({id:e,topics:s.topics});return r}(o,n);let d={index:{topics:{[t]:{}}}};const l=d.index.topics[t];for(const e of c){if(!e.id)continue;const r=M(a,t,e.id),s=e.topics??[],i=s.filter((e=>!r.includes(e))),n=r.filter((e=>!s.includes(e)));for(const t of i)l[t]||(l[t]=[]),l[t].includes(e.id)||(l[t]=[...l[t],e.id]);for(const t of n)l[t]||(l[t]=[]),l[t]=l[t].filter((t=>t!==e.id))}return y.ok(O(n,d))}],actions:{"workspace:create":(e,t)=>{const{id:r,settings:s,project:i}=t.payload;return{id:r,settings:s,project:i}},"workspace:sync":(e,t)=>{const{settings:r,project:s}=t.payload;return{...r?{settings:r}:{},...s?{project:s}:{}}}},index:async e=>({})},L=class extends j{constructor(e,t){super(e,"id"),this.storage=t}async get(e){const t=await this.collection.find({field:"id",operator:"eq",value:e});if(!t)return null;const r=t.state(),s=await this.storage.loadBytes(r.checksum);return{...r,data:s||new Uint8Array(0)}}async add(e){const{data:t,...r}=e;await this.storage.storeBytes(e.checksum,t),await this.collection.create(r)}async delete(e){const t=await this.get(e);return!!t&&(await this.storage.deleteBytes(t.checksum),await super.delete(e))}async findByChecksum(e){const t=await this.collection.find({field:"checksum",operator:"eq",value:e});if(!t)return null;return{...t.state(),data:await this.storage.loadBytes(e)||new Uint8Array(0)}}async resolve(e,t){const r=await this.get(e);if(!r)return y.ok(null);if(t){const e=r.remotes[t];if(e)return y.ok({kind:"remote",checksum:r.checksum,mime:r.mime,id:e.id,provider:t,timestamp:m.timestamp(e.timestamp)})}return y.ok({kind:"inline",checksum:r.checksum,mime:r.mime,data:r.data})}async resolveMany(e,t){const r=new Map;for(const s of e){const e=await this.resolve(s,t);if(!e.ok)return e;if(null===e.value)return y.fail({code:f.NOT_FOUND,message:`Blob ${s} not found`});r.set(s,e.value)}return y.ok(r)}},P=class{static async computeSHA256(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join("")}static computeCRC32(e){const t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let e=0;e<8;e++)r=1&r?3988292384^r>>>1:r>>>1;t[e]=r}let r=~0;for(let s=0;s<e.length;s++)r=t[r^e[s]]^r>>>8;return(-1^r).toString(16).padStart(2,"0")}static bufferToBase64(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let r=0;r<e.length;r+=32768){const s=e.subarray(r,r+32768);t.push(String.fromCharCode.apply(null,Array.from(s)))}return btoa(t.join(""))}static base64ToBuffer(e){if("undefined"!=typeof Buffer)return new Uint8Array(Buffer.from(e,"base64"));const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}static shortHash(e,t=6){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t);r|=0;return((r>>>0)%36**t).toString(36).padStart(t,"0")}static async blobToUint8Array(e){const t=await e.arrayBuffer();return new Uint8Array(t)}static uint8ArrayToBlob(e,t="application/octet-stream"){return new Blob([e],{type:t})}static textToUint8Array(e){return(new TextEncoder).encode(e)}static uint8ArrayToText(e){return(new TextDecoder).decode(e)}static bufferToUrlSafeBase64(e){return this.bufferToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static urlSafeBase64ToBuffer(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=e.length%4;return r>0&&(t+="=".repeat(4-r)),this.base64ToBuffer(t)}static async*chunkBlob(e,t=1048576){let r=0;for(;r<e.size;){const s=e.slice(r,r+t),i=await this.blobToUint8Array(s);yield i,r+=t}}static wrapBlobMetadata(e,t){const r=JSON.stringify(t),s=this.textToUint8Array(r),i=new Uint8Array(4);new DataView(i.buffer).setUint32(0,s.length);const n=new Uint8Array(s.length+4+e.length);return n.set(s,4),n.set(e,4+s.length),n.set(i,0),n}static unwrapBlobMetadata(e){if(e.length<4)throw new Error("Blob metadata wrapper own a buffer too small to contain length header.");const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0);if(e.length<4+t)throw new Error("Blob metadata wrapper own a buffer too small to contain the metadata string up to the length specified in the length header.");const r=e.subarray(4,4+t),s=this.uint8ArrayToText(r),i=JSON.parse(s);return{data:e.subarray(4+t,e.length),metadata:i}}};var z=class extends I{constructor(e){var t;super(e),(t=this).register("text",{type:"text",mode:"readwrite",description:"A standard block of text.",rules:[],schema:{type:"object",properties:{text:{type:"string"}},required:["text"]},format:e=>`[${e.key}]\n${e.value.text}`}),t.register("preference",{type:"preference",mode:"read",description:"A behavioral instruction or user-specific constraint.",rules:["Always follow these instructions with higher priority than general knowledge."],schema:{type:"object",properties:{instruction:{type:"string"}},required:["instruction"]},format:e=>`[${e.key}]\n${e.value.instruction}`}),t.register("json",{type:"json",mode:"readwrite",description:"A structured data block in JSON format.",rules:[],schema:{type:"object"},format:e=>`[${e.key}]\n\`\`\`json\n${JSON.stringify(e.value,null,2)}\n\`\`\``}),t.register("blob",{type:"blob",mode:"read",description:"A reference to a binary asset (file, image, document).",rules:[],schema:{type:"object",properties:{id:{type:"string"},checksum:{type:"string"},size:{type:"number"},mime:{type:"string"},filename:{type:"string"}},required:["id","checksum","size","mime"]},format:e=>`[${e.key}] Blob: ${e.value.filename??"unnamed"} (${e.value.mime}, ${e.value.size} bytes)`}),t.register("image",{type:"image",mode:"internal",description:"An image block within a conversation.",rules:[],schema:{type:"object",properties:{ref:{type:"object"},altText:{type:"string"}},required:["ref"]},format:()=>null}),t.register("document",{type:"document",mode:"internal",description:"A document block (PDF, docx, etc.) within a conversation.",rules:[],schema:{type:"object",properties:{ref:{type:"object"},title:{type:"string"}},required:["ref"]},format:()=>null}),t.register("thinking",{type:"thinking",mode:"internal",description:"Internal chain‑of‑thought reasoning produced by the model before the final answer.",rules:["Do not emit this block unless explicitly requested by the system.","The content is for internal reasoning only — not shown to the end user."],schema:{type:"object",properties:{thinking:{type:"string"}},required:["thinking"]},format:()=>null}),t.register("unknown",{type:"unknown",mode:"internal",description:"Fallback container for unrecognised or malformed content blocks.",rules:["Never emit this block. It is used only for parsing failures."],schema:{type:"object",properties:{raw:{},originalType:{type:"string"}}},format:()=>null})}description(e){return["# BLOCK TYPES & USAGE RULES","Your response MUST be a JSON object with a `blocks` array.","Each element of `blocks` must be one of the following types:","",this.applyFilter(this.list(),e).map((e=>{const t=[e.description];return e.rules.length>0&&(t.push("**Rules:**"),t.push(...e.rules.map((e=>`- ${e}`)))),t.join("\n")})).join("\n\n"),"","## GLOBAL CONSTRAINTS","- Output must be **valid JSON only** — no prose before or after the JSON object.","- Responses may contain multiple blocks. Blocks are rendered in order.","- **Do NOT generate IDs.** The workspace is solely responsible for block ID assignment.","- Do not infer or invent fields not defined in the block schemas above."].join("\n")}schema(e){return{type:"object",description:"The model's structured response, containing an ordered sequence of content blocks.",properties:{blocks:{type:"array",description:"An ordered array of content blocks comprising the model's response.",items:{anyOf:this.applyFilter(this.list(),e).map((e=>e.schema))}}},required:["blocks"]}}mode(e){return this.get(e)?.mode}parse(e,t){const r=this.get(e.type);if(r&&t&&r.mappings?.[t]){const s=r.mappings[t].from(e);if(s)return s}return this.createContent("unknown",{raw:e,originalType:e.type})}createContent(t,r,s){const i=e.v7(),n=(new Date).toISOString(),o=this.mode(t)??"internal";return{id:m.uuid(i),key:s?.key??P.shortHash(`${t}:${i}`),type:t,mode:o,version:s?.version??0,created:m.timestamp(n),updated:m.timestamp(n),label:s?.label,description:s?.description,topics:s?.topics??[],value:r}}filterContentInstances(e,t){const r=this.getFlags;let s=e;if(t)if(void 0!==t.consumable&&(s=s.filter((e=>r(e.mode).consumable===t.consumable))),void 0!==t.emittable&&(s=s.filter((e=>r(e.mode).emittable===t.emittable))),t.only&&t.only.length>0){const e=new Set(t.only);s=s.filter((t=>e.has(t.type)))}else if(t.exclude&&t.exclude.length>0){const e=new Set(t.exclude);s=s.filter((t=>!e.has(t.type)))}return s}applyFilter(e,t){const r=this.getFlags;let s=e.filter((e=>!0===r(e.mode).emittable));if(!t)return s;if(void 0!==t.consumable&&(s=s.filter((e=>r(e.mode).consumable===t.consumable))),void 0!==t.emittable&&(s=s.filter((e=>r(e.mode).emittable===t.emittable))),t.only&&t.only.length>0){const e=new Set(t.only);s=s.filter((t=>e.has(t.type)))}else if(t.exclude&&t.exclude.length>0){const e=new Set(t.exclude);s=s.filter((t=>!e.has(t.type)))}return s}getFlags(e){switch(e){case"read":return{consumable:!0,emittable:!1};case"write":return{consumable:!1,emittable:!0};case"readwrite":return{consumable:!0,emittable:!0};case"internal":return{consumable:!1,emittable:!1}}}},F={name:"content",version:"1.0.0",description:"Unified content entity (Read, Write, ReadWrite).",fields:{id:{name:"id",type:"string",required:!0},version:{name:"version",type:"number",required:!0},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0},type:{name:"type",type:"string",required:!0},key:{name:"key",type:"string",required:!0},mode:{name:"mode",type:"string",required:!0},topics:{name:"topics",type:"array",required:!0,itemsType:"string"},value:{name:"value",type:"record",required:!0},label:{name:"label",type:"string",required:!1},description:{name:"description",type:"string",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_key",fields:["key"],type:"unique"},{name:"by_mode",fields:["mode"],type:"normal"},{name:"by_type",fields:["type"],type:"normal"},{name:"by_topics",fields:["topics"],type:"normal"}],constraints:[],migrations:[]},G={name:"blob",version:"1.0.0",description:"Binary data metadata record.",fields:{id:{name:"id",type:"string",required:!0},version:{name:"version",type:"number",required:!0},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0},checksum:{name:"checksum",type:"string",required:!0},size:{name:"size",type:"number",required:!0},mime:{name:"mime",type:"string",required:!0},remotes:{name:"remotes",type:"record",required:!1},metadata:{name:"metadata",type:"record",required:!0}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_checksum",fields:["checksum"],type:"unique"}],constraints:[],migrations:[]},V=class extends j{constructor(e){super(e,"id")}summarize(e){return{id:e.id,key:e.key,mode:e.mode,type:e.type,topics:e.topics,label:e.label,timestamp:e.updated}}},K=class{name="content";schemas=[F,G];registries={};_contentStore;_blobStore;_blobStorage;constructor({blobStorage:e,logger:t}){const r=new z({logger:t});this.registries={content:r},this._blobStorage=e}stores=async e=>(this._contentStore=new V(await e.collection("content")),this._blobStore=new L(await e.collection("blob"),this._blobStorage),{content:this._contentStore,blobs:this._blobStore});actions={"content:add":async(e,t)=>{const r=t.payload,s={...r,created:r.created??t.timestamp,updated:r.updated??t.timestamp};await(this._contentStore?.add(s));const i={id:s.id,key:s.key,mode:s.mode,type:s.type,topics:s.topics,label:s.label,timestamp:s.updated};return{index:{content:{items:{[s.id]:i},keys:{[s.key]:s.id}}}}},"content:update":async(e,t)=>{const{id:r,updates:s}=t.payload,i=e.index?.content?.items[r];if(!i)return{};await(this._contentStore?.update(r,s));const n=t.timestamp,o={...i,...s.key?{key:s.key}:{},...s.mode?{mode:s.mode}:{},...s.type?{type:s.type}:{},...s.topics?{topics:s.topics}:{},...s.label?{label:s.label}:{},timestamp:n},a={[r]:o};let c={};return s.key&&s.key!==i.key&&(c={[i.key]:_(),[s.key]:r}),{index:{content:{items:a,keys:c}}}},"content:delete":async(e,t)=>{const{id:r}=t.payload,s=e.index.content.items[r];return s?(await(this._contentStore?.delete(r)),{index:{content:{items:{[r]:_()},keys:{[s.key]:_()}}}}):{}},"blob:register":async(e,t)=>{const{id:r,checksum:s,size:i,mime:n,data:o,metadata:a}=t.payload;await(this._blobStore?.add({id:r,checksum:s,size:i,mime:n,data:o,remotes:{},metadata:{refCount:a?.refCount??0},created:t.timestamp,updated:t.timestamp,version:1}));return{index:{content:{blobs:{...e.index.content?.blobs,[s]:r}}}}},"blob:retain":async(e,t)=>{const{id:r}=t.payload,s=await(this._blobStore?.get(r));return s&&await(this._blobStore?.update(r,{metadata:{...s.metadata,refCount:(s.metadata?.refCount??0)+1}})),{}},"blob:release":async(e,t)=>{const{id:r}=t.payload,s=await(this._blobStore?.get(r));return s&&await(this._blobStore?.update(r,{metadata:{...s.metadata,refCount:Math.max(0,(s.metadata?.refCount??0)-1)}})),{}},"blob:purge":async(e,t)=>{const{id:r}=t.payload,s=Object.entries(e.index.content.blobs).find((([e,t])=>t===r))?.[0];if(!s)return{};await(this._blobStore?.delete(r));const{[s]:i,...n}=e.index.content.blobs;return{index:{content:{blobs:n}}}},"blob:record_remote_id":async(e,t)=>{const{id:r,providerId:s,fileId:i}=t.payload,n=await(this._blobStore?.get(r));return n&&await(this._blobStore?.update(r,{remotes:{...n.remotes,[s]:{id:i,timestamp:t.timestamp}}})),{}}};async index(e){if(!this._contentStore||!this._blobStore)return{content:{items:{},keys:{},blobs:{}}};const[t,r]=await Promise.all([this._contentStore.list(),this._blobStore.list()]),s={},i={},n={},o={};for(const e of t){const t=this._contentStore.summarize(e);s[e.id]=t,i[e.key]=e.id;for(const t of e.topics)n[t]||(n[t]=[]),n[t].push(e.id)}for(const e of r)o[e.checksum]=e.id;return{content:{items:s,keys:i,blobs:o}}}},Y={name:"sessions",version:"1.0.0",description:"Conversation session metadata.",fields:{id:{name:"id",type:"string",required:!0},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0},label:{name:"label",type:"string",required:!0},role:{name:"role",type:"string",required:!0},topics:{name:"topics",type:"array",required:!0,itemsType:"string"},preferences:{name:"preferences",type:"array",required:!0,itemsType:"string"},content:{name:"content",type:"array",required:!0,itemsType:"string"},head:{name:"head",type:"record",required:!1},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_id",fields:["id"],type:"unique"},{name:"by_role",fields:["role"],type:"normal"},{name:"by_topics",fields:["topics"],type:"normal"}],constraints:[],migrations:[]},J={name:"turns",version:"1.0.0",description:"Individual conversation turn (message).",fields:{id:{name:"id",type:"string",required:!0},version:{name:"version",type:"number",required:!0},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0},session:{name:"session",type:"string",required:!0},actor:{name:"actor",type:"string",required:!0},blocks:{name:"blocks",type:"array",required:!0,itemsType:"record"},role:{name:"role",type:"string",required:!1},model:{name:"model",type:"string",required:!1},parent:{name:"parent",type:"record",required:!1},metadata:{name:"metadata",type:"record",required:!1}},indexes:[{name:"by_id_version",fields:["id","version"],type:"unique"},{name:"by_session",fields:["session"],type:"normal"}],constraints:[],migrations:[]},H=class extends j{constructor(e){super(e,"id")}summarize(e){return{id:e.id,label:e.label,role:e.role,topics:e.topics,content:e.content,preferences:e.preferences,updated:e.updated,head:e.head,metadata:e.metadata}}},W=class extends j{constructor(e){super(e,"id")}async find(e){const t=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e.id},{field:"session",operator:"eq",value:e.session},{field:"version",operator:"eq",value:e.version}]});return t?t.state():null}async updateTurn(e,t){const r=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e.id},{field:"session",operator:"eq",value:e.session},{field:"version",operator:"eq",value:e.version}]});return r?(await r.update(t),r.state()):null}async deleteTurn(e){const t=await this.collection.find({operator:"and",conditions:[{field:"id",operator:"eq",value:e.id},{field:"session",operator:"eq",value:e.session},{field:"version",operator:"eq",value:e.version}]});return!!t&&await t.delete()}async listBySession(e){return(await this.list()).filter((t=>t.session===e))}},Q=class{name="sessions";schemas=[Y,J];_sessionStore;_turnStore;stores=async e=>(this._sessionStore=new H(await e.collection("sessions")),this._turnStore=new W(await e.collection("turns")),{sessions:this._sessionStore,turns:this._turnStore});actions={"session:create":async(e,t)=>{const r=t.payload,s={...r,created:t.timestamp,updated:t.timestamp,preferences:r.preferences??[],topics:r.topics??[],content:r.content??[]};await(this._sessionStore?.add(s));const i={id:s.id,label:s.label,role:s.role,topics:s.topics,preferences:s.preferences,content:s.content,updated:s.updated,head:s.head,metadata:s.metadata};return{index:{sessions:{[s.id]:i}}}},"session:update":async(e,t)=>{const{id:r,updates:s}=t.payload,i=e.index.sessions[r];if(!i)return{};await(this._sessionStore?.update(r,s));const n={...i,...s,updated:t.timestamp};return{index:{sessions:{[r]:n}}}},"session:fork":async(e,t)=>{const{id:r,newId:s,label:i,role:n,topics:o}=t.payload,a=e.index.sessions[r];if(!a)return{};const c=await(this._sessionStore?.get(r));if(!c)return{};const d={...c,id:s,label:i,role:n??a.role,topics:o??a.topics,updated:t.timestamp,created:t.timestamp};await(this._sessionStore?.add(d));const l={id:s,label:i,role:d.role,topics:d.topics,preferences:d.preferences,content:d.content,updated:d.updated,head:d.head};return{index:{sessions:{[s]:l}}}},"session:delete":async(e,t)=>{const r=t.payload.id;return e.index.sessions[r]?(await(this._sessionStore?.delete(r)),{index:{sessions:{[r]:_()}}}):{}},"turn:add":async(e,t)=>{const r=t.payload,s=r.session,i=e.index.sessions[s];if(!i)return{};const n={...r,created:t.timestamp,updated:t.timestamp};await(this._turnStore?.add(n));const o={id:n.id,version:n.version};await(this._sessionStore?.update(s,{head:o,updated:n.updated}));const a={...i,updated:n.updated,head:o};return{index:{sessions:{[s]:a}}}},"turn:update":async(e,t)=>{const r=t.payload,{id:s,session:i,version:n,...o}=r,a=e.index.sessions[i];if(!a)return{};const c=await(this._turnStore?.updateTurn({id:s,session:i,version:n},{...o,updated:t.timestamp})),d=a.head?.id===s,l=c?.updated??t.timestamp;d&&await(this._sessionStore?.update(i,{updated:l}));const u={...a,updated:l,...d?{head:{id:s,version:n}}:{}};return{index:{sessions:{[i]:u}}}},"turn:edit":async(e,t)=>{const{session:r,id:s,content:i,version:n,role:o,model:a}=t.payload,c=e.index.sessions[r];if(!c)return{};const d=await(this._turnStore?.find({id:s,session:r,version:n-1})),l={...d??{},id:s,session:r,version:n,blocks:i,role:o??d?.role,model:a??d?.model,updated:t.timestamp,created:d?.created??t.timestamp,actor:d?.actor??"user"};if(await(this._turnStore?.add(l)),c.head?.id===s){const e={id:s,version:n};await(this._sessionStore?.update(r,{head:e,updated:t.timestamp}));const i={...c,updated:t.timestamp,head:e};return{index:{sessions:{[r]:i}}}}return await(this._sessionStore?.update(r,{updated:t.timestamp})),{index:{sessions:{[r]:{...c,updated:t.timestamp}}}}},"turn:branch":async(e,t)=>{const r=t.payload,s=e.index.sessions[r.session];if(!s)return{};const i={...r,created:r.created,updated:r.updated};await(this._turnStore?.add(i));const n={id:i.id,version:i.version};await(this._sessionStore?.update(r.session,{head:n,updated:i.updated}));const o={...s,updated:i.updated,head:n};return{index:{sessions:{[r.session]:o}}}},"turn:delete":async(e,t)=>{const{session:r,id:s,version:i,newHead:n}=t.payload,o=e.index.sessions[r];if(!o)return{};await(this._turnStore?.deleteTurn({id:s,session:r,version:i})),n?await(this._sessionStore?.update(r,{head:n,updated:t.timestamp})):await(this._sessionStore?.update(r,{updated:t.timestamp}));const a={...o,updated:t.timestamp,...n?{head:n}:{}};return{index:{sessions:{[r]:a}}}}};async index(e){if(!this._sessionStore)return{sessions:{}};const t=await this._sessionStore.list(),r={};for(const e of t){const t=this._sessionStore.summarize(e);r[e.id]=t}return{sessions:r}}};var X=class{constructor(e,t){this.turnStore=e,this.sessionStore=t}async loadAllTurns(e){return this.turnStore.listBySession(e)}async loadHead(e){const t=await this.sessionStore.get(e);return t?.head??null}},Z=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,r,s){const[i,n]=await Promise.all([r.loadAllTurns(t),void 0!==s?Promise.resolve(s):r.loadHead(t)]),o=function(e,t){const r=function(e,t){if(!t)return new Set;const r=new Map;for(const t of e)r.set(`${t.id}:${t.version}`,t);const s=new Set;let i=t;for(;i;){const e=`${i.id}:${i.version}`;if(s.has(e))break;s.add(e);const t=r.get(e);if(!t)break;i=t.parent}return s}(e,t),s={},i={};for(const t of e){s[t.id]||(s[t.id]={...t,versions:{},children:{}},i[t.id]=new Set);const e=s[t.id];e.versions[t.version]=t;const n=r.has(`${t.id}:${t.version}`),o=r.has(`${t.id}:${e.version}`);if(n&&(!o||t.version>=e.version)&&(e.version=t.version,e.blocks=t.blocks,e.created=t.created,e.updated=t.updated,e.role=t.role,e.model=t.model,e.parent=t.parent),t.parent){const e=`${t.parent.id}:${t.parent.version}`;if(i[t.parent.id]||(i[t.parent.id]=new Set),!i[t.parent.id].has(e+":"+t.id)){i[t.parent.id].add(e+":"+t.id),s[t.parent.id]||(s[t.parent.id]={id:t.parent.id,versions:{},version:t.parent.version,actor:"user",blocks:[],created:"",updated:"",role:void 0,model:void 0,children:{}});const r=s[t.parent.id];r.children[t.parent.version]||(r.children[t.parent.version]=[]),r.children[t.parent.version].push(t.id)}}}return s}(i,n);return new e(o,n)}head(){return this._head}chain(){return this._head?this.chainFrom(this._head.id):[]}chainFrom(e){const t=[];let r=m.uuid(e);for(;r;){const e=this.nodes[r];if(!e)break;t.push(e),r=e.parent?.id??null}return t.reverse()}getTurnSiblings(e){const t=this.nodes[m.uuid(e)];if(!t)return[];if(!t.parent)return Object.values(this.nodes).filter((e=>!e.parent));const r=this.nodes[t.parent.id];if(!r)return[t];const s=r.children[t.parent.version];return s?s.map((e=>this.nodes[e])).filter((e=>!!e)):[t]}branchInfo(e){const t=this.nodes[e];if(!t)return{versions:[],currentIndex:-1,total:0,hasPrev:!1,hasNext:!1};const r=Object.keys(t.versions).map(Number).sort(((e,t)=>e-t)),s=r.indexOf(t.version);return{versions:r,currentIndex:s,total:r.length,hasPrev:s>0,hasNext:s<r.length-1}}graph(){return{...this.nodes}}};var ee=class e{constructor(e,t,r,s){this.id=t,this.kernel=r,this.stores=s,this.context=new E("user",e).withMeta({session:t}).build(),this.turnRepository=new X(s.turns,s.sessions)}tree;turnRepository;context;static async create(t,r,s,i){const n=new e(t,r,s,i);return await n.sync(),n}async sync(){await this.refreshTurnTree()}close(){}sessionId(){return this.id}meta(){return this.kernel.state.get().index.sessions?.[this.id]}label(){return this.meta()?.label}async role(){const e=this.meta();if(!e)return;const t=this.kernel.state.get().index;return t.roles?.[e.role]}topics(){return this.meta()?.topics??[]}async preferences(){const e=this.meta();if(!e?.preferences)return[];const t=this.kernel.state.get().index;return e.preferences.map((e=>t.content?.items?.[e])).filter((e=>"preference"===e?.type))}head(){return this.meta()?.head??null}turns(){return this.tree.chain()}siblings(e){return this.tree.getTurnSiblings(e)}branchInfo(e){return this.tree.branchInfo(e)}turn(e){return this.tree.graph()[e]}async transcript(){return this.stores.turns.listBySession(this.id)}async data(){return this.stores.sessions.get(this.id)}async rename(e){return this.kernel.coordinator.dispatch(this.context,{type:"session:update",payload:{id:this.id,updates:{label:e}},timestamp:m.timestamp((new Date).toISOString())})}async setTopics(e){return this.kernel.coordinator.dispatch(this.context,{type:"session:update",payload:{id:this.id,updates:{topics:e}},timestamp:m.timestamp((new Date).toISOString())})}async addTopics(e){const t=this.topics(),r=Array.from(new Set([...t,...e]));return this.setTopics(r)}async switchRole(e){return await this.kernel.coordinator.dispatch(this.context,{type:"session:role:switch",payload:{sessionId:this.id,roleName:e},timestamp:m.timestamp((new Date).toISOString())})}async setModel(e){return this.updateMetadata({model:e})}async updateMetadata(e){const t=this.meta(),r={...t?.metadata||{},...e};return this.kernel.coordinator.dispatch(this.context,{type:"session:update",payload:{id:this.id,updates:{metadata:r}},timestamp:m.timestamp((new Date).toISOString())})}async setPreferences(e){return this.kernel.coordinator.dispatch(this.context,{type:"session:preferences:override",payload:{sessionId:this.id,preferences:e},timestamp:m.timestamp((new Date).toISOString())})}async setContents(e){return this.kernel.coordinator.dispatch(this.context,{type:"session:update",payload:{id:this.id,updates:{content:e}},timestamp:m.timestamp((new Date).toISOString())})}async linkContent(e){const t=this.meta(),r=Array.isArray(e)?e:[e],s=Array.from(new Set([...t?.content||[],...r]));return this.setContents(s)}async unlinkContent(e){const t=this.meta(),r=Array.isArray(e)?e:[e],s=(t?.content||[]).filter((e=>!r.includes(e)));return this.setContents(s)}async addTurn(e,t){const r=this.meta();if(!r)return{ok:!1,error:new Error("Session not found")};const s={...t,session:this.id,version:t.version??0,parent:t.parent??this.head()??void 0,role:t.role??r.role,model:t.model??r.metadata?.model},i=await this.kernel.coordinator.dispatch(e,{type:"turn:add",payload:s,timestamp:m.timestamp((new Date).toISOString())});return i.ok&&await this.refreshTurnTree({id:s.id,version:s.version}),i}async recordUserTurn(e){return this.addTurn(this.context,e)}async recordAssistantTurn(e,t){return this.addTurn(e,t)}async editTurn(e,t,r,s){const i=this.tree.graph()[e];if(!i)return{ok:!1,error:new Error(`Turn ${e} not found`)};const n=i.versions[i.version],o=Object.keys(i.versions).length,a=await this.kernel.coordinator.dispatch(this.context,{type:"turn:edit",payload:{session:this.id,version:o,id:e,content:t,role:r??n.role,model:s??n.model},timestamp:m.timestamp((new Date).toISOString())});if(a.ok){const t={id:e,version:o};await this.refreshTurnTree(t)}return a}async branch(e){if(!e.parent)return{ok:!1,error:new Error("Branch requires turn.parent to be set")};const t=await this.kernel.coordinator.dispatch(this.context,{type:"turn:branch",payload:{...e,session:this.id},timestamp:m.timestamp((new Date).toISOString())});return t.ok&&await this.refreshTurnTree({id:e.id,version:e.version}),t}async deleteTurn(e,t,r){const s=this.tree.graph();if(!s[e]?.versions[t])return{ok:!1,error:new Error(`Turn version ${e}:${t} not found`)};const i=await this.kernel.coordinator.dispatch(this.context,{type:"turn:delete",payload:{session:this.id,id:e,version:t,newHead:r??void 0},timestamp:m.timestamp((new Date).toISOString())});return i.ok&&await this.refreshTurnTree(r),i}async updateTurnStatus(e,t,r){const s=this.turn(e);if(!s)return{ok:!1,error:new Error(`Turn ${e} not found`)};const i=s.versions[t];if(!i)return{ok:!1,error:new Error(`Turn version ${e}:${t} not found`)};const n={...i,metadata:{...i.metadata||{},status:r.ok?"success":"unsuccessful",error:r.ok?void 0:r.error}},o=await this.kernel.coordinator.dispatch(this.context,{type:"turn:update",payload:n,timestamp:m.timestamp((new Date).toISOString())});return o.ok&&await this.refreshTurnTree(),o}async fork(e,t,r,s){return this.kernel.coordinator.dispatch(this.context,{type:"session:fork",payload:{id:this.id,newId:e,label:t,role:r,topics:s},timestamp:m.timestamp((new Date).toISOString())})}async switchVersionLeft(e){return this.switchVersion(e,-1)}async switchVersionRight(e){return this.switchVersion(e,1)}async snapshot(e){const t=this.meta();if(!t)return;const r=await this.role();if(!r)return;const s=await this.loadContent(t),i=await this.preferences();let n;if(e&&"string"!=typeof e){const t=e.parent?.id??this.head()?.id;n=(t?this.tree.chainFrom(t):[]).map((e=>e.versions[e.version])).filter((e=>!!e)),n.push(e)}else{n=(e?this.tree.chainFrom(e):this.tree.chain()).map((e=>e.versions[e.version])).filter((e=>!!e))}const o=[...n].reverse().find((e=>"user"===e.actor));return{id:this.id,meta:t,role:r,preferences:i,content:s,model:t.metadata?.model,transcript:n,topics:t.topics,instructions:this.kernel.state.get().settings?.prompt,constraints:{role:r.constraints,session:t.constraints,turn:o?.metadata?.constraints}}}async refreshTurnTree(e){this.tree=await Z.build(this.id,this.turnRepository,e)}async loadContent(e){const t=this.kernel.state.get().index,r=t.content?.items||{};return(e.content||[]).map((e=>r[e])).filter((e=>!!e))}async switchVersion(e,t){const r=this.tree.graph(),s=r[e];if(!s)return{ok:!1,error:new Error(`Turn ${e} not found`)};const i=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),n=i.indexOf(s.version);if(-1===n)return{ok:!1,error:new Error("Active version not found")};const o=n+t;if(o<0||o>=i.length)return{ok:!1,error:new Error(`No ${t<0?"previous":"next"} version available`)};const a=i[o],c=this.findSubtreeTip(r,e,a);return await this.refreshTurnTree(c),{ok:!0,value:void 0}}findSubtreeTip(e,t,r){let s=t,i=r;for(;;){const t=e[s];if(!t)break;const r=t.children[i];if(!r||0===r.length)break;const n=r[0],o=e[n];if(!o)break;s=n,i=o.version}return{id:s,version:i}}},te=class{_turn;constructor(e,t,r){if(r)this._turn=JSON.parse(JSON.stringify(r));else{const r=m.timestamp((new Date).toISOString());this._turn={id:m.uuid(crypto.randomUUID()),session:t,version:1,actor:e,blocks:[],created:r,updated:r,role:void 0,model:void 0}}}createBlock(e,t,r={}){const s=m.timestamp((new Date).toISOString());return{id:m.uuid(crypto.randomUUID()),version:1,created:s,updated:s,type:e,key:r.key??`block-${crypto.randomUUID().slice(0,8)}`,mode:r.mode??"read",label:r.label,topics:r.topics??[],value:t}}addText(e,t){const r=this.createBlock("text",{text:e},{...t,mode:"read"});return this._turn.blocks.push(r),this}addToolUse(e,t,r){const s=this.createBlock("tool:use",{name:e,input:t},{...r,mode:"write"});return this._turn.blocks.push(s),this}addToolResult(e,t,r,s){const i=this.createBlock("tool:result",{useId:e,content:t,isError:r},{...s,mode:"read"});return this._turn.blocks.push(i),this}addThinking(e,t){const r=this.createBlock("thinking",{thinking:e},{...t,mode:"write"});return this._turn.blocks.push(r),this}addBlock(e){return this._turn.blocks.push(e),this}deleteBlock(e){return this._turn.blocks=this._turn.blocks.filter((t=>t.id!==e)),this}withId(e){return this._turn={...this._turn,id:e},this}withVersion(e){return this._turn={...this._turn,version:e},this}withTimestamp(e){return this._turn={...this._turn,updated:e},this}withParent(e){return this._turn={...this._turn,parent:e},this}withRole(e){return this._turn={...this._turn,role:e},this}withModel(e){return this._turn={...this._turn,model:e},this}withMetadata(e){return this._turn={...this._turn,metadata:{...this._turn.metadata||{},...e}},this}build(){return JSON.parse(JSON.stringify(this._turn))}node(){const e=this.build();return{...e,versions:{[e.version]:e},children:{}}}},re="\n# WORKSPACE OPERATING SYSTEM\nYou are operating within a structured workspace. Your output MUST be a JSON object matching the provided schema.\nYour entire response MUST be valid JSON. Nothing else.\n".trim();function se(e){if(!e||"append"===e)return{placement:"append",label:null};if("prepend"===e)return{placement:"prepend",label:null};const[t,...r]=e.split(":");return("before"===t||"after"===t)&&r.length>0?{placement:t,label:r.join(":")}:{placement:"append",label:null}}var ie={name:"role",version:"1.0.0",description:"System persona containing instructions and preferences.",fields:{name:{name:"name",type:"string",required:!0},version:{name:"version",type:"number",required:!0},created:{name:"created",type:"string",required:!0},updated:{name:"updated",type:"string",required:!0},label:{name:"label",type:"string",required:!0},description:{name:"description",type:"string",required:!1},persona:{name:"persona",type:"string",required:!0},preferences:{name:"preferences",type:"array",required:!0,itemsType:"string"},topics:{name:"topics",type:"array",required:!0,itemsType:"string"},constraints:{name:"constraints",type:"record",required:!1}},indexes:[{name:"by_name",fields:["name"],type:"unique"},{name:"by_topics",fields:["topics"],type:"normal"}],constraints:[],migrations:[]},ne=class extends j{constructor(e){super(e,"name")}summarize(e){return{name:e.name,label:e.label,description:e.description,preferences:e.preferences.length,topics:e.topics,constraints:e.constraints}}},oe={};i(oe,{GOOGLE_MODELS:()=>ae,GOOGLE_MODELS_COMMON:()=>de,GOOGLE_MODELS_EMBEDDING:()=>ue,GOOGLE_MODELS_PRO:()=>le,GoogleGenAIAdapter:()=>ge});var ae=[{provider:"google",name:"gemini-3.1-pro",label:"Gemini 3.1 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3-flash-preview",label:"Gemini 3 Flash Preview",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3,cache:{read:.05,write:1}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-3.1-flash-lite",label:"Gemini 3.1 Flash Lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-pro",label:"Gemini 2.5 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10,cache:{read:.125,write:4.5}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash",label:"Gemini 2.5 Flash",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.3,output:2.5,cache:{read:.03,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-lite",label:"Gemini 2.5 Flash Lite",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.1,output:.4,cache:{read:.01,write:1}}}],capacity:[{unit:"call",max:4e3,period:60},{unit:"token",max:4e6,period:60}]},{provider:"google",name:"gemini-3-pro",label:"Gemini 3 Pro",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!0,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-2.5-flash-image",label:"Gemini 2.5 Flash Image",window:{size:4096,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"image",scale:0,cost:{input:.02,output:0}}],capacity:[{unit:"call",max:100,period:60}]},{provider:"google",name:"gemini-2.5-flash-live",label:"Gemini 2.5 Flash Live",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-3.1-flash-live",label:"Gemini 3.1 Flash Live",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:.5,output:3}}],capacity:[{unit:"concurrent",max:10,period:0}]},{provider:"google",name:"gemini-2.5-computer-use",label:"Gemini 2.5 Computer Use",window:{size:1048576,out:65536},feature:{vision:!0,tools:!0,json:!0,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:1.25,output:10}}],capacity:[{unit:"call",max:200,period:60},{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-001",label:"Gemini Embedding 001",window:{size:2048,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.5,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemini-embedding-2",label:"Gemini Embedding 2",window:{size:8192,out:0},feature:{vision:!1,tools:!1,json:!1,cache:!1,streaming:!1,thinking:!1},pricing:[{unit:"token",scale:6,cost:{input:.3,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-e2b-it",label:"Gemma 4 E2B",window:{size:131072,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-e4b-it",label:"Gemma 4 E4B",window:{size:131072,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-26b-a4b-it",label:"Gemma 4 26B A4B",window:{size:262144,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"gemma-4-31b-it",label:"Gemma 4 31B",window:{size:262144,out:8192},feature:{vision:!0,tools:!0,json:!1,cache:!1,streaming:!0,thinking:!0},pricing:[{unit:"token",scale:6,cost:{input:0,output:0}}],capacity:[{unit:"token",max:1e6,period:60}]}],ce=new Set(["gemini-2.5-flash","gemini-2.5-flash-lite","gemini-3-flash-preview","gemini-3.1-flash-lite","gemma-4-26b-a4b-it","gemma-4-31b-it"]),de=ae.filter((e=>ce.has(e.name))),le=ae.filter((e=>e.name.includes("pro"))),ue=ae.filter((e=>e.name.includes("embedding")));function pe(e){const t=e.candidates?.[0],r=[];if(!t?.content?.parts)return{ok:!1,thinking:r,error:new g({code:"BACKEND_ERROR",message:"No valid content parts in response"})};const s=[];for(const e of t.content.parts)e.thought?r.push(he(e.text??"")):e.text&&s.push(e.text);const i=s.join("").trim();if(!i)return r.length>0?{ok:!0,thinking:r,rawBlocks:[]}:{ok:!1,thinking:r,error:new g({code:"BACKEND_ERROR",message:"Response missing json part"})};const n=function(e){try{const t=JSON.parse(e);return t.blocks&&Array.isArray(t.blocks)?y.ok(t.blocks):y.fail(new g({code:"BACKEND_ERROR",message:'Invalid response: missing or malformed "blocks" array'}))}catch(e){const t=e instanceof Error?e.message:String(e);return y.fail(new g({code:"BACKEND_ERROR",message:`Failed to parse response JSON: ${t}`}))}}(i);return n.ok?{ok:!0,thinking:r,rawBlocks:n.value}:{ok:!0,thinking:r,fallback:i}}function he(e){const t=m.timestamp((new Date).toISOString());return{id:m.uuid(crypto.randomUUID()),type:"thinking",version:1,created:t,updated:t,key:`thinking-${crypto.randomUUID().slice(0,8)}`,mode:"write",topics:[],value:{thinking:e}}}var me=class{constructor(e,t,r,s,i,n,o){this.client=e,this.assembler=t,this.registry=r,this.provider=s,this.model=i,this.prompt=n,this.request=o}async execute(e){let t;try{e?.abort&&(this.request.config.abortSignal=e.abort),t=await this.client.models.generateContent(this.request)}catch(e){return y.fail(new g({code:"BACKEND_ERROR",message:e instanceof Error?e.message:String(e),cause:e}))}const r=pe(t);if(!r.ok)return y.fail(new g({code:"BACKEND_ERROR",message:r.error instanceof Error?r.error.message:String(r.error),cause:r.error}));let s;s="fallback"in r?[...r.thinking,this.registry.createContent("unknown",{raw:r.fallback})]:[...r.thinking,...this.assembler.parse(this.provider,r.rawBlocks)];const i=new te("assistant",this.prompt.session);i.withModel(this.model.name),i.withRole(this.prompt.role.name);for(const e of s)i.addBlock(e);return y.ok({turn:i.build(),effects:[]})}},ge=class e{constructor(e,t,r,s={model:"gemini-2.5-flash",models:ae}){this.client=e,this.assembler=t,this.registry=r;const i=s.models.find((e=>e.name===s.model));if(!i)throw new Error(`Could not find model: ${s.model}`);this.model=i,this._models=s.models,this.registerMappings(r)}model;_models;registerMappings(t){const r=(e=>{const t=e.createContent.bind(e);return{text:{to:({block:e})=>({text:e.value.text}),from:e=>t("text",{text:e.text},{mode:"readwrite"})},preference:{to:({block:e})=>({text:`[Preference]: ${e.value.instruction}`}),from:e=>t("preference",{instruction:e.instruction},{mode:"read"})},json:{to:({block:e})=>({text:JSON.stringify(e.value,null,2)}),from:e=>t("json",e,{mode:"readwrite"})},blob:{to:()=>null,from:e=>t("blob",{id:e.id,checksum:e.checksum,size:e.size,mime:e.mime,filename:e.filename},{mode:"read"})},image:{to:async({block:e,resolve:t})=>{const r=e.value.ref;if(!r)return null;const s=await t(r);if(!s.ok||!s.value)return null;const i=s.value;return"remote"===i.kind?{fileData:{fileUri:i.id,mimeType:i.mime}}:{inlineData:{data:Buffer.from(i.data).toString("base64"),mimeType:i.mime}}},from:e=>t("image",{ref:e.ref,altText:e.altText},{mode:"readwrite"})},document:{to:async({block:e,resolve:t})=>{const r=e.value.ref;if(!r)return null;const s=await t(r);if(!s.ok||!s.value)return null;const i=s.value;return"remote"===i.kind?{fileData:{fileUri:i.id,mimeType:i.mime}}:{inlineData:{data:Buffer.from(i.data).toString("base64"),mimeType:i.mime}}},from:e=>t("document",{ref:e.ref,title:e.title},{mode:"readwrite"})},thinking:{to:({block:e})=>"internal"===e.mode?null:{text:e.value.thinking},from:e=>t("thinking",{thinking:e.thinking},{mode:"internal"})}}})(t);for(const[s,i]of Object.entries(r))t.update(s,{mappings:{[e.provider()]:i}})}async status(){return{provider:e.provider(),model:this.model.name,ready:!0,window:this.model.window,feature:this.model.feature,pricing:this.model.pricing,rate:{load:0,capacity:this.model.capacity}}}async resolve(t){const{prompt:r}=t,s=this.model,{system:i,sections:n,transcript:o}=await this.assembler.build(e.provider(),r,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t}))),a={role:"system",parts:[{text:i}]},c=r.constraints[s.name]??{tokens:{}},d=this.assembler.registry.schema(),l={model:s.name,contents:o,config:{systemInstruction:a,thinkingConfig:{includeThoughts:!0},responseMimeType:"application/json",responseSchema:d,...void 0!==c.temperature&&{temperature:c.temperature},...void 0!==c.tokens.max&&{maxOutputTokens:c.tokens.max},...c.tokens.stops?.length&&{stopSequences:c.tokens.stops},...void 0!==c.tokens.thought&&{thinkingConfig:{includeThoughts:!0,thinkingBudget:c.tokens.thought}}}},u=new me(this.client,this.assembler,this.registry,e.provider(),s,r,l);return{model:s.name,role:r.role.name,instructions:n,transcript:r.transcript,content:r.system.content,preferences:r.system.preferences,constraints:c,tokens:{breakdown:{system:0,transcript:0},total:0,source:"estimated"},execute:e=>u.execute(e)}}static provider(){return"google"}models(){return this._models}},fe={};i(fe,{VercelAIAdapter:()=>we,mappings:()=>ye});var ye=e=>{const t=e.createContent.bind(e);return{text:{to:({block:e})=>({type:"text",text:e.value.text}),from:e=>t("text",{text:e.text},{mode:"readwrite"})},preference:{to:({block:e})=>({type:"text",text:`[Preference]: ${e.value.instruction}`}),from:e=>t("preference",{instruction:e.instruction},{mode:"read"})},json:{to:({block:e})=>({type:"text",text:JSON.stringify(e.value,null,2)}),from:e=>t("json",e,{mode:"readwrite"})},image:{to:async({block:e,resolve:t})=>{const r=e.value.ref;if(!r)return null;const s=await t(r);if(!s.ok||!s.value)return null;return{type:"text",text:`[Image: ${s.value.id}]`}},from:e=>t("image",{ref:e.ref,altText:e.altText},{mode:"readwrite"})},document:{to:async({block:e,resolve:t})=>{const r=e.value.ref;if(!r)return null;const s=await t(r);if(!s.ok||!s.value)return null;return{type:"text",text:`[Document: ${s.value.id}]`}},from:e=>t("document",{ref:e.ref,title:e.title},{mode:"readwrite"})},thinking:{to:({block:e})=>"internal"===e.mode?null:{type:"text",text:e.value.thinking},from:e=>t("thinking",{thinking:e.thinking},{mode:"internal"})}}},we=class t{constructor(e,t,r,s){this.model=e,this.assembler=t,this.registry=r,this.profile=s,this.registerMappings()}registerMappings(){const e=ye(this.registry);for(const[r,s]of Object.entries(e))this.registry.update(r,{mappings:{[t.provider()]:s}})}async status(){return{provider:this.profile.provider,model:this.profile.name,ready:!0,window:this.profile.window,feature:this.profile.feature,pricing:this.profile.pricing,rate:{load:0,capacity:this.profile.capacity}}}async resolve(e){const{prompt:s}=e,{system:i,sections:n,transcript:o}=await this.assembler.build(t.provider(),s,(({turn:e,parts:t})=>"assistant"===e.actor?{role:"assistant",content:t}:{role:"user",content:t})),a=this.profile.name,c=s.constraints[a]??{tokens:{}};return{model:a,role:s.role.name,instructions:n,transcript:s.transcript,content:s.system.content,preferences:s.system.preferences,constraints:c,tokens:{breakdown:{},total:0,source:"estimated"},execute:async e=>{try{const t=this.assembler.registry.schema(),n=e.thought?.tokens??c.tokens.thought,d={};this.profile.feature.thinking&&n&&("anthropic"===this.profile.provider?d.anthropic={thinking:{type:"enabled",budgetTokens:n}}:"openai"===this.profile.provider&&(d.openai={reasoningEffort:n>1e3?"high":"medium"}));const l=r.Output.object({schema:t});if(e.stream){const{partialOutputStream:t,usage:n,finishReason:u}=r.streamText({model:this.model,system:i,messages:o,output:l,abortSignal:e.abort,temperature:c.temperature,maxOutputTokens:c.tokens.max,stopSequences:c.tokens.stops,providerOptions:d});let p=null;for await(const e of t)p=e;return this.mapResponse(p,s.session,a,await n,await u)}{const{output:t,usage:n,finishReason:u}=await r.generateText({model:this.model,system:i,messages:o,output:l,abortSignal:e.abort,temperature:c.temperature,maxOutputTokens:c.tokens.max,stopSequences:c.tokens.stops,providerOptions:d});return this.mapResponse(t,s.session,a,n,u)}}catch(e){return y.fail(new g({code:"INTERNAL_ERROR",message:e.message||"Failed to execute Vercel AI SDK request"}))}}}}mapResponse(r,s,i,n,o){const a=this.assembler.parse(t.provider(),r?.blocks??[]),c={id:m.uuid(e.v7()),session:s,actor:"assistant",version:1,blocks:a,model:i,created:m.timestamp((new Date).toISOString()),updated:m.timestamp((new Date).toISOString()),metadata:{usage:n,finishReason:o}};return y.ok({turn:c,effects:[]})}static provider(){return"vercel"}models(){return[this.profile]}},be="blob_bytes",ke="blob_records";function ve(e){return new Promise(((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)}))}function Se(e){return new Promise(((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(new Error("Transaction aborted"))}))}exports.AgentModule=class{name="agent";schemas=[ie];_roleStore;stores=async e=>(this._roleStore=new ne(await e.collection("role")),{roles:this._roleStore});actions={"role:add":async(e,t)=>{const r={...t.payload,version:1,created:t.timestamp,updated:t.timestamp};await(this._roleStore?.add(r));const s=this._roleStore?.summarize(r);return{index:{roles:{[r.name]:s}}}},"role:update":async(e,t)=>{const{name:r,updates:s}=t.payload;if(!e.index.roles[r])return{};const i=await(this._roleStore?.update(r,{...s,updated:t.timestamp}));if(!i)return{};const n=this._roleStore?.summarize(i);return{index:{roles:{[r]:n}}}},"role:delete":async(e,t)=>{const{name:r}=t.payload;return e.index.roles[r]?(await(this._roleStore?.delete(r)),{index:{roles:{[r]:_()}}}):{}}};async index(e){if(!this._roleStore)return{roles:{}};const t=await this._roleStore.list(),r={};for(const e of t)r[e.name]=this._roleStore.summarize(e);return{roles:r}}},exports.AuthContextBuilder=E,exports.BaseStore=j,exports.Branded=m,exports.CommonErrors=f,exports.ConsoleLogger=w,exports.ContentModule=K,exports.ContentRegistry=z,exports.DELETE_SYMBOL=S,exports.GoogleAdapter=oe,exports.IndexedDBBlobStorage=class{dbName;db=null;constructor(e={}){this.dbName=e.dbName??"aiworkspace-blobs"}async open(){this.db||(this.db=await new Promise(((e,t)=>{const r=indexedDB.open(this.dbName,1);r.onupgradeneeded=e=>{const t=e.target.result;this.createSchema(t)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error),r.onblocked=()=>t(new Error(`[IndexedDBBlobStorage] Database "${this.dbName}" blocked.`))})),this.db.onversionchange=()=>{this.db?.close(),this.db=null})}createSchema(e){e.objectStoreNames.contains(be)||e.createObjectStore(be,{keyPath:"sha256"}),e.objectStoreNames.contains(ke)||e.createObjectStore(ke,{keyPath:"sha256"})}close(){this.db?.close(),this.db=null}async deleteDatabase(){this.close(),await new Promise(((e,t)=>{const r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>e(),r.onerror=()=>t(r.error)}))}getDB(){if(!this.db)throw new Error("[IndexedDBBlobStorage] Database not open. Call open() first.");return this.db}readTx(...e){return this.getDB().transaction(e,"readonly")}writeTx(...e){return this.getDB().transaction(e,"readwrite")}async storeBytes(e,t){const r=this.readTx(be);if(await ve(r.objectStore(be).get(e)))return;const s=this.writeTx(be);s.objectStore(be).put({sha256:e,data:t}),await Se(s)}async loadBytes(e){const t=this.readTx(be),r=await ve(t.objectStore(be).get(e));return r?.data??null}async hasBytes(e){const t=this.readTx(be);return await ve(t.objectStore(be).count(e))>0}async deleteBytes(e){const t=this.writeTx(be);t.objectStore(be).delete(e),await Se(t)}async exportAllBytes(){const e=this.readTx(be);return(await ve(e.objectStore(be).getAll())).map((({sha256:e,data:t})=>[e,t]))}},exports.Kernel=C,exports.LLM=class{adapters=new Map;modelsByProvider=new Map;modelProfiles=new Map;use(e,t){this.adapters.set(e,t);const r=t.models(),s=[];for(const t of r){if(t.provider!==e)throw new Error(`Profile provider mismatch: expected "${e}", got "${t.provider}" for model "${t.name}"`);this.modelProfiles.set(t.name,t),s.push(t.name)}this.modelsByProvider.set(e,s)}async status(e){if(e){const t=this.modelProfiles.get(e);if(!t)throw new g({code:"NOT_FOUND",message:`Model "${e}" not found in LLM registry.`});const r=this.adapters.get(t.provider);if(!r)throw new g({code:"NOT_FOUND",message:`Provider "${t.provider}" for model "${e}" is not registered.`});return r.status(e)}throw new g({code:"INVALID_ARGUMENT",message:"LLM orchestrator requires a specific model name for status queries."})}async resolve(e){const t=e.prompt.model;if(!t)throw new g({code:"INVALID_ARGUMENT",message:"Prompt must specify a model for resolution."});const r=this.modelProfiles.get(t);if(!r)throw new g({code:"NOT_FOUND",message:`Model "${t}" not found in LLM registry.`});const s=this.adapters.get(r.provider);if(!s)throw new g({code:"NOT_FOUND",message:`Provider "${r.provider}" for model "${t}" is not registered.`});return s.resolve(e)}models(){return Array.from(this.modelProfiles.values())}modelsBy(e){return(this.modelsByProvider.get(e)??[]).map((e=>this.modelProfiles.get(e))).filter(Boolean)}hasModel(e){return this.modelProfiles.has(e)}profile(e){return this.modelProfiles.get(e)}},exports.MemoryBlobStorage=class{bytes=new Map;async storeBytes(e,t){this.bytes.has(e)||this.bytes.set(e,t)}async loadBytes(e){return this.bytes.get(e)??null}async hasBytes(e){return this.bytes.has(e)}async deleteBytes(e){this.bytes.delete(e)}async exportAllBytes(){return Array.from(this.bytes.entries()).map((([e,t])=>[e,new Uint8Array(t)]))}},exports.ModuleAggregator=$,exports.PromptAssembler=class{constructor(e,t,r=console){this.resolver=t,this.registry=e,this.logger=r}registry;logger;async build(e,t,r,s=[]){const i=this.buildSections(t,s);return{system:this.join(i),sections:i,transcript:await Promise.all(t.transcript.map((async t=>{const s=[];for(const r of t.blocks)try{const t=this.registry.get(r.type);if(!t)continue;if(!("read"===t.mode||"readwrite"===t.mode))continue;const i=t.mappings?.[e];if(!i)continue;const n=await Promise.resolve(i.to({block:r,resolve:async t=>{try{return await this.resolver(t,e)}catch(r){throw this.logger.error(`Failed to resolve blob ref "${t}" for provider "${e}"`,r),r}}}));null!=n&&s.push(n)}catch(t){this.logger.error(`Error mapping block type "${r.type}" (key: ${r.key??"unknown"}) for provider "${e}"`,t)}return r({turn:t,parts:s})})))}}buildSections(e,t=[]){const r=e.system??{},s=[...r.extensions||[],...t],i=[];var n;i.push({label:"operating-system",content:re}),i.push({label:"block-architecture",content:this.registry.description()}),r.persona&&i.push({label:"persona",content:(n=r.persona,`# Persona\n${n}`)});const o=r.preferences??[];if(o.length>0){const e=function(e,t){const r=e.map((e=>{const r=e.value?.instruction;return r?`- ${r}`:(t.warn(`Preference block "${e.key??"unknown"}" has no instruction.`),null)})).filter((e=>null!==e));return 0===r.length?"":`# User Preferences\n${r.join("\n")}`}(o,this.logger);e?i.push({label:"preferences",content:e,metadata:{count:o.length}}):this.logger.warn("All preferences were empty or invalid, skipping preferences section.")}const a=r.content??[];if(a.length>0){const[e,t]=a.reduce(((e,t)=>("read"===t.mode?e[0].push(t):e[1].push(t),e)),[[],[]]);if(e.length>0){const t=function(e,t,r){const s=t.map((t=>{const s=e.get(t.type);if(s?.format)try{return s.format(t)}catch(e){return r.error(`Error formatting context block "${t.key??"unknown"}" (type: ${t.type})`,e),null}return r.warn(`Unsupported context type: ${t.type} (key: ${t.key??"unknown"}). No formatter registered.`),null})).filter((e=>null!==e));return 0===s.length?"":`# Context\n\n${s.join("\n\n")}`}(this.registry,e,this.logger);t&&i.push({label:"context",content:t,metadata:{count:e.length}})}if(t.length>0){const e=function(e,t,r){if(!t||0===t.length)return"";const s=t.map((t=>{const s=e.get(t.type);if(s?.format)try{return s.format(t)}catch(e){return r.error(`Error formatting artifact block "${t.key??"unknown"}" (type: ${t.type})`,e),null}return r.warn(`Unsupported artifact type: ${t.type} (key: ${t.key??"unknown"}). No formatter registered.`),null})).filter((e=>null!==e));return 0===s.length?"":`# Artifacts\n\n${s.join("\n\n")}`}(this.registry,t,this.logger);e&&i.push({label:"artifacts",content:e,metadata:{count:t.length}})}}r.instructions&&i.push({label:"instructions",content:`# Instructions\n${r.instructions}`});const c=[...i],d=[];for(const e of s){const{position:t,...r}=e,s=se(t);if("prepend"===s.placement){d.push(r);continue}if("append"===s.placement){c.push(r);continue}const i=c.findIndex((e=>e.label===s.label));if(-1===i){this.logger.warn(`Extension anchor label "${s.label}" not found, appending to end.`),c.push(r);continue}const n="before"===s.placement?i:i+1;c.splice(n,0,r)}return[...d,...c]}parse(e,t){const r=[];for(const s of t)try{const t=this.registry.parse(s,e);t&&r.push(t)}catch(t){this.logger.error(`Failed to parse raw block of type "${s.type}" for provider "${e}"`,t)}return r}join(e){return e.filter((e=>e.content&&e.content.trim().length>0)).map((e=>e.content)).join("\n\n---\n\n")}},exports.Registry=I,exports.Result=y,exports.Session=ee,exports.SessionManager=class{constructor(e,t){this.kernel=e,this.stores=t}openOnce=new Map;async open(e,t){let r=this.openOnce.get(t);r||(r=new p,this.openOnce.set(t,r));const s=await r.do((async()=>{const r=this.kernel.state.get().index,s=r.sessions?.[t];if(!s)throw new g({code:"NOT_FOUND",message:`Session ${t} not found in workspace index`});return new ee(m.uuid(e),t,this.kernel,this.stores)}));if(s.error)throw s.error;return s.value}close(e){this.openOnce.delete(e)}async delete(e){const t=(new Date).toISOString(),r=await this.kernel.coordinator.dispatch(A.default,{type:"session:delete",payload:{id:e},timestamp:m.timestamp(t)});if(r.ok)return this.close(e),{ok:!0,value:void 0};throw r.error}async has(e){const t=this.kernel.state.get().index;return!!t.sessions?.[e]}async create(t,r){const s=e.v7(),i=(new Date).toISOString(),n={id:s,label:r.label,role:r.role,topics:r.topics??[],preferences:r.preferences??[],created:i,updated:i,metadata:r.metadata??{}},o=await this.kernel.coordinator.dispatch(R(m.uuid(t)),{type:"session:create",payload:n,timestamp:m.timestamp(i)});if(o.ok)return this.open(t,s);throw o.error}list(){const e=this.kernel.state.get().index;return e.sessions?Object.values(e.sessions):[]}metadata(e){const t=this.kernel.state.get().index;return t.sessions?.[e]}},exports.SessionModule=Q,exports.SystemActor=A,exports.SystemError=g,exports.TurnBuilder=te,exports.TurnTree=Z,exports.VercelAdapter=fe,exports.WorkspaceDatabase=class{constructor(e){this.config=e}openOnce=new p({retry:!0,throws:!0});closeOnce=new p({retry:!0,throws:!0});db=null;async open(e=[]){await this.openOnce.do((async()=>{const{factory:r,schemas:s,...i}=this.config;this.db=await t.DatabaseConnection(i,r),await this.db.setupCollections([...s,...e])}))}async collection(e){if(!this.db)throw new g({code:"DATABASE_NOT_OPEN",message:"Please open database before trying to access collections"});return this.db?.collection(e)}async close(){await this.closeOnce.do((()=>this.db?.close()))}database(){return this.db}},exports.WorkspaceModule=U,exports.createAnonymousContext=function(){return T("anonymous",m.uuid("00000000-0000-0000-0000-000000000001")).withScope("public").build()},exports.createAuthContext=T,exports.createError=function(e,t){return new g({code:e,message:t})},exports.createLogger=function(e,t){return new w(e,{muted:t})},exports.createUserContext=R,exports.createWorkspace=async function(e){const{state:t,database:r,storage:s,authorizer:i,extensions:n=[],logger:o=b}=e,a=new $(t,o),c=new K({blobStorage:s,logger:o}),d=new Q;a.use(c),a.use(d),a.use(U);for(const e of n)a.use(e);await r.open(a.schemas());const l=await a.instantiateStores(r),u=new C({state:t,authorizer:i,registries:a,logger:o});for(const e of a.list())if(e.actions)for(const[t,r]of Object.entries(e.actions))u.actions.register(e.name,t,r);for(const e of a.middleware())u.actions.use(e);return await u.rebuildIndex(),{kernel:u,stores:l,aggregator:a}},exports.deepClone=v,exports.del=_,exports.logger=b,exports.merge=O;