@asaidimu/utils-workspace 6.6.4 → 6.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +1 -1
- package/index.mjs +1 -1
- package/package.json +4 -3
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("@asaidimu/utils-events"),t=require("uuid"),s=Object.defineProperty,r=[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 r of t)s[r.name]=e.roles.summarize(r);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const r of t)s[r.id]=e.preferences.summarize(r);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const r of t)s[r.key]=e.context.summarize(r);return{index:{context:s}}},async e=>{const t=await e.artifacts.list(),s={};for(const r of t)s[r.key]=e.artifacts.summarize(r);return{index:{artifacts:s}}},async e=>{const t=await e.sessions.list(),s={};for(const r of t)s[r.id]=e.sessions.summarize(r);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const r of t)s[r.name]=e.topics.summarize(r);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],n=[{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:[]}],i=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},o=class extends i{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},a=class extends i{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},c=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 r;await Promise.race([s.then((()=>clearTimeout(r))),new Promise(((s,n)=>{r=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),n(new o("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}},d=class{mutex=new c({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 r;return Promise.race([e.then((e=>(clearTimeout(r),e))),new Promise(((e,n)=>{r=setTimeout((()=>n(new o(s))),t)}))])}},l=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new c({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new a};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,r=null;try{if(this._done)throw new a;r=await e(),this._lastValue=r,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:r,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 u(e){const t=new d({retry:!0,throws:!0}),s=new d({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...n,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var p={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic",ARTIFACT:"artifact"},h=Symbol.for("delete"),m=e=>Array.isArray(e)?[...e]:{...e};function f(e){return{ok:!0,value:e}}function y(e){return{ok:!1,error:e}}var g=function(e){const t=e?.deleteMarker||h;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 r={};for(const[n,i]of Object.entries(e))if(i!==t)if("object"==typeof i&&null!==i){const e=s(i);void 0!==e&&(r[n]=e)}else r[n]=i;return r}return e===t?void 0:e}return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?s(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=m(e),i=[{target:n,source:r}];for(;i.length>0;){const{target:e,source:s}=i.pop();for(const r of Object.keys(s)){const n=s[r];if(n!==t)if(Array.isArray(n))e[r]=n;else if("object"==typeof n&&null!==n){const t=r in e&&"object"==typeof e[r]&&null!==e[r]?e[r]:{};e[r]=m(t),i.push({target:e[r],source:n})}else e[r]=n;else delete e[r]}}return n}}({deleteMarker:h});async function w(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 k(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let s=0;s<e.length;s+=32768){const r=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(r)))}return btoa(t.join(""))}function b(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 v(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 x=class{registry=new Map;middlewares=[];serializer=new l;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 y(t.error)}const t=this.registry.get(e.type);if(!t)return y({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),r=await t({workspace:s,...this._ctx},e.payload);if(!r.ok)return r;let n=r.value;for(const t of this.middlewares){const r=await t({workspace:s,command:e,patch:n,...this._ctx});n=g(n,r)}return await this.updateWorkspace(n),this.bus.emit({name:"workspace:changed",payload:n}),"workspace:sync"===e.type&&this.bus.emit({name:"workspace:synced",payload:void 0}),f(n)}));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}}},S=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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 r of e){const e=this.cache.get(r);e?t.push(e):s.push(r)}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 O(e,t,s,r,n,i){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==n||!i)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},i.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[r],d=c.includes(s);if("add"!==n||d){if("remove"===n&&d){const e=Math.max(0,(t.metadata.entries||0)-1);o[a]={...t,[r]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[r]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function _(e,t,s,r){return O(e,t,s,"contextKeys","add",r)}function T(e,t,s){return O(e,t,s,"contextKeys","remove")}function N(e,t,s,r){return O(e,t,s,"preferences","add",r)}function D(e,t,s){return O(e,t,s,"preferences","remove")}var R=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,r=t.index.topics;let n={};const i=e=>{const t=e?.index?.topics;t&&(n=g(n,t))};if(s.index?.context)for(const[n,o]of Object.entries(s.index.context)){const s=t.index.context[n];if(void 0===o&&s)i(T(r,s.topics,s.key));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(T(r,c,s.key)),a.length&&i(_(r,a,s.key,e.topics))}}else i(_(r,o.topics??[],o.key,e.topics))}if(s.index?.preferences)for(const[n,o]of Object.entries(s.index.preferences)){const s=t.index.preferences[n];if(void 0===o&&s)i(D(r,s.topics,s.id));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(D(r,c,s.id)),a.length&&i(N(r,a,s.id,e.topics))}}else i(N(r,o.topics??[],o.id,e.topics))}return Object.keys(n).length?{index:{topics:n}}:{}},A=async e=>{const{command:t,workspace:s}=e;if("artifact:add"!==t.type)return{};const{sessionId:r,key:n}=t.payload,i=s.index.sessions[r];if(!i)return console.warn(`[sessionArtifactMiddleware] Session ${r} not found in index`),{};const o=i.artifacts||[];if(o.includes(n))return{};const a=[...o,n];return await e.sessions.update(r,{artifacts:a}),{index:{sessions:{[r]:{artifacts:a}}}}},I="\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 E(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 j=class{constructor(e,t){this.resolver=t,this.registry=e}registry;async build(e,t,s,r=[]){const n=this.buildSections(t,r);return{system:this.join(n),sections:n,transcript:await Promise.all(t.transcript.map((async t=>{const r=[];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 n=t.mappings?.[e];if(!n){console.log({definition:t}),console.warn(`[PromptAssembler] build: no active mapping for block type "${s.type}" — skipping.`);continue}const i=await Promise.resolve(n.to({block:s,resolve:t=>this.resolver(t,e)}));null!=i&&r.push(i)}return s({turn:t,parts:r})})))}}buildSections(e,t=[]){const s=[...e.system.extensions||[],...t],r=[];var n,i,o,a;r.push({label:"operating-system",content:I}),e.role.persona&&r.push({label:"persona",content:(n=e.role.persona,`# Persona\n${n}`)}),e.system.preferences.length>0&&r.push({label:"preferences",content:(i=e.system.preferences,`# User Preferences\n${i.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&r.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&&r.push({label:"artifacts",content:(a=e.system.artifacts,`# Artifacts\n\n${a.map((e=>`[${e.key}] (${e.label}, v${e.version}, ${e.status})\nDescription: ${e.description}\n\n${e.content.value}`)).join("\n\n")}`),metadata:{count:e.system.artifacts.length}}),e.system.instructions&&r.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const c=[...r],d=[];for(const e of s){const{position:t,...s}=e,r=E(t);if("prepend"===r.placement){d.push(s);continue}if("append"===r.placement){c.push(s);continue}const n=c.findIndex((e=>e.label===r.label));if(-1===n){console.warn(`[SystemPromptAssembler] Anchor target "${r.label}" not found in sections. Extension "${e.label}" will be appended.`),c.push(s);continue}const i="before"===r.placement?n:n+1;c.splice(i,0,s)}return[...d,...c]}parse(e,t){const s=[];for(const r of t){const t=this.registry.parse(r,e);t&&s.push(t)}return s}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};var q={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:r,settings:n,project:i}=t,o=await s.get(r);return o?f({id:o.id,settings:o.settings,project:o.project}):(await s.add({id:r,settings:n,project:i}),f({id:r,settings:n,project:i,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 r=await t(e);s=g(s,r)}return t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=g(s.settings||{},t.settings)),t.project&&(s.project=g(s.project||{},t.project))),f(s)},"role:add":async function(e,t){const{workspace:s,roles:r}=e,n=t;return s.index.roles[n.name]?y({code:"DUPLICATE_KEY",resource:"Role",key:n.name}):(await r.add(n),f({index:{roles:{[n.name]:r.summarize(n)}}}))},"role:update":async function(e,t){const{workspace:s,roles:r}=e,{name:n,...i}=t;if(!s.index.roles[n])return y({code:"NOT_FOUND",resource:"Role",id:n});const o=await r.update(n,i);return o?f({index:{roles:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update role ${n} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:r}=e,{name:n}=t;return s.index.roles[n]?await r.delete(n)?f({index:{roles:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete role ${n} from store.`}):y({code:"NOT_FOUND",resource:"Role",id:n})},"preference:add":async function(e,t){const{workspace:s,preferences:r}=e,n=t;return s.index.preferences[n.id]?y({code:"DUPLICATE_KEY",resource:"Preference",key:n.id}):(await r.add(n),f({index:{preferences:{[n.id]:r.summarize(n)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:r}=e,{id:n,...i}=t;if(!s.index.preferences[n])return y({code:"NOT_FOUND",resource:"Preference",id:n});const o=await r.update(n,i);return o?f({index:{preferences:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update preference ${n} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:r}=e,{id:n}=t;return s.index.preferences[n]?await r.delete(n)?f({index:{preferences:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete preference ${n} from store.`}):y({code:"NOT_FOUND",resource:"Preference",id:n})},"context:add":async function(e,t){const{workspace:s,context:r}=e,n=t;return s.index.context[n.key]?y({code:"DUPLICATE_KEY",resource:"Context",key:n.key}):(await r.add(n),f({index:{context:{[n.key]:r.summarize(n)}}}))},"context:update":async function(e,t){const{workspace:s,context:r}=e,{key:n,...i}=t,o=s.index.context[n];if(!o)return y({code:"NOT_FOUND",resource:"Context",id:n});const a=await r.update(n,i,o.kind);return a?f({index:{context:{[n]:r.summarize(a)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update context ${n} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:r}=e,{key:n}=t,i=s.index.context[n];return i?await r.delete(n,i.kind)?f({index:{context:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete context ${n} from store.`}):y({code:"NOT_FOUND",resource:"Context",id:n})},"artifact:add":async function(e,s){const{workspace:r,artifacts:n}=e,{sessionId:i,...o}=s;if(r.index.artifacts[o.key])return y({code:"DUPLICATE_KEY",resource:"Artifact",key:o.key});const a={...o,type:"artifact",id:t.v7()};return await n.add(a),f({index:{artifacts:{[o.key]:n.summarize(o)}}})},"artifact:update":async function(e,t){const{workspace:s,artifacts:r}=e,{sessionId:n,...i}=t,o=i.key;if(!s.index.artifacts[o])return y({code:"NOT_FOUND",resource:"Artifact",id:o});const a=await r.get(o);if(!a)return y({code:"NOT_FOUND",resource:"Artifact",id:o});let c=a.content;if(i.content)c=i.content;else if(i.patch)return y({code:"INVALID_COMMAND",reason:"Patch updates for artifacts are not yet implemented."});const d={...a,content:c,status:i.status,version:a.version+1,updated:(new Date).toISOString()};return await r.update(o,d),f({index:{artifacts:{[o]:r.summarize(d)}}})},"artifact:delete":async function(e,t){const{workspace:s,artifacts:r}=e,{key:n}=t;return s.index.artifacts[n]?await r.delete(n)?f({index:{artifacts:{[n]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete artifact ${n} from store.`}):y({code:"NOT_FOUND",resource:"Artifact",id:n})},"topic:add":async function(e,t){const{workspace:s,topics:r}=e,n=t;return s.index.topics[n.name]?y({code:"DUPLICATE_KEY",resource:"Topic",key:n.name}):(await r.add(n),f({index:{topics:{[n.name]:r.summarize(n)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:r}=e,{name:n,...i}=t;if(!s.index.topics[n])return y({code:"NOT_FOUND",resource:"Topic",id:n});const o=await r.update(n,i);return o?f({index:{topics:{[n]:{metadata:{updated:o.updated}}}}}):y({code:"BACKEND_ERROR",reason:`Failed to update topic ${n} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return y({code:"NOT_FOUND",resource:"Topic",id:o});if(r.referencedBy(o,s.index)&&!a)return y({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 n.get(e);t&&await n.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 i.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await r.delete(o)?f({index:{topics:{[o]:h}}}):y({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return y({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 n.get(e);if(t){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await n.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 i.update(e,{topics:s})}}return await r.delete(o),f({index:{topics:{[o]:h}}})},"session:create":async function(e,t){const{workspace:s,sessions:r}=e,n=t;return s.index.sessions[n.id]?y({code:"DUPLICATE_KEY",resource:"Session",key:n.id}):(await r.add(n),f({index:{sessions:{[n.id]:r.summarize(n)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,...i}=t;if(!s.index.sessions[n])return y({code:"NOT_FOUND",resource:"Session",id:n});const o=await r.update(n,i);return o?f({index:{sessions:{[n]:r.summarize(o)}}}):y({code:"BACKEND_ERROR",reason:`Failed to update session ${n} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,newSessionId:i,label:o}=t,a=s.index.sessions[n];if(!a)return y({code:"NOT_FOUND",resource:"Session",id:n});const c={...a,id:i,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await r.add(c),f({index:{sessions:{[i]:r.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n}=t;return s.index.sessions[n]?(await r.delete(n),f({index:{sessions:{[n]:h}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"session:role:switch":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,roleName:i}=t;return s.index.sessions[n]?(await r.update(n,{role:i}),f({index:{sessions:{[n]:{role:i}}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"session:topics:add":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,topics:i}=t,o=s.index.sessions[n];if(!o)return y({code:"NOT_FOUND",resource:"Session",id:n});const a=Array.from(new Set([...o.topics,...i]));return await r.update(n,{topics:a}),f({index:{sessions:{[n]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,preferences:i}=t;return s.index.sessions[n]?(await r.update(n,{preferences:i}),f({index:{sessions:{[n]:{preferences:i}}}})):y({code:"NOT_FOUND",resource:"Session",id:n})},"turn:add":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return y({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,turns:r}=e,{sessionId:n,turn:i}=t;if(!s.index.sessions[n])return y({code:"NOT_FOUND",resource:"Session",id:n});const{id:o,session:a,version:c,...d}=i;return await r.update({id:o,session:a,version:c},d),f({})},"turn:edit":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d,modelSnapshot:l}=t,u=s.index.sessions[i];if(!u)return y({code:"NOT_FOUND",resource:"Session",id:i});let p={};const h=await n.get({id:o,version:c-1,session:i});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:i};if(await n.add(m),u.head?.id===o){const e={id:o,version:c};return await r.update(i,{head:e}),f({index:{sessions:{[i]:{head:e}}}})}return f({})},"turn:branch":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return y({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newHead:a}=t;return s.index.sessions[i]?(await n.delete({session:i,id:o,version:t.version}),a?(await r.update(i,{head:a}),f({index:{sessions:{[i]:{head:a}}}})):f({})):y({code:"NOT_FOUND",resource:"Session",id:i})},"blob:register":async function(e,t){const{blobs:s}=e,r=await s.register(t.data,t.mediaType,t.filename);if(!r.ok)return r;const n=await s.getRecord(r.value.sha256);return n?f({index:{blobs:{[n.sha256]:n}}}):y({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${r.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,r=await s.retain(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return f({index:{blobs:{[t.sha256]:n}}})},"blob:release":async function(e,t){const{blobs:s}=e,r=await s.release(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return f({index:{blobs:{[t.sha256]:n||h}}})},"blob:purge":async function(e,t){const{blobs:s}=e,r=await s.purge(t.sha256);return r.ok?f({index:{blobs:{[t.sha256]:h}}}):r},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:r,providerId:n,fileId:i,timestamp:o}=t,a=await s.recordRemoteId(r,n,i,o);if(!a.ok)return a;const c=await s.getRecord(r);return f({index:{blobs:{[r]:c}}})},"tool:call":async function(e,t){return f({})}},C=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)}},B={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"]}},U={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.","The current assistant response MUST NOT be included.","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"}},insight:{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"]}},$=[B,{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"]}},U,{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.","","### 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:["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"]},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"]}},{type:"artifact:update",emittable:!0,consumable:!1,description:["## Block: `artifact:update`","","Represents a mutation to an existing artifact previously introduced in the conversation.","Artifacts are identified using their system-provided `key`.","","Artifacts in a structured format:","","`[key] (label, version, status)`","`description`","`content`","","The `key` is the stable identity of an artifact across all updates.","Label, version, and status are descriptive metadata provided for context.","","Updates may be expressed as full replacements or targeted patches."].join("\n"),rules:["Use `artifact:update` when modifying an existing artifact identified in context.","Use the `key` from the provided artifact list to select the target artifact.","Rely on the `key` as the stable reference for all updates.","Only use keys that are explicitly present in the current artifact context.","Allow the system to manage `created`, `updated`, and version fields automatically.","Provide either `content` or `patch` to express the update clearly and unambiguously.","Use `content` when replacing the full artifact or when changes are small and localized.","Use `patch` with `format: 'unified-diff'` when making targeted edits to larger artifacts.","Ensure unified diffs apply cleanly to the provided artifact content.","Prefer patch-based updates for large artifacts with localized changes.","Set `status` to `draft` when the artifact is still in progress after the update.","Set `status` to `complete` when the artifact is finalized and ready for use.","Support multiple artifact updates in a single turn when they are independently meaningful.","Prefer updating existing artifacts over creating new ones when continuity is intended."],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 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:["unified-diff"],description:"The patch format. Currently only `unified-diff` is supported."},value:{type:"string",description:"The patch payload. For `unified-diff`, a valid unified diff string applicable to the current artifact content."}},required:["format","value"]}},required:["type","key","status"],oneOf:[{required:["content"]},{required:["patch"]}]}}];function M(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 z=class{store=new Map;constructor(){for(const e of $)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:M(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:","",M(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=M(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 r=this.store.get(e.type);if(!r)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&r.mappings?.[s])return r.mappings[s].from(e);const{id:n,...i}=e;return{id:t.v7(),...i}}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()}}},P=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:r,filename:n}=e.content,i={sha256:t,mediaType:s,sizeBytes:r,filename:n};return s.startsWith("image/")?{id:e.key,type:"image",ref:i}:{id:e.key,type:"document",ref:i,title:n}},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())}},F="__system__",K=class{constructor(e,s,r){this._actor=e,this._turn=r?JSON.parse(JSON.stringify(r)):{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 r={id:t.v7(),type:"image",ref:e,altText:s};return this._turn.blocks.push(r),this}addDocument(e,s){const r={id:t.v7(),type:"document",ref:e,title:s};return this._turn.blocks.push(r),this}addToolUse(e,s){const r={id:t.v7(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(r),this}addToolResult(e,s,r){const n={id:t.v7(),type:"tool:result",useId:e,content:s,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const s={id:t.v7(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const r={id:t.v7(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(r),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 r=this._turn.blocks[s];if("text"!==r.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...r,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))}},W=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}},L=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s,r){const[n,i]=await Promise.all([s.loadAllTurns(t),void 0!==r?Promise.resolve(r):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 r=new Set;let n=t;for(;n;){const e=`${n.id}:${n.version}`;if(r.has(e))break;r.add(e);const t=s.get(e);if(!t)break;n=t.parent}return r}(e,t),r={},n={};for(const t of e){r[t.id]||(r[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:{}},n[t.id]=new Set);const e=r[t.id];e.versions[t.version]=t;const i=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(i&&(!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(n[t.parent.id]||(n[t.parent.id]=new Set),!n[t.parent.id].has(e+":"+t.id)){n[t.parent.id].add(e+":"+t.id),r[t.parent.id]||(r[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=r[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return r}(n,i);return new e(o,i)}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 r=s.children[t.parent.version];return r?r.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)),r=s.indexOf(t.activeVersion);return{versions:s,currentIndex:r,total:s.length,hasPrev:r>0,hasNext:r<s.length-1}}graph(){return{...this.nodes}}};var V=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}},Y=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()}},J=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,r,n=[]){if(this.workspace.index.roles[e])return y({code:"DUPLICATE_KEY",resource:"role",key:e});const i={name:e,label:t,description:r,persona:s,preferences:n,topics:[]};return this.manager.dispatch({type:"role:add",payload:i,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()}):y({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return y({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?y({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,r){const n={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:r};return this.manager.dispatch({type:"context:add",payload:n,timestamp:n.timestamp})}context(){return this.manager.ctx().context.list()}async registerBlob(e,t,s){const r=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!r.ok)return y(r.error);const n=r.value,i=n?.index?.blobs;if(!i)return y({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(i)[0];if(!o)return y({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=i[o];if(!a)return y({code:"BACKEND_ERROR",reason:"Blob record missing"});return f({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},H=class e{constructor(e,t,s,r){this._id=e,this.manager=t,this.processor=s,this.turnRepository=r,this.workspace=new J(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,r){s.ctx().workspace;const n=new W(s.ctx().turns,s.ctx().sessions),i=new e(t,s,r,n);return await i.sync(),i}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()}):y({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()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async setModel(e){return this.meta()?this.updateMetadata({model:e}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async updateMetadata(e){const t=this.meta();if(!t)return y({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()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return y({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()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async addContext(e){const t=this.meta();if(!t)return y({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 y({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()}):y({code:"NOT_FOUND",resource:"session",id:this._id})}async fork(e,t,s,r){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:r},timestamp:(new Date).toISOString()}):y({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 y({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==F&&!t.index.roles[e])return y({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 y({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},r=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:s},timestamp:s.timestamp});if(r.ok){const e={id:s.id,version:s.version};await this.refreshTurnTree(e)}return r}async recordUserTurn(e){return this.meta()?this.addTurn(e):y({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return y({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return y({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.processor.process(e,this._id);let n={};const i=[];let o;for(const e of r){const t=await this.manager.dispatch(e);if(t.ok)n=g(n,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic){o=t.error;break}{const t=this.describeCommand(e);i.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(n=g(n,a.value),t&&i.length>0){const e=this.buildDenialTurn(i),t=await this.addTurn(e);t.ok&&(n=g(n,t.value))}return o?y(o):f(n)}buildDenialTurn(e){const t=new K("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,r){if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph()[e];if(!n)return y({code:"NOT_FOUND",resource:"turn",id:e});const i=n.versions[n.activeVersion],o=Object.keys(n.versions).length,a=await this.dispatch({type:"turn:edit",payload:{sessionId:this._id,turnId:e,newBlocks:t,roleSnapshot:s??i.role,modelSnapshot:r??i.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 y({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return y({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 y({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph();if(!r[e]?.versions[t])return y({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const n=await this.dispatch({type:"turn:delete",payload:{sessionId:this._id,turnId:e,version:t,newHead:s},timestamp:(new Date).toISOString()});return n.ok&&await this.refreshTurnTree(s),n}async updateTurnStatus(e,t,s){const r=this.tree.graph()[e];if(!r)return y({code:"NOT_FOUND",resource:"turn",id:e});const n=r.versions[t];if(!n)return y({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const i={...n,metadata:{...n.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:i},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 y({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return y({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return y({code:"NOT_FOUND",resource:"turn",id:e});const r=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),n=r.indexOf(s.activeVersion);if(-1===n)return y({code:"INVALID_COMMAND",reason:"Active version not found"});const i=n+t;if(i<0||i>=r.length)return y({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=r[i],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 r=t.ws(),n=t._role;if(!n)return;const i=await t.manager.ctx().context.getByTopics(r.index,s.topics),o=s.context?await Promise.all(s.context.map((e=>t.manager.ctx().context.get(e)))):[],a=Array.from(new Map([...i,...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([...n.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:n,preferences:l,context:a,artifacts:c,model:s.metadata?.model,transcript:u,topics:s.topics,instructions:r.settings?.prompt,constraints:{role:n.constraints,session:s.constraints,turn:p?.constraints}}}async refreshTurnTree(e){this.tree=await L.build(this._id,this.turnRepository,e)}findSubtreeTip(e,t,s){let r=t,n=s;for(;;){const t=e[r];if(!t)break;const s=t.children[n];if(!s||0===s.length)break;const i=s[0],o=e[i];if(!o)break;r=i,n=o.activeVersion}return{id:r,version:n}}},G=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 d,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 H.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(),r=e.metadata??{},n=await this.manager.dispatch({type:"session:create",payload:{id:s,label:e.label,role:e.role,topics:e.topics,preferences:e.preferences??[],metadata:{...r,created:(new Date).toISOString()}},timestamp:(new Date).toISOString()});if(n.ok)return this.open(s);throw n.error}list(){return Object.values(this.manager.workspace().index.sessions)}metadata(e){return this.manager.workspace().index.sessions[e]}},X=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const r=await w(e),n=await this.getRecord(r);if(n){const e={...n,refCount:n.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(r,e),f(this.reference(e))}const i={sha256:r,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(i,e):(await this.storage.storeBytes(r,e),await this.storage.saveRecord(i)),this.cache.set(r,i),this.bus.emit({name:"blobs:changed",payload:{sha256:r,record:i}}),f(this.reference(i))}async retain(e){const t=await this.getRecord(e);if(!t)return y({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),f(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return y({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),r={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(r),this.cache.set(e,r),f(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}}),f(void 0)}async recordRemoteId(e,t,s,r){const n=await this.getRecord(e);if(!n)return y({code:"NOT_FOUND",resource:"blob",id:e});const i={...n,remoteIds:{...n.remoteIds,[t]:{id:s,timestamp:r||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:i}}),f(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 f(null);if(t){const e=s.remoteIds[t];if(e)return f({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const r=await this.storage.loadBytes(s.sha256);return f(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}const r=await this.storage.loadBytes(s.sha256);return f(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}async resolveMany(e,t){const s=new Map;for(const r of e){const e=await this.resolve(r,t);if(!e.ok)return y(e.error);if(null===e.value)return y({code:"BLOB_ERROR",reason:`Unable to resolve blob ${r.sha256}${t?` with adapter ${t}`:""}`});s.set(r.sha256,e.value)}return f(s)}},Q=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 r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}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 r=this.delegates.get(s);if(r){const s=await r.update(e,t);return s&&this.cache.set(e,s),s}}const r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}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 r=await s.delete();return r&&this.cache.delete(e),r}async getByTopics(e,t){const s=new Map;for(const r of t){const t=e.topics[r];t&&t.contextKeys.forEach((t=>{const r=e.context[t],n=r?.kind||"unknown";s.has(n)||s.set(n,new Set),s.get(n).add(t)}))}if(0===s.size)return[];const r=[],n=[];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&&r.push(t)}else t.forEach((e=>n.push(e)))}if(n.length>0){const e=[];for(const t of n){const s=this.cache.get(t);s?r.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),r.push(t)}}}return r.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}}},Z=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}}},ee=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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 r of e){const e=this.cache.get(r);e?s.push(e):t.push(r)}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)}}},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:"name",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}}},se=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}},re=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},r=!0){const n=this.key({id:e,session:t,version:s});this.cache.get(n)&&this.cache.get(n);const i=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 i?(r&&this.cache.set(n,i),i):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}},ne=(e={})=>({id:e.id??t.v7(),settings:g({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:g({id:t.v7(),name:"Unnamed Project"},e.project),index:g({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}},e.index)});function ie(){return(new Date).toISOString()}function oe(e,t,s){const r=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(s??{})]),n={};for(const i of r){const r=e?.[i]??{},o=t?.[i]??{},a=s?.[i]??{};n[i]={temperature:a.temperature??o.temperature??r.temperature,tokens:{max:a.tokens?.max??o.tokens?.max??r.tokens?.max,stops:a.tokens?.stops??o.tokens?.stops??r.tokens?.stops,thought:a.tokens?.thought??o.tokens?.thought??r.tokens?.thought}}}return n}var ae="blob_bytes",ce="blob_records";function de(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function le(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var ue={};function pe(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 r in t)s(e,r,{get:t[r],enumerable:!0})})(ue,{GOOGLE_MODELS:()=>me,GoogleGenAIAdapter:()=>ge,extractModelResponse:()=>fe,mappings:()=>he});var he={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:v(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 r=await t(s);if(!r.ok||!r.value)return null;const{value:n}=r;return"remote"===n.kind?{fileData:{fileUri:n.fileId,mimeType:n.mediaType}}:{inlineData:{data:k(n.data),mimeType:n.mediaType}}},from:e=>e},document:{to:async({resolve:e,block:t})=>{const s=t.ref;if(!s)return null;const r=await e(s);if(!r.ok||!r.value)return null;const{value:n}=r;return"remote"===n.kind?{fileData:{fileUri:n.fileId,mimeType:n.mediaType}}:{inlineData:{data:k(n.data),mimeType:n.mediaType}}},from:e=>e}},me=[{provider:"google",name:"gemini-3.1-pro-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-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:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"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",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",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-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-preview",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-preview",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-preview",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",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",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}]}];function fe(e){const s=e.candidates?.[0],r=[];if(!s?.content?.parts)return{ok:!1,thinking:r,error:{code:"BACKEND_ERROR",reason:"No valid content parts in response"}};let n;for(const e of s.content.parts)if(e.thought)r.push((i=e.text??"",{id:t.v7(),type:"thinking",thinking:i}));else if(e.text){n=e;break}var i;if(!n)return r.length>0?{ok:!0,thinking:r,rawBlocks:[]}:{ok:!1,thinking:r,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)?f(t.blocks):y({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return y({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(n.text);return o.ok?{ok:!0,thinking:r,rawBlocks:o.value}:{ok:!0,thinking:r,fallback:n.text}}function ye(e){return Math.ceil(e.length/4)}var ge=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const r=this._models.get(s.model);if(!r)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=r,this.registerMappings()}model;_models;registerMappings(){const{assembler:t}=this.services;for(const[s,r]of Object.entries(he))t.registry.update(s,{mappings:{[e.provider()]:r}})}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:r}=s,{assembler:n,blockRegistry:i}=this.services,o=r.model&&this._models.get(r.model)||this.model,{system:a,sections:c,transcript:d}=await n.build(e.provider(),r,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t})),[{label:"block-architecture",content:i.description(),position:"after:instructions"}]),l={role:"system",parts:[{text:a}]},u=r.constraints[o.name]??{tokens:{}},p=i.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(""),g=ye(a),w=ye(m),k=g+w,b=this;return{model:o.name,role:r.role.name,instructions:c,transcript:r.transcript,context:r.system.context,artifacts:r.system.artifacts,preferences:r.system.preferences,constraints:u,tokens:{breakdown:{system:g,transcript:w},total:k,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-k},async execute(){let s;try{s=await b.client.models.generateContent(h)}catch(e){return y({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const n=fe(s);if(!n.ok)return y(n.error);let i;var a;i="fallback"in n?[...n.thinking,(a=n.fallback,{id:t.v7(),type:"text",text:pe(a)})]:[...n.thinking,...b.services.assembler.parse(e.provider(),n.rawBlocks)];const c=new K("assistant",r.session);c.withModel(o.name),c.withRole(r.role.name);for(const e of i)c.addBlock(e);return f({turn:c.build(),effects:[]})},async*executeStream(){let e;try{e=await b.client.models.generateContentStream(h)}catch(e){const s=e instanceof Error?e.message:String(e),n=new K("assistant",r.session);return n.addBlock({id:t.v7(),type:"text",text:`[Stream error: ${s}]`}),void(yield{turn:n.build(),effects:[]})}const s=[];for await(const r of e){const e=r.candidates?.[0];if(e?.content?.parts)for(const r of e.content.parts)r.thought||r.text&&(s.push(r.text),yield{blocks:[{id:t.v7(),type:"text",text:r.text}]})}const n=s.join(""),i=new K("assistant",r.session);i.addBlock({id:t.v7(),type:"text",text:n}),yield{turn:i.build(),effects:[]}}}}static provider(){return"google"}static models(){return me}};exports.COLLECTIONS=p,exports.CoreTurnProcessor=class{process(e,t){const s=[],r=(new Date).toISOString();for(const n of e.blocks)"artifact"===n.type?s.push(this.handleAddArtifact(n,t,r)):"artifact:update"===n.type&&s.push(this.handleUpdateArtifact(n,t,r));return s}handleAddArtifact(e,s,r){const n=t.v7(),i=e.label||`Untitled Artifact ${b(n)}`,o=e.content.extension||"txt",a=i.split(" ").join("-").replace(new RegExp(`\\.${o}$`),"");return{type:"artifact:add",timestamp:r,payload:{...{id:n,label:i,type:"artifact",key:e.key?e.key:`${a||b(i)}.${o}`,version:1,description:e.description||"",content:e.content,status:e.status||"complete",created:r,updated:r},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"]);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,r={}){const n=[],{resolved:i}=function(e){const t=[],s=new Map;for(const r of e)for(const e of r.topics){const n=s.get(e);if(!n){s.set(e,r);continue}const i=new Date(n.timestamp).getTime(),o=new Date(r.timestamp).getTime();o>i?(t.push({topic:e,kept:r.id,dropped:n.id}),s.set(e,r)):i>o&&t.push({topic:e,kept:n.id,dropped:r.id})}const r=new Map,n=new Map;for(const t of e)n.set(t.id,t.topics.length);for(const e of t)r.set(e.dropped,(r.get(e.dropped)??0)+1);const i=new Set;for(const t of e){const e=r.get(t.id)??0,s=n.get(t.id)??0;s>0&&e>=s&&i.add(t.id)}return{resolved:e.filter((e=>!i.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:r.retrieverConfig}),c=[],d=[];for(const e of a){const t=this.contextRegistry.get(e.content.kind);if(!t){n.push(`No ContextDefinition found for kind: ${e.content.kind}`);continue}const s=t.render(e),r=Array.isArray(s)?s:[s];"system"===t.target?c.push({label:`context:${e.content.kind}:${e.key}`,content:r.map((t=>"text"===t.type?t.text:`[${e.content.kind}] ${JSON.stringify(t,null,2)}`)).join("\n"),position:"after:context"}):d.push(...r)}const l=new Map;for(const t of e.artifacts)l.set(t.key,{...t});const u=e.transcript.map((e=>{const t=[];for(const s of e.blocks)if("artifact"===s.type){const r=s;l.set(r.key,{...r,version:r.version||1,created:e.timestamp,updated:e.timestamp}),t.push({type:"text",text:`[Artifact: "${r.label}" produced]`})}else if("artifact:update"===s.type){const r=s,n=l.get(r.key);if(n){const t={...n,status:r.status||n.status,version:(n.version||1)+1,updated:e.timestamp};r.content&&(t.content=r.content),l.set(r.key,t)}t.push({type:"text",text:`[Artifact: "${n?.label||r.key}" updated]`})}else this.NOISE_BLOCK_TYPES.has(s.type)||t.push(s);return{...e,blocks:t}})).filter((e=>e.blocks.length>0));let p=u;r.compress&&(p=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)}(u));const h=[];if(d.length>0){const s=p.length>0?p[0].timestamp:ie();h.push((m=e.id,y="system",g=d,w=s,{id:t.v7(),session:m,version:0,actor:y,blocks:g,timestamp:w??ie()}))}var m,y,g,w;const k=[...h,...p],b=function(e,t){const s=new Map;for(const t of e)if("blob"===t.content.kind){const{sha256:e,mediaType:r,sizeBytes:n,filename:i,previewUrl:o}=t.content;s.has(e)||s.set(e,{sha256:e,mediaType:r,sizeBytes:n,filename:i,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,k);return f({session:e.id,model:e.model,system:{persona:e.role.persona,instructions:e.instructions,preferences:i,context:[],artifacts:Array.from(l.values()),extensions:c},transcript:k,blobs:b,role:e.role,constraints:oe(e.constraints.role,e.constraints.session,e.constraints.turn),warnings:n})}},exports.EMPTY_SYSTEM_ROLE=F,exports.GoogleAdapter=ue,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(ae)||e.createObjectStore(ae,{keyPath:"sha256"}),e.objectStoreNames.contains(ce)||e.createObjectStore(ce,{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(ae);if(await de(s.objectStore(ae).get(e)))return;const r=this.writeTx(ae);r.objectStore(ae).put({sha256:e,data:t}),await le(r)}async loadBytes(e){const t=this.readTx(ae),s=await de(t.objectStore(ae).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(ae);return await de(t.objectStore(ae).count(e))>0}async deleteBytes(e){const t=this.writeTx(ae);t.objectStore(ae).delete(e),await le(t)}async saveRecord(e){const t=this.writeTx(ce);t.objectStore(ce).put(e),await le(t)}async loadRecord(e){const t=this.readTx(ce);return await de(t.objectStore(ce).get(e))??null}async deleteRecord(e){const t=this.writeTx(ce);t.objectStore(ce).delete(e),await le(t)}async listRecords(){return de(this.readTx(ce).objectStore(ce).getAll())}async exportAllBytes(){const e=this.readTx(ae);return(await de(e.objectStore(ae).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,r)=>{const n=this.getDB().transaction([ae,ce],"readwrite"),i=n.objectStore(ae),o=n.objectStore(ce),a=i.count(e.sha256);a.onsuccess=()=>{0===a.result&&i.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>r(a.error),n.oncomplete=()=>s(),n.onerror=()=>r(n.error),n.onabort=()=>r(new Error("registerBlob transaction aborted"))}))}},exports.JaccardContextRetriever=class{constructor(e){this.contextRegistry=e}rank(e){const{entries:t,recentMessages:s,config:r={}}=e,n=r.minScore??0,i=r.freshnessHalfLifeDays??30,o=r.recentMessageWindow??3;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,i)-this.freshnessWeight(e.timestamp,i)));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,i)}})).filter((e=>e.score>n)).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 r of e)t.has(r)&&s++;const r=e.size+t.size-s;return 0===r?0:s/r}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},exports.LRUCache=Y,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=j,exports.Session=H,exports.SessionManager=G,exports.TurnBuilder=K,exports.TurnTree=L,exports.WorkspaceApi=J,exports.WorkspaceManager=x,exports.WorkspaceRegistry=class{constructor(e){this.db=e}async list(){const e=u(this.db);await e.open();const t=await e.collection(p.WORKSPACE);return new V(t,new Y(100)).list()}async delete(e){const t=u(this.db);await t.open();const s=await t.collection(p.WORKSPACE);return new V(s,new Y(1)).delete(e)}async purge(){this.db.clear()}},exports.bufferToBase64=k,exports.computeSHA256=w,exports.createDefaultAssembler=function(e,t){return new j(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=ne,exports.createWorkspace=async function(t){const{blobStorage:s,eventBus:n=e.createEventBus(),getWorkspace:i,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:l=[],extensions:h=[]}=t,m=u(t.db),f=[...h.flatMap((e=>e.schemas??[]))],y={...h.reduce(((e,t)=>({...e,...t.reducers})),{})},g=[...h.flatMap((e=>e.middleware??[]))],w=[...h.flatMap((e=>e.indexers??[]))],k=h.flatMap((e=>e.blocks??[]));await m.open(f);const b={workspace:await m.collection(p.WORKSPACE),role:await m.collection(p.ROLE),preference:await m.collection(p.PREFERENCE),context:await m.collection(p.CONTEXT),session:await m.collection(p.SESSION),topic:await m.collection(p.TOPIC),turn:await m.collection(p.TURN),artifact:await m.collection(p.ARTIFACT)},v=new X(s,new Y(200),n),O=new P,_={workspaceStore:new V(b.workspace,new Y(1)),roles:new te(b.role,new Y(100)),preferences:new ee(b.preference,new Y(500)),context:new Q(b.context,new Y(500),O),artifacts:new Z(b.artifact,new Y(100)),topics:new S(b.topic,new Y(100)),sessions:new se(b.session,new Y(50)),turns:new re(b.turn,new Y(50)),blobs:v,tools:d,db:m,indexers:[...r,...w]};await Promise.all(h.map((async e=>{if(e.stores){const t=await e.stores(_);Object.assign(_,t)}})));const T=new x({ctx:_,getWorkspace:i,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=i();await _.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:n});Object.entries(q).forEach((([e,t])=>{T.register(e,t)})),Object.entries(y).forEach((([e,t])=>{T.register(e,t)})),T.use(R),T.use(A),g.forEach((e=>{T.use(e)}));const N=new G(T,a),D=new z;k.forEach((e=>D.register(e))),h.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(O.register(e),e.store){const t=e.store(_);_.context.registerDelegate(e.kind,t)}}))}));const I=new C(l),E=_.blobs.resolve.bind(_.blobs),B={assembler:new j(D,E),processor:a,blobResolver:E,blockRegistry:D,contextRegistry:O,models:I},U=async e=>{await T.dispatch({type:"workspace:sync",payload:void 0,timestamp:(new Date).toISOString()});let t=i();await T.dispatch({type:"workspace:create",payload:e.workspace,timestamp:(new Date).toISOString()}),t=i();const s=[];if(e.roles)for(const r of e.roles)t.index.roles[r.name]||(await T.dispatch({type:"role:add",payload:r,timestamp:(new Date).toISOString()}),s.push(r.name));return e.workspace.settings.defaultRole&&t.settings.defaultRole!==e.workspace.settings.defaultRole&&await T.dispatch({type:"workspace:sync",payload:{settings:{...t.settings,defaultRole:e.workspace.settings.defaultRole}},timestamp:(new Date).toISOString()}),{workspace:i(),roles:s}};if(t.bootstrap){const e=i();if(!e||!e.index){const e=ne({id:t.bootstrap.workspace.id,settings:t.bootstrap.workspace.settings,project:t.bootstrap.workspace.project});await o(e)}await U(t.bootstrap)}return{manager:T,sessions:N,ctx:_,services:B,bootstrap:U}},exports.createWorkspaceDatabase=u,exports.del=function(){return h},exports.error=y,exports.getExtension=function(e,t){return e.extensions[t]},exports.merge=g,exports.omitNullUndefined=function(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))},exports.sessionStateToMarkdown=v,exports.shortHash=b,exports.success=f;
|
|
1
|
+
"use strict";var e=require("@asaidimu/utils-events"),t=require("uuid"),s=require("diff"),r=Object.defineProperty,n=[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 r of t)s[r.name]=e.roles.summarize(r);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const r of t)s[r.id]=e.preferences.summarize(r);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const r of t)s[r.key]=e.context.summarize(r);return{index:{context:s}}},async e=>{const t=await e.artifacts.list(),s={};for(const r of t)s[r.key]=e.artifacts.summarize(r);return{index:{artifacts:s}}},async e=>{const t=await e.sessions.list(),s={};for(const r of t)s[r.id]=e.sessions.summarize(r);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const r of t)s[r.name]=e.topics.summarize(r);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],i=[{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:[]}],o=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},a=class extends o{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},c=class extends o{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},d=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 r;await Promise.race([s.then((()=>clearTimeout(r))),new Promise(((s,n)=>{r=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),n(new a("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}},l=class{mutex=new d({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 r;return Promise.race([e.then((e=>(clearTimeout(r),e))),new Promise(((e,n)=>{r=setTimeout((()=>n(new a(s))),t)}))])}},u=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new d({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new c};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,r=null;try{if(this._done)throw new c;r=await e(),this._lastValue=r,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:r,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 p(e){const t=new l({retry:!0,throws:!0}),s=new l({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...i,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var h={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic",ARTIFACT:"artifact"},m=Symbol.for("delete"),f=e=>Array.isArray(e)?[...e]:{...e};function y(e){return{ok:!0,value:e}}function g(e){return{ok:!1,error:e}}var w=function(e){const t=e?.deleteMarker||m;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 r={};for(const[n,i]of Object.entries(e))if(i!==t)if("object"==typeof i&&null!==i){const e=s(i);void 0!==e&&(r[n]=e)}else r[n]=i;return r}return e===t?void 0:e}return function(e,r){if("object"!=typeof e||null===e)return"object"==typeof r&&null!==r?s(r):r===t?{}:r;if("object"!=typeof r||null===r)return e;const n=f(e),i=[{target:n,source:r}];for(;i.length>0;){const{target:e,source:s}=i.pop();for(const r of Object.keys(s)){const n=s[r];if(n!==t)if(Array.isArray(n))e[r]=n;else if("object"==typeof n&&null!==n){const t=r in e&&"object"==typeof e[r]&&null!==e[r]?e[r]:{};e[r]=f(t),i.push({target:e[r],source:n})}else e[r]=n;else delete e[r]}}return n}}({deleteMarker:m});async function k(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 b(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let s=0;s<e.length;s+=32768){const r=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(r)))}return btoa(t.join(""))}function v(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 x(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 S=class{registry=new Map;middlewares=[];serializer=new u;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 g(t.error)}const t=this.registry.get(e.type);if(!t)return g({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),r=await t({workspace:s,...this._ctx},e.payload);if(!r.ok)return r;let n=r.value;for(const t of this.middlewares){const r=await t({workspace:s,command:e,patch:n,...this._ctx});n=w(n,r)}return await this.updateWorkspace(n),this.bus.emit({name:"workspace:changed",payload:n}),"workspace:sync"===e.type&&this.bus.emit({name:"workspace:synced",payload:void 0}),y(n)}));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}}},_=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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 r of e){const e=this.cache.get(r);e?t.push(e):s.push(r)}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 O(e,t,s,r,n,i){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==n||!i)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},i.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[r],d=c.includes(s);if("add"!==n||d){if("remove"===n&&d){const e=Math.max(0,(t.metadata.entries||0)-1);o[a]={...t,[r]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[r]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function T(e,t,s,r){return O(e,t,s,"contextKeys","add",r)}function N(e,t,s){return O(e,t,s,"contextKeys","remove")}function D(e,t,s,r){return O(e,t,s,"preferences","add",r)}function R(e,t,s){return O(e,t,s,"preferences","remove")}var A=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,r=t.index.topics;let n={};const i=e=>{const t=e?.index?.topics;t&&(n=w(n,t))};if(s.index?.context)for(const[n,o]of Object.entries(s.index.context)){const s=t.index.context[n];if(void 0===o&&s)i(N(r,s.topics,s.key));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(N(r,c,s.key)),a.length&&i(T(r,a,s.key,e.topics))}}else i(T(r,o.topics??[],o.key,e.topics))}if(s.index?.preferences)for(const[n,o]of Object.entries(s.index.preferences)){const s=t.index.preferences[n];if(void 0===o&&s)i(R(r,s.topics,s.id));else if(s||!o){if(s&&o){const t=s.topics??[],n=o.topics??t,a=n.filter((e=>!t.includes(e))),c=t.filter((e=>!n.includes(e)));c.length&&i(R(r,c,s.id)),a.length&&i(D(r,a,s.id,e.topics))}}else i(D(r,o.topics??[],o.id,e.topics))}return Object.keys(n).length?{index:{topics:n}}:{}},I=async e=>{const{command:t,workspace:s}=e;if("artifact:add"!==t.type)return{};const{sessionId:r,key:n}=t.payload,i=s.index.sessions[r];if(!i)return console.warn(`[sessionArtifactMiddleware] Session ${r} not found in index`),{};const o=i.artifacts||[];if(o.includes(n))return{};const a=[...o,n];return await e.sessions.update(r,{artifacts:a}),{index:{sessions:{[r]:{artifacts:a}}}}},j="\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 E(e){if(!e||0===e.length)return"";return`# Artifacts\n\n${e.map((e=>{const{extension:t,value:s}=e.content,r=`\`\`\`${t||""}\n${s.trim()}\n\`\`\``;return`[${e.key}] (v${e.version}, ${e.status})\nDescription: ${e.description}\n${r}`})).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 C=class{constructor(e,t){this.resolver=t,this.registry=e}registry;async build(e,t,s,r=[]){const n=this.buildSections(t,r);return{system:this.join(n),sections:n,transcript:await Promise.all(t.transcript.map((async t=>{const r=[];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 n=t.mappings?.[e];if(!n){console.log({definition:t}),console.warn(`[PromptAssembler] build: no active mapping for block type "${s.type}" — skipping.`);continue}const i=await Promise.resolve(n.to({block:s,resolve:t=>this.resolver(t,e)}));null!=i&&r.push(i)}return s({turn:t,parts:r})})))}}buildSections(e,t=[]){const s=[...e.system.extensions||[],...t],r=[];var n,i,o;r.push({label:"operating-system",content:j}),r.push({label:"block-architecture",content:this.registry.description()}),e.role.persona&&r.push({label:"persona",content:(n=e.role.persona,`# Persona\n${n}`)}),e.system.preferences.length>0&&r.push({label:"preferences",content:(i=e.system.preferences,`# User Preferences\n${i.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&r.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&&r.push({label:"artifacts",content:E(e.system.artifacts),metadata:{count:e.system.artifacts.length}}),e.system.instructions&&r.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const a=[...r],c=[];for(const e of s){const{position:t,...s}=e,r=q(t);if("prepend"===r.placement){c.push(s);continue}if("append"===r.placement){a.push(s);continue}const n=a.findIndex((e=>e.label===r.label));if(-1===n){console.warn(`[SystemPromptAssembler] Anchor target "${r.label}" not found in sections. Extension "${e.label}" will be appended.`),a.push(s);continue}const i="before"===r.placement?n:n+1;a.splice(i,0,s)}return[...c,...a]}parse(e,t){const s=[];for(const r of t){const t=this.registry.parse(r,e);t&&s.push(t)}return s}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};var B={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:r,settings:n,project:i}=t,o=await s.get(r);return o?y({id:o.id,settings:o.settings,project:o.project}):(await s.add({id:r,settings:n,project:i}),y({id:r,settings:n,project:i,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 r=await t(e);s=w(s,r)}return t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=w(s.settings||{},t.settings)),t.project&&(s.project=w(s.project||{},t.project))),y(s)},"role:add":async function(e,t){const{workspace:s,roles:r}=e,n=t;return s.index.roles[n.name]?g({code:"DUPLICATE_KEY",resource:"Role",key:n.name}):(await r.add(n),y({index:{roles:{[n.name]:r.summarize(n)}}}))},"role:update":async function(e,t){const{workspace:s,roles:r}=e,{name:n,...i}=t;if(!s.index.roles[n])return g({code:"NOT_FOUND",resource:"Role",id:n});const o=await r.update(n,i);return o?y({index:{roles:{[n]:r.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update role ${n} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:r}=e,{name:n}=t;return s.index.roles[n]?await r.delete(n)?y({index:{roles:{[n]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete role ${n} from store.`}):g({code:"NOT_FOUND",resource:"Role",id:n})},"preference:add":async function(e,t){const{workspace:s,preferences:r}=e,n=t;return s.index.preferences[n.id]?g({code:"DUPLICATE_KEY",resource:"Preference",key:n.id}):(await r.add(n),y({index:{preferences:{[n.id]:r.summarize(n)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:r}=e,{id:n,...i}=t;if(!s.index.preferences[n])return g({code:"NOT_FOUND",resource:"Preference",id:n});const o=await r.update(n,i);return o?y({index:{preferences:{[n]:r.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update preference ${n} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:r}=e,{id:n}=t;return s.index.preferences[n]?await r.delete(n)?y({index:{preferences:{[n]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete preference ${n} from store.`}):g({code:"NOT_FOUND",resource:"Preference",id:n})},"context:add":async function(e,t){const{workspace:s,context:r}=e,n=t;return s.index.context[n.key]?g({code:"DUPLICATE_KEY",resource:"Context",key:n.key}):(await r.add(n),y({index:{context:{[n.key]:r.summarize(n)}}}))},"context:update":async function(e,t){const{workspace:s,context:r}=e,{key:n,...i}=t,o=s.index.context[n];if(!o)return g({code:"NOT_FOUND",resource:"Context",id:n});const a=await r.update(n,i,o.kind);return a?y({index:{context:{[n]:r.summarize(a)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update context ${n} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:r}=e,{key:n}=t,i=s.index.context[n];return i?await r.delete(n,i.kind)?y({index:{context:{[n]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete context ${n} from store.`}):g({code:"NOT_FOUND",resource:"Context",id:n})},"artifact:add":async function(e,s){const{workspace:r,artifacts:n}=e,{sessionId:i,...o}=s;if(r.index.artifacts[o.key])return g({code:"DUPLICATE_KEY",resource:"Artifact",key:o.key});const a={...o,type:"artifact",id:t.v7()};return await n.add(a),y({index:{artifacts:{[o.key]:n.summarize(o)}}})},"artifact:update":async function(e,t){const{workspace:r,artifacts:n}=e,{sessionId:i,...o}=t,a=o.key;if(!r.index.artifacts[a])return g({code:"NOT_FOUND",resource:"Artifact",id:a});const c=await n.get(a);if(!c)return g({code:"NOT_FOUND",resource:"Artifact",id:a});let d=c.content;if(o.content)d=o.content;else if(o.patch&&"unified-diff"===o.patch.format){const e=s.applyPatch(c.content.value,o.patch.value);if(!e)return g({code:"BACKEND_ERROR",reason:"Failed to apply patch"});d.value=e}const l={...c,content:d,status:o.status,version:c.version+1,updated:(new Date).toISOString()};return await n.update(a,l),y({index:{artifacts:{[a]:n.summarize(l)}}})},"artifact:delete":async function(e,t){const{workspace:s,artifacts:r}=e,{key:n}=t;return s.index.artifacts[n]?await r.delete(n)?y({index:{artifacts:{[n]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete artifact ${n} from store.`}):g({code:"NOT_FOUND",resource:"Artifact",id:n})},"topic:add":async function(e,t){const{workspace:s,topics:r}=e,n=t;return s.index.topics[n.name]?g({code:"DUPLICATE_KEY",resource:"Topic",key:n.name}):(await r.add(n),y({index:{topics:{[n.name]:r.summarize(n)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:r}=e,{name:n,...i}=t;if(!s.index.topics[n])return g({code:"NOT_FOUND",resource:"Topic",id:n});const o=await r.update(n,i);return o?y({index:{topics:{[n]:{metadata:{updated:o.updated}}}}}):g({code:"BACKEND_ERROR",reason:`Failed to update topic ${n} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return g({code:"NOT_FOUND",resource:"Topic",id:o});if(r.referencedBy(o,s.index)&&!a)return g({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 n.get(e);t&&await n.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 i.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await r.delete(o)?y({index:{topics:{[o]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:r,roles:n,sessions:i}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return g({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 n.get(e);if(t){const s=t.topics.filter((e=>e!==o));s.includes(a)||s.push(a),await n.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 i.update(e,{topics:s})}}return await r.delete(o),y({index:{topics:{[o]:m}}})},"session:create":async function(e,t){const{workspace:s,sessions:r}=e,n=t;return s.index.sessions[n.id]?g({code:"DUPLICATE_KEY",resource:"Session",key:n.id}):(await r.add(n),y({index:{sessions:{[n.id]:r.summarize(n)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,...i}=t;if(!s.index.sessions[n])return g({code:"NOT_FOUND",resource:"Session",id:n});const o=await r.update(n,i);return o?y({index:{sessions:{[n]:r.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update session ${n} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,newSessionId:i,label:o}=t,a=s.index.sessions[n];if(!a)return g({code:"NOT_FOUND",resource:"Session",id:n});const c={...a,id:i,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await r.add(c),y({index:{sessions:{[i]:r.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n}=t;return s.index.sessions[n]?(await r.delete(n),y({index:{sessions:{[n]:m}}})):g({code:"NOT_FOUND",resource:"Session",id:n})},"session:role:switch":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,roleName:i}=t;return s.index.sessions[n]?(await r.update(n,{role:i}),y({index:{sessions:{[n]:{role:i}}}})):g({code:"NOT_FOUND",resource:"Session",id:n})},"session:topics:add":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,topics:i}=t,o=s.index.sessions[n];if(!o)return g({code:"NOT_FOUND",resource:"Session",id:n});const a=Array.from(new Set([...o.topics,...i]));return await r.update(n,{topics:a}),y({index:{sessions:{[n]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:r}=e,{sessionId:n,preferences:i}=t;return s.index.sessions[n]?(await r.update(n,{preferences:i}),y({index:{sessions:{[n]:{preferences:i}}}})):g({code:"NOT_FOUND",resource:"Session",id:n})},"turn:add":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return g({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,turns:r}=e,{sessionId:n,turn:i}=t;if(!s.index.sessions[n])return g({code:"NOT_FOUND",resource:"Session",id:n});const{id:o,session:a,version:c,...d}=i;return await r.update({id:o,session:a,version:c},d),y({})},"turn:edit":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d,modelSnapshot:l}=t,u=s.index.sessions[i];if(!u)return g({code:"NOT_FOUND",resource:"Session",id:i});let p={};const h=await n.get({id:o,version:c-1,session:i});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:i};if(await n.add(m),u.head?.id===o){const e={id:o,version:c};return await r.update(i,{head:e}),y({index:{sessions:{[i]:{head:e}}}})}return y({})},"turn:branch":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return g({code:"NOT_FOUND",resource:"Session",id:i});await n.add(o);const a={id:o.id,version:o.version};return await r.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:r,turns:n}=e,{sessionId:i,turnId:o,newHead:a}=t;return s.index.sessions[i]?(await n.delete({session:i,id:o,version:t.version}),a?(await r.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})):y({})):g({code:"NOT_FOUND",resource:"Session",id:i})},"blob:register":async function(e,t){const{blobs:s}=e,r=await s.register(t.data,t.mediaType,t.filename);if(!r.ok)return r;const n=await s.getRecord(r.value.sha256);return n?y({index:{blobs:{[n.sha256]:n}}}):g({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${r.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,r=await s.retain(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return y({index:{blobs:{[t.sha256]:n}}})},"blob:release":async function(e,t){const{blobs:s}=e,r=await s.release(t.sha256);if(!r.ok)return r;const n=await s.getRecord(t.sha256);return y({index:{blobs:{[t.sha256]:n||m}}})},"blob:purge":async function(e,t){const{blobs:s}=e,r=await s.purge(t.sha256);return r.ok?y({index:{blobs:{[t.sha256]:m}}}):r},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:r,providerId:n,fileId:i,timestamp:o}=t,a=await s.recordRemoteId(r,n,i,o);if(!a.ok)return a;const c=await s.getRecord(r);return y({index:{blobs:{[r]:c}}})},"tool:call":async function(e,t){return y({})}},U=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)}},$={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"]}},M={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"]}},F=[$,{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"]}},M,{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.","","### 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:["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"]},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"]}},{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.","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: <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");'," ```","","Updates can be applied either as a full content replacement or as a targeted patch."].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 changes are minor and localized.","Use `patch` with `format: 'unified-diff'` for targeted edits to large artifacts, ensuring diffs apply cleanly.","Set `status` to `draft` if the artifact requires further iteration, or `complete` if it is finalized.","Do not manually pass `created`, `updated`, or version numbers; the system manages these fields automatically.","Multiple independent artifact updates may be emitted in a single turn.","Prefer updating an existing artifact over creating a new one when maintaining 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 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:["unified-diff"],description:"The patch format. Currently only `unified-diff` is supported."},value:{type:"string",description:"The patch payload. For `unified-diff`, a valid unified diff string applicable to the current artifact content."}},required:["format","value"]}},required:["type","key","status"],oneOf:[{required:["content"]},{required:["patch"]}]}}];function z(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 P=class{store=new Map;constructor(){for(const e of F)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:z(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:","",z(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=z(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 r=this.store.get(e.type);if(!r)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&r.mappings?.[s])return r.mappings[s].from(e);const{id:n,...i}=e;return{id:t.v7(),...i}}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()}}},W=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:r,filename:n}=e.content,i={sha256:t,mediaType:s,sizeBytes:r,filename:n};return s.startsWith("image/")?{id:e.key,type:"image",ref:i}:{id:e.key,type:"document",ref:i,title:n}},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())}},K="__system__",L=class{constructor(e,s,r){this._actor=e,this._turn=r?JSON.parse(JSON.stringify(r)):{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 r={id:t.v7(),type:"image",ref:e,altText:s};return this._turn.blocks.push(r),this}addDocument(e,s){const r={id:t.v7(),type:"document",ref:e,title:s};return this._turn.blocks.push(r),this}addToolUse(e,s){const r={id:t.v7(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(r),this}addToolResult(e,s,r){const n={id:t.v7(),type:"tool:result",useId:e,content:s,isError:r};return this._turn.blocks.push(n),this}addSummary(e){const s={id:t.v7(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const r={id:t.v7(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(r),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 r=this._turn.blocks[s];if("text"!==r.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...r,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))}},V=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}},Y=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s,r){const[n,i]=await Promise.all([s.loadAllTurns(t),void 0!==r?Promise.resolve(r):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 r=new Set;let n=t;for(;n;){const e=`${n.id}:${n.version}`;if(r.has(e))break;r.add(e);const t=s.get(e);if(!t)break;n=t.parent}return r}(e,t),r={},n={};for(const t of e){r[t.id]||(r[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:{}},n[t.id]=new Set);const e=r[t.id];e.versions[t.version]=t;const i=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(i&&(!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(n[t.parent.id]||(n[t.parent.id]=new Set),!n[t.parent.id].has(e+":"+t.id)){n[t.parent.id].add(e+":"+t.id),r[t.parent.id]||(r[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=r[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return r}(n,i);return new e(o,i)}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 r=s.children[t.parent.version];return r?r.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)),r=s.indexOf(t.activeVersion);return{versions:s,currentIndex:r,total:s.length,hasPrev:r>0,hasNext:r<s.length-1}}graph(){return{...this.nodes}}};var J=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}},H=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()}},G=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,r,n=[]){if(this.workspace.index.roles[e])return g({code:"DUPLICATE_KEY",resource:"role",key:e});const i={name:e,label:t,description:r,persona:s,preferences:n,topics:[]};return this.manager.dispatch({type:"role:add",payload:i,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()}):g({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return g({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?g({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,r){const n={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:r};return this.manager.dispatch({type:"context:add",payload:n,timestamp:n.timestamp})}context(){return this.manager.ctx().context.list()}async registerBlob(e,t,s){const r=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!r.ok)return g(r.error);const n=r.value,i=n?.index?.blobs;if(!i)return g({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(i)[0];if(!o)return g({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=i[o];if(!a)return g({code:"BACKEND_ERROR",reason:"Blob record missing"});return y({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},X=class e{constructor(e,t,s,r){this._id=e,this.manager=t,this.processor=s,this.turnRepository=r,this.workspace=new G(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,r){s.ctx().workspace;const n=new V(s.ctx().turns,s.ctx().sessions),i=new e(t,s,r,n);return await i.sync(),i}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()}):g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async setModel(e){return this.meta()?this.updateMetadata({model:e}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async updateMetadata(e){const t=this.meta();if(!t)return g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async addContext(e){const t=this.meta();if(!t)return g({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 g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async fork(e,t,s,r){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:r},timestamp:(new Date).toISOString()}):g({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 g({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==K&&!t.index.roles[e])return g({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 g({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},r=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:s},timestamp:s.timestamp});if(r.ok){const e={id:s.id,version:s.version};await this.refreshTurnTree(e)}return r}async recordUserTurn(e){return this.meta()?this.addTurn(e):g({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return g({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return g({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.processor.process(e,this._id);let n={};const i=[];let o;for(const e of r){const t=await this.manager.dispatch(e);if(t.ok)n=w(n,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic){o=t.error;break}{const t=this.describeCommand(e);i.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(n=w(n,a.value),t&&i.length>0){const e=this.buildDenialTurn(i),t=await this.addTurn(e);t.ok&&(n=w(n,t.value))}return o?g(o):y(n)}buildDenialTurn(e){const t=new L("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,r){if(!this.meta())return g({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph()[e];if(!n)return g({code:"NOT_FOUND",resource:"turn",id:e});const i=n.versions[n.activeVersion],o=Object.keys(n.versions).length,a=await this.dispatch({type:"turn:edit",payload:{sessionId:this._id,turnId:e,newBlocks:t,roleSnapshot:s??i.role,modelSnapshot:r??i.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 g({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return g({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 g({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph();if(!r[e]?.versions[t])return g({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const n=await this.dispatch({type:"turn:delete",payload:{sessionId:this._id,turnId:e,version:t,newHead:s},timestamp:(new Date).toISOString()});return n.ok&&await this.refreshTurnTree(s),n}async updateTurnStatus(e,t,s){const r=this.tree.graph()[e];if(!r)return g({code:"NOT_FOUND",resource:"turn",id:e});const n=r.versions[t];if(!n)return g({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const i={...n,metadata:{...n.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:i},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 g({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return g({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return g({code:"NOT_FOUND",resource:"turn",id:e});const r=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),n=r.indexOf(s.activeVersion);if(-1===n)return g({code:"INVALID_COMMAND",reason:"Active version not found"});const i=n+t;if(i<0||i>=r.length)return g({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=r[i],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 r=t.ws(),n=t._role;if(!n)return;const i=await t.manager.ctx().context.getByTopics(r.index,s.topics),o=s.context?await Promise.all(s.context.map((e=>t.manager.ctx().context.get(e)))):[],a=Array.from(new Map([...i,...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([...n.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:n,preferences:l,context:a,artifacts:c,model:s.metadata?.model,transcript:u,topics:s.topics,instructions:r.settings?.prompt,constraints:{role:n.constraints,session:s.constraints,turn:p?.constraints}}}async refreshTurnTree(e){this.tree=await Y.build(this._id,this.turnRepository,e)}findSubtreeTip(e,t,s){let r=t,n=s;for(;;){const t=e[r];if(!t)break;const s=t.children[n];if(!s||0===s.length)break;const i=s[0],o=e[i];if(!o)break;r=i,n=o.activeVersion}return{id:r,version:n}}},Q=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 l,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 X.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(),r=e.metadata??{},n=await this.manager.dispatch({type:"session:create",payload:{id:s,label:e.label,role:e.role,topics:e.topics,preferences:e.preferences??[],metadata:{...r,created:(new Date).toISOString()}},timestamp:(new Date).toISOString()});if(n.ok)return this.open(s);throw n.error}list(){return Object.values(this.manager.workspace().index.sessions)}metadata(e){return this.manager.workspace().index.sessions[e]}},Z=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const r=await k(e),n=await this.getRecord(r);if(n){const e={...n,refCount:n.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(r,e),y(this.reference(e))}const i={sha256:r,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(i,e):(await this.storage.storeBytes(r,e),await this.storage.saveRecord(i)),this.cache.set(r,i),this.bus.emit({name:"blobs:changed",payload:{sha256:r,record:i}}),y(this.reference(i))}async retain(e){const t=await this.getRecord(e);if(!t)return g({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),y(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return g({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),r={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(r),this.cache.set(e,r),y(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}}),y(void 0)}async recordRemoteId(e,t,s,r){const n=await this.getRecord(e);if(!n)return g({code:"NOT_FOUND",resource:"blob",id:e});const i={...n,remoteIds:{...n.remoteIds,[t]:{id:s,timestamp:r||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:i}}),y(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 y(null);if(t){const e=s.remoteIds[t];if(e)return y({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const r=await this.storage.loadBytes(s.sha256);return y(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}const r=await this.storage.loadBytes(s.sha256);return y(r?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:r}:null)}async resolveMany(e,t){const s=new Map;for(const r of e){const e=await this.resolve(r,t);if(!e.ok)return g(e.error);if(null===e.value)return g({code:"BLOB_ERROR",reason:`Unable to resolve blob ${r.sha256}${t?` with adapter ${t}`:""}`});s.set(r.sha256,e.value)}return y(s)}},ee=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 r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;const n=r.state();return this.cache.set(e,n),n}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 r=this.delegates.get(s);if(r){const s=await r.update(e,t);return s&&this.cache.set(e,s),s}}const r=await this.collection.find({field:"key",operator:"eq",value:e});if(!r)return null;await r.update(t);const n=r.state();return this.cache.set(e,n),n}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 r=await s.delete();return r&&this.cache.delete(e),r}async getByTopics(e,t){const s=new Map;for(const r of t){const t=e.topics[r];t&&t.contextKeys.forEach((t=>{const r=e.context[t],n=r?.kind||"unknown";s.has(n)||s.set(n,new Set),s.get(n).add(t)}))}if(0===s.size)return[];const r=[],n=[];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&&r.push(t)}else t.forEach((e=>n.push(e)))}if(n.length>0){const e=[];for(const t of n){const s=this.cache.get(t);s?r.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),r.push(t)}}}return r.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}}},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:"key",operator:"eq",value:e});if(!s)return null;const r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}}},se=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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 r of e){const e=this.cache.get(r);e?s.push(e):t.push(r)}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)}}},re=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}}},ne=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 r=s.state();return this.cache.set(e,r),r}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 r=s.state();return this.cache.set(e,r),r}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}},ie=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},r=!0){const n=this.key({id:e,session:t,version:s});this.cache.get(n)&&this.cache.get(n);const i=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 i?(r&&this.cache.set(n,i),i):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}},oe=(e={})=>({id:e.id??t.v7(),settings:w({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:w({id:t.v7(),name:"Unnamed Project"},e.project),index:w({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}},e.index)});function ae(){return(new Date).toISOString()}function ce(e,t,s){const r=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(s??{})]),n={};for(const i of r){const r=e?.[i]??{},o=t?.[i]??{},a=s?.[i]??{};n[i]={temperature:a.temperature??o.temperature??r.temperature,tokens:{max:a.tokens?.max??o.tokens?.max??r.tokens?.max,stops:a.tokens?.stops??o.tokens?.stops??r.tokens?.stops,thought:a.tokens?.thought??o.tokens?.thought??r.tokens?.thought}}}return n}var de="blob_bytes",le="blob_records";function ue(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function pe(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var he={};function me(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 s in t)r(e,s,{get:t[s],enumerable:!0})})(he,{GOOGLE_MODELS:()=>ye,GoogleGenAIAdapter:()=>ke,extractModelResponse:()=>ge,mappings:()=>fe});var fe={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:x(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 r=await t(s);if(!r.ok||!r.value)return null;const{value:n}=r;return"remote"===n.kind?{fileData:{fileUri:n.fileId,mimeType:n.mediaType}}:{inlineData:{data:b(n.data),mimeType:n.mediaType}}},from:e=>e},document:{to:async({resolve:e,block:t})=>{const s=t.ref;if(!s)return null;const r=await e(s);if(!r.ok||!r.value)return null;const{value:n}=r;return"remote"===n.kind?{fileData:{fileUri:n.fileId,mimeType:n.mediaType}}:{inlineData:{data:b(n.data),mimeType:n.mediaType}}},from:e=>e}},ye=[{provider:"google",name:"gemini-3.1-pro-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-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:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"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",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",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-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-preview",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-preview",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-preview",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",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",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}]}];function ge(e){const s=e.candidates?.[0],r=[];if(!s?.content?.parts)return{ok:!1,thinking:r,error:{code:"BACKEND_ERROR",reason:"No valid content parts in response"}};let n;for(const e of s.content.parts)if(e.thought)r.push((i=e.text??"",{id:t.v7(),type:"thinking",thinking:i}));else if(e.text){n=e;break}var i;if(!n)return r.length>0?{ok:!0,thinking:r,rawBlocks:[]}:{ok:!1,thinking:r,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)?y(t.blocks):g({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return g({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(n.text);return o.ok?{ok:!0,thinking:r,rawBlocks:o.value}:{ok:!0,thinking:r,fallback:n.text}}function we(e){return Math.ceil(e.length/4)}var ke=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const r=this._models.get(s.model);if(!r)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=r,this.registerMappings()}model;_models;registerMappings(){const{assembler:t}=this.services;for(const[s,r]of Object.entries(fe))t.registry.update(s,{mappings:{[e.provider()]:r}})}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:r}=s,{assembler:n,blockRegistry:i}=this.services,o=r.model&&this._models.get(r.model)||this.model,{system:a,sections:c,transcript:d}=await n.build(e.provider(),r,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t}))),l={role:"system",parts:[{text:a}]},u=r.constraints[o.name]??{tokens:{}},p=i.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=we(a),w=we(m),k=f+w,b=this;return{model:o.name,role:r.role.name,instructions:c,transcript:r.transcript,context:r.system.context,artifacts:r.system.artifacts,preferences:r.system.preferences,constraints:u,tokens:{breakdown:{system:f,transcript:w},total:k,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-k},async execute(){let s;try{s=await b.client.models.generateContent(h)}catch(e){return g({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const n=ge(s);if(!n.ok)return g(n.error);let i;var a;i="fallback"in n?[...n.thinking,(a=n.fallback,{id:t.v7(),type:"text",text:me(a)})]:[...n.thinking,...b.services.assembler.parse(e.provider(),n.rawBlocks)];const c=new L("assistant",r.session);c.withModel(o.name),c.withRole(r.role.name);for(const e of i)c.addBlock(e);return y({turn:c.build(),effects:[]})},async*executeStream(){let e;try{e=await b.client.models.generateContentStream(h)}catch(e){const s=e instanceof Error?e.message:String(e),n=new L("assistant",r.session);return n.addBlock({id:t.v7(),type:"text",text:`[Stream error: ${s}]`}),void(yield{turn:n.build(),effects:[]})}const s=[];for await(const r of e){const e=r.candidates?.[0];if(e?.content?.parts)for(const r of e.content.parts)r.thought||r.text&&(s.push(r.text),yield{blocks:[{id:t.v7(),type:"text",text:r.text}]})}const n=s.join(""),i=new L("assistant",r.session);i.addBlock({id:t.v7(),type:"text",text:n}),yield{turn:i.build(),effects:[]}}}}static provider(){return"google"}static models(){return ye}};exports.COLLECTIONS=h,exports.CoreTurnProcessor=class{process(e,t){const s=[],r=(new Date).toISOString();for(const n of e.blocks)"artifact"===n.type?s.push(this.handleAddArtifact(n,t,r)):"artifact:update"===n.type&&s.push(this.handleUpdateArtifact(n,t,r));return s}handleAddArtifact(e,s,r){const n=t.v7(),i=e.label||`Untitled Artifact ${v(n)}`,o=e.content.extension||"txt",a=i.split(" ").join("-").replace(new RegExp(`\\.${o}$`),"");return{type:"artifact:add",timestamp:r,payload:{...{id:n,label:i,type:"artifact",key:(e.key?e.key:`${a||v(i)}.${o}`).toLowerCase(),version:1,description:e.description||"",content:e.content,status:e.status||"complete",created:r,updated:r},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"]);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,r={}){const n=[],{resolved:i}=function(e){const t=[],s=new Map;for(const r of e)for(const e of r.topics){const n=s.get(e);if(!n){s.set(e,r);continue}const i=new Date(n.timestamp).getTime(),o=new Date(r.timestamp).getTime();o>i?(t.push({topic:e,kept:r.id,dropped:n.id}),s.set(e,r)):i>o&&t.push({topic:e,kept:n.id,dropped:r.id})}const r=new Map,n=new Map;for(const t of e)n.set(t.id,t.topics.length);for(const e of t)r.set(e.dropped,(r.get(e.dropped)??0)+1);const i=new Set;for(const t of e){const e=r.get(t.id)??0,s=n.get(t.id)??0;s>0&&e>=s&&i.add(t.id)}return{resolved:e.filter((e=>!i.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:r.retrieverConfig}),c=[],d=[];for(const e of a){const t=this.contextRegistry.get(e.content.kind);if(!t){n.push(`No ContextDefinition found for kind: ${e.content.kind}`);continue}const s=t.render(e),r=Array.isArray(s)?s:[s];"system"===t.target?c.push({label:`context:${e.content.kind}:${e.key}`,content:r.map((t=>"text"===t.type?t.text:`[${e.content.kind}] ${JSON.stringify(t,null,2)}`)).join("\n"),position:"after:context"}):d.push(...r)}const l=new Map;for(const t of e.artifacts)l.set(t.key,{...t});const u=e.transcript.map((e=>{const t=[];for(const s of e.blocks)if("artifact"===s.type){const r=s;l.set(r.key,{...r,version:r.version||1,created:e.timestamp,updated:e.timestamp}),t.push({type:"text",text:`[Artifact: "${r.label}" produced]`})}else if("artifact:update"===s.type){const r=s,n=l.get(r.key);if(n){const t={...n,status:r.status||n.status,version:(n.version||1)+1,updated:e.timestamp};r.content&&(t.content=r.content),l.set(r.key,t)}t.push({type:"text",text:`[Artifact: "${n?.label||r.key}" updated]`})}else this.NOISE_BLOCK_TYPES.has(s.type)||t.push(s);return{...e,blocks:t}})).filter((e=>e.blocks.length>0));let p=u;r.compress&&(p=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)}(u));const h=[];if(d.length>0){const s=p.length>0?p[0].timestamp:ae();h.push((m=e.id,f="system",g=d,w=s,{id:t.v7(),session:m,version:0,actor:f,blocks:g,timestamp:w??ae()}))}var m,f,g,w;const k=[...h,...p],b=function(e,t){const s=new Map;for(const t of e)if("blob"===t.content.kind){const{sha256:e,mediaType:r,sizeBytes:n,filename:i,previewUrl:o}=t.content;s.has(e)||s.set(e,{sha256:e,mediaType:r,sizeBytes:n,filename:i,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,k);return y({session:e.id,model:e.model,system:{persona:e.role.persona,instructions:e.instructions,preferences:i,context:[],artifacts:Array.from(l.values()),extensions:c},transcript:k,blobs:b,role:e.role,constraints:ce(e.constraints.role,e.constraints.session,e.constraints.turn),warnings:n})}},exports.EMPTY_SYSTEM_ROLE=K,exports.GoogleAdapter=he,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(de)||e.createObjectStore(de,{keyPath:"sha256"}),e.objectStoreNames.contains(le)||e.createObjectStore(le,{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(de);if(await ue(s.objectStore(de).get(e)))return;const r=this.writeTx(de);r.objectStore(de).put({sha256:e,data:t}),await pe(r)}async loadBytes(e){const t=this.readTx(de),s=await ue(t.objectStore(de).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(de);return await ue(t.objectStore(de).count(e))>0}async deleteBytes(e){const t=this.writeTx(de);t.objectStore(de).delete(e),await pe(t)}async saveRecord(e){const t=this.writeTx(le);t.objectStore(le).put(e),await pe(t)}async loadRecord(e){const t=this.readTx(le);return await ue(t.objectStore(le).get(e))??null}async deleteRecord(e){const t=this.writeTx(le);t.objectStore(le).delete(e),await pe(t)}async listRecords(){return ue(this.readTx(le).objectStore(le).getAll())}async exportAllBytes(){const e=this.readTx(de);return(await ue(e.objectStore(de).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,r)=>{const n=this.getDB().transaction([de,le],"readwrite"),i=n.objectStore(de),o=n.objectStore(le),a=i.count(e.sha256);a.onsuccess=()=>{0===a.result&&i.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>r(a.error),n.oncomplete=()=>s(),n.onerror=()=>r(n.error),n.onabort=()=>r(new Error("registerBlob transaction aborted"))}))}},exports.JaccardContextRetriever=class{constructor(e){this.contextRegistry=e}rank(e){const{entries:t,recentMessages:s,config:r={}}=e,n=r.minScore??0,i=r.freshnessHalfLifeDays??30,o=r.recentMessageWindow??3;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,i)-this.freshnessWeight(e.timestamp,i)));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,i)}})).filter((e=>e.score>n)).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 r of e)t.has(r)&&s++;const r=e.size+t.size-s;return 0===r?0:s/r}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},exports.LRUCache=H,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=C,exports.Session=X,exports.SessionManager=Q,exports.TurnBuilder=L,exports.TurnTree=Y,exports.WorkspaceApi=G,exports.WorkspaceManager=S,exports.WorkspaceRegistry=class{constructor(e){this.db=e}async list(){const e=p(this.db);await e.open();const t=await e.collection(h.WORKSPACE);return new J(t,new H(100)).list()}async delete(e){const t=p(this.db);await t.open();const s=await t.collection(h.WORKSPACE);return new J(s,new H(1)).delete(e)}async purge(){this.db.clear()}},exports.bufferToBase64=b,exports.computeSHA256=k,exports.createDefaultAssembler=function(e,t){return new C(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=oe,exports.createWorkspace=async function(t){const{blobStorage:s,eventBus:r=e.createEventBus(),getWorkspace:i,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:l=[],extensions:u=[]}=t,m=p(t.db),f=[...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??[]))],k=u.flatMap((e=>e.blocks??[]));await m.open(f);const b={workspace:await m.collection(h.WORKSPACE),role:await m.collection(h.ROLE),preference:await m.collection(h.PREFERENCE),context:await m.collection(h.CONTEXT),session:await m.collection(h.SESSION),topic:await m.collection(h.TOPIC),turn:await m.collection(h.TURN),artifact:await m.collection(h.ARTIFACT)},v=new Z(s,new H(200),r),x=new W,O={workspaceStore:new J(b.workspace,new H(1)),roles:new re(b.role,new H(100)),preferences:new se(b.preference,new H(500)),context:new ee(b.context,new H(500),x),artifacts:new te(b.artifact,new H(100)),topics:new _(b.topic,new H(100)),sessions:new ne(b.session,new H(50)),turns:new ie(b.turn,new H(50)),blobs:v,tools:d,db:m,indexers:[...n,...w]};await Promise.all(u.map((async e=>{if(e.stores){const t=await e.stores(O);Object.assign(O,t)}})));const T=new S({ctx:O,getWorkspace:i,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=i();await O.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:r});Object.entries(B).forEach((([e,t])=>{T.register(e,t)})),Object.entries(y).forEach((([e,t])=>{T.register(e,t)})),T.use(A),T.use(I),g.forEach((e=>{T.use(e)}));const N=new Q(T,a),D=new P;k.forEach((e=>D.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 R=new U(l),j=O.blobs.resolve.bind(O.blobs),E={assembler:new C(D,j),processor:a,blobResolver:j,blockRegistry:D,contextRegistry:x,models:R},q=async e=>{await T.dispatch({type:"workspace:sync",payload:void 0,timestamp:(new Date).toISOString()});let t=i();await T.dispatch({type:"workspace:create",payload:e.workspace,timestamp:(new Date).toISOString()}),t=i();const s=[];if(e.roles)for(const r of e.roles)t.index.roles[r.name]||(await T.dispatch({type:"role:add",payload:r,timestamp:(new Date).toISOString()}),s.push(r.name));return e.workspace.settings.defaultRole&&t.settings.defaultRole!==e.workspace.settings.defaultRole&&await T.dispatch({type:"workspace:sync",payload:{settings:{...t.settings,defaultRole:e.workspace.settings.defaultRole}},timestamp:(new Date).toISOString()}),{workspace:i(),roles:s}};if(t.bootstrap){const e=i();if(!e||!e.index){const e=oe({id:t.bootstrap.workspace.id,settings:t.bootstrap.workspace.settings,project:t.bootstrap.workspace.project});await o(e)}await q(t.bootstrap)}return{manager:T,sessions:N,ctx:O,services:E,bootstrap:q}},exports.createWorkspaceDatabase=p,exports.del=function(){return m},exports.error=g,exports.getExtension=function(e,t){return e.extensions[t]},exports.merge=w,exports.omitNullUndefined=function(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))},exports.sessionStateToMarkdown=x,exports.shortHash=v,exports.success=y;
|
package/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createEventBus as e}from"@asaidimu/utils-events";import{v7 as t,v4 as s}from"uuid";var n=Object.defineProperty,r=[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 n of t)s[n.name]=e.roles.summarize(n);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const n of t)s[n.id]=e.preferences.summarize(n);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const n of t)s[n.key]=e.context.summarize(n);return{index:{context:s}}},async e=>{const t=await e.artifacts.list(),s={};for(const n of t)s[n.key]=e.artifacts.summarize(n);return{index:{artifacts:s}}},async e=>{const t=await e.sessions.list(),s={};for(const n of t)s[n.id]=e.sessions.summarize(n);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const n of t)s[n.name]=e.topics.summarize(n);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],i=[{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:[]}],o=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},a=class extends o{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},c=class extends o{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},d=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 n;await Promise.race([s.then((()=>clearTimeout(n))),new Promise(((s,r)=>{n=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),r(new a("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}},l=class{mutex=new d({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 n;return Promise.race([e.then((e=>(clearTimeout(n),e))),new Promise(((e,r)=>{n=setTimeout((()=>r(new a(s))),t)}))])}},u=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new d({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new c};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,n=null;try{if(this._done)throw new c;n=await e(),this._lastValue=n,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:n,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 p(e){const t=new l({retry:!0,throws:!0}),s=new l({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...i,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var h={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic",ARTIFACT:"artifact"},m=Symbol.for("delete"),f=e=>Array.isArray(e)?[...e]:{...e};function y(e){return{ok:!0,value:e}}function g(e){return{ok:!1,error:e}}function w(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))}function k(){return m}var b=function(e){const t=e?.deleteMarker||m;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 n={};for(const[r,i]of Object.entries(e))if(i!==t)if("object"==typeof i&&null!==i){const e=s(i);void 0!==e&&(n[r]=e)}else n[r]=i;return n}return e===t?void 0:e}return function(e,n){if("object"!=typeof e||null===e)return"object"==typeof n&&null!==n?s(n):n===t?{}:n;if("object"!=typeof n||null===n)return e;const r=f(e),i=[{target:r,source:n}];for(;i.length>0;){const{target:e,source:s}=i.pop();for(const n of Object.keys(s)){const r=s[n];if(r!==t)if(Array.isArray(r))e[n]=r;else if("object"==typeof r&&null!==r){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=f(t),i.push({target:e[n],source:r})}else e[n]=r;else delete e[n]}}return r}}({deleteMarker:m});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 n=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(n)))}return btoa(t.join(""))}function _(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 O(e,t){return e.extensions[t]}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 T=class{registry=new Map;middlewares=[];serializer=new u;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 g(t.error)}const t=this.registry.get(e.type);if(!t)return g({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),n=await t({workspace:s,...this._ctx},e.payload);if(!n.ok)return n;let r=n.value;for(const t of this.middlewares){const n=await t({workspace:s,command:e,patch:r,...this._ctx});r=b(r,n)}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}),y(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}}},N=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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 n of e){const e=this.cache.get(n);e?t.push(e):s.push(n)}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 D(e,t,s,n,r,i){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==r||!i)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},i.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[n],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,[n]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[n]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function R(e,t,s,n){return D(e,t,s,"contextKeys","add",n)}function A(e,t,s){return D(e,t,s,"contextKeys","remove")}function I(e,t,s,n){return D(e,t,s,"preferences","add",n)}function j(e,t,s){return D(e,t,s,"preferences","remove")}var E=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,n=t.index.topics;let r={};const i=e=>{const t=e?.index?.topics;t&&(r=b(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)i(A(n,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&&i(A(n,c,s.key)),a.length&&i(R(n,a,s.key,e.topics))}}else i(R(n,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)i(j(n,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&&i(j(n,c,s.id)),a.length&&i(I(n,a,s.id,e.topics))}}else i(I(n,o.topics??[],o.id,e.topics))}return Object.keys(r).length?{index:{topics:r}}:{}},q=async e=>{const{command:t,workspace:s}=e;if("artifact:add"!==t.type)return{};const{sessionId:n,key:r}=t.payload,i=s.index.sessions[n];if(!i)return console.warn(`[sessionArtifactMiddleware] Session ${n} not found in index`),{};const o=i.artifacts||[];if(o.includes(r))return{};const a=[...o,r];return await e.sessions.update(n,{artifacts:a}),{index:{sessions:{[n]:{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||"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,n=[]){const r=this.buildSections(t,n);return{system:this.join(r),sections:r,transcript:await Promise.all(t.transcript.map((async t=>{const n=[];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 i=await Promise.resolve(r.to({block:s,resolve:t=>this.resolver(t,e)}));null!=i&&n.push(i)}return s({turn:t,parts:n})})))}}buildSections(e,t=[]){const s=[...e.system.extensions||[],...t],n=[];var r,i,o,a;n.push({label:"operating-system",content:C}),e.role.persona&&n.push({label:"persona",content:(r=e.role.persona,`# Persona\n${r}`)}),e.system.preferences.length>0&&n.push({label:"preferences",content:(i=e.system.preferences,`# User Preferences\n${i.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&n.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&&n.push({label:"artifacts",content:(a=e.system.artifacts,`# Artifacts\n\n${a.map((e=>`[${e.key}] (${e.label}, v${e.version}, ${e.status})\nDescription: ${e.description}\n\n${e.content.value}`)).join("\n\n")}`),metadata:{count:e.system.artifacts.length}}),e.system.instructions&&n.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const c=[...n],d=[];for(const e of s){const{position:t,...s}=e,n=U(t);if("prepend"===n.placement){d.push(s);continue}if("append"===n.placement){c.push(s);continue}const r=c.findIndex((e=>e.label===n.label));if(-1===r){console.warn(`[SystemPromptAssembler] Anchor target "${n.label}" not found in sections. Extension "${e.label}" will be appended.`),c.push(s);continue}const i="before"===n.placement?r:r+1;c.splice(i,0,s)}return[...d,...c]}parse(e,t){const s=[];for(const n of t){const t=this.registry.parse(n,e);t&&s.push(t)}return s}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};function $(e,t){return new B(e,t)}var M={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:n,settings:r,project:i}=t,o=await s.get(n);return o?y({id:o.id,settings:o.settings,project:o.project}):(await s.add({id:n,settings:r,project:i}),y({id:n,settings:r,project:i,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 n=await t(e);s=b(s,n)}return t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=b(s.settings||{},t.settings)),t.project&&(s.project=b(s.project||{},t.project))),y(s)},"role:add":async function(e,t){const{workspace:s,roles:n}=e,r=t;return s.index.roles[r.name]?g({code:"DUPLICATE_KEY",resource:"Role",key:r.name}):(await n.add(r),y({index:{roles:{[r.name]:n.summarize(r)}}}))},"role:update":async function(e,t){const{workspace:s,roles:n}=e,{name:r,...i}=t;if(!s.index.roles[r])return g({code:"NOT_FOUND",resource:"Role",id:r});const o=await n.update(r,i);return o?y({index:{roles:{[r]:n.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update role ${r} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:n}=e,{name:r}=t;return s.index.roles[r]?await n.delete(r)?y({index:{roles:{[r]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete role ${r} from store.`}):g({code:"NOT_FOUND",resource:"Role",id:r})},"preference:add":async function(e,t){const{workspace:s,preferences:n}=e,r=t;return s.index.preferences[r.id]?g({code:"DUPLICATE_KEY",resource:"Preference",key:r.id}):(await n.add(r),y({index:{preferences:{[r.id]:n.summarize(r)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:n}=e,{id:r,...i}=t;if(!s.index.preferences[r])return g({code:"NOT_FOUND",resource:"Preference",id:r});const o=await n.update(r,i);return o?y({index:{preferences:{[r]:n.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update preference ${r} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:n}=e,{id:r}=t;return s.index.preferences[r]?await n.delete(r)?y({index:{preferences:{[r]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete preference ${r} from store.`}):g({code:"NOT_FOUND",resource:"Preference",id:r})},"context:add":async function(e,t){const{workspace:s,context:n}=e,r=t;return s.index.context[r.key]?g({code:"DUPLICATE_KEY",resource:"Context",key:r.key}):(await n.add(r),y({index:{context:{[r.key]:n.summarize(r)}}}))},"context:update":async function(e,t){const{workspace:s,context:n}=e,{key:r,...i}=t,o=s.index.context[r];if(!o)return g({code:"NOT_FOUND",resource:"Context",id:r});const a=await n.update(r,i,o.kind);return a?y({index:{context:{[r]:n.summarize(a)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update context ${r} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:n}=e,{key:r}=t,i=s.index.context[r];return i?await n.delete(r,i.kind)?y({index:{context:{[r]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete context ${r} from store.`}):g({code:"NOT_FOUND",resource:"Context",id:r})},"artifact:add":async function(e,s){const{workspace:n,artifacts:r}=e,{sessionId:i,...o}=s;if(n.index.artifacts[o.key])return g({code:"DUPLICATE_KEY",resource:"Artifact",key:o.key});const a={...o,type:"artifact",id:t()};return await r.add(a),y({index:{artifacts:{[o.key]:r.summarize(o)}}})},"artifact:update":async function(e,t){const{workspace:s,artifacts:n}=e,{sessionId:r,...i}=t,o=i.key;if(!s.index.artifacts[o])return g({code:"NOT_FOUND",resource:"Artifact",id:o});const a=await n.get(o);if(!a)return g({code:"NOT_FOUND",resource:"Artifact",id:o});let c=a.content;if(i.content)c=i.content;else if(i.patch)return g({code:"INVALID_COMMAND",reason:"Patch updates for artifacts are not yet implemented."});const d={...a,content:c,status:i.status,version:a.version+1,updated:(new Date).toISOString()};return await n.update(o,d),y({index:{artifacts:{[o]:n.summarize(d)}}})},"artifact:delete":async function(e,t){const{workspace:s,artifacts:n}=e,{key:r}=t;return s.index.artifacts[r]?await n.delete(r)?y({index:{artifacts:{[r]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete artifact ${r} from store.`}):g({code:"NOT_FOUND",resource:"Artifact",id:r})},"topic:add":async function(e,t){const{workspace:s,topics:n}=e,r=t;return s.index.topics[r.name]?g({code:"DUPLICATE_KEY",resource:"Topic",key:r.name}):(await n.add(r),y({index:{topics:{[r.name]:n.summarize(r)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:n}=e,{name:r,...i}=t;if(!s.index.topics[r])return g({code:"NOT_FOUND",resource:"Topic",id:r});const o=await n.update(r,i);return o?y({index:{topics:{[r]:{metadata:{updated:o.updated}}}}}):g({code:"BACKEND_ERROR",reason:`Failed to update topic ${r} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:n,roles:r,sessions:i}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return g({code:"NOT_FOUND",resource:"Topic",id:o});if(n.referencedBy(o,s.index)&&!a)return g({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 i.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await n.delete(o)?y({index:{topics:{[o]:m}}}):g({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:n,roles:r,sessions:i}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return g({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 i.update(e,{topics:s})}}return await n.delete(o),y({index:{topics:{[o]:m}}})},"session:create":async function(e,t){const{workspace:s,sessions:n}=e,r=t;return s.index.sessions[r.id]?g({code:"DUPLICATE_KEY",resource:"Session",key:r.id}):(await n.add(r),y({index:{sessions:{[r.id]:n.summarize(r)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,...i}=t;if(!s.index.sessions[r])return g({code:"NOT_FOUND",resource:"Session",id:r});const o=await n.update(r,i);return o?y({index:{sessions:{[r]:n.summarize(o)}}}):g({code:"BACKEND_ERROR",reason:`Failed to update session ${r} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,newSessionId:i,label:o}=t,a=s.index.sessions[r];if(!a)return g({code:"NOT_FOUND",resource:"Session",id:r});const c={...a,id:i,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await n.add(c),y({index:{sessions:{[i]:n.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r}=t;return s.index.sessions[r]?(await n.delete(r),y({index:{sessions:{[r]:m}}})):g({code:"NOT_FOUND",resource:"Session",id:r})},"session:role:switch":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,roleName:i}=t;return s.index.sessions[r]?(await n.update(r,{role:i}),y({index:{sessions:{[r]:{role:i}}}})):g({code:"NOT_FOUND",resource:"Session",id:r})},"session:topics:add":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,topics:i}=t,o=s.index.sessions[r];if(!o)return g({code:"NOT_FOUND",resource:"Session",id:r});const a=Array.from(new Set([...o.topics,...i]));return await n.update(r,{topics:a}),y({index:{sessions:{[r]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,preferences:i}=t;return s.index.sessions[r]?(await n.update(r,{preferences:i}),y({index:{sessions:{[r]:{preferences:i}}}})):g({code:"NOT_FOUND",resource:"Session",id:r})},"turn:add":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return g({code:"NOT_FOUND",resource:"Session",id:i});await r.add(o);const a={id:o.id,version:o.version};return await n.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,turns:n}=e,{sessionId:r,turn:i}=t;if(!s.index.sessions[r])return g({code:"NOT_FOUND",resource:"Session",id:r});const{id:o,session:a,version:c,...d}=i;return await n.update({id:o,session:a,version:c},d),y({})},"turn:edit":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d,modelSnapshot:l}=t,u=s.index.sessions[i];if(!u)return g({code:"NOT_FOUND",resource:"Session",id:i});let p={};const h=await r.get({id:o,version:c-1,session:i});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:i};if(await r.add(m),u.head?.id===o){const e={id:o,version:c};return await n.update(i,{head:e}),y({index:{sessions:{[i]:{head:e}}}})}return y({})},"turn:branch":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return g({code:"NOT_FOUND",resource:"Session",id:i});await r.add(o);const a={id:o.id,version:o.version};return await n.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turnId:o,newHead:a}=t;return s.index.sessions[i]?(await r.delete({session:i,id:o,version:t.version}),a?(await n.update(i,{head:a}),y({index:{sessions:{[i]:{head:a}}}})):y({})):g({code:"NOT_FOUND",resource:"Session",id:i})},"blob:register":async function(e,t){const{blobs:s}=e,n=await s.register(t.data,t.mediaType,t.filename);if(!n.ok)return n;const r=await s.getRecord(n.value.sha256);return r?y({index:{blobs:{[r.sha256]:r}}}):g({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${n.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,n=await s.retain(t.sha256);if(!n.ok)return n;const r=await s.getRecord(t.sha256);return y({index:{blobs:{[t.sha256]:r}}})},"blob:release":async function(e,t){const{blobs:s}=e,n=await s.release(t.sha256);if(!n.ok)return n;const r=await s.getRecord(t.sha256);return y({index:{blobs:{[t.sha256]:r||m}}})},"blob:purge":async function(e,t){const{blobs:s}=e,n=await s.purge(t.sha256);return n.ok?y({index:{blobs:{[t.sha256]:m}}}):n},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:n,providerId:r,fileId:i,timestamp:o}=t,a=await s.recordRemoteId(n,r,i,o);if(!a.ok)return a;const c=await s.getRecord(n);return y({index:{blobs:{[n]:c}}})},"tool:call":async function(e,t){return y({})}},z=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)}},F={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"]}},P={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.","The current assistant response MUST NOT be included.","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"}},insight:{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"]}},K=[F,{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"]}},P,{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.","","### 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:["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"]},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"]}},{type:"artifact:update",emittable:!0,consumable:!1,description:["## Block: `artifact:update`","","Represents a mutation to an existing artifact previously introduced in the conversation.","Artifacts are identified using their system-provided `key`.","","Artifacts in a structured format:","","`[key] (label, version, status)`","`description`","`content`","","The `key` is the stable identity of an artifact across all updates.","Label, version, and status are descriptive metadata provided for context.","","Updates may be expressed as full replacements or targeted patches."].join("\n"),rules:["Use `artifact:update` when modifying an existing artifact identified in context.","Use the `key` from the provided artifact list to select the target artifact.","Rely on the `key` as the stable reference for all updates.","Only use keys that are explicitly present in the current artifact context.","Allow the system to manage `created`, `updated`, and version fields automatically.","Provide either `content` or `patch` to express the update clearly and unambiguously.","Use `content` when replacing the full artifact or when changes are small and localized.","Use `patch` with `format: 'unified-diff'` when making targeted edits to larger artifacts.","Ensure unified diffs apply cleanly to the provided artifact content.","Prefer patch-based updates for large artifacts with localized changes.","Set `status` to `draft` when the artifact is still in progress after the update.","Set `status` to `complete` when the artifact is finalized and ready for use.","Support multiple artifact updates in a single turn when they are independently meaningful.","Prefer updating existing artifacts over creating new ones when continuity is intended."],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 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:["unified-diff"],description:"The patch format. Currently only `unified-diff` is supported."},value:{type:"string",description:"The patch payload. For `unified-diff`, a valid unified diff string applicable to the current artifact content."}},required:["format","value"]}},required:["type","key","status"],oneOf:[{required:["content"]},{required:["patch"]}]}}];function L(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 W=class{store=new Map;constructor(){for(const e of K)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:L(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:","",L(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=L(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 n=this.store.get(e.type);if(!n)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&n.mappings?.[s])return n.mappings[s].from(e);const{id:r,...i}=e;return{id:t(),...i}}create(e,s){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot create block of unknown type "${e}".`);return{...s,id:t(),type:e}}clone(e,s){return{...structuredClone(e),...s,id:t()}}},V=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:n,filename:r}=e.content,i={sha256:t,mediaType:s,sizeBytes:n,filename:r};return s.startsWith("image/")?{id:e.key,type:"image",ref:i}:{id:e.key,type:"document",ref:i,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())}},Y="__system__",J=class{constructor(e,s,n){this._actor=e,this._turn=n?JSON.parse(JSON.stringify(n)):{id:t(),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(),type:"text",text:e};return this._turn.blocks.push(s),this}addImage(e,s){const n={id:t(),type:"image",ref:e,altText:s};return this._turn.blocks.push(n),this}addDocument(e,s){const n={id:t(),type:"document",ref:e,title:s};return this._turn.blocks.push(n),this}addToolUse(e,s){const n={id:t(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(n),this}addToolResult(e,s,n){const r={id:t(),type:"tool:result",useId:e,content:s,isError:n};return this._turn.blocks.push(r),this}addSummary(e){const s={id:t(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const n={id:t(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(n),this}addThinking(e){const s={id:t(),type:"thinking",thinking:e};return this._turn.blocks.push(s),this}addBlock(e){return e.id||(e.id=t()),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 n=this._turn.blocks[s];if("text"!==n.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...n,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))}},G=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}},H=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s,n){const[r,i]=await Promise.all([s.loadAllTurns(t),void 0!==n?Promise.resolve(n):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 n=new Set;let r=t;for(;r;){const e=`${r.id}:${r.version}`;if(n.has(e))break;n.add(e);const t=s.get(e);if(!t)break;r=t.parent}return n}(e,t),n={},r={};for(const t of e){n[t.id]||(n[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=n[t.id];e.versions[t.version]=t;const i=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(i&&(!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),n[t.parent.id]||(n[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=n[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return n}(r,i);return new e(o,i)}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 n=s.children[t.parent.version];return n?n.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)),n=s.indexOf(t.activeVersion);return{versions:s,currentIndex:n,total:s.length,hasPrev:n>0,hasNext:n<s.length-1}}graph(){return{...this.nodes}}};var X=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}},Q=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()}},Z=class{constructor(e){this.db=e}async list(){const e=p(this.db);await e.open();const t=await e.collection(h.WORKSPACE);return new X(t,new Q(100)).list()}async delete(e){const t=p(this.db);await t.open();const s=await t.collection(h.WORKSPACE);return new X(s,new Q(1)).delete(e)}async purge(){this.db.clear()}},ee=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,n,r=[]){if(this.workspace.index.roles[e])return g({code:"DUPLICATE_KEY",resource:"role",key:e});const i={name:e,label:t,description:n,persona:s,preferences:r,topics:[]};return this.manager.dispatch({type:"role:add",payload:i,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()}):g({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return g({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?g({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,n){const r={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:n};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 n=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!n.ok)return g(n.error);const r=n.value,i=r?.index?.blobs;if(!i)return g({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(i)[0];if(!o)return g({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=i[o];if(!a)return g({code:"BACKEND_ERROR",reason:"Blob record missing"});return y({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},te=class e{constructor(e,t,s,n){this._id=e,this.manager=t,this.processor=s,this.turnRepository=n,this.workspace=new ee(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,n){s.ctx().workspace;const r=new G(s.ctx().turns,s.ctx().sessions),i=new e(t,s,n,r);return await i.sync(),i}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()}):g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async setModel(e){return this.meta()?this.updateMetadata({model:e}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async updateMetadata(e){const t=this.meta();if(!t)return g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async addContext(e){const t=this.meta();if(!t)return g({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 g({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()}):g({code:"NOT_FOUND",resource:"session",id:this._id})}async fork(e,t,s,n){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:n},timestamp:(new Date).toISOString()}):g({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 g({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==Y&&!t.index.roles[e])return g({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 g({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},n=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:s},timestamp:s.timestamp});if(n.ok){const e={id:s.id,version:s.version};await this.refreshTurnTree(e)}return n}async recordUserTurn(e){return this.meta()?this.addTurn(e):g({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return g({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return g({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.processor.process(e,this._id);let r={};const i=[];let o;for(const e of n){const t=await this.manager.dispatch(e);if(t.ok)r=b(r,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic){o=t.error;break}{const t=this.describeCommand(e);i.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=b(r,a.value),t&&i.length>0){const e=this.buildDenialTurn(i),t=await this.addTurn(e);t.ok&&(r=b(r,t.value))}return o?g(o):y(r)}buildDenialTurn(e){const t=new J("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,n){if(!this.meta())return g({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph()[e];if(!r)return g({code:"NOT_FOUND",resource:"turn",id:e});const i=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??i.role,modelSnapshot:n??i.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 g({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return g({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 g({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph();if(!n[e]?.versions[t])return g({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 n=this.tree.graph()[e];if(!n)return g({code:"NOT_FOUND",resource:"turn",id:e});const r=n.versions[t];if(!r)return g({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const i={...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:i},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 g({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return g({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return g({code:"NOT_FOUND",resource:"turn",id:e});const n=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),r=n.indexOf(s.activeVersion);if(-1===r)return g({code:"INVALID_COMMAND",reason:"Active version not found"});const i=r+t;if(i<0||i>=n.length)return g({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=n[i],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 n=t.ws(),r=t._role;if(!r)return;const i=await t.manager.ctx().context.getByTopics(n.index,s.topics),o=s.context?await Promise.all(s.context.map((e=>t.manager.ctx().context.get(e)))):[],a=Array.from(new Map([...i,...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:n.settings?.prompt,constraints:{role:r.constraints,session:s.constraints,turn:p?.constraints}}}async refreshTurnTree(e){this.tree=await H.build(this._id,this.turnRepository,e)}findSubtreeTip(e,t,s){let n=t,r=s;for(;;){const t=e[n];if(!t)break;const s=t.children[r];if(!s||0===s.length)break;const i=s[0],o=e[i];if(!o)break;n=i,r=o.activeVersion}return{id:n,version:r}}},se=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 l,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 te.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(),n=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:{...n,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]}},ne=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const n=await v(e),r=await this.getRecord(n);if(r){const e={...r,refCount:r.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(n,e),y(this.reference(e))}const i={sha256:n,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(i,e):(await this.storage.storeBytes(n,e),await this.storage.saveRecord(i)),this.cache.set(n,i),this.bus.emit({name:"blobs:changed",payload:{sha256:n,record:i}}),y(this.reference(i))}async retain(e){const t=await this.getRecord(e);if(!t)return g({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),y(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return g({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),n={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(n),this.cache.set(e,n),y(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}}),y(void 0)}async recordRemoteId(e,t,s,n){const r=await this.getRecord(e);if(!r)return g({code:"NOT_FOUND",resource:"blob",id:e});const i={...r,remoteIds:{...r.remoteIds,[t]:{id:s,timestamp:n||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:i}}),y(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 y(null);if(t){const e=s.remoteIds[t];if(e)return y({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const n=await this.storage.loadBytes(s.sha256);return y(n?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:n}:null)}const n=await this.storage.loadBytes(s.sha256);return y(n?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:n}:null)}async resolveMany(e,t){const s=new Map;for(const n of e){const e=await this.resolve(n,t);if(!e.ok)return g(e.error);if(null===e.value)return g({code:"BLOB_ERROR",reason:`Unable to resolve blob ${n.sha256}${t?` with adapter ${t}`:""}`});s.set(n.sha256,e.value)}return y(s)}},re=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 n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;const r=n.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 n=this.delegates.get(s);if(n){const s=await n.update(e,t);return s&&this.cache.set(e,s),s}}const n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;await n.update(t);const r=n.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 n=await s.delete();return n&&this.cache.delete(e),n}async getByTopics(e,t){const s=new Map;for(const n of t){const t=e.topics[n];t&&t.contextKeys.forEach((t=>{const n=e.context[t],r=n?.kind||"unknown";s.has(r)||s.set(r,new Set),s.get(r).add(t)}))}if(0===s.size)return[];const n=[],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&&n.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?n.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),n.push(t)}}}return n.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}}},ie=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}}},oe=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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 n of e){const e=this.cache.get(n);e?s.push(e):t.push(n)}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)}}},ae=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}}},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:"id",operator:"eq",value:e});if(!s)return null;const n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}},de=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},n=!0){const r=this.key({id:e,session:t,version:s});this.cache.get(r)&&this.cache.get(r);const i=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 i?(n&&this.cache.set(r,i),i):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}},le=(e={})=>({id:t(),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}),ue=(e={},s)=>({id:e.id??t(),version:e.version??0,session:e.session??s?.id??t(),actor:"user",blocks:[{id:t(),type:"text",text:"Hello, world!"}],timestamp:(new Date).toString(),role:s?.role,...e,parent:e.parent?e.parent:void 0}),pe=(e={})=>({id:e.id??t(),settings:b({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:b({id:t(),name:"Unnamed Project"},e.project),index:b({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}},e.index)}),he=class{process(e,t){const s=[],n=(new Date).toISOString();for(const r of e.blocks)"artifact"===r.type?s.push(this.handleAddArtifact(r,t,n)):"artifact:update"===r.type&&s.push(this.handleUpdateArtifact(r,t,n));return s}handleAddArtifact(e,s,n){const r=t(),i=e.label||`Untitled Artifact ${_(r)}`,o=e.content.extension||"txt",a=i.split(" ").join("-").replace(new RegExp(`\\.${o}$`),"");return{type:"artifact:add",timestamp:n,payload:{...{id:r,label:i,type:"artifact",key:e.key?e.key:`${a||_(i)}.${o}`,version:1,description:e.description||"",content:e.content,status:e.status||"complete",created:n,updated:n},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}}}};function me(){return(new Date).toISOString()}function fe(e,t,s){const n=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(s??{})]),r={};for(const i of n){const n=e?.[i]??{},o=t?.[i]??{},a=s?.[i]??{};r[i]={temperature:a.temperature??o.temperature??n.temperature,tokens:{max:a.tokens?.max??o.tokens?.max??n.tokens?.max,stops:a.tokens?.stops??o.tokens?.stops??n.tokens?.stops,thought:a.tokens?.thought??o.tokens?.thought??n.tokens?.thought}}}return r}var ye=class{constructor(e,t,s){this.contextRegistry=e,this.retriever=t,this._summarizer=s}NOISE_BLOCK_TYPES=new Set(["thinking","role:transition"]);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,n={}){const r=[],{resolved:i}=function(e){const t=[],s=new Map;for(const n of e)for(const e of n.topics){const r=s.get(e);if(!r){s.set(e,n);continue}const i=new Date(r.timestamp).getTime(),o=new Date(n.timestamp).getTime();o>i?(t.push({topic:e,kept:n.id,dropped:r.id}),s.set(e,n)):i>o&&t.push({topic:e,kept:r.id,dropped:n.id})}const n=new Map,r=new Map;for(const t of e)r.set(t.id,t.topics.length);for(const e of t)n.set(e.dropped,(n.get(e.dropped)??0)+1);const i=new Set;for(const t of e){const e=n.get(t.id)??0,s=r.get(t.id)??0;s>0&&e>=s&&i.add(t.id)}return{resolved:e.filter((e=>!i.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:n.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),n=Array.isArray(s)?s:[s];"system"===t.target?c.push({label:`context:${e.content.kind}:${e.key}`,content:n.map((t=>"text"===t.type?t.text:`[${e.content.kind}] ${JSON.stringify(t,null,2)}`)).join("\n"),position:"after:context"}):d.push(...n)}const l=new Map;for(const t of e.artifacts)l.set(t.key,{...t});const u=e.transcript.map((e=>{const t=[];for(const s of e.blocks)if("artifact"===s.type){const n=s;l.set(n.key,{...n,version:n.version||1,created:e.timestamp,updated:e.timestamp}),t.push({type:"text",text:`[Artifact: "${n.label}" produced]`})}else if("artifact:update"===s.type){const n=s,r=l.get(n.key);if(r){const t={...r,status:n.status||r.status,version:(r.version||1)+1,updated:e.timestamp};n.content&&(t.content=n.content),l.set(n.key,t)}t.push({type:"text",text:`[Artifact: "${r?.label||n.key}" updated]`})}else this.NOISE_BLOCK_TYPES.has(s.type)||t.push(s);return{...e,blocks:t}})).filter((e=>e.blocks.length>0));let p=u;n.compress&&(p=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)}(u));const h=[];if(d.length>0){const s=p.length>0?p[0].timestamp:me();h.push((m=e.id,f="system",g=d,w=s,{id:t(),session:m,version:0,actor:f,blocks:g,timestamp:w??me()}))}var m,f,g,w;const k=[...h,...p],b=function(e,t){const s=new Map;for(const t of e)if("blob"===t.content.kind){const{sha256:e,mediaType:n,sizeBytes:r,filename:i,previewUrl:o}=t.content;s.has(e)||s.set(e,{sha256:e,mediaType:n,sizeBytes:r,filename:i,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,k);return y({session:e.id,model:e.model,system:{persona:e.role.persona,instructions:e.instructions,preferences:i,context:[],artifacts:Array.from(l.values()),extensions:c},transcript:k,blobs:b,role:e.role,constraints:fe(e.constraints.role,e.constraints.session,e.constraints.turn),warnings:r})}};var ge=class{constructor(e){this.contextRegistry=e}rank(e){const{entries:t,recentMessages:s,config:n={}}=e,r=n.minScore??0,i=n.freshnessHalfLifeDays??30,o=n.recentMessageWindow??3;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,i)-this.freshnessWeight(e.timestamp,i)));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,i)}})).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 n of e)t.has(n)&&s++;const n=e.size+t.size-s;return 0===n?0:s/n}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},we=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})}},ke="blob_bytes",be="blob_records";function ve(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function xe(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var _e=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(ke)||e.createObjectStore(ke,{keyPath:"sha256"}),e.objectStoreNames.contains(be)||e.createObjectStore(be,{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(ke);if(await ve(s.objectStore(ke).get(e)))return;const n=this.writeTx(ke);n.objectStore(ke).put({sha256:e,data:t}),await xe(n)}async loadBytes(e){const t=this.readTx(ke),s=await ve(t.objectStore(ke).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(ke);return await ve(t.objectStore(ke).count(e))>0}async deleteBytes(e){const t=this.writeTx(ke);t.objectStore(ke).delete(e),await xe(t)}async saveRecord(e){const t=this.writeTx(be);t.objectStore(be).put(e),await xe(t)}async loadRecord(e){const t=this.readTx(be);return await ve(t.objectStore(be).get(e))??null}async deleteRecord(e){const t=this.writeTx(be);t.objectStore(be).delete(e),await xe(t)}async listRecords(){return ve(this.readTx(be).objectStore(be).getAll())}async exportAllBytes(){const e=this.readTx(ke);return(await ve(e.objectStore(ke).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,n)=>{const r=this.getDB().transaction([ke,be],"readwrite"),i=r.objectStore(ke),o=r.objectStore(be),a=i.count(e.sha256);a.onsuccess=()=>{0===a.result&&i.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>n(a.error),r.oncomplete=()=>s(),r.onerror=()=>n(r.error),r.onabort=()=>n(new Error("registerBlob transaction aborted"))}))}},Oe={};function Se(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 s in t)n(e,s,{get:t[s],enumerable:!0})})(Oe,{GOOGLE_MODELS:()=>Ne,GoogleGenAIAdapter:()=>Ae,extractModelResponse:()=>De,mappings:()=>Te});var Te={text:{to:({block:e})=>({text:e.text}),from:e=>({id:s(),type:"text",text:e.text})},summary:{to:({block:e})=>({text:`[Summary]: ${e.text}`}),from:e=>({id:s(),type:"summary",text:e.text})},thinking:{to:({block:e})=>({text:e.thinking}),from:e=>({id:s(),type:"thinking",thinking:e.thinking})},checkpoint:{to:({block:e})=>({text:S(e.state)}),from:e=>({id:s(),type:"checkpoint",state:e.state})},"tool:use":{to:({block:e})=>({functionCall:{name:e.name,args:e.input}}),from:e=>({id:s(),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:s(),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:s(),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:s(),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:s(),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 n=await t(s);if(!n.ok||!n.value)return null;const{value:r}=n;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 n=await e(s);if(!n.ok||!n.value)return null;const{value:r}=n;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:x(r.data),mimeType:r.mediaType}}},from:e=>e}},Ne=[{provider:"google",name:"gemini-3.1-pro-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-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:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"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",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",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-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-preview",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-preview",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-preview",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",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",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}]}];function De(e){const s=e.candidates?.[0],n=[];if(!s?.content?.parts)return{ok:!1,thinking:n,error:{code:"BACKEND_ERROR",reason:"No valid content parts in response"}};let r;for(const e of s.content.parts)if(e.thought)n.push((i=e.text??"",{id:t(),type:"thinking",thinking:i}));else if(e.text){r=e;break}var i;if(!r)return n.length>0?{ok:!0,thinking:n,rawBlocks:[]}:{ok:!1,thinking:n,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)?y(t.blocks):g({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return g({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(r.text);return o.ok?{ok:!0,thinking:n,rawBlocks:o.value}:{ok:!0,thinking:n,fallback:r.text}}function Re(e){return Math.ceil(e.length/4)}var Ae=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const n=this._models.get(s.model);if(!n)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=n,this.registerMappings()}model;_models;registerMappings(){const{assembler:t}=this.services;for(const[s,n]of Object.entries(Te))t.registry.update(s,{mappings:{[e.provider()]:n}})}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:n}=s,{assembler:r,blockRegistry:i}=this.services,o=n.model&&this._models.get(n.model)||this.model,{system:a,sections:c,transcript:d}=await r.build(e.provider(),n,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t})),[{label:"block-architecture",content:i.description(),position:"after:instructions"}]),l={role:"system",parts:[{text:a}]},u=n.constraints[o.name]??{tokens:{}},p=i.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=Re(a),w=Re(m),k=f+w,b=this;return{model:o.name,role:n.role.name,instructions:c,transcript:n.transcript,context:n.system.context,artifacts:n.system.artifacts,preferences:n.system.preferences,constraints:u,tokens:{breakdown:{system:f,transcript:w},total:k,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-k},async execute(){let s;try{s=await b.client.models.generateContent(h)}catch(e){return g({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const r=De(s);if(!r.ok)return g(r.error);let i;var a;i="fallback"in r?[...r.thinking,(a=r.fallback,{id:t(),type:"text",text:Se(a)})]:[...r.thinking,...b.services.assembler.parse(e.provider(),r.rawBlocks)];const c=new J("assistant",n.session);c.withModel(o.name),c.withRole(n.role.name);for(const e of i)c.addBlock(e);return y({turn:c.build(),effects:[]})},async*executeStream(){let e;try{e=await b.client.models.generateContentStream(h)}catch(e){const s=e instanceof Error?e.message:String(e),r=new J("assistant",n.session);return r.addBlock({id:t(),type:"text",text:`[Stream error: ${s}]`}),void(yield{turn:r.build(),effects:[]})}const s=[];for await(const n of e){const e=n.candidates?.[0];if(e?.content?.parts)for(const n of e.content.parts)n.thought||n.text&&(s.push(n.text),yield{blocks:[{id:t(),type:"text",text:n.text}]})}const r=s.join(""),i=new J("assistant",n.session);i.addBlock({id:t(),type:"text",text:r}),yield{turn:i.build(),effects:[]}}}}static provider(){return"google"}static models(){return Ne}};async function Ie(t){const{blobStorage:s,eventBus:n=e(),getWorkspace:i,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:l=[],extensions:u=[]}=t,m=p(t.db),f=[...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??[]))],k=u.flatMap((e=>e.blocks??[]));await m.open(f);const b={workspace:await m.collection(h.WORKSPACE),role:await m.collection(h.ROLE),preference:await m.collection(h.PREFERENCE),context:await m.collection(h.CONTEXT),session:await m.collection(h.SESSION),topic:await m.collection(h.TOPIC),turn:await m.collection(h.TURN),artifact:await m.collection(h.ARTIFACT)},v=new ne(s,new Q(200),n),x=new V,_={workspaceStore:new X(b.workspace,new Q(1)),roles:new ae(b.role,new Q(100)),preferences:new oe(b.preference,new Q(500)),context:new re(b.context,new Q(500),x),artifacts:new ie(b.artifact,new Q(100)),topics:new N(b.topic,new Q(100)),sessions:new ce(b.session,new Q(50)),turns:new de(b.turn,new Q(50)),blobs:v,tools:d,db:m,indexers:[...r,...w]};await Promise.all(u.map((async e=>{if(e.stores){const t=await e.stores(_);Object.assign(_,t)}})));const O=new T({ctx:_,getWorkspace:i,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=i();await _.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:n});Object.entries(M).forEach((([e,t])=>{O.register(e,t)})),Object.entries(y).forEach((([e,t])=>{O.register(e,t)})),O.use(E),O.use(q),g.forEach((e=>{O.use(e)}));const S=new se(O,a),D=new W;k.forEach((e=>D.register(e))),u.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(x.register(e),e.store){const t=e.store(_);_.context.registerDelegate(e.kind,t)}}))}));const R=new z(l),A=_.blobs.resolve.bind(_.blobs),I={assembler:new B(D,A),processor:a,blobResolver:A,blockRegistry:D,contextRegistry:x,models:R},j=async e=>{await O.dispatch({type:"workspace:sync",payload:void 0,timestamp:(new Date).toISOString()});let t=i();await O.dispatch({type:"workspace:create",payload:e.workspace,timestamp:(new Date).toISOString()}),t=i();const s=[];if(e.roles)for(const n of e.roles)t.index.roles[n.name]||(await O.dispatch({type:"role:add",payload:n,timestamp:(new Date).toISOString()}),s.push(n.name));return e.workspace.settings.defaultRole&&t.settings.defaultRole!==e.workspace.settings.defaultRole&&await O.dispatch({type:"workspace:sync",payload:{settings:{...t.settings,defaultRole:e.workspace.settings.defaultRole}},timestamp:(new Date).toISOString()}),{workspace:i(),roles:s}};if(t.bootstrap){const e=i();if(!e||!e.index){const e=pe({id:t.bootstrap.workspace.id,settings:t.bootstrap.workspace.settings,project:t.bootstrap.workspace.project});await o(e)}await j(t.bootstrap)}return{manager:O,sessions:S,ctx:_,services:I,bootstrap:j}}export{h as COLLECTIONS,he as CoreTurnProcessor,ye as DefaultPromptBuilder,Y as EMPTY_SYSTEM_ROLE,Oe as GoogleAdapter,_e as IndexedDBBlobStorage,ge as JaccardContextRetriever,Q as LRUCache,we as MemoryBlobStorage,B as PromptAssembler,te as Session,se as SessionManager,J as TurnBuilder,H as TurnTree,ee as WorkspaceApi,T as WorkspaceManager,Z as WorkspaceRegistry,x as bufferToBase64,v as computeSHA256,$ as createDefaultAssembler,le as createEmptySession,ue as createEmptyTurn,pe as createEmptyWorkspace,Ie as createWorkspace,p as createWorkspaceDatabase,k as del,g as error,O as getExtension,b as merge,w as omitNullUndefined,S as sessionStateToMarkdown,_ as shortHash,y as success};
|
|
1
|
+
import{createEventBus as e}from"@asaidimu/utils-events";import{v7 as t,v4 as s}from"uuid";import{applyPatch as n}from"diff";var r=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 n of t)s[n.name]=e.roles.summarize(n);return{index:{roles:s}}},async e=>{const t=await e.preferences.list(),s={};for(const n of t)s[n.id]=e.preferences.summarize(n);return{index:{preferences:s}}},async e=>{const t=await e.context.list(),s={};for(const n of t)s[n.key]=e.context.summarize(n);return{index:{context:s}}},async e=>{const t=await e.artifacts.list(),s={};for(const n of t)s[n.key]=e.artifacts.summarize(n);return{index:{artifacts:s}}},async e=>{const t=await e.sessions.list(),s={};for(const n of t)s[n.id]=e.sessions.summarize(n);return{index:{sessions:s}}},async e=>{const t=await e.topics.list(),s={};for(const n of t)s[n.name]=e.topics.summarize(n);return{index:{topics:s}}},async e=>({index:{blobs:await e.blobs.getAllRecords()}})],o=[{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:[]}],a=class e extends Error{constructor(t,s){super(t,{cause:s}),this.name="SyncError",Object.setPrototypeOf(this,e.prototype)}},c=class extends a{constructor(e){super(`[ArtifactContainer] Operation timed out: ${e}`)}},d=class extends a{constructor(e){super("[Serializer] The serializer has been marked as done!",e)}},l=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 n;await Promise.race([s.then((()=>clearTimeout(n))),new Promise(((s,r)=>{n=setTimeout((()=>{const e=this.waiters.indexOf(t);-1!==e&&this.waiters.splice(e,1),r(new c("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}},u=class{mutex=new l({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 n;return Promise.race([e.then((e=>(clearTimeout(n),e))),new Promise(((e,r)=>{n=setTimeout((()=>r(new c(s))),t)}))])}},p=class{mutex;_done=!1;_lastValue=null;_lastError=void 0;_hasRun=!1;constructor(e){this.mutex=new l({capacity:e?.capacity??1e3,yieldMode:e?.yieldMode??"macrotask"})}async do(e,t){if(this._done)return{value:null,error:new d};try{await this.mutex.lock(t)}catch(e){return{value:null,error:e}}let s,n=null;try{if(this._done)throw new d;n=await e(),this._lastValue=n,this._lastError=void 0,this._hasRun=!0}catch(e){s=e,this._lastError=e,this._hasRun=!0}finally{this.mutex.unlock()}return{value:n,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 h(e){const t=new u({retry:!0,throws:!0}),s=new u({retry:!0,throws:!0});return{open:async(s=[])=>(await t.do((async()=>{const t=[...o,...s];await e.setupCollections(t)}))).value,collection:async t=>e.collection(t),close:async()=>(await s.do((()=>{e.close()}))).value,database:()=>e}}var m={WORKSPACE:"workspace",ROLE:"role",PREFERENCE:"preference",CONTEXT:"context",SESSION:"session",TURN:"turn",BLOB:"blob",TOPIC:"topic",ARTIFACT:"artifact"},f=Symbol.for("delete"),y=e=>Array.isArray(e)?[...e]:{...e};function g(e){return{ok:!0,value:e}}function w(e){return{ok:!1,error:e}}function k(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>null!=t)))}function b(){return f}var v=function(e){const t=e?.deleteMarker||f;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 n={};for(const[r,i]of Object.entries(e))if(i!==t)if("object"==typeof i&&null!==i){const e=s(i);void 0!==e&&(n[r]=e)}else n[r]=i;return n}return e===t?void 0:e}return function(e,n){if("object"!=typeof e||null===e)return"object"==typeof n&&null!==n?s(n):n===t?{}:n;if("object"!=typeof n||null===n)return e;const r=y(e),i=[{target:r,source:n}];for(;i.length>0;){const{target:e,source:s}=i.pop();for(const n of Object.keys(s)){const r=s[n];if(r!==t)if(Array.isArray(r))e[n]=r;else if("object"==typeof r&&null!==r){const t=n in e&&"object"==typeof e[n]&&null!==e[n]?e[n]:{};e[n]=y(t),i.push({target:e[n],source:r})}else e[n]=r;else delete e[n]}}return r}}({deleteMarker:f});async function x(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 _(e){if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");const t=[];for(let s=0;s<e.length;s+=32768){const n=e.subarray(s,s+32768);t.push(String.fromCharCode.apply(null,Array.from(n)))}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,t){return e.extensions[t]}function T(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 N=class{registry=new Map;middlewares=[];serializer=new p;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 w(t.error)}const t=this.registry.get(e.type);if(!t)return w({code:"INVALID_COMMAND",reason:`No reducer registered for command type: ${e.type}`});const s=this._getWorkspace(),n=await t({workspace:s,...this._ctx},e.payload);if(!n.ok)return n;let r=n.value;for(const t of this.middlewares){const n=await t({workspace:s,command:e,patch:r,...this._ctx});r=v(r,n)}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}),g(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}}},D=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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 n of e){const e=this.cache.get(n);e?t.push(e):s.push(n)}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 R(e,t,s,n,r,i){const o={};for(const a of t){let t=e[a];if(!t){if("add"!==r||!i)continue;t={topic:a,contextKeys:[],preferences:[],metadata:{created:(new Date).toISOString(),updated:(new Date).toISOString(),entries:0}},i.add({name:a,created:t.metadata.created,updated:t.metadata.updated})}const c=t[n],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,[n]:c.filter((e=>e!==s)),metadata:{...t.metadata,updated:(new Date).toISOString(),entries:e}}}}else o[a]={...t,[n]:[...c,s],metadata:{...t.metadata,updated:(new Date).toISOString(),entries:(t.metadata.entries||0)+1}}}return{index:{topics:o}}}function A(e,t,s,n){return R(e,t,s,"contextKeys","add",n)}function I(e,t,s){return R(e,t,s,"contextKeys","remove")}function j(e,t,s,n){return R(e,t,s,"preferences","add",n)}function E(e,t,s){return R(e,t,s,"preferences","remove")}var q=async e=>{if(!e.patch)return;const{workspace:t,patch:s}=e,n=t.index.topics;let r={};const i=e=>{const t=e?.index?.topics;t&&(r=v(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)i(I(n,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&&i(I(n,c,s.key)),a.length&&i(A(n,a,s.key,e.topics))}}else i(A(n,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)i(E(n,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&&i(E(n,c,s.id)),a.length&&i(j(n,a,s.id,e.topics))}}else i(j(n,o.topics??[],o.id,e.topics))}return Object.keys(r).length?{index:{topics:r}}:{}},C=async e=>{const{command:t,workspace:s}=e;if("artifact:add"!==t.type)return{};const{sessionId:n,key:r}=t.payload,i=s.index.sessions[n];if(!i)return console.warn(`[sessionArtifactMiddleware] Session ${n} not found in index`),{};const o=i.artifacts||[];if(o.includes(r))return{};const a=[...o,r];return await e.sessions.update(n,{artifacts:a}),{index:{sessions:{[n]:{artifacts:a}}}}},B="\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,n=`\`\`\`${t||""}\n${s.trim()}\n\`\`\``;return`[${e.key}] (v${e.version}, ${e.status})\nDescription: ${e.description}\n${n}`})).join("\n\n")}`}function $(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 M=class{constructor(e,t){this.resolver=t,this.registry=e}registry;async build(e,t,s,n=[]){const r=this.buildSections(t,n);return{system:this.join(r),sections:r,transcript:await Promise.all(t.transcript.map((async t=>{const n=[];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 i=await Promise.resolve(r.to({block:s,resolve:t=>this.resolver(t,e)}));null!=i&&n.push(i)}return s({turn:t,parts:n})})))}}buildSections(e,t=[]){const s=[...e.system.extensions||[],...t],n=[];var r,i,o;n.push({label:"operating-system",content:B}),n.push({label:"block-architecture",content:this.registry.description()}),e.role.persona&&n.push({label:"persona",content:(r=e.role.persona,`# Persona\n${r}`)}),e.system.preferences.length>0&&n.push({label:"preferences",content:(i=e.system.preferences,`# User Preferences\n${i.map((e=>`- ${e.content}`)).join("\n")}`),metadata:{count:e.system.preferences.length}}),e.system.context.length>0&&n.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&&n.push({label:"artifacts",content:U(e.system.artifacts),metadata:{count:e.system.artifacts.length}}),e.system.instructions&&n.push({label:"instructions",content:`# Instructions\n${e.system.instructions}`});const a=[...n],c=[];for(const e of s){const{position:t,...s}=e,n=$(t);if("prepend"===n.placement){c.push(s);continue}if("append"===n.placement){a.push(s);continue}const r=a.findIndex((e=>e.label===n.label));if(-1===r){console.warn(`[SystemPromptAssembler] Anchor target "${n.label}" not found in sections. Extension "${e.label}" will be appended.`),a.push(s);continue}const i="before"===n.placement?r:r+1;a.splice(i,0,s)}return[...c,...a]}parse(e,t){const s=[];for(const n of t){const t=this.registry.parse(n,e);t&&s.push(t)}return s}join(e){return e.map((e=>e.content)).join("\n\n---\n\n")}};function F(e,t){return new M(e,t)}var z={"workspace:create":async function(e,t){const{workspaceStore:s}=e,{id:n,settings:r,project:i}=t,o=await s.get(n);return o?g({id:o.id,settings:o.settings,project:o.project}):(await s.add({id:n,settings:r,project:i}),g({id:n,settings:r,project:i,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 n=await t(e);s=v(s,n)}return t&&(t.id&&(s.id=t.id),t.settings&&(s.settings=v(s.settings||{},t.settings)),t.project&&(s.project=v(s.project||{},t.project))),g(s)},"role:add":async function(e,t){const{workspace:s,roles:n}=e,r=t;return s.index.roles[r.name]?w({code:"DUPLICATE_KEY",resource:"Role",key:r.name}):(await n.add(r),g({index:{roles:{[r.name]:n.summarize(r)}}}))},"role:update":async function(e,t){const{workspace:s,roles:n}=e,{name:r,...i}=t;if(!s.index.roles[r])return w({code:"NOT_FOUND",resource:"Role",id:r});const o=await n.update(r,i);return o?g({index:{roles:{[r]:n.summarize(o)}}}):w({code:"BACKEND_ERROR",reason:`Failed to update role ${r} in store.`})},"role:delete":async function(e,t){const{workspace:s,roles:n}=e,{name:r}=t;return s.index.roles[r]?await n.delete(r)?g({index:{roles:{[r]:f}}}):w({code:"BACKEND_ERROR",reason:`Failed to delete role ${r} from store.`}):w({code:"NOT_FOUND",resource:"Role",id:r})},"preference:add":async function(e,t){const{workspace:s,preferences:n}=e,r=t;return s.index.preferences[r.id]?w({code:"DUPLICATE_KEY",resource:"Preference",key:r.id}):(await n.add(r),g({index:{preferences:{[r.id]:n.summarize(r)}}}))},"preference:update":async function(e,t){const{workspace:s,preferences:n}=e,{id:r,...i}=t;if(!s.index.preferences[r])return w({code:"NOT_FOUND",resource:"Preference",id:r});const o=await n.update(r,i);return o?g({index:{preferences:{[r]:n.summarize(o)}}}):w({code:"BACKEND_ERROR",reason:`Failed to update preference ${r} in store.`})},"preference:delete":async function(e,t){const{workspace:s,preferences:n}=e,{id:r}=t;return s.index.preferences[r]?await n.delete(r)?g({index:{preferences:{[r]:f}}}):w({code:"BACKEND_ERROR",reason:`Failed to delete preference ${r} from store.`}):w({code:"NOT_FOUND",resource:"Preference",id:r})},"context:add":async function(e,t){const{workspace:s,context:n}=e,r=t;return s.index.context[r.key]?w({code:"DUPLICATE_KEY",resource:"Context",key:r.key}):(await n.add(r),g({index:{context:{[r.key]:n.summarize(r)}}}))},"context:update":async function(e,t){const{workspace:s,context:n}=e,{key:r,...i}=t,o=s.index.context[r];if(!o)return w({code:"NOT_FOUND",resource:"Context",id:r});const a=await n.update(r,i,o.kind);return a?g({index:{context:{[r]:n.summarize(a)}}}):w({code:"BACKEND_ERROR",reason:`Failed to update context ${r} in store.`})},"context:delete":async function(e,t){const{workspace:s,context:n}=e,{key:r}=t,i=s.index.context[r];return i?await n.delete(r,i.kind)?g({index:{context:{[r]:f}}}):w({code:"BACKEND_ERROR",reason:`Failed to delete context ${r} from store.`}):w({code:"NOT_FOUND",resource:"Context",id:r})},"artifact:add":async function(e,s){const{workspace:n,artifacts:r}=e,{sessionId:i,...o}=s;if(n.index.artifacts[o.key])return w({code:"DUPLICATE_KEY",resource:"Artifact",key:o.key});const a={...o,type:"artifact",id:t()};return await r.add(a),g({index:{artifacts:{[o.key]:r.summarize(o)}}})},"artifact:update":async function(e,t){const{workspace:s,artifacts:r}=e,{sessionId:i,...o}=t,a=o.key;if(!s.index.artifacts[a])return w({code:"NOT_FOUND",resource:"Artifact",id:a});const c=await r.get(a);if(!c)return w({code:"NOT_FOUND",resource:"Artifact",id:a});let d=c.content;if(o.content)d=o.content;else if(o.patch&&"unified-diff"===o.patch.format){const e=n(c.content.value,o.patch.value);if(!e)return w({code:"BACKEND_ERROR",reason:"Failed to apply patch"});d.value=e}const l={...c,content:d,status:o.status,version:c.version+1,updated:(new Date).toISOString()};return await r.update(a,l),g({index:{artifacts:{[a]:r.summarize(l)}}})},"artifact:delete":async function(e,t){const{workspace:s,artifacts:n}=e,{key:r}=t;return s.index.artifacts[r]?await n.delete(r)?g({index:{artifacts:{[r]:f}}}):w({code:"BACKEND_ERROR",reason:`Failed to delete artifact ${r} from store.`}):w({code:"NOT_FOUND",resource:"Artifact",id:r})},"topic:add":async function(e,t){const{workspace:s,topics:n}=e,r=t;return s.index.topics[r.name]?w({code:"DUPLICATE_KEY",resource:"Topic",key:r.name}):(await n.add(r),g({index:{topics:{[r.name]:n.summarize(r)}}}))},"topic:update":async function(e,t){const{workspace:s,topics:n}=e,{name:r,...i}=t;if(!s.index.topics[r])return w({code:"NOT_FOUND",resource:"Topic",id:r});const o=await n.update(r,i);return o?g({index:{topics:{[r]:{metadata:{updated:o.updated}}}}}):w({code:"BACKEND_ERROR",reason:`Failed to update topic ${r} in store.`})},"topic:delete":async function(e,t){const{workspace:s,topics:n,roles:r,sessions:i}=e,{name:o,cascade:a}=t;if(!s.index.topics[o])return w({code:"NOT_FOUND",resource:"Topic",id:o});if(n.referencedBy(o,s.index)&&!a)return w({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 i.update(e,{topics:t.topics.filter((e=>e!==o))})}}return await n.delete(o)?g({index:{topics:{[o]:f}}}):w({code:"BACKEND_ERROR",reason:`Failed to delete topic ${o} from store.`})},"topic:merge":async function(e,t){const{workspace:s,topics:n,roles:r,sessions:i}=e,{source:o,target:a}=t;if(!s.index.topics[o]||!s.index.topics[a])return w({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 i.update(e,{topics:s})}}return await n.delete(o),g({index:{topics:{[o]:f}}})},"session:create":async function(e,t){const{workspace:s,sessions:n}=e,r=t;return s.index.sessions[r.id]?w({code:"DUPLICATE_KEY",resource:"Session",key:r.id}):(await n.add(r),g({index:{sessions:{[r.id]:n.summarize(r)}}}))},"session:update":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,...i}=t;if(!s.index.sessions[r])return w({code:"NOT_FOUND",resource:"Session",id:r});const o=await n.update(r,i);return o?g({index:{sessions:{[r]:n.summarize(o)}}}):w({code:"BACKEND_ERROR",reason:`Failed to update session ${r} in store.`})},"session:fork":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,newSessionId:i,label:o}=t,a=s.index.sessions[r];if(!a)return w({code:"NOT_FOUND",resource:"Session",id:r});const c={...a,id:i,label:o||`Fork of ${a.label}`,role:t.role?t.role:a.role,topics:t.topics?t.topics:a.topics};return await n.add(c),g({index:{sessions:{[i]:n.summarize(c)}}})},"session:delete":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r}=t;return s.index.sessions[r]?(await n.delete(r),g({index:{sessions:{[r]:f}}})):w({code:"NOT_FOUND",resource:"Session",id:r})},"session:role:switch":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,roleName:i}=t;return s.index.sessions[r]?(await n.update(r,{role:i}),g({index:{sessions:{[r]:{role:i}}}})):w({code:"NOT_FOUND",resource:"Session",id:r})},"session:topics:add":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,topics:i}=t,o=s.index.sessions[r];if(!o)return w({code:"NOT_FOUND",resource:"Session",id:r});const a=Array.from(new Set([...o.topics,...i]));return await n.update(r,{topics:a}),g({index:{sessions:{[r]:{topics:a}}}})},"session:preferences:override":async function(e,t){const{workspace:s,sessions:n}=e,{sessionId:r,preferences:i}=t;return s.index.sessions[r]?(await n.update(r,{preferences:i}),g({index:{sessions:{[r]:{preferences:i}}}})):w({code:"NOT_FOUND",resource:"Session",id:r})},"turn:add":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return w({code:"NOT_FOUND",resource:"Session",id:i});await r.add(o);const a={id:o.id,version:o.version};return await n.update(i,{head:a}),g({index:{sessions:{[i]:{head:a}}}})},"turn:update":async function(e,t){const{workspace:s,turns:n}=e,{sessionId:r,turn:i}=t;if(!s.index.sessions[r])return w({code:"NOT_FOUND",resource:"Session",id:r});const{id:o,session:a,version:c,...d}=i;return await n.update({id:o,session:a,version:c},d),g({})},"turn:edit":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turnId:o,newBlocks:a,newVersion:c,roleSnapshot:d,modelSnapshot:l}=t,u=s.index.sessions[i];if(!u)return w({code:"NOT_FOUND",resource:"Session",id:i});let p={};const h=await r.get({id:o,version:c-1,session:i});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:i};if(await r.add(m),u.head?.id===o){const e={id:o,version:c};return await n.update(i,{head:e}),g({index:{sessions:{[i]:{head:e}}}})}return g({})},"turn:branch":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turn:o}=t;if(!s.index.sessions[i])return w({code:"NOT_FOUND",resource:"Session",id:i});await r.add(o);const a={id:o.id,version:o.version};return await n.update(i,{head:a}),g({index:{sessions:{[i]:{head:a}}}})},"turn:delete":async function(e,t){const{workspace:s,sessions:n,turns:r}=e,{sessionId:i,turnId:o,newHead:a}=t;return s.index.sessions[i]?(await r.delete({session:i,id:o,version:t.version}),a?(await n.update(i,{head:a}),g({index:{sessions:{[i]:{head:a}}}})):g({})):w({code:"NOT_FOUND",resource:"Session",id:i})},"blob:register":async function(e,t){const{blobs:s}=e,n=await s.register(t.data,t.mediaType,t.filename);if(!n.ok)return n;const r=await s.getRecord(n.value.sha256);return r?g({index:{blobs:{[r.sha256]:r}}}):w({code:"BACKEND_ERROR",reason:`Failed to retrieve registered blob record for ${n.value.sha256}`})},"blob:retain":async function(e,t){const{blobs:s}=e,n=await s.retain(t.sha256);if(!n.ok)return n;const r=await s.getRecord(t.sha256);return g({index:{blobs:{[t.sha256]:r}}})},"blob:release":async function(e,t){const{blobs:s}=e,n=await s.release(t.sha256);if(!n.ok)return n;const r=await s.getRecord(t.sha256);return g({index:{blobs:{[t.sha256]:r||f}}})},"blob:purge":async function(e,t){const{blobs:s}=e,n=await s.purge(t.sha256);return n.ok?g({index:{blobs:{[t.sha256]:f}}}):n},"blob:record_remote_id":async function(e,t){const{blobs:s}=e,{sha256:n,providerId:r,fileId:i,timestamp:o}=t,a=await s.recordRemoteId(n,r,i,o);if(!a.ok)return a;const c=await s.getRecord(n);return g({index:{blobs:{[n]:c}}})},"tool:call":async function(e,t){return g({})}},P=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)}},K={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"]}},W={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"]}},L=[K,{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"]}},W,{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.","","### 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:["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"]},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"]}},{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.","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: <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");'," ```","","Updates can be applied either as a full content replacement or as a targeted patch."].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 changes are minor and localized.","Use `patch` with `format: 'unified-diff'` for targeted edits to large artifacts, ensuring diffs apply cleanly.","Set `status` to `draft` if the artifact requires further iteration, or `complete` if it is finalized.","Do not manually pass `created`, `updated`, or version numbers; the system manages these fields automatically.","Multiple independent artifact updates may be emitted in a single turn.","Prefer updating an existing artifact over creating a new one when maintaining 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 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:["unified-diff"],description:"The patch format. Currently only `unified-diff` is supported."},value:{type:"string",description:"The patch payload. For `unified-diff`, a valid unified diff string applicable to the current artifact content."}},required:["format","value"]}},required:["type","key","status"],oneOf:[{required:["content"]},{required:["patch"]}]}}];function V(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 J=class{store=new Map;constructor(){for(const e of L)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:V(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:","",V(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=V(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 n=this.store.get(e.type);if(!n)return console.warn(`[BlockRegistry] parse() received unknown block type "${e.type}". Returning null.`),null;if(s&&n.mappings?.[s])return n.mappings[s].from(e);const{id:r,...i}=e;return{id:t(),...i}}create(e,s){if(!this.store.has(e))throw new Error(`[BlockRegistry] Cannot create block of unknown type "${e}".`);return{...s,id:t(),type:e}}clone(e,s){return{...structuredClone(e),...s,id:t()}}},Y=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:n,filename:r}=e.content,i={sha256:t,mediaType:s,sizeBytes:n,filename:r};return s.startsWith("image/")?{id:e.key,type:"image",ref:i}:{id:e.key,type:"document",ref:i,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())}},H="__system__",G=class{constructor(e,s,n){this._actor=e,this._turn=n?JSON.parse(JSON.stringify(n)):{id:t(),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(),type:"text",text:e};return this._turn.blocks.push(s),this}addImage(e,s){const n={id:t(),type:"image",ref:e,altText:s};return this._turn.blocks.push(n),this}addDocument(e,s){const n={id:t(),type:"document",ref:e,title:s};return this._turn.blocks.push(n),this}addToolUse(e,s){const n={id:t(),type:"tool:use",name:e,input:s};return this._turn.blocks.push(n),this}addToolResult(e,s,n){const r={id:t(),type:"tool:result",useId:e,content:s,isError:n};return this._turn.blocks.push(r),this}addSummary(e){const s={id:t(),type:"summary",text:e};return this._turn.blocks.push(s),this}addRoleTransition(e,s){const n={id:t(),type:"role:transition",previousRole:e,newRole:s};return this._turn.blocks.push(n),this}addThinking(e){const s={id:t(),type:"thinking",thinking:e};return this._turn.blocks.push(s),this}addBlock(e){return e.id||(e.id=t()),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 n=this._turn.blocks[s];if("text"!==n.type)throw new Error(`Block with ID ${e} is not a TextBlock.`);return this._turn.blocks[s]={...n,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))}},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}},Q=class e{constructor(e,t){this.nodes=e,this._head=t}static async build(t,s,n){const[r,i]=await Promise.all([s.loadAllTurns(t),void 0!==n?Promise.resolve(n):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 n=new Set;let r=t;for(;r;){const e=`${r.id}:${r.version}`;if(n.has(e))break;n.add(e);const t=s.get(e);if(!t)break;r=t.parent}return n}(e,t),n={},r={};for(const t of e){n[t.id]||(n[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=n[t.id];e.versions[t.version]=t;const i=s.has(`${t.id}:${t.version}`),o=s.has(`${t.id}:${e.activeVersion}`);if(i&&(!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),n[t.parent.id]||(n[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=n[t.parent.id];s.children[t.parent.version]||(s.children[t.parent.version]=[]),s.children[t.parent.version].push(t.id)}}}return n}(r,i);return new e(o,i)}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 n=s.children[t.parent.version];return n?n.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)),n=s.indexOf(t.activeVersion);return{versions:s,currentIndex:n,total:s.length,hasPrev:n>0,hasNext:n<s.length-1}}graph(){return{...this.nodes}}};var Z=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}},ee=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()}},te=class{constructor(e){this.db=e}async list(){const e=h(this.db);await e.open();const t=await e.collection(m.WORKSPACE);return new Z(t,new ee(100)).list()}async delete(e){const t=h(this.db);await t.open();const s=await t.collection(m.WORKSPACE);return new Z(s,new ee(1)).delete(e)}async purge(){this.db.clear()}},se=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,n,r=[]){if(this.workspace.index.roles[e])return w({code:"DUPLICATE_KEY",resource:"role",key:e});const i={name:e,label:t,description:n,persona:s,preferences:r,topics:[]};return this.manager.dispatch({type:"role:add",payload:i,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()}):w({code:"NOT_FOUND",resource:"role",id:e})}async deleteRole(e){const t=this.workspace;if(!t.index.roles[e])return w({code:"NOT_FOUND",resource:"role",id:e});return Object.values(t.index.sessions).some((t=>t.role===e))?w({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,n){const r={key:e,topics:s,content:t,timestamp:(new Date).toISOString(),metadata:n};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 n=await this.manager.dispatch({type:"blob:register",payload:{data:e,mediaType:t,filename:s},timestamp:(new Date).toISOString()});if(!n.ok)return w(n.error);const r=n.value,i=r?.index?.blobs;if(!i)return w({code:"BACKEND_ERROR",reason:"Blob registration succeeded but no blobs patch returned"});const o=Object.keys(i)[0];if(!o)return w({code:"BACKEND_ERROR",reason:"No SHA256 in patch"});const a=i[o];if(!a)return w({code:"BACKEND_ERROR",reason:"Blob record missing"});return g({sha256:o,ref:{sha256:o,mediaType:a.mediaType,sizeBytes:a.sizeBytes,filename:a.filename,previewUrl:a.previewUrl}})}},ne=class e{constructor(e,t,s,n){this._id=e,this.manager=t,this.processor=s,this.turnRepository=n,this.workspace=new se(t),this.unsubscribe=t.subscribe("workspace:synced",(()=>this.sync()))}workspace;_role=void 0;_preferences=[];tree;unsubscribe;static async create(t,s,n){s.ctx().workspace;const r=new X(s.ctx().turns,s.ctx().sessions),i=new e(t,s,n,r);return await i.sync(),i}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()}):w({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()}):w({code:"NOT_FOUND",resource:"session",id:this._id})}async setModel(e){return this.meta()?this.updateMetadata({model:e}):w({code:"NOT_FOUND",resource:"session",id:this._id})}async updateMetadata(e){const t=this.meta();if(!t)return w({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()}):w({code:"NOT_FOUND",resource:"session",id:this._id})}async setPreferences(e){if(!this.meta())return w({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()}):w({code:"NOT_FOUND",resource:"session",id:this._id})}async addContext(e){const t=this.meta();if(!t)return w({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 w({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()}):w({code:"NOT_FOUND",resource:"session",id:this._id})}async fork(e,t,s,n){return this.meta()?this.dispatch({type:"session:fork",payload:{sessionId:this._id,newSessionId:e,label:t,role:s,topics:n},timestamp:(new Date).toISOString()}):w({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 w({code:"NOT_FOUND",resource:"session",id:this._id});if(e!==H&&!t.index.roles[e])return w({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 w({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},n=await this.dispatch({type:"turn:add",payload:{sessionId:this._id,turn:s},timestamp:s.timestamp});if(n.ok){const e={id:s.id,version:s.version};await this.refreshTurnTree(e)}return n}async recordUserTurn(e){return this.meta()?this.addTurn(e):w({code:"NOT_FOUND",resource:"session",id:this._id})}async recordAssistantTurn(e,t){const s=this.ws();if(!s)return w({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!s.index.sessions[this._id])return w({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.processor.process(e,this._id);let r={};const i=[];let o;for(const e of n){const t=await this.manager.dispatch(e);if(t.ok)r=v(r,t.value);else{if("PERMISSION_DENIED"!==t.error.code||e.synthetic){o=t.error;break}{const t=this.describeCommand(e);i.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=v(r,a.value),t&&i.length>0){const e=this.buildDenialTurn(i),t=await this.addTurn(e);t.ok&&(r=v(r,t.value))}return o?w(o):g(r)}buildDenialTurn(e){const t=new G("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,n){if(!this.meta())return w({code:"NOT_FOUND",resource:"session",id:this._id});const r=this.tree.graph()[e];if(!r)return w({code:"NOT_FOUND",resource:"turn",id:e});const i=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??i.role,modelSnapshot:n??i.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 w({code:"NOT_FOUND",resource:"session",id:this._id});if(!e.parent)return w({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 w({code:"NOT_FOUND",resource:"session",id:this._id});const n=this.tree.graph();if(!n[e]?.versions[t])return w({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 n=this.tree.graph()[e];if(!n)return w({code:"NOT_FOUND",resource:"turn",id:e});const r=n.versions[t];if(!r)return w({code:"NOT_FOUND",resource:"turn version",id:`${e}:${t}`});const i={...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:i},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 w({code:"NOT_FOUND",resource:"workspace",id:"current"});if(!this.meta())return w({code:"NOT_FOUND",resource:"session",id:this._id});const s=this.tree.graph()[e];if(!s)return w({code:"NOT_FOUND",resource:"turn",id:e});const n=Object.keys(s.versions).map(Number).sort(((e,t)=>e-t)),r=n.indexOf(s.activeVersion);if(-1===r)return w({code:"INVALID_COMMAND",reason:"Active version not found"});const i=r+t;if(i<0||i>=n.length)return w({code:"INVALID_COMMAND",reason:`No ${t<0?"previous":"next"} version available for turn ${e}`});const o=n[i],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 n=t.ws(),r=t._role;if(!r)return;const i=await t.manager.ctx().context.getByTopics(n.index,s.topics),o=s.context?await Promise.all(s.context.map((e=>t.manager.ctx().context.get(e)))):[],a=Array.from(new Map([...i,...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:n.settings?.prompt,constraints:{role:r.constraints,session:s.constraints,turn:p?.constraints}}}async refreshTurnTree(e){this.tree=await Q.build(this._id,this.turnRepository,e)}findSubtreeTip(e,t,s){let n=t,r=s;for(;;){const t=e[n];if(!t)break;const s=t.children[r];if(!s||0===s.length)break;const i=s[0],o=e[i];if(!o)break;n=i,r=o.activeVersion}return{id:n,version:r}}},re=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 u,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 ne.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(),n=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:{...n,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]}},ie=class{constructor(e,t,s){this.storage=e,this.cache=t,this.bus=s}async register(e,t,s){const n=await x(e),r=await this.getRecord(n);if(r){const e={...r,refCount:r.refCount+1,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(e),this.cache.set(n,e),g(this.reference(e))}const i={sha256:n,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(i,e):(await this.storage.storeBytes(n,e),await this.storage.saveRecord(i)),this.cache.set(n,i),this.bus.emit({name:"blobs:changed",payload:{sha256:n,record:i}}),g(this.reference(i))}async retain(e){const t=await this.getRecord(e);if(!t)return w({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),g(void 0)}async release(e){const t=await this.getRecord(e);if(!t)return w({code:"NOT_FOUND",resource:"blob",id:e});const s=Math.max(0,t.refCount-1),n={...t,refCount:s,lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(n),this.cache.set(e,n),g(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}}),g(void 0)}async recordRemoteId(e,t,s,n){const r=await this.getRecord(e);if(!r)return w({code:"NOT_FOUND",resource:"blob",id:e});const i={...r,remoteIds:{...r.remoteIds,[t]:{id:s,timestamp:n||(new Date).toISOString()}},lastUsedAt:(new Date).toISOString()};return await this.storage.saveRecord(i),this.cache.set(e,i),this.bus.emit({name:"blobs:changed",payload:{sha256:e,record:i}}),g(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 g(null);if(t){const e=s.remoteIds[t];if(e)return g({kind:"remote",sha256:s.sha256,mediaType:s.mediaType,fileId:e.id,providerId:t,timestamp:e.timestamp});const n=await this.storage.loadBytes(s.sha256);return g(n?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:n}:null)}const n=await this.storage.loadBytes(s.sha256);return g(n?{kind:"inline",sha256:s.sha256,mediaType:s.mediaType,data:n}:null)}async resolveMany(e,t){const s=new Map;for(const n of e){const e=await this.resolve(n,t);if(!e.ok)return w(e.error);if(null===e.value)return w({code:"BLOB_ERROR",reason:`Unable to resolve blob ${n.sha256}${t?` with adapter ${t}`:""}`});s.set(n.sha256,e.value)}return g(s)}},oe=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 n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;const r=n.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 n=this.delegates.get(s);if(n){const s=await n.update(e,t);return s&&this.cache.set(e,s),s}}const n=await this.collection.find({field:"key",operator:"eq",value:e});if(!n)return null;await n.update(t);const r=n.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 n=await s.delete();return n&&this.cache.delete(e),n}async getByTopics(e,t){const s=new Map;for(const n of t){const t=e.topics[n];t&&t.contextKeys.forEach((t=>{const n=e.context[t],r=n?.kind||"unknown";s.has(r)||s.set(r,new Set),s.get(r).add(t)}))}if(0===s.size)return[];const n=[],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&&n.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?n.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),n.push(t)}}}return n.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}}},ae=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 n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}}},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:"id",operator:"eq",value:e});if(!s)return null;const n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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 n of e){const e=this.cache.get(n);e?s.push(e):t.push(n)}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)}}},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:"name",operator:"eq",value:e});if(!s)return null;const n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}}},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:"id",operator:"eq",value:e});if(!s)return null;const n=s.state();return this.cache.set(e,n),n}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 n=s.state();return this.cache.set(e,n),n}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}},ue=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},n=!0){const r=this.key({id:e,session:t,version:s});this.cache.get(r)&&this.cache.get(r);const i=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 i?(n&&this.cache.set(r,i),i):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}},pe=(e={})=>({id:t(),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}),he=(e={},s)=>({id:e.id??t(),version:e.version??0,session:e.session??s?.id??t(),actor:"user",blocks:[{id:t(),type:"text",text:"Hello, world!"}],timestamp:(new Date).toString(),role:s?.role,...e,parent:e.parent?e.parent:void 0}),me=(e={})=>({id:e.id??t(),settings:v({language:"en-US",defaultRole:void 0,prompt:void 0},e.settings),project:v({id:t(),name:"Unnamed Project"},e.project),index:v({roles:{},preferences:{},context:{},sessions:{},topics:{},blobs:{},tools:{},artifacts:{},extensions:{}},e.index)}),fe=class{process(e,t){const s=[],n=(new Date).toISOString();for(const r of e.blocks)"artifact"===r.type?s.push(this.handleAddArtifact(r,t,n)):"artifact:update"===r.type&&s.push(this.handleUpdateArtifact(r,t,n));return s}handleAddArtifact(e,s,n){const r=t(),i=e.label||`Untitled Artifact ${O(r)}`,o=e.content.extension||"txt",a=i.split(" ").join("-").replace(new RegExp(`\\.${o}$`),"");return{type:"artifact:add",timestamp:n,payload:{...{id:r,label:i,type:"artifact",key:(e.key?e.key:`${a||O(i)}.${o}`).toLowerCase(),version:1,description:e.description||"",content:e.content,status:e.status||"complete",created:n,updated:n},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}}}};function ye(){return(new Date).toISOString()}function ge(e,t,s){const n=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(s??{})]),r={};for(const i of n){const n=e?.[i]??{},o=t?.[i]??{},a=s?.[i]??{};r[i]={temperature:a.temperature??o.temperature??n.temperature,tokens:{max:a.tokens?.max??o.tokens?.max??n.tokens?.max,stops:a.tokens?.stops??o.tokens?.stops??n.tokens?.stops,thought:a.tokens?.thought??o.tokens?.thought??n.tokens?.thought}}}return r}var we=class{constructor(e,t,s){this.contextRegistry=e,this.retriever=t,this._summarizer=s}NOISE_BLOCK_TYPES=new Set(["thinking","role:transition"]);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,n={}){const r=[],{resolved:i}=function(e){const t=[],s=new Map;for(const n of e)for(const e of n.topics){const r=s.get(e);if(!r){s.set(e,n);continue}const i=new Date(r.timestamp).getTime(),o=new Date(n.timestamp).getTime();o>i?(t.push({topic:e,kept:n.id,dropped:r.id}),s.set(e,n)):i>o&&t.push({topic:e,kept:r.id,dropped:n.id})}const n=new Map,r=new Map;for(const t of e)r.set(t.id,t.topics.length);for(const e of t)n.set(e.dropped,(n.get(e.dropped)??0)+1);const i=new Set;for(const t of e){const e=n.get(t.id)??0,s=r.get(t.id)??0;s>0&&e>=s&&i.add(t.id)}return{resolved:e.filter((e=>!i.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:n.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),n=Array.isArray(s)?s:[s];"system"===t.target?c.push({label:`context:${e.content.kind}:${e.key}`,content:n.map((t=>"text"===t.type?t.text:`[${e.content.kind}] ${JSON.stringify(t,null,2)}`)).join("\n"),position:"after:context"}):d.push(...n)}const l=new Map;for(const t of e.artifacts)l.set(t.key,{...t});const u=e.transcript.map((e=>{const t=[];for(const s of e.blocks)if("artifact"===s.type){const n=s;l.set(n.key,{...n,version:n.version||1,created:e.timestamp,updated:e.timestamp}),t.push({type:"text",text:`[Artifact: "${n.label}" produced]`})}else if("artifact:update"===s.type){const n=s,r=l.get(n.key);if(r){const t={...r,status:n.status||r.status,version:(r.version||1)+1,updated:e.timestamp};n.content&&(t.content=n.content),l.set(n.key,t)}t.push({type:"text",text:`[Artifact: "${r?.label||n.key}" updated]`})}else this.NOISE_BLOCK_TYPES.has(s.type)||t.push(s);return{...e,blocks:t}})).filter((e=>e.blocks.length>0));let p=u;n.compress&&(p=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)}(u));const h=[];if(d.length>0){const s=p.length>0?p[0].timestamp:ye();h.push((m=e.id,f="system",y=d,w=s,{id:t(),session:m,version:0,actor:f,blocks:y,timestamp:w??ye()}))}var m,f,y,w;const k=[...h,...p],b=function(e,t){const s=new Map;for(const t of e)if("blob"===t.content.kind){const{sha256:e,mediaType:n,sizeBytes:r,filename:i,previewUrl:o}=t.content;s.has(e)||s.set(e,{sha256:e,mediaType:n,sizeBytes:r,filename:i,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,k);return g({session:e.id,model:e.model,system:{persona:e.role.persona,instructions:e.instructions,preferences:i,context:[],artifacts:Array.from(l.values()),extensions:c},transcript:k,blobs:b,role:e.role,constraints:ge(e.constraints.role,e.constraints.session,e.constraints.turn),warnings:r})}};var ke=class{constructor(e){this.contextRegistry=e}rank(e){const{entries:t,recentMessages:s,config:n={}}=e,r=n.minScore??0,i=n.freshnessHalfLifeDays??30,o=n.recentMessageWindow??3;if(0===s.length)return[...t].sort(((e,t)=>this.freshnessWeight(t.timestamp,i)-this.freshnessWeight(e.timestamp,i)));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,i)}})).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 n of e)t.has(n)&&s++;const n=e.size+t.size-s;return 0===n?0:s/n}freshnessWeight(e,t){const s=(Date.now()-new Date(e).getTime())/864e5;return Math.pow(.5,s/t)}},be=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})}},ve="blob_bytes",xe="blob_records";function _e(e){return new Promise(((t,s)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>s(e.error)}))}function Oe(e){return new Promise(((t,s)=>{e.oncomplete=()=>t(),e.onerror=()=>s(e.error),e.onabort=()=>s(new Error("Transaction aborted"))}))}var Se=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(ve)||e.createObjectStore(ve,{keyPath:"sha256"}),e.objectStoreNames.contains(xe)||e.createObjectStore(xe,{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(ve);if(await _e(s.objectStore(ve).get(e)))return;const n=this.writeTx(ve);n.objectStore(ve).put({sha256:e,data:t}),await Oe(n)}async loadBytes(e){const t=this.readTx(ve),s=await _e(t.objectStore(ve).get(e));return s?.data??null}async hasBytes(e){const t=this.readTx(ve);return await _e(t.objectStore(ve).count(e))>0}async deleteBytes(e){const t=this.writeTx(ve);t.objectStore(ve).delete(e),await Oe(t)}async saveRecord(e){const t=this.writeTx(xe);t.objectStore(xe).put(e),await Oe(t)}async loadRecord(e){const t=this.readTx(xe);return await _e(t.objectStore(xe).get(e))??null}async deleteRecord(e){const t=this.writeTx(xe);t.objectStore(xe).delete(e),await Oe(t)}async listRecords(){return _e(this.readTx(xe).objectStore(xe).getAll())}async exportAllBytes(){const e=this.readTx(ve);return(await _e(e.objectStore(ve).getAll())).map((({sha256:e,data:t})=>[e,t]))}async registerBlob(e,t){await new Promise(((s,n)=>{const r=this.getDB().transaction([ve,xe],"readwrite"),i=r.objectStore(ve),o=r.objectStore(xe),a=i.count(e.sha256);a.onsuccess=()=>{0===a.result&&i.put({sha256:e.sha256,data:t}),o.put(e)},a.onerror=()=>n(a.error),r.oncomplete=()=>s(),r.onerror=()=>n(r.error),r.onabort=()=>n(new Error("registerBlob transaction aborted"))}))}},Te={};function Ne(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 s in t)r(e,s,{get:t[s],enumerable:!0})})(Te,{GOOGLE_MODELS:()=>Re,GoogleGenAIAdapter:()=>je,extractModelResponse:()=>Ae,mappings:()=>De});var De={text:{to:({block:e})=>({text:e.text}),from:e=>({id:s(),type:"text",text:e.text})},summary:{to:({block:e})=>({text:`[Summary]: ${e.text}`}),from:e=>({id:s(),type:"summary",text:e.text})},thinking:{to:({block:e})=>({text:e.thinking}),from:e=>({id:s(),type:"thinking",thinking:e.thinking})},checkpoint:{to:({block:e})=>({text:T(e.state)}),from:e=>({id:s(),type:"checkpoint",state:e.state})},"tool:use":{to:({block:e})=>({functionCall:{name:e.name,args:e.input}}),from:e=>({id:s(),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:s(),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:s(),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:s(),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:s(),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 n=await t(s);if(!n.ok||!n.value)return null;const{value:r}=n;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:_(r.data),mimeType:r.mediaType}}},from:e=>e},document:{to:async({resolve:e,block:t})=>{const s=t.ref;if(!s)return null;const n=await e(s);if(!n.ok||!n.value)return null;const{value:r}=n;return"remote"===r.kind?{fileData:{fileUri:r.fileId,mimeType:r.mediaType}}:{inlineData:{data:_(r.data),mimeType:r.mediaType}}},from:e=>e}},Re=[{provider:"google",name:"gemini-3.1-pro-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-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:.25,output:1.5,cache:{read:.025,write:1}}}],capacity:[{unit:"token",max:4e6,period:60}]},{provider:"google",name:"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",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",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-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:2,output:12,cache:{read:.2,write:4.5}}}],capacity:[{unit:"token",max:1e6,period:60}]},{provider:"google",name:"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-preview",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-preview",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-preview",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",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",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}]}];function Ae(e){const s=e.candidates?.[0],n=[];if(!s?.content?.parts)return{ok:!1,thinking:n,error:{code:"BACKEND_ERROR",reason:"No valid content parts in response"}};let r;for(const e of s.content.parts)if(e.thought)n.push((i=e.text??"",{id:t(),type:"thinking",thinking:i}));else if(e.text){r=e;break}var i;if(!r)return n.length>0?{ok:!0,thinking:n,rawBlocks:[]}:{ok:!1,thinking:n,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)?g(t.blocks):w({code:"BACKEND_ERROR",reason:'Invalid response: missing or malformed "blocks" array'})}catch(e){return w({code:"BACKEND_ERROR",reason:`Failed to parse response JSON: ${e instanceof Error?e.message:String(e)}`})}}(r.text);return o.ok?{ok:!0,thinking:n,rawBlocks:o.value}:{ok:!0,thinking:n,fallback:r.text}}function Ie(e){return Math.ceil(e.length/4)}var je=class e{constructor(e,t,s={model:"gemini-2.5-flash"}){this.client=e,this.services=t,this._models=t.models;const n=this._models.get(s.model);if(!n)throw new Error(`Could not get model: ${s.model} profile in registry.`);this.model=n,this.registerMappings()}model;_models;registerMappings(){const{assembler:t}=this.services;for(const[s,n]of Object.entries(De))t.registry.update(s,{mappings:{[e.provider()]:n}})}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:n}=s,{assembler:r,blockRegistry:i}=this.services,o=n.model&&this._models.get(n.model)||this.model,{system:a,sections:c,transcript:d}=await r.build(e.provider(),n,(({turn:e,parts:t})=>({role:"assistant"===e.actor?"model":"user",parts:t}))),l={role:"system",parts:[{text:a}]},u=n.constraints[o.name]??{tokens:{}},p=i.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=Ie(a),y=Ie(m),k=f+y,b=this;return{model:o.name,role:n.role.name,instructions:c,transcript:n.transcript,context:n.system.context,artifacts:n.system.artifacts,preferences:n.system.preferences,constraints:u,tokens:{breakdown:{system:f,transcript:y},total:k,source:"estimated",output:u.tokens.max??o.window.out,remaining:o.window.size-k},async execute(){let s;try{s=await b.client.models.generateContent(h)}catch(e){return w({code:"BACKEND_ERROR",reason:e instanceof Error?e.message:String(e)})}const r=Ae(s);if(!r.ok)return w(r.error);let i;var a;i="fallback"in r?[...r.thinking,(a=r.fallback,{id:t(),type:"text",text:Ne(a)})]:[...r.thinking,...b.services.assembler.parse(e.provider(),r.rawBlocks)];const c=new G("assistant",n.session);c.withModel(o.name),c.withRole(n.role.name);for(const e of i)c.addBlock(e);return g({turn:c.build(),effects:[]})},async*executeStream(){let e;try{e=await b.client.models.generateContentStream(h)}catch(e){const s=e instanceof Error?e.message:String(e),r=new G("assistant",n.session);return r.addBlock({id:t(),type:"text",text:`[Stream error: ${s}]`}),void(yield{turn:r.build(),effects:[]})}const s=[];for await(const n of e){const e=n.candidates?.[0];if(e?.content?.parts)for(const n of e.content.parts)n.thought||n.text&&(s.push(n.text),yield{blocks:[{id:t(),type:"text",text:n.text}]})}const r=s.join(""),i=new G("assistant",n.session);i.addBlock({id:t(),type:"text",text:r}),yield{turn:i.build(),effects:[]}}}}static provider(){return"google"}static models(){return Re}};async function Ee(t){const{blobStorage:s,eventBus:n=e(),getWorkspace:r,setWorkspace:o,processor:a,guard:c,toolRegistry:d,models:l=[],extensions:u=[]}=t,p=h(t.db),f=[...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??[]))],k=u.flatMap((e=>e.blocks??[]));await p.open(f);const b={workspace:await p.collection(m.WORKSPACE),role:await p.collection(m.ROLE),preference:await p.collection(m.PREFERENCE),context:await p.collection(m.CONTEXT),session:await p.collection(m.SESSION),topic:await p.collection(m.TOPIC),turn:await p.collection(m.TURN),artifact:await p.collection(m.ARTIFACT)},v=new ie(s,new ee(200),n),x=new Y,_={workspaceStore:new Z(b.workspace,new ee(1)),roles:new de(b.role,new ee(100)),preferences:new ce(b.preference,new ee(500)),context:new oe(b.context,new ee(500),x),artifacts:new ae(b.artifact,new ee(100)),topics:new D(b.topic,new ee(100)),sessions:new le(b.session,new ee(50)),turns:new ue(b.turn,new ee(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(_);Object.assign(_,t)}})));const O=new N({ctx:_,getWorkspace:r,updateWorkspace:async e=>{if(await o(e),e?.id||e?.settings||e?.project){const e=r();await _.workspaceStore.update(e.id,{id:e.id,settings:e.settings,project:e.project})}},guard:c,bus:n});Object.entries(z).forEach((([e,t])=>{O.register(e,t)})),Object.entries(y).forEach((([e,t])=>{O.register(e,t)})),O.use(q),O.use(C),g.forEach((e=>{O.use(e)}));const S=new re(O,a),T=new J;k.forEach((e=>T.register(e))),u.forEach((e=>{e.contexts&&e.contexts.forEach((e=>{if(x.register(e),e.store){const t=e.store(_);_.context.registerDelegate(e.kind,t)}}))}));const R=new P(l),A=_.blobs.resolve.bind(_.blobs),I={assembler:new M(T,A),processor:a,blobResolver:A,blockRegistry:T,contextRegistry:x,models:R},j=async e=>{await O.dispatch({type:"workspace:sync",payload:void 0,timestamp:(new Date).toISOString()});let t=r();await O.dispatch({type:"workspace:create",payload:e.workspace,timestamp:(new Date).toISOString()}),t=r();const s=[];if(e.roles)for(const n of e.roles)t.index.roles[n.name]||(await O.dispatch({type:"role:add",payload:n,timestamp:(new Date).toISOString()}),s.push(n.name));return e.workspace.settings.defaultRole&&t.settings.defaultRole!==e.workspace.settings.defaultRole&&await O.dispatch({type:"workspace:sync",payload:{settings:{...t.settings,defaultRole:e.workspace.settings.defaultRole}},timestamp:(new Date).toISOString()}),{workspace:r(),roles:s}};if(t.bootstrap){const e=r();if(!e||!e.index){const e=me({id:t.bootstrap.workspace.id,settings:t.bootstrap.workspace.settings,project:t.bootstrap.workspace.project});await o(e)}await j(t.bootstrap)}return{manager:O,sessions:S,ctx:_,services:I,bootstrap:j}}export{m as COLLECTIONS,fe as CoreTurnProcessor,we as DefaultPromptBuilder,H as EMPTY_SYSTEM_ROLE,Te as GoogleAdapter,Se as IndexedDBBlobStorage,ke as JaccardContextRetriever,ee as LRUCache,be as MemoryBlobStorage,M as PromptAssembler,ne as Session,re as SessionManager,G as TurnBuilder,Q as TurnTree,se as WorkspaceApi,N as WorkspaceManager,te as WorkspaceRegistry,_ as bufferToBase64,x as computeSHA256,F as createDefaultAssembler,pe as createEmptySession,he as createEmptyTurn,me as createEmptyWorkspace,Ee as createWorkspace,h as createWorkspaceDatabase,b as del,w as error,S as getExtension,v as merge,k as omitNullUndefined,T as sessionStateToMarkdown,O as shortHash,g as success};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asaidimu/utils-workspace",
|
|
3
|
-
"version": "6.6.
|
|
3
|
+
"version": "6.6.5",
|
|
4
4
|
"description": "Content-addressed workspace and conversation management for AI applications.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"module": "index.mjs",
|
|
@@ -63,9 +63,10 @@
|
|
|
63
63
|
"@google/genai": "^1.50.1"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
|
+
"@asaidimu/anansi": "^4.0.2",
|
|
66
67
|
"@asaidimu/utils-database": "^3.1.5",
|
|
67
68
|
"@asaidimu/utils-events": "^1.0.0",
|
|
68
|
-
"
|
|
69
|
-
"uuid": "^
|
|
69
|
+
"diff": "^9.0.0",
|
|
70
|
+
"uuid": "^14.0.0"
|
|
70
71
|
}
|
|
71
72
|
}
|