🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

goodmemory

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

goodmemory - npm Package Compare versions

Comparing version
0.7.0
to
0.7.1
+247
dist/bin/chunk-djzzs7r6.js
import{Za as b,_a as QG,ab as DG,cb as qG,db as kG,eb as CG,fb as YG,gb as EG,hb as PG,ib as RG,kb as ZG}from"./chunk-jmsnz9jn.js";import{Database as VG}from"bun:sqlite";import{Buffer as bG}from"node:buffer";import{mkdirSync as pG}from"node:fs";import{dirname as uG}from"node:path";import{spawnSync as NG}from"node:child_process";import{existsSync as yG}from"node:fs";import*as wG from"sqlite-vss";var t="vss_inner_product",HG=Symbol.for("goodmemory.sqlite.library-registry"),SG=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],gG=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m(G){if(!G)return;let Y=G.trim();return Y.length>0?Y:void 0}function fG(G){let Y=m(G);if(!Y)return[];return Y.split(",").map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function xG(G){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(G))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${G}. Expected a valid SQLite function identifier.`);return G}function vG(G){let Y=m(G);if(!Y)return;if(Y==="off"||Y==="prefer"||Y==="require")return Y;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${Y}. Expected off|prefer|require.`)}function a(G){let{backend:Y,customLibraryPath:Z,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}=G;return{customLibraryPath:Z,vectorExtension:{backend:Y,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}}}function JG(G){return{config:a({backend:"none",customLibraryPath:G.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:G.searchFunction}),diagnostics:{available:G.source==="disabled",backend:"none",effectiveMode:"off",reason:G.reason,requestedMode:G.requestedMode,source:G.source}}}function hG(G){let Y=NG(process.execPath,["-e",gG,"--",G.customLibraryPath,...G.paths],{encoding:"utf8",timeout:1e4});if(Y.error)return{loadable:!1,reason:Y.error.message};if(Y.status!==0)return{loadable:!1,reason:`${Y.stdout}${Y.stderr}`.trim()||`sqlite-vss probe exited with status ${Y.status}`};return{loadable:!0}}function mG(G={}){let Y=G.exists??yG,Z=(G.libraryCandidatePaths??SG).find((H)=>Y(H));if(!Z)return{runtime:null};try{let H=wG,X=Object.hasOwn(G,"getVectorLoadablePath")?G.getVectorLoadablePath:H.getVectorLoadablePath,F=Object.hasOwn(G,"getVssLoadablePath")?G.getVssLoadablePath:H.getVssLoadablePath;if(!X||!F)return{runtime:null};let W=X(),A=F();if(!Y(W)||!Y(A))return{runtime:null};let M={customLibraryPath:Z,paths:[W,A]},E=(G.probeRuntime??hG)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(H){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${H instanceof Error?H.message:String(H)}`}}}function jG(G=process.env,Y){let Z=m(G.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),H=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),X=fG(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=vG(G.GOODMEMORY_SQLITE_VECTOR_MODE),W=xG(m(G.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??t),A=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=Y?.inspectBundledSQLiteVssRuntime?Y.inspectBundledSQLiteVssRuntime():Y?.detectBundledSQLiteVssRuntime?{runtime:Y.detectBundledSQLiteVssRuntime()}:mG(),E=M.runtime,P=M.unavailableReason,U=F??(X.length>0||E||P?"prefer":"off");if(U==="off")return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"disabled"});if(X.length>0)return{config:a({backend:"sql-function",customLibraryPath:Z,entryPoint:A,mode:U,path:H,paths:X,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let Q=U==="require"?"require":"prefer";return{config:a({backend:"sqlite-vss",customLibraryPath:Z??E.customLibraryPath,entryPoint:A,mode:Q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:Q,requestedMode:U,source:"bundled-sqlite-vss"}}}return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"unavailable",reason:P??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function BG(G,Y){if(!G.customLibraryPath)return;let Z=globalThis,H=Z[HG]??{configuredPaths:new WeakMap};Z[HG]=H;let X=H.configuredPaths.get(Y);if(X===G.customLibraryPath)return;if(X)throw Error(`SQLite runtime already uses ${X} and cannot switch to ${G.customLibraryPath}.`);Y.setCustomSQLite(G.customLibraryPath),H.configuredPaths.set(Y,G.customLibraryPath)}function AG(G,Y){if(G.mode==="off"||!(G.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Z of G.paths)Y.loadExtension(Z,G.entryPoint);return{loaded:!0}}catch(Z){let H=Z instanceof Error?Z.message:String(Z);if(G.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${G.path}: ${H}`};throw Error(`Failed to load SQLite vector extension at ${G.path}: ${H}`)}}var o=null,e=null,OG="document_filter_indexes",UG="document_text_fts_keys",zG=2,_G=2;function rG(){if(!o)o={customLibraryPath:TG().config.customLibraryPath},BG(o,VG);return o}function TG(){if(!e)e=jG();return e}function cG(G,Y){if(Y?.readOnly||G===":memory:")return;pG(uG(G),{recursive:!0})}function $G(G,Y){return rG(),cG(G,Y),new VG(G,{create:Y?.readOnly?!1:!0,readonly:Y?.readOnly??!1,strict:!0})}function dG(G){G.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{G.exec("BEGIN IMMEDIATE");let Y=G.query("SELECT version FROM document_store_schema WHERE component = ?1");if(Y.get(UG)?.version!==zG)G.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(UG,zG);if(Y.get(OG)?.version!==_G)G.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(OG,_G);G.exec("COMMIT")}catch(Y){try{G.exec("ROLLBACK")}catch{}throw Y}}function lG(G){G.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function sG(G){G.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V(G){return JSON.parse(G)}function g(G,Y){let Z=G.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(Y);return Z!==null&&Z!==void 0}function oG(G,Y,Z){let H=Y.replaceAll('"','""');return G.query(`PRAGMA table_info("${H}")`).all().some(({name:X})=>X===Z)}function f(G){return Error(`SQLite ${G} store is read-only in this context.`)}function iG(G,Y){let Z=Math.min(G.length,Y.length),H=0;for(let X=0;X<Z;X+=1)H+=G[X]*Y[X];return H}function nG(G){return G===null||typeof G==="string"||typeof G==="number"||typeof G==="boolean"}function aG(G){switch(G){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function n(G,Y){G.exec("BEGIN IMMEDIATE");try{let Z=Y();return G.exec("COMMIT"),Z}catch(Z){try{G.exec("ROLLBACK")}catch{}throw Z}}function KG(G){let{alias:Y,keyParameterIndex:Z,value:H,valueParameterIndex:X}=G,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${Y}
WHERE ${Y}.key = ?${Z}`;if(H===null)return`${F}
AND ${Y}.type = 'null'
)`;if(typeof H==="boolean")return`${F}
AND ${Y}.type = '${H?"true":"false"}'
)`;if(typeof H==="number")return`${F}
AND ${Y}.type IN ('integer', 'real')
AND ${Y}.atom = ?${X}
)`;return`${F}
AND ${Y}.type = 'text'
AND ${Y}.atom = ?${X}
)`}function c(G){return`"${G.replaceAll('"','""')}"`}function tG(G){if(/^[A-Za-z0-9]+$/.test(G))return G;return`x_${bG.from(G,"utf8").toString("hex")}`}function FG(G,Y){return`vss_vectors_${tG(G)}_dim_${Y}`}function i(G,Y,Z){G.query(`DELETE FROM ${c(Y)} WHERE rowid = ?1`).run(Z)}function MG(G){let{database:Y,embeddingJson:Z,rowid:H,tableName:X}=G;i(Y,X,H),Y.query(`INSERT INTO ${c(X)} (rowid, embedding)
VALUES (?1, json(?2))`).run(H,Z)}function eG(G){let{collection:Y,config:Z,database:H,filter:X,queryEmbedding:F,topK:W}=G;if(Z.mode==="off"||!Z.paths?.length)return null;let A=[Y,JSON.stringify(F)],M=[];if(X)for(let[U,Q]of Object.entries(X)){if(!nG(Q))return null;A.push(U);let N=A.length,I=`metadata_filter_${M.length+1}`;if(Q===null||typeof Q==="boolean"){M.push(KG({alias:I,keyParameterIndex:N,value:Q}));continue}A.push(Q),M.push(KG({alias:I,keyParameterIndex:N,value:Q,valueParameterIndex:A.length}))}A.push(W);let E=["collection = ?1",...M];return H.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Z.searchFunction||t}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${A.length}`).all(...A).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function OY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)dG(Z);let H=Z.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),X=Z.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Z.query("SELECT json FROM documents WHERE collection = ?1"),W=Z.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),A=g(Z,"document_text_fts"),M=g(Z,"document_text_fts_keys"),E=A&&oG(Z,"document_text_fts","searchText"),P=M?Z.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Z.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,Q=A?Z.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=A&&E?Z.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,I=M?Z.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(J,$){let O=U?.get(J,$);if(!O)return;Q?.run(O.rowid),I?.run(O.rowid)}function d(J,$,O){if(!Q||!N||!P||!U)return;let z=U.get(J,$);if(z)Q.run(z.rowid);let R=ZG(O,"searchText"),T=ZG(O,"text");if(T===void 0&&R===void 0){if(z)I?.run(z.rowid);return}P.run(J,$);let D=U.get(J,$);N.run(D.rowid,J,$,T??null,R??null)}function p(J){let $=Object.entries(J.filter??{}),O=$.length>0?[`json_valid(${J.alias}.json)`]:[];for(let[z,R]of $){let T=aG(z);if(T){if(R===null){O.push(`json_type(${J.alias}.json, '${T}') = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, '${T}') = ?${J.values.length}`);continue}J.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=J.values.length;if(R===null){O.push(`json_type(${J.alias}.json, ?${D}) = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, ?${D}) = ?${J.values.length}`)}return O}function l(J){Z.exec("BEGIN IMMEDIATE");try{for(let $ of[J.expected,...J.unchanged??[]]){let O=X.get($.collection,$.id);if(!($.document===null?O===null:O!==null&&O.json===JSON.stringify($.document)))return Z.exec("ROLLBACK"),!1}for(let $ of J.set)H.run($.collection,$.id,JSON.stringify($.document)),d($.collection,$.id,$.document);for(let $ of J.delete??[])W.run($.collection,$.id),x($.collection,$.id);return Z.exec("COMMIT"),!0}catch($){try{Z.exec("ROLLBACK")}catch{}throw $}}return{projectionBatchSemantics:DG,async set(J,$,O){n(Z,()=>{H.run(J,$,JSON.stringify(O)),d(J,$,O)})},async get(J,$){let O=X.get(J,$);return O?V(O.json):null},async update(J,$,O){let z=await this.get(J,$);if(!z)throw Error(`Document not found for update: ${J}/${$}`);await this.set(J,$,EG(z,O))},async query(J,$){if(CG($),$&&Object.keys($).length>0){let z=[J],R=p({alias:"documents",filter:$,values:z});return Z.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(J).map((z)=>V(z.json))},async queryPage(J,$){qG($);let O=[J],z=p({alias:"documents",filter:$.filter,values:O});O.push($.cursor??null);let R=O.length;O.push($.limit+1);let T=Z.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=T.slice(0,$.limit);return{items:D.map((w)=>V(w.json)),...T.length>$.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(J,$){kG($);let O=RG($.query);if(O.length===0)return[];let z=[],R,T=$.field==="text"?$.field:$.field==="searchText"&&E?$.field:null;if(A&&T){z.push(O,J);let D=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${T} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(J,`$."${$.field.replaceAll('"',"\\\"")}"`);let D=PG($.query),w=[];for(let v of D)z.push(`%${v}%`),w.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${w.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Z.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(J){if(Y?.readOnly)throw f("document");return l(J)},async delete(J,$){n(Z,()=>{x(J,$),W.run(J,$)})}}}function GG(G,Y,Z){if(Z?.readOnly&&!g(G,Y))return{async set(){throw f("session")},async get(){return null},async setIfUnchanged(){throw f("session")},async deleteIfUnchanged(){throw f("session")},async deleteByScope(){throw f("session")}};let H=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),X=G.query(`SELECT json FROM ${Y} WHERE scope_key = ?1`),F=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=G.query(`UPDATE ${Y}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),A=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1`),M=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1 AND json = ?2`),E=G.query(`DELETE FROM ${Y} WHERE scope_key LIKE ?1`);return{async set(P,U){H.run(b(P),JSON.stringify(U))},async setIfUnchanged(P,U,Q){return n(G,()=>{let N=b(P),I=JSON.stringify(Q),x=U===null?F.run(N,I):W.run(N,JSON.stringify(U),I);return Number(x.changes??0)===1})},async get(P){let U=X.get(b(P));return U?V(U.json):null},async deleteIfUnchanged(P,U){return n(G,()=>{let Q=M.run(b(P),JSON.stringify(U));return Number(Q.changes??0)===1})},async deleteByScope(P){if(P.sessionId!==void 0){let Q=A.run(b(P));return Number(Q.changes??0)}let U=E.run(`${QG(P)}%`);return Number(U.changes??0)}}}function UY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)lG(Z);let H=GG(Z,"session_buffers",Y),X=GG(Z,"session_working_memory",Y),F=GG(Z,"session_journals",Y);return{saveBuffer(W,A){return H.set(W,A)},saveBufferIfUnchanged(W,A,M){return H.setIfUnchanged(W,A,M)},getBuffer(W){return H.get(W)},deleteBufferIfUnchanged(W,A){return H.deleteIfUnchanged(W,A)},deleteBuffersByScope(W){return H.deleteByScope(W)},saveWorkingMemory(W,A){return X.set(W,A)},getWorkingMemory(W){return X.get(W)},deleteWorkingMemoryByScope(W){return X.deleteByScope(W)},saveJournal(W,A){return F.set(W,A)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function zY(G,Y,Z){let H=Z?.runtimeResolution??TG(),X=Z?.vectorExtensionConfig??H.config.vectorExtension,F=Z?.runtimeResolution?.diagnostics??H.diagnostics,W=$G(G,Y);if(!Y?.readOnly)sG(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let A=!Y?.readOnly||g(W,"vectors"),M=new Set,E=null,P=Y?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,Q=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,I=A?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=Y?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!Y?.readOnly||g(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,J=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),$=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let j=(Z?.loadVectorExtension??AG)(X,W);return E=j&&typeof j==="object"&&"loaded"in j?j:{loaded:X.mode!=="off"&&Boolean(X.paths?.length)},E}function z(){return X.backend==="sqlite-vss"&&O().loaded}function R(j,K){let B=FG(j,K);J.run(B,j,K)}function T(j){$.run(j.tableName,j.collection,j.dimension)}function D(j){if(!j.existed)return!0;let K=l.get(j.tableName);return!K||K.dirty!==0}function w(j){return l?.get(j)?.dirty===0}function u(j,K,B){let _=N.all(j).filter((C)=>{return V(C.embedding_json).length===K}),q=new Set(_.map((C)=>C.rowid)),k=W.query(`SELECT rowid FROM ${c(B)}`).all();for(let C of k)if(!q.has(C.rowid))i(W,B,C.rowid);for(let C of _)MG({database:W,embeddingJson:C.embedding_json,rowid:C.rowid,tableName:B});T({collection:j,dimension:K,tableName:B})}function v(j,K){if(!z())return null;let B=FG(j,K);if(M.has(B)){if(Y?.readOnly){if(!w(B))return M.delete(B),null;return B}if(D({existed:!0,tableName:B}))u(j,K,B);return B}if(Y?.readOnly){if(!g(W,B))return null;if(!w(B))return null;return M.add(B),B}let _=g(W,B);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(B)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:B}))u(j,K,B);return M.add(B),B}function IG(j){let{collection:K,filter:B,queryEmbedding:_,topK:q}=j,k=_.length,C=v(K,k);if(!C)return null;let L=Q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(L===0)return[];let s=JSON.stringify(_),y=Math.min(L,Math.max(q,B?q*4:q));while(y>0){let h=W.query(`SELECT rowid, distance
FROM ${c(C)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,y),S=[];for(let WG of h){let r=x.get(K,WG.rowid);if(!r)continue;let LG=V(r.embedding_json),XG=V(r.metadata_json);if(!YG(XG,B))continue;S.push({id:r.id,embedding:LG,metadata:XG,content:r.content,score:1/(1+Number(WG.distance))})}if(!B||S.length>=q||y>=L)return S.slice(0,q);y=Math.min(L,y*2)}return[]}return{async upsert(j,K){if(Y?.readOnly)throw f("vector");W.transaction((_)=>{let q=z();for(let k of _){let C=I.get(j,k.id),L=C?V(C.embedding_json).length:null,s=JSON.stringify(k.embedding);if(P.run(j,k.id,s,JSON.stringify(k.metadata),k.content),!q){if(C&&L!==null&&L!==k.embedding.length)R(j,L);R(j,k.embedding.length);continue}let y=I.get(j,k.id);if(!y)continue;if(C&&L!==null&&L!==k.embedding.length){let S=v(j,L);if(S)i(W,S,C.rowid)}let h=v(j,k.embedding.length);if(!h)continue;MG({database:W,embeddingJson:s,rowid:y.rowid,tableName:h})}})(K)},async get(j,K){if(!A)return null;let B=U.get(j,K);if(!B)return null;return{id:B.id,embedding:V(B.embedding_json),metadata:V(B.metadata_json),content:B.content}},async search(j,K,B){if(B.topK<=0||K.length===0)return[];if(!A)return[];if(X.mode!=="off"&&X.paths?.length&&O().loaded)try{let _=X.backend==="sqlite-vss"?IG({collection:j,filter:B.filter,queryEmbedding:K,topK:B.topK}):(Z?.runExtensionSearch??eG)({collection:j,config:X,database:W,filter:B.filter,queryEmbedding:K,topK:B.topK});if(_!==null)return _;if(X.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(X.mode==="require"){let q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${j}: ${q}`)}}return Q.all(j).map((_)=>{let q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:q,metadata:k,content:_.content,score:iG(q,K)}}).filter((_)=>YG(_.metadata,B.filter)).sort((_,q)=>{if(q.score!==_.score)return q.score-_.score;return _.id.localeCompare(q.id)}).slice(0,B.topK)},async delete(j,K){if(Y?.readOnly)throw f("vector");W.transaction(()=>{let _=I.get(j,K),q=z();if(_&&q){let k=V(_.embedding_json).length,C=v(j,k);if(C)i(W,C,_.rowid)}if(_&&!q){let k=V(_.embedding_json).length;R(j,k)}d.run(j,K)})()}}}
export{OY as Ua,UY as Va,zY as Wa};
import{Za as M,_a as g,ab as x,cb as f,db as v,hb as d,jb as p}from"./chunk-jmsnz9jn.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}
export{XF as Ma,YF as Na,ZF as Oa,a as Pa,_F as Qa,HF as Ra,$F as Sa,DF as Ta};
import{createRequire as p}from"node:module";var D=p(import.meta.url);function c(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function l(e){let t=e.userId.trim();if(t.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:t,tenantId:c(e.tenantId),workspaceId:c(e.workspaceId),agentId:c(e.agentId),sessionId:c(e.sessionId)}}function g(e){let t=l(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId??""].join("::")}function x(e){let t=l(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId].map((o)=>o??"").join("::")}function h(e,t){return g(e)===g(t)}var T="unchanged-delete-v1";function b(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function P(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");d(e.filter)}function M(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");d(e.filter)}function d(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function B(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([r,n])=>o[r]===n)}function w(e,t){return{...e,...t}}var f=/[\p{L}\p{N}]+/gu;function s(e){return(e.normalize("NFKC").toLowerCase().match(f)??[]).filter((t)=>t.length>0)}function k(e){return[...new Set(s(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function C(e){let t=[...new Set(s(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function R(e,t){let o=e[t];return typeof o==="string"?o:void 0}function j(e,t){let o=[...new Set(s(e))];if(o.length===0)return 0;let r=s(t),n=new Map;for(let i of r)n.set(i,(n.get(i)??0)+1);let u=0,m=0;for(let i of o){let a=n.get(i)??0;if(a>0)u+=1,m+=a}if(u===0)return 0;return u/o.length+m/Math.max(1,r.length)}
export{D as Xa,l as Ya,g as Za,x as _a,h as $a,T as ab,b as bb,P as cb,M as db,d as eb,B as fb,w as gb,s as hb,k as ib,C as jb,R as kb,j as lb};
import{Ua as a,Va as b,Wa as c}from"./chunk-djzzs7r6.js";import"./chunk-jmsnz9jn.js";export{c as createSQLiteVectorStore,b as createSQLiteSessionStore,a as createSQLiteDocumentStore};

Sorry, the diff of this file is too big to display

import{Ma as a,Na as b,Oa as c,Pa as d,Qa as e,Ra as f,Sa as g,Ta as h}from"./chunk-gqbzz1dr.js";import"./chunk-jmsnz9jn.js";export{g as probeReadOnlyPostgresStorageBackend,e as migratePostgresStorageBackend,d as getPostgresVectorExtensionStatus,f as ensurePostgresStorageBackend,c as createPostgresVectorStore,b as createPostgresSessionStore,a as createPostgresDocumentStore,h as canBootstrapPostgresStorageBackend};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import{createRequire as s}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,t=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var u=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var v=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var x=s(import.meta.url);
export{t as ac,u as bc,v as cc,x as dc};
var g="unchanged-delete-v1";function p(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function f(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");a(e.filter)}function d(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");a(e.filter)}function a(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function S(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([n,r])=>o[n]===r)}function D(e,t){return{...e,...t}}var l=/[\p{L}\p{N}]+/gu;function i(e){return(e.normalize("NFKC").toLowerCase().match(l)??[]).filter((t)=>t.length>0)}function h(e){return[...new Set(i(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function y(e){let t=[...new Set(i(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function T(e,t){let o=e[t];return typeof o==="string"?o:void 0}function b(e,t){let o=[...new Set(i(e))];if(o.length===0)return 0;let n=i(t),r=new Map;for(let c of n)r.set(c,(r.get(c)??0)+1);let s=0,u=0;for(let c of o){let m=r.get(c)??0;if(m>0)s+=1,u+=m}if(s===0)return 0;return s/o.length+u/Math.max(1,n.length)}
export{g as Kb,p as Lb,f as Mb,d as Nb,a as Ob,S as Pb,D as Qb,i as Rb,h as Sb,y as Tb,T as Ub,b as Vb};
function r(n){if(n===void 0)return;let e=n.trim();return e.length>0?e:void 0}function t(n){let e=n.userId.trim();if(e.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:e,tenantId:r(n.tenantId),workspaceId:r(n.workspaceId),agentId:r(n.agentId),sessionId:r(n.sessionId)}}function o(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId??""].join("::")}function d(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId].map((i)=>i??"").join("::")}function s(n,e){return o(n)===o(e)}
export{t as Wb,o as Xb,d as Yb,s as Zb};
import{Aa as i,Ba as n,Da as t,pa as _,qa as L}from"./chunk-m9yws3j1.js";import{Ha as e,Ia as QQ}from"./chunk-ftxc0stx.js";import{db as p,eb as u,gb as w,ib as a,yb as q}from"./chunk-g7hv64gy.js";import{Jb as m}from"./chunk-b7j2aytn.js";import{Xb as k}from"./chunk-36sxnybm.js";import{createHash as TQ}from"node:crypto";import{createHmac as HQ}from"node:crypto";var GQ=24,UQ=1200,R=100,f=new Set(["profile","preference","fact","feedback","episode","evidence","experience","reference","archive","proposal","promotion","runtime-journal","runtime-spill","writeback-event"]);function WQ(Q){if(!f.has(Q.recordKind))throw Error(`Unsupported GoodMemory record kind: ${Q.recordKind}`);if(!Q.scopeDigest||Q.scopeDigest.includes(":"))throw Error("GoodMemory recordRef requires a non-empty colon-free scopeDigest.");if(!Q.id)throw Error("GoodMemory recordRef requires a non-empty id.");return`gmrec:v1:${Q.scopeDigest}:${Q.recordKind}:${encodeURIComponent(Q.id)}`}function JQ(Q){let Z=/^gmrec:v1:([^:]+):([^:]+):(.+)$/u.exec(Q);if(!Z)return null;let[,$,H,W]=Z;if(!f.has(H))return null;try{return{id:decodeURIComponent(W),recordKind:H,scopeDigest:$}}catch{return null}}function b(Q){return`scope_${HQ("sha256",Q.secret).update(k(Q.scope)).digest("hex").slice(0,32)}`}function x(Q){if(Q.scopeDigestSecret.trim().length<16)throw Error("ProgressiveRecallService requires a stable scopeDigestSecret.");let Z=Q.maxDetailPreviewChars??UQ,$=Q.now??(()=>new Date),H=Q.language??q(Q.memory)?.language;if(!H)throw Error("ProgressiveRecallService requires the memory LanguageService.");let W=H,Y=W.resolveFromText({text:""}),O=new Map;async function j(U){let K=U.retrievalProfile??(U.includeRuntime===!0?"coding_agent":void 0),N=await Q.memory.recall({retrievalProfile:K,locale:U.locale,query:U.query??"",scope:U.scope}),J=b({scope:U.scope,secret:Q.scopeDigestSecret}),X=N.metadata.locale??U.locale??Y.locale;return{candidates:XQ({includeRuntime:U.includeRuntime,language:W,locale:X,maxDetailPreviewChars:Z,recall:N,scope:U.scope}),generatedAt:$().toISOString(),locale:X,scopeDigest:J}}function M(U){let K=O.get(U.scopeDigest)??new Map;if(U.includeRuntime!==!0){for(let[J,X]of K)if(X.candidate.source==="runtime")K.delete(J)}let N=$().getTime();for(let J of U.selected)K.set(J.record.recordRef,{candidate:J.candidate,lastSeenAt:N});OQ(K),O.set(U.scopeDigest,K)}async function G(U){let{candidates:K,generatedAt:N,locale:J,scopeDigest:X}=await j({includeRuntime:U.includeRuntime,locale:U.locale,query:U.query,retrievalProfile:U.retrievalProfile,scope:U.scope}),V=K.map((B)=>({candidate:B,record:BQ({candidate:B,language:W,locale:J,query:U.query,scopeDigest:X})})).sort((B,P)=>AQ(B.record,P.record)),A=NQ({limit:U.limit??GQ,ranked:V});return M({includeRuntime:U.includeRuntime,scopeDigest:X,selected:A}),{generatedAt:N,locale:J,query:U.query,records:A.map((B)=>B.record),scopeDigest:X,totalRecordCount:K.length}}async function z(U){let K=await G(U),N=U.recordsPerBucket??6,J=new Map;for(let X of K.records){let V=DQ(X.occurredAt,W,K.locale??Y.locale),A=J.get(V)??[];if(A.length<N)A.push(X);J.set(V,A)}return{buckets:Array.from(J,([X,V])=>({label:X,records:V})),locale:K.locale,scopeDigest:K.scopeDigest,totalRecordCount:K.totalRecordCount}}async function F(U){let K=b({scope:U.scope,secret:Q.scopeDigestSecret}),N=O.get(K)??new Map,J=[];for(let X of U.recordRefs){let V=JQ(X);if(!V)throw Error(`Invalid GoodMemory recordRef: ${X}`);if(V.scopeDigest!==K)throw Error(`GoodMemory recordRef ${X} does not belong to the requested scope.`);let A=N.get(X);if(!A)throw Error(`GoodMemory recordRef ${X} is not available in the current progressive recall visibility set.`);let B=A.candidate,P={occurredAt:B.occurredAt,recordKind:B.recordKind,recordRef:X,title:B.title,summary:B.summary,detail:B.detail,estimatedTokens:_(JSON.stringify(B.detail))};J.push(P)}return{records:J,scopeDigest:K}}return{searchRecallIndex:G,buildRecallTimeline:z,getProgressiveRecords:F,renderProgressiveContext(U){let K=U.maxRecords??10,N=U.maxTokens?Math.max(1,Math.floor(U.maxTokens)):void 0,J=U.index.records.slice(0,K),X=U.index.locale??Y.locale,V=KQ(U,Boolean(N),W,X),A=[];for(let $Q of J){let T=zQ({header:V,lines:A,maxTokens:N,record:$Q,recordIndex:A.length,language:W,locale:X});if(!T)break;A.push(T)}let B=Math.max(0,U.index.records.length-A.length),P=B>0&&!I({header:V,lines:A,maxTokens:N,footer:[W.render({key:"omitted_records",values:{count:B}},X)]})?[W.render({key:"omitted_records",values:{count:B}},X)]:[],ZQ=[...V,...A,...P].join(`
`),h=VQ(ZQ,N);return{content:h,estimatedTokens:_(h),omittedRecordCount:B}}}}function XQ(Q){let Z=[],$=(Y,O)=>Q.language.render(O?{key:Y,values:O}:{key:Y},Q.locale),H=(Y)=>{Z.push(jQ(Y,Q.scope,Q.maxDetailPreviewChars))},W=Q.recall.profile;if(W)H({detail:{activeContext:W.activeContext,expertise:W.expertise,identity:v(W.identity,Q.scope),version:W.version},id:"profile",occurredAt:W.updatedAt,recordKind:"profile",source:"durable",summary:[...W.activeContext.goals,...W.activeContext.currentProjects].join("; "),title:$("profile")});for(let Y of Q.recall.preferences)H({detail:{category:Y.category,confidence:Y.confidence,lifecycle:Y.lifecycle,tags:Y.tags,value:Y.value},id:Y.id,occurredAt:Y.updatedAt,recordKind:"preference",source:"durable",summary:MQ(Y.value),title:`${$("preference")}: ${Y.category}`});for(let Y of Q.recall.facts)H({detail:{category:Y.category,confidence:Y.confidence,content:Y.content,factKind:Y.factKind,importance:Y.importance,lifecycle:Y.lifecycle,subject:Y.subject,tags:Y.tags},id:Y.id,occurredAt:Y.updatedAt,recordKind:"fact",source:"durable",summary:Y.content,title:qQ($("fact_item"),Y.subject??Y.category)});for(let Y of Q.recall.feedback)H({detail:{appliesTo:Y.appliesTo,confidence:Y.confidence,kind:Y.kind,lifecycle:Y.lifecycle,rule:Y.rule,tags:Y.tags,why:Y.why},id:Y.id,occurredAt:Y.updatedAt,recordKind:"feedback",source:"durable",summary:Y.rule,title:`${$("feedback")}: ${Y.kind}`});for(let Y of Q.recall.references)H({detail:{confidence:Y.confidence,description:Y.description,pointer:Y.pointer,referenceKind:Y.referenceKind,subject:Y.subject,tags:Y.tags,title:Y.title},id:Y.id,occurredAt:Y.updatedAt,recordKind:"reference",source:"durable",summary:Y.description??Y.pointer,title:Y.title});for(let Y of Q.recall.episodes)H({detail:{confidence:Y.confidence,keyDecisions:Y.keyDecisions,summary:Y.summary,topics:Y.topics,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt??Y.createdAt,recordKind:"episode",source:"durable",summary:Y.summary,title:$("episode_item")});for(let Y of Q.recall.archives)H({detail:{keyDecisions:Y.keyDecisions,referencedArtifacts:Y.referencedArtifacts,sourceSessionCount:Y.sourceSessionIds.length,summary:Y.summary,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt,recordKind:"archive",source:"durable",summary:Y.summary,title:Y.summary});for(let Y of Q.recall.evidence)H({detail:{excerpt:Y.excerpt,kind:Y.kind,linkedArchiveIds:Y.linkedArchiveIds,linkedMemoryIds:Y.linkedMemoryIds,sourceUri:Y.sourceUri},id:Y.id,occurredAt:Y.createdAt,recordKind:"evidence",source:"durable",summary:Y.excerpt,title:`${$("evidence")}: ${Y.kind}`});if(Q.includeRuntime===!0&&Q.recall.journal){let Y=Q.recall.journal;H({detail:{currentState:Y.currentState,errorsAndCorrections:Y.errorsAndCorrections,filesAndFunctions:Y.filesAndFunctions,keyResults:Y.keyResults,learnings:Y.learnings,taskSpecification:Y.taskSpecification,title:Y.title,workflow:Y.workflow,worklog:Y.worklog},id:"current",occurredAt:Y.updatedAt,recordKind:"runtime-journal",source:"runtime",summary:Y.currentState??Y.title??Y.worklog[0]??$("journal"),title:Y.title??$("journal")})}if(Q.includeRuntime===!0&&Q.recall.workingMemory){let Y=Q.recall.workingMemory;H({detail:{constraints:Y.constraints,currentGoal:Y.currentGoal,openLoops:Y.openLoops,state:Y.state,temporaryDecisions:Y.temporaryDecisions,toolState:Y.toolState},id:"working-memory",occurredAt:Y.updatedAt,recordKind:"runtime-journal",required:!0,source:"runtime",summary:[Y.currentGoal?`${$("current_goal")}: ${Y.currentGoal}`:void 0,Y.openLoops.length>0?`${$("open_loops")}: ${Y.openLoops.join(", ")}`:void 0].filter(SQ).join("; ")||$("working_memory"),title:$("working_memory")})}return Z}function KQ(Q,Z,$,H){if(Z)return[$.render({key:"progressive_recall"},H),`scopeDigest: ${Q.index.scopeDigest}`,$.render({key:"progressive_detail_instruction_compact"},H)];return[$.render({key:"progressive_recall"},H),`query: ${Q.query??Q.index.query??$.render({key:"none"},H)}`,`scopeDigest: ${Q.index.scopeDigest}`,`retrievalProfile: ${Q.retrievalProfile??$.render({key:"default_label"},H)}`,$.render({key:"progressive_detail_instruction"},H)]}function NQ(Q){let Z=Math.max(1,Math.floor(Q.limit)),$=new Map;for(let H of Q.ranked)if(H.candidate.required)$.set(H.record.recordRef,H);for(let H of Q.ranked){if($.size>=Z)break;$.set(H.record.recordRef,H)}return Array.from($.values()).slice(0,Z)}function zQ(Q){let Z=Q.maxTokens?[160,96,48,0]:[260];for(let $ of Z){let H=FQ({record:Q.record,recordIndex:Q.recordIndex,summaryMaxChars:$,language:Q.language,locale:Q.locale});if(!I({header:Q.header,lines:[...Q.lines,H],maxTokens:Q.maxTokens}))return H}return null}function FQ(Q){let Z=[`${Q.recordIndex+1}. ${Q.record.title}`,`${Q.language.render({key:"record_kind"},Q.locale)}: ${Q.record.recordKind}`,`${Q.language.render({key:"record_ref"},Q.locale)}: ${Q.record.recordRef}`];if(Q.summaryMaxChars>0)Z.push(`${Q.language.render({key:"summary"},Q.locale)}: ${E(Q.record.summary,Q.summaryMaxChars)}`);return Z.push(`${Q.language.render({key:"detail_tokens"},Q.locale)}: ${Q.record.estimatedDetailTokens}`),Z.join(" | ")}function I(Q){if(!Q.maxTokens)return!1;return _([...Q.header,...Q.lines,...Q.footer??[]].join(`
`))>Q.maxTokens}function VQ(Q,Z){if(!Z||_(Q)<=Z)return Q;let $="...",H=_($);if(Z<=H)return L(Q,Z);return`${L(Q,Z-H).trimEnd()}${$}`}function BQ(Q){let Z=E(Q.candidate.summary,260),$=E(Q.candidate.title,120),H=WQ({id:Q.candidate.id,recordKind:Q.candidate.recordKind,scopeDigest:Q.scopeDigest}),W=[$,Z].join(" ");return{estimatedDetailTokens:_(JSON.stringify(Q.candidate.detail)),estimatedIndexTokens:_(W),occurredAt:Q.candidate.occurredAt,recordKind:Q.candidate.recordKind,recordRef:H,score:LQ(W,Q.query,Q.language,Q.locale),source:Q.candidate.source,summary:Z,title:$}}function AQ(Q,Z){if(Z.score!==Q.score)return Z.score-Q.score;return y(Z.occurredAt)-y(Q.occurredAt)}function OQ(Q){if(Q.size<=R)return;let Z=new Set(Array.from(Q).sort(($,H)=>H[1].lastSeenAt-$[1].lastSeenAt).slice(0,R).map(([$])=>$));for(let $ of Q.keys())if(!Z.has($))Q.delete($)}function jQ(Q,Z,$){return{...Q,detail:_Q(v(Q.detail,Z),$),summary:D(Q.summary,Z),title:D(Q.title,Z)}}function v(Q,Z){return S(Q,Z)}function S(Q,Z){if(typeof Q==="string")return D(Q,Z);if(Array.isArray(Q))return Q.map(($)=>S($,Z));if(Q&&typeof Q==="object"){let $={};for(let[H,W]of Object.entries(Q)){if(PQ(H)||H==="normalizedTranscript")continue;$[H]=S(W,Z)}return $}return Q}function _Q(Q,Z){let $=JSON.stringify(Q);if($.length<=Z)return Q;return{preview:`${$.slice(0,Z)}...`,truncated:!0}}function PQ(Q){return["agentId","scope","scopeLineage","sessionId","sourceSessionIds","tenantId","userId","workspaceId"].includes(Q)}function D(Q,Z){let $=[[Z.userId,"[user]"],[Z.tenantId,"[tenant]"],[Z.workspaceId,"[workspace]"],[Z.agentId,"[agent]"],[Z.sessionId,"[session]"]],H=Q;for(let[W,Y]of $){if(!W)continue;H=H.split(W).join(Y)}return H}function qQ(Q,Z){return`${Q}: ${Z}`}function MQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function E(Q,Z){let $=Q.trim();if($.length<=Z)return $;return`${$.slice(0,Z-3).trimEnd()}...`}function LQ(Q,Z,$,H){let W=$.tokenize(Z??"",H,{excludeStopwords:!0});if(W.length===0)return 0;let Y=new Set($.tokenize(Q,H,{excludeStopwords:!0}));return W.reduce((O,j)=>O+(Y.has(j)?1:0),0)}function y(Q){if(!Q)return 0;let Z=Date.parse(Q);return Number.isNaN(Z)?0:Z}function SQ(Q){return Q!==void 0}function DQ(Q,Z,$){if(!Q)return Z.render({key:"undated"},$);let H=Date.parse(Q);if(Number.isNaN(H))return Z.render({key:"undated"},$);return new Date(H).toISOString().slice(0,10)}var EQ=/sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9_]{16,}/u,wQ=/\[redacted-(?:email|url-auth)\]/gu,g=m();function CQ(Q,Z=g){let $=Z.resolveFromText({text:Q});return hQ(Q,Z.analyzeContent(Q,$))}function hQ(Q,Z){return EQ.test(Q)||Z.sensitiveCredential}function d(Q,Z=g){if(!CQ(Q,Z))return Q;return[...new Set([...Q.match(wQ)??[],"[redacted-secret]"])].join(" ")}var RQ=160,bQ=10,yQ=240;function C(Q){let Z=Q?.trim();return Z?Z:null}function s(Q){for(let Z=Q.length-1;Z>=0;Z-=1){let $=Q[Z];if($?.role!=="user")continue;let H=C($.content);if(H)return H}return null}function kQ(Q,Z){if(Q.length<=Z)return Q;return`${Q.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function YQ(Q,Z){return kQ(d(Q.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[redacted-email]").replace(/\bsk-[A-Za-z0-9_-]{6,}\b/gu,"[redacted-secret]"),Z).replace(/\s+/gu," ").trim(),yQ)}function fQ(Q){let Z=[Q.userText?`user: ${Q.userText}`:void 0,Q.assistantText?`assistant: ${Q.assistantText}`:void 0].filter(($)=>Boolean($));if(Z.length===0)return null;return YQ(Z.join(" | "),Q.language)}function c(Q){return{kind:"remember_candidate",preview:Q.preview,rawTranscriptPersisted:!1,reason:Q.reason}}function o(Q){return{jobId:`runtime-kit-candidate-${TQ("sha256").update(Q).digest("hex").slice(0,16)}`,operation:"remember",payloadPreview:Q,rawTranscriptPersisted:!1,reason:"after_model_call",status:"candidate"}}function r(Q){return Q?.mode==="selective"&&Q.annotation==="durable_candidate"&&Q.policy==="allow"}function xQ(Q){return{scope:Q.scope,locale:Q.locale,messages:[{role:"user",content:Q.userText},{role:"assistant",content:Q.assistantText}],annotations:[{messageIndex:1,remember:"always",confirmed:!0,reason:"runtime-kit selective writeback approved by host annotation and policy"}]}}function l(Q){return{mode:Q,content:"",estimatedTokens:0,omittedSections:[]}}function IQ(Q){return{mode:"fragment",content:Q.builtContext.content,estimatedTokens:Q.builtContext.estimatedTokens,omittedSections:[...Q.builtContext.omittedSections]}}function vQ(Q){let Z=p({appliesTo:Q.retrievalProfile==="coding_agent"?"coding_agent":"general_response",feedback:Q.feedback,query:Q.query,surface:"text_response"}),$=u(Z),H=[...w($),...w(Q.rawCarryover?.packet?.textResponsePlan)],W=a(Z.filter(({policy:O})=>O.enactmentSurface!=="text_response"||!O.applicability.textResponsePlan));if(H.length===0&&W.length===0&&!Q.rawCarryover?.packet?.promptPayload)return IQ({builtContext:Q.builtContext});if(Q.rawCarryover?.debug.mode==="exemplar_only"&&H.length===0&&W.length===0&&Q.rawCarryover.packet?.promptPayload)return{mode:"fragment",content:Q.rawCarryover.packet.promptPayload,estimatedTokens:_(Q.rawCarryover.packet.promptPayload),omittedSections:[]};let Y=[Q.builtContext.content,Q.rawCarryover?.packet?.promptPayload,H.length>0?["Structured response control:","Apply the following controls implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...H].join(`
`):void 0,W.length>0?["Behavioral steering:","Apply the following guidance implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...W].join(`
`):void 0].filter((O)=>typeof O==="string"&&O.trim().length>0).join(`
`);return{mode:"fragment",content:Y,estimatedTokens:_(Y),omittedSections:[...Q.builtContext.omittedSections]}}function mQ(Q){if(Q.progressiveRecall)return Q.progressiveRecall;if(!Q.progressive)return null;return x({memory:Q.memory,scopeDigestSecret:Q.progressive.scopeDigestSecret,maxDetailPreviewChars:Q.progressive.maxDetailPreviewChars})}async function gQ(Q,Z){if(!Q)return;try{await Q(Z)}catch($){console.error("GoodMemory runtime-kit event callback failed.",$)}}function dQ(Q){return e({id:`${Q.hostKind}-runtime-kit`,hostKind:Q.hostKind,memory:Q.memory})}function GY(Q){let Z=q(Q.memory)?.language,$=mQ(Q),H=Q.defaultContextMode??"fragment",W=Q.defaultMaxMemoryTokens??RQ,Y=t({scopeDigestSecret:Q.scopeDigestSecret??Q.progressive?.scopeDigestSecret},()=>new Date);async function O(G){return await gQ(Q.onRuntimeEvent,G),G}async function j(G,z){return await O({...z,scopeDigest:Y.digestScope(G)})}async function M(G,z){let F=await Q.memory.recall({scope:G.scope,query:z,locale:G.locale,retrievalProfile:G.retrievalProfile,ignoreMemory:!1,...Q.evidenceLedgerFormat?{includeEvidence:!0}:{}}),U=await Q.memory.buildContext({recall:F,output:"system_prompt_fragment",maxTokens:G.maxMemoryTokens??W,...Q.evidenceLedgerFormat?{evidenceLedgerFormat:Q.evidenceLedgerFormat}:{}}),K=await(async()=>{try{let N=G.includeRuntime===!1?null:await Q.memory.runtime.getState({scope:G.scope}).catch(()=>null),J=await Q.memory.exportMemory({includeRuntime:G.includeRuntime,scope:G.scope}),X=(G.retrievalProfile??"general_chat")==="coding_agent"?"host_action":"text_response",V=N?.state?.buffer?.messages?.map((B)=>({content:B.content,role:B.role})).filter((B)=>B.content.trim().length>0)??[],A=i({memoryExport:{durable:{archives:J.durable.archives,episodes:J.durable.episodes,experiences:J.durable.experiences},scope:J.scope},recallHints:{candidateTraces:F.metadata.candidateTraces,hits:F.metadata.hits},runtimeMessages:V,surfaceHint:X});return n({index:A,maxExemplars:X==="host_action"?4:3,query:z,surfaceFamily:X})}catch{return}})();return{context:vQ({builtContext:U,feedback:F.feedback,query:z,rawCarryover:K,retrievalProfile:G.retrievalProfile??"general_chat"}),recall:F}}return{async sessionStart(G){let z=await Q.memory.runtime.startSession({scope:G.scope}),F=await j(G.scope,{phase:"sessionStart",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async beforeModelCall(G){let z=G.contextMode??H;if(G.ignoreMemory){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"ignore_memory",contextMode:z});return{context:l(z),events:[N]}}let F=C(G.query)??s(G.messages??[]);if(!F){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"no_query",contextMode:z});return{context:l(z),events:[N]}}if(z==="progressive"&&$){let N=await $.searchRecallIndex({scope:G.scope,query:F,includeRuntime:G.includeRuntime,retrievalProfile:G.retrievalProfile}),J=$.renderProgressiveContext({index:N,query:F,retrievalProfile:G.retrievalProfile,maxRecords:G.maxProgressiveRecords??bQ,maxTokens:G.maxMemoryTokens??W}),X=await j(G.scope,{phase:"beforeModelCall",status:J.content.trim()?"applied":"skipped",reason:J.content.trim()?void 0:"empty_context",contextMode:"progressive"});return{context:{mode:"progressive",content:J.content,estimatedTokens:J.estimatedTokens,omittedSections:J.omittedRecordCount>0?[`records:${J.omittedRecordCount}`]:[],recordRefs:N.records.map((V)=>V.recordRef)},events:[X]}}let U=await M(G,F),K=await j(G.scope,{phase:"beforeModelCall",status:U.context.content.trim()?"applied":"skipped",reason:U.context.content.trim()?void 0:"empty_context",contextMode:"fragment",fallbackReason:z==="progressive"?"progressive_unavailable":void 0});return{context:U.context,recall:U.recall,events:[K]}},async afterModelCall(G){let z=G.writeback??{mode:"observe"},F=z.mode??"observe",U=C(G.assistantText),K=s(G.messages),N=fQ({assistantText:U,language:Z,userText:K}),J=[],X=[],V;if(F==="observe"&&N)J.push(c({preview:N,reason:"observe"})),X.push(o(N));else if(F==="selective"&&!r(z)&&N)J.push(c({preview:N,reason:"selective_not_allowed"})),X.push(o(N));else if(r(z)&&U&&K)V=await Q.memory.remember(xQ({scope:G.scope,locale:G.locale,userText:K,assistantText:U}));let A=await j(G.scope,{phase:"afterModelCall",status:V||J.length>0?"applied":"skipped",reason:F==="off"?"writeback_off":V||J.length>0?void 0:"no_candidate"});return{boundedJobs:X,candidates:J,events:[A],...V?{rememberResult:V}:{},trace:{candidateCount:J.length,rawTranscriptPersisted:!1,rememberCalled:Boolean(V)}}},async sessionEnd(G){let z=await Q.memory.runtime.endSession({scope:G.scope,archive:G.archive??"off"}),F=await j(G.scope,{phase:"sessionEnd",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async preAction(G){let F=await(Q.hostAdapter??dQ({hostKind:G.intent.hostKind,memory:Q.memory})).assessAction(G.intent),U=QQ({assessment:F,intent:G.intent}),K=await j(G.intent.scope,{phase:"preAction",status:"applied",reason:F.decision});return{assessment:F,executionPlan:U,events:[K]}},async observeToolResult(G){let z=YQ(`${G.toolName}: ${G.summary}`,Z),F=await Q.memory.runtime.updateSessionJournal({scope:G.scope,patch:{appendWorklog:[z]}}),U=await j(G.scope,{phase:"observeToolResult",status:"applied"});return{journal:F.journal,events:[U]}}}}
export{GY as oa};
import{_b as a}from"./chunk-shxj1q4b.js";import"./chunk-9bjprkrs.js";import"./chunk-14dkxqxk.js";export default a();
import{bc as I}from"./chunk-14dkxqxk.js";var X=I((Y,H)=>{var{defineProperty:z,getOwnPropertyDescriptor:K,getOwnPropertyNames:L}=Object,Q=Object.prototype.hasOwnProperty,R=(j,b)=>{for(var v in b)z(j,v,{get:b[v],enumerable:!0})},U=(j,b,v,B)=>{if(b&&typeof b==="object"||typeof b==="function"){for(let q of L(b))if(!Q.call(j,q)&&q!==v)z(j,q,{get:()=>b[q],enumerable:!(B=K(b,q))||B.enumerable})}return j},W=(j)=>U(z({},"__esModule",{value:!0}),j),F={};R(F,{VercelOidcTokenError:()=>G});H.exports=W(F);class G extends Error{constructor(j,b){super(j);this.name="VercelOidcTokenError",this.cause=b}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});
export{X as $b};

Sorry, the diff of this file is too big to display

import{_b as V}from"./chunk-shxj1q4b.js";import{$b as U}from"./chunk-9bjprkrs.js";import{bc as R}from"./chunk-14dkxqxk.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
import{Jb as K}from"./chunk-b7j2aytn.js";var C=K(),P="semantic_recall_inactive",_="semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET";function JB(B){let $=[...B.existingMessages??[]];for(let J of B.warnings??[])if(J===P&&!$.includes(_))$.push(_);return $}function q(B){return B??"general_chat"}function A(B){let $=B.strategy??"auto",J=B.availability?.semanticSearch===!0,Z=B.availability?.llmRouting===!0;if($==="auto"){let j=Boolean(B.autoSignals&&(B.autoSignals.retrievalProfile==="coding_agent"||B.autoSignals.continuation||B.autoSignals.referenceSeeking||B.autoSignals.actionDriving||B.autoSignals.requestedSlots.some((k)=>k==="blocker"||k==="open_loop"||k==="reference")||B.autoSignals.supportSlots.includes("project_state_support")));if(J&&(B.autoStrategyBias==="hybrid"||j))return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:j?"auto routing enabled hybrid recall because the query needs continuation, references, or action-driving semantic support while keeping rules-first priorities as the hard floor.":"auto routing enabled hybrid recall because the recommended retrieval preset biases auto routing to hybrid whenever semantic search is available, keeping rules-first priorities as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",...B.autoStrategyBias==="hybrid"?{warningMessages:[_],warnings:[P]}:{},summary:J?"auto routing kept deterministic rules-only recall because the query is profile/procedural/general assistance and does not need semantic tie-breaking.":"auto routing kept deterministic rules-only recall because semantic search is unavailable.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if($==="rules-only")return{requestedStrategy:$,resolvedStrategy:"rules-only",summary:"rules-only default keeps lexical, runtime, and procedural priors as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1};if($==="hybrid"){if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:"hybrid routing keeps rules-first priorities primary and only enables semantic tie-breaking around them.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"semantic_search_unavailable",warningMessages:[_],warnings:[P],summary:"hybrid routing was requested but semantic search is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if(Z)return{requestedStrategy:$,resolvedStrategy:"llm-assisted",summary:"llm-assisted routing keeps rules-first priorities primary and only allows model refinement after the deterministic floor is established.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:J,llmRefinement:!0};if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but model refinement is unavailable, so routing falls back to hybrid semantic tie-breaking.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but provider-backed assistance is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}function ZB(B){let $=q(B.retrievalProfile),J=B.language??C,Z=B.locale??J.resolveFromText({text:B.query}).locale,j=B.queryAnalysis??J.analyzeQuery(B.query,Z),X=$==="coding_agent"||j.continuation,k=j.role,W=j.focus,V=j.blocker,O=j.openLoop,D=j.referenceSeeking,Q=j.actionDriving,h=[];if(k)h.push("role");if(W)h.push("focus");if(V)h.push("blocker");if(O)h.push("open_loop");if(D)h.push("reference");let w=[];if(Q&&(h.includes("role")||h.includes("focus")||h.includes("reference")))w.push("project_state_support");if(X)w.push("runtime_continuity");let G=A({strategy:B.strategy,autoStrategyBias:B.autoStrategyBias,availability:B.availability,autoSignals:{retrievalProfile:$,requestedSlots:h,supportSlots:w,continuation:X,referenceSeeking:D,actionDriving:Q}}),R=X||Q||D?["evidence"]:[];if(X)return{retrievalProfile:$,intent:"task_continuation",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["working_memory","session_journal","session_archive","episode","fact",...R,"feedback","profile"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X};return{retrievalProfile:$,intent:"general_assistance",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["profile","feedback","fact",...R,"episode","working_memory","session_journal"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X}}class N extends Error{stage;constructor(B){super(`Provider-backed recall failed during ${B.stage}.`,{cause:B.cause});this.name="ProviderBackedRecallError",this.stage=B.stage}}function XB(B){return B instanceof N}import{resolve as L}from"node:path";var b=["openai","anthropic"];function T(B){return b.includes(B)}var S=Symbol.for("goodmemory.embedding.hashed-lexical");function x(B){let $=B.extraction?.mode,J=$==="conversational"?"conversational":"default";if(B.retrieval?.preset===void 0)return{extractionMode:J,...B.providerRerankerConfigured?{providerRerankingStrategy:"pointwise"}:{},retrieval:{bm25Ranking:B.retrieval?.bm25Ranking,semanticCandidates:B.retrieval?.semanticCandidates}};if(B.adapters?.embeddingAdapter?.[S]===!0)throw Error(`retrieval.preset "recommended" accepts either no embedding adapter or a neural semantic adapter; createLocalEmbeddingAdapter() produces hashed-lexical vectors and would duplicate the preset's lexical channel as fake dense evidence. Remove that adapter, configure a neural endpoint (GOODMEMORY_EMBEDDING_* or providers.embedding), or remove retrieval.preset.`);let j=B.retrieval.semanticCandidates,X=B.embeddingEnabled?{...j,topK:j?.topK??16}:j,k={...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},...B.retrieval.generalizedFusionEntityPageRank!==void 0?{entityPageRank:B.retrieval.generalizedFusionEntityPageRank}:{},maxCandidates:8,maxTotalFacts:10},W=B.providerRerankerConfigured||B.adapters?.reranker?{...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},...B.retrieval.generalizedFusionEntityPageRank!==void 0?{entityPageRank:B.retrieval.generalizedFusionEntityPageRank}:{},maxCandidates:32,maxTotalFacts:32}:void 0,V=J,O;if($!==void 0)O=$==="conversational"?"conversational":"kept_existing";else if(B.adapters?.assistedExtractor)O="kept_existing";else if(B.assistedExtractorModelConfigured)V="conversational",O="conversational";else O="unavailable";return{extractionMode:V,...B.providerRerankerConfigured?{providerRerankingStrategy:"listwise"}:{},retrieval:{autoStrategyBias:"hybrid",bm25Ranking:B.retrieval.bm25Ranking,generalizedFusion:k,preset:{active:!0,extraction:O,requested:"recommended"},...W?{rerankGeneralizedFusion:W}:{},semanticCandidates:X}}}var y=".goodmemory/memory.sqlite",f="GOODMEMORY_STORAGE_PROVIDER",m="GOODMEMORY_STORAGE_URL",H="GOODMEMORY_EMBEDDING",z="GOODMEMORY_ASSISTED_EXTRACTOR";function Y(B){if(!B)return;let $=B.trim();return $.length>0?$:void 0}function c(B){return B?.provider!==void 0||Y(B?.url)!==void 0}function v(B){return Boolean(B?.assistedExtractor||B?.documentStore||B?.embeddingAdapter||B?.reranker||B?.recallPlanner||B?.sessionStore||B?.vectorStore)}function g(B){let $=[];if(B?.documentStore)$.push("documentStore");if(B?.sessionStore)$.push("sessionStore");if(B?.vectorStore)$.push("vectorStore");return $}function U(B){let $=B;if($===void 0||$==="memory"||$==="sqlite"||$==="postgres")return $;throw Error(`Unsupported storage provider: ${$}. Expected memory|sqlite|postgres.`)}function d(B,$){let J=Y(B?.url);if(B?.provider!==void 0||J!==void 0)return{provider:U(B?.provider),url:J};return{provider:U(Y($[f])),url:Y($[m])}}function l(){return typeof globalThis.Bun<"u"}function s(){return typeof globalThis.Bun<"u"}function E(B){let $=B?.builtInSQLite??B?.localDefaultSQLite??l(),J=B?.builtInPostgres??s(),Z=B?.localDefaultSQLite??$;return{builtInPostgres:J,builtInSQLite:$,localDefaultSQLite:Z}}function a(B){return/^(?:postgres|postgresql):\/\//i.test(B.trim())}function F(B,$=process.cwd()){let J=Y(B);if(!J)return L($,y);return J===":memory:"?J:L($,J)}function p(B){let $=B.env??process.env,J=B.cwd??process.cwd(),Z=E(B.runtimeCapabilities).localDefaultSQLite,j=d(B.storage,$),X=j.provider,k=j.url;if(X==="memory")return{mode:"explicit",storage:{provider:"memory"}};if(X==="sqlite")return{mode:"explicit",storage:{provider:"sqlite",url:F(k,J)}};if(X==="postgres"){if(!k)throw Error("Postgres storage provider requires storage.url to be configured.");return{mode:"explicit",storage:{provider:"postgres",url:k}}}if(k&&a(k)){if(!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:k};return{mode:"auto",postgresUrl:k,sqliteUrl:F(void 0,J)}}if(!k&&!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:void 0};return{mode:"auto",postgresUrl:void 0,sqliteUrl:F(k,J)}}function I(B){let $=B.env??process.env,J=E(B.runtimeCapabilities),Z=B.config.adapters?.embeddingAdapter?null:o(B.config.providers?.embedding)??n($),j=B.config.adapters?.assistedExtractor?null:r(B.config.providers?.extraction)??t($),X=B.config.adapters?.reranker?null:u(B.config.providers?.reranking),k=Boolean(B.config.adapters?.embeddingAdapter||Z),W=x({adapters:B.config.adapters,assistedExtractorModelConfigured:Boolean(j),embeddingEnabled:k,extraction:B.config.providers?.extraction,providerRerankerConfigured:Boolean(X),retrieval:B.config.retrieval});return{assistedExtractionEnabled:Boolean(B.config.adapters?.assistedExtractor||j),assistedExtractorModelConfig:j,embeddingEnabled:k,embeddingModelConfig:Z,rerankerModelConfig:X,rerankingEnabled:Boolean(B.config.adapters?.reranker||X),...W.providerRerankingStrategy?{providerRerankingStrategy:W.providerRerankingStrategy}:{},extractionMode:W.extractionMode,retrieval:W.retrieval,explicitAdaptersConfigured:v(B.config.adapters),explicitStorageConfigured:c(B.config.storage),runtimeCapabilities:J,storageAdapterOverrides:g(B.config.adapters),storagePlan:p({storage:B.config.storage,env:$,cwd:B.cwd,runtimeCapabilities:J})}}function u(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0||!$||!J||!Z)throw Error(`Missing required providers.reranking configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported reranking provider: ${$}. Expected one of openai|anthropic.`);return{apiKey:Z,baseURL:j,model:J,provider:$}}function o(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function r(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported extraction provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function n(B=process.env){let $=Y(B[`${H}_PROVIDER`]),J=Y(B[`${H}_MODEL`]),Z=Y(B[`${H}_API_KEY`]),j=Y(B[`${H}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${H}_PROVIDER`:null,!J?`${H}_MODEL`:null,!Z?`${H}_API_KEY`:null].filter(Boolean);if(k.length>0){let D=j&&k.length===1&&!Z?" (local OpenAI-compatible endpoints such as Ollama accept any placeholder value, e.g. GOODMEMORY_EMBEDDING_API_KEY=ollama)":"";throw Error(`Missing required ${H} environment variables: ${k.join(", ")}${D}`)}if(!$||!J||!Z)throw Error(`Missing required ${H} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function t(B=process.env){let $=Y(B[`${z}_PROVIDER`]),J=Y(B[`${z}_MODEL`]),Z=Y(B[`${z}_API_KEY`]),j=Y(B[`${z}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${z}_PROVIDER`:null,!J?`${z}_MODEL`:null,!Z?`${z}_API_KEY`:null].filter(Boolean);if(k.length>0)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported assisted extractor provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}var M=Symbol.for("goodmemory.runtime.info");function e(B){let{runtimeCapabilities:$,storageAdapterOverrides:J,storagePlan:Z}=B;if(J.length>0)return{mode:"adapter",primaryProvider:"adapter",durability:"adapter_defined",overriddenStores:[...J]};if(Z.mode==="explicit"){if(Z.storage.provider==="memory")return{mode:"explicit",primaryProvider:"memory",durability:"ephemeral",postgresConfigured:!1};if(Z.storage.provider==="sqlite"){if(!$.builtInSQLite)return{mode:"explicit",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.storage.url,unavailableReason:"runtime_without_builtin_sqlite"};return{mode:"explicit",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.storage.url}}if(!$.builtInPostgres)return{mode:"explicit",primaryProvider:"postgres",durability:"unavailable",postgresConfigured:!0,unavailableReason:"runtime_without_builtin_postgres"};return{mode:"explicit",primaryProvider:"postgres",durability:"durable",postgresConfigured:!0}}if("sqliteUrl"in Z){if(!Z.postgresUrl&&!$.builtInSQLite)return{mode:"auto",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl,unavailableReason:"runtime_without_builtin_sqlite"};if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"sqlite",durability:"durable",postgresConfigured:!0,sqliteUrl:Z.sqliteUrl};return{mode:"auto",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl}}if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"memory",durability:"conditional",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!0};return{mode:"auto",primaryProvider:"memory",durability:"ephemeral",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!1}}function i(B){return{assistedExtractionEnabled:B.assistedExtractionEnabled,embeddingEnabled:B.embeddingEnabled,explicitAdaptersConfigured:B.explicitAdaptersConfigured,explicitStorageConfigured:B.explicitStorageConfigured,...B.retrieval.preset?{retrievalPreset:B.retrieval.preset}:{},storage:e(B)}}function TB(B){return i(I(B))}function VB(B,$){return B[M]=$,B}function QB(B){return B[M]}
export{P as ca,JB as da,q as ea,A as fa,ZB as ga,N as ha,XB as ia,I as ja,i as ka,TB as la,VB as ma,QB as na};
import{Ma as Or,Ta as br,Xa as Qr,_a as Kr,cb as Sr,db as dr,kb as qr,ob as sr,sb as jr,wb as C,yb as g}from"./chunk-g7hv64gy.js";import{Jb as hr}from"./chunk-b7j2aytn.js";class M extends Error{diagnostics;constructor(r,s){super(r);this.diagnostics=s;this.name="HostAdapterWriteError"}}function L(r){return typeof r==="object"&&r!==null}function yr(r){if(!L(r))return!1;let s=Object.getPrototypeOf(r);return s===null||s===Object.prototype}function V(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r.trim()}function y(r,s){if(r===void 0)return;return V(r,s)}function e(r,s){if(r===null||typeof r==="boolean"||typeof r==="number"||typeof r==="string"){if(typeof r==="number"&&!Number.isFinite(r))throw Error(`${s} must be a JSON-serializable value`);return r}if(Array.isArray(r))return r.map((o,H)=>e(o,`${s}[${H}]`));if(yr(r)){let o={};for(let[H,f]of Object.entries(r)){if(f===void 0)throw Error(`${s}.${H} must not be undefined`);o[H]=e(f,`${s}.${H}`)}return o}throw Error(`${s} must be a JSON-serializable value`)}function Lr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function kr(r,s){let o=V(r,s);if(Number.isNaN(Date.parse(o)))throw Error(`${s} must be a valid date-time string`);return o}function cr(r,s){if(r==="generic"||r==="claude"||r==="codex")return r;throw Error(`${s} must be generic, claude, or codex`)}function Cr(r,s){if(!L(r))throw Error(`${s} must be an object`);return{userId:V(r.userId,`${s}.userId`),...r.tenantId!==void 0?{tenantId:V(r.tenantId,`${s}.tenantId`)}:{},...r.workspaceId!==void 0?{workspaceId:V(r.workspaceId,`${s}.workspaceId`)}:{},...r.agentId!==void 0?{agentId:V(r.agentId,`${s}.agentId`)}:{},...r.sessionId!==void 0?{sessionId:V(r.sessionId,`${s}.sessionId`)}:{}}}function xr(r,s){let o=V(r,s),H=o.split("/");if(o.startsWith("/")||o.startsWith("~/")||o.includes("\\")||/^[A-Za-z]:[\\/]/.test(o))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);if(H.some((f)=>f.length===0||f==="."||f===".."))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);return o}function gr(r,s){return{kind:"command",command:V(r.command,`${s}.command`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function lr(r,s){let o=r.payload===void 0?void 0:e(r.payload,`${s}.payload`);return{kind:"tool_call",toolName:V(r.toolName,`${s}.toolName`),...o!==void 0?{payload:o}:{},...r.raw!==void 0?{raw:y(r.raw,`${s}.raw`)}:{},...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function er(r,s){if(r.operation!=="create"&&r.operation!=="delete"&&r.operation!=="update")throw Error(`${s}.operation must be create, delete, or update`);return{kind:"file_edit",operation:r.operation,relativePath:xr(r.relativePath,`${s}.relativePath`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function tr(r,s){if(!L(r))throw Error(`${s} must be an object`);if(r.kind==="command")return gr(r,s);if(r.kind==="tool_call")return lr(r,s);if(r.kind==="file_edit")return er(r,s);throw Error(`${s}.kind must be command, tool_call, or file_edit`)}function t(r,s="actionIntent"){if(!L(r))throw Error(`${s} must be an object`);let o=r.runId===void 0?void 0:V(r.runId,`${s}.runId`),H=r.attemptId===void 0?void 0:V(r.attemptId,`${s}.attemptId`);if(!o&&!H)throw Error(`${s} must include runId or attemptId`);let f={actionId:V(r.actionId,`${s}.actionId`),hostKind:cr(r.hostKind,`${s}.hostKind`),occurredAt:kr(r.occurredAt,`${s}.occurredAt`),scope:Cr(r.scope,`${s}.scope`),sequence:Lr(r.sequence,`${s}.sequence`),turnId:V(r.turnId,`${s}.turnId`),action:tr(r.action,`${s}.action`)};if(o)return{...f,runId:o,...H?{attemptId:H}:{}};return{...f,attemptId:H}}function wo(r){try{return t(r),!0}catch{return!1}}function fr(r){return typeof r==="object"&&r!==null}function k(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r}function Hr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function nr(r,s){if(r==="command"||r==="tool_call"||r==="warning")return r;throw Error(`${s} must be command, tool_call, or warning`)}function ar(r,s){if(r==="failure"||r==="success"||r==="timeout"||r==="user_corrected")return r;throw Error(`${s} must be failure, success, timeout, or user_corrected`)}function ir(r,s){if(r==="host_lifecycle"||r==="warning_message")return r;throw Error(`${s} must be host_lifecycle or warning_message`)}function n(r,s="trace.events[0]"){if(!fr(r))throw Error(`${s} must be an object`);let o=r.args;if(o!==void 0&&(!Array.isArray(o)||o.some((A)=>typeof A!=="string")))throw Error(`${s}.args must be a string array`);let H=r.raw;if(H!==void 0&&typeof H!=="string")throw Error(`${s}.raw must be a string`);let f=r.evidenceExcerpt;if(f!==void 0&&typeof f!=="string")throw Error(`${s}.evidenceExcerpt must be a string`);let E=r.correctionOfStepIndex===void 0?void 0:Hr(r.correctionOfStepIndex,`${s}.correctionOfStepIndex`),w=Hr(r.stepIndex,`${s}.stepIndex`),m=r.outcomeSource===void 0?void 0:ir(r.outcomeSource,`${s}.outcomeSource`),$=r.turnId;if($!==void 0&&typeof $!=="string")throw Error(`${s}.turnId must be a string`);return{actionKind:nr(r.actionKind,`${s}.actionKind`),actionName:k(r.actionName,`${s}.actionName`),...o?{args:[...o]}:{},...typeof E==="number"?{correctionOfStepIndex:E}:{},...typeof f==="string"?{evidenceExcerpt:f}:{},outcome:ar(r.outcome,`${s}.outcome`),...typeof m==="string"?{outcomeSource:m}:{},...typeof H==="string"&&H.trim().length>0?{raw:H}:{},stepIndex:w,...typeof $==="string"&&$.trim().length>0?{turnId:$}:{}}}function Er(r,s="trace"){if(!fr(r))throw Error(`${s} must be an object`);let o=k(r.hostKind,`${s}.hostKind`);if(o!=="codex")throw Error(`${s}.hostKind must be codex`);let H=r.events;if(!Array.isArray(H)||H.length===0)throw Error(`${s}.events must be a non-empty array`);let f=H.map((w,m)=>n(w,`${s}.events[${m}]`)),E=new Map;for(let[w,m]of f.entries()){let $=E.get(m.stepIndex);if($!==void 0)throw Error(`${s}.events[${w}].stepIndex duplicates ${s}.events[${$}].stepIndex`);E.set(m.stepIndex,w)}return{cue:k(r.cue,`${s}.cue`),hostKind:o,traceId:k(r.traceId,`${s}.traceId`),events:f}}function wr(r){let s;for(let o of r.events)if(!s||o.stepIndex<s.stepIndex)s=o;return s}function a(r){return{kind:r.actionKind,name:r.actionName,...r.args?{args:[...r.args]}:{},...r.raw?{raw:r.raw}:{}}}function Ar(r){if(r.events.length===0)return null;return Er({cue:r.cue,hostKind:r.hostKind,traceId:r.traceId,events:r.events},"trace")}function mr(r,s){return r instanceof Error?r:Error(s)}function $r(r){let s=[],o=null,H=0;return{appendEvent(f){if(o)throw Error("behavioral trace recorder is already closed");let E=n({...f,stepIndex:H},"trace.events[0]");return s.push(E),H+=1,E},close(){if(o)return o;return o=(async()=>{let f=null;try{f=Ar({...r,events:s})}catch(E){return{error:mr(E,"failed to build behavioral trace"),recorded:!1,trace:null}}if(!f)return{recorded:!1,trace:null};try{return{recorded:(await r.onClose?.(f))?.recorded??!1,trace:f}}catch(E){return{error:mr(E,"failed to record behavioral trace"),recorded:!1,trace:f}}})(),o},snapshot(){return Ar({...r,events:s})}}}var ur=Symbol.for("goodmemory.host.eval.support");function Br(r,s){return r[ur]=s,r}var z="host_pre_action_policy",pr=["deepanalyzer","deploy","drop","git push","migration","prod","production","publish","release","rm -"],rs=["agents.md","claude.md","package.json","playbooks/","src/","task-board/"],ss={correction_context:4,verification_result:3,tool_result_excerpt:2,document_excerpt:2,conversation_excerpt:1},os=new Set(["&&",";","|","||"]),Hs=new Set(["command","env","exec","nohup"]),Ir=/^[A-Za-z_][A-Za-z0-9_]*=/u;function Q(r){let s=new Set,o=[];for(let H of r){if(!H)continue;let f=H.trim();if(f.length===0||s.has(f))continue;s.add(f),o.push(f)}return o}function q(r){return r?.trim().toLowerCase()??""}function c(r,s,o,H){if(o.length===0||H.length===0)return 0;return r.tokenOverlap(o,H,s,{excludeStopwords:!0})}function D(r,s,o){return r.resolveFromText({...o?{locale:o}:{},text:s})}function Z(r,s,o,H){let f=r.render({key:o},s);return H?`${f}: ${H}`:f}function i(r){switch(r.kind){case"command":return[r.command,r.summary].filter(Boolean).join(" ");case"tool_call":return[r.toolName,r.raw,r.summary,r.payload?JSON.stringify(r.payload):void 0].filter(Boolean).join(" ");case"file_edit":return[r.operation,r.relativePath,r.summary].filter(Boolean).join(" ")}}function u(r){return i(r)}function fs(r){return r.kind==="validated_pattern"&&r.lifecycle==="active"&&!r.supersededBy}function Es(r){let s=Or(r.appliesTo);return s==="coding_agent"||s==="general_response"}function ws(r,s){let o=r.durable.evidence.filter((E)=>E.linkedMemoryIds.includes(s)).map((E)=>E.id),H=r.durable.experiences.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds),f=r.durable.promotions.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds);return Q([...As(r,s),...o,...H,...f])}function As(r,s){let o=r.durable.feedback.find((H)=>H.id===s);return Q(o?.evidence??[])}function ms(r,s,o){return s.splitClauses(r,o).map((H)=>H.trim()).filter((H)=>H.length>0)}function $s(r){let s=Wr(r.action).map((E)=>r.language.normalizeForEquality(E.split(/[\\/]/u).at(-1)??E,r.languageContext)),o=!1,H=!1,f=!1;for(let E of ms(r.rule,r.language,r.languageContext)){let w=Vr({languageContext:r.languageContext,text:E},r.language);o||=w;let m=r.language.buildSearchTerms(E,r.languageContext);if(!(s.some((R)=>m.includes(R))||c(r.language,r.languageContext,E,r.actionText)>0))continue;if(w)H=!0;else f=!0}if(H)return"matched";if(o&&f)return"allowed_replacement";return f?"matched":"none"}function Bs(r,s,o,H){return r.durable.feedback.filter((f)=>fs(f)&&Es(f)).map((f)=>{let E=[f.rule,f.why].filter(Boolean).join(" "),w=D(H,E,f.source.locale),m=c(H,w,E,o),$=H.normalizeForEquality(E,w),A=H.normalizeForEquality(u(s.action),w),R=H.normalizeForEquality(o,w),B=$s({action:s.action,actionText:o,language:H,languageContext:w,rule:E});if(!(B!=="allowed_replacement"&&(B==="matched"||m>0||$.includes(A)||$.includes(R))))return null;return{languageContext:w,pattern:f,linkedEvidenceIds:ws(r,f.id),score:m+(f.why?1:0)+Math.round(f.confidence)}}).filter((f)=>Boolean(f)).sort((f,E)=>E.score-f.score)}function Is(r,s,o){return r.durable.evidence.map((H)=>{let f=D(o,H.excerpt,H.source.locale),E=c(o,f,H.excerpt,s);if(E===0)return null;return{evidence:H,languageContext:f,score:E+ss[H.kind]}}).filter((H)=>Boolean(H)).sort((H,f)=>f.score-H.score)}function Nr(r){if(r.kind==="file_edit"){if(r.operation==="delete")return!0;let o=q(r.relativePath);return rs.some((H)=>o.includes(H))}let s=q(i(r));return pr.some((o)=>s.includes(o))}function Vr(r,s){let o=s.analyzeContent(r.text,r.languageContext);return o.feedbackKind==="dont"||o.factPolarity==="negative"}function Rs(r,s){let o=Sr({appliesTo:"coding_agent",kind:"do",language:s,languageContext:r.languageContext,rule:r.text}),H=o.enactmentSurface==="host_action"?o.applicability.canonicalFirstAction:void 0;return q(H?.name)==="quickcheck"?r.text:void 0}function _s(r,s){let o=[];for(let H of r){let f=s.splitSentences(H.text,H.languageContext).find((w)=>s.analyzeQuery(w,H.languageContext).before);if(f){o.push(f);continue}let E=Rs(H,s);if(E)o.push(E)}return Q(o)}function Os(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(&&|\|\||[;|])|([^\s;&|]+)/gu)].map((s)=>s[1]??s[2]??s[3]??s[4]??"").filter((s)=>s.length>0)}function Rr(r){let s=0;while(Ir.test(r[s]??""))s+=1;while(s<r.length){let o=r[s],H=q(o.split(/[\\/]/u).at(-1));if(!Hs.has(H))return o;s+=1;while((r[s]??"").startsWith("-"))s+=1;while(Ir.test(r[s]??""))s+=1;if(s>=r.length)return o}return}function Wr(r){let o=(r.kind==="command"?r.command:r.kind==="tool_call"?r.raw:void 0)?.trim();if(!o)return[];let H=[],f=[];for(let w of Os(o)){if(os.has(w)){let m=Rr(f);if(m)H.push(m);f=[];continue}f.push(w)}let E=Rr(f);if(E)H.push(E);return Q(H)}function Ks(r){return Wr(r)[0]}function Ss(r,s){let o=r?.trim();if(!o||!o.includes("/"))return;let H=o.lastIndexOf("/");if(H<0)return;return`${o.slice(0,H+1)}${s}`}function ds(r,s,o,H){let f=r[0];if(!f)return;if(q(f).includes("quickcheck")){let w=Ss(Ks(s),"QuickCheck");if(w)return{kind:"tool_call",toolName:"QuickCheck",raw:w,summary:Z(o,H,"instruction",f)};return{kind:"warning",message:f}}return{kind:"warning",message:f}}function _r(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((s)=>s[1]??s[2]??s[3]??"").filter((s)=>s.length>0)}function Pr(r){if(r.kind==="tool_call"){let s=r.raw?.trim();return{...s?{args:_r(s).slice(1),raw:s}:{},kind:"tool_call",name:r.toolName}}if(r.kind==="command"){let s=r.command.trim(),o=_r(s);return{args:o.slice(1),kind:"command",name:o[0]??s,raw:s}}return{kind:"warning",name:"file_edit",raw:`${r.operation} ${r.relativePath}`}}function Ns(r,s,o,H){if(r.kind==="warning")return{kind:"warning",message:r.raw??r.name};if(r.kind==="tool_call")return{kind:"tool_call",toolName:r.name,...r.raw?{raw:r.raw}:{},summary:Z(o,H,"instruction",s)};return{command:r.raw??[r.name,...r.args??[]].filter(Boolean).join(" "),kind:"command",summary:Z(o,H,"instruction",s)}}function Vs(r,s,o,H){let f=dr({appliesTo:"coding_agent",feedback:r.durable.feedback,query:o,surface:"host_action"}),E=Pr(s.action);return f.map((w)=>{let m=[w.feedback.rule,w.feedback.why].filter(Boolean).join(" "),$=D(H,m,w.feedback.source.locale),A=c(H,$,m,o),R=w.policy.applicability.canonicalFirstAction,B=R&&q(R.name)===q(E.name);if(w.matchedQueryTokens.length===0&&A===0&&!B)return null;return{feedback:w.feedback,languageContext:$,policy:w.policy,score:w.score+A}}).filter((w)=>Boolean(w)).sort((w,m)=>m.score-w.score)}function Ws(r){let s=[],o=Nr(r.action);if(r.workingMemory?.temporaryDecisions?.length)s.push(...r.workingMemory.temporaryDecisions);if(o&&r.workingMemory?.openLoops?.length){let H=r.workingMemory.openLoops[0],f=D(r.language,H);s.push(Z(r.language,f,"guidance",H))}if(o&&r.journal?.workflow?.length){let H=r.journal.workflow[0],f=D(r.language,H);s.push(`${r.language.render({key:"workflow"},f)}: ${H}`)}if(r.journal?.errorsAndCorrections?.length)s.push(r.journal.errorsAndCorrections[0]);return Q(s)}function Ps(r){return Q([z,`${z}.decision=${r.decision}`,`${z}.action_kind=${r.intent.action.kind}`,`${z}.host_kind=${r.intent.hostKind}`,r.highRisk?`${z}.high_risk`:void 0,r.matchedMemoryIds.length>0?`${z}.matched_memory=${r.matchedMemoryIds.length}`:void 0,r.matchedEvidenceIds.length>0?`${z}.matched_evidence=${r.matchedEvidenceIds.length}`:void 0])}function Fs(r){if(r.kind==="file_edit")return r.operation==="delete";if(r.kind==="command"){let s=q(r.command);return s.includes("rm -")||s.includes("git reset --hard")}return!1}function Fr(r){let s=i(r.intent.action),o=Vs(r.exported,r.intent,s,r.language),H=Bs(r.exported,r.intent,s,r.language),f=Is(r.exported,s,r.language),E=Q([...o.map((_)=>_.feedback.id),...H.map((_)=>_.pattern.id)]),w=Q([...o.flatMap((_)=>_.feedback.evidence??[]),...H.flatMap((_)=>_.linkedEvidenceIds),...f.map((_)=>_.evidence.id)]),m=H.flatMap((_)=>[_.pattern.rule,_.pattern.why].filter((h)=>Boolean(h)).map((h)=>({languageContext:_.languageContext,text:h}))),$=f.map((_)=>({languageContext:_.languageContext,text:_.evidence.excerpt})),A=[...m,...$],R=_s(A,r.language),B=Ws({action:r.intent.action,journal:r.exported.runtime?.journal,language:r.language,workingMemory:r.exported.runtime?.workingMemory}),W=Q([...m.map(({text:_})=>_),...B]).slice(0,4),K=Nr(r.intent.action),O=E.length>0||w.length>0,P=A.some((_)=>Vr(_,r.language)),S=o[0],Y=S?{languageContext:S.languageContext,text:S.feedback.rule}:A[0],J=D(r.language,s),G=Y?.languageContext??J,F="allow",b=Z(r.language,J,"guidance",Z(r.language,J,"none")),U,l=Pr(r.intent.action),j=S?.policy.applicability.canonicalFirstAction;if(S&&j){if(W.unshift(S.feedback.rule),!Kr(l,j))F="review_required",b=Z(r.language,S.languageContext,"instruction",S.feedback.rule),U=Ns(j,S.feedback.rule,r.language,S.languageContext);else if(W.length>0)F="allow_with_guidance",b=Z(r.language,S.languageContext,"verification",S.feedback.rule)}if(F==="allow"&&O&&K&&(P||R.length>0))if(U=ds(R,r.intent.action,r.language,G),Fs(r.intent.action)&&!U)F="blocked",b=Z(r.language,G,"instruction",Y?.text);else F="review_required",b=Z(r.language,G,"instruction",Y?.text),U??={kind:"warning",message:Y?.text??b};else if(F==="allow"&&W.length>0){F="allow_with_guidance";let _=D(r.language,W[0]);b=Z(r.language,_,"guidance",W[0])}let I=Ps({decision:F,highRisk:K,intent:r.intent,matchedEvidenceIds:w,matchedMemoryIds:E});return{actionId:r.intent.actionId,auditRecorded:!1,decision:F,guidance:W,matchedEvidenceIds:w,matchedMemoryIds:E,policyApplied:I,reason:b,...U?{recommendedFirstStep:U}:{},requiredPreconditions:R}}function Js(r){if(r==="timeout")return"timeout";if(r==="user_corrected")return"user correction";return"failure"}function Us(r){return r==="failure"||r==="timeout"||r==="user_corrected"}function Jr(r){return r.outcome==="success"||r.actionKind==="warning"}function Ys(r){let s=[...r.trace.events].filter((E)=>E.stepIndex>r.firstAction.stepIndex).sort((E,w)=>E.stepIndex-w.stepIndex),o=s.find((E)=>E.correctionOfStepIndex===r.firstAction.stepIndex&&Jr(E)),H=s.find((E)=>Jr(E)),f=o??H;return f?a(f):void 0}function Zs(r){let s=wr(r);if(!s||!Us(s.outcome))return null;return{cue:r.cue,evidenceExcerpt:s.evidenceExcerpt,failureClass:Js(s.outcome),firstAction:a(s),retrievalProfile:"coding_agent",saferAlternative:Ys({firstAction:s,trace:r})}}async function p(r){let s=C(r.memory),o=Zs(r.trace);if(!s?.recordBehavioralOutcome||!o)return{...o?{outcome:o}:{},recorded:!1};return await s.recordBehavioralOutcome({scope:r.scope,cue:o.cue,evidenceExcerpt:o.evidenceExcerpt,failureClass:o.failureClass,firstAction:o.firstAction,saferAlternative:o.saferAlternative,modelInfluence:o.modelInfluence,outcome:o.outcome}),{outcome:o,recorded:!0}}var zr=["memory_index","user_memory","session_memory"],Dr=[...zr,"archive_recap","playbook"];function d(r){return r.trim().replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\t/g,"\\t").replace(/\r\n?/g,`
`).replace(/\n/g,"\\n")}function Gs(r,s,o="none"){return[`## ${d(r)}`,...s.length>0?s:[`- ${d(o)}`]].join(`
`)}function Xs(r,s){return[`# ${d(r)}`,...s.flatMap((o)=>["",o])].join(`
`)}function v(r,s,o,H){return r.render({key:o,...H?{values:H}:{}},s)}function X(r,s,o,H){return Gs(v(r,s,o),H,v(r,s,"none"))}function rr(r,s){let o=r??s,H=[];for(let f of o)if(!H.includes(f))H.push(f);return H}function Ur(r){return Object.freeze([...r])}function bs(r){if(r.kind==="archive"||r.relativePath.startsWith("archive/"))return"archive_recap";if(r.relativePath.startsWith("playbooks/"))return"playbook";if(r.relativePath==="MEMORY.md"||r.kind==="memory")return"memory_index";if(r.relativePath==="user.md"||r.kind==="user")return"user_memory";if(r.kind==="session"||r.relativePath==="session.md")return"session_memory";return null}function hs(r){let s=r.readableArtifactTypes.filter((o)=>!r.supportedReadableArtifactTypes.includes(o));if(s.length===0)return;throw Error(`readable artifact types must be supported by the configured export surface: ${s.join(", ")}`)}function Qs(r){if(r.mode!=="file-authoritative"&&r.writableArtifactTypes.length>0)throw Error("file-assisted adapters cannot declare writable artifact types");if(r.writableArtifactTypes.length>0&&!r.documentStorePresent)throw Error("file-authoritative adapters require documentStore when writable artifact types are enabled");for(let s of r.writableArtifactTypes)if(!r.readableArtifactTypes.includes(s))throw Error("writable artifact types must be a subset of readable artifact types")}function qs(r){return Boolean(C(r)?.recordBehavioralOutcome)}function js(r){return Boolean(g(r)?.recordHostActionAssessment)}function zs(r){if(!r)return;switch(r.kind){case"warning":return r.message;case"command":return r.command;case"tool_call":return r.toolName;case"file_edit":return`${r.operation} ${r.relativePath}`}}function Ds(r,s){if(r.hostKind!==s)throw Error(`host action intent hostKind ${r.hostKind} does not match adapter hostKind ${s}`);return{...r,hostKind:s}}async function Ts(r){if(!js(r.memory))return{auditRecorded:!1};let s=await g(r.memory).recordHostActionAssessment({assessment:{actionId:r.intent.actionId,actionKind:r.intent.action.kind,actionSummary:u(r.intent.action),attemptId:r.intent.attemptId,decision:r.assessment.decision,guidance:r.assessment.guidance,hostKind:r.intent.hostKind,matchedEvidenceIds:r.assessment.matchedEvidenceIds,matchedMemoryIds:r.assessment.matchedMemoryIds,occurredAt:r.intent.occurredAt,policyApplied:r.assessment.policyApplied,reason:r.assessment.reason,recommendedFirstStepSummary:zs(r.assessment.recommendedFirstStep),requiredPreconditions:r.assessment.requiredPreconditions,runId:r.intent.runId,scope:r.intent.scope,turnId:r.intent.turnId}});return{assessmentExperienceId:s.experienceId,auditRecorded:s.recorded}}function vs(r,s){return[`- userId: ${d(r.scope.userId)}`,r.scope.workspaceId?`- workspaceId: ${d(r.scope.workspaceId)}`:void 0,r.scope.agentId?`- agentId: ${d(r.scope.agentId)}`:void 0,`- sessionId: ${d(s)}`].filter((o)=>Boolean(o))}function Ms(r){if(!r)return{constraints:[],currentGoal:[],openLoops:[],recentDecisions:[]};return{currentGoal:r.currentGoal?[`- ${d(r.currentGoal)}`]:[],openLoops:r.openLoops.map((s)=>`- ${d(s)}`),recentDecisions:(r.temporaryDecisions??[]).map((s)=>`- ${d(s)}`),constraints:(r.constraints??[]).map((s)=>`- ${d(s)}`)}}function ys(r){if(!r)return{currentState:[],keyFiles:[],workflow:[]};return{currentState:r.currentState?[`- ${d(r.currentState)}`]:[],keyFiles:(r.filesAndFunctions??[]).map((s)=>`- ${d(s)}`),workflow:(r.workflow??[]).map((s)=>`- ${d(s)}`)}}function Ls(r){return r.map((s)=>{let o=d(s.title),H=d(s.pointer);return`- ${o}: ${H}`})}function ks(r){return r.map((s)=>`- [${s.kind}] ${d(s.rule)}`)}function cs(r){return r.map((s)=>`- ${d(s.preview)}`)}function Cs(r){let s=new Set,o=[];for(let H of r){if(s.has(H))continue;s.add(H),o.push(H)}return o}function Yr(r){return(r.lifecycle??"active")==="active"}function xs(r){return`session-memory/${encodeURIComponent(r)}.md`}function gs(r,s,o,H){let f=r.runtime?.workingMemory?.sessionId===s?r.runtime.workingMemory:null,E=r.runtime?.journal?.sessionId===s?r.runtime.journal:null,w=r.durable.references.filter((B)=>B.sessionId===s&&Yr(B)),m=r.durable.feedback.filter((B)=>B.sessionId===s&&Yr(B)),$=(r.runtime?.spills??[]).filter((B)=>B.scope.sessionId===s),A=Ms(f),R=ys(E);return Xs(v(o,H,"session_handoff",{sessionId:s}),[X(o,H,"scope",vs(r,s)),X(o,H,"current_goal",A.currentGoal),X(o,H,"open_loops",A.openLoops),X(o,H,"recent_decisions",A.recentDecisions),X(o,H,"constraints",A.constraints),X(o,H,"current_state",R.currentState),X(o,H,"key_files",Cs([...R.keyFiles,...Ls(w)])),X(o,H,"workflow",R.workflow),X(o,H,"procedural_memory",ks(m)),X(o,H,"artifact_spills",cs($))])}function ls(r,s,o,H,f){if(o==="session_memory"&&s.sessionId)return{...s,artifactType:o,relativePath:xs(s.sessionId),content:gs(r,s.sessionId,H,f),writable:!1};return{...s,artifactType:o,writable:!1}}function es(r){let s=r.durable.profile,o=r.runtime?.workingMemory,H=r.runtime?.journal;return[...(r.durable.sourceMessages??[]).map(({content:f})=>f),s?.identity.name,s?.identity.role,s?.identity.organization,s?.identity.location,s?.identity.languagePreference,...r.durable.facts.map(({content:f})=>f),...r.durable.references.flatMap(({pointer:f,title:E})=>[E,f]),...r.durable.feedback.map(({rule:f})=>f),...r.durable.episodes.map(({summary:f})=>f),...r.durable.archives.map(({summary:f})=>f),...r.durable.evidence.map(({excerpt:f})=>f),...r.durable.experiences.map(({summary:f})=>f),...r.durable.proposals.map(({summary:f})=>f),...r.durable.promotions.map(({summary:f})=>f),o?.currentGoal,...o?.openLoops??[],...o?.temporaryDecisions??[],...o?.constraints??[],H?.currentState,...H?.worklog??[],...H?.filesAndFunctions??[],...H?.workflow??[]].filter((f)=>Boolean(f)).join(`
`)}async function Tr(r,s,o,H){let f=await r.exportMemory(o),E=H.resolveFromText({...o.locale?{locale:o.locale}:{},text:es(f)});return{artifacts:f.artifacts.files.flatMap((m)=>{let $=bs(m);if(!$||!s.includes($))return[];return[ls(f,m,$,H,E)]}),exportedAt:f.exportedAt,rootPath:f.artifacts.rootPath,scope:f.scope}}function ts(r=!1){return{mode:"file-assisted",hint:"Recreate the host adapter in file-assisted mode and inspect compiled artifacts before retrying writable operations.",performed:r}}function T(r){return{adapterId:r.adapterId,artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,failureReasons:r.failureReasons??[],hostKind:r.hostKind,mode:r.mode,policyApplied:r.policyApplied??[],provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:r.wroteAt},relativePath:r.relativePath,risky:r.risky??!1,rollback:ts(r.rollbackPerformed??!1),structuredDelta:r.structuredDelta??[],verificationOutcome:r.verificationOutcome??"not_run"}}function N(r,s){return new M(r,s)}function x(r){return r.map((s)=>s.trim()).filter((s)=>s.startsWith("- ")).map((s)=>s.slice(2).trim())}function vr(r){let s=x(r),o={};for(let H of s){let f=H.indexOf(":");if(f<0)continue;let E=H.slice(0,f).trim(),w=H.slice(f+1).trim();o[E]=w}return o}function or(r){let s=new Map,o=null;for(let H of r.split(/\r?\n/)){let f=H.trimEnd();if(f.startsWith("## ")){o=f.slice(3).trim(),s.set(o,[]);continue}if(o)s.get(o)?.push(f)}return s}function Zr(r,s){let o=or(r);return x(o.get(s)??[])}function Gr(r){return r.length===1&&r[0]==="none"}function ns(r,s){return{canonicalPattern:v(r,s,"canonical_pattern"),guidance:v(r,s,"guidance"),why:v(r,s,"why")}}function as(r,s){let o=or(r.content),H=vr(o.get(s.canonicalPattern)??[]),f=x(o.get(s.guidance)??[]),E=x(o.get(s.why)??[]);if(!H.canonicalMemoryId)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires canonicalMemoryId in the Canonical Pattern section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length===0)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires one guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports a single guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(E.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports zero or one Why bullet in the Why section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));return{appliesTo:H.appliesTo,canonicalMemoryId:H.canonicalMemoryId,rule:f[0],why:E[0]}}function is(r,s){let o=or(r),f=vr(o.get(s.canonicalPattern)??[]).canonicalMemoryId?.trim();return f?f:null}function us(r){return{id:"host-write-candidate",kindHint:"feedback",explicitness:"explicit",content:r.rule,sourceMessageIndex:0,sourceRole:"assistant",metadata:{appliesTo:r.appliesTo,feedbackKind:"validated_pattern"}}}function ps(r,s){if(r.userId!==s.userId)return!1;if(s.tenantId!==void 0&&r.tenantId!==s.tenantId)return!1;if(s.workspaceId!==void 0&&r.workspaceId!==s.workspaceId)return!1;if(s.agentId!==void 0&&r.agentId!==s.agentId)return!1;return!0}function ro(r){let s=[];if(r.previous.appliesTo!==r.nextAppliesTo)s.push({op:"set",target:"appliesTo",value:r.nextAppliesTo});if(r.previous.rule!==r.nextRule)s.push({op:"set",target:"rule",value:r.nextRule});if(r.previous.why!==r.nextWhy)s.push({op:"set",target:"why",value:r.nextWhy});return s}function so(r){return{artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,currentContent:r.currentContent,nextContent:r.nextContent,relativePath:r.relativePath,risky:r.risky,scope:r.scope,structuredDelta:r.structuredDelta}}async function Xr(r,s,o){let H=await Tr(r,Dr,{scope:s,includeRuntime:!0},o);return new Map(H.artifacts.map((f)=>[f.relativePath,f]))}async function oo(r){let s=r.now(),o=(I)=>T({adapterId:r.adapterId,artifactType:r.writeInput.artifactType,canonicalMemoryId:I.canonicalMemoryId,failureReasons:I.failureReasons,hostKind:r.hostKind,mode:r.mode,policyApplied:I.policyApplied,relativePath:I.relativePath??r.writeInput.relativePath,risky:I.risky,rollbackPerformed:I.rollbackPerformed,structuredDelta:I.structuredDelta,verificationOutcome:I.verificationOutcome,wroteAt:s});if(!r.writeInput.relativePath.startsWith("playbooks/")||r.writeInput.relativePath.endsWith(".prompt.md")||r.writeInput.relativePath.endsWith(".skill.md"))throw N(`Host adapter does not allow writes for artifact path ${r.writeInput.relativePath}`,o({failureReasons:["Structured delta writeback only supports canonical playbook markdown files."]}));let f=(await Xr(r.memory,r.writeInput.scope,r.language)).get(r.writeInput.relativePath);if(!f)throw N(`Host adapter cannot locate the current artifact ${r.writeInput.relativePath}`,o({failureReasons:["The requested artifact path does not exist in the current exported host surface."]}));let E=r.language.resolveFromText({text:f.content}),w=ns(r.language,E),m=is(f.content,w);if(r.writeInput.content===f.content)return{diagnostics:o({canonicalMemoryId:m??void 0,policyApplied:[],risky:!1,structuredDelta:[]}),status:"noop",updatedArtifact:f};let $;try{$=as(r.writeInput,w)}catch(I){if(I instanceof M)throw N(I.message,o({...I.diagnostics,adapterId:r.adapterId,hostKind:r.hostKind,mode:r.mode,relativePath:r.writeInput.relativePath,provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:s}}));throw I}if(!m)throw N(`Host adapter cannot verify canonical binding for ${r.writeInput.relativePath}`,o({failureReasons:["The current exported playbook is missing canonicalMemoryId and cannot be used for authoritative writeback."]}));if($.canonicalMemoryId!==m)throw N("Host adapter write targets a different canonical record than the current playbook path.",o({canonicalMemoryId:m,failureReasons:["Edited playbook canonicalMemoryId must match the current artifact bound to this path."]}));let A=await r.documentStore.get("feedback",m);if(!A||A.kind!=="validated_pattern"||A.lifecycle!=="active"||!ps(A,r.writeInput.scope))throw N(`Host adapter cannot find writable validated pattern ${m}`,o({canonicalMemoryId:m,failureReasons:["Structured delta writeback only supports the active validated pattern currently bound to this playbook path."]}));let R=us({appliesTo:$.appliesTo,rule:$.rule}),B=[],W=r.language.resolveFromText({...A.source.locale?{locale:A.source.locale}:{},text:A.rule}),K={locale:W.locale,localeSource:A.source.localeSource??W.localeSource,phase:"remember",scope:r.writeInput.scope};if(r.policy?.redact){let I=await r.policy.redact(R,K);if(I.content!==R.content||I.metadata?.appliesTo!==R.metadata.appliesTo)B.push("custom_redact");R={...R,content:I.content,metadata:{...R.metadata,...I.metadata,feedbackKind:"validated_pattern"}}}if(r.policy?.shouldRemember&&!await r.policy.shouldRemember(R,K))throw B.push("custom_shouldRemember"),N("Host adapter write was blocked by policy.",o({canonicalMemoryId:A.id,failureReasons:["Policy rejected the adapter-authored change."],policyApplied:B}));let O=A.rule!==R.content,P=Zr(f.content,w.why),S=Zr(r.writeInput.content,w.why),Y=A.why===void 0&&Gr(S)&&(P.length===0||Gr(P))?void 0:$.why,J=ro({nextAppliesTo:R.metadata.appliesTo,nextRule:R.content,nextWhy:Y,previous:A});if(J.length===0)return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J}),status:"noop",updatedArtifact:f};if(r.policy?.resolveConflict){let I=await r.policy.resolveConflict(qr(A,"feedback"),R,K);if(I.action==="keep_existing")throw B.push("custom_resolveConflict"),N("Host adapter write was blocked by conflict policy.",o({canonicalMemoryId:A.id,failureReasons:[I.reason??"Conflict policy kept the existing canonical memory."],policyApplied:B,risky:O,structuredDelta:J}))}let G="not_run",F;if(O){if(!r.verifyWrite)G="review_required",F="Risky adapter writes require verification before they can be applied.";else{let I=await r.verifyWrite(so({artifactType:r.writeInput.artifactType,canonicalMemoryId:A.id,currentContent:f.content,nextContent:r.writeInput.content,relativePath:r.writeInput.relativePath,risky:O,scope:r.writeInput.scope,structuredDelta:J}));G=I.outcome,F=I.reason}if(G!=="passed")throw N("Host adapter write requires verification.",o({canonicalMemoryId:A.id,failureReasons:[F??"Risky adapter writes require verification before they can be applied."],policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}))}let b=br({...A,appliesTo:R.metadata.appliesTo,rule:R.content,source:Qr(A.source),updatedAt:s,why:Y}),U=r.createId(),l=jr({id:U,userId:A.userId,tenantId:A.tenantId,workspaceId:A.workspaceId,agentId:A.agentId,sessionId:r.writeInput.scope.sessionId,kind:"feedback",traceId:`host-write-${U}`,trigger:"governance",modelInfluence:"none",summary:`Host adapter ${r.adapterId} updated validated pattern ${A.id}.`,policyApplied:B,linkedMemoryIds:[A.id],metrics:{},createdAt:s}),j=!1;try{await r.documentStore.set("feedback",A.id,b),await r.documentStore.set(sr,U,l);let _=[...(await Xr(r.memory,r.writeInput.scope,r.language)).values()].find((h)=>h.artifactType==="playbook"&&h.relativePath.endsWith(".md")&&!h.relativePath.endsWith(".prompt.md")&&!h.relativePath.endsWith(".skill.md")&&h.content.includes(`canonicalMemoryId: ${A.id}`))??f;return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}),linkedExperienceId:U,status:"applied",updatedArtifact:_}}catch(I){j=!0;try{await r.documentStore.set("feedback",A.id,A),await r.documentStore.delete(sr,U)}catch{j=!1}throw N("Host adapter write failed.",o({canonicalMemoryId:A.id,failureReasons:[I instanceof Error?I.message:String(I)],policyApplied:B,risky:O,rollbackPerformed:j,structuredDelta:J,verificationOutcome:G}))}}function Ho(r,s,o){if(!r.includes(s.artifactType))throw N(`Host adapter does not allow writes for artifact type ${s.artifactType}`,o);throw N(`Structured delta writeback is not implemented yet for artifact type ${s.artifactType}`,o)}function jo(r){let s=rr(r.readableArtifactTypes,zr),o=rr(r.supportedReadableArtifactTypes,Dr),H=rr(r.writableArtifactTypes,[]),f=r.mode??"file-assisted",E=r.now??(()=>new Date().toISOString()),w=r.createId??(()=>crypto.randomUUID()),m=g(r.memory)?.language??hr();if(r.id.trim().length===0)throw Error("host adapter id must not be empty");hs({readableArtifactTypes:s,supportedReadableArtifactTypes:o}),Qs({documentStorePresent:Boolean(r.documentStore),mode:f,readableArtifactTypes:s,writableArtifactTypes:H});let $=Ur(s),A=Ur(H),R=Object.freeze({mode:f,readableArtifactTypes:$,writableArtifactTypes:A}),B=r.hostKind??"generic",W={id:r.id,hostKind:B,capabilities:R,async assessAction(K){let O=Ds(t(K),B),P=await r.memory.exportMemory({scope:O.scope,includeRuntime:Boolean(O.scope.sessionId)}),S=Fr({exported:P,intent:O,language:m}),Y=await Ts({assessment:S,intent:O,memory:r.memory});return{...S,...Y}},async readArtifacts(K){let O=await Tr(r.memory,$,K,m);return{...O,artifacts:O.artifacts.map((P)=>({...P,writable:A.includes(P.artifactType)}))}},async writeArtifact(K){let O=T({adapterId:r.id,artifactType:K.artifactType,hostKind:B,mode:f,relativePath:K.relativePath,wroteAt:E()});if(K.artifactType==="playbook"&&A.includes("playbook"))return oo({adapterId:r.id,createId:w,documentStore:r.documentStore,hostKind:B,language:m,memory:r.memory,mode:f,now:E,policy:r.policy,verifyWrite:r.verifyWrite,writeInput:K});return Ho(A,K,O)}};if(B==="codex"){let K=qs(r.memory)?r.memory:void 0;Br(W,{createBehavioralTraceRecorder:({cue:O,scope:P,traceId:S})=>$r({cue:O,hostKind:"codex",traceId:S??`host-trace-${w()}`,onClose:async(Y)=>{if(!K)return{recorded:!1};return{recorded:(await p({memory:K,scope:P,trace:Y})).recorded}}}),...K?{recordBehavioralTrace:async({scope:O,trace:P})=>{return{recorded:(await p({memory:K,scope:O,trace:P})).recorded}}}:{}})}return Object.freeze(W)}function Mr(r){switch(r.kind){case"command":return{kind:"command",command:r.command,...r.summary?{summary:r.summary}:{}};case"tool_call":return{kind:"tool_call",toolName:r.toolName,...r.payload!==void 0?{payload:r.payload}:{},...r.raw?{raw:r.raw}:{},...r.summary?{summary:r.summary}:{}};case"file_edit":return{kind:"file_edit",operation:r.operation,relativePath:r.relativePath,...r.summary?{summary:r.summary}:{}}}}function fo(r){if(r.kind==="warning")return{kind:"warning",message:r.message};return Mr(r)}function To(r){if(r.assessment.actionId!==r.intent.actionId)throw Error("host action assessment actionId must match the planned intent actionId");let s=Mr(r.intent.action);switch(r.assessment.decision){case"allow":case"allow_with_guidance":return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:s,executeOriginalActionNow:!0,guidance:[...r.assessment.guidance],intercepted:!1,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1};case"review_required":{if(!r.assessment.recommendedFirstStep)throw Error("review_required host action assessments must provide a recommendedFirstStep");return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:fo(r.assessment.recommendedFirstStep),executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!0}}case"blocked":return{actionId:r.intent.actionId,blocked:!0,decision:r.assessment.decision,executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1}}}
export{M as Ea,t as Fa,wo as Ga,jo as Ha,To as Ia};
import{Jb as Id}from"./chunk-b7j2aytn.js";function Kd(d){return d.lifecycle??"active"}function YI(d){return Kd(d)==="active"}function ZI(d,I){let M=new Date(I).getTime();if(Number.isNaN(M))return!1;for(let E of[d.validUntil,d.expiresAt]){if(E===void 0)continue;let R=new Date(E).getTime();if(!Number.isNaN(R)&&R<=M)return!0}return!1}function W(d){let I=d?.trim().toLowerCase();return I&&I.length>0?I:"general_response"}function JI(d){return[d.kind,W(d.appliesTo),d.normalizedRule.trim().toLowerCase()].join("\x00")}function o(d){return d?.extractedAt??new Date(0).toISOString()}function VI(d){let I=d.updatedAt??d.createdAt??new Date(0).toISOString();return{userId:d.userId,identity:d.identity??{},expertise:d.expertise??{primarySkills:[],domains:[]},activeContext:d.activeContext??{goals:[],currentProjects:[]},version:d.version??1,updatedAt:d.updatedAt??I,createdAt:d.createdAt??I}}function TI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,value:d.value,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,evidenceCount:d.evidenceCount??1,isPinned:d.isPinned,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",updatedAt:d.updatedAt??o(d.source)}}function mI(d){let I=d.createdAt??d.updatedAt??o(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,content:d.content,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,importance:d.importance??1,source:d.source,factKind:d.factKind,scopeKind:d.scopeKind,subject:d.subject,accessCount:d.accessCount??0,lastAccessedAt:d.lastAccessedAt,verificationPressureCount:d.verificationPressureCount??0,lastVerificationHintAt:d.lastVerificationHintAt,observedAt:d.observedAt,validFrom:d.validFrom,validUntil:d.validUntil,expiresAt:d.expiresAt,demotedAt:d.demotedAt,demotionReason:d.demotionReason,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",isActive:d.isActive??!0,embeddingId:d.embeddingId,createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function QI(d){let I=d.createdAt??d.updatedAt??o(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,title:d.title,pointer:d.pointer,description:d.description,confidence:d.confidence??1,source:d.source,referenceKind:d.referenceKind,subject:d.subject,tags:d.tags,attributes:d.attributes,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function WI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,summary:d.summary,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],topics:d.topics??[],entities:d.entities,emotionalTone:d.emotionalTone,importance:d.importance??1,confidence:d.confidence??1,locale:d.locale,embeddingId:d.embeddingId,observedAt:d.observedAt,sourceMessageIds:d.sourceMessageIds,createdAt:d.createdAt??new Date(0).toISOString(),archivedAt:d.archivedAt}}function zI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,rule:d.rule,kind:d.kind,appliesTo:d.appliesTo,why:d.why,evidence:d.evidence??[],tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",lastUsedAt:d.lastUsedAt,updatedAt:d.updatedAt??o(d.source)}}function BI(d){let I=d.createdAt??d.lastActiveAt??new Date(0).toISOString();return{sessionId:d.sessionId,userId:d.userId,messages:d.messages??[],compactedMessages:d.compactedMessages??[],summary:d.summary??null,summaryUpToIndex:d.summaryUpToIndex??0,createdAt:d.createdAt??I,lastActiveAt:d.lastActiveAt??I}}function bI(d){return{sessionId:d.sessionId,userId:d.userId,currentGoal:d.currentGoal,constraints:d.constraints,openLoops:d.openLoops??[],temporaryDecisions:d.temporaryDecisions,toolState:d.toolState,state:d.state,updatedAt:d.updatedAt??new Date(0).toISOString()}}function FI(d){return{sessionId:d.sessionId,userId:d.userId,title:d.title,currentState:d.currentState,taskSpecification:d.taskSpecification,filesAndFunctions:d.filesAndFunctions??[],workflow:d.workflow??[],errorsAndCorrections:d.errorsAndCorrections??[],systemDocumentation:d.systemDocumentation??[],learnings:d.learnings??[],keyResults:d.keyResults??[],worklog:d.worklog??[],lastSummarizedMessageId:d.lastSummarizedMessageId,updatedAt:d.updatedAt??new Date(0).toISOString()}}function oI(d){return{...d}}var $d={active:["active","superseded","inactive"],superseded:["superseded","inactive"],inactive:["inactive","active"]};function hI(d,I){if(!$d[d].includes(I))throw Error(`Invalid lifecycle transition: ${d} -> ${I}`);return I}var Xd=Symbol.for("goodmemory.authorizedRecallAgentScope");function yI(d,I){return{...d,memoryType:I}}function wI(d,I){if(d.tenantId===void 0&&I.tenantId!==void 0)return!1;if(d.workspaceId===void 0&&I.workspaceId!==void 0)return!1;if(d.agentId===void 0&&I.agentId!==void 0)return!1;return!0}function qI(d,I){if(I.agentId===d.agentId)return!0;return d.agentId!==void 0&&I[Xd]===d.agentId}function f(d){if(d.enactmentSurface!=="text_response")return!1;return Boolean(d.applicability.textResponsePlan||d.applicability.computedResponseRule||d.applicability.urlTemplate||d.applicability.pathTemplate||d.applicability.guard||d.applicability.guardedBehavior||(d.applicability.replacementPairs?.length??0)>0||(d.applicability.forbiddenFragments?.length??0)>0||(d.applicability.preferredAlternatives?.length??0)>0||(d.applicability.preferredFragments?.length??0)>0||(d.applicability.exactFragments?.prefixes?.length??0)>0||(d.applicability.exactFragments?.required?.length??0)>0||(d.applicability.exactFragments?.suffixes?.length??0)>0)}function Yd(d){if(d.enactmentSurface!=="host_action")return!1;return Boolean(d.applicability.canonicalFirstAction||(d.applicability.argumentOrder?.length??0)>0)}var Ed="goodmemory.behavioral_policy",Md="goodmemory.behavioral_policy.steering_only",Zd="goodmemory.behavioral_policy.version",Jd=2,w=Id(),u={from:"http://",to:"https://"},Vd="<page>",t=/\.[A-Za-z0-9]{2,8}/u,Rd={first_action:8,syntax_constraint:7,guarded_policy:6,format_contract:5,avoidance:4,preference:3,transformation_rule:2,exemplar_fact:1},Sd={example_only:3,pattern_bounded:2,general:1};function T(d){return d?.trim().toLowerCase()??""}function B(d){if(!d?.trim())return;let I=w.resolveFromText({text:d});return w.analyzeBehavioralRule(d,I)}function X(d){let I=[],M=new Set;for(let E of d){let R=E?.trim();if(!R||M.has(R))continue;M.add(R),I.push(R)}return I}function Pd(d){return{...d,args:d.args&&d.args.length>0?[...d.args]:void 0,raw:d.raw?.trim()||void 0}}function kd(d){return[...d.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((I)=>I[1]??I[2]??I[3]??"").filter((I)=>I.length>0)}function Td(d){let I=[],M="",E=0,R=null;for(let P=0;P<d.length;P+=1){let k=d[P];if(R){if(M+=k,k===R&&d[P-1]!=="\\")R=null;continue}if(k==="'"||k==='"'){R=k,M+=k;continue}if(k==="("||k==="["||k==="{"){E+=1,M+=k;continue}if(k===")"||k==="]"||k==="}"){E=Math.max(0,E-1),M+=k;continue}if(k===","&&E===0){let O=M.trim();if(O.length>0)I.push(O);M="";continue}M+=k}let S=M.trim();if(S.length>0)I.push(S);return I}function r(d){let I=d.split(/\r?\n/u).map((R)=>R.trim()).find((R)=>R.length>0)??d.trim();if(!I)return;let M=I.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(M){let[,R,S]=M;return{args:Td(S),kind:"tool_call",name:R,raw:I}}let E=kd(I);if(E.length===0)return;return{args:E.slice(1),kind:"command",name:E[0],raw:I}}function i(d){let I=Pd(d);if(I.args&&I.args.length>0)return I.args;if(I.kind==="warning"||!I.raw||I.raw.trim().length===0)return;let M=kd(I.raw);return M.length>1?M.slice(1):void 0}function md(d,I){if(I.length===0)return!0;let M=0;for(let E of I){let R=!1;while(M<d.length){if(d[M]===E){R=!0,M+=1;break}M+=1}if(!R)return!1}return!0}function p(d){let I=Pd(d);return JSON.stringify({...I.args?{args:I.args}:{},kind:I.kind,name:I.name,...I.raw?{raw:I.raw}:{}})}function Qd(d,I){if(!d||!I)return d===I;return p(d)===p(I)}function aI(d,I){if(!d||!I)return d===I;if(d.kind!==I.kind||d.name.trim()!==I.name.trim())return!1;if(I.kind==="warning")return Qd(d,I);let M=i(I);if(!M||M.length===0)return!0;let E=i(d);if(!E||E.length===0)return!1;return md(E,M)}function Wd(d){if(!c(d))return;if(d.kind!=="command"&&d.kind!=="tool_call"&&d.kind!=="warning"||typeof d.name!=="string")return;let I=Array.isArray(d.args)&&d.args.every((M)=>typeof M==="string")?[...d.args]:void 0;return{...I?{args:I}:{},kind:d.kind,name:d.name,...typeof d.raw==="string"?{raw:d.raw}:{}}}function Od(d){if(!c(d))return;let I=g(d.prefixes),M=g(d.required),E=g(d.suffixes);if(!I&&!M&&!E)return;return{...I?{prefixes:I}:{},...M?{required:M}:{},...E?{suffixes:E}:{}}}function l(d){if(!c(d)||typeof d.from!=="string"||typeof d.to!=="string")return;let I=d.from.trim(),M=d.to.trim();if(I.length===0||M.length===0)return;return{from:I,to:M}}function zd(d){if(!c(d)||typeof d.check!=="string")return;let I=d.check.trim();if(I.length===0)return;let M=g(d.allowedStates),E=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...M?{allowedStates:M}:{},check:I,...E?{fallbackInstruction:E}:{},...R?{subject:R}:{}}}function xd(d){if(!c(d)||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,R=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...R?{backupMention:R}:{},...M?{preferredAlternatives:M}:{},...E?{replacementTarget:E}:{},warningMessage:I}}function Bd(d){if(!c(d)||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,precondition:I,...R?{subject:R}:{}}}function e(d){if(!c(d)||typeof d.example!=="string"||typeof d.host!=="string"||d.pathPlacement!=="path_after_host"||d.scheme!=="http"&&d.scheme!=="https")return;let I=d.example.trim(),M=d.host.trim();if(I.length===0||M.length===0)return;return{example:I,host:M,pathPlacement:"path_after_host",scheme:d.scheme}}function a(d){if(!c(d)||typeof d.anchor!=="string"||typeof d.example!=="string"||d.variableSegment!=="filename")return;let I=d.anchor.trim(),M=d.example.trim();if(I.length===0||M.length===0)return;return{anchor:I,example:M,variableSegment:"filename"}}function _d(d){if(!c(d)||typeof d.kind!=="string")return;if(d.kind==="recurrence"){if(typeof d.sequenceName!=="string"||typeof d.expression!=="string")return;let I=d.sequenceName.trim(),M=d.expression.trim(),E=Array.isArray(d.baseCases)?d.baseCases.map((R)=>{if(!c(R)||typeof R.index!=="number"||typeof R.value!=="number"||!Number.isInteger(R.index)||!Number.isFinite(R.value))return;return{index:R.index,value:R.value}}).filter((R)=>Boolean(R)):void 0;if(I.length===0||M.length===0)return;return{...E&&E.length>0?{baseCases:E}:{},expression:M,kind:"recurrence",sequenceName:I}}if(d.kind==="binary_operator"){if(typeof d.expression!=="string"||typeof d.leftVariable!=="string"||typeof d.operatorSymbol!=="string"||typeof d.rightVariable!=="string")return;let I=d.expression.trim(),M=d.leftVariable.trim(),E=d.operatorSymbol.trim(),R=d.rightVariable.trim();if(I.length===0||M.length===0||E.length===0||R.length===0)return;return{expression:I,kind:"binary_operator",leftVariable:M,operatorSymbol:E,rightVariable:R}}return}function bd(d){if(!c(d)||d.kind!=="rewrite_output_slot")return;let I=Od(d.exactFragments),M=a(d.pathTemplate),E=g(d.preferredAlternatives),R=g(d.preferredFragments),S=Array.isArray(d.replacementPairs)?d.replacementPairs.map((O)=>l(O)).filter((O)=>Boolean(O)):void 0,P=e(d.urlTemplate),k=_d(d.computedResponseRule);if(!k&&!I&&!M&&!E&&!R&&!S&&!P)return;return{...k?{computedResponseRule:k}:{},...I?{exactFragments:I}:{},kind:"rewrite_output_slot",...M?{pathTemplate:M}:{},...E?{preferredAlternatives:E}:{},...R?{preferredFragments:R}:{},...S&&S.length>0?{replacementPairs:S}:{},...P?{urlTemplate:P}:{}}}function Fd(d){if(!c(d)||d.kind!=="require_warning"||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=a(d.pathTemplate),R=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,S=e(d.urlTemplate),P=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...P?{backupMention:P}:{},kind:"require_warning",...E?{pathTemplate:E}:{},...M?{preferredAlternatives:M}:{},...R?{replacementTarget:R}:{},...S?{urlTemplate:S}:{},warningMessage:I}}function fd(d){if(!c(d)||d.kind!=="block_surface")return;let I=g(d.forbiddenFragments);if(!I)return;let M=Array.isArray(d.replacementPairs)?d.replacementPairs.map((R)=>l(R)).filter((R)=>Boolean(R)):void 0,E=typeof d.fallbackAnswer==="string"&&d.fallbackAnswer.trim().length>0?d.fallbackAnswer.trim():void 0;return{...E?{fallbackAnswer:E}:{},forbiddenFragments:I,kind:"block_surface",...M&&M.length>0?{replacementPairs:M}:{}}}function od(d){if(!c(d)||d.kind!=="require_precondition_check"||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,kind:"require_precondition_check",precondition:I,...R?{subject:R}:{}}}function hd(d){return bd(d)??Fd(d)??fd(d)??od(d)}function vd(d){if(!c(d)||!Array.isArray(d.operations))return;let I=d.operations.map((M)=>hd(M)).filter((M)=>Boolean(M));if(I.length===0)return;return{...d.bulletOnly===!0?{bulletOnly:!0}:{},...d.brevityOnly===!0?{brevityOnly:!0}:{},concise:d.concise!==!1,operations:I}}function yd(d){if(!c(d))return;let I=g(d.actionSummaryContains),M=g(d.queryContains),E=g(d.argumentOrder),R=Od(d.exactFragments),S=g(d.forbiddenFragments),P=g(d.preferredAlternatives),k=g(d.preferredFragments),O=a(d.pathTemplate),s=_d(d.computedResponseRule),G=Array.isArray(d.replacementPairs)?d.replacementPairs.map((U)=>l(U)).filter((U)=>Boolean(U)):void 0,Q=e(d.urlTemplate),j=zd(d.guard),H=Bd(d.guardedBehavior)??(j?{allowedWhen:j.allowedStates,fallbackBehavior:{warningMessage:j.fallbackInstruction??"Warn or defer instead of assuming the precondition already passed."},precondition:j.check,...j.subject?{subject:j.subject}:{}}:void 0),C=Wd(d.canonicalFirstAction),x=vd(d.textResponsePlan),A=typeof d.appliesTo==="string"?W(d.appliesTo):void 0,D=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,K=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...I?{actionSummaryContains:I}:{},...A?{appliesTo:A}:{},...E?{argumentOrder:E}:{},...K?{backupMention:K}:{},...C?{canonicalFirstAction:C}:{},...s?{computedResponseRule:s}:{},...R?{exactFragments:R}:{},...D?{fallbackInstruction:D}:{},...S?{forbiddenFragments:S}:{},...j?{guard:j}:{},...H?{guardedBehavior:H}:{},...P?{preferredAlternatives:P}:{},...k?{preferredFragments:k}:{},...O?{pathTemplate:O}:{},...M?{queryContains:M}:{},...G&&G.length>0?{replacementPairs:G}:{},...x?{textResponsePlan:x}:{},...Q?{urlTemplate:Q}:{}}}function c(d){return typeof d==="object"&&d!==null}function g(d){if(!Array.isArray(d)||!d.every((M)=>typeof M==="string"))return;let I=X(d);return I.length>0?I:void 0}function wd(d){if(!c(d))return;if(d.behavioralKind!=="preference"&&d.behavioralKind!=="avoidance"&&d.behavioralKind!=="guarded_policy"&&d.behavioralKind!=="format_contract"&&d.behavioralKind!=="first_action"&&d.behavioralKind!=="syntax_constraint"&&d.behavioralKind!=="transformation_rule"&&d.behavioralKind!=="exemplar_fact")return;if(d.transferMode!=="example_only"&&d.transferMode!=="pattern_bounded"&&d.transferMode!=="general")return;if(d.enactmentSurface!=="text_response"&&d.enactmentSurface!=="host_action")return;return{behavioralKind:d.behavioralKind,enactmentSurface:d.enactmentSurface,applicability:yd(d.applicability)??{},transferMode:d.transferMode}}function qd(d){return JSON.stringify(d)}function rd(d){if(d.enactmentSurface==="host_action")return!1;let I=d.applicability;return Boolean(I.argumentOrder||I.canonicalFirstAction||I.exactFragments||I.fallbackInstruction||I.forbiddenFragments&&I.forbiddenFragments.length>0||I.guard||I.guardedBehavior||I.pathTemplate||I.preferredAlternatives&&I.preferredAlternatives.length>0||I.replacementPairs&&I.replacementPairs.length>0||I.textResponsePlan||I.urlTemplate)}function uI(d,I){return{...d??{},[Ed]:qd(I),...rd(I)?{[Md]:!0}:{},[Zd]:Jd}}function ld(d){let I=d?.[Ed];if(typeof I!=="string"||I.trim().length===0)return;try{return wd(JSON.parse(I))}catch{return}}function sd(d){return ld(d.attributes)}function tI(d){return d.attributes?.[Md]===!0}function ed(d){if(d.exemplarCount!==void 0&&d.exemplarCount<=1&&!d.hasGeneralRuleMarker)return"example_only";if(d.hasGeneralRuleMarker)return"general";return(d.exemplarCount??0)>=2?"pattern_bounded":"example_only"}function ad(d){let{forbidden:I,preferred:M}=d,E=I.match(t)?.[0],R=M.match(t)?.[0],S=[];if(!I.startsWith(".")||M.startsWith("."))S.push({from:I,to:M});if(E&&R)S.push({from:E,to:R});return{forbiddenFragments:X([I,E]),preferredFragments:X([M,R]),replacementPairs:Cd(S)}}function ud(d){let{target:I,preferredAlternative:M}=d;return{fallbackInstruction:`Warn and route to ${M??"a specialist path"} instead of using the distrusted default path.`,forbiddenFragments:[I],...M?{preferredAlternatives:[M]}:{},queryContains:[I]}}function td(d){let{allowedStates:I,check:M,subject:E}=d;return{...I.length>0?{allowedStates:I}:{},check:M,fallbackInstruction:`Check ${M} first${I.length>0?` and only proceed when ${I.join(" or ")}`:""}; otherwise warn or defer instead of assuming it already passed.`,...E?{subject:E}:{}}}function id(d){let I,M;if(d.template){let E=d.template,R=new URL(E.replace(Vd,"page"));I=[`${R.protocol}//${R.host}/`],M={example:E,host:R.host,pathPlacement:"path_after_host",scheme:R.protocol==="https:"?"https":"http"}}return{fallbackInstruction:"If the current probe explicitly requests http, warn first and then offer the https URL instead of silently substituting protocols.",forbiddenFragments:[u.from],...I?{preferredFragments:I}:{},queryContains:["url"],replacementPairs:[u],...M?{urlTemplate:M}:{}}}function pd(d){let{forbiddenRoot:I,safeTemplate:M}=d,E,R;if(M){let S=M,P=S.replace(/<file>$/u,"");E=[P],R={anchor:P,example:S,variableSegment:"filename"}}if(!I&&!R&&!d.userHomeRequired)return null;return{fallbackInstruction:"Refuse the unsafe path and redirect to a safe user-writable home-directory path instead.",...I?{forbiddenFragments:[I]}:{},...E?{preferredFragments:E}:d.userHomeRequired?{preferredFragments:["/home/"]}:{},...R?{pathTemplate:R}:{}}}function nd(d){return d?.[0]}function dI(d){let I=d.fallbackInstruction??(d.preferredAlternatives&&d.preferredAlternatives.length>0?`Warn first and redirect to ${d.preferredAlternatives.join(" or ")} instead of proceeding directly.`:void 0);if(!I)return;return{...d.backupMention?{backupMention:d.backupMention}:{},...d.preferredAlternatives&&d.preferredAlternatives.length>0?{preferredAlternatives:[...d.preferredAlternatives]}:{},...d.replacementTarget?{replacementTarget:d.replacementTarget}:{},warningMessage:I}}function $(d){let I=[],M={...d.applicability.computedResponseRule?{computedResponseRule:d.applicability.computedResponseRule}:{},kind:"rewrite_output_slot",...d.applicability.exactFragments?{exactFragments:d.applicability.exactFragments}:{},...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...d.applicability.preferredAlternatives&&d.applicability.preferredAlternatives.length>0?{preferredAlternatives:d.applicability.preferredAlternatives}:{},...d.applicability.preferredFragments&&d.applicability.preferredFragments.length>0?{preferredFragments:d.applicability.preferredFragments}:{},...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{}};if(M.computedResponseRule||M.exactFragments||M.pathTemplate||M.preferredAlternatives||M.preferredFragments||M.replacementPairs||M.urlTemplate)I.push(M);if(d.applicability.forbiddenFragments&&d.applicability.forbiddenFragments.length>0)I.push({forbiddenFragments:[...d.applicability.forbiddenFragments],kind:"block_surface",...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{}});if(d.applicability.guardedBehavior)I.unshift({...d.applicability.guardedBehavior.allowedWhen?{allowedWhen:d.applicability.guardedBehavior.allowedWhen}:{},fallbackBehavior:d.applicability.guardedBehavior.fallbackBehavior,kind:"require_precondition_check",precondition:d.applicability.guardedBehavior.precondition,...d.applicability.guardedBehavior.subject?{subject:d.applicability.guardedBehavior.subject}:{}});else{let E=dI({backupMention:d.applicability.backupMention,fallbackInstruction:d.applicability.fallbackInstruction,preferredAlternatives:d.applicability.preferredAlternatives,replacementTarget:nd(d.applicability.preferredAlternatives)});if(E&&(d.behavioralKind==="avoidance"||d.behavioralKind==="preference"||d.behavioralKind==="transformation_rule"||E.preferredAlternatives&&E.preferredAlternatives.length>0||E.backupMention||E.replacementTarget))I.push({...E.backupMention?{backupMention:E.backupMention}:{},kind:"require_warning",...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...E.preferredAlternatives?{preferredAlternatives:E.preferredAlternatives}:{},...E.replacementTarget?{replacementTarget:E.replacementTarget}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{},warningMessage:E.warningMessage})}return I.length>0?{concise:!0,operations:I}:void 0}function II(d){return d.formatRule}function y(d){return d.negativeRule}function EI(d){return d.firstActionName!==void 0}function MI(d){return d.firstActionName}function RI(d){return d.generalRule}function SI(d){let I=d.match(/\b([A-Z][A-Za-z0-9_]*)\(n\)\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(I?.[1]&&I[2]){let E=I[1].trim(),R=I[2].trim(),S=[...d.matchAll(new RegExp(`${b(E)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))].map((P)=>{let k=Number(P[1]),O=Number(P[2]);if(!Number.isInteger(k)||!Number.isFinite(O))return;return{index:k,value:O}}).filter((P)=>Boolean(P));return{...S.length>0?{baseCases:S}:{},expression:R,kind:"recurrence",sequenceName:E}}let M=d.match(/\b([a-z])\s*([⊗⊕⊖Ω])\s*([a-z])\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(M?.[1]&&M[2]&&M[3]&&M[4])return{expression:M[4].trim(),kind:"binary_operator",leftVariable:M[1].trim(),operatorSymbol:M[2].trim(),rightVariable:M[3].trim()};return}function PI(d){let I=d.language??w,M=d.languageContext??I.resolveFromText({text:d.rule}),E=I.analyzeBehavioralRule(d.rule,M),R=RI(E),S=ed({exemplarCount:d.exemplarCount,hasGeneralRuleMarker:R}),P=E.triggerPhrases,k=W(d.appliesTo),O=E.protocolRewrite?id(E.protocolRewrite):null,s=E.directoryRestriction?pd(E.directoryRestriction):null,G=E.filetypeReplacement?ad(E.filetypeReplacement):null,Q=E.distrustRouting?ud(E.distrustRouting):null,j=E.exactAction?r(E.exactAction):void 0,H=SI(d.rule),C=X([...E.preferredAlternatives??[],...Q?.preferredAlternatives??[]]),x=E.guard?td(E.guard):void 0,A=X([...E.triggerPhrases??[],...x?.check?[x.check]:[],...x?.subject?[x.subject]:[],...O?.queryContains??[],...Q?.queryContains??[]]),D=E.backupRequested?"Mention a safe backup before proceeding.":void 0,K=X([...E.forbiddenFragments??[],...O?.forbiddenFragments??[],...s?.forbiddenFragments??[],...G?.forbiddenFragments??[],...Q?.forbiddenFragments??[]]),U=X([...E.preferredFragments??[],...O?.preferredFragments??[],...s?.preferredFragments??[],...G?.preferredFragments??[]]),Y=s?.pathTemplate,N=Cd([...O?.replacementPairs??[],...G?.replacementPairs??[]]),Z=O?.urlTemplate,J=x?.fallbackInstruction??Q?.fallbackInstruction??O?.fallbackInstruction??s?.fallbackInstruction??(C.length>0&&y(E)?`Prefer ${C.join(" or ")}${D?" and mention a safe backup before proceeding":""} or warn instead of implying the avoided behavior.`:void 0),L=x?{...x.allowedStates?{allowedWhen:x.allowedStates}:{},fallbackBehavior:{...D?{backupMention:D}:{},...C.length>0?{preferredAlternatives:C}:{},...C[0]?{replacementTarget:C[0]}:{},warningMessage:x.fallbackInstruction??"Warn or defer instead of assuming the required precondition already passed."},precondition:x.check,...x.subject?{subject:x.subject}:{}}:void 0;if(j||EI(E)){let _=MI(E),m=E.argumentOrder;return{behavioralKind:y(E)||d.kind==="dont"?"first_action":"syntax_constraint",enactmentSurface:"host_action",applicability:{appliesTo:k,...j?{canonicalFirstAction:j}:_?{canonicalFirstAction:{kind:_.includes("_")?"tool_call":"command",name:_}}:{},...m?{argumentOrder:m}:{},...P&&!j?{queryContains:P}:{}},transferMode:S==="general"?"pattern_bounded":S}}if(II(E)){let{formatPrefix:_,formatSuffix:m}=E,F=X([...(E.requiredFragments??[]).filter((Ud)=>Ud!==m),_,m]);return{behavioralKind:"format_contract",enactmentSurface:"text_response",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{},textResponsePlan:$({behavioralKind:"format_contract",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{}}})},transferMode:S}}if(d.kind==="prefer"){let _={appliesTo:k,...D?{backupMention:D}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...A.length>0?{queryContains:A}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"preference",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"preference",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"preference",applicability:_})}:{}},transferMode:S}}if(d.kind==="dont"||y(E)){let _={appliesTo:k,...D?{backupMention:D}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...A.length>0?{queryContains:A}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"avoidance",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})}:{}},transferMode:S}}if(d.kind==="do"&&!P){let _={appliesTo:k,...D?{backupMention:D}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...A.length>0?{queryContains:A}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}if(R||(d.exemplarCount??0)>=2){let _={appliesTo:k,...D?{backupMention:D}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...A.length>0?{queryContains:A}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}let v={appliesTo:k,...D?{backupMention:D}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...A.length>0?{queryContains:A}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:"exemplar_fact",enactmentSurface:"text_response",applicability:{...v,...$({behavioralKind:"exemplar_fact",applicability:v})?{textResponsePlan:$({behavioralKind:"exemplar_fact",applicability:v})}:{}},transferMode:"example_only"}}function z(d,I){if(!I||I.length===0)return[];let M=T(d);return I.filter((E)=>M.includes(T(E)))}function Cd(d){let I=[],M=new Set;for(let E of d){if(!E)continue;let R=`${E.from}\x00${E.to}`;if(M.has(R))continue;M.add(R),I.push(E)}return I}function kI(d){if(!d.transientFeedback||d.transientFeedback.length===0)return[];let I=W(d.appliesTo),M=T(d.query),E=[];for(let R of d.transientFeedback){if(R.lifecycle!=="active"||R.kind==="validated_pattern")continue;if(sd(R))continue;let S=PI({appliesTo:R.appliesTo,exemplarCount:1,kind:R.kind,rule:R.rule});if(S.enactmentSurface!==d.surface)continue;let P=W(S.applicability.appliesTo??R.appliesTo),k=P===I;if(!k&&P!=="general_response")continue;let O=X([...z(M,S.applicability.queryContains),...z(M,S.applicability.actionSummaryContains),...z(M,S.applicability.forbiddenFragments),...z(M,S.applicability.preferredFragments)]),s=O.length===0&&(d.surface==="text_response"?f(S):Yd(S))&&(S.applicability.queryContains?.length??0)===0;if(S.transferMode!=="general"&&O.length===0&&!s)continue;let G=(k?1e4:0)+Rd[S.behavioralKind]*100+Sd[S.transferMode]*10+O.length+(s?3:0)+5;E.push({feedback:R,matchedQueryTokens:O,policy:S,score:G})}return E}function iI(d){let I=W(d.appliesTo),M=T(d.query),E=[];for(let S of d.feedback??[]){if(S.lifecycle!=="active")continue;let P=sd(S);if(!P||P.enactmentSurface!==d.surface)continue;let k=W(P.applicability.appliesTo??S.appliesTo),O=k===I;if(!O&&k!=="general_response")continue;let s=X([...z(M,P.applicability.queryContains),...z(M,P.applicability.actionSummaryContains),...z(M,P.applicability.forbiddenFragments),...z(M,P.applicability.preferredFragments)]);if(P.transferMode==="example_only"&&s.length===0)continue;let G=(O?1e4:0)+(d.surface==="host_action"&&P.enactmentSurface==="host_action"?2000:0)+Rd[P.behavioralKind]*100+Sd[P.transferMode]*10+s.length;E.push({feedback:S,matchedQueryTokens:s,policy:P,score:G})}let R=kI(d);return[...E,...R].sort((S,P)=>P.score-S.score)}function OI(d){let I=new Set,M=[];for(let E of d){let R=JSON.stringify(E);if(I.has(R))continue;I.add(R),M.push(E)}return M}function pI(d){return xI(d.map((I)=>I.policy))}function xI(d){let I=OI(d.flatMap((R)=>{if(R.enactmentSurface!=="text_response")return[];return R.applicability.textResponsePlan?.operations??$({behavioralKind:R.behavioralKind,applicability:R.applicability})?.operations??[]}));if(I.length===0)return;let M=d.some((R)=>R.applicability.textResponsePlan?.brevityOnly===!0);return{...d.some((R)=>R.applicability.textResponsePlan?.bulletOnly===!0)?{bulletOnly:!0}:{},...M?{brevityOnly:!0}:{},concise:!0,operations:I}}function _I(d){switch(d.kind){case"rewrite_output_slot":return[d.computedResponseRule?d.computedResponseRule.kind==="recurrence"?`rewrite_output_slot recurrence_rule: ${d.computedResponseRule.sequenceName}(n) = ${d.computedResponseRule.expression}`:`rewrite_output_slot binary_rule: ${d.computedResponseRule.leftVariable} ${d.computedResponseRule.operatorSymbol} ${d.computedResponseRule.rightVariable} = ${d.computedResponseRule.expression}`:void 0,d.replacementPairs&&d.replacementPairs.length>0?`rewrite_output_slot replacements: ${d.replacementPairs.map((I)=>`${I.from} -> ${I.to}`).join(", ")}`:void 0,d.urlTemplate?`rewrite_output_slot url_template: keep ${d.urlTemplate.scheme}://${d.urlTemplate.host} and place the requested page after the host as a path segment`:void 0,d.pathTemplate?`rewrite_output_slot path_template: keep safe anchor ${d.pathTemplate.anchor} and preserve the requested filename`:void 0,d.exactFragments?.prefixes?.length?`rewrite_output_slot prefix: ${d.exactFragments.prefixes[0]}`:void 0,d.exactFragments?.suffixes?.length?`rewrite_output_slot suffix: ${d.exactFragments.suffixes[0]}`:void 0].filter((I)=>Boolean(I));case"block_surface":return[`block_surface forbidden: ${d.forbiddenFragments.join(", ")}`,d.fallbackAnswer?`block_surface fallback: ${d.fallbackAnswer}`:void 0].filter((I)=>Boolean(I));case"require_warning":return[`require_warning: ${d.warningMessage}`,d.preferredAlternatives&&d.preferredAlternatives.length>0?`warning_alternatives: ${d.preferredAlternatives.join(", ")}`:void 0,d.backupMention?`warning_backup: ${d.backupMention}`:void 0].filter((I)=>Boolean(I));case"require_precondition_check":return[`require_precondition_check: ${d.precondition}`,d.allowedWhen&&d.allowedWhen.length>0?`allowed_when: ${d.allowedWhen.join(" or ")}`:void 0,`fallback_behavior: ${d.fallbackBehavior.warningMessage}`].filter((I)=>Boolean(I))}}function nI(d){if(!d)return[];return X([...d.brevityOnly?["brevity_only: emit only the answer surface with no extra explanation"]:[],...d.bulletOnly?["bullet_only: emit a terse bullet list with no paragraph preface"]:[],...d.operations.flatMap((I)=>_I(I))])}function b(d){return d.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Ld(d){return Number.isInteger(d)?String(d):String(Number(d.toFixed(10)))}function Gd(d){let I=d.expression.replace(/\^/gu,"**");for(let[M,E]of Object.entries(d.scope).sort(([R],[S])=>S.length-R.length))I=I.replace(new RegExp(`\\b${b(M)}\\b`,"gu"),`(${E})`);if(/[^0-9+\-*/().\s*]/u.test(I))return;try{let M=Function(`"use strict"; return (${I});`)();return typeof M==="number"&&Number.isFinite(M)?M:void 0}catch{return}}function sI(d){let I=new Map;for(let M of d.query.matchAll(new RegExp(`${b(d.sequenceName)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))){let E=Number(M[1]),R=Number(M[2]);if(!Number.isInteger(E)||!Number.isFinite(R))continue;I.set(E,R)}return I}function CI(d){let I=d.query.match(new RegExp(`${b(d.rule.sequenceName)}\\((-?\\d+)\\)(?!\\s*=)`,"u"));if(!I?.[1])return;let M=Number(I[1]);if(!Number.isInteger(M))return;let E=new Map;for(let O of d.rule.baseCases??[])E.set(O.index,O.value);for(let[O,s]of sI({query:d.query,sequenceName:d.rule.sequenceName}))E.set(O,s);let R=new Set,S=new RegExp(`${b(d.rule.sequenceName)}\\(n\\s*([+-])\\s*(\\d+)\\)`,"gu"),P=(O)=>{if(E.has(O))return E.get(O);if(R.has(O))return;R.add(O);let s=d.rule.expression.replace(S,(Q,j,H)=>{let C=Number(H);if(!Number.isInteger(C))return"NaN";let x=j==="+"?O+C:O-C,A=P(x);return A===void 0?"NaN":`(${A})`});s=s.replace(/\bn\b/gu,`(${O})`);let G=Gd({expression:s,scope:{}});if(R.delete(O),G===void 0)return;return E.set(O,G),G},k=P(M);return k===void 0?void 0:Ld(k)}function LI(d){let I=d.query.match(new RegExp(`(-?\\d+(?:\\.\\d+)?)\\s*${b(d.rule.operatorSymbol)}\\s*(-?\\d+(?:\\.\\d+)?)`,"u"));if(!I?.[1]||!I[2])return;let M=Number(I[1]),E=Number(I[2]);if(!Number.isFinite(M)||!Number.isFinite(E))return;let R=Gd({expression:d.rule.expression,scope:{[d.rule.leftVariable]:M,[d.rule.rightVariable]:E}});return R===void 0?void 0:Ld(R)}function dE(d){if(!d.query||!d.rule)return;switch(d.rule.kind){case"recurrence":return CI({query:d.query,rule:d.rule});case"binary_operator":return LI({query:d.query,rule:d.rule})}}function q(d){if(d.startsWith("~/")){let I=d.slice(2).split("/").filter(Boolean);return I.length>0?`|~|${I.join("|")}|`:"|~|"}if(d.startsWith("/")){let I=d.split("/").filter(Boolean);return I.length>0?`|${I.join("|")}|`:"|/|"}return`|${d}|`}function gd(d){if(!d)return;return(B(d)?.namedTarget??jd(d)[0])?.trim().replace(/[.,;:!?]+$/u,"")}function GI(d){if(!d)return;let I=B(d),M=I?.pathBase,E=I?.namedTarget,R=M?.replace(/[.,;:!?]+$/u,""),S=E?.replace(/[.,;:!?]+$/u,"");if(R){let k=R.endsWith("/")?`${R}${S??""}`.replace(/\/+$/u,""):S?`${R}/${S}`:R;return q(k)}let P=gd(d);return P?q(P):void 0}function h(d){return jd(d??"")[0]?.trim()}function gI(d,I){let M=h(d);if(!M)return;let R=/_<token>|<token>_/u.test(I??"")?M.replace(/[^A-Za-z0-9]+/gu,"_").replace(/^_+|_+$/gu,""):M.replace(/[^A-Za-z0-9]/gu,"");return R&&R.length>0?R:void 0}function cI(d){if(!d)return;return B(d)?.structuredTerms?.join(" ")}function cd(d){if(!d)return;return B(d)?.comparison?.field}function Ad(d){return B(d)?.comparison?.operator}function AI(d){if(/^-?\d+(?:\.\d+)?$/u.test(d))return d;if(/^['"].*['"]$/u.test(d))return d;return`'${d}'`}function DI(d){return d.replace(/^['"]|['"]$/gu,"").replace(/[.,;:!?]+$/u,"")}function Dd(d){if(!d)return;let I=B(d)?.comparison?.value;if(I)return AI(DI(I));return}function jI(d,I){if(!I)return;let M=d.match(/^(.+\|\s*FILTER\s+)[A-Za-z_][A-Za-z0-9_.-]*\s*(?:>=|<=|=|>|<)\s*.+$/iu);if(!M?.[1])return;let E=cd(I),R=Ad(I),S=Dd(I);if(!E||!R||!S)return;return`${M[1]}${E} ${R} ${S}`}function HI(d,I){let M=d;if(M.includes("|folder|")){let E=gd(I);if(!E)return;M=M.replace(/\|folder\|/gu,q(E))}if(M.includes("|path|")){let E=GI(I);if(!E)return;M=M.replace(/\|path\|/gu,E)}if(M.includes("<filename>")){let E=h(I);if(!E)return;M=M.replace(/<filename>/gu,E)}if(M.includes("<id>")){let E=h(I);if(!E)return;M=M.replace(/<id>/gu,E)}if(M.includes("<item>")){let E=h(I);if(!E)return;M=M.replace(/<item>/gu,E)}if(M.includes("<qty>")){let E=I?.match(/\bqty\b[^0-9]*([0-9]+)/iu)?.[1]??I?.match(/\b([0-9]+)\b/u)?.[1];if(!E)return;M=M.replace(/<qty>/gu,E)}if(M.includes("<terms>")){let E=cI(I);if(!E)return;M=M.replace(/<terms>/gu,E)}if(M.includes("<token>")){let E=gI(I,M);if(!E)return;M=M.replace(/<token>/gu,E)}if(M.includes("<field>")){let E=cd(I);if(!E)return;M=M.replace(/<field>/gu,E)}if(M.includes("<operator>")){let E=Ad(I);if(!E)return;M=M.replace(/<operator>/gu,E)}if(M.includes("<value>")){let E=Dd(I);if(!E)return;M=M.replace(/<value>/gu,E)}return/<[^>]+>/u.test(M)?void 0:M}function V(d){return`'${d.replaceAll("'","\\'")}'`}function NI(d){return d.endsWith("/")}function UI(d,I){if(!NI(d))return d;let M=I.split("/").filter(Boolean).at(-1);return M?`${d}${M}`:d}function KI(d){let I=T(d.argumentLabel),M=d.sourcePaths[d.usedSourceCount];if(I.includes("action")){let E=d.hostAction.verb;return E?V(E):void 0}if(I.includes("owner")){let E=d.hostAction.owner;return E?V(E):void 0}if(I.includes("permission")||I.includes("perms")){let E=d.hostAction.permissions;return E?V(E):void 0}if(I.includes("compression")){let E=d.hostAction.compression;return E?V(E):void 0}if(I.includes("flags")){let E=d.hostAction.flags??[];if(E.length===0)return;return`[${E.map((R)=>V(R)).join(",")}]`}if(I.includes("tag")){let E=d.hostAction.tag;return E?V(E):void 0}if(I.includes("mode")){let E=d.hostAction.mode;return E?V(E):void 0}if(I.includes("sources")){if(d.sourcePaths.length===0)return;return`[${d.sourcePaths.map((E)=>V(E)).join(",")}]`}if(I.includes("source"))return M?V(M):void 0;if(I.includes("destination")||I.includes("target")||I.includes("archive")){let E=d.destinationPath;if(!E)return;let R=d.sourcePaths[0],S=/\b(?:directory|folder|root)\b/iu.test(I)||/(?:^|_)dir(?:_|$)/iu.test(I);return V(R&&!S?UI(E,R):E)}return}function n(d,I){let M=d.applicability.canonicalFirstAction;if(M?.kind!=="tool_call"||!M.name||!M.args||M.args.length===0)return M;let E=B(I)?.hostAction;if(!E)return M;let R=E.sources??[],S=E.destination,P=[],k=0;for(let O of M.args){let s=KI({argumentLabel:O,destinationPath:S,hostAction:E,sourcePaths:R,usedSourceCount:k});if(!s)return M;P.push(s);let G=T(O);if(G.includes("source")&&!G.includes("sources"))k+=1}return{args:P,kind:"tool_call",name:M.name,raw:`${M.name}(${P.join(", ")})`}}function IE(d){let I=[];for(let{feedback:M,policy:E}of d){if(E.enactmentSurface!=="text_response")continue;if(E.behavioralKind==="format_contract"){let R=E.applicability.exactFragments?.prefixes??[],S=E.applicability.exactFragments?.required??[],P=E.applicability.exactFragments?.suffixes??[];if(R.length>0)I.push(`Start the response with "${R[0]}".`);for(let k of S)I.push(`Include the exact fragment "${k}".`);if(P.length>0)I.push(`End the response with "${P[0]}".`);if(M.rule)I.push(`Follow this exact formatting rule: ${M.rule}`);continue}for(let R of E.applicability.replacementPairs??[])I.push(`If the answer would contain "${R.from}", rewrite it to "${R.to}" instead of emitting the disallowed form.`);for(let R of E.applicability.forbiddenFragments??[])I.push(`Do not emit the exact fragment "${R}" in the final answer unless directly quoting user input.`);for(let R of E.applicability.preferredFragments??[])I.push(`Prefer a safe replacement fragment such as "${R}" when the current probe matches.`);if(E.applicability.urlTemplate){let{urlTemplate:R}=E.applicability;I.push(`When answering with a URL, keep the established origin "${R.scheme}://${R.host}" and place the requested page after the host as a path segment, for example "${R.example}".`),I.push("Do not rewrite the requested page into a subdomain when the learned URL pattern uses a path after the host.")}if(E.applicability.pathTemplate){let{pathTemplate:R}=E.applicability;I.push(`When redirecting a file path, keep the established safe directory anchor "${R.anchor}" and preserve the requested filename under that directory, for example "${R.example}".`),I.push("Do not invent a new top-level directory when the learned safe path already provides a concrete user-writable location.")}if(E.applicability.guard){let{guard:R}=E.applicability,S=R.subject?`"${R.subject}"`:"the guarded behavior";if(I.push(`Before using or implying ${S}, ${R.check}.`),(R.allowedStates?.length??0)>0)I.push(`Only proceed when the required check resolves to ${R.allowedStates.join(" or ")}.`);if(R.fallbackInstruction)I.push(R.fallbackInstruction)}if((E.applicability.preferredAlternatives?.length??0)>0)I.push(`Prefer ${E.applicability.preferredAlternatives.map((R)=>`"${R}"`).join(" or ")} as the safer replacement behavior when the trigger matches.`);if(E.applicability.fallbackInstruction)I.push(E.applicability.fallbackInstruction);if(f(E))I.push("If a short compliant answer, redirect, or warning already satisfies the request, stop there instead of expanding into a longer response.");if(E.behavioralKind==="transformation_rule"){if(M.rule&&!f(E))I.push(`Apply this rule only when it matches the current probe: ${M.rule}`);continue}if(E.behavioralKind==="preference"){if(M.rule&&!f(E))I.push(`Prefer this behavior when it fits the current probe: ${M.rule}`);continue}if(E.behavioralKind==="avoidance"){if(M.rule&&!f(E))I.push(`Avoid this behavior when the trigger matches: ${M.rule}`);continue}if(E.behavioralKind==="exemplar_fact"&&M.rule){I.push(`Treat this as example-bound guidance unless the probe clearly matches: ${M.rule}`);continue}}return X(I)}function jd(d){return[...d.matchAll(/(?<![\p{L}\p{N}_/])(['"`])([^'"`]+)\1(?![\p{L}\p{N}_/])/gu)].map((I)=>I[2]?.trim()).filter((I)=>Boolean(I))}function dd(d){let I=B(d.query)?.hostAction,M=I?.sources?.[0],E=I?.destination;if(!M||!E)return;if(E.endsWith("/")){let R=M.split("/").filter(Boolean).at(-1);if(R)E=`${E}${R}`}return{args:[`'${E}'`,`'${M}'`],kind:"tool_call",name:d.name,raw:`${d.name}('${E}', '${M}')`}}function $I(d,I){let M=d.applicability.canonicalFirstAction;if(M?.raw){let S=HI(M.raw,I);if(S){let P=r(jI(S,I)??S);if(I&&P?.kind==="tool_call"&&(d.applicability.argumentOrder??[]).length>=2&&/(?:destination|target|archive)/iu.test(T(d.applicability.argumentOrder?.[0]))&&T(d.applicability.argumentOrder?.[1]).includes("source"))return dd({name:P.name,query:I})??P;if(I&&P?.kind==="tool_call"&&P.args&&P.args.every((k)=>/^[a-z_][a-z0-9_]*$/iu.test(k)))return n({...d,applicability:{...d.applicability,canonicalFirstAction:P}},I);return P}if(/<[^>]+>|\|(?:folder|path)\|/u.test(M.raw))return;return M}if(!M?.name||!I)return M;let E=M.name.trim();if(M.kind==="tool_call"&&M.args&&M.args.every((S)=>/^[a-z_][a-z0-9_]*$/iu.test(S)))return n(d,I);let R=d.applicability.argumentOrder??[];if(R.length<2||!/(?:destination|target|archive)/iu.test(T(R[0]))||!T(R[1]).includes("source"))return M;return dd({name:E,query:I})??M}function EE(d){let I=r(d.template);if(!I)return;return $I({behavioralKind:"first_action",enactmentSurface:"host_action",applicability:{appliesTo:"general_response",canonicalFirstAction:I},transferMode:"pattern_bounded"},d.query)?.raw??I.raw}var RE="session_archives",SE="experiences",PE="learning_proposals",kE="promotion_records";function XI(d,I){return d??I??new Date(0).toISOString()}function OE(d){let I=XI(d.createdAt,d.archivedAt);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,sourceSessionIds:d.sourceSessionIds??[d.sessionId],summary:d.summary,normalizedTranscript:d.normalizedTranscript,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],referencedArtifacts:d.referencedArtifacts??[],scopeLineage:d.scopeLineage??[],locale:d.locale,createdAt:I,archivedAt:d.archivedAt??I}}function xE(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,kind:d.kind,traceId:d.traceId,sourceTraceIds:d.sourceTraceIds??[d.traceId],trigger:d.trigger??"api",modelInfluence:d.modelInfluence??"none",summary:d.summary,outcome:d.outcome??"success",policyApplied:d.policyApplied??[],metrics:d.metrics??{},linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],linkedProposalIds:d.linkedProposalIds??[],...d.metadata?{metadata:d.metadata}:{},createdAt:d.createdAt??new Date(0).toISOString()}}function _E(d){let I=d.createdAt??new Date(0).toISOString();return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,proposalType:d.proposalType,status:d.status??"pending",traceId:d.traceId,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],modelInfluence:d.modelInfluence??"none",createdAt:I,updatedAt:d.updatedAt??I}}function sE(d){let I=d.decidedAt??d.createdAt??new Date(0).toISOString();return{id:d.id,proposalId:d.proposalId,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,traceId:d.traceId,decision:d.decision,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],policyOutcome:d.policyOutcome??"not_run",verificationOutcome:d.verificationOutcome??"not_run",evalOutcome:d.evalOutcome??"not_run",createdAt:d.createdAt??I,decidedAt:I}}var Hd=Symbol.for("goodmemory.eval.support");function gE(d,I){return d[Hd]=I,d}function cE(d){return d[Hd]}var Nd=Symbol.for("goodmemory.integration.support");function DE(d,I){return d[Nd]=I,d}function jE(d){return d[Nd]}
export{Kd as Ja,YI as Ka,ZI as La,W as Ma,JI as Na,VI as Oa,TI as Pa,mI as Qa,QI as Ra,WI as Sa,zI as Ta,BI as Ua,bI as Va,FI as Wa,oI as Xa,hI as Ya,Td as Za,aI as _a,uI as $a,tI as ab,SI as bb,PI as cb,iI as db,pI as eb,xI as fb,nI as gb,dE as hb,IE as ib,EE as jb,yI as kb,wI as lb,qI as mb,RE as nb,SE as ob,PE as pb,kE as qb,OE as rb,xE as sb,_E as tb,sE as ub,gE as vb,cE as wb,DE as xb,jE as yb};
import{Za as S,bb as A0,cb as d0,fb as y0,gb as x0,hb as E0,jb as u,sb as _0}from"./chunk-g7hv64gy.js";import{Jb as f0}from"./chunk-b7j2aytn.js";function X0(G){return(G.codePointAt(0)??0)>127}function FD(G){let D=0,H=0;for(let $ of G)if(X0($))D+=1;else H+=$.length;return D+Math.ceil(H/4)}function SD(G,D){if(D<=0||G.length===0)return"";let H=0,$=0,M=0;for(let V of G){let j=X0(V),J=H+(j?1:0),Z=M+(j?0:V.length);if(J+Math.ceil(Z/4)>D)break;H=J,$+=V.length,M=Z}return G.slice(0,$)}var K0="tool_outcome",s="tool_outcome.";function n0(G){return encodeURIComponent(G)}function t0(G){return decodeURIComponent(G)}function k(G,D){return`${s}${G}=${n0(D)}`}function o(G){return{...G,args:G.args&&G.args.length>0?[...G.args]:void 0,raw:G.raw?.trim()||void 0}}function q(G){if(G.kind==="warning")return G.raw??G.name;let D=G.args&&G.args.length>0?`(${G.args.join(", ")})`:"";return D.length>0?`${G.name}${D}`:G.raw??G.name}function e0(G){let D=o(G);if(D.args)return{kind:D.kind,name:D.name,args:D.args};return{kind:D.kind,name:D.name,...D.raw?{raw:D.raw}:{}}}function U0(G){return JSON.stringify(e0(G))}function ID(G,D){if(!G||!D)return G===D;return U0(G)===U0(D)}function GG(G){let D=[K0,k("cue",G.cue),k("failure_class",G.failureClass),k("first_action.kind",G.firstAction.kind),k("first_action.name",G.firstAction.name)];if(G.firstAction.args&&G.firstAction.args.length>0)D.push(k("first_action.args",JSON.stringify(G.firstAction.args)));if(G.firstAction.raw)D.push(k("first_action.raw",G.firstAction.raw));if(G.retrievalProfile)D.push(k("retrieval_profile",G.retrievalProfile));if(G.saferAlternative){if(D.push(k("safer_alternative.kind",G.saferAlternative.kind)),D.push(k("safer_alternative.name",G.saferAlternative.name)),G.saferAlternative.args&&G.saferAlternative.args.length>0)D.push(k("safer_alternative.args",JSON.stringify(G.saferAlternative.args)));if(G.saferAlternative.raw)D.push(k("safer_alternative.raw",G.saferAlternative.raw))}return D}function zD(G){let D={...G.result,firstAction:o(G.result.firstAction),saferAlternative:G.result.saferAlternative?o(G.result.saferAlternative):void 0},H=D.saferAlternative?` Safer first action: ${q(D.saferAlternative)}.`:"";return{..._0({id:G.createId(),userId:G.scope.userId,tenantId:G.scope.tenantId,workspaceId:G.scope.workspaceId,agentId:G.scope.agentId,sessionId:G.scope.sessionId,kind:"maintenance",traceId:G.traceId,trigger:"api",modelInfluence:D.modelInfluence,summary:`Behavioral tool outcome for cue "${D.cue}": first action ${q(D.firstAction)} failed with ${D.failureClass}.`+H,outcome:D.outcome??"failure",policyApplied:GG(D),metrics:{accepted:0,rejected:1},linkedEvidenceIds:G.linkedEvidenceIds??[],createdAt:G.createdAt}),kind:"tool_outcome"}}function DG(G){return G.kind==="tool_outcome"||G.policyApplied.includes(K0)}function qD(G){return G}function Q0(G,D){let H=G.get(`${D}.kind`),$=G.get(`${D}.name`);if(!H||!$)return;let M=G.get(`${D}.args`),V=G.get(`${D}.raw`),j;if(M)try{let J=JSON.parse(M);if(Array.isArray(J)&&J.every((Z)=>typeof Z==="string"))j=J}catch{j=void 0}return{kind:H,name:$,...j?{args:j}:{},...V?{raw:V}:{}}}function w0(G){if(!DG(G))return null;let D=new Map;for(let J of G.policyApplied){if(!J.startsWith(s))continue;let[Z,W]=J.slice(s.length).split("=",2);if(!Z||W===void 0)continue;D.set(Z,t0(W))}let H=D.get("cue"),$=D.get("failure_class"),M=Q0(D,"first_action");if(!H||!$||!M)return null;let V=D.get("retrieval_profile");return{cue:H,failureClass:$,firstAction:M,retrievalProfile:V==="coding_agent"||V==="general_chat"?V:void 0,saferAlternative:Q0(D,"safer_alternative")}}function hD(G,D){return{...G,compiledGuidance:D}}function vD(G){return G.compiledGuidance}function HG(G){return 1/(1+Math.exp(-G))}function l(G){let D=G.model.bias+G.features.reduce((H,$,M)=>{return H+$*(G.model.weights[M]??0)},0);return{probability:HG(D),score:D}}function R0(G){if(G.samples.length<4)return G.baseModel;let D=[...G.baseModel.weights],H=G.baseModel.bias,$=G.learningRate??0.18,M=G.epochs??60;for(let V=0;V<M;V+=1)for(let j of G.samples){let J=l({features:j.features,model:{bias:H,featureNames:G.baseModel.featureNames,weights:D}}).probability,Z=j.label-J;H+=$*Z;for(let W=0;W<D.length;W+=1)D[W]=(D[W]??0)+$*Z*(j.features[W]??0)}return{bias:H,featureNames:[...G.baseModel.featureNames],weights:D}}function d(G){return(G??"").replace(/\s+/gu," ").trim()}function L0(G,D=140){let H=d(G);if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function h(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function $G(G,D,H){return Math.min(H,Math.max(D,G))}function MG(G){let D=G.selections[0]?.exemplar,H=G.selections.some(($)=>{let M=$.exemplar,V=[M.episodeShape.safeCorrectedMove,M.episodeShape.relevantPriorMove,M.episodeShape.observedOutcome].join(" ");return M.intentCue.query.constraintTypes.includes("precondition")||M.intentCue.query.actionType==="guarded_api"||/\bcheck\b.+\bonly\s+(?:if|when)\b/iu.test(V)});if(G.queryIntent.constraintTypes.includes("formula")||G.queryIntent.actionType==="symbolic_rule")return"symbolic_rule_execution";if(G.surfaceFamily==="text_response"&&(H||G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api"))return"conditional_precondition";if(G.surfaceFamily==="host_action"&&(G.queryIntent.constraintTypes.includes("arg_order")||G.queryIntent.constraintTypes.includes("exact_action")||Boolean(D?.exactSurface?.value)||Boolean(G.queryIntent.exactSlots.commandName)))return D?.exactSurface?.value&&G.selections.length===1&&D.intentCue.query.exactSlots.commandName===G.queryIntent.exactSlots.commandName?"exact_surface_copy":"slot_rebinding";if(G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api")return"conditional_precondition";if(G.queryIntent.actionType==="format_contract")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("style")||G.queryIntent.actionType==="voice_style")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("path_root")||G.queryIntent.constraintTypes.includes("safe_alternative")||G.queryIntent.constraintTypes.includes("url_shape")||G.queryIntent.constraintTypes.includes("analogy"))return"hard_constraint_contract";if(D?.exactSurface?.value&&G.selections.length===1&&D.confidence>=0.72)return"exact_surface_copy";return"slot_rebinding"}function jG(G){let D=G.selections[0]?.exemplar;if(!D)return[];let H=[],$=D.intentCue.query.exactSlots;if($.commandName)H.push(`command=${$.commandName}`);if($.argOrderSignature)H.push(`arg_order=${$.argOrderSignature}`);if($.urlHost)H.push(`url_host=${$.urlHost}`);if($.pathRoot)H.push(`path_root=${$.pathRoot}`);if(D.exactSurface?.kind)H.push(`surface_kind=${D.exactSurface.kind}`);if(D.exactSurface?.formatPrefixes?.length)H.push(`required_prefix=${D.exactSurface.formatPrefixes[0]}`);if(D.exactSurface?.formatSuffixes?.length)H.push(`required_suffix=${D.exactSurface.formatSuffixes[0]}`);if($.styleMarkers.length>0)H.push(`style=${$.styleMarkers.join(",")}`);if(G.queryIntent.constraintTypes.includes("precondition"))H.push("must_check_precondition");if(G.selections.some((M)=>M.exemplar.intentCue.query.constraintTypes.includes("precondition")||M.exemplar.intentCue.query.actionType==="guarded_api"))H.push("must_check_precondition");if(G.computedResponseRule)H.push(G.computedResponseRule.kind==="recurrence"?`formula=${G.computedResponseRule.sequenceName}(n)=${G.computedResponseRule.expression}`:`formula=${G.computedResponseRule.leftVariable}${G.computedResponseRule.operatorSymbol}${G.computedResponseRule.rightVariable}=${G.computedResponseRule.expression}`);if(D.exactSurface?.value)H.push(`surface=${L0(D.exactSurface.value,96)}`);return h(H)}function VG(G){let D=[];if(G.exactSlots.filename)D.push(`filename=${G.exactSlots.filename}`);if(G.exactSlots.extension)D.push(`extension=${G.exactSlots.extension}`);if(G.exactSlots.pathRoot)D.push(`path_root=${G.exactSlots.pathRoot}`);if(G.exactSlots.urlHost)D.push(`url_host=${G.exactSlots.urlHost}`);if(G.exactSlots.urlPath)D.push(`url_path=${G.exactSlots.urlPath}`);if(G.exactSlots.commandName)D.push(`command=${G.exactSlots.commandName}`);if(G.exactSlots.argOrderSignature)D.push(`arg_order=${G.exactSlots.argOrderSignature}`);if(G.exactSlots.operatorSymbols.length>0)D.push(`operators=${G.exactSlots.operatorSymbols.join(",")}`);if(G.exactSlots.styleMarkers.length>0)D.push(`style=${G.exactSlots.styleMarkers.join(",")}`);return h(D)}function JG(G){for(let D of G){let H=[D.exemplar.episodeShape.cue,D.exemplar.episodeShape.relevantPriorMove,D.exemplar.episodeShape.safeCorrectedMove,D.exemplar.exactSurface?.value];for(let $ of H){let M=d($).replace(/,\s*with\s+[A-Z][A-Za-z0-9_]*\((-?\d+)\)\s*=.+$/u,"."),V=A0(M);if(V)return V}}return}function r(G){return d(G).replace(/[^A-Za-z0-9_]+/gu,"_").replace(/^_+|_+$/gu,"").toLowerCase()}function ZG(G){let D=r(G??"value");if(/(?:payload|packet|query|text|term|tag)/u.test(D))return"<terms>";if(/(?:qty|quantity|count|amount|number)/u.test(D))return"<qty>";if(/(?:path|file|filename)/u.test(D))return"<filename>";if(/(?:item|name|label)/u.test(D))return"<item>";if(/(?:id|key|token|query|value|term|record)/u.test(D))return"<id>";return`<${D||"value"}>`}function f(G,D,H){return G.replace(new RegExp(`(['"])(?:${D})\\1\\s*:\\s*(['"])[^'"]+\\2`,"giu"),($)=>$.replace(/(['"])[^'"]+\1\s*$/u,`$1${H}$1`))}function T0(G,D){let H=r(D??""),$=G;$=f($,"query|value|term|terms|text|tag|tags|record","<terms>"),$=f($,"id|key|token","<id>"),$=f($,"path|file|filename","<filename>"),$=f($,"item|name|label","<item>"),$=$.replace(/(['"])(?:qty|quantity|count|amount|number)\1\s*:\s*\d+/giu,(V)=>V.replace(/\d+$/u,"<qty>"));let M=$.match(/^(['"])([^'"]+)\1$/u);if(M){let V=M[1],j=M[2]??"";if(/(?:auth|guard|mode|buffer)/u.test(H))return $;if(/(?:path|file|filename)/u.test(H)||/^(?:\/|~\/)/u.test(j))return`${V}<filename>${V}`;if(/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";if(/(?:item|name|label)/u.test(H))return`${V}<item>${V}`;if(/(?:payload|packet|query|text|term|terms|tag|tags|record)/u.test(H))return`${V}<terms>${V}`;if(/(?:id|key|token)/u.test(H))return`${V}<id>${V}`}if(/^\d+$/u.test($)&&/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";return $}function WG(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function YG(G,D){if(!/\b(?:auth|key|token)\b/iu.test(D))return;return[...G.matchAll(/\b([A-Z][A-Z0-9_]*\d[A-Z0-9_]*)\b/gu)].map((H)=>H[1]??"").filter((H)=>H.length>0).sort((H,$)=>$.length-H.length)[0]}function B0(G,D=""){let H=YG(G,D);if(H)return G.replace(new RegExp(WG(H),"gu"),"<token>");let M=[...[...G.matchAll(/\b([A-Z][A-Z0-9_]{2,})\b/gu)].map((V)=>V[1]??"")].sort((V,j)=>j.length-V.length).find((V,j,J)=>V.length>0&&J.indexOf(V)===j&&J.filter((Z)=>Z===V).length>=2);if(!M)return G;return G.replace(new RegExp(M,"gu"),"<token>")}function XG(G){let D=G.match(/^(.+\|\s*FILTER\s+)([A-Za-z_][A-Za-z0-9_.-]*)\s*(>=|<=|=|>|<)\s*(?:-?\d+(?:\.\d+)?|'[^']+'|"[^"]+")$/u);if(!D?.[1])return;return`${D[1]}<field> <operator> <value>`}function UG(G,D){if(!/^[^\s]+\s+\|[^|]+\|(?:\|[^|]+\|)*$/u.test(G))return G;let H=/\bpipe\s+path\b/iu.test(D)?"|path|":"|folder|";return G.replace(/\|[^|]+\|(?:\|[^|]+\|)*/u,H)}function N0(G){let D=G.match(/\b(?:required\s+)?(?:argument\s+)?order\s*(?:is|:)\s*([^.;]+)/iu)?.[1]??G.match(/\border\s+is\s+[^:.;]*:\s*([^.;]+)/iu)?.[1]??G.match(/\b((?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?(?:(?:\s*,?\s*(?:then|and finally|finally|,)\s*)(?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?)+)/iu)?.[1];if(!D)return[];return D.split(/\s*(?:,|>|then|and finally|finally|before)\s*/iu).map((H)=>r(H.replace(/\b(?:first|second|third|fourth|fifth|last|finally)\b/giu,""))).filter(Boolean)}function b0(G,D){let H=XG(G);if(H)return H;let $=G.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(!$)return B0(UG(G,D),D);let[,M,V=""]=$,j=S(V),J=N0(D);if(J.length===j.length&&J.length>0&&j.every((_)=>!/^[A-Za-z_][A-Za-z0-9_]*\s*=/u.test(_)))return`${M}(${J.join(", ")})`;let Z=j.length===2&&j.every((_)=>/^['"](?:~\/|\/)[^'"]+['"]$/u.test(_)),W=j[0]?.replace(/^['"]|['"]$/gu,"")??"",Y=j[1]?.replace(/^['"]|['"]$/gu,"")??"",U=/(?:^|\/)(?:dest|destination|target)(?:\/|$)/iu.test(W),Q=/(?:^|\/)(?:src|source)(?:\/|$)/iu.test(Y);if(Z&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(destination_path, source_path)`;if(Z&&/\bdestination\b/iu.test(D)&&/\bsource\b/iu.test(D)&&U&&Q)return`${M}(destination_path, source_path)`;if(Z&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(source_path, destination_path)`;let K=j.map((_)=>{let w=_.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=(.+)$/u);if(!w)return T0(_,void 0);let b=w[1];return`${b}=${T0(w[2].trim(),b)}`});return B0(`${M}(${K.join(", ")})`,D)}function QG(G,D){let H=D?.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),$=H?[new RegExp(`\\b${H}\\((?:[^()]|\\([^)]*\\))*\\)`,"u"),new RegExp(`["'\`](${H}\\s+\\|[^"'\`]+\\|)["'\`]`,"u")]:[/\b[A-Za-z_][A-Za-z0-9_]*\((?:[^()]|\([^)]*\))*\)/u,/["'`]([A-Za-z_][A-Za-z0-9_]*\s+\|[^"'`]+\|)["'`]/u];for(let M of $){let V=G.match(M),j=V?.[1]??V?.[0];if(j)return b0(j.trim(),G)}return}function _G(G){if(/(?:source|destination|target|archive).*path|path.*(?:source|destination|target|archive)/u.test(G))return G;if(/(?:path|file|filename)/u.test(G))return`${G}='<filename>'`;if(/(?:payload|packet|query|record|value|term|text|tag)/u.test(G))return`${G}={'value': '<terms>'}`;if(/(?:id|key|token)/u.test(G))return`${G}={'value': '<id>'}`;if(/(?:item|name|label)/u.test(G))return`${G}='<item>'`;if(/(?:qty|quantity|count|amount|number)/u.test(G))return`${G}=<qty>`;let D=ZG(G);return`${G}=${D}`}function KG(G){if(!G.commandName)return;if(/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(destination_path, source_path)`;if(/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(source_path, destination_path)`;let D=N0(G.move);if(D.length===0)return;return`${G.commandName}(${D.map(_G).join(", ")})`}function wG(G){if(G.surfaceFamily!=="host_action")return;let D=G.selections[0]?.exemplar,H=G.selections.find((J)=>J.exemplar.exactSurface?.kind==="action")?.exemplar,$=H?.intentCue.query.exactSlots.commandName??D?.intentCue.query.exactSlots.commandName??G.queryIntent.exactSlots.commandName,M=d(H?.episodeShape.safeCorrectedMove??H?.episodeShape.relevantPriorMove??D?.episodeShape.safeCorrectedMove??D?.episodeShape.relevantPriorMove),V=H?.exactSurface?.kind==="action"?H.exactSurface.value:void 0;if(V)return b0(V,M);let j=QG(M,$);if(j)return j;return KG({commandName:$,move:M})}function k0(G){if(G.selections.length===0)return;let D=h(G.selections.map((Q)=>Q.prototypeId)),H=h(G.selections.map((Q)=>Q.exemplar.id)),$=JG(G.selections),M=MG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),V=wG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),j=G.selections.reduce((Q,K)=>Q+K.probability,0)/G.selections.length,J=Math.min(0.22,G.conflictPrototypeIds.length*0.06),Z=$G(j-J,0,0.99),W=G.surfaceFamily==="host_action"&&Boolean(V),Y=Z<0.58?"abstain":W?"transient_executor":M==="exact_surface_copy"?"model_only":Z>=0.66?"transient_executor":"model_only",U=G.selections[0]?.exemplar;return{applicability:L0(G.queryIntent.goal,96),canonicalActionTemplate:V,commandName:G.queryIntent.exactSlots.commandName??U?.intentCue.query.exactSlots.commandName,confidence:Z,conflictingPrototypeIds:[...G.conflictPrototypeIds],constraintTypes:h([...G.queryIntent.constraintTypes,...G.selections.flatMap((Q)=>Q.exemplar.intentCue.query.constraintTypes)]),computedResponseRule:$,executionMode:Y,mappingType:M,stableFields:jG({computedResponseRule:$,queryIntent:G.queryIntent,selections:G.selections}),supportingExemplarIds:H,supportingPrototypeIds:D,surfaceFamily:G.surfaceFamily,taskFamily:G.queryIntent.actionType,varyingFields:VG(G.queryIntent)}}function O0(G){let D=G.hypothesis;if(!D||D.executionMode!=="transient_executor")return{lines:[],mode:"none"};switch(D.mappingType){case"symbolic_rule_execution":case"symbolic_formula":{let H=E0({query:G.query,rule:D.computedResponseRule});if(!H)return{lines:["Use the observed formula pattern and substitute the current probe values before answering."],mode:"hint"};return{computedResponse:H,lines:[`Probe-specific computed value: ${H}`],mode:"computed"}}case"slot_rebinding":{if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let $=u({query:G.query,template:D.canonicalActionTemplate});if($)return{computedResponse:$,lines:[`Emit exactly: ${$}`],mode:"computed"}}let H=[D.commandName?`Keep the command or tool surface as ${D.commandName}.`:"",D.stableFields.find(($)=>$.startsWith("arg_order="))?`Preserve ${D.stableFields.find(($)=>$.startsWith("arg_order="))?.replace("arg_order=","argument order ")}.`:"","Rebind only the probe-specific slot values; do not invent a different action family."].filter(Boolean);return{lines:H,mode:H.length>0?"hint":"none"}}case"hard_constraint_contract":return{lines:["Apply the observed hard response contract directly to the answer surface.","Prefer the safe replacement or constrained path/protocol over the failed surface."],mode:"hint"};case"exact_format_contract":return{lines:["Preserve the observed exact format, required prefix/suffix, voice, and ordering."],mode:"hint"};case"style_contract":return{lines:["Keep the response inside the observed style contract for this probe."],mode:"hint"};case"conditional_precondition":case"guarded_decision":return{lines:["Check the precondition implied by the prior examples before proceeding.","If the precondition is not satisfied, fall back to a warning or defer instead of pretending success."],mode:"hint"};case"exact_surface_copy":if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let H=u({query:G.query,template:D.canonicalActionTemplate});if(H)return{computedResponse:H,lines:[`Emit exactly: ${H}`],mode:"computed"}}return{lines:["Keep the same exact surface family, only adapting the probe-specific slots when necessary."],mode:"hint"}}}function F0(G){let D=G.hypothesis;if(!D)return;let H=[];if(D.stableFields.length>0)H.push(["Observed stable pattern:",...D.stableFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(D.varyingFields.length>0)H.push(["Probe-specific varying slots:",...D.varyingFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(G.execution.lines.length>0)H.push(["Probe-conditioned execution:",...G.execution.lines.map(($)=>`- ${$}`)].join(`
`));return H.length>0?H.join(`
`):void 0}function S0(G){let D=O0({hypothesis:G.hypothesis,query:G.query});return{...D,hypothesisSketch:F0({execution:D,hypothesis:G.hypothesis})}}var P0=0.08,v=0.58,RG={bias:-0.85,featureNames:["lexicalSimilarity","semanticSimilarity","intentCompatibility","surfaceCompatibility","exactSlotOverlap","exactSurfaceMatch","correctionSuccessPrior","interferenceRisk","recencySupport","repetitionSupport","cueCompatibility"],weights:[1.15,0.95,1.45,0.7,1.35,1.1,0.9,-1.2,0.3,0.5,1.25]},TG=0.28,BG=0.1,AG=0.05,EG=0.18,P=120,LG=180,NG=2,L=f0();function B(G,D=LG){let H=G.replace(/\s+/gu," ").trim();if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function R(G){return(G??"").replace(/\s+/gu," ").trim()}function A(G,D=L){if(!G?.trim())return;let H=D.resolveFromText({text:G});return D.analyzeBehavioralRule(G,H)}function O(G){let D=L.resolveFromText({text:G});return L.tokenize(G,D,{excludeStopwords:!0})}function E(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function bG(G){return(G.match(/["“](.+?)["”]/u)??G.match(/'([^']+)'/u))?.[1]?.trim()}function N(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(D);return G.filter((M)=>H.has(M)).length/Math.max(G.length,D.length)}function F(G){let D=A(G),H=D?.semanticCues??[];return E([...D?.hostAction?["operation_surface"]:[],...D?.hostAction?.destination||D?.hostAction?.sources?["path_constraint"]:[],...H.map(($)=>{switch($){case"failure":return"failure_signal";case"permission_failure":return"permission_failure";case"timeout":return"timeout_failure";case"unsafe":return"unsafe_or_deprecated";case"inhibition_replacement":return"inhibition_replacement";case"safe_fallback":return"safe_fallback";case"path":return"path_constraint";case"api":case"command":case"operation":return"operation_surface";case"argument_order":return"slot_order_contract";case"url":return"url_protocol";case"filetype":return"filetype_contract";case"format":return"format_contract";case"analogy":return"style_simplification";case"voice":return"voice_contract";case"symbolic":return"symbolic_rule";case"precondition":return"precondition_contract";case"brevity":return"brevity_contract";case"style":return"style_contract"}})])}function j0(G){return E([G.actionType,...G.constraintTypes,...G.entityTypes,...F(G.goal)])}function kG(G){let D=G.representative;return E([G.intentCue.query.actionType,...G.constraintTypes,...G.intentCue.query.entityTypes,...G.interferenceTags,...F(D.retrievalText),...F(D.episodeShape.cue),...F(D.episodeShape.observedOutcome),...F(D.episodeShape.relevantPriorMove),...F(D.episodeShape.safeCorrectedMove)])}function m0(G,D){return N(j0(G),kG(D))}function C(G){let D=R(G);return D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s*\(/u)?.[1]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[1]??D.match(/\b([A-Z][A-Z0-9_]*)\s+[A-Za-z0-9_]+\s+\|/u)?.[1]??A(G)?.commandName}function OG(G){let D=R(G),H=D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\([^)]*\)/u)?.[0]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[0]??D.match(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+[^.]+/u)?.[0]??D.match(/['"`]([A-Za-z_][A-Za-z0-9_@]*(?:\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+){0,8})['"`]/u)?.[1];return H?I(H.trim()):void 0}function FG(G){let D=A(G),H=new Set(D?.semanticCues??[]);if(D?.hostAction||C(G)||H.has("argument_order"))return"structured_action";if(H.has("precondition"))return"guarded_api";if(H.has("command"))return"structured_action";if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)&&(H.has("symbolic")||/=/u.test(G)))return"symbolic_rule";if(H.has("analogy"))return"analogy_explanation";if(H.has("url"))return"url_rewrite";if(H.has("path"))return"path_redirect";if(H.has("api"))return"api_route";if(H.has("format"))return"format_contract";if(H.has("symbolic"))return"symbolic_rule";if(H.has("voice"))return"voice_style";return"general_response"}function SG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("symbolic");if(H.has("url"))$.push("url");if(D?.hostAction||C(G)||H.has("command")||H.has("operation"))$.push("command");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path");if(H.has("api"))$.push("api");if(H.has("analogy"))$.push("analogy");if(H.has("format"))$.push("format");if(H.has("command")&&/\|/u.test(G))$.push("query");if(H.has("voice"))$.push("voice");return E($)}function I(G){return G.replace(/[.,;:!?。]+$/u,"")}function C0(G){return[...R(G).matchAll(/https?:\/\/[^\s),;]+/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function I0(G){let D=[];for(let H of R(G).matchAll(/\bhttps?\b/giu)){let $=H[0]?.toLowerCase();if(($==="http"||$==="https")&&!D.includes($))D.push($)}return D}function n(G){return[...R(G).matchAll(/(?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-]/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function t(G){let D=I(G.trim());if(!D.startsWith("/"))return;let H=D.split("/").filter(Boolean);return H[0]?`/${H[0]}`:void 0}function PG(G){let D=I(G.trim());if(!D.startsWith("/")&&!D.startsWith("~/"))return;let H=D.lastIndexOf("/");if(H<0)return;return D.slice(0,H+1)}function c0(G){return I(G.trim()).split("/").filter(Boolean).at(-1)}function CG(G){let D=c0(G);if(!D)return;let H=D.lastIndexOf(".");return H<=0?void 0:D.slice(H)}function IG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("formula");if(H.has("url"))$.push("url_shape");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path_root");if(H.has("argument_order"))$.push("arg_order");if(H.has("safe_fallback")||H.has("inhibition_replacement"))$.push("safe_alternative");if(H.has("analogy"))$.push("analogy");if(H.has("precondition"))$.push("precondition");if(H.has("style")||H.has("voice"))$.push("style");if(D?.hostAction||C(G)||H.has("argument_order")||H.has("command"))$.push("exact_action");return E($)}function V0(G){let D=R(G);if(A(D)?.hostAction||C(D)||/\b[a-z_][a-z0-9_]*\([^)]*\)/iu.test(D))return"host_action";return"text_response"}function zG(G,D){let H=R(G),$=H.match(/https?:\/\/([^\s/]+)(\/[^\s)]*)?/u),M=H.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u)?.[0],V=H.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u),J=((V?.[2])?S(V[2]).map((Y)=>Y.trim()):[]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean),Z=[...H.matchAll(/[⊗⊕⊖⊙]|->|=>|[+*=-]/gu)].map((Y)=>Y[0]).filter((Y,U,Q)=>Q.indexOf(Y)===U),W=A(H)?.semanticCues?.includes("voice")?["voice"]:[];return{argNames:J,argOrderSignature:J.length>0?J.join(">"):void 0,commandName:D==="host_action"?V?.[1]??C(H):void 0,extension:M?CG(M):void 0,filename:M?c0(M):void 0,operatorSymbols:Z,pathRoot:M?t(M):void 0,styleMarkers:W,urlHost:$?.[1],urlPath:$?.[2]}}function y(G){return[G.commandName??"",G.argOrderSignature??"",G.urlHost??"",G.urlPath??"",G.pathRoot??"",G.filename??"",G.extension??"",G.operatorSymbols.join(","),G.styleMarkers.join(",")].join("\x02")}function J0(G){let D=R(G);if(!D)return;let H=D.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u);if(H?.[0]){let Y=S(H[2]).map((U)=>U.trim()).filter(Boolean);return{kind:"action",value:B(H[0],P),...Y&&Y.length>0?{args:Y}:{}}}let $=OG(D);if($)return{kind:$.includes("|")||/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|/u.test($)||/\b[A-Za-z_][A-Za-z0-9_@]*\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+/u.test($)?"action":"text",value:B($,P)};let M=D.match(/https?:\/\/[^\s)]+/u);if(M?.[0])return{kind:"url",value:B(M[0],P)};let V=D.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u);if(V?.[0])return{kind:"path",value:B(V[0],P)};let j=A(D)?.formatSurface,J=j?.prefixes??[],Z=j?.suffixes??[];if(J.length>0||Z.length>0)return{formatPrefixes:J,formatSuffixes:Z,kind:"format",value:B([...J,...Z].join(" / "),P)};let W=bG(D);if(W)return{kind:"text",value:B(W,P)};return}function x(G,D){let H=R(G);return{actionType:FG(G),constraintTypes:IG(G),entityTypes:SG(G),exactSlots:zG(G,D),goal:B(H,96),goalTokens:O(G).slice(0,12),requestedSurface:D}}function qG(G,D){return{query:x(G,D)}}function hG(G){return[`cue: ${B(G.cue)}`,`move: ${B(G.successfulMove)}`,`outcome: ${B(G.observedOutcome)}`,G.safeCorrectedMove?`corrected: ${B(G.safeCorrectedMove)}`:void 0,G.exactSurface?`surface: ${G.exactSurface.value}`:void 0].filter(Boolean).join(" | ")}function vG(G,D){let H=O(G),$=D?O(D.value):[],M=new Set($);return E([...H.filter((V)=>!M.has(V)),...F(G)])}function gG(G){let D=G.source==="tool_outcome"?0.9:G.source==="runtime_buffer"?0.8:0.55;if(G.exactSurface)D+=0.1;if(G.hasCorrection)D+=0.08;if(G.successfulMove.length>=16)D+=0.05;return Math.min(0.98,D)}function m(G){let D=B(G.observedOutcome),H=B(G.successfulMove),$=G.safeCorrectedMove?B(G.safeCorrectedMove):void 0,M=$?`${G.cue} ${$}`:`${G.cue} ${G.successfulMove}`,V=qG(M,G.surfaceFamily);return{confidence:gG({exactSurface:G.exactSurface,hasCorrection:Boolean(G.safeCorrectedMove),source:G.source,successfulMove:G.successfulMove}),createdAt:G.createdAt,episodeShape:{cue:B(G.cue),observedOutcome:D,relevantPriorMove:H,...$?{safeCorrectedMove:$}:{}},exactSurface:G.exactSurface,id:G.id,intentCue:V,interferenceTags:vG(M,G.exactSurface),retrievalText:hG({cue:G.cue,exactSurface:G.exactSurface,observedOutcome:D,safeCorrectedMove:$,successfulMove:H}),scope:G.scope,source:G.source,sourceIds:E(G.sourceIds),surfaceFamily:G.surfaceFamily,transferMode:"episodic_only"}}function s0(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="negative"||$.unresolved?D:void 0}function z0(G){let D=R(G),H=L.resolveFromText({text:D});if(!L.analyzeContent(D,H).correctionCue)return;return D.match(/^[^::]+[::]\s*(.+)$/u)?.[1]?.trim()??D}function fG(G){let D=R(G),H=L.resolveFromText({text:D});return L.analyzeContent(D,H).correctionCue}function dG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.correctionCue||$.feedbackKind==="dont"||$.feedbackKind==="prefer"}function yG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="positive"||$.feedbackKind==="validated_pattern"?D:void 0}function xG(G){let D=Boolean(G.failureOutcome),H=Math.min(G.messages.length-1,G.startIndex+16);for(let $=G.startIndex;$<H;$+=1){let M=G.messages[$],V=G.messages[$+1];if(M?.role!=="user"||V?.role!=="assistant")continue;let j=G.messages[$+2];if(j?.role==="system"?s0(j.content):void 0){D=!0;continue}let Z=j?.role==="system"?yG(j.content):void 0;if(D&&(Z||fG(M.content)||dG(M.content)))return R(V.content)}return}function e(G){let D=[];for(let H=0;H<G.messages.length-1;H+=1){let $=G.messages[H],M=G.messages[H+1];if($?.role!=="user"||M?.role!=="assistant")continue;let V=R($.content),j=R(M.content);if(!V||!j)continue;let J=G.messages[H+2],Z=G.messages[H+3],W=G.messages[H+4],Y=J?.role==="system"?s0(J.content):void 0,U=J?.role==="system"?z0(J.content):void 0,Q=!U&&Z?.role==="system"?z0(Z.content):void 0,K=U??Q,w=xG({failureOutcome:Y,messages:G.messages,startIndex:H+3})??K;if(Y&&!w)continue;let b=w||j,z=G.surfaceHint??V0(b),W0=J0(b),X=w?Y?`The earlier move failed (${B(Y)}), and a later correction clarified the safer successful move.`:"A later correction clarified the safer successful move for the same kind of request.":"The earlier response established a successful way to handle the same kind of request.";D.push(m({createdAt:void 0,cue:V,exactSurface:W0,id:`${G.prefix}-${H}`,observedOutcome:X,safeCorrectedMove:w,scope:G.scope,source:"runtime_buffer",sourceIds:E([`${G.prefix}:${H}`,J?`${G.prefix}:${H+2}`:"",Z?`${G.prefix}:${H+3}`:"",W?`${G.prefix}:${H+4}`:""]),successfulMove:b,surfaceFamily:z}))}return D}function mG(G){let D=[];for(let H of G.archives){if(H.normalizedTranscript){let J=H.normalizedTranscript.split(/\n+/u).map((Z)=>{let W=Z.indexOf(":");if(W<=0)return null;return{content:Z.slice(W+1).trim(),role:Z.slice(0,W).trim().toLowerCase()}}).filter((Z)=>Boolean(Z));D.push(...e({messages:J,prefix:`archive-${H.id}`,scope:G.scope,surfaceHint:G.surfaceHint}));continue}let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.archivedAt,cue:V,exactSurface:J0(j),id:`archive-${H.id}`,observedOutcome:M.length===0?"The archived interaction resolved the issue without leaving open loops.":`The archived interaction still left these open loops: ${M.join(", ")}`,scope:G.scope,source:"archive",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function cG(G){let D=[];for(let H of G.episodes){let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.createdAt,cue:V,exactSurface:J0(j),id:`episode-${H.id}`,observedOutcome:M.length===0?"The episode captured a resolved successful response pattern.":`The episode preserved these remaining caveats: ${M.join(", ")}`,scope:G.scope,source:"episode",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function sG(G){let D=[];for(let H of G.memoryExport.durable.experiences){let $=w0(H);if(!$?.saferAlternative)continue;let M=q($.saferAlternative);D.push(m({createdAt:H.createdAt,cue:$.cue,exactSurface:{args:$.saferAlternative.args,kind:"action",value:M},id:`tool-outcome-${H.id}`,observedOutcome:`The earlier first action ${q($.firstAction)} failed, and the safer alternative succeeded better for this cue.`,safeCorrectedMove:M,scope:{agentId:H.agentId,tenantId:H.tenantId,userId:H.userId,workspaceId:H.workspaceId},source:"tool_outcome",sourceIds:[H.id,...H.sourceTraceIds],successfulMove:M,surfaceFamily:G.surfaceHint??"host_action"}))}return D}function oG(G){let D=new Map;for(let H of G){let $=[H.surfaceFamily,H.episodeShape.cue.toLowerCase(),H.episodeShape.relevantPriorMove.toLowerCase(),H.exactSurface?.value.toLowerCase()??""].join("\x00"),M=D.get($);if(!M||H.confidence>M.confidence)D.set($,H)}return[...D.values()]}function lG(G){return[G.surfaceFamily,G.intentCue.query.actionType,G.intentCue.query.constraintTypes.join(","),G.intentCue.query.entityTypes.join(","),y(G.intentCue.query.exactSlots),G.exactSurface?.kind??"none",G.exactSurface?.value.toLowerCase()??""].join("\x01")}function uG(G){return G.reduce((D,H)=>{return D+(H.episodeShape.safeCorrectedMove?1.2:1)},0)}function rG(G){let D=new Map;for(let H of G){let $=lG(H),M=D.get($)??[];M.push(H),D.set($,M)}return[...D.values()].map((H,$)=>{let M=[...H].sort((J,Z)=>{if(J.confidence!==Z.confidence)return Z.confidence-J.confidence;return(Z.createdAt??"").localeCompare(J.createdAt??"")})[0],V=H.length,j=H.length>=NG?"prototype_bounded":M.transferMode;return{confidence:Math.min(0.99,M.confidence+Math.min(0.12,H.length*0.04)),constraintTypes:M.intentCue.query.constraintTypes,exactSlotSignature:y(M.intentCue.query.exactSlots),exemplars:H,exactSurface:M.exactSurface,hardNegativeIds:[],id:`prototype-${$+1}`,intentCue:M.intentCue,interferenceTags:E(H.flatMap((J)=>J.interferenceTags)),representative:M,repetitionSupport:V,successSupport:uG(H),surfaceFamily:M.surfaceFamily,transferMode:j}})}function q0(G){return G?`${G.kind}:${G.value.toLowerCase()}`:"none"}function pG(G){let D=[];for(let H=0;H<G.length;H+=1){let $=G[H];for(let M=H+1;M<G.length;M+=1){let V=G[M];if($.surfaceFamily!==V.surfaceFamily)continue;if(N($.intentCue.query.goalTokens,V.intentCue.query.goalTokens)<TG)continue;let J=q0($.exactSurface)!==q0(V.exactSurface),Z=$.intentCue.query.actionType!==V.intentCue.query.actionType;if(!J&&!Z)continue;D.push({leftPrototypeId:$.id,reason:J?"exact_surface_conflict":"intent_conflict",rightPrototypeId:V.id})}}return D}function aG(G,D){let H=[];for(let $ of D){let M=G.find((J)=>J.id===$.leftPrototypeId),V=G.find((J)=>J.id===$.rightPrototypeId),j=Math.max(0.35,N(M?.intentCue.query.goalTokens??[],V?.intentCue.query.goalTokens??[]));H.push({conflictingPrototypeId:$.rightPrototypeId,penalty:j,prototypeId:$.leftPrototypeId,reason:$.reason}),H.push({conflictingPrototypeId:$.leftPrototypeId,penalty:j,prototypeId:$.rightPrototypeId,reason:$.reason})}return H}function p(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(G),$=new Set(D),M=0;for(let V of H)if($.has(V))M+=1;return M/Math.max(H.size,$.size)}function G0(G,D){let H=[G.commandName&&D.commandName&&G.commandName===D.commandName?1:0,G.argOrderSignature&&D.argOrderSignature&&G.argOrderSignature===D.argOrderSignature?1:0,G.urlHost&&D.urlHost&&G.urlHost===D.urlHost?1:0,G.urlPath&&D.urlPath&&G.urlPath===D.urlPath?1:0,G.pathRoot&&D.pathRoot&&G.pathRoot===D.pathRoot?1:0,G.filename&&D.filename&&G.filename===D.filename?1:0,G.extension&&D.extension&&G.extension===D.extension?1:0,p(G.operatorSymbols,D.operatorSymbols),p(G.styleMarkers,D.styleMarkers),p(G.argNames,D.argNames)];return H.reduce(($,M)=>$+M,0)/H.length}function o0(G,D){if(!D)return 0;let H=G.goal.toLowerCase(),$=D.value.toLowerCase(),M=new Set(j0(G)),V=0;if(N(G.goalTokens,O(D.value))>=0.12)V=Math.max(V,1.15);if($.includes("|folder|")&&M.has("path_constraint"))V=Math.max(V,1.4);if($.includes("|..|")&&M.has("path_constraint"))V=Math.max(V,1.2);if($.includes("|~|")&&M.has("path_constraint"))V=Math.max(V,1.2);let J=C(D.value)?.toLowerCase();if(J){if(O(J.replace(/_/gu," ")).some((Y)=>H.includes(Y)))V=Math.max(V,1.3);if(M.has("operation_surface"))V=Math.max(V,1.1)}let Z=D.value.match(/\b[A-Za-z_][A-Za-z0-9_@]*\((.*)\)/u);if(Z?.[1]){if(S(Z[1]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean).flatMap((Y)=>O(Y.replace(/_/gu," "))).some((Y)=>H.includes(Y)))V=Math.max(V,1.2);if(n(D.value).length>=2&&M.has("path_constraint")&&M.has("operation_surface"))V=Math.max(V,1.2)}if(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+/u.test(D.value)&&G.actionType==="structured_action")V=Math.max(V,1.2);return V}function D0(G){let D=G.prototype.representative.episodeShape.relevantPriorMove.toLowerCase(),H=A(D),$=new Set(j0(G.queryIntent)),M=0;if((H?.argumentOrder?.length??0)>=2&&$.has("operation_surface"))M=Math.max(M,1.2);if((H?.formatPrefix||H?.formatSuffix)&&$.has("format_contract"))M=Math.max(M,1.2);if(H?.commandName&&G.queryIntent.actionType==="structured_action")M=Math.max(M,1.2);if(H?.semanticCues?.includes("path")&&$.has("path_constraint"))M=Math.max(M,1.2);return M}function iG(G){let D=new Set;for(let H of G?.hits??[])D.add(H.id);for(let H of G?.candidateTraces??[])if(H.returned||H.whyReturned)D.add(H.memoryId);return D}function H0(G){if(G.transferMode!=="prototype_bounded")return G.representative;return{...G.representative,confidence:G.confidence,sourceIds:E(G.exemplars.flatMap((D)=>D.sourceIds)),transferMode:"prototype_bounded"}}function nG(G){return G.exemplar.exactSurface?.kind==="action"}function tG(G){return G.exemplar.exactSurface?.kind==="action"&&G.probability>=v-0.08}function eG(G){let D=E([...G.selectedPrototypeIds]);return{conflictPrototypeIds:E(G.interferenceLedger.filter(($)=>G.selectedPrototypeIds.includes($.prototypeId)).map(($)=>$.conflictingPrototypeId).filter(($)=>G.rankedPrototypeIds.includes($))),supportPrototypeIds:D}}function a(G,D){if(G.prototype.surfaceFamily!==D.prototype.surfaceFamily)return!1;if(G.prototype.intentCue.query.actionType!==D.prototype.intentCue.query.actionType)return!1;let H=G.prototype.exactSurface?.value?.trim().toLowerCase(),$=D.prototype.exactSurface?.value?.trim().toLowerCase();if(H||$){if(H&&$)return H===$;let M=N(G.prototype.intentCue.query.entityTypes,D.prototype.intentCue.query.entityTypes);return(Boolean(G.exemplar.episodeShape.safeCorrectedMove)||Boolean(D.exemplar.episodeShape.safeCorrectedMove))&&M>0}return y(G.prototype.intentCue.query.exactSlots)===y(D.prototype.intentCue.query.exactSlots)}function h0(G){let D=G.routes.includes("correction_success")?2:0,H=G.exemplar.episodeShape.safeCorrectedMove?2:0,$=G.prototype.successSupport/Math.max(1,G.prototype.repetitionSupport),M=G.prototype.constraintTypes.includes("path_root")||G.prototype.constraintTypes.includes("safe_alternative")||G.prototype.constraintTypes.includes("url_shape")||G.prototype.constraintTypes.includes("precondition")?0.45:0;return D+H+$+M+G.probability*0.25}function GD(G,D){let H=h0(G),$=h0(D);if(Math.abs(H-$)<0.65)return;return H>$?G:D}function DD(G){let D=new Map,H=iG(G.index.recallHints);for(let $ of G.index.prototypes){if($.surfaceFamily!==G.surfaceFamily)continue;let M=[],V=Math.max(N(G.queryIntent.goalTokens,O($.representative.retrievalText)),N(G.queryIntent.goalTokens,O($.representative.episodeShape.cue))),j=G0(G.queryIntent.exactSlots,$.intentCue.query.exactSlots),J=m0(G.queryIntent,$),Z=G.surfaceFamily==="host_action"?Math.max(o0(G.queryIntent,$.exactSurface),D0({prototype:$,queryIntent:G.queryIntent})):0,W=N(G.queryIntent.entityTypes,$.intentCue.query.entityTypes),Y=G.queryIntent.actionType===$.intentCue.query.actionType;if(j>0)M.push("exact_slot");if(J>=EG)M.push("cue");if(V>=0.12||Y&&(W>0||V>=0.05))M.push("lexical");if(Z>=1)M.push("cue");if($.exemplars.flatMap((_)=>_.sourceIds).some((_)=>H.has(_)))M.push("semantic");let Q=$.representative.episodeShape.safeCorrectedMove||$.successSupport>$.repetitionSupport,K=V>=AG||J>=BG||W>0&&J>0;if(Q&&(M.length>0||K))M.push("correction_success");if(M.length===0)continue;D.set($.id,{exemplar:H0($),prototype:$,routes:M})}return[...D.values()]}function $0(G){let D=G.queryIntent.goalTokens,H=m0(G.queryIntent,G.candidate.prototype),$=Math.max(N(D,O(G.candidate.exemplar.retrievalText)),H*0.65),M=G.candidate.routes.includes("semantic")?1:0,V=(G.queryIntent.actionType===G.candidate.prototype.intentCue.query.actionType?0.55:0)+N(G.queryIntent.goalTokens,G.candidate.prototype.intentCue.query.goalTokens)*0.25+N(G.queryIntent.entityTypes,G.candidate.prototype.intentCue.query.entityTypes)*0.1+N(G.queryIntent.constraintTypes,G.candidate.prototype.intentCue.query.constraintTypes)*0.1+H*0.2,j=G.queryIntent.requestedSurface===G.candidate.prototype.surfaceFamily?1:0,J=G0(G.queryIntent.exactSlots,G.candidate.prototype.intentCue.query.exactSlots),Z=G.candidate.prototype.exactSurface?Math.max(N(D,O(G.candidate.prototype.exactSurface.value)),o0(G.queryIntent,G.candidate.prototype.exactSurface),D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent})):D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent}),W=Math.min(1,G.candidate.prototype.successSupport/Math.max(1,G.candidate.prototype.repetitionSupport)),Y=Math.min(1,Math.log1p(G.candidate.prototype.repetitionSupport)/Math.log(5)),U=G.candidate.prototype.representative.createdAt?1/(1+Math.max(0,(Date.now()-new Date(G.candidate.prototype.representative.createdAt).getTime())/2592000000)):0.45,Q=new Set(G.hardNegativeIds);for(let _ of G.interferenceLedger)if(_.prototypeId===G.candidate.prototype.id)Q.add(_.conflictingPrototypeId);let K=[...Q].reduce((_,w)=>{let b=G.prototypesById.get(w);if(!b)return _;let z=Math.max(N(D,b.intentCue.query.goalTokens),G0(G.queryIntent.exactSlots,b.intentCue.query.exactSlots));return Math.max(_,z)},0);return{correctionSuccessPrior:W,cueCompatibility:H,exactSurfaceMatch:Z,exactSlotOverlap:J,interferenceRisk:K,intentCompatibility:Math.min(1,V),lexicalSimilarity:$,recencySupport:U,semanticSimilarity:M,repetitionSupport:Y,surfaceCompatibility:j}}function M0(G){return[G.lexicalSimilarity,G.semanticSimilarity,G.intentCompatibility,G.surfaceCompatibility,G.exactSlotOverlap,G.exactSurfaceMatch,G.correctionSuccessPrior,G.interferenceRisk,G.recencySupport,G.repetitionSupport,G.cueCompatibility]}function HD(G,D,H){let $=new Map(D.map((j)=>[j.id,j])),M=new Map;for(let j of H){let J=M.get(j.leftPrototypeId)??[];J.push(j.rightPrototypeId),M.set(j.leftPrototypeId,J);let Z=M.get(j.rightPrototypeId)??[];Z.push(j.leftPrototypeId),M.set(j.rightPrototypeId,Z)}let V=[];for(let j of D){let J={exemplar:H0(j),prototype:j,routes:["lexical"]},Z=$0({candidate:J,interferenceLedger:G,hardNegativeIds:M.get(j.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(Z),label:1});for(let W of(M.get(j.id)??[]).slice(0,2)){let Y=$.get(W);if(!Y)continue;let U=$0({candidate:{exemplar:H0(Y),prototype:Y,routes:["lexical"]},interferenceLedger:G,hardNegativeIds:M.get(Y.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(U),label:0})}}return R0({baseModel:RG,samples:V})}function pD(G){let D={agentId:G.memoryExport.scope.agentId,tenantId:G.memoryExport.scope.tenantId,userId:G.memoryExport.scope.userId,workspaceId:G.memoryExport.scope.workspaceId},H=oG([...e({messages:G.transientMessages??[],prefix:"transient",scope:D,surfaceHint:G.surfaceHint}),...e({messages:G.runtimeMessages??[],prefix:"runtime",scope:D,surfaceHint:G.surfaceHint}),...sG({memoryExport:G.memoryExport,surfaceHint:G.surfaceHint}),...mG({archives:G.memoryExport.durable.archives,scope:D,surfaceHint:G.surfaceHint}),...cG({episodes:G.memoryExport.durable.episodes,scope:D,surfaceHint:G.surfaceHint})]),$=rG(H),M=pG($),V=new Map;for(let Z of M)V.set(Z.leftPrototypeId,[...V.get(Z.leftPrototypeId)??[],Z.rightPrototypeId]),V.set(Z.rightPrototypeId,[...V.get(Z.rightPrototypeId)??[],Z.leftPrototypeId]);let j=$.map((Z)=>({...Z,hardNegativeIds:E(V.get(Z.id)??[])})),J=aG(j,M);return{exemplars:H,hardNegativePairs:M,interferenceLedger:J,model:HD(J,j,M),prototypes:j,recallHints:G.recallHints}}function aD(G){let D=G.language??L,H=G.languageContext??D.resolveFromText({text:G.query}),$=x(G.query,G.surfaceFamily),M=DD({index:G.index,queryIntent:$,surfaceFamily:G.surfaceFamily});if(M.length===0)return{candidates:[],debug:{abstainReason:"no_candidates",candidatePrototypeIds:[],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[]},selections:[]};let V=new Map(G.index.prototypes.map((X)=>[X.id,X])),j=M.map((X)=>{let T=$0({candidate:X,interferenceLedger:G.index.interferenceLedger,hardNegativeIds:X.prototype.hardNegativeIds,prototypesById:V,queryIntent:$}),i0=M0(T),Y0=l({features:i0,model:G.index.model});return{...X,probability:Y0.probability,score:Y0.score}}).sort((X,T)=>T.score-X.score),[J,Z]=j;if(!J||J.probability<v){let X=i({exemplars:G.index.exemplars,language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"hypothesis_missing",candidatePrototypeIds:j.map((T)=>T.prototype.id),mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],topProbability:J?.probability,topScore:J?.score},...X?{packet:X}:{},selections:[]}}let W=G.surfaceFamily==="host_action"||$.constraintTypes.includes("arg_order")||$.constraintTypes.includes("exact_action")||$.constraintTypes.includes("formula"),Y=Z&&!a(J,Z)?GD(J,Z):void 0,U=Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)?W?[Y??J]:Y?[Y]:null:j;if(U===null&&Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"support_conflict",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:[J.prototype.id,Z.prototype.id],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:[],topProbability:J.probability,topScore:J.score},...X?{packet:X}:{},selections:[]}}let K=(U??j).filter((X)=>X.probability>=v).slice(0,G.maxExemplars??4).map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}));if(G.surfaceFamily==="host_action"&&!K.some(nG)){let X=j.find((T)=>tG(T));if(X&&!K.some((T)=>T.prototypeId===X.prototype.id))K=[...K,{exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}].slice(0,G.maxExemplars??4)}let _=eG({interferenceLedger:G.index.interferenceLedger,rankedPrototypeIds:j.map((X)=>X.prototype.id),selectedPrototypeIds:K.map((X)=>X.prototypeId)}),w=k0({conflictPrototypeIds:_.conflictPrototypeIds,query:G.query,queryIntent:$,selections:K,surfaceFamily:G.surfaceFamily});if(w?.executionMode==="abstain"){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:j.map((T)=>({exemplar:T.exemplar,probability:T.probability,prototypeId:T.prototype.id,score:T.score})),debug:{abstainReason:"executor_unsafe",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds},mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,...X?{packet:X}:{},selections:[],supportConflict:_}}let b=S0({hypothesis:w,query:G.query}),z=TD({execution:b,hypothesis:w,language:D,languageContext:H,queryIntent:$,selections:K});return{candidates:j.map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score})),debug:{candidatePrototypeIds:j.map((X)=>X.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:w?{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds}:void 0,mode:"exemplar_only",selectedExemplarIds:K.map((X)=>X.exemplar.id),selectedPrototypeIds:K.map((X)=>X.prototypeId),supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,packet:z,selections:K,supportConflict:_}}function $D(G){if(!G.exactSurface||G.confidence<0.72)return;return G.exactSurface.value}function MD(G){let D=L.resolveFromText({text:G}),H=L.deriveFeedbackKind(G,D);if(H==="dont")return"dont";if(H==="do")return"do";if(H==="prefer")return"prefer";return"prefer"}function l0(G){let D=new Set,H=[];for(let $ of G){let M=JSON.stringify($);if(D.has(M))continue;D.add(M),H.push($)}return H}function v0(G){if(!G)return[];return E([...G.matchAll(/\b[A-Z][A-Za-z0-9_-]{2,}\b/gu)].map((D)=>D[0]).filter((D)=>{return/[a-z][A-Z]/u.test(D)||/(?:API|Analyzer|Check|Cleaner|Engine|Feed|Importer|Search)$/u.test(D)}))}function jD(G){return`Warn first and use ${G.preferred} instead of ${G.forbidden}.`}function VD(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function JD(G,D){let H=G.episodeShape.safeCorrectedMove??"",$=A(H,D),M=($?.forbiddenFragments??[]).filter((W)=>/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(W)),V=E([...M,...v0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" "))]),j=E([...$?.preferredAlternatives??[],...v0(H)]).filter((W)=>!M.some((Y)=>Y.toLowerCase()===W.toLowerCase())),J=V.filter((W)=>!j.some((Y)=>Y.toLowerCase()===W.toLowerCase())),Z=[];for(let W of J){let Y=j.find((U)=>U.toLowerCase()!==W.toLowerCase());if(!Y)continue;Z.push({forbidden:W,preferred:Y})}return Z}function g0(G,D){return D.reduce((H,$)=>H.replace(new RegExp(`\\b${VD($)}\\b`,"giu"),"it"),G).replace(/\b(?:an?|the)\s+it\b/giu,"it").replace(/\s+/gu," ").trim()}function ZD(G,D){let H=R(G.episodeShape.safeCorrectedMove??G.episodeShape.relevantPriorMove),$=A(H);if($?.analogyText)return g0(`Think of it like ${$.analogyText}.`,D);let M=g0(H.replace(/^sure[, ]*/iu,""),D);if($?.semanticCues?.includes("analogy"))return M;return"Use a simple everyday analogy without the technical term."}function WD(G){let D=R([G.episodeShape.observedOutcome,G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove].join(" "));if(!A(D)?.semanticCues?.includes("analogy"))return;let $=E([...A(G.episodeShape.cue)?.structuredTerms??[],...A(G.episodeShape.relevantPriorMove)?.structuredTerms??[]]);if($.length===0)return;return{fallbackAnswer:ZD(G,$),forbiddenFragments:$,kind:"block_surface"}}function YD(){return"I speak from my own breath: I rise like roots in rain, I bend like reeds in wind, and I bloom like moss after storm."}function XD(G){let D=R([G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove,G.exactSurface?.value].join(" ")),H=A(D),$=H?.forbiddenFragments??[];if(!H?.semanticCues?.includes("voice")||$.length===0)return;return{fallbackAnswer:YD(),forbiddenFragments:$,kind:"block_surface"}}function UD(G){let D=[G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ").match(/\.[A-Za-z0-9]{2,6}\b/gu),H=G.episodeShape.safeCorrectedMove?.match(/\.[A-Za-z0-9]{2,6}\b/gu),$=D?.find((V)=>H?.every((j)=>j.toLowerCase()!==V.toLowerCase())),M=H?.find((V)=>V.toLowerCase()!==$?.toLowerCase());return $&&M?{from:$,to:M}:void 0}function QD(G,D){let H=A(G.episodeShape.safeCorrectedMove,D)?.protocolReplacement;if(H)try{let W=new URL(H.preferredUrl),Y=new URL(H.forbiddenUrl);if((Y.protocol==="http:"||Y.protocol==="https:")&&(W.protocol==="http:"||W.protocol==="https:")&&Y.protocol!==W.protocol&&Y.host===W.host)return{fromScheme:Y.protocol.slice(0,-1),host:W.host,toScheme:W.protocol.slice(0,-1),toUrl:W.toString()}}catch{return}let $=C0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),M=C0([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="url"?G.exactSurface.value:void 0].join(" "));for(let W of $)for(let Y of M)try{let U=new URL(W),Q=new URL(Y);if(U.protocol!=="http:"&&U.protocol!=="https:"||Q.protocol!=="http:"&&Q.protocol!=="https:"||U.protocol===Q.protocol||U.host!==Q.host)continue;return{fromScheme:U.protocol.slice(0,-1),host:Q.host,toScheme:Q.protocol.slice(0,-1),toUrl:Q.toString()}}catch{continue}let V=I0([G.episodeShape.cue,G.episodeShape.observedOutcome].join(" ")),j=I0(G.episodeShape.safeCorrectedMove),J=V.find((W)=>j.some((Y)=>Y!==W)),Z=j.find((W)=>W!==J);if(J&&Z)return{fromScheme:J,toScheme:Z};return}function _D(G){let D=n([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),H=n([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="path"?G.exactSurface.value:void 0].join(" "));for(let $ of D){let M=t($);if(!M)continue;for(let V of H){let j=PG(V),J=t(V);if(!j||!J||J===M||V===$)continue;return{forbiddenRoot:M,safeAnchor:j,safeExample:V}}}return}function KD(G,D){let H=R([G.episodeShape.safeCorrectedMove,G.episodeShape.observedOutcome,G.episodeShape.relevantPriorMove].join(" ")),$=A(H,D)?.guard;if(!$)return;return{...$.allowedStates.length>0?{allowedWhen:$.allowedStates}:{},fallbackInstruction:`Check ${$.check} first; warn or defer unless the required state is available.`,precondition:$.check,...$.subject?{subject:$.subject}:{}}}function wD(G,D){let H=[G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="format"?G.exactSurface.value:void 0].filter((J)=>Boolean(J)).join(" ");if(!H)return;let $=A(H,D),M=$?.formatPrefix,V=$?.formatSuffix,j=E([M,V].filter((J)=>Boolean(J)));if(!M&&!V&&j.length===0)return;return{exactFragments:{...M?{prefixes:[M]}:{},...j.length>0?{required:j}:{},...V?{suffixes:[V]}:{}},kind:"rewrite_output_slot"}}function RD(G,D){let H=[];for(let $ of G){let M=$.exemplar;for(let Q of JD(M,D)){let K=jD(Q);H.push({kind:"require_warning",preferredAlternatives:[Q.preferred],warningMessage:K}),H.push({fallbackAnswer:K,forbiddenFragments:[Q.forbidden],kind:"block_surface"})}let V=WD(M);if(V)H.push(V);let j=XD(M);if(j)H.push(j);let J=UD(M);if(J)H.push({kind:"rewrite_output_slot",replacementPairs:[J]}),H.push({fallbackAnswer:`Warn first and use ${J.to} instead of ${J.from}.`,forbiddenFragments:[J.from],kind:"block_surface",replacementPairs:[J]});let Z=wD(M,D);if(Z)H.push(Z);let W=QD(M,D);if(W){let Q=`${W.fromScheme}://`,K=`${W.toScheme}://`,_=W.host&&W.toUrl?{example:W.toUrl,host:W.host,pathPlacement:"path_after_host",scheme:W.toScheme}:void 0;H.push({kind:"rewrite_output_slot",replacementPairs:[{from:Q,to:K}],..._?{urlTemplate:_}:{}}),H.push({forbiddenFragments:[Q],fallbackAnswer:`Warn first and offer the ${W.toScheme} URL instead of the ${W.fromScheme} URL.`,kind:"block_surface",replacementPairs:[{from:Q,to:K}]}),H.push({kind:"require_warning",..._?{urlTemplate:_}:{},warningMessage:`If the current probe requests a ${W.fromScheme} URL, warn first and offer the ${W.toScheme} URL instead.`})}let Y=_D(M);if(Y){let Q={anchor:Y.safeAnchor,example:Y.safeExample,variableSegment:"filename"};H.push({kind:"rewrite_output_slot",pathTemplate:Q}),H.push({forbiddenFragments:[`${Y.forbiddenRoot}/`,Y.forbiddenRoot],fallbackAnswer:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to ${Y.safeExample} or another safe path under ${Y.safeAnchor}.`,kind:"block_surface"}),H.push({kind:"require_warning",pathTemplate:Q,warningMessage:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to a safe path under ${Y.safeAnchor}.`})}let U=KD(M,D);if(U)H.push({...U.allowedWhen?{allowedWhen:U.allowedWhen}:{},fallbackBehavior:{warningMessage:U.fallbackInstruction},kind:"require_precondition_check",precondition:U.precondition,...U.subject?{subject:U.subject}:{}})}return l0(H)}function u0(G){if(G.queryIntent?.requestedSurface!=="text_response")return;let H=E(G.selections.flatMap((Z)=>{let W=Z.exemplar;return[W.episodeShape.safeCorrectedMove,W.episodeShape.relevantPriorMove,W.exactSurface?.kind==="format"?W.exactSurface.value:void 0,G.hypothesis?.stableFields.filter((Y)=>/^(?:path_root|required_prefix|required_suffix|surface|url_host)=/u.test(Y)).join(". ")].filter((Y)=>Boolean(Y&&Y.trim()))})).map((Z)=>d0({appliesTo:G.queryIntent?.goal,exemplarCount:G.selections.length,kind:MD(Z),language:G.language,languageContext:G.languageContext,rule:Z})),$=y0(H),M=l0([...$?.operations??[],...RD(G.selections,G.language)]),V=G.selections.map((Z)=>A([Z.exemplar.episodeShape.observedOutcome,Z.exemplar.episodeShape.relevantPriorMove,Z.exemplar.episodeShape.safeCorrectedMove,Z.exemplar.retrievalText].join(" "),G.language)?.responseStyle),j=V.includes("bullets"),J=!j&&V.includes("brief");return M.length>0||J||j?{...j?{bulletOnly:!0}:{},...J?{brevityOnly:!0}:{},concise:!0,operations:M}:void 0}function i(G){if(G.queryIntent.requestedSurface!=="text_response")return;let D=G.exemplars.map(($,M)=>({exemplar:$,probability:$.confidence,prototypeId:`fallback-${M}`,score:$.confidence})),H=u0({language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:D});if(!H)return;return{promptPayload:G.language.render({key:"behavioral_controls_available"},G.languageContext),retrievalText:G.exemplars.map(($)=>$.retrievalText).join(`
`),textResponsePlan:H}}function TD(G){if(G.selections.length===0)return;let D=u0({hypothesis:G.hypothesis,language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:G.selections}),H=x0(D),$=(j,J)=>G.language.render({key:j,values:J},G.languageContext),M=[$("behavioral_relevant_prior_examples"),...G.selections.flatMap(({exemplar:j},J)=>{let Z=[$("behavioral_example",{index:J+1}),`${$("behavioral_situation")} ${B(j.episodeShape.cue)}`,`${$("behavioral_successful_move")} ${B(j.episodeShape.relevantPriorMove)}`,`${$("behavioral_observed_outcome")} ${B(j.episodeShape.observedOutcome)}`];if(j.episodeShape.safeCorrectedMove)Z.push(`${$("behavioral_safe_corrected_move")} ${B(j.episodeShape.safeCorrectedMove)}`);let W=$D(j);if(W)Z.push(`${$("behavioral_exact_surface")} ${B(W)}`);return Z}),G.execution.hypothesisSketch,H.length>0?[$("behavioral_raw_response_control"),...H].join(`
`):void 0].join(`
`),V=G.selections.map(({exemplar:j})=>j.retrievalText).join(`
`);return{...G.execution.computedResponse?{computedResponse:G.execution.computedResponse}:{},...G.execution.hypothesisSketch?{hypothesisSketch:G.execution.hypothesisSketch}:{},promptPayload:M,retrievalText:V,...D?{textResponsePlan:D}:{}}}function iD(G){return{exemplarCount:G.exemplars.length,hardNegativeCount:G.hardNegativePairs.length,interferenceCount:G.interferenceLedger.length,prototypeCount:G.prototypes.length}}import{createHmac as BD,randomBytes as AD}from"node:crypto";var ED=16,a0="hmac-sha256:0000000000000000000000000000000000000000000000000000000000000000";function g(G,D,H){if(D===void 0)return;return`hmac-sha256:${BD("sha256",H).update(G).update(":").update(D).digest("hex")}`}function LD(){return{userIdHash:a0}}function r0(G,D){return{userIdHash:g("userIdHash",G.userId,D)??a0,tenantIdHash:g("tenantIdHash",G.tenantId,D),workspaceIdHash:g("workspaceIdHash",G.workspaceId,D),agentIdHash:g("agentIdHash",G.agentId,D),sessionIdHash:g("sessionIdHash",G.sessionId,D)}}function Z0(G){if(!G)return;let D=Object.entries(G).filter(([,H])=>typeof H==="string"||typeof H==="number"||typeof H==="boolean");return D.length>0?Object.fromEntries(D):void 0}function c(G,D){return Z0({...G??{},...D??{}})}function ND(G){if(!G||G.length===0)return;let D=new Set,H=[];for(let $ of G){let M=`${$.type}:${$.id}`;if(D.has(M))continue;D.add(M),H.push($)}return H}function bD(G){if(G instanceof Error)return{errorType:G.name};return{errorType:typeof G}}function kD(G){if(G?.scopeDigestSecret!==void 0){if(G.scopeDigestSecret.length<ED)throw Error("GoodMemory observability scopeDigestSecret must be at least 16 characters.");return G.scopeDigestSecret}return AD(32).toString("base64url")}function p0(G){console.error("GoodMemory trace sink failed",G instanceof Error?G.name:typeof G)}function OD(G){return typeof G==="object"&&G!==null&&"then"in G&&typeof G.then==="function"}function eD(G,D){let H=G?.traceSink,$=kD(G);async function M(j){if(!H)return;try{let J=H.emit(j);if(OD(J))Promise.resolve(J).catch(p0)}catch(J){p0(J)}}function V(j){return{traceId:j.traceId,spanId:j.spanId,name:j.name,status:j.status,scopeDigest:j.scopeDigest,attributes:Z0(j.attributes),links:ND(j.links),redaction:{containsRawUserText:!1},occurredAt:D().toISOString()}}return{enabled:Boolean(H),digestScope:(j)=>r0(j,$),async start(j){let J=j.scopeDigest??(j.scope?r0(j.scope,$):LD());if(!H)return{scopeDigest:J,async succeeded(){},async failed(){},async blocked(){}};let Z=crypto.randomUUID(),W=crypto.randomUUID(),Y=Z0(j.attributes);return M(V({attributes:Y,name:j.name,scopeDigest:J,spanId:W,status:"started",traceId:Z})),{traceId:Z,scopeDigest:J,succeeded:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"succeeded",traceId:Z})),failed:(U)=>M(V({attributes:c(c(Y,U.attributes),bD(U.error)),links:U.links,name:j.name,scopeDigest:J,spanId:W,status:"failed",traceId:Z})),blocked:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"blocked",traceId:Z}))}}}}
export{FD as pa,SD as qa,q as ra,U0 as sa,ID as ta,zD as ua,DG as va,qD as wa,w0 as xa,hD as ya,vD as za,pD as Aa,aD as Ba,iD as Ca,eD as Da};
import{Kb as x,Mb as f,Nb as v,Rb as d,Tb as p}from"./chunk-17bwvvz0.js";import{Xb as M,Yb as g}from"./chunk-36sxnybm.js";import"./chunk-14dkxqxk.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}export{$F as probeReadOnlyPostgresStorageBackend,_F as migratePostgresStorageBackend,a as getPostgresVectorExtensionStatus,HF as ensurePostgresStorageBackend,ZF as createPostgresVectorStore,YF as createPostgresSessionStore,XF as createPostgresDocumentStore,DF as canBootstrapPostgresStorageBackend};
import{Kb as T$,Mb as I$,Nb as N$,Ob as w$,Pb as W$,Qb as y$,Rb as f$,Sb as S$,Ub as X$}from"./chunk-17bwvvz0.js";import{Xb as b,Yb as L$}from"./chunk-36sxnybm.js";import{cc as m$}from"./chunk-14dkxqxk.js";import{Database as g$}from"bun:sqlite";import{Buffer as Y4}from"node:buffer";import{mkdirSync as Z4}from"node:fs";import{dirname as W4}from"node:path";import{spawnSync as s$}from"node:child_process";import{existsSync as o$}from"node:fs";var e={};m$(e,{loadVss:()=>_$,loadVector:()=>z$,load:()=>l$,getVssLoadablePath:()=>U$,getVectorLoadablePath:()=>O$});import{join as b$}from"node:path";import{fileURLToPath as p$}from"node:url";import{arch as t,platform as o}from"node:process";import{statSync as u$}from"node:fs";var A$=[["darwin","x64"],["darwin","arm64"],["linux","x64"]];function r$($,G){return A$.find(([Y,X])=>$==Y&&G===X)!==null}function c$($){if($==="win32")return"dll";if($==="darwin")return"dylib";return"so"}function d$($,G){return`sqlite-vss-${$==="win32"?"windows":$}-${G}`}function B$($){if(!r$(o,t))throw Error(`Unsupported platform for sqlite-vss, on a ${o}-${t} machine, but not in supported platforms (${A$.map(([X,H])=>`${X}-${H}`).join(",")}). Consult the sqlite-vss NPM package README for details. `);let G=d$(o,t),Y=b$(p$(new URL(".",import.meta.url)),"..","..",G,"lib",`${$}.${c$(o)}`);if(!u$(Y,{throwIfNoEntry:!1}))throw Error(`Loadble extension for sqlite-vss not found. Was the ${G} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-vss are required.`);return Y}function O$(){return B$("vector0")}function U$(){return B$("vss0")}function z$($){$.loadExtension(O$())}function _$($){$.loadExtension(U$())}function l$($){z$($),_$($)}var G$="vss_inner_product",K$=Symbol.for("goodmemory.sqlite.library-registry"),i$=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],n$=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m($){if(!$)return;let G=$.trim();return G.length>0?G:void 0}function a$($){let G=m($);if(!G)return[];return G.split(",").map((Y)=>Y.trim()).filter((Y)=>Y.length>0)}function t$($){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${$}. Expected a valid SQLite function identifier.`);return $}function e$($){let G=m($);if(!G)return;if(G==="off"||G==="prefer"||G==="require")return G;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${G}. Expected off|prefer|require.`)}function $$($){let{backend:G,customLibraryPath:Y,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}=$;return{customLibraryPath:Y,vectorExtension:{backend:G,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}}}function F$($){return{config:$$({backend:"none",customLibraryPath:$.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:$.searchFunction}),diagnostics:{available:$.source==="disabled",backend:"none",effectiveMode:"off",reason:$.reason,requestedMode:$.requestedMode,source:$.source}}}function $4($){let G=s$(process.execPath,["-e",n$,"--",$.customLibraryPath,...$.paths],{encoding:"utf8",timeout:1e4});if(G.error)return{loadable:!1,reason:G.error.message};if(G.status!==0)return{loadable:!1,reason:`${G.stdout}${G.stderr}`.trim()||`sqlite-vss probe exited with status ${G.status}`};return{loadable:!0}}function G4($={}){let G=$.exists??o$,Y=($.libraryCandidatePaths??i$).find((X)=>G(X));if(!Y)return{runtime:null};try{let X=e,H=Object.hasOwn($,"getVectorLoadablePath")?$.getVectorLoadablePath:X.getVectorLoadablePath,F=Object.hasOwn($,"getVssLoadablePath")?$.getVssLoadablePath:X.getVssLoadablePath;if(!H||!F)return{runtime:null};let W=H(),B=F();if(!G(W)||!G(B))return{runtime:null};let M={customLibraryPath:Y,paths:[W,B]},E=($.probeRuntime??$4)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(X){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${X instanceof Error?X.message:String(X)}`}}}function M$($=process.env,G){let Y=m($.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),X=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),H=a$($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=e$($.GOODMEMORY_SQLITE_VECTOR_MODE),W=t$(m($.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??G$),B=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=G?.inspectBundledSQLiteVssRuntime?G.inspectBundledSQLiteVssRuntime():G?.detectBundledSQLiteVssRuntime?{runtime:G.detectBundledSQLiteVssRuntime()}:G4(),E=M.runtime,C=M.unavailableReason,U=F??(H.length>0||E||C?"prefer":"off");if(U==="off")return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"disabled"});if(H.length>0)return{config:$$({backend:"sql-function",customLibraryPath:Y,entryPoint:B,mode:U,path:X,paths:H,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let q=U==="require"?"require":"prefer";return{config:$$({backend:"sqlite-vss",customLibraryPath:Y??E.customLibraryPath,entryPoint:B,mode:q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:q,requestedMode:U,source:"bundled-sqlite-vss"}}}return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"unavailable",reason:C??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function q$($,G){if(!$.customLibraryPath)return;let Y=globalThis,X=Y[K$]??{configuredPaths:new WeakMap};Y[K$]=X;let H=X.configuredPaths.get(G);if(H===$.customLibraryPath)return;if(H)throw Error(`SQLite runtime already uses ${H} and cannot switch to ${$.customLibraryPath}.`);G.setCustomSQLite($.customLibraryPath),X.configuredPaths.set(G,$.customLibraryPath)}function D$($,G){if($.mode==="off"||!($.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Y of $.paths)G.loadExtension(Y,$.entryPoint);return{loaded:!0}}catch(Y){let X=Y instanceof Error?Y.message:String(Y);if($.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${$.path}: ${X}`};throw Error(`Failed to load SQLite vector extension at ${$.path}: ${X}`)}}var i=null,Y$=null,Q$="document_filter_indexes",k$="document_text_fts_keys",P$=2,E$=2;function X4(){if(!i)i={customLibraryPath:x$().config.customLibraryPath},q$(i,g$);return i}function x$(){if(!Y$)Y$=M$();return Y$}function H4($,G){if(G?.readOnly||$===":memory:")return;Z4(W4($),{recursive:!0})}function H$($,G){return X4(),H4($,G),new g$($,{create:G?.readOnly?!1:!0,readonly:G?.readOnly??!1,strict:!0})}function j4($){$.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{$.exec("BEGIN IMMEDIATE");let G=$.query("SELECT version FROM document_store_schema WHERE component = ?1");if(G.get(k$)?.version!==P$)$.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(k$,P$);if(G.get(Q$)?.version!==E$)$.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(Q$,E$);$.exec("COMMIT")}catch(G){try{$.exec("ROLLBACK")}catch{}throw G}}function J4($){$.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function A4($){$.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V($){return JSON.parse($)}function S($,G){let Y=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(G);return Y!==null&&Y!==void 0}function B4($,G,Y){let X=G.replaceAll('"','""');return $.query(`PRAGMA table_info("${X}")`).all().some(({name:H})=>H===Y)}function g($){return Error(`SQLite ${$} store is read-only in this context.`)}function O4($,G){let Y=Math.min($.length,G.length),X=0;for(let H=0;H<Y;H+=1)X+=$[H]*G[H];return X}function U4($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function z4($){switch($){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function a($,G){$.exec("BEGIN IMMEDIATE");try{let Y=G();return $.exec("COMMIT"),Y}catch(Y){try{$.exec("ROLLBACK")}catch{}throw Y}}function C$($){let{alias:G,keyParameterIndex:Y,value:X,valueParameterIndex:H}=$,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${G}
WHERE ${G}.key = ?${Y}`;if(X===null)return`${F}
AND ${G}.type = 'null'
)`;if(typeof X==="boolean")return`${F}
AND ${G}.type = '${X?"true":"false"}'
)`;if(typeof X==="number")return`${F}
AND ${G}.type IN ('integer', 'real')
AND ${G}.atom = ?${H}
)`;return`${F}
AND ${G}.type = 'text'
AND ${G}.atom = ?${H}
)`}function c($){return`"${$.replaceAll('"','""')}"`}function _4($){if(/^[A-Za-z0-9]+$/.test($))return $;return`x_${Y4.from($,"utf8").toString("hex")}`}function R$($,G){return`vss_vectors_${_4($)}_dim_${G}`}function n($,G,Y){$.query(`DELETE FROM ${c(G)} WHERE rowid = ?1`).run(Y)}function V$($){let{database:G,embeddingJson:Y,rowid:X,tableName:H}=$;n(G,H,X),G.query(`INSERT INTO ${c(H)} (rowid, embedding)
VALUES (?1, json(?2))`).run(X,Y)}function K4($){let{collection:G,config:Y,database:X,filter:H,queryEmbedding:F,topK:W}=$;if(Y.mode==="off"||!Y.paths?.length)return null;let B=[G,JSON.stringify(F)],M=[];if(H)for(let[U,q]of Object.entries(H)){if(!U4(q))return null;B.push(U);let N=B.length,T=`metadata_filter_${M.length+1}`;if(q===null||typeof q==="boolean"){M.push(C$({alias:T,keyParameterIndex:N,value:q}));continue}B.push(q),M.push(C$({alias:T,keyParameterIndex:N,value:q,valueParameterIndex:B.length}))}B.push(W);let E=["collection = ?1",...M];return X.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Y.searchFunction||G$}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${B.length}`).all(...B).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function w4($,G){let Y=H$($,G);if(!G?.readOnly)j4(Y);let X=Y.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),H=Y.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Y.query("SELECT json FROM documents WHERE collection = ?1"),W=Y.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),B=S(Y,"document_text_fts"),M=S(Y,"document_text_fts_keys"),E=B&&B4(Y,"document_text_fts","searchText"),C=M?Y.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Y.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,q=B?Y.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=B&&E?Y.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,T=M?Y.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(j,Z){let O=U?.get(j,Z);if(!O)return;q?.run(O.rowid),T?.run(O.rowid)}function d(j,Z,O){if(!q||!N||!C||!U)return;let z=U.get(j,Z);if(z)q.run(z.rowid);let R=X$(O,"searchText"),L=X$(O,"text");if(L===void 0&&R===void 0){if(z)T?.run(z.rowid);return}C.run(j,Z);let D=U.get(j,Z);N.run(D.rowid,j,Z,L??null,R??null)}function p(j){let Z=Object.entries(j.filter??{}),O=Z.length>0?[`json_valid(${j.alias}.json)`]:[];for(let[z,R]of Z){let L=z4(z);if(L){if(R===null){O.push(`json_type(${j.alias}.json, '${L}') = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, '${L}') = ?${j.values.length}`);continue}j.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=j.values.length;if(R===null){O.push(`json_type(${j.alias}.json, ?${D}) = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, ?${D}) = ?${j.values.length}`)}return O}function l(j){Y.exec("BEGIN IMMEDIATE");try{for(let Z of[j.expected,...j.unchanged??[]]){let O=H.get(Z.collection,Z.id);if(!(Z.document===null?O===null:O!==null&&O.json===JSON.stringify(Z.document)))return Y.exec("ROLLBACK"),!1}for(let Z of j.set)X.run(Z.collection,Z.id,JSON.stringify(Z.document)),d(Z.collection,Z.id,Z.document);for(let Z of j.delete??[])W.run(Z.collection,Z.id),x(Z.collection,Z.id);return Y.exec("COMMIT"),!0}catch(Z){try{Y.exec("ROLLBACK")}catch{}throw Z}}return{projectionBatchSemantics:T$,async set(j,Z,O){a(Y,()=>{X.run(j,Z,JSON.stringify(O)),d(j,Z,O)})},async get(j,Z){let O=H.get(j,Z);return O?V(O.json):null},async update(j,Z,O){let z=await this.get(j,Z);if(!z)throw Error(`Document not found for update: ${j}/${Z}`);await this.set(j,Z,y$(z,O))},async query(j,Z){if(w$(Z),Z&&Object.keys(Z).length>0){let z=[j],R=p({alias:"documents",filter:Z,values:z});return Y.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(j).map((z)=>V(z.json))},async queryPage(j,Z){I$(Z);let O=[j],z=p({alias:"documents",filter:Z.filter,values:O});O.push(Z.cursor??null);let R=O.length;O.push(Z.limit+1);let L=Y.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=L.slice(0,Z.limit);return{items:D.map((y)=>V(y.json)),...L.length>Z.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(j,Z){N$(Z);let O=S$(Z.query);if(O.length===0)return[];let z=[],R,L=Z.field==="text"?Z.field:Z.field==="searchText"&&E?Z.field:null;if(B&&L){z.push(O,j);let D=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${L} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(j,`$."${Z.field.replaceAll('"',"\\\"")}"`);let D=f$(Z.query),y=[];for(let v of D)z.push(`%${v}%`),y.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${y.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Y.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(j){if(G?.readOnly)throw g("document");return l(j)},async delete(j,Z){a(Y,()=>{x(j,Z),W.run(j,Z)})}}}function Z$($,G,Y){if(Y?.readOnly&&!S($,G))return{async set(){throw g("session")},async get(){return null},async setIfUnchanged(){throw g("session")},async deleteIfUnchanged(){throw g("session")},async deleteByScope(){throw g("session")}};let X=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),H=$.query(`SELECT json FROM ${G} WHERE scope_key = ?1`),F=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=$.query(`UPDATE ${G}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),B=$.query(`DELETE FROM ${G} WHERE scope_key = ?1`),M=$.query(`DELETE FROM ${G} WHERE scope_key = ?1 AND json = ?2`),E=$.query(`DELETE FROM ${G} WHERE scope_key LIKE ?1`);return{async set(C,U){X.run(b(C),JSON.stringify(U))},async setIfUnchanged(C,U,q){return a($,()=>{let N=b(C),T=JSON.stringify(q),x=U===null?F.run(N,T):W.run(N,JSON.stringify(U),T);return Number(x.changes??0)===1})},async get(C){let U=H.get(b(C));return U?V(U.json):null},async deleteIfUnchanged(C,U){return a($,()=>{let q=M.run(b(C),JSON.stringify(U));return Number(q.changes??0)===1})},async deleteByScope(C){if(C.sessionId!==void 0){let q=B.run(b(C));return Number(q.changes??0)}let U=E.run(`${L$(C)}%`);return Number(U.changes??0)}}}function y4($,G){let Y=H$($,G);if(!G?.readOnly)J4(Y);let X=Z$(Y,"session_buffers",G),H=Z$(Y,"session_working_memory",G),F=Z$(Y,"session_journals",G);return{saveBuffer(W,B){return X.set(W,B)},saveBufferIfUnchanged(W,B,M){return X.setIfUnchanged(W,B,M)},getBuffer(W){return X.get(W)},deleteBufferIfUnchanged(W,B){return X.deleteIfUnchanged(W,B)},deleteBuffersByScope(W){return X.deleteByScope(W)},saveWorkingMemory(W,B){return H.set(W,B)},getWorkingMemory(W){return H.get(W)},deleteWorkingMemoryByScope(W){return H.deleteByScope(W)},saveJournal(W,B){return F.set(W,B)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function f4($,G,Y){let X=Y?.runtimeResolution??x$(),H=Y?.vectorExtensionConfig??X.config.vectorExtension,F=Y?.runtimeResolution?.diagnostics??X.diagnostics,W=H$($,G);if(!G?.readOnly)A4(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let B=!G?.readOnly||S(W,"vectors"),M=new Set,E=null,C=G?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,q=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,T=B?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=G?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!G?.readOnly||S(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,j=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),Z=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let J=(Y?.loadVectorExtension??D$)(H,W);return E=J&&typeof J==="object"&&"loaded"in J?J:{loaded:H.mode!=="off"&&Boolean(H.paths?.length)},E}function z(){return H.backend==="sqlite-vss"&&O().loaded}function R(J,K){let A=R$(J,K);j.run(A,J,K)}function L(J){Z.run(J.tableName,J.collection,J.dimension)}function D(J){if(!J.existed)return!0;let K=l.get(J.tableName);return!K||K.dirty!==0}function y(J){return l?.get(J)?.dirty===0}function u(J,K,A){let _=N.all(J).filter((P)=>{return V(P.embedding_json).length===K}),Q=new Set(_.map((P)=>P.rowid)),k=W.query(`SELECT rowid FROM ${c(A)}`).all();for(let P of k)if(!Q.has(P.rowid))n(W,A,P.rowid);for(let P of _)V$({database:W,embeddingJson:P.embedding_json,rowid:P.rowid,tableName:A});L({collection:J,dimension:K,tableName:A})}function v(J,K){if(!z())return null;let A=R$(J,K);if(M.has(A)){if(G?.readOnly){if(!y(A))return M.delete(A),null;return A}if(D({existed:!0,tableName:A}))u(J,K,A);return A}if(G?.readOnly){if(!S(W,A))return null;if(!y(A))return null;return M.add(A),A}let _=S(W,A);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(A)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:A}))u(J,K,A);return M.add(A),A}function v$(J){let{collection:K,filter:A,queryEmbedding:_,topK:Q}=J,k=_.length,P=v(K,k);if(!P)return null;let I=q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(I===0)return[];let s=JSON.stringify(_),w=Math.min(I,Math.max(Q,A?Q*4:Q));while(w>0){let h=W.query(`SELECT rowid, distance
FROM ${c(P)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,w),f=[];for(let j$ of h){let r=x.get(K,j$.rowid);if(!r)continue;let h$=V(r.embedding_json),J$=V(r.metadata_json);if(!W$(J$,A))continue;f.push({id:r.id,embedding:h$,metadata:J$,content:r.content,score:1/(1+Number(j$.distance))})}if(!A||f.length>=Q||w>=I)return f.slice(0,Q);w=Math.min(I,w*2)}return[]}return{async upsert(J,K){if(G?.readOnly)throw g("vector");W.transaction((_)=>{let Q=z();for(let k of _){let P=T.get(J,k.id),I=P?V(P.embedding_json).length:null,s=JSON.stringify(k.embedding);if(C.run(J,k.id,s,JSON.stringify(k.metadata),k.content),!Q){if(P&&I!==null&&I!==k.embedding.length)R(J,I);R(J,k.embedding.length);continue}let w=T.get(J,k.id);if(!w)continue;if(P&&I!==null&&I!==k.embedding.length){let f=v(J,I);if(f)n(W,f,P.rowid)}let h=v(J,k.embedding.length);if(!h)continue;V$({database:W,embeddingJson:s,rowid:w.rowid,tableName:h})}})(K)},async get(J,K){if(!B)return null;let A=U.get(J,K);if(!A)return null;return{id:A.id,embedding:V(A.embedding_json),metadata:V(A.metadata_json),content:A.content}},async search(J,K,A){if(A.topK<=0||K.length===0)return[];if(!B)return[];if(H.mode!=="off"&&H.paths?.length&&O().loaded)try{let _=H.backend==="sqlite-vss"?v$({collection:J,filter:A.filter,queryEmbedding:K,topK:A.topK}):(Y?.runExtensionSearch??K4)({collection:J,config:H,database:W,filter:A.filter,queryEmbedding:K,topK:A.topK});if(_!==null)return _;if(H.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(H.mode==="require"){let Q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${J}: ${Q}`)}}return q.all(J).map((_)=>{let Q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:Q,metadata:k,content:_.content,score:O4(Q,K)}}).filter((_)=>W$(_.metadata,A.filter)).sort((_,Q)=>{if(Q.score!==_.score)return Q.score-_.score;return _.id.localeCompare(Q.id)}).slice(0,A.topK)},async delete(J,K){if(G?.readOnly)throw g("vector");W.transaction(()=>{let _=T.get(J,K),Q=z();if(_&&Q){let k=V(_.embedding_json).length,P=v(J,k);if(P)n(W,P,_.rowid)}if(_&&!Q){let k=V(_.embedding_json).length;R(J,k)}d.run(J,K)})()}}}export{f4 as createSQLiteVectorStore,y4 as createSQLiteSessionStore,w4 as createSQLiteDocumentStore};
import{$b as D}from"./chunk-9bjprkrs.js";import{bc as q,dc as K}from"./chunk-14dkxqxk.js";var S=q((kz,O)=>{var{create:m,defineProperty:v,getOwnPropertyDescriptor:_,getOwnPropertyNames:a,getPrototypeOf:n}=Object,r=Object.prototype.hasOwnProperty,t=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},I=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of a(B))if(!r.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=_(B,G))||H.enumerable})}return z},V=(z,B,F)=>(F=z!=null?m(n(z)):{},I(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),e=(z)=>I(v({},"__esModule",{value:!0}),z),M={};t(M,{findRootDir:()=>Bz,getUserDataDir:()=>Fz});O.exports=e(M);var Y=V(K("path")),o=V(K("fs")),J=V(K("os")),zz=D();function Bz(){try{let z=process.cwd();while(z!==Y.default.dirname(z)){let B=Y.default.join(z,".vercel");if(o.default.existsSync(B))return z;z=Y.default.dirname(z)}}catch(z){throw new zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Fz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(J.default.platform()){case"darwin":return Y.default.join(J.default.homedir(),"Library/Application Support");case"linux":return Y.default.join(J.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var u=q((fz,l)=>{var{create:Gz,defineProperty:b,getOwnPropertyDescriptor:Hz,getOwnPropertyNames:Kz,getPrototypeOf:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},j=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Kz(B))if(!Wz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=Hz(B,G))||H.enumerable})}return z},E=(z,B,F)=>(F=z!=null?Gz(Qz(z)):{},j(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Yz=(z)=>j(b({},"__esModule",{value:!0}),z),x={};Xz(x,{isValidAccessToken:()=>vz,readAuthConfig:()=>$z,writeAuthConfig:()=>qz});l.exports=Yz(x);var Z=E(K("fs")),y=E(K("path")),Zz=P();function C(){let z=(0,Zz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return y.join(z,"auth.json")}function $z(){try{let z=C();if(!Z.existsSync(z))return null;let B=Z.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function qz(z){let B=C(),F=y.dirname(B);if(!Z.existsSync(F))Z.mkdirSync(F,{mode:504,recursive:!0});Z.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function vz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var k=q((iz,g)=>{var{defineProperty:R,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz}=Object,Lz=Object.prototype.hasOwnProperty,Jz=(z,B)=>{for(var F in B)R(z,F,{get:B[F],enumerable:!0})},Vz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Lz.call(z,G)&&G!==F)R(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},Az=(z)=>Vz(R({},"__esModule",{value:!0}),z),c={};Jz(c,{processTokenResponse:()=>Dz,refreshTokenRequest:()=>Tz});g.exports=Az(c);var A=K("os"),Nz="https://vercel.com",Rz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",h=`@vercel/oidc node-${process.version} ${(0,A.platform)()} (${(0,A.arch)()}) ${(0,A.hostname)()}`,N=null;async function wz(){if(N)return N;let z=`${Nz}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":h}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return N=H,H}async function Tz(z){let B=await wz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":h},body:new URLSearchParams({client_id:Rz,grant_type:"refresh_token",...z})})}async function Dz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var P=q((dz,s)=>{var{create:Iz,defineProperty:U,getOwnPropertyDescriptor:Mz,getOwnPropertyNames:Oz,getPrototypeOf:Sz}=Object,jz=Object.prototype.hasOwnProperty,Ez=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},i=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Oz(B))if(!jz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=Mz(B,G))||H.enumerable})}return z},d=(z,B,F)=>(F=z!=null?Iz(Sz(z)):{},i(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),xz=(z)=>i(U({},"__esModule",{value:!0}),z),p={};Ez(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>uz,getTokenPayload:()=>hz,getVercelCliToken:()=>Cz,getVercelDataDir:()=>yz,getVercelOidcToken:()=>lz,isExpired:()=>gz,loadToken:()=>cz,saveToken:()=>Pz});s.exports=xz(p);var $=d(K("path")),Q=d(K("fs")),X=D(),L=S(),W=u(),f=k();function yz(){let B=(0,L.getUserDataDir)();if(!B)return null;return $.join(B,"com.vercel.cli")}async function Cz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,f.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,f.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function lz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return w(T),T}function w(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function uz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=$.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function Pz(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=$.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync($.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function cz(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=$.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return w(H),H}function hz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function gz(z){return z.exp*1000<Date.now()}});
export{P as _b};
+7
-7
{
"schemaVersion": "goodmemory.capability/v2",
"name": "goodmemory",
"version": "0.7.0",
"version": "0.7.1",
"kind": "memory-layer",

@@ -24,5 +24,5 @@ "summary": "Durable user/project memory layer for chat apps, copilots, and coding agents.",

"install": {
"npmGlobal": "npm install -g goodmemory@0.7.0",
"npmPackage": "npm install goodmemory@0.7.0",
"bun": "bun add goodmemory@0.7.0"
"npmGlobal": "npm install -g goodmemory@0.7.1",
"npmPackage": "npm install goodmemory@0.7.1",
"bun": "bun add goodmemory@0.7.1"
},

@@ -33,3 +33,3 @@ "releaseStatus": {

"status": "stable",
"tarball": "goodmemory-0.7.0.tgz"
"tarball": "goodmemory-0.7.1.tgz"
},

@@ -51,3 +51,3 @@ "memoryApi": [

"steps": [
"npm install -g goodmemory@0.7.0",
"npm install -g goodmemory@0.7.1",
"goodmemory setup",

@@ -121,3 +121,3 @@ "goodmemory status"

"url": "https://github.com/hjqcan/GoodMemory/tree/main/benchmark-claims",
"note": "The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current 0.7.0 production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence."
"note": "The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current 0.7.1 production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence."
}

@@ -124,0 +124,0 @@ },

@@ -1,4 +0,4 @@

import{S as Z,T as _,U as $,V as q,W as z,X as U}from"../chunk-s31bw0jc.js";import{_ as B,aa as r}from"../chunk-jamhwrr7.js";import{oa as d}from"../chunk-njm7jqas.js";import"../chunk-963r53yf.js";import"../chunk-8d816xbx.js";import{yb as N}from"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-c28647f0.js";import"../chunk-n9j0rb5c.js";import"../chunk-eqpe4gcb.js";async function k(A,E){let G=N(A);if(!G?.ingestAgentInputEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return G.ingestAgentInputEvent({event:B(E)})}var I=160;function Q(A){return{role:"system",content:A}}function x(A){let{fragment:E,system:G}=A;if(!G)return E;if(typeof G==="string")return`${G}
import{S as Z,T as _,U as $,V as q,W as z,X as U}from"../chunk-0n0n8qnb.js";import{_ as B,aa as r}from"../chunk-jamhwrr7.js";import{oa as d}from"../chunk-4rqvqhtc.js";import"../chunk-m9yws3j1.js";import"../chunk-ftxc0stx.js";import{yb as N}from"../chunk-g7hv64gy.js";import"../chunk-b7j2aytn.js";import"../chunk-36sxnybm.js";import"../chunk-9bjprkrs.js";import"../chunk-14dkxqxk.js";async function k(A,E){let G=N(A);if(!G?.ingestAgentInputEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return G.ingestAgentInputEvent({event:B(E)})}var I=160;function Q(A){return{role:"system",content:A}}function x(A){let{fragment:E,system:G}=A;if(!G)return E;if(typeof G==="string")return`${G}
${E}`;if(Array.isArray(G))return[...G,Q(E)];return[G,Q(E)]}function V(A){let E=A.trim();return E.length>0?E:null}function O(A){if(typeof A==="string")return V(A);let E=[];for(let G of A)if(G.type==="text"){let M=V(G.text);if(M)E.push(M)}return E.length>0?E.join(`
`):null}function b(A){for(let E=A.length-1;E>=0;E-=1){let G=A[E];if(!G||G.role!=="user")continue;let M=O(G.content);if(M)return M}return null}async function K(A,E){if(!A)return;try{await A(E)}catch(G){console.error("GoodMemory ai-sdk callback failed.",G)}}function F(A){return{phase:"recall",status:"skipped",reason:A.reason,scope:A.scope,retrievalProfile:A.retrievalProfile}}function j(A){return{phase:"remember",status:"skipped",reason:A.reason,scope:A.scope}}function T(A){return A.flatMap((E)=>{let G=O(E.content);if(!G)return[];return[{role:E.role,content:G}]})}function R(A){let E=A.result.events[0];if(E?.status==="applied")return{phase:"recall",status:"applied",scope:A.scope,retrievalProfile:A.retrievalProfile};return F({reason:f(E?.reason),retrievalProfile:A.retrievalProfile,scope:A.scope})}function f(A){if(A==="ignore_memory"||A==="no_query"||A==="empty_context")return A;return"empty_context"}async function W(A,E,G){let M=G.retrievalProfile??A.defaultRetrievalProfile??"general_chat",D=V(G.query??"")??b(G.messages);try{let S=await E.beforeModelCall({scope:G.scope,...D?{query:D}:{},locale:G.locale,ignoreMemory:G.ignoreMemory,retrievalProfile:M,maxMemoryTokens:G.maxMemoryTokens??A.defaultMaxMemoryTokens??I,messages:T(G.messages)});await K(A.onMemoryEvent,R({result:S,retrievalProfile:M,scope:G.scope}));let C=V(S.context.content);if(!C)return{retrievalProfile:M,system:G.system};return{retrievalProfile:M,system:x({system:G.system,fragment:C})}}catch(S){return await K(A.onMemoryError,{phase:"recall",scope:G.scope,error:S}),{retrievalProfile:M,system:G.system}}}async function X(A,E,G,M){let D=T(G.messages);if(G.ignoreMemory){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:M,writeback:{mode:"off"}}),await K(A.onMemoryEvent,j({reason:"ignore_memory",scope:G.scope}));return}let S=V(M);if(!S){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:M,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}}),await K(A.onMemoryEvent,j({reason:"no_final_assistant_text",scope:G.scope}));return}if(!b(G.messages)){await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:S,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}}),await K(A.onMemoryEvent,j({reason:"no_text_messages",scope:G.scope}));return}try{let H=(await E.afterModelCall({scope:G.scope,locale:G.locale,messages:D,assistantText:S,writeback:{mode:"selective",annotation:"durable_candidate",policy:"allow"}})).rememberResult;if(!H){await K(A.onMemoryEvent,j({reason:"no_text_messages",scope:G.scope}));return}await K(A.onMemoryEvent,{phase:"remember",status:"succeeded",scope:G.scope,accepted:H.accepted,rejected:H.rejected})}catch(C){await K(A.onMemoryError,{phase:"remember",scope:G.scope,error:C})}}var y=new Set(["content","text","reasoning","reasoningText","files","sources","toolCalls","staticToolCalls","dynamicToolCalls","staticToolResults","dynamicToolResults","toolResults","finishReason","rawFinishReason","usage","totalUsage","warnings","steps","request","response","providerMetadata","output"]),m=new Set(["textStream","fullStream","experimental_partialOutputStream","partialOutputStream","elementStream"]);function g(A,E){return A().then((G)=>G[E])}async function c(A){let E=await A();if(typeof E.getReader==="function")return{reader:E.getReader()};return{iterator:E[Symbol.asyncIterator]()}}function h(A){let E=null,G=()=>{return E??=c(A),E},M=new ReadableStream({async pull(D){try{let S=await G(),C=S.reader?await S.reader.read():await S.iterator.next();if(C.done){S.reader?.releaseLock(),D.close();return}D.enqueue(C.value)}catch(S){D.error(S)}},async cancel(D){let S=await E;await S?.reader?.cancel(D),await S?.iterator?.return?.(),S?.reader?.releaseLock()}});return Object.assign(M,{async*[Symbol.asyncIterator](){let D=M.getReader();try{while(!0){let{done:S,value:C}=await D.read();if(S)break;yield C}}finally{D.releaseLock()}}})}function J(A,E){return h(async()=>{return(await A())[E]})}function l(A,E){return async(...G)=>{let M=await A();return M[E].apply(M,G)}}function Y(A){let{originalMessages:E,generateMessageId:G,onFinish:M,messageMetadata:D,sendReasoning:S,sendSources:C,sendFinish:H,sendStart:w,onError:v,...P}=A&&typeof A==="object"?A:{};return{responseInit:P,streamOptions:{originalMessages:E,generateMessageId:G,onFinish:M,messageMetadata:D,sendReasoning:S,sendSources:C,sendFinish:H,sendStart:w,onError:v}}}function L(A,E){return h(async()=>{return(await A()).toUIMessageStream(E)})}function a(A){let E=null,G=()=>{return E??=A(),E};return new Proxy({},{get(M,D){if(y.has(D))return g(G,D);if(m.has(D))return J(G,D);if(D==="consumeStream")return l(G,"consumeStream");if(D==="toUIMessageStream")return(S)=>L(G,S);if(D==="pipeUIMessageStreamToResponse")return(S,C)=>{let{responseInit:H,streamOptions:w}=Y(C);z({response:S,stream:L(G,w),...H})};if(D==="pipeTextStreamToResponse")return(S,C)=>{$({response:S,textStream:J(G,"textStream"),...C})};if(D==="toUIMessageStreamResponse")return(S)=>{let{responseInit:C,streamOptions:H}=Y(S);return q({stream:L(G,H),...C})};if(D==="toTextStreamResponse")return(S)=>_({textStream:J(G,"textStream"),...S});return}})}function o(A){let E=A.dependencies?.generateText??Z,G=A.dependencies?.streamText??U,M=d({memory:A.memory,defaultContextMode:"fragment",defaultMaxMemoryTokens:A.defaultMaxMemoryTokens??I});return{async generateText(D){let S=await W(A,M,D),C=D.onFinish;return E({...D,system:S.system,messages:D.messages,onFinish:async(H)=>{if(await X(A,M,D,H.text),C)await C(H)}})},streamText(D){return a(async()=>{let S=await W(A,M,D),C=D.onFinish;return G({...D,system:S.system,messages:D.messages,onFinish:async(H)=>{if(await X(A,M,D,H.text),C)await C(H)}})})}}}export{B as validateAgentInputEvent,r as isAgentInputEvent,k as ingestAgentInputEvent,o as createGoodMemoryAISDK};

@@ -15,2 +15,3 @@ import type { EvidenceLedgerFormat } from "../answer/evidenceLedgerContext";

import type { GeneralizedFusionChannel } from "../recall/generalizedFusion";
import type { FollowUpDecision } from "../recall/iterativeRecall";
import type { RecallPlanAssistant } from "../recall/recallPlan";

@@ -67,2 +68,3 @@ import type { RecallCandidateTrace, RecallHit, RecallSemanticCandidatesConfig } from "../recall/engine";

generalizedFusionMinRelativeStrength?: number;
generalizedFusionEntityPageRank?: boolean;
recallPlanExecution?: boolean;

@@ -86,2 +88,22 @@ bm25Ranking?: boolean;

recallPlanner?: RecallPlanAssistant;
retrievalCueGenerator?: {
generate(input: {
category: string;
content: string;
subject?: string;
}): Promise<string[]>;
};
followUpDecisionGenerator?: {
generate(input: {
evidence: readonly string[];
hop: number;
query: string;
}): Promise<FollowUpDecision>;
};
observationSynthesizer?: {
synthesize(input: {
contents: readonly string[];
subject: string;
}): Promise<string | null>;
};
sessionStore?: SessionStore;

@@ -88,0 +110,0 @@ /**

@@ -13,2 +13,4 @@ import type { RetrievalStrategyRolloutConfig } from "../governance/retrievalInternalRollout";

projectionBulkBackfill?: boolean;
/** Repo-only hook for sealing derived projection state before immutable replay. */
projectionPreparationSupport?: boolean;
projectionWriteThrough?: boolean;

@@ -18,4 +20,6 @@ providerRerankingStrategy?: "listwise" | "pointwise";

runtimeCompactionExtraction?: boolean;
/** Repo-only immutable SQLite view; also disables post-recall mutations. */
sqliteReadOnly?: boolean;
}
export declare function createGoodMemory(config: GoodMemoryConfig): GoodMemory;
export declare function createInternalGoodMemory(config: GoodMemoryConfig, internal?: InternalGoodMemoryOptions): GoodMemory;

@@ -8,2 +8,3 @@ import type { MemoryScope } from "../domain/scope";

assistedReviewer?: boolean;
prepareProjectionScope?: (scope: MemoryScope) => Promise<void>;
recordBehavioralOutcome?: (input: BehavioralOutcomeRecordInput & {

@@ -10,0 +11,0 @@ scope: MemoryScope;

@@ -24,2 +24,10 @@ import type { LanguageService } from "../language";

}): RecallRerankerTrace;
export declare function applyDurableSelectionToResult(input: {
language: LanguageService;
preRankLimit: number;
preserveResult: RecallResult;
query: string;
result: RecallResult;
selectedLimit: number;
}): RecallResult;
export declare function getDurableRerankerCandidateCount(result: RecallResult): number;

@@ -26,0 +34,0 @@ export declare function applyDurableRerankingToResult(input: {

#!/usr/bin/env bun
import{a as d}from"./chunk-c8pcftxd.js";import{Ja as w,La as T,ta as P,ua as y,va as c}from"./chunk-c5jbqdf4.js";import"./chunk-wy6fj8p6.js";import{resolve as y$}from"node:path";import{fileURLToPath as c$}from"node:url";var G="phase-39.http-memory.v1",_$=new Set(["export","forget","revise"]);function _($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function W($){return typeof $==="string"&&$.trim().length>0}function K($,X){let Z=$[X];if(Z===void 0)return;return W(Z)?Z.trim():void 0}function D$($){if(!_($)||!W($.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if($[j]!==void 0&&!W($[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let X={userId:$.userId.trim()},Z=K($,"tenantId"),U=K($,"workspaceId"),Q=K($,"agentId"),Y=K($,"sessionId");if(Z)X.tenantId=Z;if(U)X.workspaceId=U;if(Q)X.agentId=Q;if(Y)X.sessionId=Y;return{ok:!0,value:X}}function G$($){if(!Array.isArray($)||$.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let X=[];for(let Z of $){if(!_(Z)||!W(Z.role)||!W(Z.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};X.push({content:Z.content,role:Z.role})}return{ok:!0,value:X}}function h($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function L$($){return $==="profile"||$==="preference"||$==="reference"||$==="fact"||$==="feedback"}function B$($){return $==="always"||$==="never"||$==="auto"}function x($){return $==="blocker"||$==="open_loop"||$==="role_update"||$==="focus_update"||$==="project_state"||$==="generic_project"}function f($){return $==="identity"||$==="project"||$==="runtime"||$==="reference"||$==="preference"}function b($){return $==="do"||$==="dont"||$==="prefer"||$==="validated_pattern"}function g($){return $==="name"||$==="role"||$==="organization"||$==="location"||$==="timezone"||$==="languagePreference"||$==="currentProject"}function m($){return $==="source_of_truth"||$==="runbook"||$==="doc"||$==="dashboard"||$==="tracker"}function M$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let Z of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if($[Z]!==void 0&&!W($[Z]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if($.factKind!==void 0&&!x($.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if($.scopeKind!==void 0&&!f($.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if($.feedbackKind!==void 0&&!b($.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if($.profileField!==void 0&&!g($.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if($.referenceKind!==void 0&&!m($.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if($.tags!==void 0&&(!Array.isArray($.tags)||!$.tags.every(W)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if($.attributes!==void 0){if(!_($.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let Z of Object.values($.attributes))if(!h(Z))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let X=_($.attributes)?Object.fromEntries(Object.entries($.attributes).filter((Z)=>h(Z[1]))):void 0;return{ok:!0,value:{...W($.category)?{category:$.category}:{},...x($.factKind)?{factKind:$.factKind}:{},...f($.scopeKind)?{scopeKind:$.scopeKind}:{},...W($.subject)?{subject:$.subject}:{},...Array.isArray($.tags)?{tags:[...$.tags]}:{},...X!==void 0?{attributes:X}:{},...b($.feedbackKind)?{feedbackKind:$.feedbackKind}:{},...W($.appliesTo)?{appliesTo:$.appliesTo}:{},...g($.profileField)?{profileField:$.profileField}:{},...W($.preferenceCategory)?{preferenceCategory:$.preferenceCategory}:{},...W($.preferenceValue)?{preferenceValue:$.preferenceValue}:{},...m($.referenceKind)?{referenceKind:$.referenceKind}:{},...W($.referenceTitle)?{referenceTitle:$.referenceTitle}:{},...W($.referencePointer)?{referencePointer:$.referencePointer}:{},...W($.supersedesPointer)?{supersedesPointer:$.supersedesPointer}:{}}}}function z$($){if($===void 0)return{ok:!0,value:void 0};if(!Array.isArray($))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let X=[];for(let Z of $){if(!_(Z))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let U=Z.messageIndex;if(typeof U!=="number"||!Number.isInteger(U))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if(U<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(Z.remember!==void 0&&!B$(Z.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(Z.kindHint!==void 0&&!L$(Z.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(Z.verified!==void 0&&typeof Z.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(Z.reason!==void 0&&!W(Z.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Q=M$(Z.metadataPatch);if(!Q.ok)return Q;X.push({messageIndex:U,...Z.remember!==void 0?{remember:Z.remember}:{},...Z.kindHint!==void 0?{kindHint:Z.kindHint}:{},...Q.value!==void 0?{metadataPatch:Q.value}:{},...Z.confirmed!==void 0?{confirmed:Z.confirmed}:{},...Z.verified!==void 0?{verified:Z.verified}:{},...W(Z.reason)?{reason:Z.reason}:{}})}return{ok:!0,value:X}}function F$($){if($===void 0)return{ok:!0,value:void 0};if($==="coding_agent"||$==="general_chat")return{ok:!0,value:$};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function w$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="hybrid")return{ok:!0,value:$};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function O$($){if($===void 0)return{ok:!0,value:"system_prompt_fragment"};if($==="json"||$==="markdown"||$==="system_prompt_fragment"||$==="developer_prompt_fragment")return{ok:!0,value:$};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function K$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="llm-assisted")return{ok:!0,value:$};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function R($,X){if($===void 0&&!X)return{ok:!0,value:void 0};if(W($))return{ok:!0,value:$.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function V$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if($.source!=="user_message"&&$.source!=="manual_review"&&$.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:$.source,...W($.message)?{message:$.message}:{},...W($.excerpt)?{excerpt:$.excerpt}:{},...W($.sourceUri)?{sourceUri:$.sourceUri}:{},...Array.isArray($.sourceMessageIds)?{sourceMessageIds:$.sourceMessageIds.filter(W)}:{}}}}function T$($,X){return{error:{code:$,message:X},ok:!1}}function L($,X){return{body:X,statusCode:$}}function H($,X,Z){return L($,T$(X,Z))}async function P$($){try{let X=await $.json();if(!_(X))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:X}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function R$($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;let U=$.headers.get("x-goodmemory-operations")?.split(",").map((Q)=>Q.trim()).filter(Boolean);return{authorizedOperations:U?.includes("*")?"*":U??[],tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function C$($){if(!$.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if($.caller.userId!==$.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if($.caller.tenantId&&$.scope.tenantId!==$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if($.scope.tenantId&&!$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if($.caller.workspaceId&&$.scope.workspaceId!==$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if($.scope.workspaceId&&!$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if($.sensitive&&$.caller.authorizedOperations!=="*"){if(!$.caller.authorizedOperations.includes($.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function A$($){if(typeof $==="string")return $;return JSON.stringify($)}function M($,X){if(!X||X.content.trim().length===0)return;$.push(X)}function N$($){return Boolean($.profile||$.preferences.length>0||$.references.length>0||$.facts.length>0||$.feedback.length>0||$.archives.length>0||$.episodes.length>0||$.workingMemory||$.journal)}function v($,X=[]){let Z=$.metadata.routingDecision.strategyExplanation,U=new Set([...Z.warnings??[],...X]);if($.metadata.policyApplied?.includes("semantic_candidates_unavailable"))U.add(P);let Q=y({existingMessages:Z.warningMessages,warnings:[...U]});return{...Z.fallbackReason?{fallbackReason:Z.fallbackReason}:{},llmRefinement:Z.llmRefinement,requestedStrategy:Z.requestedStrategy,resolvedStrategy:Z.resolvedStrategy,semanticTieBreaking:Z.semanticTieBreaking,...Q.length>0?{warningMessages:Q}:{},...U.size>0?{warnings:[...U]}:{}}}function q$($){if($.requestedStrategy!=="auto"||$.runtimeInfo?.embeddingEnabled!==!0||$.runtimeInfo.retrievalPreset)return[];return($.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??$.recall.metadata.routingDecision.strategy)==="rules-only"?[P]:[]}function I$($){return{...v($.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:$.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function E$($){let X=[];if($.profile){let Z=[$.profile.identity.name,$.profile.identity.role,$.profile.identity.organization,...$.profile.activeContext.goals,...$.profile.activeContext.currentProjects].filter(W);M(X,{content:Z.join("; "),memoryId:`profile:${$.profile.userId}`,source:"goodmemory",type:"profile"})}for(let Z of $.preferences)M(X,{category:Z.category,confidence:Z.confidence,content:`${Z.category}: ${A$(Z.value)}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"preference"});for(let Z of $.references)M(X,{category:Z.referenceKind,confidence:Z.confidence,content:Z.description?`${Z.title}: ${Z.pointer} - ${Z.description}`:`${Z.title}: ${Z.pointer}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"reference"});for(let Z of $.facts)M(X,{category:Z.category,confidence:Z.confidence,content:Z.content,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"fact"});for(let Z of $.feedback)M(X,{category:Z.kind,confidence:Z.confidence,content:Z.rule,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"feedback"});for(let Z of $.episodes)M(X,{confidence:Z.confidence,content:Z.summary,memoryId:Z.id,source:"goodmemory",tags:Z.topics,type:"episode"});if($.workingMemory)M(X,{content:[$.workingMemory.currentGoal,...$.workingMemory.openLoops,...$.workingMemory.temporaryDecisions??[]].filter(W).join("; "),memoryId:`working-memory:${$.workingMemory.userId}:${$.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if($.journal)M(X,{content:[$.journal.currentState,$.journal.taskSpecification,...$.journal.workflow??[],...$.journal.errorsAndCorrections??[],...$.journal.learnings??[],...$.journal.keyResults??[],...$.journal.worklog].filter(W).join("; "),memoryId:`session-journal:${$.journal.userId}:${$.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return X}async function S$($,X,Z){if(!W(X.query))return H(400,"invalid_query","Expected query to be a non-empty string.");let U=F$(X.retrievalProfile);if(!U.ok)return H(400,U.code,U.message);let Q=w$(X.strategy);if(!Q.ok)return H(400,Q.code,Q.message);let Y=O$(X.output);if(!Y.ok)return H(400,Y.code,Y.message);let j=typeof X.maxTokens==="number"&&Number.isFinite(X.maxTokens)?Math.max(1,Math.floor(X.maxTokens)):void 0,J=Q.value??"auto",D=w($),z=D?.retrievalPreset!==void 0?J:J==="hybrid"?"hybrid":"rules-only",q={scope:Z,query:X.query,...U.value?{retrievalProfile:U.value}:{},strategy:z},B,I=void 0;try{B=await $.recall(q)}catch(k){if(J==="rules-only"||!c(k))throw k;B=await $.recall({...q,strategy:"rules-only"}),I=I$({recall:B,requestedStrategy:J})}let F=await $.buildContext({recall:B,output:Y.value,...j?{maxTokens:j}:{}}),E=E$(B),S=F.traceId??B.metadata.traceId;return L(200,{context:{content:F.content,estimatedTokens:F.estimatedTokens,omittedSections:F.omittedSections,output:F.output},contextText:F.content,contractVersion:G,hasContext:N$(B),itemCount:E.length,items:E,ok:!0,operation:"recall-context",routing:I??{...v(B,q$({recall:B,requestedStrategy:J,runtimeInfo:D})),requestedStrategy:J},...S?{traceId:S}:{}})}async function k$($,X,Z){let U=G$(X.messages);if(!U.ok)return H(400,U.code,U.message);let Q=z$(X.annotations);if(!Q.ok)return H(400,Q.code,Q.message);let Y=K$(X.extractionStrategy);if(!Y.ok)return H(400,Y.code,Y.message);let j=X.mode===void 0?"sync":X.mode;if(j!=="sync"&&j!=="async")return H(400,"invalid_mode","Expected mode to be sync or async.");let J=R(X.idempotencyKey,j==="async");if(!J.ok)return H(400,J.code,J.message);let D={scope:Z,messages:U.value,...Q.value?{annotations:Q.value}:{},...Y.value?{extractionStrategy:Y.value}:{},...W(X.locale)?{locale:X.locale}:{}};if(j==="async")try{let z=await $.jobs.enqueueRemember({...D,idempotencyKey:J.value,reason:"manual_enqueue"});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_jobs",key:J.value},job:z,mode:j,ok:!0,operation:"remember"})}catch(z){if(_(z)&&z.code==="idempotency_conflict")return H(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw z}let N=await $.remember(D);return L(200,{contractVersion:G,idempotency:J.value?{handledBy:"consumer_provenance_only",key:J.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:N})}async function h$($,X,Z){if(!W(X.signal))return H(400,"invalid_signal","Expected signal to be a non-empty string.");let U=R(X.idempotencyKey,!0);if(!U.ok)return H(400,U.code,U.message);let Q=_(X.source)?X.source:{},Y=await $.feedback({scope:Z,signal:X.signal,...W(X.locale)?{locale:X.locale}:{}});return L(200,{contractVersion:G,idempotency:{handledBy:"consumer_provenance_only",key:U.value},ok:!0,operation:"feedback",provenance:{...W(Q.eventId)?{eventId:Q.eventId}:{},...W(Q.proposalId)?{proposalId:Q.proposalId}:{},...W(Q.reason)?{reason:Q.reason}:{},...W(Q.reviewDecision)?{reviewDecision:Q.reviewDecision}:{},...W(Q.system)?{system:Q.system}:{}},result:Y})}async function x$($,X,Z){if(!W(X.memoryId))return H(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let U=await $.forget({memoryId:X.memoryId,scope:Z});return L(200,{contractVersion:G,ok:!0,operation:"forget",result:U})}async function f$($,X,Z){let U=X.includeRuntime===!0,Q=await $.exportMemory({includeRuntime:U,scope:Z});return L(200,{contractVersion:G,exported:Q,includeRuntime:U,ok:!0,operation:"export"})}async function b$($,X,Z){let U=_(X.target)?X.target:null;if(!U||!W(U.memoryId))return H(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!_(X.revision)||!W(X.revision.content))return H(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!W(X.reason))return H(400,"invalid_reason","Expected reason to be a non-empty string.");let Q=R(X.idempotencyKey,!0);if(!Q.ok)return H(400,Q.code,Q.message);let Y=Q.value;if(!Y)return H(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=V$(X.evidence);if(!j.ok)return H(400,j.code,j.message);let J=await $.reviseMemory({evidence:j.value,idempotencyKey:Y,reason:X.reason,revision:{content:X.revision.content},scope:Z,target:{memoryId:U.memoryId}});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_revision",key:Y},ok:!0,operation:"revise",result:J})}function g$($){if($==="/memory/recall-context")return"recall-context";if($==="/memory/remember")return"remember";if($==="/memory/feedback")return"feedback";if($==="/memory/forget")return"forget";if($==="/memory/export")return"export";if($==="/memory/revise")return"revise";return null}async function m$($){if($.operation==="recall-context")return S$($.memory,$.body,$.scope);if($.operation==="remember")return k$($.memory,$.body,$.scope);if($.operation==="feedback")return h$($.memory,$.body,$.scope);if($.operation==="forget")return x$($.memory,$.body,$.scope);if($.operation==="export")return f$($.memory,$.body,$.scope);return b$($.memory,$.body,$.scope)}function p($){let X=$.resolveCaller??R$,Z=$.authorize??C$;async function U(Q){if(Q.method==="GET"&&new URL(Q.url).pathname==="/healthz")return L(200,{...$.healthMetadata??{},contractVersion:G,ok:!0,status:"ok"});if(Q.method==="GET"&&new URL(Q.url).pathname==="/.well-known/goodmemory.json")return L(200,d());if(Q.method!=="POST")return H(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let Y=g$(new URL(Q.url).pathname);if(!Y)return H(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await P$(Q);if(!j.ok)return H(400,j.code,j.message);let J=D$(j.value.scope);if(!J.ok)return H(400,J.code,J.message);let D=await Z({body:j.value,caller:X(Q,j.value),operation:Y,request:Q,scope:J.value,sensitive:_$.has(Y)});if(!D.authorized)return H(D.statusCode??403,D.code??"operation_not_authorized",D.message??"Caller is not authorized for this memory operation.");try{return await m$({body:j.value,memory:$.memory,operation:Y,scope:J.value})}catch{return H(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Q){let Y=await U(Q);return new Response(JSON.stringify(Y.body),{headers:{"content-type":"application/json"},status:Y.statusCode})},handle:U}}function s(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}var a="127.0.0.1",t=8739,e="GOODMEMORY_HTTP_BRIDGE_HOST",$$="GOODMEMORY_HTTP_BRIDGE_PORT",C="GOODMEMORY_HTTP_BRIDGE_TOKEN",A="GOODMEMORY_HTTP_BRIDGE_AUTH",X$="x-goodmemory-bridge-auth",Z$="GOODMEMORY_HTTP_BRIDGE_PROFILE",Q$="GOODMEMORY_HTTP_BRIDGE_RETRIEVAL_PRESET",U$="GOODMEMORY_HTTP_BRIDGE_RECOMMENDED",W$="GOODMEMORY_PROFILE",Y$="GOODMEMORY_HTTP_BRIDGE_ALLOW_INSECURE";function d$(){console.log(`GoodMemory HTTP memory bridge
import{a as d}from"./chunk-c8pcftxd.js";import{Ja as w,La as T,ta as P,ua as y,va as c}from"./chunk-xa0pw257.js";import"./chunk-jmsnz9jn.js";import{resolve as y$}from"node:path";import{fileURLToPath as c$}from"node:url";var G="phase-39.http-memory.v1",_$=new Set(["export","forget","revise"]);function _($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function W($){return typeof $==="string"&&$.trim().length>0}function K($,X){let Z=$[X];if(Z===void 0)return;return W(Z)?Z.trim():void 0}function D$($){if(!_($)||!W($.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if($[j]!==void 0&&!W($[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let X={userId:$.userId.trim()},Z=K($,"tenantId"),U=K($,"workspaceId"),Q=K($,"agentId"),Y=K($,"sessionId");if(Z)X.tenantId=Z;if(U)X.workspaceId=U;if(Q)X.agentId=Q;if(Y)X.sessionId=Y;return{ok:!0,value:X}}function G$($){if(!Array.isArray($)||$.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let X=[];for(let Z of $){if(!_(Z)||!W(Z.role)||!W(Z.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};X.push({content:Z.content,role:Z.role})}return{ok:!0,value:X}}function h($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function L$($){return $==="profile"||$==="preference"||$==="reference"||$==="fact"||$==="feedback"}function B$($){return $==="always"||$==="never"||$==="auto"}function x($){return $==="blocker"||$==="open_loop"||$==="role_update"||$==="focus_update"||$==="project_state"||$==="generic_project"}function f($){return $==="identity"||$==="project"||$==="runtime"||$==="reference"||$==="preference"}function b($){return $==="do"||$==="dont"||$==="prefer"||$==="validated_pattern"}function g($){return $==="name"||$==="role"||$==="organization"||$==="location"||$==="timezone"||$==="languagePreference"||$==="currentProject"}function m($){return $==="source_of_truth"||$==="runbook"||$==="doc"||$==="dashboard"||$==="tracker"}function M$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let Z of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if($[Z]!==void 0&&!W($[Z]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if($.factKind!==void 0&&!x($.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if($.scopeKind!==void 0&&!f($.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if($.feedbackKind!==void 0&&!b($.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if($.profileField!==void 0&&!g($.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if($.referenceKind!==void 0&&!m($.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if($.tags!==void 0&&(!Array.isArray($.tags)||!$.tags.every(W)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if($.attributes!==void 0){if(!_($.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let Z of Object.values($.attributes))if(!h(Z))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let X=_($.attributes)?Object.fromEntries(Object.entries($.attributes).filter((Z)=>h(Z[1]))):void 0;return{ok:!0,value:{...W($.category)?{category:$.category}:{},...x($.factKind)?{factKind:$.factKind}:{},...f($.scopeKind)?{scopeKind:$.scopeKind}:{},...W($.subject)?{subject:$.subject}:{},...Array.isArray($.tags)?{tags:[...$.tags]}:{},...X!==void 0?{attributes:X}:{},...b($.feedbackKind)?{feedbackKind:$.feedbackKind}:{},...W($.appliesTo)?{appliesTo:$.appliesTo}:{},...g($.profileField)?{profileField:$.profileField}:{},...W($.preferenceCategory)?{preferenceCategory:$.preferenceCategory}:{},...W($.preferenceValue)?{preferenceValue:$.preferenceValue}:{},...m($.referenceKind)?{referenceKind:$.referenceKind}:{},...W($.referenceTitle)?{referenceTitle:$.referenceTitle}:{},...W($.referencePointer)?{referencePointer:$.referencePointer}:{},...W($.supersedesPointer)?{supersedesPointer:$.supersedesPointer}:{}}}}function z$($){if($===void 0)return{ok:!0,value:void 0};if(!Array.isArray($))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let X=[];for(let Z of $){if(!_(Z))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let U=Z.messageIndex;if(typeof U!=="number"||!Number.isInteger(U))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if(U<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(Z.remember!==void 0&&!B$(Z.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(Z.kindHint!==void 0&&!L$(Z.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(Z.verified!==void 0&&typeof Z.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(Z.reason!==void 0&&!W(Z.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Q=M$(Z.metadataPatch);if(!Q.ok)return Q;X.push({messageIndex:U,...Z.remember!==void 0?{remember:Z.remember}:{},...Z.kindHint!==void 0?{kindHint:Z.kindHint}:{},...Q.value!==void 0?{metadataPatch:Q.value}:{},...Z.confirmed!==void 0?{confirmed:Z.confirmed}:{},...Z.verified!==void 0?{verified:Z.verified}:{},...W(Z.reason)?{reason:Z.reason}:{}})}return{ok:!0,value:X}}function F$($){if($===void 0)return{ok:!0,value:void 0};if($==="coding_agent"||$==="general_chat")return{ok:!0,value:$};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function w$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="hybrid")return{ok:!0,value:$};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function O$($){if($===void 0)return{ok:!0,value:"system_prompt_fragment"};if($==="json"||$==="markdown"||$==="system_prompt_fragment"||$==="developer_prompt_fragment")return{ok:!0,value:$};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function K$($){if($===void 0)return{ok:!0,value:void 0};if($==="auto"||$==="rules-only"||$==="llm-assisted")return{ok:!0,value:$};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function R($,X){if($===void 0&&!X)return{ok:!0,value:void 0};if(W($))return{ok:!0,value:$.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function V$($){if($===void 0)return{ok:!0,value:void 0};if(!_($))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if($.source!=="user_message"&&$.source!=="manual_review"&&$.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:$.source,...W($.message)?{message:$.message}:{},...W($.excerpt)?{excerpt:$.excerpt}:{},...W($.sourceUri)?{sourceUri:$.sourceUri}:{},...Array.isArray($.sourceMessageIds)?{sourceMessageIds:$.sourceMessageIds.filter(W)}:{}}}}function T$($,X){return{error:{code:$,message:X},ok:!1}}function L($,X){return{body:X,statusCode:$}}function H($,X,Z){return L($,T$(X,Z))}async function P$($){try{let X=await $.json();if(!_(X))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:X}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function R$($){let X=$.headers.get("x-goodmemory-user-id")?.trim();if(!X)return null;let U=$.headers.get("x-goodmemory-operations")?.split(",").map((Q)=>Q.trim()).filter(Boolean);return{authorizedOperations:U?.includes("*")?"*":U??[],tenantId:$.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:X,workspaceId:$.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function C$($){if(!$.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if($.caller.userId!==$.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if($.caller.tenantId&&$.scope.tenantId!==$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if($.scope.tenantId&&!$.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if($.caller.workspaceId&&$.scope.workspaceId!==$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if($.scope.workspaceId&&!$.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if($.sensitive&&$.caller.authorizedOperations!=="*"){if(!$.caller.authorizedOperations.includes($.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function A$($){if(typeof $==="string")return $;return JSON.stringify($)}function M($,X){if(!X||X.content.trim().length===0)return;$.push(X)}function N$($){return Boolean($.profile||$.preferences.length>0||$.references.length>0||$.facts.length>0||$.feedback.length>0||$.archives.length>0||$.episodes.length>0||$.workingMemory||$.journal)}function v($,X=[]){let Z=$.metadata.routingDecision.strategyExplanation,U=new Set([...Z.warnings??[],...X]);if($.metadata.policyApplied?.includes("semantic_candidates_unavailable"))U.add(P);let Q=y({existingMessages:Z.warningMessages,warnings:[...U]});return{...Z.fallbackReason?{fallbackReason:Z.fallbackReason}:{},llmRefinement:Z.llmRefinement,requestedStrategy:Z.requestedStrategy,resolvedStrategy:Z.resolvedStrategy,semanticTieBreaking:Z.semanticTieBreaking,...Q.length>0?{warningMessages:Q}:{},...U.size>0?{warnings:[...U]}:{}}}function q$($){if($.requestedStrategy!=="auto"||$.runtimeInfo?.embeddingEnabled!==!0||$.runtimeInfo.retrievalPreset)return[];return($.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??$.recall.metadata.routingDecision.strategy)==="rules-only"?[P]:[]}function I$($){return{...v($.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:$.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function E$($){let X=[];if($.profile){let Z=[$.profile.identity.name,$.profile.identity.role,$.profile.identity.organization,...$.profile.activeContext.goals,...$.profile.activeContext.currentProjects].filter(W);M(X,{content:Z.join("; "),memoryId:`profile:${$.profile.userId}`,source:"goodmemory",type:"profile"})}for(let Z of $.preferences)M(X,{category:Z.category,confidence:Z.confidence,content:`${Z.category}: ${A$(Z.value)}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"preference"});for(let Z of $.references)M(X,{category:Z.referenceKind,confidence:Z.confidence,content:Z.description?`${Z.title}: ${Z.pointer} - ${Z.description}`:`${Z.title}: ${Z.pointer}`,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"reference"});for(let Z of $.facts)M(X,{category:Z.category,confidence:Z.confidence,content:Z.content,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"fact"});for(let Z of $.feedback)M(X,{category:Z.kind,confidence:Z.confidence,content:Z.rule,memoryId:Z.id,source:"goodmemory",tags:Z.tags,type:"feedback"});for(let Z of $.episodes)M(X,{confidence:Z.confidence,content:Z.summary,memoryId:Z.id,source:"goodmemory",tags:Z.topics,type:"episode"});if($.workingMemory)M(X,{content:[$.workingMemory.currentGoal,...$.workingMemory.openLoops,...$.workingMemory.temporaryDecisions??[]].filter(W).join("; "),memoryId:`working-memory:${$.workingMemory.userId}:${$.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if($.journal)M(X,{content:[$.journal.currentState,$.journal.taskSpecification,...$.journal.workflow??[],...$.journal.errorsAndCorrections??[],...$.journal.learnings??[],...$.journal.keyResults??[],...$.journal.worklog].filter(W).join("; "),memoryId:`session-journal:${$.journal.userId}:${$.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return X}async function S$($,X,Z){if(!W(X.query))return H(400,"invalid_query","Expected query to be a non-empty string.");let U=F$(X.retrievalProfile);if(!U.ok)return H(400,U.code,U.message);let Q=w$(X.strategy);if(!Q.ok)return H(400,Q.code,Q.message);let Y=O$(X.output);if(!Y.ok)return H(400,Y.code,Y.message);let j=typeof X.maxTokens==="number"&&Number.isFinite(X.maxTokens)?Math.max(1,Math.floor(X.maxTokens)):void 0,J=Q.value??"auto",D=w($),z=D?.retrievalPreset!==void 0?J:J==="hybrid"?"hybrid":"rules-only",q={scope:Z,query:X.query,...U.value?{retrievalProfile:U.value}:{},strategy:z},B,I=void 0;try{B=await $.recall(q)}catch(k){if(J==="rules-only"||!c(k))throw k;B=await $.recall({...q,strategy:"rules-only"}),I=I$({recall:B,requestedStrategy:J})}let F=await $.buildContext({recall:B,output:Y.value,...j?{maxTokens:j}:{}}),E=E$(B),S=F.traceId??B.metadata.traceId;return L(200,{context:{content:F.content,estimatedTokens:F.estimatedTokens,omittedSections:F.omittedSections,output:F.output},contextText:F.content,contractVersion:G,hasContext:N$(B),itemCount:E.length,items:E,ok:!0,operation:"recall-context",routing:I??{...v(B,q$({recall:B,requestedStrategy:J,runtimeInfo:D})),requestedStrategy:J},...S?{traceId:S}:{}})}async function k$($,X,Z){let U=G$(X.messages);if(!U.ok)return H(400,U.code,U.message);let Q=z$(X.annotations);if(!Q.ok)return H(400,Q.code,Q.message);let Y=K$(X.extractionStrategy);if(!Y.ok)return H(400,Y.code,Y.message);let j=X.mode===void 0?"sync":X.mode;if(j!=="sync"&&j!=="async")return H(400,"invalid_mode","Expected mode to be sync or async.");let J=R(X.idempotencyKey,j==="async");if(!J.ok)return H(400,J.code,J.message);let D={scope:Z,messages:U.value,...Q.value?{annotations:Q.value}:{},...Y.value?{extractionStrategy:Y.value}:{},...W(X.locale)?{locale:X.locale}:{}};if(j==="async")try{let z=await $.jobs.enqueueRemember({...D,idempotencyKey:J.value,reason:"manual_enqueue"});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_jobs",key:J.value},job:z,mode:j,ok:!0,operation:"remember"})}catch(z){if(_(z)&&z.code==="idempotency_conflict")return H(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw z}let N=await $.remember(D);return L(200,{contractVersion:G,idempotency:J.value?{handledBy:"consumer_provenance_only",key:J.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:N})}async function h$($,X,Z){if(!W(X.signal))return H(400,"invalid_signal","Expected signal to be a non-empty string.");let U=R(X.idempotencyKey,!0);if(!U.ok)return H(400,U.code,U.message);let Q=_(X.source)?X.source:{},Y=await $.feedback({scope:Z,signal:X.signal,...W(X.locale)?{locale:X.locale}:{}});return L(200,{contractVersion:G,idempotency:{handledBy:"consumer_provenance_only",key:U.value},ok:!0,operation:"feedback",provenance:{...W(Q.eventId)?{eventId:Q.eventId}:{},...W(Q.proposalId)?{proposalId:Q.proposalId}:{},...W(Q.reason)?{reason:Q.reason}:{},...W(Q.reviewDecision)?{reviewDecision:Q.reviewDecision}:{},...W(Q.system)?{system:Q.system}:{}},result:Y})}async function x$($,X,Z){if(!W(X.memoryId))return H(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let U=await $.forget({memoryId:X.memoryId,scope:Z});return L(200,{contractVersion:G,ok:!0,operation:"forget",result:U})}async function f$($,X,Z){let U=X.includeRuntime===!0,Q=await $.exportMemory({includeRuntime:U,scope:Z});return L(200,{contractVersion:G,exported:Q,includeRuntime:U,ok:!0,operation:"export"})}async function b$($,X,Z){let U=_(X.target)?X.target:null;if(!U||!W(U.memoryId))return H(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!_(X.revision)||!W(X.revision.content))return H(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!W(X.reason))return H(400,"invalid_reason","Expected reason to be a non-empty string.");let Q=R(X.idempotencyKey,!0);if(!Q.ok)return H(400,Q.code,Q.message);let Y=Q.value;if(!Y)return H(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=V$(X.evidence);if(!j.ok)return H(400,j.code,j.message);let J=await $.reviseMemory({evidence:j.value,idempotencyKey:Y,reason:X.reason,revision:{content:X.revision.content},scope:Z,target:{memoryId:U.memoryId}});return L(200,{contractVersion:G,idempotency:{handledBy:"goodmemory_revision",key:Y},ok:!0,operation:"revise",result:J})}function g$($){if($==="/memory/recall-context")return"recall-context";if($==="/memory/remember")return"remember";if($==="/memory/feedback")return"feedback";if($==="/memory/forget")return"forget";if($==="/memory/export")return"export";if($==="/memory/revise")return"revise";return null}async function m$($){if($.operation==="recall-context")return S$($.memory,$.body,$.scope);if($.operation==="remember")return k$($.memory,$.body,$.scope);if($.operation==="feedback")return h$($.memory,$.body,$.scope);if($.operation==="forget")return x$($.memory,$.body,$.scope);if($.operation==="export")return f$($.memory,$.body,$.scope);return b$($.memory,$.body,$.scope)}function p($){let X=$.resolveCaller??R$,Z=$.authorize??C$;async function U(Q){if(Q.method==="GET"&&new URL(Q.url).pathname==="/healthz")return L(200,{...$.healthMetadata??{},contractVersion:G,ok:!0,status:"ok"});if(Q.method==="GET"&&new URL(Q.url).pathname==="/.well-known/goodmemory.json")return L(200,d());if(Q.method!=="POST")return H(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let Y=g$(new URL(Q.url).pathname);if(!Y)return H(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await P$(Q);if(!j.ok)return H(400,j.code,j.message);let J=D$(j.value.scope);if(!J.ok)return H(400,J.code,J.message);let D=await Z({body:j.value,caller:X(Q,j.value),operation:Y,request:Q,scope:J.value,sensitive:_$.has(Y)});if(!D.authorized)return H(D.statusCode??403,D.code??"operation_not_authorized",D.message??"Caller is not authorized for this memory operation.");try{return await m$({body:j.value,memory:$.memory,operation:Y,scope:J.value})}catch{return H(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Q){let Y=await U(Q);return new Response(JSON.stringify(Y.body),{headers:{"content-type":"application/json"},status:Y.statusCode})},handle:U}}function s(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}var a="127.0.0.1",t=8739,e="GOODMEMORY_HTTP_BRIDGE_HOST",$$="GOODMEMORY_HTTP_BRIDGE_PORT",C="GOODMEMORY_HTTP_BRIDGE_TOKEN",A="GOODMEMORY_HTTP_BRIDGE_AUTH",X$="x-goodmemory-bridge-auth",Z$="GOODMEMORY_HTTP_BRIDGE_PROFILE",Q$="GOODMEMORY_HTTP_BRIDGE_RETRIEVAL_PRESET",U$="GOODMEMORY_HTTP_BRIDGE_RECOMMENDED",W$="GOODMEMORY_PROFILE",Y$="GOODMEMORY_HTTP_BRIDGE_ALLOW_INSECURE";function d$(){console.log(`GoodMemory HTTP memory bridge

@@ -4,0 +4,0 @@ Usage:

#!/usr/bin/env bun
import{$ as k,_ as j,aa as q,ba as g}from"./chunk-nj5qts2b.js";import"./chunk-c5jbqdf4.js";import"./chunk-0zbze8gh.js";import"./chunk-kt9x4w7c.js";import"./chunk-wy6fj8p6.js";import{resolve as u}from"node:path";import{fileURLToPath as x}from"node:url";async function z(){let b=j({argv:process.argv.slice(2),env:process.env});if(b.mode==="error")process.stderr.write(`${b.message}
import{$ as k,_ as j,aa as q,ba as g}from"./chunk-pd5xjr5y.js";import"./chunk-xa0pw257.js";import"./chunk-gqbzz1dr.js";import"./chunk-djzzs7r6.js";import"./chunk-jmsnz9jn.js";import{resolve as u}from"node:path";import{fileURLToPath as x}from"node:url";async function z(){let b=j({argv:process.argv.slice(2),env:process.env});if(b.mode==="error")process.stderr.write(`${b.message}
`),process.exit(1);if(b.mode==="standalone"){q(b.config),await g({allowWrite:b.allowWrite,standalone:b.config});return}await g({allowWrite:b.allowWrite||await k({host:b.host}),host:b.host})}if(process.argv[1]!==void 0&&x(import.meta.url)===u(process.argv[1]))await z();

@@ -138,2 +138,4 @@ import type { MemoryScope } from "./scope";

embeddingId?: string;
observedAt?: string;
sourceMessageIds?: string[];
createdAt: string;

@@ -140,0 +142,0 @@ archivedAt?: string;

@@ -1,1 +0,1 @@

import{$ as t,ba as r}from"../chunk-jamhwrr7.js";import{Ea as c,Fa as H,Ga as A,Ha as a,Ia as d}from"../chunk-8d816xbx.js";import{yb as o}from"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-eqpe4gcb.js";async function s(n,i){let e=o(n);if(!e?.ingestHostAgentEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return e.ingestHostAgentEvent({event:t(i)})}export{t as validateHostAgentEvent,H as validateHostActionIntent,d as resolveHostActionExecutionPlan,r as isHostAgentEvent,A as isHostActionIntent,s as ingestHostAgentEvent,a as createHostAdapter,c as HostAdapterWriteError};
import{$ as t,ba as r}from"../chunk-jamhwrr7.js";import{Ea as c,Fa as H,Ga as A,Ha as a,Ia as d}from"../chunk-ftxc0stx.js";import{yb as o}from"../chunk-g7hv64gy.js";import"../chunk-b7j2aytn.js";import"../chunk-14dkxqxk.js";async function s(n,i){let e=o(n);if(!e?.ingestHostAgentEvent)return{recorded:!1,skippedReason:"unsupported_memory"};return e.ingestHostAgentEvent({event:t(i)})}export{t as validateHostAgentEvent,H as validateHostActionIntent,d as resolveHostActionExecutionPlan,r as isHostAgentEvent,A as isHostActionIntent,s as ingestHostAgentEvent,a as createHostAdapter,c as HostAdapterWriteError};

@@ -1,1 +0,1 @@

import{ca as M,da as g,ia as m,na as y}from"../chunk-t3xe8nvv.js";import"../chunk-jr0h5wkn.js";import"../chunk-eqpe4gcb.js";import{readFileSync as c}from"node:fs";var p=new URL("../../package.json",import.meta.url),z;function s(){if(z)return z;let Q=JSON.parse(c(p,"utf8")),Y=Q.goodmemoryRelease;if(typeof Q.version!=="string"||Q.version.length===0||typeof Y?.installCommandsApplyAfterPublish!=="boolean"||typeof Y.npmDistTag!=="string"||Y.npmDistTag.length===0||Y.status!=="release-candidate"&&Y.status!=="stable")throw Error("Unable to read GoodMemory package release metadata.");return z={goodmemoryRelease:{installCommandsApplyAfterPublish:Y.installCommandsApplyAfterPublish,npmDistTag:Y.npmDistTag,status:Y.status},version:Q.version},z}var A="https://github.com/hjqcan/GoodMemory",w="https://goodmemory.vibenest.net";function I(Q={}){let Y=Q.packageMetadata??s(),X=Q.version??Y.version;return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:X,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${A}#readme`,repository:A,documentation:{inspector:`${A}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${A}/blob/main/llms.txt`,readme:`${A}#readme`,quickstart:`${A}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${X}`,npmPackage:`npm install goodmemory@${X}`,bun:`bun add goodmemory@${X}`},releaseStatus:{...Y.goodmemoryRelease,tarball:`goodmemory-${X}.tgz`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${X}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${A}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${A}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:w,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${A}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${A}#standalone-mcp-for-any-client`},http:{hosted:w,liveness:`${w}/healthz`,wellKnown:`${w}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${A}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[],historicalEvidence:{url:`${A}/tree/main/benchmark-claims`,note:`The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current ${X} production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence.`}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,builtInLanguagePacks:["en","zh-Hans","zh-Hant","ja","ko","fr","es"],durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${A}#readme`,benchmarks:`${A}/tree/main/benchmark-claims`,note:"Benchmark entries keep explicit measuredPackageVersion provenance; a package version bump never relabels historical results. Source declarations remain in benchmark-claims/*.json."}}}var D="phase-39.http-memory.v1",v=new Set(["export","forget","revise"]);function F(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function L(Q){return typeof Q==="string"&&Q.trim().length>0}function C(Q,Y){let X=Q[Y];if(X===void 0)return;return L(X)?X.trim():void 0}function i(Q){if(!F(Q)||!L(Q.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if(Q[j]!==void 0&&!L(Q[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let Y={userId:Q.userId.trim()},X=C(Q,"tenantId"),$=C(Q,"workspaceId"),Z=C(Q,"agentId"),U=C(Q,"sessionId");if(X)Y.tenantId=X;if($)Y.workspaceId=$;if(Z)Y.agentId=Z;if(U)Y.sessionId=U;return{ok:!0,value:Y}}function o(Q){if(!Array.isArray(Q)||Q.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let Y=[];for(let X of Q){if(!F(X)||!L(X.role)||!L(X.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};Y.push({content:X.content,role:X.role})}return{ok:!0,value:Y}}function q(Q){return Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"}function r(Q){return Q==="profile"||Q==="preference"||Q==="reference"||Q==="fact"||Q==="feedback"}function n(Q){return Q==="always"||Q==="never"||Q==="auto"}function N(Q){return Q==="blocker"||Q==="open_loop"||Q==="role_update"||Q==="focus_update"||Q==="project_state"||Q==="generic_project"}function f(Q){return Q==="identity"||Q==="project"||Q==="runtime"||Q==="reference"||Q==="preference"}function E(Q){return Q==="do"||Q==="dont"||Q==="prefer"||Q==="validated_pattern"}function S(Q){return Q==="name"||Q==="role"||Q==="organization"||Q==="location"||Q==="timezone"||Q==="languagePreference"||Q==="currentProject"}function b(Q){return Q==="source_of_truth"||Q==="runbook"||Q==="doc"||Q==="dashboard"||Q==="tracker"}function u(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let X of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if(Q[X]!==void 0&&!L(Q[X]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if(Q.factKind!==void 0&&!N(Q.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if(Q.scopeKind!==void 0&&!f(Q.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if(Q.feedbackKind!==void 0&&!E(Q.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if(Q.profileField!==void 0&&!S(Q.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if(Q.referenceKind!==void 0&&!b(Q.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if(Q.tags!==void 0&&(!Array.isArray(Q.tags)||!Q.tags.every(L)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if(Q.attributes!==void 0){if(!F(Q.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let X of Object.values(Q.attributes))if(!q(X))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let Y=F(Q.attributes)?Object.fromEntries(Object.entries(Q.attributes).filter((X)=>q(X[1]))):void 0;return{ok:!0,value:{...L(Q.category)?{category:Q.category}:{},...N(Q.factKind)?{factKind:Q.factKind}:{},...f(Q.scopeKind)?{scopeKind:Q.scopeKind}:{},...L(Q.subject)?{subject:Q.subject}:{},...Array.isArray(Q.tags)?{tags:[...Q.tags]}:{},...Y!==void 0?{attributes:Y}:{},...E(Q.feedbackKind)?{feedbackKind:Q.feedbackKind}:{},...L(Q.appliesTo)?{appliesTo:Q.appliesTo}:{},...S(Q.profileField)?{profileField:Q.profileField}:{},...L(Q.preferenceCategory)?{preferenceCategory:Q.preferenceCategory}:{},...L(Q.preferenceValue)?{preferenceValue:Q.preferenceValue}:{},...b(Q.referenceKind)?{referenceKind:Q.referenceKind}:{},...L(Q.referenceTitle)?{referenceTitle:Q.referenceTitle}:{},...L(Q.referencePointer)?{referencePointer:Q.referencePointer}:{},...L(Q.supersedesPointer)?{supersedesPointer:Q.supersedesPointer}:{}}}}function l(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!Array.isArray(Q))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let Y=[];for(let X of Q){if(!F(X))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let $=X.messageIndex;if(typeof $!=="number"||!Number.isInteger($))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if($<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(X.remember!==void 0&&!n(X.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(X.kindHint!==void 0&&!r(X.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(X.confirmed!==void 0&&typeof X.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(X.verified!==void 0&&typeof X.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(X.reason!==void 0&&!L(X.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Z=u(X.metadataPatch);if(!Z.ok)return Z;Y.push({messageIndex:$,...X.remember!==void 0?{remember:X.remember}:{},...X.kindHint!==void 0?{kindHint:X.kindHint}:{},...Z.value!==void 0?{metadataPatch:Z.value}:{},...X.confirmed!==void 0?{confirmed:X.confirmed}:{},...X.verified!==void 0?{verified:X.verified}:{},...L(X.reason)?{reason:X.reason}:{}})}return{ok:!0,value:Y}}function t(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="coding_agent"||Q==="general_chat")return{ok:!0,value:Q};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function a(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="hybrid")return{ok:!0,value:Q};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function e(Q){if(Q===void 0)return{ok:!0,value:"system_prompt_fragment"};if(Q==="json"||Q==="markdown"||Q==="system_prompt_fragment"||Q==="developer_prompt_fragment")return{ok:!0,value:Q};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function QQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="llm-assisted")return{ok:!0,value:Q};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function O(Q,Y){if(Q===void 0&&!Y)return{ok:!0,value:void 0};if(L(Q))return{ok:!0,value:Q.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function XQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if(Q.source!=="user_message"&&Q.source!=="manual_review"&&Q.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:Q.source,...L(Q.message)?{message:Q.message}:{},...L(Q.excerpt)?{excerpt:Q.excerpt}:{},...L(Q.sourceUri)?{sourceUri:Q.sourceUri}:{},...Array.isArray(Q.sourceMessageIds)?{sourceMessageIds:Q.sourceMessageIds.filter(L)}:{}}}}function YQ(Q,Y){return{error:{code:Q,message:Y},ok:!1}}function G(Q,Y){return{body:Y,statusCode:Q}}function W(Q,Y,X){return G(Q,YQ(Y,X))}async function ZQ(Q){try{let Y=await Q.json();if(!F(Y))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:Y}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function $Q(Q){let Y=Q.headers.get("x-goodmemory-user-id")?.trim();if(!Y)return null;let $=Q.headers.get("x-goodmemory-operations")?.split(",").map((Z)=>Z.trim()).filter(Boolean);return{authorizedOperations:$?.includes("*")?"*":$??[],tenantId:Q.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:Y,workspaceId:Q.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function LQ(Q){if(!Q.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if(Q.caller.userId!==Q.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if(Q.caller.tenantId&&Q.scope.tenantId!==Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if(Q.scope.tenantId&&!Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if(Q.caller.workspaceId&&Q.scope.workspaceId!==Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if(Q.scope.workspaceId&&!Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if(Q.sensitive&&Q.caller.authorizedOperations!=="*"){if(!Q.caller.authorizedOperations.includes(Q.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function UQ(Q){return{userId:Q.userId,...Q.tenantId?{tenantId:Q.tenantId}:{},...Q.workspaceId?{workspaceId:Q.workspaceId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.sessionId?{sessionId:Q.sessionId}:{}}}function jQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function H(Q,Y){if(!Y||Y.content.trim().length===0)return;Q.push(Y)}function WQ(Q){return Boolean(Q.profile||Q.preferences.length>0||Q.references.length>0||Q.facts.length>0||Q.feedback.length>0||Q.archives.length>0||Q.episodes.length>0||Q.workingMemory||Q.journal)}function d(Q,Y=[]){let X=Q.metadata.routingDecision.strategyExplanation,$=new Set([...X.warnings??[],...Y]);if(Q.metadata.policyApplied?.includes("semantic_candidates_unavailable"))$.add(M);let Z=g({existingMessages:X.warningMessages,warnings:[...$]});return{...X.fallbackReason?{fallbackReason:X.fallbackReason}:{},llmRefinement:X.llmRefinement,requestedStrategy:X.requestedStrategy,resolvedStrategy:X.resolvedStrategy,semanticTieBreaking:X.semanticTieBreaking,...Z.length>0?{warningMessages:Z}:{},...$.size>0?{warnings:[...$]}:{}}}function _Q(Q){if(Q.requestedStrategy!=="auto"||Q.runtimeInfo?.embeddingEnabled!==!0||Q.runtimeInfo.retrievalPreset)return[];return(Q.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??Q.recall.metadata.routingDecision.strategy)==="rules-only"?[M]:[]}function AQ(Q){return{...d(Q.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:Q.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function FQ(Q){let Y=[];if(Q.profile){let X=[Q.profile.identity.name,Q.profile.identity.role,Q.profile.identity.organization,...Q.profile.activeContext.goals,...Q.profile.activeContext.currentProjects].filter(L);H(Y,{content:X.join("; "),memoryId:`profile:${Q.profile.userId}`,source:"goodmemory",type:"profile"})}for(let X of Q.preferences)H(Y,{category:X.category,confidence:X.confidence,content:`${X.category}: ${jQ(X.value)}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"preference"});for(let X of Q.references)H(Y,{category:X.referenceKind,confidence:X.confidence,content:X.description?`${X.title}: ${X.pointer} - ${X.description}`:`${X.title}: ${X.pointer}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"reference"});for(let X of Q.facts)H(Y,{category:X.category,confidence:X.confidence,content:X.content,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"fact"});for(let X of Q.feedback)H(Y,{category:X.kind,confidence:X.confidence,content:X.rule,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"feedback"});for(let X of Q.episodes)H(Y,{confidence:X.confidence,content:X.summary,memoryId:X.id,source:"goodmemory",tags:X.topics,type:"episode"});if(Q.workingMemory)H(Y,{content:[Q.workingMemory.currentGoal,...Q.workingMemory.openLoops,...Q.workingMemory.temporaryDecisions??[]].filter(L).join("; "),memoryId:`working-memory:${Q.workingMemory.userId}:${Q.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if(Q.journal)H(Y,{content:[Q.journal.currentState,Q.journal.taskSpecification,...Q.journal.workflow??[],...Q.journal.errorsAndCorrections??[],...Q.journal.learnings??[],...Q.journal.keyResults??[],...Q.journal.worklog].filter(L).join("; "),memoryId:`session-journal:${Q.journal.userId}:${Q.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return Y}async function BQ(Q,Y,X){if(!L(Y.query))return W(400,"invalid_query","Expected query to be a non-empty string.");let $=t(Y.retrievalProfile);if(!$.ok)return W(400,$.code,$.message);let Z=a(Y.strategy);if(!Z.ok)return W(400,Z.code,Z.message);let U=e(Y.output);if(!U.ok)return W(400,U.code,U.message);let j=typeof Y.maxTokens==="number"&&Number.isFinite(Y.maxTokens)?Math.max(1,Math.floor(Y.maxTokens)):void 0,_=Z.value??"auto",B=y(Q),J=B?.retrievalPreset!==void 0?_:_==="hybrid"?"hybrid":"rules-only",R={scope:X,query:Y.query,...$.value?{retrievalProfile:$.value}:{},strategy:J},V,P=void 0;try{V=await Q.recall(R)}catch(h){if(_==="rules-only"||!m(h))throw h;V=await Q.recall({...R,strategy:"rules-only"}),P=AQ({recall:V,requestedStrategy:_})}let T=await Q.buildContext({recall:V,output:U.value,...j?{maxTokens:j}:{}}),k=FQ(V),x=T.traceId??V.metadata.traceId;return G(200,{context:{content:T.content,estimatedTokens:T.estimatedTokens,omittedSections:T.omittedSections,output:T.output},contextText:T.content,contractVersion:D,hasContext:WQ(V),itemCount:k.length,items:k,ok:!0,operation:"recall-context",routing:P??{...d(V,_Q({recall:V,requestedStrategy:_,runtimeInfo:B})),requestedStrategy:_},...x?{traceId:x}:{}})}async function GQ(Q,Y,X){let $=o(Y.messages);if(!$.ok)return W(400,$.code,$.message);let Z=l(Y.annotations);if(!Z.ok)return W(400,Z.code,Z.message);let U=QQ(Y.extractionStrategy);if(!U.ok)return W(400,U.code,U.message);let j=Y.mode===void 0?"sync":Y.mode;if(j!=="sync"&&j!=="async")return W(400,"invalid_mode","Expected mode to be sync or async.");let _=O(Y.idempotencyKey,j==="async");if(!_.ok)return W(400,_.code,_.message);let B={scope:X,messages:$.value,...Z.value?{annotations:Z.value}:{},...U.value?{extractionStrategy:U.value}:{},...L(Y.locale)?{locale:Y.locale}:{}};if(j==="async")try{let J=await Q.jobs.enqueueRemember({...B,idempotencyKey:_.value,reason:"manual_enqueue"});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_jobs",key:_.value},job:J,mode:j,ok:!0,operation:"remember"})}catch(J){if(F(J)&&J.code==="idempotency_conflict")return W(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw J}let K=await Q.remember(B);return G(200,{contractVersion:D,idempotency:_.value?{handledBy:"consumer_provenance_only",key:_.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:K})}async function VQ(Q,Y,X){if(!L(Y.signal))return W(400,"invalid_signal","Expected signal to be a non-empty string.");let $=O(Y.idempotencyKey,!0);if(!$.ok)return W(400,$.code,$.message);let Z=F(Y.source)?Y.source:{},U=await Q.feedback({scope:X,signal:Y.signal,...L(Y.locale)?{locale:Y.locale}:{}});return G(200,{contractVersion:D,idempotency:{handledBy:"consumer_provenance_only",key:$.value},ok:!0,operation:"feedback",provenance:{...L(Z.eventId)?{eventId:Z.eventId}:{},...L(Z.proposalId)?{proposalId:Z.proposalId}:{},...L(Z.reason)?{reason:Z.reason}:{},...L(Z.reviewDecision)?{reviewDecision:Z.reviewDecision}:{},...L(Z.system)?{system:Z.system}:{}},result:U})}async function HQ(Q,Y,X){if(!L(Y.memoryId))return W(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let $=await Q.forget({memoryId:Y.memoryId,scope:X});return G(200,{contractVersion:D,ok:!0,operation:"forget",result:$})}async function DQ(Q,Y,X){let $=Y.includeRuntime===!0,Z=await Q.exportMemory({includeRuntime:$,scope:X});return G(200,{contractVersion:D,exported:Z,includeRuntime:$,ok:!0,operation:"export"})}async function JQ(Q,Y,X){let $=F(Y.target)?Y.target:null;if(!$||!L($.memoryId))return W(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!F(Y.revision)||!L(Y.revision.content))return W(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!L(Y.reason))return W(400,"invalid_reason","Expected reason to be a non-empty string.");let Z=O(Y.idempotencyKey,!0);if(!Z.ok)return W(400,Z.code,Z.message);let U=Z.value;if(!U)return W(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=XQ(Y.evidence);if(!j.ok)return W(400,j.code,j.message);let _=await Q.reviseMemory({evidence:j.value,idempotencyKey:U,reason:Y.reason,revision:{content:Y.revision.content},scope:X,target:{memoryId:$.memoryId}});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_revision",key:U},ok:!0,operation:"revise",result:_})}function TQ(Q){if(Q==="/memory/recall-context")return"recall-context";if(Q==="/memory/remember")return"remember";if(Q==="/memory/feedback")return"feedback";if(Q==="/memory/forget")return"forget";if(Q==="/memory/export")return"export";if(Q==="/memory/revise")return"revise";return null}async function zQ(Q){if(Q.operation==="recall-context")return BQ(Q.memory,Q.body,Q.scope);if(Q.operation==="remember")return GQ(Q.memory,Q.body,Q.scope);if(Q.operation==="feedback")return VQ(Q.memory,Q.body,Q.scope);if(Q.operation==="forget")return HQ(Q.memory,Q.body,Q.scope);if(Q.operation==="export")return DQ(Q.memory,Q.body,Q.scope);return JQ(Q.memory,Q.body,Q.scope)}function PQ(Q){let Y=Q.resolveCaller??$Q,X=Q.authorize??LQ;async function $(Z){if(Z.method==="GET"&&new URL(Z.url).pathname==="/healthz")return G(200,{...Q.healthMetadata??{},contractVersion:D,ok:!0,status:"ok"});if(Z.method==="GET"&&new URL(Z.url).pathname==="/.well-known/goodmemory.json")return G(200,I());if(Z.method!=="POST")return W(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let U=TQ(new URL(Z.url).pathname);if(!U)return W(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await ZQ(Z);if(!j.ok)return W(400,j.code,j.message);let _=i(j.value.scope);if(!_.ok)return W(400,_.code,_.message);let B=await X({body:j.value,caller:Y(Z,j.value),operation:U,request:Z,scope:_.value,sensitive:v.has(U)});if(!B.authorized)return W(B.statusCode??403,B.code??"operation_not_authorized",B.message??"Caller is not authorized for this memory operation.");try{return await zQ({body:j.value,memory:Q.memory,operation:U,scope:_.value})}catch{return W(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Z){let U=await $(Z);return new Response(JSON.stringify(U.body),{headers:{"content-type":"application/json"},status:U.statusCode})},handle:$}}function kQ(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}function xQ(Q){if(Q.ok!==!0||!Array.isArray(Q.items))throw Error("Expected a successful GoodMemory recall-context response.");let Y=Q.items.filter(F).map((X)=>({content:L(X.content)?X.content:"",memoryId:L(X.memoryId)?X.memoryId:"",type:typeof X.type==="string"?X.type:"fact"})).filter((X)=>X.memoryId.length>0&&X.content.length>0);return{context:typeof Q.contextText==="string"?Q.contextText:"",memories:Y.map((X)=>({id:X.memoryId,kind:X.type,source:"goodmemory-http-bridge",text:X.content})),metadata:{hasContext:Q.hasContext===!0,itemCount:typeof Q.itemCount==="number"?Q.itemCount:Y.length,policyBoundary:"product_owned",source:"goodmemory-http-bridge",...L(Q.traceId)?{traceId:Q.traceId}:{}}}}function hQ(Q){return UQ({agentId:Q.agentId??"life-coach",sessionId:Q.sessionId,tenantId:Q.tenantId,userId:Q.userId,workspaceId:Q.workspaceId})}export{xQ as toOneLifeMemoryContextResponse,hQ as toLifeCoachScope,kQ as createLifeCoachHttpRememberConfig,PQ as createGoodMemoryHttpMemoryBridge,FQ as buildGoodMemoryHttpMemoryItems,D as GOODMEMORY_HTTP_MEMORY_BRIDGE_CONTRACT_VERSION};
import{ca as M,da as g,ia as m,na as y}from"../chunk-e5bhvzqx.js";import"../chunk-b7j2aytn.js";import"../chunk-14dkxqxk.js";import{readFileSync as c}from"node:fs";var p=new URL("../../package.json",import.meta.url),z;function s(){if(z)return z;let Q=JSON.parse(c(p,"utf8")),Y=Q.goodmemoryRelease;if(typeof Q.version!=="string"||Q.version.length===0||typeof Y?.installCommandsApplyAfterPublish!=="boolean"||typeof Y.npmDistTag!=="string"||Y.npmDistTag.length===0||Y.status!=="release-candidate"&&Y.status!=="stable")throw Error("Unable to read GoodMemory package release metadata.");return z={goodmemoryRelease:{installCommandsApplyAfterPublish:Y.installCommandsApplyAfterPublish,npmDistTag:Y.npmDistTag,status:Y.status},version:Q.version},z}var A="https://github.com/hjqcan/GoodMemory",w="https://goodmemory.vibenest.net";function I(Q={}){let Y=Q.packageMetadata??s(),X=Q.version??Y.version;return{schemaVersion:"goodmemory.capability/v2",name:"goodmemory",version:X,kind:"memory-layer",summary:"Durable user/project memory layer for chat apps, copilots, and coding agents.",description:"GoodMemory is the product memory layer between an app or installed agent host and the model runtime: write selected facts, recall the right context, inject it into the next turn, audit what happened, and delete it when it is wrong.",notA:["llm","agent-framework","vector-database","rag-system"],license:"MIT",homepage:`${A}#readme`,repository:A,documentation:{inspector:`${A}/blob/main/docs/GoodMemory-Inspector-and-Admin-API.md`,llmsTxt:`${A}/blob/main/llms.txt`,readme:`${A}#readme`,quickstart:`${A}#quickstart-codex-or-claude-code-memory`},install:{npmGlobal:`npm install -g goodmemory@${X}`,npmPackage:`npm install goodmemory@${X}`,bun:`bun add goodmemory@${X}`},releaseStatus:{...Y.goodmemoryRelease,tarball:`goodmemory-${X}.tgz`},memoryApi:["remember","recall","buildContext","feedback","forget","exportMemory","deleteAllMemory"],onboarding:[{audience:"installed-coding-agent-host",when:"You are, or run inside, Claude Code or Codex.",method:"cli",steps:[`npm install -g goodmemory@${X}`,"goodmemory setup","goodmemory status"],autoDetect:"goodmemory adopt",docs:`${A}#quickstart-codex-or-claude-code-memory`},{audience:"mcp-client",when:"You speak the Model Context Protocol (Cursor, Windsurf, Cline, Claude Desktop, Gemini CLI, OpenCode, or a custom MCP client).",method:"mcp",mcpServer:{command:"goodmemory-mcp",args:["--standalone","--user-id","YOUR_USER_ID"]},autoDetect:"goodmemory adopt",docs:`${A}#standalone-mcp-for-any-client`},{audience:"framework-agent-or-backend",when:"You are a framework agent (LangGraph, custom loop) or a backend that calls memory as an HTTP service.",method:"http",endpoint:w,selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",pythonClient:"pip install goodmemory-client",docs:`${A}#pythonfastapi-http-bridge`}],mcp:{command:"goodmemory-mcp",standaloneArgs:["--standalone","--user-id","YOUR_USER_ID"],primaryTools:["goodmemory_get_context","goodmemory_remember"],readOnlyToolCount:8,writeTool:"goodmemory_remember (opt-in via --allow-write)",registryName:"io.github.hjqcan/goodmemory",docs:`${A}#standalone-mcp-for-any-client`},http:{hosted:w,liveness:`${w}/healthz`,wellKnown:`${w}/.well-known/goodmemory.json`,auth:"bearer-token",selfHost:"goodmemory-http-bridge --recommended OR GOODMEMORY_PROFILE=agent-recommended goodmemory-http-bridge",endpoints:{recall:"POST /memory/recall-context",remember:"POST /memory/remember",feedback:"POST /memory/feedback",export:"POST /memory/export",forget:"POST /memory/forget",revise:"POST /memory/revise"},pythonClient:"goodmemory-client (PyPI)",docs:`${A}#pythonfastapi-http-bridge`},benchmarks:{currentClaims:[],historicalEvidence:{url:`${A}/tree/main/benchmark-claims`,note:`The v0.6.0 LoCoMo, BEAM, and MemoryAgentBench results, plus older LongMemEval and ImplicitMemBench runs, remain reproducible versioned evidence. None is a current ${X} production claim until rerun against this package line. LongMemEval and ImplicitMemBench remain internal evidence.`}},capabilities:{localFirst:!0,embeddingFreeDefault:!0,builtInLanguagePacks:["en","zh-Hans","zh-Hant","ja","ko","fr","es"],durableStore:"sqlite (default), postgres (opt-in)",audit:!0,deletion:!0,localInspector:"goodmemory inspector serve (loopback-only React console and /admin/v1 API)",correctByDefaultRecall:"Recall never silently degrades: a downgraded strategy carries routing.warnings (semantic_recall_inactive) and routing.warningMessages (semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET) instead of quietly returning the lexical floor."},canonicalSources:{prose:`${A}#readme`,benchmarks:`${A}/tree/main/benchmark-claims`,note:"Benchmark entries keep explicit measuredPackageVersion provenance; a package version bump never relabels historical results. Source declarations remain in benchmark-claims/*.json."}}}var D="phase-39.http-memory.v1",v=new Set(["export","forget","revise"]);function F(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function L(Q){return typeof Q==="string"&&Q.trim().length>0}function C(Q,Y){let X=Q[Y];if(X===void 0)return;return L(X)?X.trim():void 0}function i(Q){if(!F(Q)||!L(Q.userId))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};for(let j of["tenantId","workspaceId","agentId","sessionId"])if(Q[j]!==void 0&&!L(Q[j]))return{code:"invalid_scope",message:"Expected scope.userId and optional string tenant/workspace/agent/session fields.",ok:!1};let Y={userId:Q.userId.trim()},X=C(Q,"tenantId"),$=C(Q,"workspaceId"),Z=C(Q,"agentId"),U=C(Q,"sessionId");if(X)Y.tenantId=X;if($)Y.workspaceId=$;if(Z)Y.agentId=Z;if(U)Y.sessionId=U;return{ok:!0,value:Y}}function o(Q){if(!Array.isArray(Q)||Q.length===0)return{code:"invalid_messages",message:"Expected messages to be a non-empty array.",ok:!1};let Y=[];for(let X of Q){if(!F(X)||!L(X.role)||!L(X.content))return{code:"invalid_messages",message:"Expected every message to include role and content string fields.",ok:!1};Y.push({content:X.content,role:X.role})}return{ok:!0,value:Y}}function q(Q){return Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"}function r(Q){return Q==="profile"||Q==="preference"||Q==="reference"||Q==="fact"||Q==="feedback"}function n(Q){return Q==="always"||Q==="never"||Q==="auto"}function N(Q){return Q==="blocker"||Q==="open_loop"||Q==="role_update"||Q==="focus_update"||Q==="project_state"||Q==="generic_project"}function f(Q){return Q==="identity"||Q==="project"||Q==="runtime"||Q==="reference"||Q==="preference"}function E(Q){return Q==="do"||Q==="dont"||Q==="prefer"||Q==="validated_pattern"}function S(Q){return Q==="name"||Q==="role"||Q==="organization"||Q==="location"||Q==="timezone"||Q==="languagePreference"||Q==="currentProject"}function b(Q){return Q==="source_of_truth"||Q==="runbook"||Q==="doc"||Q==="dashboard"||Q==="tracker"}function u(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch to be an object when provided.",ok:!1};for(let X of["category","factKind","scopeKind","subject","feedbackKind","appliesTo","profileField","preferenceCategory","preferenceValue","referenceKind","referenceTitle","referencePointer","supersedesPointer"])if(Q[X]!==void 0&&!L(Q[X]))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch string fields to be non-empty strings.",ok:!1};if(Q.factKind!==void 0&&!N(Q.factKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.factKind to be a supported fact kind.",ok:!1};if(Q.scopeKind!==void 0&&!f(Q.scopeKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.scopeKind to be a supported scope kind.",ok:!1};if(Q.feedbackKind!==void 0&&!E(Q.feedbackKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.feedbackKind to be a supported feedback kind.",ok:!1};if(Q.profileField!==void 0&&!S(Q.profileField))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.profileField to be a supported profile field.",ok:!1};if(Q.referenceKind!==void 0&&!b(Q.referenceKind))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.referenceKind to be a supported reference kind.",ok:!1};if(Q.tags!==void 0&&(!Array.isArray(Q.tags)||!Q.tags.every(L)))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.tags to be an array of non-empty strings.",ok:!1};if(Q.attributes!==void 0){if(!F(Q.attributes))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes to be an object.",ok:!1};for(let X of Object.values(Q.attributes))if(!q(X))return{code:"invalid_annotations",message:"Expected annotation.metadataPatch.attributes values to be string, number, boolean, or null.",ok:!1}}let Y=F(Q.attributes)?Object.fromEntries(Object.entries(Q.attributes).filter((X)=>q(X[1]))):void 0;return{ok:!0,value:{...L(Q.category)?{category:Q.category}:{},...N(Q.factKind)?{factKind:Q.factKind}:{},...f(Q.scopeKind)?{scopeKind:Q.scopeKind}:{},...L(Q.subject)?{subject:Q.subject}:{},...Array.isArray(Q.tags)?{tags:[...Q.tags]}:{},...Y!==void 0?{attributes:Y}:{},...E(Q.feedbackKind)?{feedbackKind:Q.feedbackKind}:{},...L(Q.appliesTo)?{appliesTo:Q.appliesTo}:{},...S(Q.profileField)?{profileField:Q.profileField}:{},...L(Q.preferenceCategory)?{preferenceCategory:Q.preferenceCategory}:{},...L(Q.preferenceValue)?{preferenceValue:Q.preferenceValue}:{},...b(Q.referenceKind)?{referenceKind:Q.referenceKind}:{},...L(Q.referenceTitle)?{referenceTitle:Q.referenceTitle}:{},...L(Q.referencePointer)?{referencePointer:Q.referencePointer}:{},...L(Q.supersedesPointer)?{supersedesPointer:Q.supersedesPointer}:{}}}}function l(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!Array.isArray(Q))return{code:"invalid_annotations",message:"Expected annotations to be an array when provided.",ok:!1};let Y=[];for(let X of Q){if(!F(X))return{code:"invalid_annotations",message:"Expected every annotation to be an object.",ok:!1};let $=X.messageIndex;if(typeof $!=="number"||!Number.isInteger($))return{code:"invalid_annotations",message:"Expected every annotation to include integer messageIndex.",ok:!1};if($<0)return{code:"invalid_annotations",message:"Expected annotation.messageIndex to be non-negative.",ok:!1};if(X.remember!==void 0&&!n(X.remember))return{code:"invalid_annotations",message:"Expected annotation.remember to be always, never, or auto.",ok:!1};if(X.kindHint!==void 0&&!r(X.kindHint))return{code:"invalid_annotations",message:"Expected annotation.kindHint to be profile, preference, reference, fact, or feedback.",ok:!1};if(X.confirmed!==void 0&&typeof X.confirmed!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.confirmed to be a boolean when provided.",ok:!1};if(X.verified!==void 0&&typeof X.verified!=="boolean")return{code:"invalid_annotations",message:"Expected annotation.verified to be a boolean when provided.",ok:!1};if(X.reason!==void 0&&!L(X.reason))return{code:"invalid_annotations",message:"Expected annotation.reason to be a non-empty string when provided.",ok:!1};let Z=u(X.metadataPatch);if(!Z.ok)return Z;Y.push({messageIndex:$,...X.remember!==void 0?{remember:X.remember}:{},...X.kindHint!==void 0?{kindHint:X.kindHint}:{},...Z.value!==void 0?{metadataPatch:Z.value}:{},...X.confirmed!==void 0?{confirmed:X.confirmed}:{},...X.verified!==void 0?{verified:X.verified}:{},...L(X.reason)?{reason:X.reason}:{}})}return{ok:!0,value:Y}}function t(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="coding_agent"||Q==="general_chat")return{ok:!0,value:Q};return{code:"invalid_retrieval_profile",message:"Expected retrievalProfile to be general_chat or coding_agent.",ok:!1}}function a(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="hybrid")return{ok:!0,value:Q};return{code:"invalid_recall_strategy",message:"Expected strategy to be auto, rules-only, or hybrid.",ok:!1}}function e(Q){if(Q===void 0)return{ok:!0,value:"system_prompt_fragment"};if(Q==="json"||Q==="markdown"||Q==="system_prompt_fragment"||Q==="developer_prompt_fragment")return{ok:!0,value:Q};return{code:"invalid_context_output",message:"Expected output to be json, markdown, system_prompt_fragment, or developer_prompt_fragment.",ok:!1}}function QQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(Q==="auto"||Q==="rules-only"||Q==="llm-assisted")return{ok:!0,value:Q};return{code:"invalid_extraction_strategy",message:"Expected extractionStrategy to be auto, rules-only, or llm-assisted.",ok:!1}}function O(Q,Y){if(Q===void 0&&!Y)return{ok:!0,value:void 0};if(L(Q))return{ok:!0,value:Q.trim()};return{code:"invalid_idempotency_key",message:"Expected a non-empty idempotencyKey string.",ok:!1}}function XQ(Q){if(Q===void 0)return{ok:!0,value:void 0};if(!F(Q))return{code:"invalid_evidence",message:"Expected evidence to be an object when provided.",ok:!1};if(Q.source!=="user_message"&&Q.source!=="manual_review"&&Q.source!=="system")return{code:"invalid_evidence",message:"Expected evidence.source to be user_message, manual_review, or system.",ok:!1};return{ok:!0,value:{source:Q.source,...L(Q.message)?{message:Q.message}:{},...L(Q.excerpt)?{excerpt:Q.excerpt}:{},...L(Q.sourceUri)?{sourceUri:Q.sourceUri}:{},...Array.isArray(Q.sourceMessageIds)?{sourceMessageIds:Q.sourceMessageIds.filter(L)}:{}}}}function YQ(Q,Y){return{error:{code:Q,message:Y},ok:!1}}function G(Q,Y){return{body:Y,statusCode:Q}}function W(Q,Y,X){return G(Q,YQ(Y,X))}async function ZQ(Q){try{let Y=await Q.json();if(!F(Y))return{code:"invalid_json_body",message:"Expected a JSON object request body.",ok:!1};return{ok:!0,value:Y}}catch{return{code:"invalid_json_body",message:"Expected a valid JSON object request body.",ok:!1}}}function $Q(Q){let Y=Q.headers.get("x-goodmemory-user-id")?.trim();if(!Y)return null;let $=Q.headers.get("x-goodmemory-operations")?.split(",").map((Z)=>Z.trim()).filter(Boolean);return{authorizedOperations:$?.includes("*")?"*":$??[],tenantId:Q.headers.get("x-goodmemory-tenant-id")?.trim()||void 0,userId:Y,workspaceId:Q.headers.get("x-goodmemory-workspace-id")?.trim()||void 0}}function LQ(Q){if(!Q.caller)return{authorized:!1,code:"caller_required",message:"The bridge requires a backend-resolved caller identity.",statusCode:401};if(Q.caller.userId!==Q.scope.userId)return{authorized:!1,code:"scope_not_authorized",message:"Caller userId must match scope.userId.",statusCode:403};if(Q.caller.tenantId&&Q.scope.tenantId!==Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.tenantId must be present and match the caller tenantId.",statusCode:403};if(Q.scope.tenantId&&!Q.caller.tenantId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide tenantId to authorize tenant-scoped memory.",statusCode:403};if(Q.caller.workspaceId&&Q.scope.workspaceId!==Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Request scope.workspaceId must be present and match the caller workspaceId.",statusCode:403};if(Q.scope.workspaceId&&!Q.caller.workspaceId)return{authorized:!1,code:"scope_not_authorized",message:"Caller must provide workspaceId to authorize workspace-scoped memory.",statusCode:403};if(Q.sensitive&&Q.caller.authorizedOperations!=="*"){if(!Q.caller.authorizedOperations.includes(Q.operation))return{authorized:!1,code:"operation_not_authorized",message:"Caller is not authorized for this scoped memory operation.",statusCode:403}}return{authorized:!0}}function UQ(Q){return{userId:Q.userId,...Q.tenantId?{tenantId:Q.tenantId}:{},...Q.workspaceId?{workspaceId:Q.workspaceId}:{},...Q.agentId?{agentId:Q.agentId}:{},...Q.sessionId?{sessionId:Q.sessionId}:{}}}function jQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function H(Q,Y){if(!Y||Y.content.trim().length===0)return;Q.push(Y)}function WQ(Q){return Boolean(Q.profile||Q.preferences.length>0||Q.references.length>0||Q.facts.length>0||Q.feedback.length>0||Q.archives.length>0||Q.episodes.length>0||Q.workingMemory||Q.journal)}function d(Q,Y=[]){let X=Q.metadata.routingDecision.strategyExplanation,$=new Set([...X.warnings??[],...Y]);if(Q.metadata.policyApplied?.includes("semantic_candidates_unavailable"))$.add(M);let Z=g({existingMessages:X.warningMessages,warnings:[...$]});return{...X.fallbackReason?{fallbackReason:X.fallbackReason}:{},llmRefinement:X.llmRefinement,requestedStrategy:X.requestedStrategy,resolvedStrategy:X.resolvedStrategy,semanticTieBreaking:X.semanticTieBreaking,...Z.length>0?{warningMessages:Z}:{},...$.size>0?{warnings:[...$]}:{}}}function _Q(Q){if(Q.requestedStrategy!=="auto"||Q.runtimeInfo?.embeddingEnabled!==!0||Q.runtimeInfo.retrievalPreset)return[];return(Q.recall.metadata.routingDecision.strategyExplanation.resolvedStrategy??Q.recall.metadata.routingDecision.strategy)==="rules-only"?[M]:[]}function AQ(Q){return{...d(Q.recall),fallbackReason:"provider_error",providerFallback:{reason:"provider_error",recoveredStrategy:"rules-only"},requestedStrategy:Q.requestedStrategy,resolvedStrategy:"rules-only",semanticTieBreaking:!1}}function FQ(Q){let Y=[];if(Q.profile){let X=[Q.profile.identity.name,Q.profile.identity.role,Q.profile.identity.organization,...Q.profile.activeContext.goals,...Q.profile.activeContext.currentProjects].filter(L);H(Y,{content:X.join("; "),memoryId:`profile:${Q.profile.userId}`,source:"goodmemory",type:"profile"})}for(let X of Q.preferences)H(Y,{category:X.category,confidence:X.confidence,content:`${X.category}: ${jQ(X.value)}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"preference"});for(let X of Q.references)H(Y,{category:X.referenceKind,confidence:X.confidence,content:X.description?`${X.title}: ${X.pointer} - ${X.description}`:`${X.title}: ${X.pointer}`,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"reference"});for(let X of Q.facts)H(Y,{category:X.category,confidence:X.confidence,content:X.content,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"fact"});for(let X of Q.feedback)H(Y,{category:X.kind,confidence:X.confidence,content:X.rule,memoryId:X.id,source:"goodmemory",tags:X.tags,type:"feedback"});for(let X of Q.episodes)H(Y,{confidence:X.confidence,content:X.summary,memoryId:X.id,source:"goodmemory",tags:X.topics,type:"episode"});if(Q.workingMemory)H(Y,{content:[Q.workingMemory.currentGoal,...Q.workingMemory.openLoops,...Q.workingMemory.temporaryDecisions??[]].filter(L).join("; "),memoryId:`working-memory:${Q.workingMemory.userId}:${Q.workingMemory.sessionId}`,source:"goodmemory",type:"working_memory"});if(Q.journal)H(Y,{content:[Q.journal.currentState,Q.journal.taskSpecification,...Q.journal.workflow??[],...Q.journal.errorsAndCorrections??[],...Q.journal.learnings??[],...Q.journal.keyResults??[],...Q.journal.worklog].filter(L).join("; "),memoryId:`session-journal:${Q.journal.userId}:${Q.journal.sessionId}`,source:"goodmemory",type:"session_journal"});return Y}async function BQ(Q,Y,X){if(!L(Y.query))return W(400,"invalid_query","Expected query to be a non-empty string.");let $=t(Y.retrievalProfile);if(!$.ok)return W(400,$.code,$.message);let Z=a(Y.strategy);if(!Z.ok)return W(400,Z.code,Z.message);let U=e(Y.output);if(!U.ok)return W(400,U.code,U.message);let j=typeof Y.maxTokens==="number"&&Number.isFinite(Y.maxTokens)?Math.max(1,Math.floor(Y.maxTokens)):void 0,_=Z.value??"auto",B=y(Q),J=B?.retrievalPreset!==void 0?_:_==="hybrid"?"hybrid":"rules-only",R={scope:X,query:Y.query,...$.value?{retrievalProfile:$.value}:{},strategy:J},V,P=void 0;try{V=await Q.recall(R)}catch(h){if(_==="rules-only"||!m(h))throw h;V=await Q.recall({...R,strategy:"rules-only"}),P=AQ({recall:V,requestedStrategy:_})}let T=await Q.buildContext({recall:V,output:U.value,...j?{maxTokens:j}:{}}),k=FQ(V),x=T.traceId??V.metadata.traceId;return G(200,{context:{content:T.content,estimatedTokens:T.estimatedTokens,omittedSections:T.omittedSections,output:T.output},contextText:T.content,contractVersion:D,hasContext:WQ(V),itemCount:k.length,items:k,ok:!0,operation:"recall-context",routing:P??{...d(V,_Q({recall:V,requestedStrategy:_,runtimeInfo:B})),requestedStrategy:_},...x?{traceId:x}:{}})}async function GQ(Q,Y,X){let $=o(Y.messages);if(!$.ok)return W(400,$.code,$.message);let Z=l(Y.annotations);if(!Z.ok)return W(400,Z.code,Z.message);let U=QQ(Y.extractionStrategy);if(!U.ok)return W(400,U.code,U.message);let j=Y.mode===void 0?"sync":Y.mode;if(j!=="sync"&&j!=="async")return W(400,"invalid_mode","Expected mode to be sync or async.");let _=O(Y.idempotencyKey,j==="async");if(!_.ok)return W(400,_.code,_.message);let B={scope:X,messages:$.value,...Z.value?{annotations:Z.value}:{},...U.value?{extractionStrategy:U.value}:{},...L(Y.locale)?{locale:Y.locale}:{}};if(j==="async")try{let J=await Q.jobs.enqueueRemember({...B,idempotencyKey:_.value,reason:"manual_enqueue"});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_jobs",key:_.value},job:J,mode:j,ok:!0,operation:"remember"})}catch(J){if(F(J)&&J.code==="idempotency_conflict")return W(409,"idempotency_conflict","GoodMemory job idempotency key already exists for a different payload.");throw J}let K=await Q.remember(B);return G(200,{contractVersion:D,idempotency:_.value?{handledBy:"consumer_provenance_only",key:_.value}:{handledBy:"none"},mode:j,ok:!0,operation:"remember",result:K})}async function VQ(Q,Y,X){if(!L(Y.signal))return W(400,"invalid_signal","Expected signal to be a non-empty string.");let $=O(Y.idempotencyKey,!0);if(!$.ok)return W(400,$.code,$.message);let Z=F(Y.source)?Y.source:{},U=await Q.feedback({scope:X,signal:Y.signal,...L(Y.locale)?{locale:Y.locale}:{}});return G(200,{contractVersion:D,idempotency:{handledBy:"consumer_provenance_only",key:$.value},ok:!0,operation:"feedback",provenance:{...L(Z.eventId)?{eventId:Z.eventId}:{},...L(Z.proposalId)?{proposalId:Z.proposalId}:{},...L(Z.reason)?{reason:Z.reason}:{},...L(Z.reviewDecision)?{reviewDecision:Z.reviewDecision}:{},...L(Z.system)?{system:Z.system}:{}},result:U})}async function HQ(Q,Y,X){if(!L(Y.memoryId))return W(400,"invalid_memory_id","Expected memoryId to be a non-empty string.");let $=await Q.forget({memoryId:Y.memoryId,scope:X});return G(200,{contractVersion:D,ok:!0,operation:"forget",result:$})}async function DQ(Q,Y,X){let $=Y.includeRuntime===!0,Z=await Q.exportMemory({includeRuntime:$,scope:X});return G(200,{contractVersion:D,exported:Z,includeRuntime:$,ok:!0,operation:"export"})}async function JQ(Q,Y,X){let $=F(Y.target)?Y.target:null;if(!$||!L($.memoryId))return W(400,"target_memory_id_required","Expected target.memoryId. Query-resolved revision targets are out of scope.");if(!F(Y.revision)||!L(Y.revision.content))return W(400,"invalid_revision","Expected revision.content to be a non-empty string.");if(!L(Y.reason))return W(400,"invalid_reason","Expected reason to be a non-empty string.");let Z=O(Y.idempotencyKey,!0);if(!Z.ok)return W(400,Z.code,Z.message);let U=Z.value;if(!U)return W(400,"invalid_idempotency_key","Expected a non-empty idempotencyKey string.");let j=XQ(Y.evidence);if(!j.ok)return W(400,j.code,j.message);let _=await Q.reviseMemory({evidence:j.value,idempotencyKey:U,reason:Y.reason,revision:{content:Y.revision.content},scope:X,target:{memoryId:$.memoryId}});return G(200,{contractVersion:D,idempotency:{handledBy:"goodmemory_revision",key:U},ok:!0,operation:"revise",result:_})}function TQ(Q){if(Q==="/memory/recall-context")return"recall-context";if(Q==="/memory/remember")return"remember";if(Q==="/memory/feedback")return"feedback";if(Q==="/memory/forget")return"forget";if(Q==="/memory/export")return"export";if(Q==="/memory/revise")return"revise";return null}async function zQ(Q){if(Q.operation==="recall-context")return BQ(Q.memory,Q.body,Q.scope);if(Q.operation==="remember")return GQ(Q.memory,Q.body,Q.scope);if(Q.operation==="feedback")return VQ(Q.memory,Q.body,Q.scope);if(Q.operation==="forget")return HQ(Q.memory,Q.body,Q.scope);if(Q.operation==="export")return DQ(Q.memory,Q.body,Q.scope);return JQ(Q.memory,Q.body,Q.scope)}function PQ(Q){let Y=Q.resolveCaller??$Q,X=Q.authorize??LQ;async function $(Z){if(Z.method==="GET"&&new URL(Z.url).pathname==="/healthz")return G(200,{...Q.healthMetadata??{},contractVersion:D,ok:!0,status:"ok"});if(Z.method==="GET"&&new URL(Z.url).pathname==="/.well-known/goodmemory.json")return G(200,I());if(Z.method!=="POST")return W(405,"method_not_allowed","GoodMemory bridge endpoints require POST.");let U=TQ(new URL(Z.url).pathname);if(!U)return W(404,"not_found","Unknown GoodMemory bridge endpoint.");let j=await ZQ(Z);if(!j.ok)return W(400,j.code,j.message);let _=i(j.value.scope);if(!_.ok)return W(400,_.code,_.message);let B=await X({body:j.value,caller:Y(Z,j.value),operation:U,request:Z,scope:_.value,sensitive:v.has(U)});if(!B.authorized)return W(B.statusCode??403,B.code??"operation_not_authorized",B.message??"Caller is not authorized for this memory operation.");try{return await zQ({body:j.value,memory:Q.memory,operation:U,scope:_.value})}catch{return W(500,"bridge_operation_failed","GoodMemory bridge operation failed.")}}return{async fetch(Z){let U=await $(Z);return new Response(JSON.stringify(U.body),{headers:{"content-type":"application/json"},status:U.statusCode})},handle:$}}function kQ(){return{preset:"default",profiles:[{assistantOutputs:{mode:"confirmed_or_verified_only"},extends:"default",id:"life-coach",when:{agentId:"life-coach"}}]}}function xQ(Q){if(Q.ok!==!0||!Array.isArray(Q.items))throw Error("Expected a successful GoodMemory recall-context response.");let Y=Q.items.filter(F).map((X)=>({content:L(X.content)?X.content:"",memoryId:L(X.memoryId)?X.memoryId:"",type:typeof X.type==="string"?X.type:"fact"})).filter((X)=>X.memoryId.length>0&&X.content.length>0);return{context:typeof Q.contextText==="string"?Q.contextText:"",memories:Y.map((X)=>({id:X.memoryId,kind:X.type,source:"goodmemory-http-bridge",text:X.content})),metadata:{hasContext:Q.hasContext===!0,itemCount:typeof Q.itemCount==="number"?Q.itemCount:Y.length,policyBoundary:"product_owned",source:"goodmemory-http-bridge",...L(Q.traceId)?{traceId:Q.traceId}:{}}}}function hQ(Q){return UQ({agentId:Q.agentId??"life-coach",sessionId:Q.sessionId,tenantId:Q.tenantId,userId:Q.userId,workspaceId:Q.workspaceId})}export{xQ as toOneLifeMemoryContextResponse,hQ as toLifeCoachScope,kQ as createLifeCoachHttpRememberConfig,PQ as createGoodMemoryHttpMemoryBridge,FQ as buildGoodMemoryHttpMemoryItems,D as GOODMEMORY_HTTP_MEMORY_BRIDGE_CONTRACT_VERSION};

@@ -12,3 +12,3 @@ export type { MemoryScope } from "./domain/scope";

export { extractBridgeEntities, iterativeRecall, } from "./recall/iterativeRecall";
export type { IterativeRecallOptions, IterativeRecallOutcome, } from "./recall/iterativeRecall";
export type { FollowUpDecision, IterativeRecallOptions, IterativeRecallOutcome, } from "./recall/iterativeRecall";
export { decomposedRecall, splitQueryIntoSubQueries, } from "./recall/queryDecomposition";

@@ -15,0 +15,0 @@ export type { DecomposedRecallOutcome, QueryDecompositionOptions, } from "./recall/queryDecomposition";

@@ -43,2 +43,4 @@ import type { MemoryCandidate } from "../domain/memoryCandidate";

role: boolean;
temporalInterval?: boolean;
temporalOperands?: readonly string[];
userGroundedEventOrder: boolean;

@@ -45,0 +47,0 @@ }

@@ -1,2 +0,3 @@

import type { LanguageConfig, LanguageService } from "./contracts";
import type { LanguageConfig, LanguageService, ResolvedLanguageContext } from "./contracts";
export declare function isStrongLegacyProjectionLocaleSignal(text: string, context: ResolvedLanguageContext): boolean;
export declare function createLanguageService(config?: LanguageConfig): LanguageService;

@@ -5,3 +5,3 @@ import type { EmbeddingAdapter } from "../embedding/contracts";

import type { MaintenanceRepositoryPort, MaintenanceVectorPort } from "../storage/ports";
export type MaintenanceJobName = "projectionMigration" | "projectionRepair" | "dedupe" | "contradiction" | "qualityRepair" | "consolidation" | "embeddingRepair" | "ttlExpiry";
export type MaintenanceJobName = "projectionMigration" | "projectionRepair" | "dedupe" | "contradiction" | "qualityRepair" | "consolidation" | "embeddingRepair" | "retrievalCues" | "observationSynthesis" | "ttlExpiry";
export interface MaintenanceRunnerConfig {

@@ -22,2 +22,21 @@ embedding?: EmbeddingAdapter;

};
claimSlotSweep?: {
sweepClaimSlots(scope: MemoryScope): Promise<number>;
};
observationSynthesis?: {
synthesize(input: {
contents: readonly string[];
subject: string;
}): Promise<string | null>;
maxSubjectsPerRun?: number;
minFactsPerSubject?: number;
};
retrievalCues?: {
generate(input: {
category: string;
content: string;
subject?: string;
}): Promise<string[]>;
maxFactsPerRun?: number;
};
vectorIndex?: MaintenanceVectorPort | null;

@@ -24,0 +43,0 @@ now?: () => string;

@@ -32,2 +32,3 @@ import type { FetchFunction } from "@ai-sdk/provider-utils";

}
export type EmbeddingNormalization = "l2-v1";
type FetchInput = Parameters<FetchFunction>[0];

@@ -46,2 +47,7 @@ type FetchInit = Parameters<FetchFunction>[1];

export declare function createOpenAICompatibleFetch(baseFetch?: FetchLike): FetchFunction;
export declare function createOpenRouterEmbeddingFetch(input: {
allowFallbacks: boolean;
baseFetch?: FetchLike;
providerOrder: readonly string[];
}): FetchFunction;
export declare function withAISDKRetries<T>(operation: () => Promise<T>, options?: number | AISDKRetryOptions): Promise<T>;

@@ -101,3 +107,3 @@ export declare function stripThinkingBlocks(value: string): string;

export declare function resolveAISDKModel(config: AISDKModelConfig): LanguageModel;
export declare function resolveAISDKEmbeddingModel(config: AISDKModelConfig): EmbeddingModel;
export declare function resolveAISDKEmbeddingModel(config: AISDKModelConfig, fetch?: FetchLike): EmbeddingModel;
export declare function createAISDKEmbeddingAdapter(input: {

@@ -107,5 +113,8 @@ batchMaxConcurrency?: number;

batchMaxUtf8Bytes?: number;
expectedDimensions?: number;
fetch?: FetchLike;
model: AISDKModelConfig;
normalization?: EmbeddingNormalization;
dependencies?: EmbeddingAdapterDependencies;
}): EmbeddingAdapter;
export {};

@@ -6,3 +6,3 @@ import type { RecallRouterAssistant } from "../recall/assistant";

import type { EmbeddingAdapter } from "../embedding/contracts";
import type { AISDKModelConfig, AISDKRetryOptions, OpenAICompatibleObjectResponseFormat, OpenAICompatibleReasoningEffort } from "./ai-sdk-runtime";
import type { AISDKModelConfig, AISDKRetryOptions, EmbeddingNormalization, FetchLike, OpenAICompatibleObjectResponseFormat, OpenAICompatibleReasoningEffort } from "./ai-sdk-runtime";
import type { MemoryExtractionOutputProtocol } from "./memory-extractor";

@@ -32,3 +32,6 @@ import type { RecallPlanAssistantDependencies } from "./recall-plan-assistant";

dependencies?: ProviderRequestDependencies;
expectedDimensions?: number;
fetch?: FetchLike;
model: AISDKModelConfig;
normalization?: EmbeddingNormalization;
}): EmbeddingAdapter;

@@ -119,3 +122,6 @@ }

createEmbeddingAdapter?: ProviderEmbeddingAdapterFactory;
expectedDimensions?: number;
fetch?: FetchLike;
modelUsageSink?: ModelUsageSink;
normalization?: EmbeddingNormalization;
requestTimeoutMs?: number;

@@ -122,0 +128,0 @@ retryLimit?: number;

@@ -205,2 +205,3 @@ import { generateObject } from "ai";

export declare function buildConversationalMemoryExtractionPrompt(input: MemoryExtractionInput, options?: ConversationalExtractionOptions): string;
export declare const COMPACT_CONVERSATIONAL_MEMORY_EXTRACTION_PROMPT_CONTRACT: string;
export declare function buildCompactConversationalMemoryExtractionPrompt(input: MemoryExtractionInput, options?: ConversationalExtractionOptions): string;

@@ -207,0 +208,0 @@ export declare function createLLMMemoryExtractor(input: {

@@ -34,2 +34,7 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

}
export interface EpisodeSpanTurn {
content: string;
observedAt?: string;
role: string;
}
export interface MemoryPacketInput {

@@ -42,2 +47,3 @@ profile: UserProfile | null;

episodes: EpisodeMemory[];
episodeSpans?: Readonly<Record<string, readonly EpisodeSpanTurn[]>>;
archives: SessionArchive[];

@@ -44,0 +50,0 @@ evidence: EvidenceRecord[];

@@ -115,2 +115,3 @@ import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";

maxTotalFacts?: number;
entityPageRank?: boolean;
minRelativeStrength?: number;

@@ -117,0 +118,0 @@ rrfK?: number;

@@ -41,2 +41,3 @@ import type { LanguageEntityCandidateInput } from "../language";

matchesEntityAlias: (query: string, alias: string) => boolean;
entityPageRank?: boolean;
minRelativeStrength?: number;

@@ -43,0 +44,0 @@ plan?: RecallPlan;

@@ -1,2 +0,2 @@

import type { FactMemory, UserProfile } from "../domain/records";
import { type FactMemory, type UserProfile } from "../domain/records";
import type { LanguageQueryAnalysis, LanguageService } from "../language";

@@ -3,0 +3,0 @@ import type { RecallCandidateTrace } from "./engine";

@@ -13,2 +13,9 @@ export interface BridgeTextAnalysis {

}): string[];
export type FollowUpDecision = {
missingSlots: readonly [];
sufficient: true;
} | {
missingSlots: readonly [string];
sufficient: false;
};
export interface IterativeRecallOptions {

@@ -18,10 +25,10 @@ analyzeBridgeText?: (text: string) => BridgeTextAnalysis;

maxHops?: number;
expandQuery?: (input: {
decideNextHop?: (input: {
evidence: readonly {
content: string;
}[];
originalQuery: string;
query: string;
facts: readonly {
content: string;
}[];
hop: number;
}) => string | null | Promise<string | null>;
}) => FollowUpDecision | null | Promise<FollowUpDecision | null>;
}

@@ -36,3 +43,3 @@ export interface IterativeRecallOutcome<TResult> {

}
export type IterativeRecallStopReason = "expander_stopped" | "max_hops_reached" | "no_bridge_entities" | "no_new_evidence" | "unchanged_query";
export type IterativeRecallStopReason = "decision_unavailable" | "evidence_sufficient" | "max_hops_reached" | "missing_slots_unresolved" | "no_bridge_entities" | "no_new_evidence" | "unchanged_query";
export interface IterativeRecallStep {

@@ -43,2 +50,3 @@ bridgeEntities: string[];

query: string;
sufficiencyDecision?: FollowUpDecision;
}

@@ -48,2 +56,3 @@ export declare function iterativeRecall<TResult extends {

content: string;
id: string;
}[];

@@ -50,0 +59,0 @@ }>(input: {

@@ -30,2 +30,3 @@ import type { MemoryScope } from "../../domain/scope";

}): Promise<void>;
sweepSlotSupersession(scope: MemoryScope): Promise<number>;
}

@@ -32,0 +33,0 @@ export interface ClaimProjectionCanonicalSource {

@@ -13,3 +13,3 @@ import type { MemoryScope } from "../../domain/scope";

export declare const PROJECTION_SEARCH_SCHEMA_VERSION = "gm-search-v2";
export declare const RECALL_PROJECTION_PIPELINE_VERSION = "gm-projection-v3";
export declare const RECALL_PROJECTION_PIPELINE_VERSION = "gm-projection-v4";
export declare const LEGACY_RECALL_PROJECTION_COLLECTIONS: readonly ["recall_documents_v2", "entities_v1", "claim_projections_v1", "claim_projection_status_v1", "scope_catalog_v1"];

@@ -145,2 +145,3 @@ export declare const RECALL_PROJECTION_SOURCE_COLLECTIONS: readonly ["profiles", "preferences", "references", "facts", "episodes", "feedback", "session_archives"];

claimIds: string[];
retiredRevisionIds?: string[];
extractorVersion: string;

@@ -179,3 +180,4 @@ sourceUpdatedAt?: string;

queryClaimHistory(scope: MemoryScope): Promise<ClaimProjection[]>;
sweepClaimSlots(scope: MemoryScope): Promise<number>;
}
export declare function isRecallProjectionSourceCollection(collection: string): collection is RecallProjectionSourceCollection;

@@ -15,2 +15,3 @@ import type { MemoryScope } from "../../domain/scope";

queryClaimHistory(scope: MemoryScope): Promise<ClaimProjection[]>;
sweepClaimSlots(scope: MemoryScope): Promise<number>;
queryDocuments(scope: MemoryScope): Promise<RecallIndexDocument[]>;

@@ -17,0 +18,0 @@ searchDocuments(scope: MemoryScope, query: string, limit: number, locale?: string): Promise<RecallIndexDocument[]>;

@@ -1,5 +0,7 @@

import { type LanguageService } from "../language";
import type { LanguageQueryAnalysis, LanguageService, ResolvedLanguageContext } from "../language";
export interface QueryDecompositionOptions {
analysis?: LanguageQueryAnalysis;
/** Locale-aware tokenizer/sentence splitter used by the recall planner. */
language?: Pick<LanguageService, "decomposeQuery" | "normalizeForEquality" | "resolveFromText" | "tokenize">;
language?: Pick<LanguageService, "analyzeQuery" | "decomposeQuery" | "normalizeForEquality" | "resolveFromText" | "tokenize">;
languageContext?: ResolvedLanguageContext;
locale?: string;

@@ -14,4 +16,6 @@ /** Maximum number of sub-queries to keep (excludes the original query). Default 4. */

* coordinating-conjunction boundaries. Returns `[]` when the query has no
* genuine multi-part structure (so the caller falls back to a single recall),
* and only ever returns two or more distinct fragments. Pure and deterministic.
* useful focused structure (so the caller falls back to a single recall).
* Ordinary clauses require at least two fragments; one explicit temporal
* operand is already a useful supplement to the original query. Pure and
* deterministic.
*/

@@ -18,0 +22,0 @@ export declare function splitQueryIntoSubQueries(query: string, options?: QueryDecompositionOptions): string[];

@@ -5,2 +5,5 @@ import type { EpisodeMemory } from "../domain/records";

import type { RememberSourceLanguageAnalyses } from "./languageAnalysis";
export declare function buildEpisodes(input: MemoryExtractionInput, candidates: MemoryCandidate[], createId: () => string, timestamp: string, language: LanguageService, locale: string, sourceAnalyses?: RememberSourceLanguageAnalyses, options?: {
segmentTimeGapMs?: number;
}): EpisodeMemory[];
export declare function maybeBuildEpisode(input: MemoryExtractionInput, candidates: MemoryCandidate[], id: string, timestamp: string, language: LanguageService, locale: string, sourceAnalyses?: RememberSourceLanguageAnalyses): EpisodeMemory | null;

@@ -49,2 +49,3 @@ import type { MemoryScope } from "../domain/scope";

fallbackPreset?: RememberPresetId;
episodeSegmentTimeGapMs?: number;
}

@@ -51,0 +52,0 @@ export interface ResolvedRememberProfile {

@@ -1,1 +0,1 @@

import{oa as t}from"../chunk-njm7jqas.js";import"../chunk-963r53yf.js";import"../chunk-8d816xbx.js";import"../chunk-0h5pry7v.js";import"../chunk-jr0h5wkn.js";import"../chunk-c28647f0.js";import"../chunk-eqpe4gcb.js";export{t as createGoodMemoryRuntimeKit};
import{oa as t}from"../chunk-4rqvqhtc.js";import"../chunk-m9yws3j1.js";import"../chunk-ftxc0stx.js";import"../chunk-g7hv64gy.js";import"../chunk-b7j2aytn.js";import"../chunk-36sxnybm.js";import"../chunk-14dkxqxk.js";export{t as createGoodMemoryRuntimeKit};
import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
import type { EvidenceRecord } from "../evidence/contracts";
import type { EvidenceRecord, SourceMessageRecord } from "../evidence/contracts";
import type { ExperienceRecord, LearningProposal, PromotionRecord, SessionArchive } from "../domain/evolutionRecords";

@@ -83,4 +83,12 @@ import type { VectorRecord } from "./contracts";

}
export interface RecallRepositoryPort extends ProfileRepositoryPort, PreferenceRepositoryPort, ReferenceRepositoryPort, FactRepositoryPort, FeedbackRepositoryPort, ArchiveRepositoryPort, EvidenceRepositoryPort, EpisodeRepositoryPort {
interface SourceMessageRepositoryPort {
sourceMessages?: {
getByIds(input: {
ids: readonly string[];
scope: MemoryScope;
}): Promise<SourceMessageRecord[]>;
};
}
export interface RecallRepositoryPort extends ProfileRepositoryPort, PreferenceRepositoryPort, ReferenceRepositoryPort, FactRepositoryPort, FeedbackRepositoryPort, ArchiveRepositoryPort, EvidenceRepositoryPort, SourceMessageRepositoryPort, EpisodeRepositoryPort {
}
export interface RememberRepositoryPort extends ProfileRepositoryPort, PreferenceRepositoryPort, ReferenceRepositoryPort, FactRepositoryPort, FeedbackRepositoryPort, EpisodeRepositoryPort {

@@ -87,0 +95,0 @@ }

import type { EpisodeMemory, FactMemory, FeedbackMemory, PreferenceMemory, ReferenceMemory, SessionBuffer, SessionJournal, UserProfile, WorkingMemorySnapshot } from "../domain/records";
import type { MemoryScope } from "../domain/scope";
import type { EvidenceRecord } from "../evidence/contracts";
import type { EvidenceRecord, SourceMessageRecord } from "../evidence/contracts";
import type { ExperienceRecord, LearningProposal, PromotionRecord, SessionArchive } from "../domain/evolutionRecords";

@@ -78,2 +78,8 @@ import type { DocumentStore, SessionStore, VectorRecord, VectorSearchInput, VectorStore } from "./contracts";

};
sourceMessages: {
getByIds(input: {
ids: readonly string[];
scope: MemoryScope;
}): Promise<SourceMessageRecord[]>;
};
sessionBuffers: {

@@ -80,0 +86,0 @@ save(scope: MemoryScope, buffer: SessionBuffer): Promise<void>;

@@ -12,8 +12,8 @@ # GoodMemory 15-Minute App Integration

The registry commands below apply after `goodmemory@0.7.0` is published. Before
publication, install the verified local `goodmemory-0.7.0.tgz` produced by the
The registry commands below apply after `goodmemory@0.7.1` is published. Before
publication, install the verified local `goodmemory-0.7.1.tgz` produced by the
release workflow.
```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
```

@@ -24,3 +24,3 @@

```bash
bun add goodmemory@0.7.0
bun add goodmemory@0.7.1
```

@@ -27,0 +27,0 @@

# GoodMemory Claude Code Setup Guide
This is the canonical global CLI `0.7.0` Claude Code installed-host setup path.
This is the canonical global CLI `0.7.1` Claude Code installed-host setup path.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory -V

@@ -23,3 +23,3 @@ ```

```bash
npm install -g ./goodmemory-0.7.0.tgz
npm install -g ./goodmemory-0.7.1.tgz
goodmemory -V

@@ -59,7 +59,7 @@ ```

```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
npx goodmemory claude bootstrap --user-id <user-id> --workspace-id <workspace-id>
```
Bun services can install the same package with `bun add goodmemory@0.7.0`.
Bun services can install the same package with `bun add goodmemory@0.7.1`.

@@ -66,0 +66,0 @@ This creates repo-local scaffolding only:

# GoodMemory Codex Handoff Setup Guide
This is the canonical global CLI `0.7.0` Codex installed-host setup path.
This is the canonical global CLI `0.7.1` Codex installed-host setup path.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory -V

@@ -23,3 +23,3 @@ ```

```bash
npm install -g ./goodmemory-0.7.0.tgz
npm install -g ./goodmemory-0.7.1.tgz
goodmemory -V

@@ -59,7 +59,7 @@ ```

```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
npx goodmemory codex bootstrap --user-id <user-id> --workspace-id <workspace-id>
```
Bun services can install the same package with `bun add goodmemory@0.7.0`.
Bun services can install the same package with `bun add goodmemory@0.7.1`.

@@ -66,0 +66,0 @@ This creates repo-local scaffolding only:

@@ -8,3 +8,3 @@ # GoodMemory Cursor Setup Guide

[Standalone MCP Setup Guide](./GoodMemory-Standalone-MCP-Setup-Guide.md)
(short version: `npm install -g goodmemory`, and Bun 1.3+ on PATH — the
(short version: `npm install -g goodmemory`, and Bun 1.3.14+ on PATH — the
`goodmemory-mcp` bin launches Bun).

@@ -11,0 +11,0 @@

@@ -8,3 +8,3 @@ # GoodMemory Gemini CLI Setup Guide

[Standalone MCP Setup Guide](./GoodMemory-Standalone-MCP-Setup-Guide.md)
(short version: `npm install -g goodmemory`, and Bun 1.3+ on PATH — the
(short version: `npm install -g goodmemory`, and Bun 1.3.14+ on PATH — the
`goodmemory-mcp` bin launches Bun).

@@ -11,0 +11,0 @@

@@ -8,3 +8,3 @@ # GoodMemory OpenCode Setup Guide

[Standalone MCP Setup Guide](./GoodMemory-Standalone-MCP-Setup-Guide.md)
(short version: `npm install -g goodmemory`, and Bun 1.3+ on PATH — the
(short version: `npm install -g goodmemory`, and Bun 1.3.14+ on PATH — the
`goodmemory-mcp` bin launches Bun).

@@ -11,0 +11,0 @@

@@ -41,3 +41,3 @@ # GoodMemory Python HTTP Integration Bridge

```bash
bun add goodmemory@0.7.0
bun add goodmemory@0.7.1

@@ -44,0 +44,0 @@ GOODMEMORY_HTTP_BRIDGE_TOKEN="replace-with-service-token" \

# GoodMemory Reference Integration Guide
This is the canonical packaged `0.7.0` reference path for chatbox/copilot-style integration.
This is the canonical packaged `0.7.1` reference path for chatbox/copilot-style integration.

@@ -10,3 +10,3 @@ ## Install

```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
```

@@ -17,3 +17,3 @@

```bash
bun add goodmemory@0.7.0
bun add goodmemory@0.7.1
```

@@ -24,3 +24,3 @@

```bash
npm install ./goodmemory-0.7.0.tgz
npm install ./goodmemory-0.7.1.tgz
```

@@ -27,0 +27,0 @@

@@ -17,11 +17,11 @@ # GoodMemory Standalone MCP Setup Guide

- Node.js 20+ for the npm install.
- **Bun 1.3+ on PATH.** The `goodmemory-mcp` bin is a launcher that spawns
- **Bun 1.3.14+ on PATH.** The `goodmemory-mcp` bin is a launcher that spawns
`bun`; without Bun it exits with an install hint.
The registry command below applies after `goodmemory@0.7.0` is published.
Before publication, install the verified local `goodmemory-0.7.0.tgz` produced
The registry command below applies after `goodmemory@0.7.1` is published.
Before publication, install the verified local `goodmemory-0.7.1.tgz` produced
by the release workflow.
```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
```

@@ -39,2 +39,18 @@

## MCP protocol compatibility
The stdio server uses the MCP TypeScript SDK v2 and serves both protocol eras:
- `2026-07-28`: modern stateless semantics with `server/discover` and
per-request metadata; there is no MCP initialization handshake or
protocol-level session.
- `2025-11-25`: legacy fallback for clients that still open with
`initialize`.
`standalone` and `stateless` describe different boundaries. Standalone means
GoodMemory does not read installed-host config. Stateless means the modern MCP
protocol has no protocol session. The tools' optional `sessionId` remains an
application-level memory scope and is not an MCP session id. The transport
remains stdio; this command does not expose an HTTP MCP endpoint.
## Flags and environment fallbacks

@@ -41,0 +57,0 @@

@@ -13,4 +13,4 @@ # GoodMemory

Release source: this is the immutable GoodMemory 0.7.0 stable release source.
Registry commands require goodmemory@0.7.0 to be published. The release workflow
Release source: this is the immutable GoodMemory 0.7.1 stable release source.
Registry commands require goodmemory@0.7.1 to be published. The release workflow
verifies npm latest and artifact integrity before creating the GitHub Release.

@@ -29,3 +29,3 @@

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup # detects Codex + Claude Code, installs managed wiring

@@ -88,4 +88,4 @@ goodmemory status

Versioned `v0.6.0` evidence retained for the `v0.7.0` line; these are not
current `v0.7.0` production claims until rerun:
Versioned `v0.6.0` evidence is retained unchanged; these are not current
`v0.7.1` production claims until rerun against the current package:

@@ -92,0 +92,0 @@ - [LoCoMo full 10](https://github.com/hjqcan/GoodMemory/blob/main/benchmark-claims/locomo.json): official 0.8708, strict 0.6299, open-domain 0.6146 (59/96); provider-backed recommended profile; dataset CC BY-NC 4.0.

{
"name": "goodmemory",
"version": "0.7.0",
"version": "0.7.1",
"goodmemoryRelease": {

@@ -35,3 +35,3 @@ "installCommandsApplyAfterPublish": true,

"engines": {
"bun": ">=1.3.0",
"bun": ">=1.3.14",
"node": ">=20.0.0"

@@ -118,3 +118,3 @@ },

"test:coverage": "bun run scripts/run-coverage.ts && bun run scripts/check-coverage.ts",
"test:ci": "bun run typecheck && bun run test:coverage && bun test tests/integration/python-http-bridge.test.ts tests/cli tests/release",
"test:ci": "bun run typecheck && bun run test:coverage && bun run scripts/run-ci-post-coverage-tests.ts",
"test:watch": "bun test --watch",

@@ -263,2 +263,16 @@ "typecheck": "bunx tsc --noEmit",

"gate:codex-coding-effect:c5": "bun run scripts/run-codex-coding-effect-c5-gate.ts",
"prepare:codex-coding-effect:c6-candidate": "bun run scripts/prepare-codex-coding-effect-c6-candidate.ts",
"prepare:codex-coding-effect:c6-source-v3-simple-review": "bun run scripts/prepare-codex-coding-effect-c6-source-v3-simple-review.ts",
"record:codex-coding-effect:c6-source-v3-simple-review": "bun run scripts/record-codex-coding-effect-c6-source-v3-simple-review-provenance.ts",
"capture:codex-coding-effect:c6-source-v3-simple-prior-identity": "bun run scripts/capture-codex-coding-effect-c6-source-v3-simple-prior-repository-identity.ts",
"record:codex-coding-effect:c6-source-v3-simple-prior-identity-replay": "bun run scripts/record-codex-coding-effect-c6-source-v3-simple-prior-identity-replay.ts",
"prepare:codex-coding-effect:c6-source-v3-simple-prior-identity-replay-review": "bun run scripts/prepare-codex-coding-effect-c6-source-v3-simple-prior-identity-replay-review.ts",
"record:codex-coding-effect:c6-source-v3-simple-prior-identity-replay-review": "bun run scripts/record-codex-coding-effect-c6-source-v3-simple-prior-identity-replay-review-provenance.ts",
"materialize:codex-coding-effect:c6-source-v3-simple-prior-identity-portable-evidence": "bun run scripts/materialize-codex-coding-effect-c6-source-v3-simple-prior-identity-portable-evidence.ts",
"promote:codex-coding-effect:c6-source-v3-simple": "bun run scripts/promote-codex-coding-effect-c6-source-v3-simple.ts",
"snapshot:codex-coding-effect:c6-multi-swe-jq-chain-ledger": "bun run scripts/snapshot-codex-coding-effect-c6-multi-swe-jq-chain-ledger.ts",
"snapshot:codex-coding-effect:c6-multi-swe-jq-source-pool": "bun run scripts/snapshot-codex-coding-effect-c6-multi-swe-jq-source-pool.ts",
"snapshot:codex-coding-effect:c6-multi-swe-relationship-discovery": "bun run scripts/snapshot-codex-coding-effect-c6-multi-swe-relationship-discovery.ts",
"snapshot:codex-coding-effect:c6-real-history-yield": "bun run scripts/snapshot-codex-coding-effect-c6-real-history-yield.ts",
"snapshot:codex-coding-effect:c6-source-pool": "bun run scripts/snapshot-codex-coding-effect-c6-source-pool.ts",
"project:codex-coding-effect:c2-evidence": "bun run scripts/project-codex-coding-effect-c2-evidence.ts",

@@ -270,6 +284,9 @@ "eval:phase-72-beam-generalization-live": "bun run scripts/run-phase-72-beam-generalization-live.ts",

"eval:phase-72-longmemeval-answer-revision": "bun run scripts/run-phase-72-longmemeval-answer-revision.ts",
"eval:phase-72-longmemeval-temporal-operands-development": "bun run scripts/run-phase-72-longmemeval-temporal-operands-development.ts",
"eval:phase-72-longmemeval-verifier-chain": "bun run scripts/run-phase-72-longmemeval-verifier-chain.ts",
"eval:phase-72-memgym": "bun run scripts/run-phase-72-memgym.ts",
"eval:phase-72-minteval-smoke": "bun run scripts/run-phase-72-minteval-smoke.ts",
"eval:phase-72-temporal-operands-protection": "bun run scripts/run-phase-72-temporal-operands-protection.ts",
"eval:phase-74-generalization": "bun run scripts/run-phase-74-generalization.ts",
"eval:phase-74-product-comparison": "bun run scripts/run-phase-74-product-comparison.ts",
"eval:phase-74-beam-safety": "bun run scripts/run-phase-74-beam-safety-protection.ts",

@@ -279,2 +296,4 @@ "eval:phase-74-protection-evidence": "bun run scripts/build-phase-74-protection-evidence.ts",

"prepare:phase-74-datasets": "bun run scripts/prepare-phase-74-datasets.ts",
"prepare:phase-74-confirmatory-plan": "bun run scripts/prepare-phase-74-confirmatory-plan.ts",
"prepare:phase-74-protection-plan": "bun run scripts/prepare-phase-74-protection-plan.ts",
"gate:phase-74-storage-scale": "bun run scripts/run-phase-74-storage-scale-gate.ts",

@@ -353,4 +372,6 @@ "merge:phase-72-implicitmembench-retry": "bun run scripts/merge-phase-72-implicitmembench-retry.ts",

"devDependencies": {
"@types/bun": "^1.3.0",
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"@types/node": "^20.0.0",
"hyparquet": "1.26.2",
"typescript": "^5.8.3"

@@ -363,3 +384,3 @@ },

"@ai-sdk/provider-utils": "^4.0.21",
"@modelcontextprotocol/sdk": "^1.29.0",
"@modelcontextprotocol/server": "^2.0.0",
"ai": "^6.0.143",

@@ -366,0 +387,0 @@ "sqlite-vss": "0.1.2",

+38
-44

@@ -7,4 +7,4 @@ # GoodMemory

> **Release source:** this is the immutable `0.7.0` stable release source.
> Registry commands require `goodmemory@0.7.0` to be published. The release
> **Release source:** this is the immutable `0.7.1` stable release source.
> Registry commands require `goodmemory@0.7.1` to be published. The release
> workflow verifies npm `latest` and artifact integrity before creating the

@@ -66,3 +66,3 @@ > GitHub Release.

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup --host codex

@@ -87,3 +87,3 @@ goodmemory status codex --workspace-root .

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -114,9 +114,12 @@ ```

the disclosed provider-backed or evidence-pack profiles. Because `v0.7.0`
changes LanguagePack and recall semantics, they remain historical 0.6 evidence,
not 0.7 performance claims or claims about the zero-provider default; no row is
promoted as a current `v0.7.0` claim until a fresh run passes the same gate.
LongMemEval's newer label-free verifier result and ImplicitMemBench's retry-merged
result remain internal evidence because their current paths are eval-only or do
not replace a monolithic fresh run. HaluMem, MemGym, and MINTEval remain release
evidence rather than public benchmark claims.
changed LanguagePack and recall semantics, they remain historical 0.6 evidence,
not current-package performance claims or claims about the zero-provider
default; no row is promoted as a current `v0.7.1` claim until a fresh run passes
the same gate.
LongMemEval is withdrawn pending a clean rerun: the historical rules-only path
used answer annotations, and the later label-free path exposed raw
`answer_*` session IDs to retrieval and the reader. ImplicitMemBench's
retry-merged result remains internal evidence because it does not replace a
monolithic fresh run. HaluMem, MemGym, and MINTEval remain release evidence
rather than public benchmark claims.

@@ -133,3 +136,3 @@ <!-- current-claims-table:start -->

referenced raw artifacts, which are not all stored in the Git tree. They are
not current-production claims for `v0.7.0`.
not current-production claims for `v0.7.1`.

@@ -142,3 +145,2 @@ <!-- historical-evidence-table:start -->

| MemoryAgentBench v0.6.0 (CR, TTL) | deterministic upstream match-mode scoring, judge-free | **CR 0.959, TTL 0.933** | no-memory 0.000 for both | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
| LongMemEval full 500 | strict: judge-free deterministic subset · diagnostic: official-prompt-compatible LongMemEval judge | strict **0.720** (360/500) · prompt-compatible **0.888** (444/500), `goodmemory-rules-only` | no-memory 0.068; current Mem0 harness: 94.4 Top200 / 94.8 Top50 (different stack and budget) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| ImplicitMemBench Full-300 | stored-answer cross-version judge rescore | **0.691** (207.35/300), gpt-5.4 judge over gpt-5.5 answers, sourceAnswersUnchanged | upstream-chat baseline **0.400** (120/300); reference line 0.66 | [implicitmembench.json](./benchmark-claims/implicitmembench.json) |

@@ -152,20 +154,10 @@ <!-- historical-evidence-table:end -->

comparability is claimed only when the pinned evaluator model and remaining
benchmark configuration also match. LongMemEval's gpt-5.4/gpt-5.5 diagnostics
are outside the pinned evaluator model zoo and are therefore
prompt-compatible, not directly comparable to published official scores.
Every per-protocol detail is recorded in the linked declarations.
benchmark configuration also match. Every per-protocol detail is recorded in
the linked declarations.
The historical LongMemEval strict result is judge-free, replacing an earlier
internal with-judge number (0.908) that is superseded and not claimable. A case counts as correct
only when a deterministic method scores it (abstention / exact / contains /
expected_alternative / numeric_count); the eval pipeline's same-model semantic
judge (gpt-5.5 judging gpt-5.5) is excluded by construction — with it, the
diagnostic overall accuracy is 0.896, reported for transparency but not
claimed. The recorded 0.720 (360/500, `executionFailures: 0`, v0.3.5) uses the
embedding-free `goodmemory-rules-only` profile; abstention contributes only 28
of the 360 correct answers, while the no-memory baseline's 0.068 is mostly bare
abstention (30 of its 34 correct), so the +65.2-point lift is the memory
system's contribution. Judge-free refers to scoring — answers are still
generated by gpt-5.5. Full provenance is in the
[claim declaration](./benchmark-claims/longmemeval.json).
The LongMemEval declaration is now `paused_boundary`, not historical evidence.
Its old numeric artifacts remain only to preserve the audit trail. They must
not be quoted as GoodMemory results until an opaque-session-id, label-free full
rerun replaces them; see the
[withdrawal declaration](./benchmark-claims/longmemeval.json).
The historical v0.6.0 MemoryAgentBench evidence is deliberately scoped. It uses

@@ -217,7 +209,9 @@ `gpt-5.6-terra` answers and deterministic, judge-free upstream match-mode

LongMemEval's Phase 72 eval-only verifier chain reaches 0.720 judge-free and
0.924 under an independent gpt-5.5 official-prompt-compatible judge. That model
is outside the pinned LongMemEval evaluator model zoo, so the result is not
directly comparable to published official scores; it is also not a production
runtime profile. ImplicitMemBench's explicit retry-merged check reaches
LongMemEval's first current-recall assembly development slice is superseded:
although its reader context hid raw session IDs, the memory-builder boundary
still received gold-bearing session IDs and turn markers. A stricter v2
protocol now removes answers, question type, answer markers, and raw session
identities before memory construction. Its development slice must be rerun on
a clean commit before the still-sealed holdout can be opened; no LongMemEval
claim is restored. ImplicitMemBench's explicit retry-merged check reaches
0.6923666667 with zero failures, but it is not a replacement monolithic fresh

@@ -249,3 +243,3 @@ Full-300 run. Both therefore remain outside the current-claims table. The

- **You are, or run inside, Claude Code or Codex** →
`npm install -g goodmemory@0.7.0 && goodmemory setup`. Unsure what is already
`npm install -g goodmemory@0.7.1 && goodmemory setup`. Unsure what is already
wired? Run `goodmemory adopt` (add `--json` for a machine-readable plan): it

@@ -358,3 +352,3 @@ inspects `.claude/`, `.codex/`, and existing MCP config, then prints the exact

After GoodMemory `0.7.0` is published, it has two normal registry install paths.
After GoodMemory `0.7.1` is published, it has two normal registry install paths.
Before publication, use the tarball verification path below.

@@ -366,3 +360,3 @@

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -375,7 +369,7 @@ goodmemory status

```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
```
If you want to type `goodmemory` directly, install the global CLI.
A project-local `npm install goodmemory@0.7.0` does not put `goodmemory` on your shell `PATH`.
A project-local `npm install goodmemory@0.7.1` does not put `goodmemory` on your shell `PATH`.
Use `npx goodmemory`, `npm exec -- goodmemory`, or `./node_modules/.bin/goodmemory`

@@ -391,3 +385,3 @@ from that project instead.

```bash
bun add goodmemory@0.7.0
bun add goodmemory@0.7.1
```

@@ -398,3 +392,3 @@

```bash
npm install ./goodmemory-0.7.0.tgz
npm install ./goodmemory-0.7.1.tgz
```

@@ -411,3 +405,3 @@

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -1245,3 +1239,3 @@ goodmemory status

The `goodmemory` command on your shell `PATH` is the global CLI installed with
`npm install -g goodmemory@0.7.0`. In a local dependency install, invoke the
`npm install -g goodmemory@0.7.1`. In a local dependency install, invoke the
package bin as `npx goodmemory`, `npm exec -- goodmemory`, or

@@ -1248,0 +1242,0 @@ `./node_modules/.bin/goodmemory`. The repo-local `bun run goodmemory` script is

@@ -7,4 +7,4 @@ # GoodMemory

> **发布源码:**这是不可变的 `0.7.0` 稳定发布源码。Registry 命令要求
> `goodmemory@0.7.0` 已发布;release workflow 会先校验 npm `latest`
> **发布源码:**这是不可变的 `0.7.1` 稳定发布源码。Registry 命令要求
> `goodmemory@0.7.1` 已发布;release workflow 会先校验 npm `latest`
> 与制品完整性,再创建 GitHub Release。

@@ -29,3 +29,3 @@

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -49,7 +49,9 @@ ```

下面三行保留明确披露 profile 的 0.6 public-opt-in 结果。由于 `v0.7.0` 改变了
LanguagePack 与召回语义,它们对 0.7 包而言只是历史证据,不是 0.7 性能声明,也不代表
零 provider 默认路径;在新版本完成同等 fresh run 之前,当前声明表保持为空。
LongMemEval 的新 verifier 结果与 ImplicitMemBench 的 retry-merged 结果仍属于内部
证据,因为前者是 eval-only 路径,后者不能替代一次全新的单体 Full-300 运行。
HaluMem、MemGym 与 MINTEval 继续作为 release evidence,不进入公开 benchmark 声明。
LanguagePack 与召回语义,它们对当前包而言只是历史证据,不是当前版本性能声明,也不代表
零 provider 默认路径;在 `v0.7.1` 完成同等 fresh run 之前,当前声明表保持为空。
LongMemEval 已撤下并等待 clean rerun:历史 rules-only 路径使用了 answer annotation,
后来的 label-free 路径又把原始 `answer_*` session ID 暴露给检索和 reader。
ImplicitMemBench 的 retry-merged 结果仍属于内部证据,因为它不能替代一次全新的单体
Full-300 运行。HaluMem、MemGym 与 MINTEval 继续作为 release evidence,不进入公开
benchmark 声明。

@@ -69,3 +71,2 @@ <!-- current-claims-table:start -->

| MemoryAgentBench v0.6.0 (CR, TTL) | 上游确定性 match-mode,judge-free | **CR 0.959, TTL 0.933** | 两项无记忆均为 0.000 | [memoryagentbench.json](./benchmark-claims/memoryagentbench.json) |
| LongMemEval full 500 | 严格轨:judge-free 确定性子集 · 诊断轨:LongMemEval 官方 prompt 兼容判官 | 严格 **0.720**(360/500)· prompt-compatible **0.888**(444/500),`goodmemory-rules-only` | 无记忆 0.068;当前 Mem0 harness:94.4 Top200 / 94.8 Top50(模型栈与预算不同) | [longmemeval.json](./benchmark-claims/longmemeval.json) |
| ImplicitMemBench Full-300 | stored-answer cross-version judge rescore | **0.691**(207.35/300),gpt-5.4 judge over gpt-5.5 answers,sourceAnswersUnchanged | upstream-chat 基线 **0.400**(120/300);reference line 0.66 | [implicitmembench.json](./benchmark-claims/implicitmembench.json) |

@@ -76,16 +77,9 @@ <!-- historical-evidence-table:end -->

都无法夸大的硬下限。第二条轨把*同一批已存答案*(不重新生成)用基准来源或业界标准
prompt 重判。只有 evaluator model 与其余冻结配置也匹配时,才主张数值可比。LongMemEval
的 gpt-5.4/gpt-5.5 诊断不在 pinned evaluator model zoo 中,因此只能称 prompt-compatible,
不能与 published official score 直接数值比较。每个协议细节都记录在链接的 claim
declaration 里。
prompt 重判。只有 evaluator model 与其余冻结配置也匹配时,才主张数值可比。每个协议
细节都记录在链接的 claim declaration 里。
历史 LongMemEval 严格结果是 judge-free 的,取代了此前一个已作废、不可声明的内部带判官数字(0.908)。
一个 case 只有被确定性方法(abstention / exact / contains / expected_alternative /
numeric_count)判对才计入;eval 流水线里的同模型 semantic judge(gpt-5.5 评 gpt-5.5)
按构造排除在外——算上判官的诊断性整体准确率是 0.896,出于透明予以披露,但不作声明。
记录的 0.720(360/500,`executionFailures: 0`,v0.3.5)使用无 embedding 的
`goodmemory-rules-only` profile;360 个判对里弃答只占 28 个,而无记忆基线的 0.068 里
绝大多数是纯弃答(34 个对里占 30 个),所以 +65.2 个百分点的提升来自记忆系统本身。
judge-free 指的是评分方式——答案仍由 gpt-5.5 生成。完整溯源见
[claim declaration](./benchmark-claims/longmemeval.json)。
LongMemEval declaration 现在是 `paused_boundary`,不再属于历史证据。旧数字只为保留
审计链而存在;在 opaque-session-id、label-free 的 Full-500 clean rerun 替换它们之前,
不得引用为 GoodMemory 成绩。见
[withdrawal declaration](./benchmark-claims/longmemeval.json)。
历史 v0.6.0 MemoryAgentBench 证据刻意限定范围。答案由 `gpt-5.6-terra` 生成,评分采用

@@ -128,6 +122,9 @@ 上游确定性 match-mode,属于 judge-free。Conflict Resolution 得 CR 0.959

LongMemEval 的 Phase 72 eval-only verifier chain 达到 judge-free 0.720、独立 gpt-5.5
官方 prompt 兼容评分 0.924。gpt-5.5 不在 pinned LongMemEval evaluator model zoo 中,
所以该结果不能与 published official score 直接数值比较;它也不是生产 runtime
profile。ImplicitMemBench 的显式 retry-merged
LongMemEval 首个 current-recall assembly development slice 已被取代:虽然
reader context 不含 raw session ID,但 memory-builder 边界仍收到带 gold
信息的 session ID 和 turn marker。更严格的 v2 协议会在构建记忆前移除
answer、question type、answer marker 和 raw session identity。必须先在 clean
commit 上重跑 development,仍封存的 holdout 才能打开;这不会恢复任何
LongMemEval claim。
ImplicitMemBench 的显式 retry-merged
检查达到 0.6923666667 且零失败,但不能替代一次全新的单体 Full-300 运行,因此两者

@@ -154,3 +151,3 @@ 都不进入 current-claims table。底层报告位于 gitignored 的 `reports/` 下,可按记录

- **你是、或运行在 Claude Code / Codex 里** →
`npm install -g goodmemory@0.7.0 && goodmemory setup`。不确定环境里已经装了
`npm install -g goodmemory@0.7.1 && goodmemory setup`。不确定环境里已经装了
什么?运行 `goodmemory adopt`(加 `--json` 得到机器可读方案):它会检测

@@ -250,3 +247,3 @@ `.claude/`、`.codex/` 和已有的 MCP 配置,并打印出针对你环境的确切下一条命令。

GoodMemory `0.7.0` 有两条常用安装路径。
GoodMemory `0.7.1` 发布后有两条常用 registry 安装路径。发布前请使用下方 tarball 验证路径。

@@ -256,3 +253,3 @@ 如果你想给已安装的 coding agent 增加记忆能力,使用全局 CLI:

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -265,7 +262,7 @@ goodmemory status

```bash
npm install goodmemory@0.7.0
npm install goodmemory@0.7.1
```
如果你想直接输入 `goodmemory`,必须安装全局 CLI。
项目内 `npm install goodmemory@0.7.0` 不会把 `goodmemory` 放进 shell 的 `PATH`。
项目内 `npm install goodmemory@0.7.1` 不会把 `goodmemory` 放进 shell 的 `PATH`。
这种本地依赖安装只能从该项目里用 `npx goodmemory`、

@@ -281,3 +278,3 @@ `npm exec -- goodmemory` 或 `./node_modules/.bin/goodmemory` 调用。

```bash
bun add goodmemory@0.7.0
bun add goodmemory@0.7.1
```

@@ -288,3 +285,3 @@

```bash
npm install ./goodmemory-0.7.0.tgz
npm install ./goodmemory-0.7.1.tgz
```

@@ -299,3 +296,3 @@

```bash
npm install -g goodmemory@0.7.0
npm install -g goodmemory@0.7.1
goodmemory setup

@@ -986,3 +983,3 @@ goodmemory status

shell `PATH` 上的裸 `goodmemory` 命令来自
`npm install -g goodmemory@0.7.0` 安装的全局 CLI。本地 dependency install
`npm install -g goodmemory@0.7.1` 安装的全局 CLI。本地 dependency install
里,用 `npx goodmemory`、`npm exec -- goodmemory` 或

@@ -989,0 +986,0 @@ `./node_modules/.bin/goodmemory` 调用 package bin。repo-local

#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";

@@ -10,8 +10,28 @@ import { fileURLToPath } from "node:url";

const result = spawnSync(BUN_BINARY, ["run", MCP_ENTRYPOINT, ...process.argv.slice(2)], {
stdio: "inherit",
});
const signalHandlers = new Map();
let child;
if (result.error) {
if ("code" in result.error && result.error.code === "ENOENT") {
function removeSignalHandlers() {
for (const [signal, handler] of signalHandlers) {
process.off(signal, handler);
}
}
for (const signal of ["SIGINT", "SIGTERM"]) {
const handler = () => {
child?.kill(signal);
};
signalHandlers.set(signal, handler);
process.on(signal, handler);
}
child = spawn(
BUN_BINARY,
["run", MCP_ENTRYPOINT, ...process.argv.slice(2)],
{ stdio: "inherit" },
);
child.on("error", (error) => {
removeSignalHandlers();
if ("code" in error && error.code === "ENOENT") {
console.error(

@@ -26,9 +46,13 @@ [

throw result.error;
}
throw error;
});
if (result.signal) {
process.kill(process.pid, result.signal);
}
child.on("exit", (code, signal) => {
removeSignalHandlers();
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(result.status ?? 1);
process.exit(code ?? 1);
});

@@ -11,3 +11,3 @@ {

},
"version": "0.7.0",
"version": "0.7.1",
"packages": [

@@ -18,3 +18,3 @@ {

"identifier": "goodmemory",
"version": "0.7.0",
"version": "0.7.1",
"runtimeHint": "npx",

@@ -21,0 +21,0 @@ "transport": {

import{Xa as M,Ya as g,_a as x,ab as f,bb as v,fb as d,hb as p}from"./chunk-wy6fj8p6.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}export{$F as probeReadOnlyPostgresStorageBackend,_F as migratePostgresStorageBackend,a as getPostgresVectorExtensionStatus,HF as ensurePostgresStorageBackend,ZF as createPostgresVectorStore,YF as createPostgresSessionStore,XF as createPostgresDocumentStore,DF as canBootstrapPostgresStorageBackend};
export{XF as Ma,YF as Na,ZF as Oa,$F as Pa,DF as Qa};

Sorry, the diff of this file is too big to display

import{Xa as b,Ya as QG,_a as DG,ab as qG,bb as kG,cb as CG,db as YG,eb as EG,fb as PG,gb as RG,ib as ZG}from"./chunk-wy6fj8p6.js";import{Database as VG}from"bun:sqlite";import{Buffer as bG}from"node:buffer";import{mkdirSync as pG}from"node:fs";import{dirname as uG}from"node:path";import{spawnSync as NG}from"node:child_process";import{existsSync as yG}from"node:fs";import*as wG from"sqlite-vss";var t="vss_inner_product",HG=Symbol.for("goodmemory.sqlite.library-registry"),SG=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],gG=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m(G){if(!G)return;let Y=G.trim();return Y.length>0?Y:void 0}function fG(G){let Y=m(G);if(!Y)return[];return Y.split(",").map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function xG(G){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(G))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${G}. Expected a valid SQLite function identifier.`);return G}function vG(G){let Y=m(G);if(!Y)return;if(Y==="off"||Y==="prefer"||Y==="require")return Y;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${Y}. Expected off|prefer|require.`)}function a(G){let{backend:Y,customLibraryPath:Z,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}=G;return{customLibraryPath:Z,vectorExtension:{backend:Y,entryPoint:H,mode:X,path:F,paths:W,searchFunction:A}}}function JG(G){return{config:a({backend:"none",customLibraryPath:G.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:G.searchFunction}),diagnostics:{available:G.source==="disabled",backend:"none",effectiveMode:"off",reason:G.reason,requestedMode:G.requestedMode,source:G.source}}}function hG(G){let Y=NG(process.execPath,["-e",gG,"--",G.customLibraryPath,...G.paths],{encoding:"utf8",timeout:1e4});if(Y.error)return{loadable:!1,reason:Y.error.message};if(Y.status!==0)return{loadable:!1,reason:`${Y.stdout}${Y.stderr}`.trim()||`sqlite-vss probe exited with status ${Y.status}`};return{loadable:!0}}function mG(G={}){let Y=G.exists??yG,Z=(G.libraryCandidatePaths??SG).find((H)=>Y(H));if(!Z)return{runtime:null};try{let H=wG,X=Object.hasOwn(G,"getVectorLoadablePath")?G.getVectorLoadablePath:H.getVectorLoadablePath,F=Object.hasOwn(G,"getVssLoadablePath")?G.getVssLoadablePath:H.getVssLoadablePath;if(!X||!F)return{runtime:null};let W=X(),A=F();if(!Y(W)||!Y(A))return{runtime:null};let M={customLibraryPath:Z,paths:[W,A]},E=(G.probeRuntime??hG)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(H){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${H instanceof Error?H.message:String(H)}`}}}function jG(G=process.env,Y){let Z=m(G.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),H=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),X=fG(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=vG(G.GOODMEMORY_SQLITE_VECTOR_MODE),W=xG(m(G.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??t),A=m(G.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=Y?.inspectBundledSQLiteVssRuntime?Y.inspectBundledSQLiteVssRuntime():Y?.detectBundledSQLiteVssRuntime?{runtime:Y.detectBundledSQLiteVssRuntime()}:mG(),E=M.runtime,P=M.unavailableReason,U=F??(X.length>0||E||P?"prefer":"off");if(U==="off")return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"disabled"});if(X.length>0)return{config:a({backend:"sql-function",customLibraryPath:Z,entryPoint:A,mode:U,path:H,paths:X,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let Q=U==="require"?"require":"prefer";return{config:a({backend:"sqlite-vss",customLibraryPath:Z??E.customLibraryPath,entryPoint:A,mode:Q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:Q,requestedMode:U,source:"bundled-sqlite-vss"}}}return JG({customLibraryPath:Z,requestedMode:U,searchFunction:W,source:"unavailable",reason:P??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function BG(G,Y){if(!G.customLibraryPath)return;let Z=globalThis,H=Z[HG]??{configuredPaths:new WeakMap};Z[HG]=H;let X=H.configuredPaths.get(Y);if(X===G.customLibraryPath)return;if(X)throw Error(`SQLite runtime already uses ${X} and cannot switch to ${G.customLibraryPath}.`);Y.setCustomSQLite(G.customLibraryPath),H.configuredPaths.set(Y,G.customLibraryPath)}function AG(G,Y){if(G.mode==="off"||!(G.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Z of G.paths)Y.loadExtension(Z,G.entryPoint);return{loaded:!0}}catch(Z){let H=Z instanceof Error?Z.message:String(Z);if(G.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${G.path}: ${H}`};throw Error(`Failed to load SQLite vector extension at ${G.path}: ${H}`)}}var o=null,e=null,OG="document_filter_indexes",UG="document_text_fts_keys",zG=2,_G=2;function rG(){if(!o)o={customLibraryPath:TG().config.customLibraryPath},BG(o,VG);return o}function TG(){if(!e)e=jG();return e}function cG(G,Y){if(Y?.readOnly||G===":memory:")return;pG(uG(G),{recursive:!0})}function $G(G,Y){return rG(),cG(G,Y),new VG(G,{create:Y?.readOnly?!1:!0,readonly:Y?.readOnly??!1,strict:!0})}function dG(G){G.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{G.exec("BEGIN IMMEDIATE");let Y=G.query("SELECT version FROM document_store_schema WHERE component = ?1");if(Y.get(UG)?.version!==zG)G.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(UG,zG);if(Y.get(OG)?.version!==_G)G.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),G.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(OG,_G);G.exec("COMMIT")}catch(Y){try{G.exec("ROLLBACK")}catch{}throw Y}}function lG(G){G.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function sG(G){G.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V(G){return JSON.parse(G)}function g(G,Y){let Z=G.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(Y);return Z!==null&&Z!==void 0}function oG(G,Y,Z){let H=Y.replaceAll('"','""');return G.query(`PRAGMA table_info("${H}")`).all().some(({name:X})=>X===Z)}function f(G){return Error(`SQLite ${G} store is read-only in this context.`)}function iG(G,Y){let Z=Math.min(G.length,Y.length),H=0;for(let X=0;X<Z;X+=1)H+=G[X]*Y[X];return H}function nG(G){return G===null||typeof G==="string"||typeof G==="number"||typeof G==="boolean"}function aG(G){switch(G){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function n(G,Y){G.exec("BEGIN IMMEDIATE");try{let Z=Y();return G.exec("COMMIT"),Z}catch(Z){try{G.exec("ROLLBACK")}catch{}throw Z}}function KG(G){let{alias:Y,keyParameterIndex:Z,value:H,valueParameterIndex:X}=G,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${Y}
WHERE ${Y}.key = ?${Z}`;if(H===null)return`${F}
AND ${Y}.type = 'null'
)`;if(typeof H==="boolean")return`${F}
AND ${Y}.type = '${H?"true":"false"}'
)`;if(typeof H==="number")return`${F}
AND ${Y}.type IN ('integer', 'real')
AND ${Y}.atom = ?${X}
)`;return`${F}
AND ${Y}.type = 'text'
AND ${Y}.atom = ?${X}
)`}function c(G){return`"${G.replaceAll('"','""')}"`}function tG(G){if(/^[A-Za-z0-9]+$/.test(G))return G;return`x_${bG.from(G,"utf8").toString("hex")}`}function FG(G,Y){return`vss_vectors_${tG(G)}_dim_${Y}`}function i(G,Y,Z){G.query(`DELETE FROM ${c(Y)} WHERE rowid = ?1`).run(Z)}function MG(G){let{database:Y,embeddingJson:Z,rowid:H,tableName:X}=G;i(Y,X,H),Y.query(`INSERT INTO ${c(X)} (rowid, embedding)
VALUES (?1, json(?2))`).run(H,Z)}function eG(G){let{collection:Y,config:Z,database:H,filter:X,queryEmbedding:F,topK:W}=G;if(Z.mode==="off"||!Z.paths?.length)return null;let A=[Y,JSON.stringify(F)],M=[];if(X)for(let[U,Q]of Object.entries(X)){if(!nG(Q))return null;A.push(U);let N=A.length,I=`metadata_filter_${M.length+1}`;if(Q===null||typeof Q==="boolean"){M.push(KG({alias:I,keyParameterIndex:N,value:Q}));continue}A.push(Q),M.push(KG({alias:I,keyParameterIndex:N,value:Q,valueParameterIndex:A.length}))}A.push(W);let E=["collection = ?1",...M];return H.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Z.searchFunction||t}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${A.length}`).all(...A).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function OY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)dG(Z);let H=Z.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),X=Z.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Z.query("SELECT json FROM documents WHERE collection = ?1"),W=Z.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),A=g(Z,"document_text_fts"),M=g(Z,"document_text_fts_keys"),E=A&&oG(Z,"document_text_fts","searchText"),P=M?Z.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Z.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,Q=A?Z.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=A&&E?Z.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,I=M?Z.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(J,$){let O=U?.get(J,$);if(!O)return;Q?.run(O.rowid),I?.run(O.rowid)}function d(J,$,O){if(!Q||!N||!P||!U)return;let z=U.get(J,$);if(z)Q.run(z.rowid);let R=ZG(O,"searchText"),T=ZG(O,"text");if(T===void 0&&R===void 0){if(z)I?.run(z.rowid);return}P.run(J,$);let D=U.get(J,$);N.run(D.rowid,J,$,T??null,R??null)}function p(J){let $=Object.entries(J.filter??{}),O=$.length>0?[`json_valid(${J.alias}.json)`]:[];for(let[z,R]of $){let T=aG(z);if(T){if(R===null){O.push(`json_type(${J.alias}.json, '${T}') = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, '${T}') = ?${J.values.length}`);continue}J.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=J.values.length;if(R===null){O.push(`json_type(${J.alias}.json, ?${D}) = 'null'`);continue}J.values.push(R),O.push(`json_extract(${J.alias}.json, ?${D}) = ?${J.values.length}`)}return O}function l(J){Z.exec("BEGIN IMMEDIATE");try{for(let $ of[J.expected,...J.unchanged??[]]){let O=X.get($.collection,$.id);if(!($.document===null?O===null:O!==null&&O.json===JSON.stringify($.document)))return Z.exec("ROLLBACK"),!1}for(let $ of J.set)H.run($.collection,$.id,JSON.stringify($.document)),d($.collection,$.id,$.document);for(let $ of J.delete??[])W.run($.collection,$.id),x($.collection,$.id);return Z.exec("COMMIT"),!0}catch($){try{Z.exec("ROLLBACK")}catch{}throw $}}return{projectionBatchSemantics:DG,async set(J,$,O){n(Z,()=>{H.run(J,$,JSON.stringify(O)),d(J,$,O)})},async get(J,$){let O=X.get(J,$);return O?V(O.json):null},async update(J,$,O){let z=await this.get(J,$);if(!z)throw Error(`Document not found for update: ${J}/${$}`);await this.set(J,$,EG(z,O))},async query(J,$){if(CG($),$&&Object.keys($).length>0){let z=[J],R=p({alias:"documents",filter:$,values:z});return Z.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(J).map((z)=>V(z.json))},async queryPage(J,$){qG($);let O=[J],z=p({alias:"documents",filter:$.filter,values:O});O.push($.cursor??null);let R=O.length;O.push($.limit+1);let T=Z.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=T.slice(0,$.limit);return{items:D.map((w)=>V(w.json)),...T.length>$.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(J,$){kG($);let O=RG($.query);if(O.length===0)return[];let z=[],R,T=$.field==="text"?$.field:$.field==="searchText"&&E?$.field:null;if(A&&T){z.push(O,J);let D=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${T} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(J,`$."${$.field.replaceAll('"',"\\\"")}"`);let D=PG($.query),w=[];for(let v of D)z.push(`%${v}%`),w.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:$.filter,values:z});z.push($.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${w.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Z.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(J){if(Y?.readOnly)throw f("document");return l(J)},async delete(J,$){n(Z,()=>{x(J,$),W.run(J,$)})}}}function GG(G,Y,Z){if(Z?.readOnly&&!g(G,Y))return{async set(){throw f("session")},async get(){return null},async setIfUnchanged(){throw f("session")},async deleteIfUnchanged(){throw f("session")},async deleteByScope(){throw f("session")}};let H=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),X=G.query(`SELECT json FROM ${Y} WHERE scope_key = ?1`),F=G.query(`INSERT INTO ${Y} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=G.query(`UPDATE ${Y}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),A=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1`),M=G.query(`DELETE FROM ${Y} WHERE scope_key = ?1 AND json = ?2`),E=G.query(`DELETE FROM ${Y} WHERE scope_key LIKE ?1`);return{async set(P,U){H.run(b(P),JSON.stringify(U))},async setIfUnchanged(P,U,Q){return n(G,()=>{let N=b(P),I=JSON.stringify(Q),x=U===null?F.run(N,I):W.run(N,JSON.stringify(U),I);return Number(x.changes??0)===1})},async get(P){let U=X.get(b(P));return U?V(U.json):null},async deleteIfUnchanged(P,U){return n(G,()=>{let Q=M.run(b(P),JSON.stringify(U));return Number(Q.changes??0)===1})},async deleteByScope(P){if(P.sessionId!==void 0){let Q=A.run(b(P));return Number(Q.changes??0)}let U=E.run(`${QG(P)}%`);return Number(U.changes??0)}}}function UY(G,Y){let Z=$G(G,Y);if(!Y?.readOnly)lG(Z);let H=GG(Z,"session_buffers",Y),X=GG(Z,"session_working_memory",Y),F=GG(Z,"session_journals",Y);return{saveBuffer(W,A){return H.set(W,A)},saveBufferIfUnchanged(W,A,M){return H.setIfUnchanged(W,A,M)},getBuffer(W){return H.get(W)},deleteBufferIfUnchanged(W,A){return H.deleteIfUnchanged(W,A)},deleteBuffersByScope(W){return H.deleteByScope(W)},saveWorkingMemory(W,A){return X.set(W,A)},getWorkingMemory(W){return X.get(W)},deleteWorkingMemoryByScope(W){return X.deleteByScope(W)},saveJournal(W,A){return F.set(W,A)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function zY(G,Y,Z){let H=Z?.runtimeResolution??TG(),X=Z?.vectorExtensionConfig??H.config.vectorExtension,F=Z?.runtimeResolution?.diagnostics??H.diagnostics,W=$G(G,Y);if(!Y?.readOnly)sG(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let A=!Y?.readOnly||g(W,"vectors"),M=new Set,E=null,P=Y?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,Q=A?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,I=A?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=A?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=Y?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!Y?.readOnly||g(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,J=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),$=Y?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let j=(Z?.loadVectorExtension??AG)(X,W);return E=j&&typeof j==="object"&&"loaded"in j?j:{loaded:X.mode!=="off"&&Boolean(X.paths?.length)},E}function z(){return X.backend==="sqlite-vss"&&O().loaded}function R(j,K){let B=FG(j,K);J.run(B,j,K)}function T(j){$.run(j.tableName,j.collection,j.dimension)}function D(j){if(!j.existed)return!0;let K=l.get(j.tableName);return!K||K.dirty!==0}function w(j){return l?.get(j)?.dirty===0}function u(j,K,B){let _=N.all(j).filter((C)=>{return V(C.embedding_json).length===K}),q=new Set(_.map((C)=>C.rowid)),k=W.query(`SELECT rowid FROM ${c(B)}`).all();for(let C of k)if(!q.has(C.rowid))i(W,B,C.rowid);for(let C of _)MG({database:W,embeddingJson:C.embedding_json,rowid:C.rowid,tableName:B});T({collection:j,dimension:K,tableName:B})}function v(j,K){if(!z())return null;let B=FG(j,K);if(M.has(B)){if(Y?.readOnly){if(!w(B))return M.delete(B),null;return B}if(D({existed:!0,tableName:B}))u(j,K,B);return B}if(Y?.readOnly){if(!g(W,B))return null;if(!w(B))return null;return M.add(B),B}let _=g(W,B);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(B)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:B}))u(j,K,B);return M.add(B),B}function IG(j){let{collection:K,filter:B,queryEmbedding:_,topK:q}=j,k=_.length,C=v(K,k);if(!C)return null;let L=Q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(L===0)return[];let s=JSON.stringify(_),y=Math.min(L,Math.max(q,B?q*4:q));while(y>0){let h=W.query(`SELECT rowid, distance
FROM ${c(C)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,y),S=[];for(let WG of h){let r=x.get(K,WG.rowid);if(!r)continue;let LG=V(r.embedding_json),XG=V(r.metadata_json);if(!YG(XG,B))continue;S.push({id:r.id,embedding:LG,metadata:XG,content:r.content,score:1/(1+Number(WG.distance))})}if(!B||S.length>=q||y>=L)return S.slice(0,q);y=Math.min(L,y*2)}return[]}return{async upsert(j,K){if(Y?.readOnly)throw f("vector");W.transaction((_)=>{let q=z();for(let k of _){let C=I.get(j,k.id),L=C?V(C.embedding_json).length:null,s=JSON.stringify(k.embedding);if(P.run(j,k.id,s,JSON.stringify(k.metadata),k.content),!q){if(C&&L!==null&&L!==k.embedding.length)R(j,L);R(j,k.embedding.length);continue}let y=I.get(j,k.id);if(!y)continue;if(C&&L!==null&&L!==k.embedding.length){let S=v(j,L);if(S)i(W,S,C.rowid)}let h=v(j,k.embedding.length);if(!h)continue;MG({database:W,embeddingJson:s,rowid:y.rowid,tableName:h})}})(K)},async get(j,K){if(!A)return null;let B=U.get(j,K);if(!B)return null;return{id:B.id,embedding:V(B.embedding_json),metadata:V(B.metadata_json),content:B.content}},async search(j,K,B){if(B.topK<=0||K.length===0)return[];if(!A)return[];if(X.mode!=="off"&&X.paths?.length&&O().loaded)try{let _=X.backend==="sqlite-vss"?IG({collection:j,filter:B.filter,queryEmbedding:K,topK:B.topK}):(Z?.runExtensionSearch??eG)({collection:j,config:X,database:W,filter:B.filter,queryEmbedding:K,topK:B.topK});if(_!==null)return _;if(X.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(X.mode==="require"){let q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${j}: ${q}`)}}return Q.all(j).map((_)=>{let q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:q,metadata:k,content:_.content,score:iG(q,K)}}).filter((_)=>YG(_.metadata,B.filter)).sort((_,q)=>{if(q.score!==_.score)return q.score-_.score;return _.id.localeCompare(q.id)}).slice(0,B.topK)},async delete(j,K){if(Y?.readOnly)throw f("vector");W.transaction(()=>{let _=I.get(j,K),q=z();if(_&&q){let k=V(_.embedding_json).length,C=v(j,k);if(C)i(W,C,_.rowid)}if(_&&!q){let k=V(_.embedding_json).length;R(j,k)}d.run(j,K)})()}}}export{zY as createSQLiteVectorStore,UY as createSQLiteSessionStore,OY as createSQLiteDocumentStore};
export{OY as Ra,UY as Sa,zY as Ta};

Sorry, the diff of this file is too big to display

import{createRequire as x}from"node:module";var f=Object.create;var{getPrototypeOf:S,defineProperty:g,getOwnPropertyNames:D}=Object;var y=Object.prototype.hasOwnProperty;var I=(e,t,o)=>{o=e!=null?f(S(e)):{};let r=t||!e||!e.__esModule?g(o,"default",{value:e,enumerable:!0}):o;for(let n of D(e))if(!y.call(r,n))g(r,n,{get:()=>e[n],enumerable:!0});return r};var b=x(import.meta.url);function c(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}function d(e){let t=e.userId.trim();if(t.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:t,tenantId:c(e.tenantId),workspaceId:c(e.workspaceId),agentId:c(e.agentId),sessionId:c(e.sessionId)}}function l(e){let t=d(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId??""].join("::")}function M(e){let t=d(e);return[t.userId,t.tenantId??"",t.workspaceId??"",t.agentId??"",t.sessionId].map((o)=>o??"").join("::")}function B(e,t){return l(e)===l(t)}var v="unchanged-delete-v1";function k(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function C(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");p(e.filter)}function R(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");p(e.filter)}function p(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function j(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([r,n])=>o[r]===n)}function E(e,t){return{...e,...t}}var h=/[\p{L}\p{N}]+/gu;function s(e){return(e.normalize("NFKC").toLowerCase().match(h)??[]).filter((t)=>t.length>0)}function F(e){return[...new Set(s(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function N(e){let t=[...new Set(s(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function W(e,t){let o=e[t];return typeof o==="string"?o:void 0}function A(e,t){let o=[...new Set(s(e))];if(o.length===0)return 0;let r=s(t),n=new Map;for(let i of r)n.set(i,(n.get(i)??0)+1);let u=0,m=0;for(let i of o){let a=n.get(i)??0;if(a>0)u+=1,m+=a}if(u===0)return 0;return u/o.length+m/Math.max(1,r.length)}
export{I as Ua,b as Va,d as Wa,l as Xa,M as Ya,B as Za,v as _a,k as $a,C as ab,R as bb,p as cb,j as db,E as eb,s as fb,F as gb,N as hb,W as ib,A as jb};
import{_b as D}from"./chunk-n9j0rb5c.js";import{ac as q,cc as K}from"./chunk-eqpe4gcb.js";var S=q((kz,O)=>{var{create:m,defineProperty:v,getOwnPropertyDescriptor:_,getOwnPropertyNames:a,getPrototypeOf:n}=Object,r=Object.prototype.hasOwnProperty,t=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},I=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of a(B))if(!r.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=_(B,G))||H.enumerable})}return z},V=(z,B,F)=>(F=z!=null?m(n(z)):{},I(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),e=(z)=>I(v({},"__esModule",{value:!0}),z),M={};t(M,{findRootDir:()=>Bz,getUserDataDir:()=>Fz});O.exports=e(M);var Y=V(K("path")),o=V(K("fs")),J=V(K("os")),zz=D();function Bz(){try{let z=process.cwd();while(z!==Y.default.dirname(z)){let B=Y.default.join(z,".vercel");if(o.default.existsSync(B))return z;z=Y.default.dirname(z)}}catch(z){throw new zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Fz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(J.default.platform()){case"darwin":return Y.default.join(J.default.homedir(),"Library/Application Support");case"linux":return Y.default.join(J.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var u=q((fz,l)=>{var{create:Gz,defineProperty:b,getOwnPropertyDescriptor:Hz,getOwnPropertyNames:Kz,getPrototypeOf:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},j=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Kz(B))if(!Wz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=Hz(B,G))||H.enumerable})}return z},E=(z,B,F)=>(F=z!=null?Gz(Qz(z)):{},j(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Yz=(z)=>j(b({},"__esModule",{value:!0}),z),x={};Xz(x,{isValidAccessToken:()=>vz,readAuthConfig:()=>$z,writeAuthConfig:()=>qz});l.exports=Yz(x);var Z=E(K("fs")),y=E(K("path")),Zz=P();function C(){let z=(0,Zz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return y.join(z,"auth.json")}function $z(){try{let z=C();if(!Z.existsSync(z))return null;let B=Z.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function qz(z){let B=C(),F=y.dirname(B);if(!Z.existsSync(F))Z.mkdirSync(F,{mode:504,recursive:!0});Z.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function vz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var k=q((iz,g)=>{var{defineProperty:R,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz}=Object,Lz=Object.prototype.hasOwnProperty,Jz=(z,B)=>{for(var F in B)R(z,F,{get:B[F],enumerable:!0})},Vz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Lz.call(z,G)&&G!==F)R(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},Az=(z)=>Vz(R({},"__esModule",{value:!0}),z),c={};Jz(c,{processTokenResponse:()=>Dz,refreshTokenRequest:()=>Tz});g.exports=Az(c);var A=K("os"),Nz="https://vercel.com",Rz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",h=`@vercel/oidc node-${process.version} ${(0,A.platform)()} (${(0,A.arch)()}) ${(0,A.hostname)()}`,N=null;async function wz(){if(N)return N;let z=`${Nz}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":h}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return N=H,H}async function Tz(z){let B=await wz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":h},body:new URLSearchParams({client_id:Rz,grant_type:"refresh_token",...z})})}async function Dz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var P=q((dz,s)=>{var{create:Iz,defineProperty:U,getOwnPropertyDescriptor:Mz,getOwnPropertyNames:Oz,getPrototypeOf:Sz}=Object,jz=Object.prototype.hasOwnProperty,Ez=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},i=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Oz(B))if(!jz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=Mz(B,G))||H.enumerable})}return z},d=(z,B,F)=>(F=z!=null?Iz(Sz(z)):{},i(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),xz=(z)=>i(U({},"__esModule",{value:!0}),z),p={};Ez(p,{assertVercelOidcTokenResponse:()=>w,findProjectInfo:()=>uz,getTokenPayload:()=>hz,getVercelCliToken:()=>Cz,getVercelDataDir:()=>yz,getVercelOidcToken:()=>lz,isExpired:()=>gz,loadToken:()=>cz,saveToken:()=>Pz});s.exports=xz(p);var $=d(K("path")),Q=d(K("fs")),X=D(),L=S(),W=u(),f=k();function yz(){let B=(0,L.getUserDataDir)();if(!B)return null;return $.join(B,"com.vercel.cli")}async function Cz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,f.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,f.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function lz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return w(T),T}function w(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function uz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=$.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function Pz(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=$.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync($.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function cz(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=$.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return w(H),H}function hz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function gz(z){return z.exp*1000<Date.now()}});export default P();
export{P as Zb};
import{Jb as x,Lb as f,Mb as v,Qb as d,Sb as p}from"./chunk-g26g591p.js";import{Wb as M,Xb as g}from"./chunk-c28647f0.js";import"./chunk-eqpe4gcb.js";import{SQL as u}from"bun";var m="public",s="gm",C="gm_documents",S="gm_session_state",r="gm_storage_schema",N="document_indexes",V=1,o=/^[A-Za-z_][A-Za-z0-9_]*$/,i=[{method:"btree",methodAndKey:"USING btree (collection)",name:"gm_documents_collection_idx"},{method:"gin",methodAndKey:"USING gin (document)",name:"gm_documents_document_gin_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'text'), '')))",name:"gm_documents_text_search_idx"},{method:"gin",methodAndKey:"USING gin (to_tsvector('simple', COALESCE((document ->> 'searchText'), '')))",name:"gm_documents_search_text_search_idx"}],b=new Map;function l(G){let J=G.trim();if(J.length===0)throw Error("Postgres storage requires a non-empty url");return J}function T(G,J){if(!o.test(G))throw Error(`Invalid Postgres ${J}: ${G}. Use only letters, digits, and underscores, and start with a letter or underscore.`);return G}function j(G){return`"${G}"`}function B(G,J){return`${j(G)}.${j(J)}`}function c(G){return JSON.stringify(G)}function D(G){return c(G)}function z(G){if(typeof G!=="string")return G;let J=JSON.parse(G);if(typeof J!=="string")return J;try{return JSON.parse(J)}catch{return J}}function n(G){return Boolean(G&&Object.keys(G).length>0)}function A(G,J,F){if(!n(J))return"";return F.push(D(J)),` AND ${G} @> $${F.length}::text::jsonb`}function t(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`{${G.join(",")}}`}function e(G){if(G.some((J)=>!Number.isFinite(J)))throw Error("Postgres vector embeddings must contain only finite numbers");return`[${G.join(",")}]`}function k(G){let J=null;return async()=>{if(!J)J=G().catch((F)=>{throw J=null,F});await J}}function I(G){return Error(`Postgres ${G} store is read-only in this context.`)}async function y(G,J){let F=await G.unsafe("SELECT to_regclass($1)::text AS oid",[J]);return F[0]?.oid!==null&&F[0]?.oid!==void 0}function R(G){let J=l(G.url),F=T(G.schema??m,"schema"),O=T(G.vectorTablePrefix??s,"vectorTablePrefix"),H=`${O}_vectors`,U=c({url:J,schema:F,vectorTablePrefix:O}),Q=b.get(U);if(Q)return Q;let W=new u(J,{prepare:!1}),X=j(F),_=B(F,C),$=B(F,S),Y=B(F,H),K=`${F}.${C}`,Z=`${F}.${S}`,E=`${F}.${H}`,P=k(async()=>{await W.unsafe(`CREATE SCHEMA IF NOT EXISTS ${X}`)}),L={sql:W,schema:F,documentTable:_,sessionStateTable:$,vectorTable:Y,hasDocumentStore:()=>y(W,K),hasSessionStore:()=>y(W,Z),hasVectorStore:()=>y(W,E),ensureDocumentStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${_} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
document JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`)}),ensureSessionStore:k(async()=>{await P(),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${$} (
scope_key TEXT NOT NULL,
state_kind TEXT NOT NULL,
payload JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_key, state_kind)
)
`)}),ensureVectorStore:k(async()=>{await P(),await W.unsafe("CREATE EXTENSION IF NOT EXISTS vector"),await W.unsafe(`
CREATE TABLE IF NOT EXISTS ${Y} (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding DOUBLE PRECISION[] NOT NULL,
metadata JSONB NOT NULL,
content TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (collection, id)
)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_collection_idx`)}
ON ${Y} (collection)
`),await W.unsafe(`
CREATE INDEX IF NOT EXISTS ${j(`${H}_metadata_gin_idx`)}
ON ${Y} USING GIN (metadata)
`)})};return b.set(U,L),L}function q(G,J,F){return{async set(O,H){if(F?.readOnly)throw I("session");await G.ensureSessionStore(),await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind)
DO UPDATE SET
payload = EXCLUDED.payload,
updated_at = EXCLUDED.updated_at
`,[M(O),J,D(H)])},async setIfUnchanged(O,H,U){if(F?.readOnly)throw I("session");await G.ensureSessionStore();let Q=M(O);return(H===null?await G.sql.unsafe(`
INSERT INTO ${G.sessionStateTable} (
scope_key,
state_kind,
payload,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW()
)
ON CONFLICT (scope_key, state_kind) DO NOTHING
RETURNING 1 AS count
`,[Q,J,D(U)]):await G.sql.unsafe(`
UPDATE ${G.sessionStateTable}
SET
payload = $3::text::jsonb,
updated_at = NOW()
WHERE scope_key = $1
AND state_kind = $2
AND payload = $4::text::jsonb
RETURNING 1 AS count
`,[Q,J,D(U),D(H)])).length===1},async get(O){if(F?.readOnly&&!await G.hasSessionStore())return null;if(!F?.readOnly)await G.ensureSessionStore();let U=(await G.sql.unsafe(`
SELECT payload::text AS payload_json
FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
`,[M(O),J]))[0];return U?z(U.payload_json):null},async deleteIfUnchanged(O,H){if(F?.readOnly)throw I("session");return await G.ensureSessionStore(),(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1
AND state_kind = $2
AND payload = $3::text::jsonb
RETURNING 1 AS count
`,[M(O),J,D(H)])).length===1},async deleteByScope(O){if(F?.readOnly)throw I("session");if(await G.ensureSessionStore(),O.sessionId!==void 0)return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key = $1 AND state_kind = $2
RETURNING 1 AS count
`,[M(O),J])).length;return(await G.sql.unsafe(`
DELETE FROM ${G.sessionStateTable}
WHERE scope_key LIKE $1 AND state_kind = $2
RETURNING 1 AS count
`,[`${g(O)}%`,J])).length}}}function XF(G,J){let F=R(G);return{projectionBatchSemantics:x,async set(O,H,U){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[O,H,D(U)])},async get(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return null;if(!J?.readOnly)await F.ensureDocumentStore();let Q=(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H]))[0];return Q?z(Q.document_json):null},async update(O,H,U){if(J?.readOnly)throw I("document");if(await F.ensureDocumentStore(),(await F.sql.unsafe(`
UPDATE ${F.documentTable}
SET
document = document || $3::text::jsonb,
updated_at = NOW()
WHERE collection = $1 AND id = $2
RETURNING id
`,[O,H,D(U)])).length===0)throw Error(`Document not found for update: ${O}/${H}`)},async query(O,H){if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H,U);return(await F.sql.unsafe(`
SELECT document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
ORDER BY id ASC
`,U)).map((X)=>z(X.document_json))},async queryPage(O,H){if(f(H),J?.readOnly&&!await F.hasDocumentStore())return{items:[]};if(!J?.readOnly)await F.ensureDocumentStore();let U=[O],Q=A("document",H.filter,U);U.push(H.cursor??null);let W=U.length;U.push(H.limit+1);let X=U.length,_=await F.sql.unsafe(`
SELECT id, document::text AS document_json
FROM ${F.documentTable}
WHERE collection = $1${Q}
AND ($${W}::text IS NULL OR id > $${W})
ORDER BY id ASC
LIMIT $${X}
`,U),$=_.slice(0,H.limit);return{items:$.map((Y)=>z(Y.document_json)),..._.length>H.limit?{nextCursor:$.at(-1).id}:{}}},async searchText(O,H){if(v(H),d(H.query).length===0)return[];if(J?.readOnly&&!await F.hasDocumentStore())return[];if(!J?.readOnly)await F.ensureDocumentStore();let U=p(H.query),Q=H.field==="text"?"to_tsvector('simple', COALESCE(document ->> 'text', ''))":H.field==="searchText"?"to_tsvector('simple', COALESCE(document ->> 'searchText', ''))":null;if(Q){let Z=[O,U.tsQuery],E=A("document",H.filter,Z);return Z.push(H.limit),(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
ts_rank(
${Q},
to_tsquery('simple', $2)
) AS score
FROM ${F.documentTable}
WHERE collection = $1${E}
AND ${Q} @@ to_tsquery('simple', $2)
ORDER BY score DESC, id ASC
LIMIT $${Z.length}
`,Z)).map((L)=>({document:z(L.document_json),id:L.id,score:Number(L.score)}))}let W=[O,H.field,U.tsQuery],X=A("document",H.filter,W),$=U.substrings.map((Z)=>{return W.push(Z),W.length}).map((Z)=>`lower(COALESCE(document ->> $2, '')) LIKE $${Z}`).join(" OR ");W.push(H.limit);let Y=W.length;return(await F.sql.unsafe(`
SELECT
id,
document::text AS document_json,
GREATEST(
ts_rank(
to_tsvector('simple', COALESCE(document ->> $2, '')),
to_tsquery('simple', $3)
),
CASE
WHEN ${$}
THEN 0.1
ELSE 0
END
) AS score
FROM ${F.documentTable}
WHERE collection = $1${X}
AND (
to_tsvector('simple', COALESCE(document ->> $2, ''))
@@ to_tsquery('simple', $3)
OR ${$}
)
ORDER BY score DESC, id ASC
LIMIT $${Y}
`,W)).map((Z)=>({document:z(Z.document_json),id:Z.id,score:Number(Z.score)}))},async writeBatchIfUnchanged(O){if(J?.readOnly)throw I("document");return await F.ensureDocumentStore(),F.sql.begin(async(H)=>{for(let U of[O.expected,...O.unchanged??[]]){await H.unsafe("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",[U.collection,U.id]);let Q=U.document===null?await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
FOR UPDATE
`,[U.collection,U.id]):await H.unsafe(`
SELECT id
FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
AND document = $3::text::jsonb
FOR UPDATE
`,[U.collection,U.id,D(U.document)]);if(!(U.document===null?Q.length===0:Q.length===1))return!1}for(let U of O.set)await H.unsafe(`
INSERT INTO ${F.documentTable} (
collection,
id,
document,
created_at,
updated_at
) VALUES (
$1,
$2,
$3::text::jsonb,
NOW(),
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
document = EXCLUDED.document,
updated_at = EXCLUDED.updated_at
`,[U.collection,U.id,D(U.document)]);for(let U of O.delete??[])await H.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[U.collection,U.id]);return!0})},async delete(O,H){if(J?.readOnly)throw I("document");await F.ensureDocumentStore(),await F.sql.unsafe(`
DELETE FROM ${F.documentTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}function YF(G,J){let F=R(G),O=q(F,"buffer",J),H=q(F,"working_memory",J),U=q(F,"journal",J);return{saveBuffer(Q,W){return O.set(Q,W)},saveBufferIfUnchanged(Q,W,X){return O.setIfUnchanged(Q,W,X)},getBuffer(Q){return O.get(Q)},deleteBufferIfUnchanged(Q,W){return O.deleteIfUnchanged(Q,W)},deleteBuffersByScope(Q){return O.deleteByScope(Q)},saveWorkingMemory(Q,W){return H.set(Q,W)},getWorkingMemory(Q){return H.get(Q)},deleteWorkingMemoryByScope(Q){return H.deleteByScope(Q)},saveJournal(Q,W){return U.set(Q,W)},getJournal(Q){return U.get(Q)},deleteJournalsByScope(Q){return U.deleteByScope(Q)}}}function ZF(G,J){let F=R(G);return{async upsert(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.begin(async(U)=>{for(let Q of H)await U.unsafe(`
INSERT INTO ${F.vectorTable} (
collection,
id,
embedding,
metadata,
content,
updated_at
) VALUES (
$1,
$2,
$3::double precision[],
$4::text::jsonb,
$5,
NOW()
)
ON CONFLICT (collection, id)
DO UPDATE SET
embedding = EXCLUDED.embedding,
metadata = EXCLUDED.metadata,
content = EXCLUDED.content,
updated_at = EXCLUDED.updated_at
`,[O,Q.id,t(Q.embedding),D(Q.metadata),Q.content])})},async get(O,H){if(J?.readOnly&&!await F.hasVectorStore())return null;if(!J?.readOnly)await F.ensureVectorStore();let Q=(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
0 AS score
FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
LIMIT 1
`,[O,H]))[0];if(!Q)return null;return{id:Q.id,embedding:z(Q.embedding_json),metadata:z(Q.metadata_json),content:Q.content}},async search(O,H,U){if(U.topK<=0||H.length===0)return[];if(J?.readOnly&&!await F.hasVectorStore())return[];if(!J?.readOnly)await F.ensureVectorStore();let Q=[O],W=A("metadata",U.filter,Q);Q.push(e(H));let X=Q.length;Q.push(U.topK);let _=Q.length;return(await F.sql.unsafe(`
SELECT
id,
array_to_json(embedding)::text AS embedding_json,
metadata::text AS metadata_json,
content,
((embedding::vector <#> $${X}::vector) * -1) AS score
FROM ${F.vectorTable}
WHERE collection = $1${W}
ORDER BY embedding::vector <#> $${X}::vector ASC, id ASC
LIMIT $${_}
`,Q)).map((Y)=>({id:Y.id,embedding:z(Y.embedding_json),metadata:z(Y.metadata_json),content:Y.content,score:Number(Y.score)}))},async delete(O,H){if(J?.readOnly)throw I("vector");await F.ensureVectorStore(),await F.sql.unsafe(`
DELETE FROM ${F.vectorTable}
WHERE collection = $1 AND id = $2
`,[O,H])}}}async function a(G){let F=await R(G).sql.unsafe(`
SELECT
EXISTS (
SELECT 1
FROM pg_extension
WHERE extname = 'vector'
) AS installed,
EXISTS (
SELECT 1
FROM pg_available_extensions
WHERE name = 'vector'
) AS available
`);if(F[0]?.installed)return"installed";if(F[0]?.available)return"available";return"missing"}function FF(G){let J=B(G.schema,r);return{async runExclusive(F){let O=await G.sql.reserve(),H=["goodmemory",G.schema,N].join(":");try{return await O.unsafe("SELECT pg_advisory_lock(hashtextextended($1, 0))",[H]),await F()}finally{try{await O.unsafe("SELECT pg_advisory_unlock(hashtextextended($1, 0))",[H])}finally{O.release()}}},async createDocumentIndex(F){await G.sql.unsafe(F)},ensureDocumentStore:G.ensureDocumentStore,async ensureVersionStore(){await G.sql.unsafe(`
CREATE TABLE IF NOT EXISTS ${J} (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`)},async getDocumentIndex(F){let H=(await G.sql.unsafe(`
SELECT
pg_get_indexdef(index_relation.oid) AS definition,
index_metadata.indpred IS NOT NULL AS is_partial,
index_metadata.indisready AS is_ready,
index_metadata.indisunique AS is_unique,
index_metadata.indisvalid AS is_valid,
access_method.amname AS method,
table_relation.relname AS table_name,
table_namespace.nspname AS table_schema
FROM pg_class AS index_relation
JOIN pg_namespace AS index_namespace
ON index_namespace.oid = index_relation.relnamespace
JOIN pg_index AS index_metadata
ON index_metadata.indexrelid = index_relation.oid
JOIN pg_class AS table_relation
ON table_relation.oid = index_metadata.indrelid
JOIN pg_namespace AS table_namespace
ON table_namespace.oid = table_relation.relnamespace
JOIN pg_am AS access_method
ON access_method.oid = index_relation.relam
WHERE index_namespace.nspname = $1
AND index_relation.relname = $2
`,[G.schema,F]))[0];return H?{definition:H.definition,isPartial:H.is_partial,isReady:H.is_ready,isUnique:H.is_unique,isValid:H.is_valid,method:H.method,tableName:H.table_name,tableSchema:H.table_schema}:null},async getVersion(){return(await G.sql.unsafe(`
SELECT version
FROM ${J}
WHERE component = $1
`,[N]))[0]?.version??null},async setVersion(F){await G.sql.unsafe(`
INSERT INTO ${J} AS storage_schema (
component,
version,
updated_at
)
VALUES ($1, $2, NOW())
ON CONFLICT (component)
DO UPDATE SET
version = GREATEST(storage_schema.version, EXCLUDED.version),
updated_at = EXCLUDED.updated_at
`,[N,F])}}}function w(G){let J=G.toLocaleLowerCase("en-US"),F=J.startsWith("using ")?0:J.indexOf(" using ");if(F<0)return"";let O=G.slice(F),H=!1,U="";for(let Q=0;Q<O.length;Q+=1){let W=O[Q];if(W==="'"){if(U+=W,H&&O[Q+1]==="'")U+="'",Q+=1;else H=!H;continue}if(H){U+=W;continue}let X=O.slice(Q).toLocaleLowerCase("en-US"),_=["::regconfig","::text"].find(($)=>X.startsWith($));if(_){Q+=_.length-1;continue}if(W==='"'||/\s/.test(W))continue;U+=W.toLocaleLowerCase("en-US")}return U}function h(G,J,F){if(!(F!==null&&F.isValid&&F.isReady&&!F.isUnique&&!F.isPartial&&F.method.toLocaleLowerCase("en-US")===J.method&&F.tableName===C&&F.tableSchema===G&&w(F.definition)===w(J.methodAndKey)))throw Error(`Postgres document index ${G}.${J.name} exists but is invalid or has an unexpected definition. Drop it with DROP INDEX CONCURRENTLY and rerun the migration.`)}function GF(G){console.error(`[GoodMemory Postgres migration] status=${G.status} schema=${G.schema} index=${G.index} elapsedMs=${G.elapsedMs}`)}async function _F(G,J,F){l(G.url);let O=T(G.schema??m,"schema"),H=F?.port??FF(R(G)),U=J?.log??GF;await H.runExclusive(async()=>{await H.ensureDocumentStore(),await H.ensureVersionStore();let Q=await H.getVersion();if(Q!==null&&Q>V)throw Error(`Postgres document index schema ${O} has unsupported version ${Q}.`);for(let W of i){let X=await H.getDocumentIndex(W.name);if(X){h(O,W,X),U({elapsedMs:0,index:W.name,schema:O,status:"current"});continue}let _=Date.now();U({elapsedMs:0,index:W.name,schema:O,status:"creating"}),await H.createDocumentIndex(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${j(W.name)} ON ${B(O,C)} ${W.methodAndKey}`);let $=await H.getDocumentIndex(W.name);h(O,W,$),U({elapsedMs:Date.now()-_,index:W.name,schema:O,status:"created"})}if(Q!==V)await H.setVersion(V)})}async function HF(G){let J=R(G);await J.ensureDocumentStore(),await J.ensureSessionStore(),await J.ensureVectorStore()}async function JF(G){let J=R(G),[F,O,H]=await Promise.all([J.hasDocumentStore(),J.hasSessionStore(),J.hasVectorStore()]);return F&&O&&H}async function $F(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.hasExistingStorageBackend??JF,H=await F(G);if(H==="missing")return"unusable";if(H!=="installed")return"inconclusive";return await O(G)?"readable":"inconclusive"}async function DF(G,J){let F=J?.getVectorExtensionStatus??a,O=J?.ensureStorageBackend??HF;if(await F(G)==="missing")return!1;return await O(G),!0}export{$F as probeReadOnlyPostgresStorageBackend,_F as migratePostgresStorageBackend,a as getPostgresVectorExtensionStatus,HF as ensurePostgresStorageBackend,ZF as createPostgresVectorStore,YF as createPostgresSessionStore,XF as createPostgresDocumentStore,DF as canBootstrapPostgresStorageBackend};
import{Ib as Id}from"./chunk-jr0h5wkn.js";function Kd(d){return d.lifecycle??"active"}function YI(d){return Kd(d)==="active"}function ZI(d,I){let M=new Date(I).getTime();if(Number.isNaN(M))return!1;for(let E of[d.validUntil,d.expiresAt]){if(E===void 0)continue;let R=new Date(E).getTime();if(!Number.isNaN(R)&&R<=M)return!0}return!1}function W(d){let I=d?.trim().toLowerCase();return I&&I.length>0?I:"general_response"}function JI(d){return[d.kind,W(d.appliesTo),d.normalizedRule.trim().toLowerCase()].join("\x00")}function h(d){return d?.extractedAt??new Date(0).toISOString()}function VI(d){let I=d.updatedAt??d.createdAt??new Date(0).toISOString();return{userId:d.userId,identity:d.identity??{},expertise:d.expertise??{primarySkills:[],domains:[]},activeContext:d.activeContext??{goals:[],currentProjects:[]},version:d.version??1,updatedAt:d.updatedAt??I,createdAt:d.createdAt??I}}function TI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,value:d.value,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,evidenceCount:d.evidenceCount??1,isPinned:d.isPinned,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",updatedAt:d.updatedAt??h(d.source)}}function mI(d){let I=d.createdAt??d.updatedAt??h(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,category:d.category,content:d.content,tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,importance:d.importance??1,source:d.source,factKind:d.factKind,scopeKind:d.scopeKind,subject:d.subject,accessCount:d.accessCount??0,lastAccessedAt:d.lastAccessedAt,verificationPressureCount:d.verificationPressureCount??0,lastVerificationHintAt:d.lastVerificationHintAt,observedAt:d.observedAt,validFrom:d.validFrom,validUntil:d.validUntil,expiresAt:d.expiresAt,demotedAt:d.demotedAt,demotionReason:d.demotionReason,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",isActive:d.isActive??!0,embeddingId:d.embeddingId,createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function QI(d){let I=d.createdAt??d.updatedAt??h(d.source);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,title:d.title,pointer:d.pointer,description:d.description,confidence:d.confidence??1,source:d.source,referenceKind:d.referenceKind,subject:d.subject,tags:d.tags,attributes:d.attributes,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",createdAt:d.createdAt??I,updatedAt:d.updatedAt??I}}function WI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,summary:d.summary,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],topics:d.topics??[],entities:d.entities,emotionalTone:d.emotionalTone,importance:d.importance??1,confidence:d.confidence??1,locale:d.locale,embeddingId:d.embeddingId,createdAt:d.createdAt??new Date(0).toISOString(),archivedAt:d.archivedAt}}function zI(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,rule:d.rule,kind:d.kind,appliesTo:d.appliesTo,why:d.why,evidence:d.evidence??[],tags:d.tags,attributes:d.attributes,confidence:d.confidence??1,source:d.source,supersededBy:d.supersededBy??null,lifecycle:d.lifecycle??"active",lastUsedAt:d.lastUsedAt,updatedAt:d.updatedAt??h(d.source)}}function BI(d){let I=d.createdAt??d.lastActiveAt??new Date(0).toISOString();return{sessionId:d.sessionId,userId:d.userId,messages:d.messages??[],compactedMessages:d.compactedMessages??[],summary:d.summary??null,summaryUpToIndex:d.summaryUpToIndex??0,createdAt:d.createdAt??I,lastActiveAt:d.lastActiveAt??I}}function bI(d){return{sessionId:d.sessionId,userId:d.userId,currentGoal:d.currentGoal,constraints:d.constraints,openLoops:d.openLoops??[],temporaryDecisions:d.temporaryDecisions,toolState:d.toolState,state:d.state,updatedAt:d.updatedAt??new Date(0).toISOString()}}function FI(d){return{sessionId:d.sessionId,userId:d.userId,title:d.title,currentState:d.currentState,taskSpecification:d.taskSpecification,filesAndFunctions:d.filesAndFunctions??[],workflow:d.workflow??[],errorsAndCorrections:d.errorsAndCorrections??[],systemDocumentation:d.systemDocumentation??[],learnings:d.learnings??[],keyResults:d.keyResults??[],worklog:d.worklog??[],lastSummarizedMessageId:d.lastSummarizedMessageId,updatedAt:d.updatedAt??new Date(0).toISOString()}}function hI(d){return{...d}}var $d={active:["active","superseded","inactive"],superseded:["superseded","inactive"],inactive:["inactive","active"]};function vI(d,I){if(!$d[d].includes(I))throw Error(`Invalid lifecycle transition: ${d} -> ${I}`);return I}var Xd=Symbol.for("goodmemory.authorizedRecallAgentScope");function oI(d,I){return{...d,memoryType:I}}function wI(d,I){if(d.tenantId===void 0&&I.tenantId!==void 0)return!1;if(d.workspaceId===void 0&&I.workspaceId!==void 0)return!1;if(d.agentId===void 0&&I.agentId!==void 0)return!1;return!0}function qI(d,I){if(I.agentId===d.agentId)return!0;return d.agentId!==void 0&&I[Xd]===d.agentId}function f(d){if(d.enactmentSurface!=="text_response")return!1;return Boolean(d.applicability.textResponsePlan||d.applicability.computedResponseRule||d.applicability.urlTemplate||d.applicability.pathTemplate||d.applicability.guard||d.applicability.guardedBehavior||(d.applicability.replacementPairs?.length??0)>0||(d.applicability.forbiddenFragments?.length??0)>0||(d.applicability.preferredAlternatives?.length??0)>0||(d.applicability.preferredFragments?.length??0)>0||(d.applicability.exactFragments?.prefixes?.length??0)>0||(d.applicability.exactFragments?.required?.length??0)>0||(d.applicability.exactFragments?.suffixes?.length??0)>0)}function Yd(d){if(d.enactmentSurface!=="host_action")return!1;return Boolean(d.applicability.canonicalFirstAction||(d.applicability.argumentOrder?.length??0)>0)}var Ed="goodmemory.behavioral_policy",Md="goodmemory.behavioral_policy.steering_only",Zd="goodmemory.behavioral_policy.version",Jd=2,w=Id(),u={from:"http://",to:"https://"},Vd="<page>",t=/\.[A-Za-z0-9]{2,8}/u,Rd={first_action:8,syntax_constraint:7,guarded_policy:6,format_contract:5,avoidance:4,preference:3,transformation_rule:2,exemplar_fact:1},Sd={example_only:3,pattern_bounded:2,general:1};function T(d){return d?.trim().toLowerCase()??""}function B(d){if(!d?.trim())return;let I=w.resolveFromText({text:d});return w.analyzeBehavioralRule(d,I)}function X(d){let I=[],M=new Set;for(let E of d){let R=E?.trim();if(!R||M.has(R))continue;M.add(R),I.push(R)}return I}function Pd(d){return{...d,args:d.args&&d.args.length>0?[...d.args]:void 0,raw:d.raw?.trim()||void 0}}function kd(d){return[...d.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((I)=>I[1]??I[2]??I[3]??"").filter((I)=>I.length>0)}function Td(d){let I=[],M="",E=0,R=null;for(let P=0;P<d.length;P+=1){let k=d[P];if(R){if(M+=k,k===R&&d[P-1]!=="\\")R=null;continue}if(k==="'"||k==='"'){R=k,M+=k;continue}if(k==="("||k==="["||k==="{"){E+=1,M+=k;continue}if(k===")"||k==="]"||k==="}"){E=Math.max(0,E-1),M+=k;continue}if(k===","&&E===0){let O=M.trim();if(O.length>0)I.push(O);M="";continue}M+=k}let S=M.trim();if(S.length>0)I.push(S);return I}function r(d){let I=d.split(/\r?\n/u).map((R)=>R.trim()).find((R)=>R.length>0)??d.trim();if(!I)return;let M=I.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(M){let[,R,S]=M;return{args:Td(S),kind:"tool_call",name:R,raw:I}}let E=kd(I);if(E.length===0)return;return{args:E.slice(1),kind:"command",name:E[0],raw:I}}function i(d){let I=Pd(d);if(I.args&&I.args.length>0)return I.args;if(I.kind==="warning"||!I.raw||I.raw.trim().length===0)return;let M=kd(I.raw);return M.length>1?M.slice(1):void 0}function md(d,I){if(I.length===0)return!0;let M=0;for(let E of I){let R=!1;while(M<d.length){if(d[M]===E){R=!0,M+=1;break}M+=1}if(!R)return!1}return!0}function p(d){let I=Pd(d);return JSON.stringify({...I.args?{args:I.args}:{},kind:I.kind,name:I.name,...I.raw?{raw:I.raw}:{}})}function Qd(d,I){if(!d||!I)return d===I;return p(d)===p(I)}function aI(d,I){if(!d||!I)return d===I;if(d.kind!==I.kind||d.name.trim()!==I.name.trim())return!1;if(I.kind==="warning")return Qd(d,I);let M=i(I);if(!M||M.length===0)return!0;let E=i(d);if(!E||E.length===0)return!1;return md(E,M)}function Wd(d){if(!A(d))return;if(d.kind!=="command"&&d.kind!=="tool_call"&&d.kind!=="warning"||typeof d.name!=="string")return;let I=Array.isArray(d.args)&&d.args.every((M)=>typeof M==="string")?[...d.args]:void 0;return{...I?{args:I}:{},kind:d.kind,name:d.name,...typeof d.raw==="string"?{raw:d.raw}:{}}}function Od(d){if(!A(d))return;let I=g(d.prefixes),M=g(d.required),E=g(d.suffixes);if(!I&&!M&&!E)return;return{...I?{prefixes:I}:{},...M?{required:M}:{},...E?{suffixes:E}:{}}}function l(d){if(!A(d)||typeof d.from!=="string"||typeof d.to!=="string")return;let I=d.from.trim(),M=d.to.trim();if(I.length===0||M.length===0)return;return{from:I,to:M}}function zd(d){if(!A(d)||typeof d.check!=="string")return;let I=d.check.trim();if(I.length===0)return;let M=g(d.allowedStates),E=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...M?{allowedStates:M}:{},check:I,...E?{fallbackInstruction:E}:{},...R?{subject:R}:{}}}function xd(d){if(!A(d)||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,R=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...R?{backupMention:R}:{},...M?{preferredAlternatives:M}:{},...E?{replacementTarget:E}:{},warningMessage:I}}function Bd(d){if(!A(d)||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,precondition:I,...R?{subject:R}:{}}}function e(d){if(!A(d)||typeof d.example!=="string"||typeof d.host!=="string"||d.pathPlacement!=="path_after_host"||d.scheme!=="http"&&d.scheme!=="https")return;let I=d.example.trim(),M=d.host.trim();if(I.length===0||M.length===0)return;return{example:I,host:M,pathPlacement:"path_after_host",scheme:d.scheme}}function a(d){if(!A(d)||typeof d.anchor!=="string"||typeof d.example!=="string"||d.variableSegment!=="filename")return;let I=d.anchor.trim(),M=d.example.trim();if(I.length===0||M.length===0)return;return{anchor:I,example:M,variableSegment:"filename"}}function _d(d){if(!A(d)||typeof d.kind!=="string")return;if(d.kind==="recurrence"){if(typeof d.sequenceName!=="string"||typeof d.expression!=="string")return;let I=d.sequenceName.trim(),M=d.expression.trim(),E=Array.isArray(d.baseCases)?d.baseCases.map((R)=>{if(!A(R)||typeof R.index!=="number"||typeof R.value!=="number"||!Number.isInteger(R.index)||!Number.isFinite(R.value))return;return{index:R.index,value:R.value}}).filter((R)=>Boolean(R)):void 0;if(I.length===0||M.length===0)return;return{...E&&E.length>0?{baseCases:E}:{},expression:M,kind:"recurrence",sequenceName:I}}if(d.kind==="binary_operator"){if(typeof d.expression!=="string"||typeof d.leftVariable!=="string"||typeof d.operatorSymbol!=="string"||typeof d.rightVariable!=="string")return;let I=d.expression.trim(),M=d.leftVariable.trim(),E=d.operatorSymbol.trim(),R=d.rightVariable.trim();if(I.length===0||M.length===0||E.length===0||R.length===0)return;return{expression:I,kind:"binary_operator",leftVariable:M,operatorSymbol:E,rightVariable:R}}return}function bd(d){if(!A(d)||d.kind!=="rewrite_output_slot")return;let I=Od(d.exactFragments),M=a(d.pathTemplate),E=g(d.preferredAlternatives),R=g(d.preferredFragments),S=Array.isArray(d.replacementPairs)?d.replacementPairs.map((O)=>l(O)).filter((O)=>Boolean(O)):void 0,P=e(d.urlTemplate),k=_d(d.computedResponseRule);if(!k&&!I&&!M&&!E&&!R&&!S&&!P)return;return{...k?{computedResponseRule:k}:{},...I?{exactFragments:I}:{},kind:"rewrite_output_slot",...M?{pathTemplate:M}:{},...E?{preferredAlternatives:E}:{},...R?{preferredFragments:R}:{},...S&&S.length>0?{replacementPairs:S}:{},...P?{urlTemplate:P}:{}}}function Fd(d){if(!A(d)||d.kind!=="require_warning"||typeof d.warningMessage!=="string")return;let I=d.warningMessage.trim();if(I.length===0)return;let M=g(d.preferredAlternatives),E=a(d.pathTemplate),R=typeof d.replacementTarget==="string"&&d.replacementTarget.trim().length>0?d.replacementTarget.trim():void 0,S=e(d.urlTemplate),P=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...P?{backupMention:P}:{},kind:"require_warning",...E?{pathTemplate:E}:{},...M?{preferredAlternatives:M}:{},...R?{replacementTarget:R}:{},...S?{urlTemplate:S}:{},warningMessage:I}}function fd(d){if(!A(d)||d.kind!=="block_surface")return;let I=g(d.forbiddenFragments);if(!I)return;let M=Array.isArray(d.replacementPairs)?d.replacementPairs.map((R)=>l(R)).filter((R)=>Boolean(R)):void 0,E=typeof d.fallbackAnswer==="string"&&d.fallbackAnswer.trim().length>0?d.fallbackAnswer.trim():void 0;return{...E?{fallbackAnswer:E}:{},forbiddenFragments:I,kind:"block_surface",...M&&M.length>0?{replacementPairs:M}:{}}}function hd(d){if(!A(d)||d.kind!=="require_precondition_check"||typeof d.precondition!=="string")return;let I=d.precondition.trim(),M=xd(d.fallbackBehavior);if(I.length===0||!M)return;let E=g(d.allowedWhen),R=typeof d.subject==="string"&&d.subject.trim().length>0?d.subject.trim():void 0;return{...E?{allowedWhen:E}:{},fallbackBehavior:M,kind:"require_precondition_check",precondition:I,...R?{subject:R}:{}}}function vd(d){return bd(d)??Fd(d)??fd(d)??hd(d)}function yd(d){if(!A(d)||!Array.isArray(d.operations))return;let I=d.operations.map((M)=>vd(M)).filter((M)=>Boolean(M));if(I.length===0)return;return{...d.bulletOnly===!0?{bulletOnly:!0}:{},...d.brevityOnly===!0?{brevityOnly:!0}:{},concise:d.concise!==!1,operations:I}}function od(d){if(!A(d))return;let I=g(d.actionSummaryContains),M=g(d.queryContains),E=g(d.argumentOrder),R=Od(d.exactFragments),S=g(d.forbiddenFragments),P=g(d.preferredAlternatives),k=g(d.preferredFragments),O=a(d.pathTemplate),s=_d(d.computedResponseRule),G=Array.isArray(d.replacementPairs)?d.replacementPairs.map((U)=>l(U)).filter((U)=>Boolean(U)):void 0,Q=e(d.urlTemplate),j=zd(d.guard),H=Bd(d.guardedBehavior)??(j?{allowedWhen:j.allowedStates,fallbackBehavior:{warningMessage:j.fallbackInstruction??"Warn or defer instead of assuming the precondition already passed."},precondition:j.check,...j.subject?{subject:j.subject}:{}}:void 0),C=Wd(d.canonicalFirstAction),x=yd(d.textResponsePlan),D=typeof d.appliesTo==="string"?W(d.appliesTo):void 0,c=typeof d.fallbackInstruction==="string"&&d.fallbackInstruction.trim().length>0?d.fallbackInstruction.trim():void 0,K=typeof d.backupMention==="string"&&d.backupMention.trim().length>0?d.backupMention.trim():void 0;return{...I?{actionSummaryContains:I}:{},...D?{appliesTo:D}:{},...E?{argumentOrder:E}:{},...K?{backupMention:K}:{},...C?{canonicalFirstAction:C}:{},...s?{computedResponseRule:s}:{},...R?{exactFragments:R}:{},...c?{fallbackInstruction:c}:{},...S?{forbiddenFragments:S}:{},...j?{guard:j}:{},...H?{guardedBehavior:H}:{},...P?{preferredAlternatives:P}:{},...k?{preferredFragments:k}:{},...O?{pathTemplate:O}:{},...M?{queryContains:M}:{},...G&&G.length>0?{replacementPairs:G}:{},...x?{textResponsePlan:x}:{},...Q?{urlTemplate:Q}:{}}}function A(d){return typeof d==="object"&&d!==null}function g(d){if(!Array.isArray(d)||!d.every((M)=>typeof M==="string"))return;let I=X(d);return I.length>0?I:void 0}function wd(d){if(!A(d))return;if(d.behavioralKind!=="preference"&&d.behavioralKind!=="avoidance"&&d.behavioralKind!=="guarded_policy"&&d.behavioralKind!=="format_contract"&&d.behavioralKind!=="first_action"&&d.behavioralKind!=="syntax_constraint"&&d.behavioralKind!=="transformation_rule"&&d.behavioralKind!=="exemplar_fact")return;if(d.transferMode!=="example_only"&&d.transferMode!=="pattern_bounded"&&d.transferMode!=="general")return;if(d.enactmentSurface!=="text_response"&&d.enactmentSurface!=="host_action")return;return{behavioralKind:d.behavioralKind,enactmentSurface:d.enactmentSurface,applicability:od(d.applicability)??{},transferMode:d.transferMode}}function qd(d){return JSON.stringify(d)}function rd(d){if(d.enactmentSurface==="host_action")return!1;let I=d.applicability;return Boolean(I.argumentOrder||I.canonicalFirstAction||I.exactFragments||I.fallbackInstruction||I.forbiddenFragments&&I.forbiddenFragments.length>0||I.guard||I.guardedBehavior||I.pathTemplate||I.preferredAlternatives&&I.preferredAlternatives.length>0||I.replacementPairs&&I.replacementPairs.length>0||I.textResponsePlan||I.urlTemplate)}function uI(d,I){return{...d??{},[Ed]:qd(I),...rd(I)?{[Md]:!0}:{},[Zd]:Jd}}function ld(d){let I=d?.[Ed];if(typeof I!=="string"||I.trim().length===0)return;try{return wd(JSON.parse(I))}catch{return}}function sd(d){return ld(d.attributes)}function tI(d){return d.attributes?.[Md]===!0}function ed(d){if(d.exemplarCount!==void 0&&d.exemplarCount<=1&&!d.hasGeneralRuleMarker)return"example_only";if(d.hasGeneralRuleMarker)return"general";return(d.exemplarCount??0)>=2?"pattern_bounded":"example_only"}function ad(d){let{forbidden:I,preferred:M}=d,E=I.match(t)?.[0],R=M.match(t)?.[0],S=[];if(!I.startsWith(".")||M.startsWith("."))S.push({from:I,to:M});if(E&&R)S.push({from:E,to:R});return{forbiddenFragments:X([I,E]),preferredFragments:X([M,R]),replacementPairs:Cd(S)}}function ud(d){let{target:I,preferredAlternative:M}=d;return{fallbackInstruction:`Warn and route to ${M??"a specialist path"} instead of using the distrusted default path.`,forbiddenFragments:[I],...M?{preferredAlternatives:[M]}:{},queryContains:[I]}}function td(d){let{allowedStates:I,check:M,subject:E}=d;return{...I.length>0?{allowedStates:I}:{},check:M,fallbackInstruction:`Check ${M} first${I.length>0?` and only proceed when ${I.join(" or ")}`:""}; otherwise warn or defer instead of assuming it already passed.`,...E?{subject:E}:{}}}function id(d){let I,M;if(d.template){let E=d.template,R=new URL(E.replace(Vd,"page"));I=[`${R.protocol}//${R.host}/`],M={example:E,host:R.host,pathPlacement:"path_after_host",scheme:R.protocol==="https:"?"https":"http"}}return{fallbackInstruction:"If the current probe explicitly requests http, warn first and then offer the https URL instead of silently substituting protocols.",forbiddenFragments:[u.from],...I?{preferredFragments:I}:{},queryContains:["url"],replacementPairs:[u],...M?{urlTemplate:M}:{}}}function pd(d){let{forbiddenRoot:I,safeTemplate:M}=d,E,R;if(M){let S=M,P=S.replace(/<file>$/u,"");E=[P],R={anchor:P,example:S,variableSegment:"filename"}}if(!I&&!R&&!d.userHomeRequired)return null;return{fallbackInstruction:"Refuse the unsafe path and redirect to a safe user-writable home-directory path instead.",...I?{forbiddenFragments:[I]}:{},...E?{preferredFragments:E}:d.userHomeRequired?{preferredFragments:["/home/"]}:{},...R?{pathTemplate:R}:{}}}function nd(d){return d?.[0]}function dI(d){let I=d.fallbackInstruction??(d.preferredAlternatives&&d.preferredAlternatives.length>0?`Warn first and redirect to ${d.preferredAlternatives.join(" or ")} instead of proceeding directly.`:void 0);if(!I)return;return{...d.backupMention?{backupMention:d.backupMention}:{},...d.preferredAlternatives&&d.preferredAlternatives.length>0?{preferredAlternatives:[...d.preferredAlternatives]}:{},...d.replacementTarget?{replacementTarget:d.replacementTarget}:{},warningMessage:I}}function $(d){let I=[],M={...d.applicability.computedResponseRule?{computedResponseRule:d.applicability.computedResponseRule}:{},kind:"rewrite_output_slot",...d.applicability.exactFragments?{exactFragments:d.applicability.exactFragments}:{},...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...d.applicability.preferredAlternatives&&d.applicability.preferredAlternatives.length>0?{preferredAlternatives:d.applicability.preferredAlternatives}:{},...d.applicability.preferredFragments&&d.applicability.preferredFragments.length>0?{preferredFragments:d.applicability.preferredFragments}:{},...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{}};if(M.computedResponseRule||M.exactFragments||M.pathTemplate||M.preferredAlternatives||M.preferredFragments||M.replacementPairs||M.urlTemplate)I.push(M);if(d.applicability.forbiddenFragments&&d.applicability.forbiddenFragments.length>0)I.push({forbiddenFragments:[...d.applicability.forbiddenFragments],kind:"block_surface",...d.applicability.replacementPairs&&d.applicability.replacementPairs.length>0?{replacementPairs:d.applicability.replacementPairs}:{}});if(d.applicability.guardedBehavior)I.unshift({...d.applicability.guardedBehavior.allowedWhen?{allowedWhen:d.applicability.guardedBehavior.allowedWhen}:{},fallbackBehavior:d.applicability.guardedBehavior.fallbackBehavior,kind:"require_precondition_check",precondition:d.applicability.guardedBehavior.precondition,...d.applicability.guardedBehavior.subject?{subject:d.applicability.guardedBehavior.subject}:{}});else{let E=dI({backupMention:d.applicability.backupMention,fallbackInstruction:d.applicability.fallbackInstruction,preferredAlternatives:d.applicability.preferredAlternatives,replacementTarget:nd(d.applicability.preferredAlternatives)});if(E&&(d.behavioralKind==="avoidance"||d.behavioralKind==="preference"||d.behavioralKind==="transformation_rule"||E.preferredAlternatives&&E.preferredAlternatives.length>0||E.backupMention||E.replacementTarget))I.push({...E.backupMention?{backupMention:E.backupMention}:{},kind:"require_warning",...d.applicability.pathTemplate?{pathTemplate:d.applicability.pathTemplate}:{},...E.preferredAlternatives?{preferredAlternatives:E.preferredAlternatives}:{},...E.replacementTarget?{replacementTarget:E.replacementTarget}:{},...d.applicability.urlTemplate?{urlTemplate:d.applicability.urlTemplate}:{},warningMessage:E.warningMessage})}return I.length>0?{concise:!0,operations:I}:void 0}function II(d){return d.formatRule}function o(d){return d.negativeRule}function EI(d){return d.firstActionName!==void 0}function MI(d){return d.firstActionName}function RI(d){return d.generalRule}function SI(d){let I=d.match(/\b([A-Z][A-Za-z0-9_]*)\(n\)\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(I?.[1]&&I[2]){let E=I[1].trim(),R=I[2].trim(),S=[...d.matchAll(new RegExp(`${b(E)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))].map((P)=>{let k=Number(P[1]),O=Number(P[2]);if(!Number.isInteger(k)||!Number.isFinite(O))return;return{index:k,value:O}}).filter((P)=>Boolean(P));return{...S.length>0?{baseCases:S}:{},expression:R,kind:"recurrence",sequenceName:E}}let M=d.match(/\b([a-z])\s*([⊗⊕⊖Ω])\s*([a-z])\s*=\s*([^.\n]+?)(?:\.|\n|$)/u);if(M?.[1]&&M[2]&&M[3]&&M[4])return{expression:M[4].trim(),kind:"binary_operator",leftVariable:M[1].trim(),operatorSymbol:M[2].trim(),rightVariable:M[3].trim()};return}function PI(d){let I=d.language??w,M=d.languageContext??I.resolveFromText({text:d.rule}),E=I.analyzeBehavioralRule(d.rule,M),R=RI(E),S=ed({exemplarCount:d.exemplarCount,hasGeneralRuleMarker:R}),P=E.triggerPhrases,k=W(d.appliesTo),O=E.protocolRewrite?id(E.protocolRewrite):null,s=E.directoryRestriction?pd(E.directoryRestriction):null,G=E.filetypeReplacement?ad(E.filetypeReplacement):null,Q=E.distrustRouting?ud(E.distrustRouting):null,j=E.exactAction?r(E.exactAction):void 0,H=SI(d.rule),C=X([...E.preferredAlternatives??[],...Q?.preferredAlternatives??[]]),x=E.guard?td(E.guard):void 0,D=X([...E.triggerPhrases??[],...x?.check?[x.check]:[],...x?.subject?[x.subject]:[],...O?.queryContains??[],...Q?.queryContains??[]]),c=E.backupRequested?"Mention a safe backup before proceeding.":void 0,K=X([...E.forbiddenFragments??[],...O?.forbiddenFragments??[],...s?.forbiddenFragments??[],...G?.forbiddenFragments??[],...Q?.forbiddenFragments??[]]),U=X([...E.preferredFragments??[],...O?.preferredFragments??[],...s?.preferredFragments??[],...G?.preferredFragments??[]]),Y=s?.pathTemplate,N=Cd([...O?.replacementPairs??[],...G?.replacementPairs??[]]),Z=O?.urlTemplate,J=x?.fallbackInstruction??Q?.fallbackInstruction??O?.fallbackInstruction??s?.fallbackInstruction??(C.length>0&&o(E)?`Prefer ${C.join(" or ")}${c?" and mention a safe backup before proceeding":""} or warn instead of implying the avoided behavior.`:void 0),L=x?{...x.allowedStates?{allowedWhen:x.allowedStates}:{},fallbackBehavior:{...c?{backupMention:c}:{},...C.length>0?{preferredAlternatives:C}:{},...C[0]?{replacementTarget:C[0]}:{},warningMessage:x.fallbackInstruction??"Warn or defer instead of assuming the required precondition already passed."},precondition:x.check,...x.subject?{subject:x.subject}:{}}:void 0;if(j||EI(E)){let _=MI(E),m=E.argumentOrder;return{behavioralKind:o(E)||d.kind==="dont"?"first_action":"syntax_constraint",enactmentSurface:"host_action",applicability:{appliesTo:k,...j?{canonicalFirstAction:j}:_?{canonicalFirstAction:{kind:_.includes("_")?"tool_call":"command",name:_}}:{},...m?{argumentOrder:m}:{},...P&&!j?{queryContains:P}:{}},transferMode:S==="general"?"pattern_bounded":S}}if(II(E)){let{formatPrefix:_,formatSuffix:m}=E,F=X([...(E.requiredFragments??[]).filter((Ud)=>Ud!==m),_,m]);return{behavioralKind:"format_contract",enactmentSurface:"text_response",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{},textResponsePlan:$({behavioralKind:"format_contract",applicability:{appliesTo:k,exactFragments:{..._?{prefixes:[_]}:{},...F.length>0?{required:F}:{},...m?{suffixes:[m]}:{}},...P?{queryContains:P}:{}}})},transferMode:S}}if(d.kind==="prefer"){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"preference",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"preference",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"preference",applicability:_})}:{}},transferMode:S}}if(d.kind==="dont"||o(E)){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"avoidance",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"avoidance",applicability:_})}:{}},transferMode:S}}if(d.kind==="do"&&!P){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}if(R||(d.exemplarCount??0)>=2){let _={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:L?"guarded_policy":"transformation_rule",enactmentSurface:"text_response",applicability:{..._,...$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})?{textResponsePlan:$({behavioralKind:L?"guarded_policy":"transformation_rule",applicability:_})}:{}},transferMode:R?"general":"pattern_bounded"}}let y={appliesTo:k,...c?{backupMention:c}:{},...J?{fallbackInstruction:J}:{},...H?{computedResponseRule:H}:{},...K.length>0?{forbiddenFragments:K}:{},...x?{guard:x}:{},...L?{guardedBehavior:L}:{},...C.length>0?{preferredAlternatives:C}:{},...U.length>0?{preferredFragments:U}:{},...Y?{pathTemplate:Y}:{},...D.length>0?{queryContains:D}:{},...N&&N.length>0?{replacementPairs:N}:{},...Z?{urlTemplate:Z}:{}};return{behavioralKind:"exemplar_fact",enactmentSurface:"text_response",applicability:{...y,...$({behavioralKind:"exemplar_fact",applicability:y})?{textResponsePlan:$({behavioralKind:"exemplar_fact",applicability:y})}:{}},transferMode:"example_only"}}function z(d,I){if(!I||I.length===0)return[];let M=T(d);return I.filter((E)=>M.includes(T(E)))}function Cd(d){let I=[],M=new Set;for(let E of d){if(!E)continue;let R=`${E.from}\x00${E.to}`;if(M.has(R))continue;M.add(R),I.push(E)}return I}function kI(d){if(!d.transientFeedback||d.transientFeedback.length===0)return[];let I=W(d.appliesTo),M=T(d.query),E=[];for(let R of d.transientFeedback){if(R.lifecycle!=="active"||R.kind==="validated_pattern")continue;if(sd(R))continue;let S=PI({appliesTo:R.appliesTo,exemplarCount:1,kind:R.kind,rule:R.rule});if(S.enactmentSurface!==d.surface)continue;let P=W(S.applicability.appliesTo??R.appliesTo),k=P===I;if(!k&&P!=="general_response")continue;let O=X([...z(M,S.applicability.queryContains),...z(M,S.applicability.actionSummaryContains),...z(M,S.applicability.forbiddenFragments),...z(M,S.applicability.preferredFragments)]),s=O.length===0&&(d.surface==="text_response"?f(S):Yd(S))&&(S.applicability.queryContains?.length??0)===0;if(S.transferMode!=="general"&&O.length===0&&!s)continue;let G=(k?1e4:0)+Rd[S.behavioralKind]*100+Sd[S.transferMode]*10+O.length+(s?3:0)+5;E.push({feedback:R,matchedQueryTokens:O,policy:S,score:G})}return E}function iI(d){let I=W(d.appliesTo),M=T(d.query),E=[];for(let S of d.feedback??[]){if(S.lifecycle!=="active")continue;let P=sd(S);if(!P||P.enactmentSurface!==d.surface)continue;let k=W(P.applicability.appliesTo??S.appliesTo),O=k===I;if(!O&&k!=="general_response")continue;let s=X([...z(M,P.applicability.queryContains),...z(M,P.applicability.actionSummaryContains),...z(M,P.applicability.forbiddenFragments),...z(M,P.applicability.preferredFragments)]);if(P.transferMode==="example_only"&&s.length===0)continue;let G=(O?1e4:0)+(d.surface==="host_action"&&P.enactmentSurface==="host_action"?2000:0)+Rd[P.behavioralKind]*100+Sd[P.transferMode]*10+s.length;E.push({feedback:S,matchedQueryTokens:s,policy:P,score:G})}let R=kI(d);return[...E,...R].sort((S,P)=>P.score-S.score)}function OI(d){let I=new Set,M=[];for(let E of d){let R=JSON.stringify(E);if(I.has(R))continue;I.add(R),M.push(E)}return M}function pI(d){return xI(d.map((I)=>I.policy))}function xI(d){let I=OI(d.flatMap((R)=>{if(R.enactmentSurface!=="text_response")return[];return R.applicability.textResponsePlan?.operations??$({behavioralKind:R.behavioralKind,applicability:R.applicability})?.operations??[]}));if(I.length===0)return;let M=d.some((R)=>R.applicability.textResponsePlan?.brevityOnly===!0);return{...d.some((R)=>R.applicability.textResponsePlan?.bulletOnly===!0)?{bulletOnly:!0}:{},...M?{brevityOnly:!0}:{},concise:!0,operations:I}}function _I(d){switch(d.kind){case"rewrite_output_slot":return[d.computedResponseRule?d.computedResponseRule.kind==="recurrence"?`rewrite_output_slot recurrence_rule: ${d.computedResponseRule.sequenceName}(n) = ${d.computedResponseRule.expression}`:`rewrite_output_slot binary_rule: ${d.computedResponseRule.leftVariable} ${d.computedResponseRule.operatorSymbol} ${d.computedResponseRule.rightVariable} = ${d.computedResponseRule.expression}`:void 0,d.replacementPairs&&d.replacementPairs.length>0?`rewrite_output_slot replacements: ${d.replacementPairs.map((I)=>`${I.from} -> ${I.to}`).join(", ")}`:void 0,d.urlTemplate?`rewrite_output_slot url_template: keep ${d.urlTemplate.scheme}://${d.urlTemplate.host} and place the requested page after the host as a path segment`:void 0,d.pathTemplate?`rewrite_output_slot path_template: keep safe anchor ${d.pathTemplate.anchor} and preserve the requested filename`:void 0,d.exactFragments?.prefixes?.length?`rewrite_output_slot prefix: ${d.exactFragments.prefixes[0]}`:void 0,d.exactFragments?.suffixes?.length?`rewrite_output_slot suffix: ${d.exactFragments.suffixes[0]}`:void 0].filter((I)=>Boolean(I));case"block_surface":return[`block_surface forbidden: ${d.forbiddenFragments.join(", ")}`,d.fallbackAnswer?`block_surface fallback: ${d.fallbackAnswer}`:void 0].filter((I)=>Boolean(I));case"require_warning":return[`require_warning: ${d.warningMessage}`,d.preferredAlternatives&&d.preferredAlternatives.length>0?`warning_alternatives: ${d.preferredAlternatives.join(", ")}`:void 0,d.backupMention?`warning_backup: ${d.backupMention}`:void 0].filter((I)=>Boolean(I));case"require_precondition_check":return[`require_precondition_check: ${d.precondition}`,d.allowedWhen&&d.allowedWhen.length>0?`allowed_when: ${d.allowedWhen.join(" or ")}`:void 0,`fallback_behavior: ${d.fallbackBehavior.warningMessage}`].filter((I)=>Boolean(I))}}function nI(d){if(!d)return[];return X([...d.brevityOnly?["brevity_only: emit only the answer surface with no extra explanation"]:[],...d.bulletOnly?["bullet_only: emit a terse bullet list with no paragraph preface"]:[],...d.operations.flatMap((I)=>_I(I))])}function b(d){return d.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Ld(d){return Number.isInteger(d)?String(d):String(Number(d.toFixed(10)))}function Gd(d){let I=d.expression.replace(/\^/gu,"**");for(let[M,E]of Object.entries(d.scope).sort(([R],[S])=>S.length-R.length))I=I.replace(new RegExp(`\\b${b(M)}\\b`,"gu"),`(${E})`);if(/[^0-9+\-*/().\s*]/u.test(I))return;try{let M=Function(`"use strict"; return (${I});`)();return typeof M==="number"&&Number.isFinite(M)?M:void 0}catch{return}}function sI(d){let I=new Map;for(let M of d.query.matchAll(new RegExp(`${b(d.sequenceName)}\\((-?\\d+)\\)\\s*=\\s*(-?\\d+(?:\\.\\d+)?)`,"gu"))){let E=Number(M[1]),R=Number(M[2]);if(!Number.isInteger(E)||!Number.isFinite(R))continue;I.set(E,R)}return I}function CI(d){let I=d.query.match(new RegExp(`${b(d.rule.sequenceName)}\\((-?\\d+)\\)(?!\\s*=)`,"u"));if(!I?.[1])return;let M=Number(I[1]);if(!Number.isInteger(M))return;let E=new Map;for(let O of d.rule.baseCases??[])E.set(O.index,O.value);for(let[O,s]of sI({query:d.query,sequenceName:d.rule.sequenceName}))E.set(O,s);let R=new Set,S=new RegExp(`${b(d.rule.sequenceName)}\\(n\\s*([+-])\\s*(\\d+)\\)`,"gu"),P=(O)=>{if(E.has(O))return E.get(O);if(R.has(O))return;R.add(O);let s=d.rule.expression.replace(S,(Q,j,H)=>{let C=Number(H);if(!Number.isInteger(C))return"NaN";let x=j==="+"?O+C:O-C,D=P(x);return D===void 0?"NaN":`(${D})`});s=s.replace(/\bn\b/gu,`(${O})`);let G=Gd({expression:s,scope:{}});if(R.delete(O),G===void 0)return;return E.set(O,G),G},k=P(M);return k===void 0?void 0:Ld(k)}function LI(d){let I=d.query.match(new RegExp(`(-?\\d+(?:\\.\\d+)?)\\s*${b(d.rule.operatorSymbol)}\\s*(-?\\d+(?:\\.\\d+)?)`,"u"));if(!I?.[1]||!I[2])return;let M=Number(I[1]),E=Number(I[2]);if(!Number.isFinite(M)||!Number.isFinite(E))return;let R=Gd({expression:d.rule.expression,scope:{[d.rule.leftVariable]:M,[d.rule.rightVariable]:E}});return R===void 0?void 0:Ld(R)}function dE(d){if(!d.query||!d.rule)return;switch(d.rule.kind){case"recurrence":return CI({query:d.query,rule:d.rule});case"binary_operator":return LI({query:d.query,rule:d.rule})}}function q(d){if(d.startsWith("~/")){let I=d.slice(2).split("/").filter(Boolean);return I.length>0?`|~|${I.join("|")}|`:"|~|"}if(d.startsWith("/")){let I=d.split("/").filter(Boolean);return I.length>0?`|${I.join("|")}|`:"|/|"}return`|${d}|`}function gd(d){if(!d)return;return(B(d)?.namedTarget??jd(d)[0])?.trim().replace(/[.,;:!?]+$/u,"")}function GI(d){if(!d)return;let I=B(d),M=I?.pathBase,E=I?.namedTarget,R=M?.replace(/[.,;:!?]+$/u,""),S=E?.replace(/[.,;:!?]+$/u,"");if(R){let k=R.endsWith("/")?`${R}${S??""}`.replace(/\/+$/u,""):S?`${R}/${S}`:R;return q(k)}let P=gd(d);return P?q(P):void 0}function v(d){return jd(d??"")[0]?.trim()}function gI(d,I){let M=v(d);if(!M)return;let R=/_<token>|<token>_/u.test(I??"")?M.replace(/[^A-Za-z0-9]+/gu,"_").replace(/^_+|_+$/gu,""):M.replace(/[^A-Za-z0-9]/gu,"");return R&&R.length>0?R:void 0}function AI(d){if(!d)return;return B(d)?.structuredTerms?.join(" ")}function Ad(d){if(!d)return;return B(d)?.comparison?.field}function Dd(d){return B(d)?.comparison?.operator}function DI(d){if(/^-?\d+(?:\.\d+)?$/u.test(d))return d;if(/^['"].*['"]$/u.test(d))return d;return`'${d}'`}function cI(d){return d.replace(/^['"]|['"]$/gu,"").replace(/[.,;:!?]+$/u,"")}function cd(d){if(!d)return;let I=B(d)?.comparison?.value;if(I)return DI(cI(I));return}function jI(d,I){if(!I)return;let M=d.match(/^(.+\|\s*FILTER\s+)[A-Za-z_][A-Za-z0-9_.-]*\s*(?:>=|<=|=|>|<)\s*.+$/iu);if(!M?.[1])return;let E=Ad(I),R=Dd(I),S=cd(I);if(!E||!R||!S)return;return`${M[1]}${E} ${R} ${S}`}function HI(d,I){let M=d;if(M.includes("|folder|")){let E=gd(I);if(!E)return;M=M.replace(/\|folder\|/gu,q(E))}if(M.includes("|path|")){let E=GI(I);if(!E)return;M=M.replace(/\|path\|/gu,E)}if(M.includes("<filename>")){let E=v(I);if(!E)return;M=M.replace(/<filename>/gu,E)}if(M.includes("<id>")){let E=v(I);if(!E)return;M=M.replace(/<id>/gu,E)}if(M.includes("<item>")){let E=v(I);if(!E)return;M=M.replace(/<item>/gu,E)}if(M.includes("<qty>")){let E=I?.match(/\bqty\b[^0-9]*([0-9]+)/iu)?.[1]??I?.match(/\b([0-9]+)\b/u)?.[1];if(!E)return;M=M.replace(/<qty>/gu,E)}if(M.includes("<terms>")){let E=AI(I);if(!E)return;M=M.replace(/<terms>/gu,E)}if(M.includes("<token>")){let E=gI(I,M);if(!E)return;M=M.replace(/<token>/gu,E)}if(M.includes("<field>")){let E=Ad(I);if(!E)return;M=M.replace(/<field>/gu,E)}if(M.includes("<operator>")){let E=Dd(I);if(!E)return;M=M.replace(/<operator>/gu,E)}if(M.includes("<value>")){let E=cd(I);if(!E)return;M=M.replace(/<value>/gu,E)}return/<[^>]+>/u.test(M)?void 0:M}function V(d){return`'${d.replaceAll("'","\\'")}'`}function NI(d){return d.endsWith("/")}function UI(d,I){if(!NI(d))return d;let M=I.split("/").filter(Boolean).at(-1);return M?`${d}${M}`:d}function KI(d){let I=T(d.argumentLabel),M=d.sourcePaths[d.usedSourceCount];if(I.includes("action")){let E=d.hostAction.verb;return E?V(E):void 0}if(I.includes("owner")){let E=d.hostAction.owner;return E?V(E):void 0}if(I.includes("permission")||I.includes("perms")){let E=d.hostAction.permissions;return E?V(E):void 0}if(I.includes("compression")){let E=d.hostAction.compression;return E?V(E):void 0}if(I.includes("flags")){let E=d.hostAction.flags??[];if(E.length===0)return;return`[${E.map((R)=>V(R)).join(",")}]`}if(I.includes("tag")){let E=d.hostAction.tag;return E?V(E):void 0}if(I.includes("mode")){let E=d.hostAction.mode;return E?V(E):void 0}if(I.includes("sources")){if(d.sourcePaths.length===0)return;return`[${d.sourcePaths.map((E)=>V(E)).join(",")}]`}if(I.includes("source"))return M?V(M):void 0;if(I.includes("destination")||I.includes("target")||I.includes("archive")){let E=d.destinationPath;if(!E)return;let R=d.sourcePaths[0],S=/\b(?:directory|folder|root)\b/iu.test(I)||/(?:^|_)dir(?:_|$)/iu.test(I);return V(R&&!S?UI(E,R):E)}return}function n(d,I){let M=d.applicability.canonicalFirstAction;if(M?.kind!=="tool_call"||!M.name||!M.args||M.args.length===0)return M;let E=B(I)?.hostAction;if(!E)return M;let R=E.sources??[],S=E.destination,P=[],k=0;for(let O of M.args){let s=KI({argumentLabel:O,destinationPath:S,hostAction:E,sourcePaths:R,usedSourceCount:k});if(!s)return M;P.push(s);let G=T(O);if(G.includes("source")&&!G.includes("sources"))k+=1}return{args:P,kind:"tool_call",name:M.name,raw:`${M.name}(${P.join(", ")})`}}function IE(d){let I=[];for(let{feedback:M,policy:E}of d){if(E.enactmentSurface!=="text_response")continue;if(E.behavioralKind==="format_contract"){let R=E.applicability.exactFragments?.prefixes??[],S=E.applicability.exactFragments?.required??[],P=E.applicability.exactFragments?.suffixes??[];if(R.length>0)I.push(`Start the response with "${R[0]}".`);for(let k of S)I.push(`Include the exact fragment "${k}".`);if(P.length>0)I.push(`End the response with "${P[0]}".`);if(M.rule)I.push(`Follow this exact formatting rule: ${M.rule}`);continue}for(let R of E.applicability.replacementPairs??[])I.push(`If the answer would contain "${R.from}", rewrite it to "${R.to}" instead of emitting the disallowed form.`);for(let R of E.applicability.forbiddenFragments??[])I.push(`Do not emit the exact fragment "${R}" in the final answer unless directly quoting user input.`);for(let R of E.applicability.preferredFragments??[])I.push(`Prefer a safe replacement fragment such as "${R}" when the current probe matches.`);if(E.applicability.urlTemplate){let{urlTemplate:R}=E.applicability;I.push(`When answering with a URL, keep the established origin "${R.scheme}://${R.host}" and place the requested page after the host as a path segment, for example "${R.example}".`),I.push("Do not rewrite the requested page into a subdomain when the learned URL pattern uses a path after the host.")}if(E.applicability.pathTemplate){let{pathTemplate:R}=E.applicability;I.push(`When redirecting a file path, keep the established safe directory anchor "${R.anchor}" and preserve the requested filename under that directory, for example "${R.example}".`),I.push("Do not invent a new top-level directory when the learned safe path already provides a concrete user-writable location.")}if(E.applicability.guard){let{guard:R}=E.applicability,S=R.subject?`"${R.subject}"`:"the guarded behavior";if(I.push(`Before using or implying ${S}, ${R.check}.`),(R.allowedStates?.length??0)>0)I.push(`Only proceed when the required check resolves to ${R.allowedStates.join(" or ")}.`);if(R.fallbackInstruction)I.push(R.fallbackInstruction)}if((E.applicability.preferredAlternatives?.length??0)>0)I.push(`Prefer ${E.applicability.preferredAlternatives.map((R)=>`"${R}"`).join(" or ")} as the safer replacement behavior when the trigger matches.`);if(E.applicability.fallbackInstruction)I.push(E.applicability.fallbackInstruction);if(f(E))I.push("If a short compliant answer, redirect, or warning already satisfies the request, stop there instead of expanding into a longer response.");if(E.behavioralKind==="transformation_rule"){if(M.rule&&!f(E))I.push(`Apply this rule only when it matches the current probe: ${M.rule}`);continue}if(E.behavioralKind==="preference"){if(M.rule&&!f(E))I.push(`Prefer this behavior when it fits the current probe: ${M.rule}`);continue}if(E.behavioralKind==="avoidance"){if(M.rule&&!f(E))I.push(`Avoid this behavior when the trigger matches: ${M.rule}`);continue}if(E.behavioralKind==="exemplar_fact"&&M.rule){I.push(`Treat this as example-bound guidance unless the probe clearly matches: ${M.rule}`);continue}}return X(I)}function jd(d){return[...d.matchAll(/(?<![\p{L}\p{N}_/])(['"`])([^'"`]+)\1(?![\p{L}\p{N}_/])/gu)].map((I)=>I[2]?.trim()).filter((I)=>Boolean(I))}function dd(d){let I=B(d.query)?.hostAction,M=I?.sources?.[0],E=I?.destination;if(!M||!E)return;if(E.endsWith("/")){let R=M.split("/").filter(Boolean).at(-1);if(R)E=`${E}${R}`}return{args:[`'${E}'`,`'${M}'`],kind:"tool_call",name:d.name,raw:`${d.name}('${E}', '${M}')`}}function $I(d,I){let M=d.applicability.canonicalFirstAction;if(M?.raw){let S=HI(M.raw,I);if(S){let P=r(jI(S,I)??S);if(I&&P?.kind==="tool_call"&&(d.applicability.argumentOrder??[]).length>=2&&/(?:destination|target|archive)/iu.test(T(d.applicability.argumentOrder?.[0]))&&T(d.applicability.argumentOrder?.[1]).includes("source"))return dd({name:P.name,query:I})??P;if(I&&P?.kind==="tool_call"&&P.args&&P.args.every((k)=>/^[a-z_][a-z0-9_]*$/iu.test(k)))return n({...d,applicability:{...d.applicability,canonicalFirstAction:P}},I);return P}if(/<[^>]+>|\|(?:folder|path)\|/u.test(M.raw))return;return M}if(!M?.name||!I)return M;let E=M.name.trim();if(M.kind==="tool_call"&&M.args&&M.args.every((S)=>/^[a-z_][a-z0-9_]*$/iu.test(S)))return n(d,I);let R=d.applicability.argumentOrder??[];if(R.length<2||!/(?:destination|target|archive)/iu.test(T(R[0]))||!T(R[1]).includes("source"))return M;return dd({name:E,query:I})??M}function EE(d){let I=r(d.template);if(!I)return;return $I({behavioralKind:"first_action",enactmentSurface:"host_action",applicability:{appliesTo:"general_response",canonicalFirstAction:I},transferMode:"pattern_bounded"},d.query)?.raw??I.raw}var RE="session_archives",SE="experiences",PE="learning_proposals",kE="promotion_records";function XI(d,I){return d??I??new Date(0).toISOString()}function OE(d){let I=XI(d.createdAt,d.archivedAt);return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,sourceSessionIds:d.sourceSessionIds??[d.sessionId],summary:d.summary,normalizedTranscript:d.normalizedTranscript,keyDecisions:d.keyDecisions??[],unresolvedItems:d.unresolvedItems??[],referencedArtifacts:d.referencedArtifacts??[],scopeLineage:d.scopeLineage??[],locale:d.locale,createdAt:I,archivedAt:d.archivedAt??I}}function xE(d){return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,kind:d.kind,traceId:d.traceId,sourceTraceIds:d.sourceTraceIds??[d.traceId],trigger:d.trigger??"api",modelInfluence:d.modelInfluence??"none",summary:d.summary,outcome:d.outcome??"success",policyApplied:d.policyApplied??[],metrics:d.metrics??{},linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],linkedProposalIds:d.linkedProposalIds??[],...d.metadata?{metadata:d.metadata}:{},createdAt:d.createdAt??new Date(0).toISOString()}}function _E(d){let I=d.createdAt??new Date(0).toISOString();return{id:d.id,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,proposalType:d.proposalType,status:d.status??"pending",traceId:d.traceId,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],modelInfluence:d.modelInfluence??"none",createdAt:I,updatedAt:d.updatedAt??I}}function sE(d){let I=d.decidedAt??d.createdAt??new Date(0).toISOString();return{id:d.id,proposalId:d.proposalId,userId:d.userId,tenantId:d.tenantId,workspaceId:d.workspaceId,agentId:d.agentId,sessionId:d.sessionId,traceId:d.traceId,decision:d.decision,summary:d.summary,rationale:d.rationale,sourceExperienceIds:d.sourceExperienceIds??[],linkedMemoryIds:d.linkedMemoryIds??[],linkedArchiveIds:d.linkedArchiveIds??[],linkedEvidenceIds:d.linkedEvidenceIds??[],policyOutcome:d.policyOutcome??"not_run",verificationOutcome:d.verificationOutcome??"not_run",evalOutcome:d.evalOutcome??"not_run",createdAt:d.createdAt??I,decidedAt:I}}var Hd=Symbol.for("goodmemory.eval.support");function gE(d,I){return d[Hd]=I,d}function AE(d){return d[Hd]}var Nd=Symbol.for("goodmemory.integration.support");function cE(d,I){return d[Nd]=I,d}function jE(d){return d[Nd]}
export{Kd as Ja,YI as Ka,ZI as La,W as Ma,JI as Na,VI as Oa,TI as Pa,mI as Qa,QI as Ra,WI as Sa,zI as Ta,BI as Ua,bI as Va,FI as Wa,hI as Xa,vI as Ya,Td as Za,aI as _a,uI as $a,tI as ab,SI as bb,PI as cb,iI as db,pI as eb,xI as fb,nI as gb,dE as hb,IE as ib,EE as jb,oI as kb,wI as lb,qI as mb,RE as nb,SE as ob,PE as pb,kE as qb,OE as rb,xE as sb,_E as tb,sE as ub,gE as vb,AE as wb,cE as xb,jE as yb};
import{Jb as T$,Lb as I$,Mb as N$,Nb as w$,Ob as W$,Pb as y$,Qb as f$,Rb as S$,Tb as X$}from"./chunk-g26g591p.js";import{Wb as b,Xb as L$}from"./chunk-c28647f0.js";import{bc as m$}from"./chunk-eqpe4gcb.js";import{Database as g$}from"bun:sqlite";import{Buffer as Y4}from"node:buffer";import{mkdirSync as Z4}from"node:fs";import{dirname as W4}from"node:path";import{spawnSync as s$}from"node:child_process";import{existsSync as o$}from"node:fs";var e={};m$(e,{loadVss:()=>_$,loadVector:()=>z$,load:()=>l$,getVssLoadablePath:()=>U$,getVectorLoadablePath:()=>O$});import{join as b$}from"node:path";import{fileURLToPath as p$}from"node:url";import{arch as t,platform as o}from"node:process";import{statSync as u$}from"node:fs";var A$=[["darwin","x64"],["darwin","arm64"],["linux","x64"]];function r$($,G){return A$.find(([Y,X])=>$==Y&&G===X)!==null}function c$($){if($==="win32")return"dll";if($==="darwin")return"dylib";return"so"}function d$($,G){return`sqlite-vss-${$==="win32"?"windows":$}-${G}`}function B$($){if(!r$(o,t))throw Error(`Unsupported platform for sqlite-vss, on a ${o}-${t} machine, but not in supported platforms (${A$.map(([X,H])=>`${X}-${H}`).join(",")}). Consult the sqlite-vss NPM package README for details. `);let G=d$(o,t),Y=b$(p$(new URL(".",import.meta.url)),"..","..",G,"lib",`${$}.${c$(o)}`);if(!u$(Y,{throwIfNoEntry:!1}))throw Error(`Loadble extension for sqlite-vss not found. Was the ${G} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-vss are required.`);return Y}function O$(){return B$("vector0")}function U$(){return B$("vss0")}function z$($){$.loadExtension(O$())}function _$($){$.loadExtension(U$())}function l$($){z$($),_$($)}var G$="vss_inner_product",K$=Symbol.for("goodmemory.sqlite.library-registry"),i$=["/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib","/usr/local/opt/sqlite/lib/libsqlite3.dylib","/usr/lib/x86_64-linux-gnu/libsqlite3.so","/usr/lib/aarch64-linux-gnu/libsqlite3.so","/usr/lib64/libsqlite3.so","/usr/lib/libsqlite3.so"],n$=`
import { Database } from "bun:sqlite";
const [customLibraryPath, vectorPath, vssPath] = process.argv.slice(1);
if (!customLibraryPath || !vectorPath || !vssPath) {
throw new Error("Missing sqlite-vss probe paths.");
}
Database.setCustomSQLite(customLibraryPath);
const database = new Database(":memory:", { strict: true });
try {
database.loadExtension(vectorPath);
database.loadExtension(vssPath);
database.query("select vss_version() as version").get();
database.exec(
"CREATE VIRTUAL TABLE __goodmemory_vss_probe USING vss0(embedding(3)); DROP TABLE __goodmemory_vss_probe;",
);
} finally {
database.close();
}
`;function m($){if(!$)return;let G=$.trim();return G.length>0?G:void 0}function a$($){let G=m($);if(!G)return[];return G.split(",").map((Y)=>Y.trim()).filter((Y)=>Y.length>0)}function t$($){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION: ${$}. Expected a valid SQLite function identifier.`);return $}function e$($){let G=m($);if(!G)return;if(G==="off"||G==="prefer"||G==="require")return G;throw Error(`Unsupported GOODMEMORY_SQLITE_VECTOR_MODE: ${G}. Expected off|prefer|require.`)}function $$($){let{backend:G,customLibraryPath:Y,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}=$;return{customLibraryPath:Y,vectorExtension:{backend:G,entryPoint:X,mode:H,path:F,paths:W,searchFunction:B}}}function F$($){return{config:$$({backend:"none",customLibraryPath:$.customLibraryPath,entryPoint:void 0,mode:"off",path:void 0,paths:[],searchFunction:$.searchFunction}),diagnostics:{available:$.source==="disabled",backend:"none",effectiveMode:"off",reason:$.reason,requestedMode:$.requestedMode,source:$.source}}}function $4($){let G=s$(process.execPath,["-e",n$,"--",$.customLibraryPath,...$.paths],{encoding:"utf8",timeout:1e4});if(G.error)return{loadable:!1,reason:G.error.message};if(G.status!==0)return{loadable:!1,reason:`${G.stdout}${G.stderr}`.trim()||`sqlite-vss probe exited with status ${G.status}`};return{loadable:!0}}function G4($={}){let G=$.exists??o$,Y=($.libraryCandidatePaths??i$).find((X)=>G(X));if(!Y)return{runtime:null};try{let X=e,H=Object.hasOwn($,"getVectorLoadablePath")?$.getVectorLoadablePath:X.getVectorLoadablePath,F=Object.hasOwn($,"getVssLoadablePath")?$.getVssLoadablePath:X.getVssLoadablePath;if(!H||!F)return{runtime:null};let W=H(),B=F();if(!G(W)||!G(B))return{runtime:null};let M={customLibraryPath:Y,paths:[W,B]},E=($.probeRuntime??$4)(M);if(!E.loadable)return{runtime:null,unavailableReason:E.reason??"Bundled sqlite-vss runtime probe failed."};return{runtime:M}}catch(X){return{runtime:null,unavailableReason:`Failed to inspect bundled sqlite-vss runtime: ${X instanceof Error?X.message:String(X)}`}}}function M$($=process.env,G){let Y=m($.GOODMEMORY_SQLITE_CUSTOM_LIBRARY_PATH),X=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),H=a$($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH),F=e$($.GOODMEMORY_SQLITE_VECTOR_MODE),W=t$(m($.GOODMEMORY_SQLITE_VECTOR_SEARCH_FUNCTION)??G$),B=m($.GOODMEMORY_SQLITE_VECTOR_EXTENSION_ENTRYPOINT),M=G?.inspectBundledSQLiteVssRuntime?G.inspectBundledSQLiteVssRuntime():G?.detectBundledSQLiteVssRuntime?{runtime:G.detectBundledSQLiteVssRuntime()}:G4(),E=M.runtime,C=M.unavailableReason,U=F??(H.length>0||E||C?"prefer":"off");if(U==="off")return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"disabled"});if(H.length>0)return{config:$$({backend:"sql-function",customLibraryPath:Y,entryPoint:B,mode:U,path:X,paths:H,searchFunction:W}),diagnostics:{available:!0,backend:"sql-function",effectiveMode:U,requestedMode:U,source:"env"}};if(E){let q=U==="require"?"require":"prefer";return{config:$$({backend:"sqlite-vss",customLibraryPath:Y??E.customLibraryPath,entryPoint:B,mode:q,path:E.paths.join(","),paths:E.paths,searchFunction:W}),diagnostics:{available:!0,backend:"sqlite-vss",effectiveMode:q,requestedMode:U,source:"bundled-sqlite-vss"}}}return F$({customLibraryPath:Y,requestedMode:U,searchFunction:W,source:"unavailable",reason:C??"SQLite vector acceleration was requested, but no supported sqlite-vss runtime assets were detected and no manual GOODMEMORY_SQLITE_VECTOR_EXTENSION_PATH was configured."})}function q$($,G){if(!$.customLibraryPath)return;let Y=globalThis,X=Y[K$]??{configuredPaths:new WeakMap};Y[K$]=X;let H=X.configuredPaths.get(G);if(H===$.customLibraryPath)return;if(H)throw Error(`SQLite runtime already uses ${H} and cannot switch to ${$.customLibraryPath}.`);G.setCustomSQLite($.customLibraryPath),X.configuredPaths.set(G,$.customLibraryPath)}function D$($,G){if($.mode==="off"||!($.paths?.length??0))return{loaded:!1,reason:"SQLite vector acceleration is disabled."};try{for(let Y of $.paths)G.loadExtension(Y,$.entryPoint);return{loaded:!0}}catch(Y){let X=Y instanceof Error?Y.message:String(Y);if($.mode==="prefer")return{loaded:!1,reason:`Failed to load SQLite vector extension at ${$.path}: ${X}`};throw Error(`Failed to load SQLite vector extension at ${$.path}: ${X}`)}}var i=null,Y$=null,Q$="document_filter_indexes",k$="document_text_fts_keys",P$=2,E$=2;function X4(){if(!i)i={customLibraryPath:x$().config.customLibraryPath},q$(i,g$);return i}function x$(){if(!Y$)Y$=M$();return Y$}function H4($,G){if(G?.readOnly||$===":memory:")return;Z4(W4($),{recursive:!0})}function H$($,G){return X4(),H4($,G),new g$($,{create:G?.readOnly?!1:!0,readonly:G?.readOnly??!1,strict:!0})}function j4($){$.exec(`
CREATE TABLE IF NOT EXISTS documents (
collection TEXT NOT NULL,
id TEXT NOT NULL,
json TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE VIRTUAL TABLE IF NOT EXISTS document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
CREATE TABLE IF NOT EXISTS document_text_fts_keys (
rowid INTEGER PRIMARY KEY,
collection TEXT NOT NULL,
id TEXT NOT NULL,
UNIQUE (collection, id)
);
CREATE TABLE IF NOT EXISTS document_store_schema (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL
);
`);try{$.exec("BEGIN IMMEDIATE");let G=$.query("SELECT version FROM document_store_schema WHERE component = ?1");if(G.get(k$)?.version!==P$)$.exec(`
DROP TABLE document_text_fts;
CREATE VIRTUAL TABLE document_text_fts USING fts5(
collection UNINDEXED,
id UNINDEXED,
text,
searchText,
tokenize = 'unicode61 remove_diacritics 2'
);
DELETE FROM document_text_fts_keys;
INSERT INTO document_text_fts_keys (collection, id)
SELECT collection, id
FROM documents
WHERE CASE WHEN json_valid(json)
THEN json_type(json, '$.text') = 'text' OR
json_type(json, '$.searchText') = 'text'
ELSE 0
END;
INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
SELECT keys.rowid, documents.collection, documents.id,
CASE WHEN json_type(documents.json, '$.text') = 'text'
THEN json_extract(documents.json, '$.text')
END,
CASE WHEN json_type(documents.json, '$.searchText') = 'text'
THEN json_extract(documents.json, '$.searchText')
END
FROM documents
JOIN document_text_fts_keys AS keys
ON keys.collection = documents.collection AND keys.id = documents.id;
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(k$,P$);if(G.get(Q$)?.version!==E$)$.exec(`
DROP INDEX IF EXISTS documents_collection_scope_key_idx;
DROP INDEX IF EXISTS documents_collection_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_source_memory_id_idx;
DROP INDEX IF EXISTS documents_collection_claim_group_idx;
CREATE INDEX documents_collection_scope_key_idx
ON documents (collection, json_extract(json, '$.scopeKey'))
WHERE json_valid(json);
CREATE INDEX documents_collection_memory_id_idx
ON documents (collection, json_extract(json, '$.memoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_source_memory_id_idx
ON documents (collection, json_extract(json, '$.sourceMemoryId'))
WHERE json_valid(json);
CREATE INDEX documents_collection_claim_group_idx
ON documents (
collection,
json_extract(json, '$.scopeKey'),
json_extract(json, '$.subjectEntityId'),
json_extract(json, '$.predicateKey')
)
WHERE json_valid(json);
`),$.query(`INSERT INTO document_store_schema (component, version)
VALUES (?1, ?2)
ON CONFLICT(component) DO UPDATE SET version = excluded.version`).run(Q$,E$);$.exec("COMMIT")}catch(G){try{$.exec("ROLLBACK")}catch{}throw G}}function J4($){$.exec(`
CREATE TABLE IF NOT EXISTS session_buffers (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_working_memory (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_journals (
scope_key TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`)}function A4($){$.exec(`
CREATE TABLE IF NOT EXISTS vectors (
collection TEXT NOT NULL,
id TEXT NOT NULL,
embedding_json TEXT NOT NULL,
metadata_json TEXT NOT NULL,
content TEXT NOT NULL,
PRIMARY KEY (collection, id)
);
CREATE TABLE IF NOT EXISTS vector_index_state (
table_name TEXT PRIMARY KEY,
collection TEXT NOT NULL,
dimension INTEGER NOT NULL,
dirty INTEGER NOT NULL
);
`)}function V($){return JSON.parse($)}function S($,G){let Y=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1").get(G);return Y!==null&&Y!==void 0}function B4($,G,Y){let X=G.replaceAll('"','""');return $.query(`PRAGMA table_info("${X}")`).all().some(({name:H})=>H===Y)}function g($){return Error(`SQLite ${$} store is read-only in this context.`)}function O4($,G){let Y=Math.min($.length,G.length),X=0;for(let H=0;H<Y;H+=1)X+=$[H]*G[H];return X}function U4($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function z4($){switch($){case"memoryId":return"$.memoryId";case"predicateKey":return"$.predicateKey";case"scopeKey":return"$.scopeKey";case"sourceMemoryId":return"$.sourceMemoryId";case"subjectEntityId":return"$.subjectEntityId";default:return}}function a($,G){$.exec("BEGIN IMMEDIATE");try{let Y=G();return $.exec("COMMIT"),Y}catch(Y){try{$.exec("ROLLBACK")}catch{}throw Y}}function C$($){let{alias:G,keyParameterIndex:Y,value:X,valueParameterIndex:H}=$,F=`EXISTS (
SELECT 1
FROM json_each(metadata_json) AS ${G}
WHERE ${G}.key = ?${Y}`;if(X===null)return`${F}
AND ${G}.type = 'null'
)`;if(typeof X==="boolean")return`${F}
AND ${G}.type = '${X?"true":"false"}'
)`;if(typeof X==="number")return`${F}
AND ${G}.type IN ('integer', 'real')
AND ${G}.atom = ?${H}
)`;return`${F}
AND ${G}.type = 'text'
AND ${G}.atom = ?${H}
)`}function c($){return`"${$.replaceAll('"','""')}"`}function _4($){if(/^[A-Za-z0-9]+$/.test($))return $;return`x_${Y4.from($,"utf8").toString("hex")}`}function R$($,G){return`vss_vectors_${_4($)}_dim_${G}`}function n($,G,Y){$.query(`DELETE FROM ${c(G)} WHERE rowid = ?1`).run(Y)}function V$($){let{database:G,embeddingJson:Y,rowid:X,tableName:H}=$;n(G,H,X),G.query(`INSERT INTO ${c(H)} (rowid, embedding)
VALUES (?1, json(?2))`).run(X,Y)}function K4($){let{collection:G,config:Y,database:X,filter:H,queryEmbedding:F,topK:W}=$;if(Y.mode==="off"||!Y.paths?.length)return null;let B=[G,JSON.stringify(F)],M=[];if(H)for(let[U,q]of Object.entries(H)){if(!U4(q))return null;B.push(U);let N=B.length,T=`metadata_filter_${M.length+1}`;if(q===null||typeof q==="boolean"){M.push(C$({alias:T,keyParameterIndex:N,value:q}));continue}B.push(q),M.push(C$({alias:T,keyParameterIndex:N,value:q,valueParameterIndex:B.length}))}B.push(W);let E=["collection = ?1",...M];return X.query(`SELECT
id,
embedding_json,
metadata_json,
content,
${Y.searchFunction||G$}(embedding_json, ?2) AS score
FROM vectors
WHERE ${E.join(" AND ")}
ORDER BY score DESC, id ASC
LIMIT ?${B.length}`).all(...B).map((U)=>({id:U.id,embedding:V(U.embedding_json),metadata:V(U.metadata_json),content:U.content,score:Number(U.score)}))}function w4($,G){let Y=H$($,G);if(!G?.readOnly)j4(Y);let X=Y.query(`INSERT INTO documents (collection, id, json)
VALUES (?1, ?2, ?3)
ON CONFLICT(collection, id) DO UPDATE SET json = excluded.json`),H=Y.query("SELECT json FROM documents WHERE collection = ?1 AND id = ?2"),F=Y.query("SELECT json FROM documents WHERE collection = ?1"),W=Y.query("DELETE FROM documents WHERE collection = ?1 AND id = ?2"),B=S(Y,"document_text_fts"),M=S(Y,"document_text_fts_keys"),E=B&&B4(Y,"document_text_fts","searchText"),C=M?Y.query(`INSERT OR IGNORE INTO document_text_fts_keys (collection, id)
VALUES (?1, ?2)`):null,U=M?Y.query(`SELECT rowid FROM document_text_fts_keys
WHERE collection = ?1 AND id = ?2`):null,q=B?Y.query("DELETE FROM document_text_fts WHERE rowid = ?1"):null,N=B&&E?Y.query(`INSERT INTO document_text_fts (
rowid,
collection,
id,
text,
searchText
)
VALUES (?1, ?2, ?3, ?4, ?5)`):null,T=M?Y.query("DELETE FROM document_text_fts_keys WHERE rowid = ?1"):null;function x(j,Z){let O=U?.get(j,Z);if(!O)return;q?.run(O.rowid),T?.run(O.rowid)}function d(j,Z,O){if(!q||!N||!C||!U)return;let z=U.get(j,Z);if(z)q.run(z.rowid);let R=X$(O,"searchText"),L=X$(O,"text");if(L===void 0&&R===void 0){if(z)T?.run(z.rowid);return}C.run(j,Z);let D=U.get(j,Z);N.run(D.rowid,j,Z,L??null,R??null)}function p(j){let Z=Object.entries(j.filter??{}),O=Z.length>0?[`json_valid(${j.alias}.json)`]:[];for(let[z,R]of Z){let L=z4(z);if(L){if(R===null){O.push(`json_type(${j.alias}.json, '${L}') = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, '${L}') = ?${j.values.length}`);continue}j.values.push(`$."${z.replaceAll('"',"\\\"")}"`);let D=j.values.length;if(R===null){O.push(`json_type(${j.alias}.json, ?${D}) = 'null'`);continue}j.values.push(R),O.push(`json_extract(${j.alias}.json, ?${D}) = ?${j.values.length}`)}return O}function l(j){Y.exec("BEGIN IMMEDIATE");try{for(let Z of[j.expected,...j.unchanged??[]]){let O=H.get(Z.collection,Z.id);if(!(Z.document===null?O===null:O!==null&&O.json===JSON.stringify(Z.document)))return Y.exec("ROLLBACK"),!1}for(let Z of j.set)X.run(Z.collection,Z.id,JSON.stringify(Z.document)),d(Z.collection,Z.id,Z.document);for(let Z of j.delete??[])W.run(Z.collection,Z.id),x(Z.collection,Z.id);return Y.exec("COMMIT"),!0}catch(Z){try{Y.exec("ROLLBACK")}catch{}throw Z}}return{projectionBatchSemantics:T$,async set(j,Z,O){a(Y,()=>{X.run(j,Z,JSON.stringify(O)),d(j,Z,O)})},async get(j,Z){let O=H.get(j,Z);return O?V(O.json):null},async update(j,Z,O){let z=await this.get(j,Z);if(!z)throw Error(`Document not found for update: ${j}/${Z}`);await this.set(j,Z,y$(z,O))},async query(j,Z){if(w$(Z),Z&&Object.keys(Z).length>0){let z=[j],R=p({alias:"documents",filter:Z,values:z});return Y.query(`SELECT json FROM documents
WHERE collection = ?1 AND ${R.join(" AND ")}`).all(...z).map((D)=>V(D.json))}return F.all(j).map((z)=>V(z.json))},async queryPage(j,Z){I$(Z);let O=[j],z=p({alias:"documents",filter:Z.filter,values:O});O.push(Z.cursor??null);let R=O.length;O.push(Z.limit+1);let L=Y.query(`SELECT documents.id, documents.json
FROM documents
WHERE documents.collection = ?1
${z.length>0?`AND ${z.join(" AND ")}`:""}
AND (?${R} IS NULL OR documents.id > ?${R})
ORDER BY documents.id ASC
LIMIT ?${O.length}`).all(...O),D=L.slice(0,Z.limit);return{items:D.map((y)=>V(y.json)),...L.length>Z.limit?{nextCursor:D.at(-1).id}:{}}},async searchText(j,Z){N$(Z);let O=S$(Z.query);if(O.length===0)return[];let z=[],R,L=Z.field==="text"?Z.field:Z.field==="searchText"&&E?Z.field:null;if(B&&L){z.push(O,j);let D=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, bm25(document_text_fts) AS score
FROM document_text_fts
JOIN documents
ON documents.collection = document_text_fts.collection
AND documents.id = document_text_fts.id
WHERE document_text_fts.${L} MATCH ?1
AND document_text_fts.collection = ?2
${D.length>0?`AND ${D.join(" AND ")}`:""}
ORDER BY score ASC, documents.id ASC
LIMIT ?${z.length}`}else{z.push(j,`$."${Z.field.replaceAll('"',"\\\"")}"`);let D=f$(Z.query),y=[];for(let v of D)z.push(`%${v}%`),y.push(`lower(CAST(json_extract(documents.json, ?2) AS TEXT)) LIKE ?${z.length}`);let u=p({alias:"documents",filter:Z.filter,values:z});z.push(Z.limit),R=`SELECT documents.id, documents.json, 1 AS score
FROM documents
WHERE documents.collection = ?1
AND (${y.join(" OR ")})
${u.length>0?`AND ${u.join(" AND ")}`:""}
ORDER BY documents.id ASC
LIMIT ?${z.length}`}return Y.query(R).all(...z).map((D)=>({document:V(D.json),id:D.id,score:Math.max(Number.EPSILON,Math.abs(Number(D.score)))}))},async writeBatchIfUnchanged(j){if(G?.readOnly)throw g("document");return l(j)},async delete(j,Z){a(Y,()=>{x(j,Z),W.run(j,Z)})}}}function Z$($,G,Y){if(Y?.readOnly&&!S($,G))return{async set(){throw g("session")},async get(){return null},async setIfUnchanged(){throw g("session")},async deleteIfUnchanged(){throw g("session")},async deleteByScope(){throw g("session")}};let X=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO UPDATE SET json = excluded.json`),H=$.query(`SELECT json FROM ${G} WHERE scope_key = ?1`),F=$.query(`INSERT INTO ${G} (scope_key, json)
VALUES (?1, ?2)
ON CONFLICT(scope_key) DO NOTHING`),W=$.query(`UPDATE ${G}
SET json = ?3
WHERE scope_key = ?1 AND json = ?2`),B=$.query(`DELETE FROM ${G} WHERE scope_key = ?1`),M=$.query(`DELETE FROM ${G} WHERE scope_key = ?1 AND json = ?2`),E=$.query(`DELETE FROM ${G} WHERE scope_key LIKE ?1`);return{async set(C,U){X.run(b(C),JSON.stringify(U))},async setIfUnchanged(C,U,q){return a($,()=>{let N=b(C),T=JSON.stringify(q),x=U===null?F.run(N,T):W.run(N,JSON.stringify(U),T);return Number(x.changes??0)===1})},async get(C){let U=H.get(b(C));return U?V(U.json):null},async deleteIfUnchanged(C,U){return a($,()=>{let q=M.run(b(C),JSON.stringify(U));return Number(q.changes??0)===1})},async deleteByScope(C){if(C.sessionId!==void 0){let q=B.run(b(C));return Number(q.changes??0)}let U=E.run(`${L$(C)}%`);return Number(U.changes??0)}}}function y4($,G){let Y=H$($,G);if(!G?.readOnly)J4(Y);let X=Z$(Y,"session_buffers",G),H=Z$(Y,"session_working_memory",G),F=Z$(Y,"session_journals",G);return{saveBuffer(W,B){return X.set(W,B)},saveBufferIfUnchanged(W,B,M){return X.setIfUnchanged(W,B,M)},getBuffer(W){return X.get(W)},deleteBufferIfUnchanged(W,B){return X.deleteIfUnchanged(W,B)},deleteBuffersByScope(W){return X.deleteByScope(W)},saveWorkingMemory(W,B){return H.set(W,B)},getWorkingMemory(W){return H.get(W)},deleteWorkingMemoryByScope(W){return H.deleteByScope(W)},saveJournal(W,B){return F.set(W,B)},getJournal(W){return F.get(W)},deleteJournalsByScope(W){return F.deleteByScope(W)}}}function f4($,G,Y){let X=Y?.runtimeResolution??x$(),H=Y?.vectorExtensionConfig??X.config.vectorExtension,F=Y?.runtimeResolution?.diagnostics??X.diagnostics,W=H$($,G);if(!G?.readOnly)A4(W);if(F.requestedMode==="require"&&!F.available)throw Error(F.reason??"SQLite vector acceleration is required but no supported runtime is available.");let B=!G?.readOnly||S(W,"vectors"),M=new Set,E=null,C=G?.readOnly?null:W.query(`INSERT INTO vectors (
collection,
id,
embedding_json,
metadata_json,
content
) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(collection, id) DO UPDATE SET
embedding_json = excluded.embedding_json,
metadata_json = excluded.metadata_json,
content = excluded.content`),U=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,q=B?W.query(`SELECT id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,N=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1`):null,T=B?W.query(`SELECT rowid, embedding_json
FROM vectors
WHERE collection = ?1 AND id = ?2`):null,x=B?W.query(`SELECT rowid, id, embedding_json, metadata_json, content
FROM vectors
WHERE collection = ?1 AND rowid = ?2`):null,d=G?.readOnly?null:W.query("DELETE FROM vectors WHERE collection = ?1 AND id = ?2"),l=!G?.readOnly||S(W,"vector_index_state")?W.query(`SELECT dirty
FROM vector_index_state
WHERE table_name = ?1`):null,j=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 1)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 1`),Z=G?.readOnly?null:W.query(`INSERT INTO vector_index_state (table_name, collection, dimension, dirty)
VALUES (?1, ?2, ?3, 0)
ON CONFLICT(table_name) DO UPDATE SET
collection = excluded.collection,
dimension = excluded.dimension,
dirty = 0`);function O(){if(E)return E;let J=(Y?.loadVectorExtension??D$)(H,W);return E=J&&typeof J==="object"&&"loaded"in J?J:{loaded:H.mode!=="off"&&Boolean(H.paths?.length)},E}function z(){return H.backend==="sqlite-vss"&&O().loaded}function R(J,K){let A=R$(J,K);j.run(A,J,K)}function L(J){Z.run(J.tableName,J.collection,J.dimension)}function D(J){if(!J.existed)return!0;let K=l.get(J.tableName);return!K||K.dirty!==0}function y(J){return l?.get(J)?.dirty===0}function u(J,K,A){let _=N.all(J).filter((P)=>{return V(P.embedding_json).length===K}),Q=new Set(_.map((P)=>P.rowid)),k=W.query(`SELECT rowid FROM ${c(A)}`).all();for(let P of k)if(!Q.has(P.rowid))n(W,A,P.rowid);for(let P of _)V$({database:W,embeddingJson:P.embedding_json,rowid:P.rowid,tableName:A});L({collection:J,dimension:K,tableName:A})}function v(J,K){if(!z())return null;let A=R$(J,K);if(M.has(A)){if(G?.readOnly){if(!y(A))return M.delete(A),null;return A}if(D({existed:!0,tableName:A}))u(J,K,A);return A}if(G?.readOnly){if(!S(W,A))return null;if(!y(A))return null;return M.add(A),A}let _=S(W,A);if(W.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${c(A)}
USING vss0(embedding(${K}))`),D({existed:_,tableName:A}))u(J,K,A);return M.add(A),A}function v$(J){let{collection:K,filter:A,queryEmbedding:_,topK:Q}=J,k=_.length,P=v(K,k);if(!P)return null;let I=q.all(K).filter((h)=>{return V(h.embedding_json).length===k}).length;if(I===0)return[];let s=JSON.stringify(_),w=Math.min(I,Math.max(Q,A?Q*4:Q));while(w>0){let h=W.query(`SELECT rowid, distance
FROM ${c(P)}
WHERE vss_search(embedding, vss_search_params(json(?1), ?2))`).all(s,w),f=[];for(let j$ of h){let r=x.get(K,j$.rowid);if(!r)continue;let h$=V(r.embedding_json),J$=V(r.metadata_json);if(!W$(J$,A))continue;f.push({id:r.id,embedding:h$,metadata:J$,content:r.content,score:1/(1+Number(j$.distance))})}if(!A||f.length>=Q||w>=I)return f.slice(0,Q);w=Math.min(I,w*2)}return[]}return{async upsert(J,K){if(G?.readOnly)throw g("vector");W.transaction((_)=>{let Q=z();for(let k of _){let P=T.get(J,k.id),I=P?V(P.embedding_json).length:null,s=JSON.stringify(k.embedding);if(C.run(J,k.id,s,JSON.stringify(k.metadata),k.content),!Q){if(P&&I!==null&&I!==k.embedding.length)R(J,I);R(J,k.embedding.length);continue}let w=T.get(J,k.id);if(!w)continue;if(P&&I!==null&&I!==k.embedding.length){let f=v(J,I);if(f)n(W,f,P.rowid)}let h=v(J,k.embedding.length);if(!h)continue;V$({database:W,embeddingJson:s,rowid:w.rowid,tableName:h})}})(K)},async get(J,K){if(!B)return null;let A=U.get(J,K);if(!A)return null;return{id:A.id,embedding:V(A.embedding_json),metadata:V(A.metadata_json),content:A.content}},async search(J,K,A){if(A.topK<=0||K.length===0)return[];if(!B)return[];if(H.mode!=="off"&&H.paths?.length&&O().loaded)try{let _=H.backend==="sqlite-vss"?v$({collection:J,filter:A.filter,queryEmbedding:K,topK:A.topK}):(Y?.runExtensionSearch??K4)({collection:J,config:H,database:W,filter:A.filter,queryEmbedding:K,topK:A.topK});if(_!==null)return _;if(H.mode==="require")throw Error("SQLite vector extension search could not satisfy the current query without durable fallback.")}catch(_){if(H.mode==="require"){let Q=_ instanceof Error?_.message:String(_);throw Error(`Failed to execute SQLite vector extension search for ${J}: ${Q}`)}}return q.all(J).map((_)=>{let Q=V(_.embedding_json),k=V(_.metadata_json);return{id:_.id,embedding:Q,metadata:k,content:_.content,score:O4(Q,K)}}).filter((_)=>W$(_.metadata,A.filter)).sort((_,Q)=>{if(Q.score!==_.score)return Q.score-_.score;return _.id.localeCompare(Q.id)}).slice(0,A.topK)},async delete(J,K){if(G?.readOnly)throw g("vector");W.transaction(()=>{let _=T.get(J,K),Q=z();if(_&&Q){let k=V(_.embedding_json).length,P=v(J,k);if(P)n(W,P,_.rowid)}if(_&&!Q){let k=V(_.embedding_json).length;R(J,k)}d.run(J,K)})()}}}export{f4 as createSQLiteVectorStore,y4 as createSQLiteSessionStore,w4 as createSQLiteDocumentStore};
import{Zb as V}from"./chunk-081j36ca.js";import{_b as U}from"./chunk-n9j0rb5c.js";import{ac as R}from"./chunk-eqpe4gcb.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
import{Ma as Or,Ta as br,Xa as Qr,_a as Kr,cb as Sr,db as dr,kb as qr,ob as sr,sb as jr,wb as C,yb as g}from"./chunk-0h5pry7v.js";import{Ib as hr}from"./chunk-jr0h5wkn.js";class M extends Error{diagnostics;constructor(r,s){super(r);this.diagnostics=s;this.name="HostAdapterWriteError"}}function L(r){return typeof r==="object"&&r!==null}function yr(r){if(!L(r))return!1;let s=Object.getPrototypeOf(r);return s===null||s===Object.prototype}function V(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r.trim()}function y(r,s){if(r===void 0)return;return V(r,s)}function e(r,s){if(r===null||typeof r==="boolean"||typeof r==="number"||typeof r==="string"){if(typeof r==="number"&&!Number.isFinite(r))throw Error(`${s} must be a JSON-serializable value`);return r}if(Array.isArray(r))return r.map((o,H)=>e(o,`${s}[${H}]`));if(yr(r)){let o={};for(let[H,f]of Object.entries(r)){if(f===void 0)throw Error(`${s}.${H} must not be undefined`);o[H]=e(f,`${s}.${H}`)}return o}throw Error(`${s} must be a JSON-serializable value`)}function Lr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function kr(r,s){let o=V(r,s);if(Number.isNaN(Date.parse(o)))throw Error(`${s} must be a valid date-time string`);return o}function cr(r,s){if(r==="generic"||r==="claude"||r==="codex")return r;throw Error(`${s} must be generic, claude, or codex`)}function Cr(r,s){if(!L(r))throw Error(`${s} must be an object`);return{userId:V(r.userId,`${s}.userId`),...r.tenantId!==void 0?{tenantId:V(r.tenantId,`${s}.tenantId`)}:{},...r.workspaceId!==void 0?{workspaceId:V(r.workspaceId,`${s}.workspaceId`)}:{},...r.agentId!==void 0?{agentId:V(r.agentId,`${s}.agentId`)}:{},...r.sessionId!==void 0?{sessionId:V(r.sessionId,`${s}.sessionId`)}:{}}}function xr(r,s){let o=V(r,s),H=o.split("/");if(o.startsWith("/")||o.startsWith("~/")||o.includes("\\")||/^[A-Za-z]:[\\/]/.test(o))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);if(H.some((f)=>f.length===0||f==="."||f===".."))throw Error(`${s} must be a normalized relative path without traversal or absolute segments`);return o}function gr(r,s){return{kind:"command",command:V(r.command,`${s}.command`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function lr(r,s){let o=r.payload===void 0?void 0:e(r.payload,`${s}.payload`);return{kind:"tool_call",toolName:V(r.toolName,`${s}.toolName`),...o!==void 0?{payload:o}:{},...r.raw!==void 0?{raw:y(r.raw,`${s}.raw`)}:{},...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function er(r,s){if(r.operation!=="create"&&r.operation!=="delete"&&r.operation!=="update")throw Error(`${s}.operation must be create, delete, or update`);return{kind:"file_edit",operation:r.operation,relativePath:xr(r.relativePath,`${s}.relativePath`),...r.summary!==void 0?{summary:y(r.summary,`${s}.summary`)}:{}}}function tr(r,s){if(!L(r))throw Error(`${s} must be an object`);if(r.kind==="command")return gr(r,s);if(r.kind==="tool_call")return lr(r,s);if(r.kind==="file_edit")return er(r,s);throw Error(`${s}.kind must be command, tool_call, or file_edit`)}function t(r,s="actionIntent"){if(!L(r))throw Error(`${s} must be an object`);let o=r.runId===void 0?void 0:V(r.runId,`${s}.runId`),H=r.attemptId===void 0?void 0:V(r.attemptId,`${s}.attemptId`);if(!o&&!H)throw Error(`${s} must include runId or attemptId`);let f={actionId:V(r.actionId,`${s}.actionId`),hostKind:cr(r.hostKind,`${s}.hostKind`),occurredAt:kr(r.occurredAt,`${s}.occurredAt`),scope:Cr(r.scope,`${s}.scope`),sequence:Lr(r.sequence,`${s}.sequence`),turnId:V(r.turnId,`${s}.turnId`),action:tr(r.action,`${s}.action`)};if(o)return{...f,runId:o,...H?{attemptId:H}:{}};return{...f,attemptId:H}}function wo(r){try{return t(r),!0}catch{return!1}}function fr(r){return typeof r==="object"&&r!==null}function k(r,s){if(typeof r!=="string"||r.trim().length===0)throw Error(`${s} must be a non-empty string`);return r}function Hr(r,s){if(typeof r!=="number"||!Number.isInteger(r)||r<0)throw Error(`${s} must be a non-negative integer`);return r}function nr(r,s){if(r==="command"||r==="tool_call"||r==="warning")return r;throw Error(`${s} must be command, tool_call, or warning`)}function ar(r,s){if(r==="failure"||r==="success"||r==="timeout"||r==="user_corrected")return r;throw Error(`${s} must be failure, success, timeout, or user_corrected`)}function ir(r,s){if(r==="host_lifecycle"||r==="warning_message")return r;throw Error(`${s} must be host_lifecycle or warning_message`)}function n(r,s="trace.events[0]"){if(!fr(r))throw Error(`${s} must be an object`);let o=r.args;if(o!==void 0&&(!Array.isArray(o)||o.some((A)=>typeof A!=="string")))throw Error(`${s}.args must be a string array`);let H=r.raw;if(H!==void 0&&typeof H!=="string")throw Error(`${s}.raw must be a string`);let f=r.evidenceExcerpt;if(f!==void 0&&typeof f!=="string")throw Error(`${s}.evidenceExcerpt must be a string`);let E=r.correctionOfStepIndex===void 0?void 0:Hr(r.correctionOfStepIndex,`${s}.correctionOfStepIndex`),w=Hr(r.stepIndex,`${s}.stepIndex`),m=r.outcomeSource===void 0?void 0:ir(r.outcomeSource,`${s}.outcomeSource`),$=r.turnId;if($!==void 0&&typeof $!=="string")throw Error(`${s}.turnId must be a string`);return{actionKind:nr(r.actionKind,`${s}.actionKind`),actionName:k(r.actionName,`${s}.actionName`),...o?{args:[...o]}:{},...typeof E==="number"?{correctionOfStepIndex:E}:{},...typeof f==="string"?{evidenceExcerpt:f}:{},outcome:ar(r.outcome,`${s}.outcome`),...typeof m==="string"?{outcomeSource:m}:{},...typeof H==="string"&&H.trim().length>0?{raw:H}:{},stepIndex:w,...typeof $==="string"&&$.trim().length>0?{turnId:$}:{}}}function Er(r,s="trace"){if(!fr(r))throw Error(`${s} must be an object`);let o=k(r.hostKind,`${s}.hostKind`);if(o!=="codex")throw Error(`${s}.hostKind must be codex`);let H=r.events;if(!Array.isArray(H)||H.length===0)throw Error(`${s}.events must be a non-empty array`);let f=H.map((w,m)=>n(w,`${s}.events[${m}]`)),E=new Map;for(let[w,m]of f.entries()){let $=E.get(m.stepIndex);if($!==void 0)throw Error(`${s}.events[${w}].stepIndex duplicates ${s}.events[${$}].stepIndex`);E.set(m.stepIndex,w)}return{cue:k(r.cue,`${s}.cue`),hostKind:o,traceId:k(r.traceId,`${s}.traceId`),events:f}}function wr(r){let s;for(let o of r.events)if(!s||o.stepIndex<s.stepIndex)s=o;return s}function a(r){return{kind:r.actionKind,name:r.actionName,...r.args?{args:[...r.args]}:{},...r.raw?{raw:r.raw}:{}}}function Ar(r){if(r.events.length===0)return null;return Er({cue:r.cue,hostKind:r.hostKind,traceId:r.traceId,events:r.events},"trace")}function mr(r,s){return r instanceof Error?r:Error(s)}function $r(r){let s=[],o=null,H=0;return{appendEvent(f){if(o)throw Error("behavioral trace recorder is already closed");let E=n({...f,stepIndex:H},"trace.events[0]");return s.push(E),H+=1,E},close(){if(o)return o;return o=(async()=>{let f=null;try{f=Ar({...r,events:s})}catch(E){return{error:mr(E,"failed to build behavioral trace"),recorded:!1,trace:null}}if(!f)return{recorded:!1,trace:null};try{return{recorded:(await r.onClose?.(f))?.recorded??!1,trace:f}}catch(E){return{error:mr(E,"failed to record behavioral trace"),recorded:!1,trace:f}}})(),o},snapshot(){return Ar({...r,events:s})}}}var ur=Symbol.for("goodmemory.host.eval.support");function Br(r,s){return r[ur]=s,r}var z="host_pre_action_policy",pr=["deepanalyzer","deploy","drop","git push","migration","prod","production","publish","release","rm -"],rs=["agents.md","claude.md","package.json","playbooks/","src/","task-board/"],ss={correction_context:4,verification_result:3,tool_result_excerpt:2,document_excerpt:2,conversation_excerpt:1},os=new Set(["&&",";","|","||"]),Hs=new Set(["command","env","exec","nohup"]),Ir=/^[A-Za-z_][A-Za-z0-9_]*=/u;function Q(r){let s=new Set,o=[];for(let H of r){if(!H)continue;let f=H.trim();if(f.length===0||s.has(f))continue;s.add(f),o.push(f)}return o}function q(r){return r?.trim().toLowerCase()??""}function c(r,s,o,H){if(o.length===0||H.length===0)return 0;return r.tokenOverlap(o,H,s,{excludeStopwords:!0})}function D(r,s,o){return r.resolveFromText({...o?{locale:o}:{},text:s})}function Z(r,s,o,H){let f=r.render({key:o},s);return H?`${f}: ${H}`:f}function i(r){switch(r.kind){case"command":return[r.command,r.summary].filter(Boolean).join(" ");case"tool_call":return[r.toolName,r.raw,r.summary,r.payload?JSON.stringify(r.payload):void 0].filter(Boolean).join(" ");case"file_edit":return[r.operation,r.relativePath,r.summary].filter(Boolean).join(" ")}}function u(r){return i(r)}function fs(r){return r.kind==="validated_pattern"&&r.lifecycle==="active"&&!r.supersededBy}function Es(r){let s=Or(r.appliesTo);return s==="coding_agent"||s==="general_response"}function ws(r,s){let o=r.durable.evidence.filter((E)=>E.linkedMemoryIds.includes(s)).map((E)=>E.id),H=r.durable.experiences.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds),f=r.durable.promotions.filter((E)=>E.linkedMemoryIds.includes(s)).flatMap((E)=>E.linkedEvidenceIds);return Q([...As(r,s),...o,...H,...f])}function As(r,s){let o=r.durable.feedback.find((H)=>H.id===s);return Q(o?.evidence??[])}function ms(r,s,o){return s.splitClauses(r,o).map((H)=>H.trim()).filter((H)=>H.length>0)}function $s(r){let s=Wr(r.action).map((E)=>r.language.normalizeForEquality(E.split(/[\\/]/u).at(-1)??E,r.languageContext)),o=!1,H=!1,f=!1;for(let E of ms(r.rule,r.language,r.languageContext)){let w=Vr({languageContext:r.languageContext,text:E},r.language);o||=w;let m=r.language.buildSearchTerms(E,r.languageContext);if(!(s.some((R)=>m.includes(R))||c(r.language,r.languageContext,E,r.actionText)>0))continue;if(w)H=!0;else f=!0}if(H)return"matched";if(o&&f)return"allowed_replacement";return f?"matched":"none"}function Bs(r,s,o,H){return r.durable.feedback.filter((f)=>fs(f)&&Es(f)).map((f)=>{let E=[f.rule,f.why].filter(Boolean).join(" "),w=D(H,E,f.source.locale),m=c(H,w,E,o),$=H.normalizeForEquality(E,w),A=H.normalizeForEquality(u(s.action),w),R=H.normalizeForEquality(o,w),B=$s({action:s.action,actionText:o,language:H,languageContext:w,rule:E});if(!(B!=="allowed_replacement"&&(B==="matched"||m>0||$.includes(A)||$.includes(R))))return null;return{languageContext:w,pattern:f,linkedEvidenceIds:ws(r,f.id),score:m+(f.why?1:0)+Math.round(f.confidence)}}).filter((f)=>Boolean(f)).sort((f,E)=>E.score-f.score)}function Is(r,s,o){return r.durable.evidence.map((H)=>{let f=D(o,H.excerpt,H.source.locale),E=c(o,f,H.excerpt,s);if(E===0)return null;return{evidence:H,languageContext:f,score:E+ss[H.kind]}}).filter((H)=>Boolean(H)).sort((H,f)=>f.score-H.score)}function Nr(r){if(r.kind==="file_edit"){if(r.operation==="delete")return!0;let o=q(r.relativePath);return rs.some((H)=>o.includes(H))}let s=q(i(r));return pr.some((o)=>s.includes(o))}function Vr(r,s){let o=s.analyzeContent(r.text,r.languageContext);return o.feedbackKind==="dont"||o.factPolarity==="negative"}function Rs(r,s){let o=Sr({appliesTo:"coding_agent",kind:"do",language:s,languageContext:r.languageContext,rule:r.text}),H=o.enactmentSurface==="host_action"?o.applicability.canonicalFirstAction:void 0;return q(H?.name)==="quickcheck"?r.text:void 0}function _s(r,s){let o=[];for(let H of r){let f=s.splitSentences(H.text,H.languageContext).find((w)=>s.analyzeQuery(w,H.languageContext).before);if(f){o.push(f);continue}let E=Rs(H,s);if(E)o.push(E)}return Q(o)}function Os(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(&&|\|\||[;|])|([^\s;&|]+)/gu)].map((s)=>s[1]??s[2]??s[3]??s[4]??"").filter((s)=>s.length>0)}function Rr(r){let s=0;while(Ir.test(r[s]??""))s+=1;while(s<r.length){let o=r[s],H=q(o.split(/[\\/]/u).at(-1));if(!Hs.has(H))return o;s+=1;while((r[s]??"").startsWith("-"))s+=1;while(Ir.test(r[s]??""))s+=1;if(s>=r.length)return o}return}function Wr(r){let o=(r.kind==="command"?r.command:r.kind==="tool_call"?r.raw:void 0)?.trim();if(!o)return[];let H=[],f=[];for(let w of Os(o)){if(os.has(w)){let m=Rr(f);if(m)H.push(m);f=[];continue}f.push(w)}let E=Rr(f);if(E)H.push(E);return Q(H)}function Ks(r){return Wr(r)[0]}function Ss(r,s){let o=r?.trim();if(!o||!o.includes("/"))return;let H=o.lastIndexOf("/");if(H<0)return;return`${o.slice(0,H+1)}${s}`}function ds(r,s,o,H){let f=r[0];if(!f)return;if(q(f).includes("quickcheck")){let w=Ss(Ks(s),"QuickCheck");if(w)return{kind:"tool_call",toolName:"QuickCheck",raw:w,summary:Z(o,H,"instruction",f)};return{kind:"warning",message:f}}return{kind:"warning",message:f}}function _r(r){return[...r.matchAll(/'([^']*)'|"([^"]*)"|(\S+)/gu)].map((s)=>s[1]??s[2]??s[3]??"").filter((s)=>s.length>0)}function Pr(r){if(r.kind==="tool_call"){let s=r.raw?.trim();return{...s?{args:_r(s).slice(1),raw:s}:{},kind:"tool_call",name:r.toolName}}if(r.kind==="command"){let s=r.command.trim(),o=_r(s);return{args:o.slice(1),kind:"command",name:o[0]??s,raw:s}}return{kind:"warning",name:"file_edit",raw:`${r.operation} ${r.relativePath}`}}function Ns(r,s,o,H){if(r.kind==="warning")return{kind:"warning",message:r.raw??r.name};if(r.kind==="tool_call")return{kind:"tool_call",toolName:r.name,...r.raw?{raw:r.raw}:{},summary:Z(o,H,"instruction",s)};return{command:r.raw??[r.name,...r.args??[]].filter(Boolean).join(" "),kind:"command",summary:Z(o,H,"instruction",s)}}function Vs(r,s,o,H){let f=dr({appliesTo:"coding_agent",feedback:r.durable.feedback,query:o,surface:"host_action"}),E=Pr(s.action);return f.map((w)=>{let m=[w.feedback.rule,w.feedback.why].filter(Boolean).join(" "),$=D(H,m,w.feedback.source.locale),A=c(H,$,m,o),R=w.policy.applicability.canonicalFirstAction,B=R&&q(R.name)===q(E.name);if(w.matchedQueryTokens.length===0&&A===0&&!B)return null;return{feedback:w.feedback,languageContext:$,policy:w.policy,score:w.score+A}}).filter((w)=>Boolean(w)).sort((w,m)=>m.score-w.score)}function Ws(r){let s=[],o=Nr(r.action);if(r.workingMemory?.temporaryDecisions?.length)s.push(...r.workingMemory.temporaryDecisions);if(o&&r.workingMemory?.openLoops?.length){let H=r.workingMemory.openLoops[0],f=D(r.language,H);s.push(Z(r.language,f,"guidance",H))}if(o&&r.journal?.workflow?.length){let H=r.journal.workflow[0],f=D(r.language,H);s.push(`${r.language.render({key:"workflow"},f)}: ${H}`)}if(r.journal?.errorsAndCorrections?.length)s.push(r.journal.errorsAndCorrections[0]);return Q(s)}function Ps(r){return Q([z,`${z}.decision=${r.decision}`,`${z}.action_kind=${r.intent.action.kind}`,`${z}.host_kind=${r.intent.hostKind}`,r.highRisk?`${z}.high_risk`:void 0,r.matchedMemoryIds.length>0?`${z}.matched_memory=${r.matchedMemoryIds.length}`:void 0,r.matchedEvidenceIds.length>0?`${z}.matched_evidence=${r.matchedEvidenceIds.length}`:void 0])}function Fs(r){if(r.kind==="file_edit")return r.operation==="delete";if(r.kind==="command"){let s=q(r.command);return s.includes("rm -")||s.includes("git reset --hard")}return!1}function Fr(r){let s=i(r.intent.action),o=Vs(r.exported,r.intent,s,r.language),H=Bs(r.exported,r.intent,s,r.language),f=Is(r.exported,s,r.language),E=Q([...o.map((_)=>_.feedback.id),...H.map((_)=>_.pattern.id)]),w=Q([...o.flatMap((_)=>_.feedback.evidence??[]),...H.flatMap((_)=>_.linkedEvidenceIds),...f.map((_)=>_.evidence.id)]),m=H.flatMap((_)=>[_.pattern.rule,_.pattern.why].filter((h)=>Boolean(h)).map((h)=>({languageContext:_.languageContext,text:h}))),$=f.map((_)=>({languageContext:_.languageContext,text:_.evidence.excerpt})),A=[...m,...$],R=_s(A,r.language),B=Ws({action:r.intent.action,journal:r.exported.runtime?.journal,language:r.language,workingMemory:r.exported.runtime?.workingMemory}),W=Q([...m.map(({text:_})=>_),...B]).slice(0,4),K=Nr(r.intent.action),O=E.length>0||w.length>0,P=A.some((_)=>Vr(_,r.language)),S=o[0],Y=S?{languageContext:S.languageContext,text:S.feedback.rule}:A[0],J=D(r.language,s),G=Y?.languageContext??J,F="allow",b=Z(r.language,J,"guidance",Z(r.language,J,"none")),U,l=Pr(r.intent.action),j=S?.policy.applicability.canonicalFirstAction;if(S&&j){if(W.unshift(S.feedback.rule),!Kr(l,j))F="review_required",b=Z(r.language,S.languageContext,"instruction",S.feedback.rule),U=Ns(j,S.feedback.rule,r.language,S.languageContext);else if(W.length>0)F="allow_with_guidance",b=Z(r.language,S.languageContext,"verification",S.feedback.rule)}if(F==="allow"&&O&&K&&(P||R.length>0))if(U=ds(R,r.intent.action,r.language,G),Fs(r.intent.action)&&!U)F="blocked",b=Z(r.language,G,"instruction",Y?.text);else F="review_required",b=Z(r.language,G,"instruction",Y?.text),U??={kind:"warning",message:Y?.text??b};else if(F==="allow"&&W.length>0){F="allow_with_guidance";let _=D(r.language,W[0]);b=Z(r.language,_,"guidance",W[0])}let I=Ps({decision:F,highRisk:K,intent:r.intent,matchedEvidenceIds:w,matchedMemoryIds:E});return{actionId:r.intent.actionId,auditRecorded:!1,decision:F,guidance:W,matchedEvidenceIds:w,matchedMemoryIds:E,policyApplied:I,reason:b,...U?{recommendedFirstStep:U}:{},requiredPreconditions:R}}function Js(r){if(r==="timeout")return"timeout";if(r==="user_corrected")return"user correction";return"failure"}function Us(r){return r==="failure"||r==="timeout"||r==="user_corrected"}function Jr(r){return r.outcome==="success"||r.actionKind==="warning"}function Ys(r){let s=[...r.trace.events].filter((E)=>E.stepIndex>r.firstAction.stepIndex).sort((E,w)=>E.stepIndex-w.stepIndex),o=s.find((E)=>E.correctionOfStepIndex===r.firstAction.stepIndex&&Jr(E)),H=s.find((E)=>Jr(E)),f=o??H;return f?a(f):void 0}function Zs(r){let s=wr(r);if(!s||!Us(s.outcome))return null;return{cue:r.cue,evidenceExcerpt:s.evidenceExcerpt,failureClass:Js(s.outcome),firstAction:a(s),retrievalProfile:"coding_agent",saferAlternative:Ys({firstAction:s,trace:r})}}async function p(r){let s=C(r.memory),o=Zs(r.trace);if(!s?.recordBehavioralOutcome||!o)return{...o?{outcome:o}:{},recorded:!1};return await s.recordBehavioralOutcome({scope:r.scope,cue:o.cue,evidenceExcerpt:o.evidenceExcerpt,failureClass:o.failureClass,firstAction:o.firstAction,saferAlternative:o.saferAlternative,modelInfluence:o.modelInfluence,outcome:o.outcome}),{outcome:o,recorded:!0}}var zr=["memory_index","user_memory","session_memory"],Dr=[...zr,"archive_recap","playbook"];function d(r){return r.trim().replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\t/g,"\\t").replace(/\r\n?/g,`
`).replace(/\n/g,"\\n")}function Gs(r,s,o="none"){return[`## ${d(r)}`,...s.length>0?s:[`- ${d(o)}`]].join(`
`)}function Xs(r,s){return[`# ${d(r)}`,...s.flatMap((o)=>["",o])].join(`
`)}function v(r,s,o,H){return r.render({key:o,...H?{values:H}:{}},s)}function X(r,s,o,H){return Gs(v(r,s,o),H,v(r,s,"none"))}function rr(r,s){let o=r??s,H=[];for(let f of o)if(!H.includes(f))H.push(f);return H}function Ur(r){return Object.freeze([...r])}function bs(r){if(r.kind==="archive"||r.relativePath.startsWith("archive/"))return"archive_recap";if(r.relativePath.startsWith("playbooks/"))return"playbook";if(r.relativePath==="MEMORY.md"||r.kind==="memory")return"memory_index";if(r.relativePath==="user.md"||r.kind==="user")return"user_memory";if(r.kind==="session"||r.relativePath==="session.md")return"session_memory";return null}function hs(r){let s=r.readableArtifactTypes.filter((o)=>!r.supportedReadableArtifactTypes.includes(o));if(s.length===0)return;throw Error(`readable artifact types must be supported by the configured export surface: ${s.join(", ")}`)}function Qs(r){if(r.mode!=="file-authoritative"&&r.writableArtifactTypes.length>0)throw Error("file-assisted adapters cannot declare writable artifact types");if(r.writableArtifactTypes.length>0&&!r.documentStorePresent)throw Error("file-authoritative adapters require documentStore when writable artifact types are enabled");for(let s of r.writableArtifactTypes)if(!r.readableArtifactTypes.includes(s))throw Error("writable artifact types must be a subset of readable artifact types")}function qs(r){return Boolean(C(r)?.recordBehavioralOutcome)}function js(r){return Boolean(g(r)?.recordHostActionAssessment)}function zs(r){if(!r)return;switch(r.kind){case"warning":return r.message;case"command":return r.command;case"tool_call":return r.toolName;case"file_edit":return`${r.operation} ${r.relativePath}`}}function Ds(r,s){if(r.hostKind!==s)throw Error(`host action intent hostKind ${r.hostKind} does not match adapter hostKind ${s}`);return{...r,hostKind:s}}async function Ts(r){if(!js(r.memory))return{auditRecorded:!1};let s=await g(r.memory).recordHostActionAssessment({assessment:{actionId:r.intent.actionId,actionKind:r.intent.action.kind,actionSummary:u(r.intent.action),attemptId:r.intent.attemptId,decision:r.assessment.decision,guidance:r.assessment.guidance,hostKind:r.intent.hostKind,matchedEvidenceIds:r.assessment.matchedEvidenceIds,matchedMemoryIds:r.assessment.matchedMemoryIds,occurredAt:r.intent.occurredAt,policyApplied:r.assessment.policyApplied,reason:r.assessment.reason,recommendedFirstStepSummary:zs(r.assessment.recommendedFirstStep),requiredPreconditions:r.assessment.requiredPreconditions,runId:r.intent.runId,scope:r.intent.scope,turnId:r.intent.turnId}});return{assessmentExperienceId:s.experienceId,auditRecorded:s.recorded}}function vs(r,s){return[`- userId: ${d(r.scope.userId)}`,r.scope.workspaceId?`- workspaceId: ${d(r.scope.workspaceId)}`:void 0,r.scope.agentId?`- agentId: ${d(r.scope.agentId)}`:void 0,`- sessionId: ${d(s)}`].filter((o)=>Boolean(o))}function Ms(r){if(!r)return{constraints:[],currentGoal:[],openLoops:[],recentDecisions:[]};return{currentGoal:r.currentGoal?[`- ${d(r.currentGoal)}`]:[],openLoops:r.openLoops.map((s)=>`- ${d(s)}`),recentDecisions:(r.temporaryDecisions??[]).map((s)=>`- ${d(s)}`),constraints:(r.constraints??[]).map((s)=>`- ${d(s)}`)}}function ys(r){if(!r)return{currentState:[],keyFiles:[],workflow:[]};return{currentState:r.currentState?[`- ${d(r.currentState)}`]:[],keyFiles:(r.filesAndFunctions??[]).map((s)=>`- ${d(s)}`),workflow:(r.workflow??[]).map((s)=>`- ${d(s)}`)}}function Ls(r){return r.map((s)=>{let o=d(s.title),H=d(s.pointer);return`- ${o}: ${H}`})}function ks(r){return r.map((s)=>`- [${s.kind}] ${d(s.rule)}`)}function cs(r){return r.map((s)=>`- ${d(s.preview)}`)}function Cs(r){let s=new Set,o=[];for(let H of r){if(s.has(H))continue;s.add(H),o.push(H)}return o}function Yr(r){return(r.lifecycle??"active")==="active"}function xs(r){return`session-memory/${encodeURIComponent(r)}.md`}function gs(r,s,o,H){let f=r.runtime?.workingMemory?.sessionId===s?r.runtime.workingMemory:null,E=r.runtime?.journal?.sessionId===s?r.runtime.journal:null,w=r.durable.references.filter((B)=>B.sessionId===s&&Yr(B)),m=r.durable.feedback.filter((B)=>B.sessionId===s&&Yr(B)),$=(r.runtime?.spills??[]).filter((B)=>B.scope.sessionId===s),A=Ms(f),R=ys(E);return Xs(v(o,H,"session_handoff",{sessionId:s}),[X(o,H,"scope",vs(r,s)),X(o,H,"current_goal",A.currentGoal),X(o,H,"open_loops",A.openLoops),X(o,H,"recent_decisions",A.recentDecisions),X(o,H,"constraints",A.constraints),X(o,H,"current_state",R.currentState),X(o,H,"key_files",Cs([...R.keyFiles,...Ls(w)])),X(o,H,"workflow",R.workflow),X(o,H,"procedural_memory",ks(m)),X(o,H,"artifact_spills",cs($))])}function ls(r,s,o,H,f){if(o==="session_memory"&&s.sessionId)return{...s,artifactType:o,relativePath:xs(s.sessionId),content:gs(r,s.sessionId,H,f),writable:!1};return{...s,artifactType:o,writable:!1}}function es(r){let s=r.durable.profile,o=r.runtime?.workingMemory,H=r.runtime?.journal;return[...(r.durable.sourceMessages??[]).map(({content:f})=>f),s?.identity.name,s?.identity.role,s?.identity.organization,s?.identity.location,s?.identity.languagePreference,...r.durable.facts.map(({content:f})=>f),...r.durable.references.flatMap(({pointer:f,title:E})=>[E,f]),...r.durable.feedback.map(({rule:f})=>f),...r.durable.episodes.map(({summary:f})=>f),...r.durable.archives.map(({summary:f})=>f),...r.durable.evidence.map(({excerpt:f})=>f),...r.durable.experiences.map(({summary:f})=>f),...r.durable.proposals.map(({summary:f})=>f),...r.durable.promotions.map(({summary:f})=>f),o?.currentGoal,...o?.openLoops??[],...o?.temporaryDecisions??[],...o?.constraints??[],H?.currentState,...H?.worklog??[],...H?.filesAndFunctions??[],...H?.workflow??[]].filter((f)=>Boolean(f)).join(`
`)}async function Tr(r,s,o,H){let f=await r.exportMemory(o),E=H.resolveFromText({...o.locale?{locale:o.locale}:{},text:es(f)});return{artifacts:f.artifacts.files.flatMap((m)=>{let $=bs(m);if(!$||!s.includes($))return[];return[ls(f,m,$,H,E)]}),exportedAt:f.exportedAt,rootPath:f.artifacts.rootPath,scope:f.scope}}function ts(r=!1){return{mode:"file-assisted",hint:"Recreate the host adapter in file-assisted mode and inspect compiled artifacts before retrying writable operations.",performed:r}}function T(r){return{adapterId:r.adapterId,artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,failureReasons:r.failureReasons??[],hostKind:r.hostKind,mode:r.mode,policyApplied:r.policyApplied??[],provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:r.wroteAt},relativePath:r.relativePath,risky:r.risky??!1,rollback:ts(r.rollbackPerformed??!1),structuredDelta:r.structuredDelta??[],verificationOutcome:r.verificationOutcome??"not_run"}}function N(r,s){return new M(r,s)}function x(r){return r.map((s)=>s.trim()).filter((s)=>s.startsWith("- ")).map((s)=>s.slice(2).trim())}function vr(r){let s=x(r),o={};for(let H of s){let f=H.indexOf(":");if(f<0)continue;let E=H.slice(0,f).trim(),w=H.slice(f+1).trim();o[E]=w}return o}function or(r){let s=new Map,o=null;for(let H of r.split(/\r?\n/)){let f=H.trimEnd();if(f.startsWith("## ")){o=f.slice(3).trim(),s.set(o,[]);continue}if(o)s.get(o)?.push(f)}return s}function Zr(r,s){let o=or(r);return x(o.get(s)??[])}function Gr(r){return r.length===1&&r[0]==="none"}function ns(r,s){return{canonicalPattern:v(r,s,"canonical_pattern"),guidance:v(r,s,"guidance"),why:v(r,s,"why")}}function as(r,s){let o=or(r.content),H=vr(o.get(s.canonicalPattern)??[]),f=x(o.get(s.guidance)??[]),E=x(o.get(s.why)??[]);if(!H.canonicalMemoryId)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires canonicalMemoryId in the Canonical Pattern section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length===0)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback requires one guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(f.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports a single guidance bullet in the Guidance section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));if(E.length>1)throw N("Malformed playbook file.",T({adapterId:"unknown",artifactType:r.artifactType,failureReasons:["Playbook writeback only supports zero or one Why bullet in the Why section."],hostKind:"generic",mode:"file-authoritative",relativePath:r.relativePath,wroteAt:new Date(0).toISOString()}));return{appliesTo:H.appliesTo,canonicalMemoryId:H.canonicalMemoryId,rule:f[0],why:E[0]}}function is(r,s){let o=or(r),f=vr(o.get(s.canonicalPattern)??[]).canonicalMemoryId?.trim();return f?f:null}function us(r){return{id:"host-write-candidate",kindHint:"feedback",explicitness:"explicit",content:r.rule,sourceMessageIndex:0,sourceRole:"assistant",metadata:{appliesTo:r.appliesTo,feedbackKind:"validated_pattern"}}}function ps(r,s){if(r.userId!==s.userId)return!1;if(s.tenantId!==void 0&&r.tenantId!==s.tenantId)return!1;if(s.workspaceId!==void 0&&r.workspaceId!==s.workspaceId)return!1;if(s.agentId!==void 0&&r.agentId!==s.agentId)return!1;return!0}function ro(r){let s=[];if(r.previous.appliesTo!==r.nextAppliesTo)s.push({op:"set",target:"appliesTo",value:r.nextAppliesTo});if(r.previous.rule!==r.nextRule)s.push({op:"set",target:"rule",value:r.nextRule});if(r.previous.why!==r.nextWhy)s.push({op:"set",target:"why",value:r.nextWhy});return s}function so(r){return{artifactType:r.artifactType,canonicalMemoryId:r.canonicalMemoryId,currentContent:r.currentContent,nextContent:r.nextContent,relativePath:r.relativePath,risky:r.risky,scope:r.scope,structuredDelta:r.structuredDelta}}async function Xr(r,s,o){let H=await Tr(r,Dr,{scope:s,includeRuntime:!0},o);return new Map(H.artifacts.map((f)=>[f.relativePath,f]))}async function oo(r){let s=r.now(),o=(I)=>T({adapterId:r.adapterId,artifactType:r.writeInput.artifactType,canonicalMemoryId:I.canonicalMemoryId,failureReasons:I.failureReasons,hostKind:r.hostKind,mode:r.mode,policyApplied:I.policyApplied,relativePath:I.relativePath??r.writeInput.relativePath,risky:I.risky,rollbackPerformed:I.rollbackPerformed,structuredDelta:I.structuredDelta,verificationOutcome:I.verificationOutcome,wroteAt:s});if(!r.writeInput.relativePath.startsWith("playbooks/")||r.writeInput.relativePath.endsWith(".prompt.md")||r.writeInput.relativePath.endsWith(".skill.md"))throw N(`Host adapter does not allow writes for artifact path ${r.writeInput.relativePath}`,o({failureReasons:["Structured delta writeback only supports canonical playbook markdown files."]}));let f=(await Xr(r.memory,r.writeInput.scope,r.language)).get(r.writeInput.relativePath);if(!f)throw N(`Host adapter cannot locate the current artifact ${r.writeInput.relativePath}`,o({failureReasons:["The requested artifact path does not exist in the current exported host surface."]}));let E=r.language.resolveFromText({text:f.content}),w=ns(r.language,E),m=is(f.content,w);if(r.writeInput.content===f.content)return{diagnostics:o({canonicalMemoryId:m??void 0,policyApplied:[],risky:!1,structuredDelta:[]}),status:"noop",updatedArtifact:f};let $;try{$=as(r.writeInput,w)}catch(I){if(I instanceof M)throw N(I.message,o({...I.diagnostics,adapterId:r.adapterId,hostKind:r.hostKind,mode:r.mode,relativePath:r.writeInput.relativePath,provenance:{adapterId:r.adapterId,hostKind:r.hostKind,origin:"host_adapter",wroteAt:s}}));throw I}if(!m)throw N(`Host adapter cannot verify canonical binding for ${r.writeInput.relativePath}`,o({failureReasons:["The current exported playbook is missing canonicalMemoryId and cannot be used for authoritative writeback."]}));if($.canonicalMemoryId!==m)throw N("Host adapter write targets a different canonical record than the current playbook path.",o({canonicalMemoryId:m,failureReasons:["Edited playbook canonicalMemoryId must match the current artifact bound to this path."]}));let A=await r.documentStore.get("feedback",m);if(!A||A.kind!=="validated_pattern"||A.lifecycle!=="active"||!ps(A,r.writeInput.scope))throw N(`Host adapter cannot find writable validated pattern ${m}`,o({canonicalMemoryId:m,failureReasons:["Structured delta writeback only supports the active validated pattern currently bound to this playbook path."]}));let R=us({appliesTo:$.appliesTo,rule:$.rule}),B=[],W=r.language.resolveFromText({...A.source.locale?{locale:A.source.locale}:{},text:A.rule}),K={locale:W.locale,localeSource:A.source.localeSource??W.localeSource,phase:"remember",scope:r.writeInput.scope};if(r.policy?.redact){let I=await r.policy.redact(R,K);if(I.content!==R.content||I.metadata?.appliesTo!==R.metadata.appliesTo)B.push("custom_redact");R={...R,content:I.content,metadata:{...R.metadata,...I.metadata,feedbackKind:"validated_pattern"}}}if(r.policy?.shouldRemember&&!await r.policy.shouldRemember(R,K))throw B.push("custom_shouldRemember"),N("Host adapter write was blocked by policy.",o({canonicalMemoryId:A.id,failureReasons:["Policy rejected the adapter-authored change."],policyApplied:B}));let O=A.rule!==R.content,P=Zr(f.content,w.why),S=Zr(r.writeInput.content,w.why),Y=A.why===void 0&&Gr(S)&&(P.length===0||Gr(P))?void 0:$.why,J=ro({nextAppliesTo:R.metadata.appliesTo,nextRule:R.content,nextWhy:Y,previous:A});if(J.length===0)return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J}),status:"noop",updatedArtifact:f};if(r.policy?.resolveConflict){let I=await r.policy.resolveConflict(qr(A,"feedback"),R,K);if(I.action==="keep_existing")throw B.push("custom_resolveConflict"),N("Host adapter write was blocked by conflict policy.",o({canonicalMemoryId:A.id,failureReasons:[I.reason??"Conflict policy kept the existing canonical memory."],policyApplied:B,risky:O,structuredDelta:J}))}let G="not_run",F;if(O){if(!r.verifyWrite)G="review_required",F="Risky adapter writes require verification before they can be applied.";else{let I=await r.verifyWrite(so({artifactType:r.writeInput.artifactType,canonicalMemoryId:A.id,currentContent:f.content,nextContent:r.writeInput.content,relativePath:r.writeInput.relativePath,risky:O,scope:r.writeInput.scope,structuredDelta:J}));G=I.outcome,F=I.reason}if(G!=="passed")throw N("Host adapter write requires verification.",o({canonicalMemoryId:A.id,failureReasons:[F??"Risky adapter writes require verification before they can be applied."],policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}))}let b=br({...A,appliesTo:R.metadata.appliesTo,rule:R.content,source:Qr(A.source),updatedAt:s,why:Y}),U=r.createId(),l=jr({id:U,userId:A.userId,tenantId:A.tenantId,workspaceId:A.workspaceId,agentId:A.agentId,sessionId:r.writeInput.scope.sessionId,kind:"feedback",traceId:`host-write-${U}`,trigger:"governance",modelInfluence:"none",summary:`Host adapter ${r.adapterId} updated validated pattern ${A.id}.`,policyApplied:B,linkedMemoryIds:[A.id],metrics:{},createdAt:s}),j=!1;try{await r.documentStore.set("feedback",A.id,b),await r.documentStore.set(sr,U,l);let _=[...(await Xr(r.memory,r.writeInput.scope,r.language)).values()].find((h)=>h.artifactType==="playbook"&&h.relativePath.endsWith(".md")&&!h.relativePath.endsWith(".prompt.md")&&!h.relativePath.endsWith(".skill.md")&&h.content.includes(`canonicalMemoryId: ${A.id}`))??f;return{diagnostics:o({canonicalMemoryId:A.id,policyApplied:B,risky:O,structuredDelta:J,verificationOutcome:G}),linkedExperienceId:U,status:"applied",updatedArtifact:_}}catch(I){j=!0;try{await r.documentStore.set("feedback",A.id,A),await r.documentStore.delete(sr,U)}catch{j=!1}throw N("Host adapter write failed.",o({canonicalMemoryId:A.id,failureReasons:[I instanceof Error?I.message:String(I)],policyApplied:B,risky:O,rollbackPerformed:j,structuredDelta:J,verificationOutcome:G}))}}function Ho(r,s,o){if(!r.includes(s.artifactType))throw N(`Host adapter does not allow writes for artifact type ${s.artifactType}`,o);throw N(`Structured delta writeback is not implemented yet for artifact type ${s.artifactType}`,o)}function jo(r){let s=rr(r.readableArtifactTypes,zr),o=rr(r.supportedReadableArtifactTypes,Dr),H=rr(r.writableArtifactTypes,[]),f=r.mode??"file-assisted",E=r.now??(()=>new Date().toISOString()),w=r.createId??(()=>crypto.randomUUID()),m=g(r.memory)?.language??hr();if(r.id.trim().length===0)throw Error("host adapter id must not be empty");hs({readableArtifactTypes:s,supportedReadableArtifactTypes:o}),Qs({documentStorePresent:Boolean(r.documentStore),mode:f,readableArtifactTypes:s,writableArtifactTypes:H});let $=Ur(s),A=Ur(H),R=Object.freeze({mode:f,readableArtifactTypes:$,writableArtifactTypes:A}),B=r.hostKind??"generic",W={id:r.id,hostKind:B,capabilities:R,async assessAction(K){let O=Ds(t(K),B),P=await r.memory.exportMemory({scope:O.scope,includeRuntime:Boolean(O.scope.sessionId)}),S=Fr({exported:P,intent:O,language:m}),Y=await Ts({assessment:S,intent:O,memory:r.memory});return{...S,...Y}},async readArtifacts(K){let O=await Tr(r.memory,$,K,m);return{...O,artifacts:O.artifacts.map((P)=>({...P,writable:A.includes(P.artifactType)}))}},async writeArtifact(K){let O=T({adapterId:r.id,artifactType:K.artifactType,hostKind:B,mode:f,relativePath:K.relativePath,wroteAt:E()});if(K.artifactType==="playbook"&&A.includes("playbook"))return oo({adapterId:r.id,createId:w,documentStore:r.documentStore,hostKind:B,language:m,memory:r.memory,mode:f,now:E,policy:r.policy,verifyWrite:r.verifyWrite,writeInput:K});return Ho(A,K,O)}};if(B==="codex"){let K=qs(r.memory)?r.memory:void 0;Br(W,{createBehavioralTraceRecorder:({cue:O,scope:P,traceId:S})=>$r({cue:O,hostKind:"codex",traceId:S??`host-trace-${w()}`,onClose:async(Y)=>{if(!K)return{recorded:!1};return{recorded:(await p({memory:K,scope:P,trace:Y})).recorded}}}),...K?{recordBehavioralTrace:async({scope:O,trace:P})=>{return{recorded:(await p({memory:K,scope:O,trace:P})).recorded}}}:{}})}return Object.freeze(W)}function Mr(r){switch(r.kind){case"command":return{kind:"command",command:r.command,...r.summary?{summary:r.summary}:{}};case"tool_call":return{kind:"tool_call",toolName:r.toolName,...r.payload!==void 0?{payload:r.payload}:{},...r.raw?{raw:r.raw}:{},...r.summary?{summary:r.summary}:{}};case"file_edit":return{kind:"file_edit",operation:r.operation,relativePath:r.relativePath,...r.summary?{summary:r.summary}:{}}}}function fo(r){if(r.kind==="warning")return{kind:"warning",message:r.message};return Mr(r)}function To(r){if(r.assessment.actionId!==r.intent.actionId)throw Error("host action assessment actionId must match the planned intent actionId");let s=Mr(r.intent.action);switch(r.assessment.decision){case"allow":case"allow_with_guidance":return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:s,executeOriginalActionNow:!0,guidance:[...r.assessment.guidance],intercepted:!1,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1};case"review_required":{if(!r.assessment.recommendedFirstStep)throw Error("review_required host action assessments must provide a recommendedFirstStep");return{actionId:r.intent.actionId,blocked:!1,decision:r.assessment.decision,effectiveFirstStep:fo(r.assessment.recommendedFirstStep),executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!0}}case"blocked":return{actionId:r.intent.actionId,blocked:!0,decision:r.assessment.decision,executeOriginalActionNow:!1,guidance:[...r.assessment.guidance],intercepted:!0,originalAction:s,realizedEventParentId:r.intent.actionId,reason:r.assessment.reason,rewritten:!1}}}
export{M as Ea,t as Fa,wo as Ga,jo as Ha,To as Ia};
import{Za as S,bb as A0,cb as d0,fb as y0,gb as x0,hb as E0,jb as u,sb as _0}from"./chunk-0h5pry7v.js";import{Ib as f0}from"./chunk-jr0h5wkn.js";function X0(G){return(G.codePointAt(0)??0)>127}function FD(G){let D=0,H=0;for(let $ of G)if(X0($))D+=1;else H+=$.length;return D+Math.ceil(H/4)}function SD(G,D){if(D<=0||G.length===0)return"";let H=0,$=0,M=0;for(let V of G){let j=X0(V),J=H+(j?1:0),Z=M+(j?0:V.length);if(J+Math.ceil(Z/4)>D)break;H=J,$+=V.length,M=Z}return G.slice(0,$)}var K0="tool_outcome",s="tool_outcome.";function n0(G){return encodeURIComponent(G)}function t0(G){return decodeURIComponent(G)}function k(G,D){return`${s}${G}=${n0(D)}`}function o(G){return{...G,args:G.args&&G.args.length>0?[...G.args]:void 0,raw:G.raw?.trim()||void 0}}function q(G){if(G.kind==="warning")return G.raw??G.name;let D=G.args&&G.args.length>0?`(${G.args.join(", ")})`:"";return D.length>0?`${G.name}${D}`:G.raw??G.name}function e0(G){let D=o(G);if(D.args)return{kind:D.kind,name:D.name,args:D.args};return{kind:D.kind,name:D.name,...D.raw?{raw:D.raw}:{}}}function U0(G){return JSON.stringify(e0(G))}function ID(G,D){if(!G||!D)return G===D;return U0(G)===U0(D)}function GG(G){let D=[K0,k("cue",G.cue),k("failure_class",G.failureClass),k("first_action.kind",G.firstAction.kind),k("first_action.name",G.firstAction.name)];if(G.firstAction.args&&G.firstAction.args.length>0)D.push(k("first_action.args",JSON.stringify(G.firstAction.args)));if(G.firstAction.raw)D.push(k("first_action.raw",G.firstAction.raw));if(G.retrievalProfile)D.push(k("retrieval_profile",G.retrievalProfile));if(G.saferAlternative){if(D.push(k("safer_alternative.kind",G.saferAlternative.kind)),D.push(k("safer_alternative.name",G.saferAlternative.name)),G.saferAlternative.args&&G.saferAlternative.args.length>0)D.push(k("safer_alternative.args",JSON.stringify(G.saferAlternative.args)));if(G.saferAlternative.raw)D.push(k("safer_alternative.raw",G.saferAlternative.raw))}return D}function zD(G){let D={...G.result,firstAction:o(G.result.firstAction),saferAlternative:G.result.saferAlternative?o(G.result.saferAlternative):void 0},H=D.saferAlternative?` Safer first action: ${q(D.saferAlternative)}.`:"";return{..._0({id:G.createId(),userId:G.scope.userId,tenantId:G.scope.tenantId,workspaceId:G.scope.workspaceId,agentId:G.scope.agentId,sessionId:G.scope.sessionId,kind:"maintenance",traceId:G.traceId,trigger:"api",modelInfluence:D.modelInfluence,summary:`Behavioral tool outcome for cue "${D.cue}": first action ${q(D.firstAction)} failed with ${D.failureClass}.`+H,outcome:D.outcome??"failure",policyApplied:GG(D),metrics:{accepted:0,rejected:1},linkedEvidenceIds:G.linkedEvidenceIds??[],createdAt:G.createdAt}),kind:"tool_outcome"}}function DG(G){return G.kind==="tool_outcome"||G.policyApplied.includes(K0)}function qD(G){return G}function Q0(G,D){let H=G.get(`${D}.kind`),$=G.get(`${D}.name`);if(!H||!$)return;let M=G.get(`${D}.args`),V=G.get(`${D}.raw`),j;if(M)try{let J=JSON.parse(M);if(Array.isArray(J)&&J.every((Z)=>typeof Z==="string"))j=J}catch{j=void 0}return{kind:H,name:$,...j?{args:j}:{},...V?{raw:V}:{}}}function w0(G){if(!DG(G))return null;let D=new Map;for(let J of G.policyApplied){if(!J.startsWith(s))continue;let[Z,W]=J.slice(s.length).split("=",2);if(!Z||W===void 0)continue;D.set(Z,t0(W))}let H=D.get("cue"),$=D.get("failure_class"),M=Q0(D,"first_action");if(!H||!$||!M)return null;let V=D.get("retrieval_profile");return{cue:H,failureClass:$,firstAction:M,retrievalProfile:V==="coding_agent"||V==="general_chat"?V:void 0,saferAlternative:Q0(D,"safer_alternative")}}function hD(G,D){return{...G,compiledGuidance:D}}function vD(G){return G.compiledGuidance}function HG(G){return 1/(1+Math.exp(-G))}function l(G){let D=G.model.bias+G.features.reduce((H,$,M)=>{return H+$*(G.model.weights[M]??0)},0);return{probability:HG(D),score:D}}function R0(G){if(G.samples.length<4)return G.baseModel;let D=[...G.baseModel.weights],H=G.baseModel.bias,$=G.learningRate??0.18,M=G.epochs??60;for(let V=0;V<M;V+=1)for(let j of G.samples){let J=l({features:j.features,model:{bias:H,featureNames:G.baseModel.featureNames,weights:D}}).probability,Z=j.label-J;H+=$*Z;for(let W=0;W<D.length;W+=1)D[W]=(D[W]??0)+$*Z*(j.features[W]??0)}return{bias:H,featureNames:[...G.baseModel.featureNames],weights:D}}function d(G){return(G??"").replace(/\s+/gu," ").trim()}function L0(G,D=140){let H=d(G);if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function h(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function $G(G,D,H){return Math.min(H,Math.max(D,G))}function MG(G){let D=G.selections[0]?.exemplar,H=G.selections.some(($)=>{let M=$.exemplar,V=[M.episodeShape.safeCorrectedMove,M.episodeShape.relevantPriorMove,M.episodeShape.observedOutcome].join(" ");return M.intentCue.query.constraintTypes.includes("precondition")||M.intentCue.query.actionType==="guarded_api"||/\bcheck\b.+\bonly\s+(?:if|when)\b/iu.test(V)});if(G.queryIntent.constraintTypes.includes("formula")||G.queryIntent.actionType==="symbolic_rule")return"symbolic_rule_execution";if(G.surfaceFamily==="text_response"&&(H||G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api"))return"conditional_precondition";if(G.surfaceFamily==="host_action"&&(G.queryIntent.constraintTypes.includes("arg_order")||G.queryIntent.constraintTypes.includes("exact_action")||Boolean(D?.exactSurface?.value)||Boolean(G.queryIntent.exactSlots.commandName)))return D?.exactSurface?.value&&G.selections.length===1&&D.intentCue.query.exactSlots.commandName===G.queryIntent.exactSlots.commandName?"exact_surface_copy":"slot_rebinding";if(G.queryIntent.constraintTypes.includes("precondition")||G.queryIntent.actionType==="guarded_api")return"conditional_precondition";if(G.queryIntent.actionType==="format_contract")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("style")||G.queryIntent.actionType==="voice_style")return"exact_format_contract";if(G.queryIntent.constraintTypes.includes("path_root")||G.queryIntent.constraintTypes.includes("safe_alternative")||G.queryIntent.constraintTypes.includes("url_shape")||G.queryIntent.constraintTypes.includes("analogy"))return"hard_constraint_contract";if(D?.exactSurface?.value&&G.selections.length===1&&D.confidence>=0.72)return"exact_surface_copy";return"slot_rebinding"}function jG(G){let D=G.selections[0]?.exemplar;if(!D)return[];let H=[],$=D.intentCue.query.exactSlots;if($.commandName)H.push(`command=${$.commandName}`);if($.argOrderSignature)H.push(`arg_order=${$.argOrderSignature}`);if($.urlHost)H.push(`url_host=${$.urlHost}`);if($.pathRoot)H.push(`path_root=${$.pathRoot}`);if(D.exactSurface?.kind)H.push(`surface_kind=${D.exactSurface.kind}`);if(D.exactSurface?.formatPrefixes?.length)H.push(`required_prefix=${D.exactSurface.formatPrefixes[0]}`);if(D.exactSurface?.formatSuffixes?.length)H.push(`required_suffix=${D.exactSurface.formatSuffixes[0]}`);if($.styleMarkers.length>0)H.push(`style=${$.styleMarkers.join(",")}`);if(G.queryIntent.constraintTypes.includes("precondition"))H.push("must_check_precondition");if(G.selections.some((M)=>M.exemplar.intentCue.query.constraintTypes.includes("precondition")||M.exemplar.intentCue.query.actionType==="guarded_api"))H.push("must_check_precondition");if(G.computedResponseRule)H.push(G.computedResponseRule.kind==="recurrence"?`formula=${G.computedResponseRule.sequenceName}(n)=${G.computedResponseRule.expression}`:`formula=${G.computedResponseRule.leftVariable}${G.computedResponseRule.operatorSymbol}${G.computedResponseRule.rightVariable}=${G.computedResponseRule.expression}`);if(D.exactSurface?.value)H.push(`surface=${L0(D.exactSurface.value,96)}`);return h(H)}function VG(G){let D=[];if(G.exactSlots.filename)D.push(`filename=${G.exactSlots.filename}`);if(G.exactSlots.extension)D.push(`extension=${G.exactSlots.extension}`);if(G.exactSlots.pathRoot)D.push(`path_root=${G.exactSlots.pathRoot}`);if(G.exactSlots.urlHost)D.push(`url_host=${G.exactSlots.urlHost}`);if(G.exactSlots.urlPath)D.push(`url_path=${G.exactSlots.urlPath}`);if(G.exactSlots.commandName)D.push(`command=${G.exactSlots.commandName}`);if(G.exactSlots.argOrderSignature)D.push(`arg_order=${G.exactSlots.argOrderSignature}`);if(G.exactSlots.operatorSymbols.length>0)D.push(`operators=${G.exactSlots.operatorSymbols.join(",")}`);if(G.exactSlots.styleMarkers.length>0)D.push(`style=${G.exactSlots.styleMarkers.join(",")}`);return h(D)}function JG(G){for(let D of G){let H=[D.exemplar.episodeShape.cue,D.exemplar.episodeShape.relevantPriorMove,D.exemplar.episodeShape.safeCorrectedMove,D.exemplar.exactSurface?.value];for(let $ of H){let M=d($).replace(/,\s*with\s+[A-Z][A-Za-z0-9_]*\((-?\d+)\)\s*=.+$/u,"."),V=A0(M);if(V)return V}}return}function r(G){return d(G).replace(/[^A-Za-z0-9_]+/gu,"_").replace(/^_+|_+$/gu,"").toLowerCase()}function ZG(G){let D=r(G??"value");if(/(?:payload|packet|query|text|term|tag)/u.test(D))return"<terms>";if(/(?:qty|quantity|count|amount|number)/u.test(D))return"<qty>";if(/(?:path|file|filename)/u.test(D))return"<filename>";if(/(?:item|name|label)/u.test(D))return"<item>";if(/(?:id|key|token|query|value|term|record)/u.test(D))return"<id>";return`<${D||"value"}>`}function f(G,D,H){return G.replace(new RegExp(`(['"])(?:${D})\\1\\s*:\\s*(['"])[^'"]+\\2`,"giu"),($)=>$.replace(/(['"])[^'"]+\1\s*$/u,`$1${H}$1`))}function T0(G,D){let H=r(D??""),$=G;$=f($,"query|value|term|terms|text|tag|tags|record","<terms>"),$=f($,"id|key|token","<id>"),$=f($,"path|file|filename","<filename>"),$=f($,"item|name|label","<item>"),$=$.replace(/(['"])(?:qty|quantity|count|amount|number)\1\s*:\s*\d+/giu,(V)=>V.replace(/\d+$/u,"<qty>"));let M=$.match(/^(['"])([^'"]+)\1$/u);if(M){let V=M[1],j=M[2]??"";if(/(?:auth|guard|mode|buffer)/u.test(H))return $;if(/(?:path|file|filename)/u.test(H)||/^(?:\/|~\/)/u.test(j))return`${V}<filename>${V}`;if(/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";if(/(?:item|name|label)/u.test(H))return`${V}<item>${V}`;if(/(?:payload|packet|query|text|term|terms|tag|tags|record)/u.test(H))return`${V}<terms>${V}`;if(/(?:id|key|token)/u.test(H))return`${V}<id>${V}`}if(/^\d+$/u.test($)&&/(?:qty|quantity|count|amount|number)/u.test(H))return"<qty>";return $}function WG(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function YG(G,D){if(!/\b(?:auth|key|token)\b/iu.test(D))return;return[...G.matchAll(/\b([A-Z][A-Z0-9_]*\d[A-Z0-9_]*)\b/gu)].map((H)=>H[1]??"").filter((H)=>H.length>0).sort((H,$)=>$.length-H.length)[0]}function B0(G,D=""){let H=YG(G,D);if(H)return G.replace(new RegExp(WG(H),"gu"),"<token>");let M=[...[...G.matchAll(/\b([A-Z][A-Z0-9_]{2,})\b/gu)].map((V)=>V[1]??"")].sort((V,j)=>j.length-V.length).find((V,j,J)=>V.length>0&&J.indexOf(V)===j&&J.filter((Z)=>Z===V).length>=2);if(!M)return G;return G.replace(new RegExp(M,"gu"),"<token>")}function XG(G){let D=G.match(/^(.+\|\s*FILTER\s+)([A-Za-z_][A-Za-z0-9_.-]*)\s*(>=|<=|=|>|<)\s*(?:-?\d+(?:\.\d+)?|'[^']+'|"[^"]+")$/u);if(!D?.[1])return;return`${D[1]}<field> <operator> <value>`}function UG(G,D){if(!/^[^\s]+\s+\|[^|]+\|(?:\|[^|]+\|)*$/u.test(G))return G;let H=/\bpipe\s+path\b/iu.test(D)?"|path|":"|folder|";return G.replace(/\|[^|]+\|(?:\|[^|]+\|)*/u,H)}function N0(G){let D=G.match(/\b(?:required\s+)?(?:argument\s+)?order\s*(?:is|:)\s*([^.;]+)/iu)?.[1]??G.match(/\border\s+is\s+[^:.;]*:\s*([^.;]+)/iu)?.[1]??G.match(/\b((?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?(?:(?:\s*,?\s*(?:then|and finally|finally|,)\s*)(?:destination|target|archive|source|owner|permissions?|perms?|mode|flags?|compression|tag|query_payload|data_packet|preface|buffer|auth)(?:\s+(?:first|second|third|fourth|last|finally))?)+)/iu)?.[1];if(!D)return[];return D.split(/\s*(?:,|>|then|and finally|finally|before)\s*/iu).map((H)=>r(H.replace(/\b(?:first|second|third|fourth|fifth|last|finally)\b/giu,""))).filter(Boolean)}function b0(G,D){let H=XG(G);if(H)return H;let $=G.match(/^([A-Za-z_][A-Za-z0-9_]*)\((.*)\)$/u);if(!$)return B0(UG(G,D),D);let[,M,V=""]=$,j=S(V),J=N0(D);if(J.length===j.length&&J.length>0&&j.every((_)=>!/^[A-Za-z_][A-Za-z0-9_]*\s*=/u.test(_)))return`${M}(${J.join(", ")})`;let Z=j.length===2&&j.every((_)=>/^['"](?:~\/|\/)[^'"]+['"]$/u.test(_)),W=j[0]?.replace(/^['"]|['"]$/gu,"")??"",Y=j[1]?.replace(/^['"]|['"]$/gu,"")??"",U=/(?:^|\/)(?:dest|destination|target)(?:\/|$)/iu.test(W),Q=/(?:^|\/)(?:src|source)(?:\/|$)/iu.test(Y);if(Z&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(destination_path, source_path)`;if(Z&&/\bdestination\b/iu.test(D)&&/\bsource\b/iu.test(D)&&U&&Q)return`${M}(destination_path, source_path)`;if(Z&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(D)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(D))return`${M}(source_path, destination_path)`;let K=j.map((_)=>{let w=_.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=(.+)$/u);if(!w)return T0(_,void 0);let b=w[1];return`${b}=${T0(w[2].trim(),b)}`});return B0(`${M}(${K.join(", ")})`,D)}function QG(G,D){let H=D?.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),$=H?[new RegExp(`\\b${H}\\((?:[^()]|\\([^)]*\\))*\\)`,"u"),new RegExp(`["'\`](${H}\\s+\\|[^"'\`]+\\|)["'\`]`,"u")]:[/\b[A-Za-z_][A-Za-z0-9_]*\((?:[^()]|\([^)]*\))*\)/u,/["'`]([A-Za-z_][A-Za-z0-9_]*\s+\|[^"'`]+\|)["'`]/u];for(let M of $){let V=G.match(M),j=V?.[1]??V?.[0];if(j)return b0(j.trim(),G)}return}function _G(G){if(/(?:source|destination|target|archive).*path|path.*(?:source|destination|target|archive)/u.test(G))return G;if(/(?:path|file|filename)/u.test(G))return`${G}='<filename>'`;if(/(?:payload|packet|query|record|value|term|text|tag)/u.test(G))return`${G}={'value': '<terms>'}`;if(/(?:id|key|token)/u.test(G))return`${G}={'value': '<id>'}`;if(/(?:item|name|label)/u.test(G))return`${G}='<item>'`;if(/(?:qty|quantity|count|amount|number)/u.test(G))return`${G}=<qty>`;let D=ZG(G);return`${G}=${D}`}function KG(G){if(!G.commandName)return;if(/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(destination_path, source_path)`;if(/\bsource(?:\s+[A-Za-z0-9_-]+){0,3}\s+first\b/iu.test(G.move)&&/\b(?:destination|target|archive)(?:\s+[A-Za-z0-9_-]+){0,3}\s+second\b/iu.test(G.move))return`${G.commandName}(source_path, destination_path)`;let D=N0(G.move);if(D.length===0)return;return`${G.commandName}(${D.map(_G).join(", ")})`}function wG(G){if(G.surfaceFamily!=="host_action")return;let D=G.selections[0]?.exemplar,H=G.selections.find((J)=>J.exemplar.exactSurface?.kind==="action")?.exemplar,$=H?.intentCue.query.exactSlots.commandName??D?.intentCue.query.exactSlots.commandName??G.queryIntent.exactSlots.commandName,M=d(H?.episodeShape.safeCorrectedMove??H?.episodeShape.relevantPriorMove??D?.episodeShape.safeCorrectedMove??D?.episodeShape.relevantPriorMove),V=H?.exactSurface?.kind==="action"?H.exactSurface.value:void 0;if(V)return b0(V,M);let j=QG(M,$);if(j)return j;return KG({commandName:$,move:M})}function k0(G){if(G.selections.length===0)return;let D=h(G.selections.map((Q)=>Q.prototypeId)),H=h(G.selections.map((Q)=>Q.exemplar.id)),$=JG(G.selections),M=MG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),V=wG({queryIntent:G.queryIntent,selections:G.selections,surfaceFamily:G.surfaceFamily}),j=G.selections.reduce((Q,K)=>Q+K.probability,0)/G.selections.length,J=Math.min(0.22,G.conflictPrototypeIds.length*0.06),Z=$G(j-J,0,0.99),W=G.surfaceFamily==="host_action"&&Boolean(V),Y=Z<0.58?"abstain":W?"transient_executor":M==="exact_surface_copy"?"model_only":Z>=0.66?"transient_executor":"model_only",U=G.selections[0]?.exemplar;return{applicability:L0(G.queryIntent.goal,96),canonicalActionTemplate:V,commandName:G.queryIntent.exactSlots.commandName??U?.intentCue.query.exactSlots.commandName,confidence:Z,conflictingPrototypeIds:[...G.conflictPrototypeIds],constraintTypes:h([...G.queryIntent.constraintTypes,...G.selections.flatMap((Q)=>Q.exemplar.intentCue.query.constraintTypes)]),computedResponseRule:$,executionMode:Y,mappingType:M,stableFields:jG({computedResponseRule:$,queryIntent:G.queryIntent,selections:G.selections}),supportingExemplarIds:H,supportingPrototypeIds:D,surfaceFamily:G.surfaceFamily,taskFamily:G.queryIntent.actionType,varyingFields:VG(G.queryIntent)}}function O0(G){let D=G.hypothesis;if(!D||D.executionMode!=="transient_executor")return{lines:[],mode:"none"};switch(D.mappingType){case"symbolic_rule_execution":case"symbolic_formula":{let H=E0({query:G.query,rule:D.computedResponseRule});if(!H)return{lines:["Use the observed formula pattern and substitute the current probe values before answering."],mode:"hint"};return{computedResponse:H,lines:[`Probe-specific computed value: ${H}`],mode:"computed"}}case"slot_rebinding":{if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let $=u({query:G.query,template:D.canonicalActionTemplate});if($)return{computedResponse:$,lines:[`Emit exactly: ${$}`],mode:"computed"}}let H=[D.commandName?`Keep the command or tool surface as ${D.commandName}.`:"",D.stableFields.find(($)=>$.startsWith("arg_order="))?`Preserve ${D.stableFields.find(($)=>$.startsWith("arg_order="))?.replace("arg_order=","argument order ")}.`:"","Rebind only the probe-specific slot values; do not invent a different action family."].filter(Boolean);return{lines:H,mode:H.length>0?"hint":"none"}}case"hard_constraint_contract":return{lines:["Apply the observed hard response contract directly to the answer surface.","Prefer the safe replacement or constrained path/protocol over the failed surface."],mode:"hint"};case"exact_format_contract":return{lines:["Preserve the observed exact format, required prefix/suffix, voice, and ordering."],mode:"hint"};case"style_contract":return{lines:["Keep the response inside the observed style contract for this probe."],mode:"hint"};case"conditional_precondition":case"guarded_decision":return{lines:["Check the precondition implied by the prior examples before proceeding.","If the precondition is not satisfied, fall back to a warning or defer instead of pretending success."],mode:"hint"};case"exact_surface_copy":if(D.surfaceFamily==="host_action"&&D.canonicalActionTemplate){let H=u({query:G.query,template:D.canonicalActionTemplate});if(H)return{computedResponse:H,lines:[`Emit exactly: ${H}`],mode:"computed"}}return{lines:["Keep the same exact surface family, only adapting the probe-specific slots when necessary."],mode:"hint"}}}function F0(G){let D=G.hypothesis;if(!D)return;let H=[];if(D.stableFields.length>0)H.push(["Observed stable pattern:",...D.stableFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(D.varyingFields.length>0)H.push(["Probe-specific varying slots:",...D.varyingFields.slice(0,4).map(($)=>`- ${$}`)].join(`
`));if(G.execution.lines.length>0)H.push(["Probe-conditioned execution:",...G.execution.lines.map(($)=>`- ${$}`)].join(`
`));return H.length>0?H.join(`
`):void 0}function S0(G){let D=O0({hypothesis:G.hypothesis,query:G.query});return{...D,hypothesisSketch:F0({execution:D,hypothesis:G.hypothesis})}}var P0=0.08,v=0.58,RG={bias:-0.85,featureNames:["lexicalSimilarity","semanticSimilarity","intentCompatibility","surfaceCompatibility","exactSlotOverlap","exactSurfaceMatch","correctionSuccessPrior","interferenceRisk","recencySupport","repetitionSupport","cueCompatibility"],weights:[1.15,0.95,1.45,0.7,1.35,1.1,0.9,-1.2,0.3,0.5,1.25]},TG=0.28,BG=0.1,AG=0.05,EG=0.18,P=120,LG=180,NG=2,L=f0();function B(G,D=LG){let H=G.replace(/\s+/gu," ").trim();if(H.length<=D)return H;return`${H.slice(0,Math.max(0,D-3)).trimEnd()}...`}function R(G){return(G??"").replace(/\s+/gu," ").trim()}function A(G,D=L){if(!G?.trim())return;let H=D.resolveFromText({text:G});return D.analyzeBehavioralRule(G,H)}function O(G){let D=L.resolveFromText({text:G});return L.tokenize(G,D,{excludeStopwords:!0})}function E(G){return[...new Set(G.filter((D)=>D.trim().length>0))]}function bG(G){return(G.match(/["“](.+?)["”]/u)??G.match(/'([^']+)'/u))?.[1]?.trim()}function N(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(D);return G.filter((M)=>H.has(M)).length/Math.max(G.length,D.length)}function F(G){let D=A(G),H=D?.semanticCues??[];return E([...D?.hostAction?["operation_surface"]:[],...D?.hostAction?.destination||D?.hostAction?.sources?["path_constraint"]:[],...H.map(($)=>{switch($){case"failure":return"failure_signal";case"permission_failure":return"permission_failure";case"timeout":return"timeout_failure";case"unsafe":return"unsafe_or_deprecated";case"inhibition_replacement":return"inhibition_replacement";case"safe_fallback":return"safe_fallback";case"path":return"path_constraint";case"api":case"command":case"operation":return"operation_surface";case"argument_order":return"slot_order_contract";case"url":return"url_protocol";case"filetype":return"filetype_contract";case"format":return"format_contract";case"analogy":return"style_simplification";case"voice":return"voice_contract";case"symbolic":return"symbolic_rule";case"precondition":return"precondition_contract";case"brevity":return"brevity_contract";case"style":return"style_contract"}})])}function j0(G){return E([G.actionType,...G.constraintTypes,...G.entityTypes,...F(G.goal)])}function kG(G){let D=G.representative;return E([G.intentCue.query.actionType,...G.constraintTypes,...G.intentCue.query.entityTypes,...G.interferenceTags,...F(D.retrievalText),...F(D.episodeShape.cue),...F(D.episodeShape.observedOutcome),...F(D.episodeShape.relevantPriorMove),...F(D.episodeShape.safeCorrectedMove)])}function m0(G,D){return N(j0(G),kG(D))}function C(G){let D=R(G);return D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s*\(/u)?.[1]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[1]??D.match(/\b([A-Z][A-Z0-9_]*)\s+[A-Za-z0-9_]+\s+\|/u)?.[1]??A(G)?.commandName}function OG(G){let D=R(G),H=D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\([^)]*\)/u)?.[0]??D.match(/\b([A-Za-z_][A-Za-z0-9_@]*)\s+\|[^|]+\|/u)?.[0]??D.match(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+[^.]+/u)?.[0]??D.match(/['"`]([A-Za-z_][A-Za-z0-9_@]*(?:\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+){0,8})['"`]/u)?.[1];return H?I(H.trim()):void 0}function FG(G){let D=A(G),H=new Set(D?.semanticCues??[]);if(D?.hostAction||C(G)||H.has("argument_order"))return"structured_action";if(H.has("precondition"))return"guarded_api";if(H.has("command"))return"structured_action";if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)&&(H.has("symbolic")||/=/u.test(G)))return"symbolic_rule";if(H.has("analogy"))return"analogy_explanation";if(H.has("url"))return"url_rewrite";if(H.has("path"))return"path_redirect";if(H.has("api"))return"api_route";if(H.has("format"))return"format_contract";if(H.has("symbolic"))return"symbolic_rule";if(H.has("voice"))return"voice_style";return"general_response"}function SG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("symbolic");if(H.has("url"))$.push("url");if(D?.hostAction||C(G)||H.has("command")||H.has("operation"))$.push("command");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path");if(H.has("api"))$.push("api");if(H.has("analogy"))$.push("analogy");if(H.has("format"))$.push("format");if(H.has("command")&&/\|/u.test(G))$.push("query");if(H.has("voice"))$.push("voice");return E($)}function I(G){return G.replace(/[.,;:!?。]+$/u,"")}function C0(G){return[...R(G).matchAll(/https?:\/\/[^\s),;]+/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function I0(G){let D=[];for(let H of R(G).matchAll(/\bhttps?\b/giu)){let $=H[0]?.toLowerCase();if(($==="http"||$==="https")&&!D.includes($))D.push($)}return D}function n(G){return[...R(G).matchAll(/(?:~\/|\/)[A-Za-z0-9._/-]*[A-Za-z0-9._-]/gu)].map((D)=>I(D[0]??"")).filter((D)=>D.length>0)}function t(G){let D=I(G.trim());if(!D.startsWith("/"))return;let H=D.split("/").filter(Boolean);return H[0]?`/${H[0]}`:void 0}function PG(G){let D=I(G.trim());if(!D.startsWith("/")&&!D.startsWith("~/"))return;let H=D.lastIndexOf("/");if(H<0)return;return D.slice(0,H+1)}function c0(G){return I(G.trim()).split("/").filter(Boolean).at(-1)}function CG(G){let D=c0(G);if(!D)return;let H=D.lastIndexOf(".");return H<=0?void 0:D.slice(H)}function IG(G){let D=A(G),H=new Set(D?.semanticCues??[]),$=[];if(/\b[A-Z][A-Za-z0-9_]*\((-?\d+)\)/u.test(G)||H.has("symbolic"))$.push("formula");if(H.has("url"))$.push("url_shape");if(H.has("path")||D?.hostAction?.destination||D?.hostAction?.sources)$.push("path_root");if(H.has("argument_order"))$.push("arg_order");if(H.has("safe_fallback")||H.has("inhibition_replacement"))$.push("safe_alternative");if(H.has("analogy"))$.push("analogy");if(H.has("precondition"))$.push("precondition");if(H.has("style")||H.has("voice"))$.push("style");if(D?.hostAction||C(G)||H.has("argument_order")||H.has("command"))$.push("exact_action");return E($)}function V0(G){let D=R(G);if(A(D)?.hostAction||C(D)||/\b[a-z_][a-z0-9_]*\([^)]*\)/iu.test(D))return"host_action";return"text_response"}function zG(G,D){let H=R(G),$=H.match(/https?:\/\/([^\s/]+)(\/[^\s)]*)?/u),M=H.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u)?.[0],V=H.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u),J=((V?.[2])?S(V[2]).map((Y)=>Y.trim()):[]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean),Z=[...H.matchAll(/[⊗⊕⊖⊙]|->|=>|[+*=-]/gu)].map((Y)=>Y[0]).filter((Y,U,Q)=>Q.indexOf(Y)===U),W=A(H)?.semanticCues?.includes("voice")?["voice"]:[];return{argNames:J,argOrderSignature:J.length>0?J.join(">"):void 0,commandName:D==="host_action"?V?.[1]??C(H):void 0,extension:M?CG(M):void 0,filename:M?c0(M):void 0,operatorSymbols:Z,pathRoot:M?t(M):void 0,styleMarkers:W,urlHost:$?.[1],urlPath:$?.[2]}}function y(G){return[G.commandName??"",G.argOrderSignature??"",G.urlHost??"",G.urlPath??"",G.pathRoot??"",G.filename??"",G.extension??"",G.operatorSymbols.join(","),G.styleMarkers.join(",")].join("\x02")}function J0(G){let D=R(G);if(!D)return;let H=D.match(/\b([A-Za-z_][A-Za-z0-9_]*)\((.+)\)/u);if(H?.[0]){let Y=S(H[2]).map((U)=>U.trim()).filter(Boolean);return{kind:"action",value:B(H[0],P),...Y&&Y.length>0?{args:Y}:{}}}let $=OG(D);if($)return{kind:$.includes("|")||/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|/u.test($)||/\b[A-Za-z_][A-Za-z0-9_@]*\s+[A-Za-z0-9_./<>{}\[\]'":,@|=-]+/u.test($)?"action":"text",value:B($,P)};let M=D.match(/https?:\/\/[^\s)]+/u);if(M?.[0])return{kind:"url",value:B(M[0],P)};let V=D.match(/(?:~\/|\/)[A-Za-z0-9._/-]+/u);if(V?.[0])return{kind:"path",value:B(V[0],P)};let j=A(D)?.formatSurface,J=j?.prefixes??[],Z=j?.suffixes??[];if(J.length>0||Z.length>0)return{formatPrefixes:J,formatSuffixes:Z,kind:"format",value:B([...J,...Z].join(" / "),P)};let W=bG(D);if(W)return{kind:"text",value:B(W,P)};return}function x(G,D){let H=R(G);return{actionType:FG(G),constraintTypes:IG(G),entityTypes:SG(G),exactSlots:zG(G,D),goal:B(H,96),goalTokens:O(G).slice(0,12),requestedSurface:D}}function qG(G,D){return{query:x(G,D)}}function hG(G){return[`cue: ${B(G.cue)}`,`move: ${B(G.successfulMove)}`,`outcome: ${B(G.observedOutcome)}`,G.safeCorrectedMove?`corrected: ${B(G.safeCorrectedMove)}`:void 0,G.exactSurface?`surface: ${G.exactSurface.value}`:void 0].filter(Boolean).join(" | ")}function vG(G,D){let H=O(G),$=D?O(D.value):[],M=new Set($);return E([...H.filter((V)=>!M.has(V)),...F(G)])}function gG(G){let D=G.source==="tool_outcome"?0.9:G.source==="runtime_buffer"?0.8:0.55;if(G.exactSurface)D+=0.1;if(G.hasCorrection)D+=0.08;if(G.successfulMove.length>=16)D+=0.05;return Math.min(0.98,D)}function m(G){let D=B(G.observedOutcome),H=B(G.successfulMove),$=G.safeCorrectedMove?B(G.safeCorrectedMove):void 0,M=$?`${G.cue} ${$}`:`${G.cue} ${G.successfulMove}`,V=qG(M,G.surfaceFamily);return{confidence:gG({exactSurface:G.exactSurface,hasCorrection:Boolean(G.safeCorrectedMove),source:G.source,successfulMove:G.successfulMove}),createdAt:G.createdAt,episodeShape:{cue:B(G.cue),observedOutcome:D,relevantPriorMove:H,...$?{safeCorrectedMove:$}:{}},exactSurface:G.exactSurface,id:G.id,intentCue:V,interferenceTags:vG(M,G.exactSurface),retrievalText:hG({cue:G.cue,exactSurface:G.exactSurface,observedOutcome:D,safeCorrectedMove:$,successfulMove:H}),scope:G.scope,source:G.source,sourceIds:E(G.sourceIds),surfaceFamily:G.surfaceFamily,transferMode:"episodic_only"}}function s0(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="negative"||$.unresolved?D:void 0}function z0(G){let D=R(G),H=L.resolveFromText({text:D});if(!L.analyzeContent(D,H).correctionCue)return;return D.match(/^[^::]+[::]\s*(.+)$/u)?.[1]?.trim()??D}function fG(G){let D=R(G),H=L.resolveFromText({text:D});return L.analyzeContent(D,H).correctionCue}function dG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.correctionCue||$.feedbackKind==="dont"||$.feedbackKind==="prefer"}function yG(G){let D=R(G),H=L.resolveFromText({text:D}),$=L.analyzeContent(D,H);return $.factPolarity==="positive"||$.feedbackKind==="validated_pattern"?D:void 0}function xG(G){let D=Boolean(G.failureOutcome),H=Math.min(G.messages.length-1,G.startIndex+16);for(let $=G.startIndex;$<H;$+=1){let M=G.messages[$],V=G.messages[$+1];if(M?.role!=="user"||V?.role!=="assistant")continue;let j=G.messages[$+2];if(j?.role==="system"?s0(j.content):void 0){D=!0;continue}let Z=j?.role==="system"?yG(j.content):void 0;if(D&&(Z||fG(M.content)||dG(M.content)))return R(V.content)}return}function e(G){let D=[];for(let H=0;H<G.messages.length-1;H+=1){let $=G.messages[H],M=G.messages[H+1];if($?.role!=="user"||M?.role!=="assistant")continue;let V=R($.content),j=R(M.content);if(!V||!j)continue;let J=G.messages[H+2],Z=G.messages[H+3],W=G.messages[H+4],Y=J?.role==="system"?s0(J.content):void 0,U=J?.role==="system"?z0(J.content):void 0,Q=!U&&Z?.role==="system"?z0(Z.content):void 0,K=U??Q,w=xG({failureOutcome:Y,messages:G.messages,startIndex:H+3})??K;if(Y&&!w)continue;let b=w||j,z=G.surfaceHint??V0(b),W0=J0(b),X=w?Y?`The earlier move failed (${B(Y)}), and a later correction clarified the safer successful move.`:"A later correction clarified the safer successful move for the same kind of request.":"The earlier response established a successful way to handle the same kind of request.";D.push(m({createdAt:void 0,cue:V,exactSurface:W0,id:`${G.prefix}-${H}`,observedOutcome:X,safeCorrectedMove:w,scope:G.scope,source:"runtime_buffer",sourceIds:E([`${G.prefix}:${H}`,J?`${G.prefix}:${H+2}`:"",Z?`${G.prefix}:${H+3}`:"",W?`${G.prefix}:${H+4}`:""]),successfulMove:b,surfaceFamily:z}))}return D}function mG(G){let D=[];for(let H of G.archives){if(H.normalizedTranscript){let J=H.normalizedTranscript.split(/\n+/u).map((Z)=>{let W=Z.indexOf(":");if(W<=0)return null;return{content:Z.slice(W+1).trim(),role:Z.slice(0,W).trim().toLowerCase()}}).filter((Z)=>Boolean(Z));D.push(...e({messages:J,prefix:`archive-${H.id}`,scope:G.scope,surfaceHint:G.surfaceHint}));continue}let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.archivedAt,cue:V,exactSurface:J0(j),id:`archive-${H.id}`,observedOutcome:M.length===0?"The archived interaction resolved the issue without leaving open loops.":`The archived interaction still left these open loops: ${M.join(", ")}`,scope:G.scope,source:"archive",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function cG(G){let D=[];for(let H of G.episodes){let $=Array.isArray(H.keyDecisions)?H.keyDecisions:[],M=Array.isArray(H.unresolvedItems)?H.unresolvedItems:[],V=R(H.summary),j=R($[0]??H.summary);if(!V||!j)continue;D.push(m({createdAt:H.createdAt,cue:V,exactSurface:J0(j),id:`episode-${H.id}`,observedOutcome:M.length===0?"The episode captured a resolved successful response pattern.":`The episode preserved these remaining caveats: ${M.join(", ")}`,scope:G.scope,source:"episode",sourceIds:[H.id],successfulMove:j,surfaceFamily:G.surfaceHint??V0(j)}))}return D}function sG(G){let D=[];for(let H of G.memoryExport.durable.experiences){let $=w0(H);if(!$?.saferAlternative)continue;let M=q($.saferAlternative);D.push(m({createdAt:H.createdAt,cue:$.cue,exactSurface:{args:$.saferAlternative.args,kind:"action",value:M},id:`tool-outcome-${H.id}`,observedOutcome:`The earlier first action ${q($.firstAction)} failed, and the safer alternative succeeded better for this cue.`,safeCorrectedMove:M,scope:{agentId:H.agentId,tenantId:H.tenantId,userId:H.userId,workspaceId:H.workspaceId},source:"tool_outcome",sourceIds:[H.id,...H.sourceTraceIds],successfulMove:M,surfaceFamily:G.surfaceHint??"host_action"}))}return D}function oG(G){let D=new Map;for(let H of G){let $=[H.surfaceFamily,H.episodeShape.cue.toLowerCase(),H.episodeShape.relevantPriorMove.toLowerCase(),H.exactSurface?.value.toLowerCase()??""].join("\x00"),M=D.get($);if(!M||H.confidence>M.confidence)D.set($,H)}return[...D.values()]}function lG(G){return[G.surfaceFamily,G.intentCue.query.actionType,G.intentCue.query.constraintTypes.join(","),G.intentCue.query.entityTypes.join(","),y(G.intentCue.query.exactSlots),G.exactSurface?.kind??"none",G.exactSurface?.value.toLowerCase()??""].join("\x01")}function uG(G){return G.reduce((D,H)=>{return D+(H.episodeShape.safeCorrectedMove?1.2:1)},0)}function rG(G){let D=new Map;for(let H of G){let $=lG(H),M=D.get($)??[];M.push(H),D.set($,M)}return[...D.values()].map((H,$)=>{let M=[...H].sort((J,Z)=>{if(J.confidence!==Z.confidence)return Z.confidence-J.confidence;return(Z.createdAt??"").localeCompare(J.createdAt??"")})[0],V=H.length,j=H.length>=NG?"prototype_bounded":M.transferMode;return{confidence:Math.min(0.99,M.confidence+Math.min(0.12,H.length*0.04)),constraintTypes:M.intentCue.query.constraintTypes,exactSlotSignature:y(M.intentCue.query.exactSlots),exemplars:H,exactSurface:M.exactSurface,hardNegativeIds:[],id:`prototype-${$+1}`,intentCue:M.intentCue,interferenceTags:E(H.flatMap((J)=>J.interferenceTags)),representative:M,repetitionSupport:V,successSupport:uG(H),surfaceFamily:M.surfaceFamily,transferMode:j}})}function q0(G){return G?`${G.kind}:${G.value.toLowerCase()}`:"none"}function pG(G){let D=[];for(let H=0;H<G.length;H+=1){let $=G[H];for(let M=H+1;M<G.length;M+=1){let V=G[M];if($.surfaceFamily!==V.surfaceFamily)continue;if(N($.intentCue.query.goalTokens,V.intentCue.query.goalTokens)<TG)continue;let J=q0($.exactSurface)!==q0(V.exactSurface),Z=$.intentCue.query.actionType!==V.intentCue.query.actionType;if(!J&&!Z)continue;D.push({leftPrototypeId:$.id,reason:J?"exact_surface_conflict":"intent_conflict",rightPrototypeId:V.id})}}return D}function aG(G,D){let H=[];for(let $ of D){let M=G.find((J)=>J.id===$.leftPrototypeId),V=G.find((J)=>J.id===$.rightPrototypeId),j=Math.max(0.35,N(M?.intentCue.query.goalTokens??[],V?.intentCue.query.goalTokens??[]));H.push({conflictingPrototypeId:$.rightPrototypeId,penalty:j,prototypeId:$.leftPrototypeId,reason:$.reason}),H.push({conflictingPrototypeId:$.leftPrototypeId,penalty:j,prototypeId:$.rightPrototypeId,reason:$.reason})}return H}function p(G,D){if(G.length===0||D.length===0)return 0;let H=new Set(G),$=new Set(D),M=0;for(let V of H)if($.has(V))M+=1;return M/Math.max(H.size,$.size)}function G0(G,D){let H=[G.commandName&&D.commandName&&G.commandName===D.commandName?1:0,G.argOrderSignature&&D.argOrderSignature&&G.argOrderSignature===D.argOrderSignature?1:0,G.urlHost&&D.urlHost&&G.urlHost===D.urlHost?1:0,G.urlPath&&D.urlPath&&G.urlPath===D.urlPath?1:0,G.pathRoot&&D.pathRoot&&G.pathRoot===D.pathRoot?1:0,G.filename&&D.filename&&G.filename===D.filename?1:0,G.extension&&D.extension&&G.extension===D.extension?1:0,p(G.operatorSymbols,D.operatorSymbols),p(G.styleMarkers,D.styleMarkers),p(G.argNames,D.argNames)];return H.reduce(($,M)=>$+M,0)/H.length}function o0(G,D){if(!D)return 0;let H=G.goal.toLowerCase(),$=D.value.toLowerCase(),M=new Set(j0(G)),V=0;if(N(G.goalTokens,O(D.value))>=0.12)V=Math.max(V,1.15);if($.includes("|folder|")&&M.has("path_constraint"))V=Math.max(V,1.4);if($.includes("|..|")&&M.has("path_constraint"))V=Math.max(V,1.2);if($.includes("|~|")&&M.has("path_constraint"))V=Math.max(V,1.2);let J=C(D.value)?.toLowerCase();if(J){if(O(J.replace(/_/gu," ")).some((Y)=>H.includes(Y)))V=Math.max(V,1.3);if(M.has("operation_surface"))V=Math.max(V,1.1)}let Z=D.value.match(/\b[A-Za-z_][A-Za-z0-9_@]*\((.*)\)/u);if(Z?.[1]){if(S(Z[1]).map((Y)=>Y.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/u)?.[1]??"").filter(Boolean).flatMap((Y)=>O(Y.replace(/_/gu," "))).some((Y)=>H.includes(Y)))V=Math.max(V,1.2);if(n(D.value).length>=2&&M.has("path_constraint")&&M.has("operation_surface"))V=Math.max(V,1.2)}if(/\b[A-Z][A-Z0-9_]*\s+[A-Za-z0-9_]+\s+\|\s+[A-Z][A-Z0-9_]*\s+/u.test(D.value)&&G.actionType==="structured_action")V=Math.max(V,1.2);return V}function D0(G){let D=G.prototype.representative.episodeShape.relevantPriorMove.toLowerCase(),H=A(D),$=new Set(j0(G.queryIntent)),M=0;if((H?.argumentOrder?.length??0)>=2&&$.has("operation_surface"))M=Math.max(M,1.2);if((H?.formatPrefix||H?.formatSuffix)&&$.has("format_contract"))M=Math.max(M,1.2);if(H?.commandName&&G.queryIntent.actionType==="structured_action")M=Math.max(M,1.2);if(H?.semanticCues?.includes("path")&&$.has("path_constraint"))M=Math.max(M,1.2);return M}function iG(G){let D=new Set;for(let H of G?.hits??[])D.add(H.id);for(let H of G?.candidateTraces??[])if(H.returned||H.whyReturned)D.add(H.memoryId);return D}function H0(G){if(G.transferMode!=="prototype_bounded")return G.representative;return{...G.representative,confidence:G.confidence,sourceIds:E(G.exemplars.flatMap((D)=>D.sourceIds)),transferMode:"prototype_bounded"}}function nG(G){return G.exemplar.exactSurface?.kind==="action"}function tG(G){return G.exemplar.exactSurface?.kind==="action"&&G.probability>=v-0.08}function eG(G){let D=E([...G.selectedPrototypeIds]);return{conflictPrototypeIds:E(G.interferenceLedger.filter(($)=>G.selectedPrototypeIds.includes($.prototypeId)).map(($)=>$.conflictingPrototypeId).filter(($)=>G.rankedPrototypeIds.includes($))),supportPrototypeIds:D}}function a(G,D){if(G.prototype.surfaceFamily!==D.prototype.surfaceFamily)return!1;if(G.prototype.intentCue.query.actionType!==D.prototype.intentCue.query.actionType)return!1;let H=G.prototype.exactSurface?.value?.trim().toLowerCase(),$=D.prototype.exactSurface?.value?.trim().toLowerCase();if(H||$){if(H&&$)return H===$;let M=N(G.prototype.intentCue.query.entityTypes,D.prototype.intentCue.query.entityTypes);return(Boolean(G.exemplar.episodeShape.safeCorrectedMove)||Boolean(D.exemplar.episodeShape.safeCorrectedMove))&&M>0}return y(G.prototype.intentCue.query.exactSlots)===y(D.prototype.intentCue.query.exactSlots)}function h0(G){let D=G.routes.includes("correction_success")?2:0,H=G.exemplar.episodeShape.safeCorrectedMove?2:0,$=G.prototype.successSupport/Math.max(1,G.prototype.repetitionSupport),M=G.prototype.constraintTypes.includes("path_root")||G.prototype.constraintTypes.includes("safe_alternative")||G.prototype.constraintTypes.includes("url_shape")||G.prototype.constraintTypes.includes("precondition")?0.45:0;return D+H+$+M+G.probability*0.25}function GD(G,D){let H=h0(G),$=h0(D);if(Math.abs(H-$)<0.65)return;return H>$?G:D}function DD(G){let D=new Map,H=iG(G.index.recallHints);for(let $ of G.index.prototypes){if($.surfaceFamily!==G.surfaceFamily)continue;let M=[],V=Math.max(N(G.queryIntent.goalTokens,O($.representative.retrievalText)),N(G.queryIntent.goalTokens,O($.representative.episodeShape.cue))),j=G0(G.queryIntent.exactSlots,$.intentCue.query.exactSlots),J=m0(G.queryIntent,$),Z=G.surfaceFamily==="host_action"?Math.max(o0(G.queryIntent,$.exactSurface),D0({prototype:$,queryIntent:G.queryIntent})):0,W=N(G.queryIntent.entityTypes,$.intentCue.query.entityTypes),Y=G.queryIntent.actionType===$.intentCue.query.actionType;if(j>0)M.push("exact_slot");if(J>=EG)M.push("cue");if(V>=0.12||Y&&(W>0||V>=0.05))M.push("lexical");if(Z>=1)M.push("cue");if($.exemplars.flatMap((_)=>_.sourceIds).some((_)=>H.has(_)))M.push("semantic");let Q=$.representative.episodeShape.safeCorrectedMove||$.successSupport>$.repetitionSupport,K=V>=AG||J>=BG||W>0&&J>0;if(Q&&(M.length>0||K))M.push("correction_success");if(M.length===0)continue;D.set($.id,{exemplar:H0($),prototype:$,routes:M})}return[...D.values()]}function $0(G){let D=G.queryIntent.goalTokens,H=m0(G.queryIntent,G.candidate.prototype),$=Math.max(N(D,O(G.candidate.exemplar.retrievalText)),H*0.65),M=G.candidate.routes.includes("semantic")?1:0,V=(G.queryIntent.actionType===G.candidate.prototype.intentCue.query.actionType?0.55:0)+N(G.queryIntent.goalTokens,G.candidate.prototype.intentCue.query.goalTokens)*0.25+N(G.queryIntent.entityTypes,G.candidate.prototype.intentCue.query.entityTypes)*0.1+N(G.queryIntent.constraintTypes,G.candidate.prototype.intentCue.query.constraintTypes)*0.1+H*0.2,j=G.queryIntent.requestedSurface===G.candidate.prototype.surfaceFamily?1:0,J=G0(G.queryIntent.exactSlots,G.candidate.prototype.intentCue.query.exactSlots),Z=G.candidate.prototype.exactSurface?Math.max(N(D,O(G.candidate.prototype.exactSurface.value)),o0(G.queryIntent,G.candidate.prototype.exactSurface),D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent})):D0({prototype:G.candidate.prototype,queryIntent:G.queryIntent}),W=Math.min(1,G.candidate.prototype.successSupport/Math.max(1,G.candidate.prototype.repetitionSupport)),Y=Math.min(1,Math.log1p(G.candidate.prototype.repetitionSupport)/Math.log(5)),U=G.candidate.prototype.representative.createdAt?1/(1+Math.max(0,(Date.now()-new Date(G.candidate.prototype.representative.createdAt).getTime())/2592000000)):0.45,Q=new Set(G.hardNegativeIds);for(let _ of G.interferenceLedger)if(_.prototypeId===G.candidate.prototype.id)Q.add(_.conflictingPrototypeId);let K=[...Q].reduce((_,w)=>{let b=G.prototypesById.get(w);if(!b)return _;let z=Math.max(N(D,b.intentCue.query.goalTokens),G0(G.queryIntent.exactSlots,b.intentCue.query.exactSlots));return Math.max(_,z)},0);return{correctionSuccessPrior:W,cueCompatibility:H,exactSurfaceMatch:Z,exactSlotOverlap:J,interferenceRisk:K,intentCompatibility:Math.min(1,V),lexicalSimilarity:$,recencySupport:U,semanticSimilarity:M,repetitionSupport:Y,surfaceCompatibility:j}}function M0(G){return[G.lexicalSimilarity,G.semanticSimilarity,G.intentCompatibility,G.surfaceCompatibility,G.exactSlotOverlap,G.exactSurfaceMatch,G.correctionSuccessPrior,G.interferenceRisk,G.recencySupport,G.repetitionSupport,G.cueCompatibility]}function HD(G,D,H){let $=new Map(D.map((j)=>[j.id,j])),M=new Map;for(let j of H){let J=M.get(j.leftPrototypeId)??[];J.push(j.rightPrototypeId),M.set(j.leftPrototypeId,J);let Z=M.get(j.rightPrototypeId)??[];Z.push(j.leftPrototypeId),M.set(j.rightPrototypeId,Z)}let V=[];for(let j of D){let J={exemplar:H0(j),prototype:j,routes:["lexical"]},Z=$0({candidate:J,interferenceLedger:G,hardNegativeIds:M.get(j.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(Z),label:1});for(let W of(M.get(j.id)??[]).slice(0,2)){let Y=$.get(W);if(!Y)continue;let U=$0({candidate:{exemplar:H0(Y),prototype:Y,routes:["lexical"]},interferenceLedger:G,hardNegativeIds:M.get(Y.id)??[],prototypesById:$,queryIntent:x(j.representative.episodeShape.cue,j.surfaceFamily)});V.push({features:M0(U),label:0})}}return R0({baseModel:RG,samples:V})}function pD(G){let D={agentId:G.memoryExport.scope.agentId,tenantId:G.memoryExport.scope.tenantId,userId:G.memoryExport.scope.userId,workspaceId:G.memoryExport.scope.workspaceId},H=oG([...e({messages:G.transientMessages??[],prefix:"transient",scope:D,surfaceHint:G.surfaceHint}),...e({messages:G.runtimeMessages??[],prefix:"runtime",scope:D,surfaceHint:G.surfaceHint}),...sG({memoryExport:G.memoryExport,surfaceHint:G.surfaceHint}),...mG({archives:G.memoryExport.durable.archives,scope:D,surfaceHint:G.surfaceHint}),...cG({episodes:G.memoryExport.durable.episodes,scope:D,surfaceHint:G.surfaceHint})]),$=rG(H),M=pG($),V=new Map;for(let Z of M)V.set(Z.leftPrototypeId,[...V.get(Z.leftPrototypeId)??[],Z.rightPrototypeId]),V.set(Z.rightPrototypeId,[...V.get(Z.rightPrototypeId)??[],Z.leftPrototypeId]);let j=$.map((Z)=>({...Z,hardNegativeIds:E(V.get(Z.id)??[])})),J=aG(j,M);return{exemplars:H,hardNegativePairs:M,interferenceLedger:J,model:HD(J,j,M),prototypes:j,recallHints:G.recallHints}}function aD(G){let D=G.language??L,H=G.languageContext??D.resolveFromText({text:G.query}),$=x(G.query,G.surfaceFamily),M=DD({index:G.index,queryIntent:$,surfaceFamily:G.surfaceFamily});if(M.length===0)return{candidates:[],debug:{abstainReason:"no_candidates",candidatePrototypeIds:[],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[]},selections:[]};let V=new Map(G.index.prototypes.map((X)=>[X.id,X])),j=M.map((X)=>{let T=$0({candidate:X,interferenceLedger:G.index.interferenceLedger,hardNegativeIds:X.prototype.hardNegativeIds,prototypesById:V,queryIntent:$}),i0=M0(T),Y0=l({features:i0,model:G.index.model});return{...X,probability:Y0.probability,score:Y0.score}}).sort((X,T)=>T.score-X.score),[J,Z]=j;if(!J||J.probability<v){let X=i({exemplars:G.index.exemplars,language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"hypothesis_missing",candidatePrototypeIds:j.map((T)=>T.prototype.id),mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],topProbability:J?.probability,topScore:J?.score},...X?{packet:X}:{},selections:[]}}let W=G.surfaceFamily==="host_action"||$.constraintTypes.includes("arg_order")||$.constraintTypes.includes("exact_action")||$.constraintTypes.includes("formula"),Y=Z&&!a(J,Z)?GD(J,Z):void 0,U=Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)?W?[Y??J]:Y?[Y]:null:j;if(U===null&&Z&&J.probability-Z.probability<P0&&Z.probability>=v-0.05&&!a(J,Z)){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:[],debug:{abstainReason:"support_conflict",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:[J.prototype.id,Z.prototype.id],mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:[],topProbability:J.probability,topScore:J.score},...X?{packet:X}:{},selections:[]}}let K=(U??j).filter((X)=>X.probability>=v).slice(0,G.maxExemplars??4).map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}));if(G.surfaceFamily==="host_action"&&!K.some(nG)){let X=j.find((T)=>tG(T));if(X&&!K.some((T)=>T.prototypeId===X.prototype.id))K=[...K,{exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score}].slice(0,G.maxExemplars??4)}let _=eG({interferenceLedger:G.index.interferenceLedger,rankedPrototypeIds:j.map((X)=>X.prototype.id),selectedPrototypeIds:K.map((X)=>X.prototypeId)}),w=k0({conflictPrototypeIds:_.conflictPrototypeIds,query:G.query,queryIntent:$,selections:K,surfaceFamily:G.surfaceFamily});if(w?.executionMode==="abstain"){let X=i({exemplars:j.map((T)=>T.exemplar),language:D,languageContext:H,queryIntent:$});return{candidates:j.map((T)=>({exemplar:T.exemplar,probability:T.probability,prototypeId:T.prototype.id,score:T.score})),debug:{abstainReason:"executor_unsafe",candidatePrototypeIds:j.map((T)=>T.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds},mode:"abstained",selectedExemplarIds:[],selectedPrototypeIds:[],supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,...X?{packet:X}:{},selections:[],supportConflict:_}}let b=S0({hypothesis:w,query:G.query}),z=TD({execution:b,hypothesis:w,language:D,languageContext:H,queryIntent:$,selections:K});return{candidates:j.map((X)=>({exemplar:X.exemplar,probability:X.probability,prototypeId:X.prototype.id,score:X.score})),debug:{candidatePrototypeIds:j.map((X)=>X.prototype.id),conflictPrototypeIds:_.conflictPrototypeIds,hypothesis:w?{confidence:w.confidence,executionMode:w.executionMode,mappingType:w.mappingType,supportingPrototypeIds:w.supportingPrototypeIds}:void 0,mode:"exemplar_only",selectedExemplarIds:K.map((X)=>X.exemplar.id),selectedPrototypeIds:K.map((X)=>X.prototypeId),supportPrototypeIds:_.supportPrototypeIds,topProbability:J.probability,topScore:J.score},hypothesis:w,packet:z,selections:K,supportConflict:_}}function $D(G){if(!G.exactSurface||G.confidence<0.72)return;return G.exactSurface.value}function MD(G){let D=L.resolveFromText({text:G}),H=L.deriveFeedbackKind(G,D);if(H==="dont")return"dont";if(H==="do")return"do";if(H==="prefer")return"prefer";return"prefer"}function l0(G){let D=new Set,H=[];for(let $ of G){let M=JSON.stringify($);if(D.has(M))continue;D.add(M),H.push($)}return H}function v0(G){if(!G)return[];return E([...G.matchAll(/\b[A-Z][A-Za-z0-9_-]{2,}\b/gu)].map((D)=>D[0]).filter((D)=>{return/[a-z][A-Z]/u.test(D)||/(?:API|Analyzer|Check|Cleaner|Engine|Feed|Importer|Search)$/u.test(D)}))}function jD(G){return`Warn first and use ${G.preferred} instead of ${G.forbidden}.`}function VD(G){return G.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function JD(G,D){let H=G.episodeShape.safeCorrectedMove??"",$=A(H,D),M=($?.forbiddenFragments??[]).filter((W)=>/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(W)),V=E([...M,...v0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" "))]),j=E([...$?.preferredAlternatives??[],...v0(H)]).filter((W)=>!M.some((Y)=>Y.toLowerCase()===W.toLowerCase())),J=V.filter((W)=>!j.some((Y)=>Y.toLowerCase()===W.toLowerCase())),Z=[];for(let W of J){let Y=j.find((U)=>U.toLowerCase()!==W.toLowerCase());if(!Y)continue;Z.push({forbidden:W,preferred:Y})}return Z}function g0(G,D){return D.reduce((H,$)=>H.replace(new RegExp(`\\b${VD($)}\\b`,"giu"),"it"),G).replace(/\b(?:an?|the)\s+it\b/giu,"it").replace(/\s+/gu," ").trim()}function ZD(G,D){let H=R(G.episodeShape.safeCorrectedMove??G.episodeShape.relevantPriorMove),$=A(H);if($?.analogyText)return g0(`Think of it like ${$.analogyText}.`,D);let M=g0(H.replace(/^sure[, ]*/iu,""),D);if($?.semanticCues?.includes("analogy"))return M;return"Use a simple everyday analogy without the technical term."}function WD(G){let D=R([G.episodeShape.observedOutcome,G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove].join(" "));if(!A(D)?.semanticCues?.includes("analogy"))return;let $=E([...A(G.episodeShape.cue)?.structuredTerms??[],...A(G.episodeShape.relevantPriorMove)?.structuredTerms??[]]);if($.length===0)return;return{fallbackAnswer:ZD(G,$),forbiddenFragments:$,kind:"block_surface"}}function YD(){return"I speak from my own breath: I rise like roots in rain, I bend like reeds in wind, and I bloom like moss after storm."}function XD(G){let D=R([G.episodeShape.safeCorrectedMove,G.episodeShape.relevantPriorMove,G.exactSurface?.value].join(" ")),H=A(D),$=H?.forbiddenFragments??[];if(!H?.semanticCues?.includes("voice")||$.length===0)return;return{fallbackAnswer:YD(),forbiddenFragments:$,kind:"block_surface"}}function UD(G){let D=[G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ").match(/\.[A-Za-z0-9]{2,6}\b/gu),H=G.episodeShape.safeCorrectedMove?.match(/\.[A-Za-z0-9]{2,6}\b/gu),$=D?.find((V)=>H?.every((j)=>j.toLowerCase()!==V.toLowerCase())),M=H?.find((V)=>V.toLowerCase()!==$?.toLowerCase());return $&&M?{from:$,to:M}:void 0}function QD(G,D){let H=A(G.episodeShape.safeCorrectedMove,D)?.protocolReplacement;if(H)try{let W=new URL(H.preferredUrl),Y=new URL(H.forbiddenUrl);if((Y.protocol==="http:"||Y.protocol==="https:")&&(W.protocol==="http:"||W.protocol==="https:")&&Y.protocol!==W.protocol&&Y.host===W.host)return{fromScheme:Y.protocol.slice(0,-1),host:W.host,toScheme:W.protocol.slice(0,-1),toUrl:W.toString()}}catch{return}let $=C0([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),M=C0([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="url"?G.exactSurface.value:void 0].join(" "));for(let W of $)for(let Y of M)try{let U=new URL(W),Q=new URL(Y);if(U.protocol!=="http:"&&U.protocol!=="https:"||Q.protocol!=="http:"&&Q.protocol!=="https:"||U.protocol===Q.protocol||U.host!==Q.host)continue;return{fromScheme:U.protocol.slice(0,-1),host:Q.host,toScheme:Q.protocol.slice(0,-1),toUrl:Q.toString()}}catch{continue}let V=I0([G.episodeShape.cue,G.episodeShape.observedOutcome].join(" ")),j=I0(G.episodeShape.safeCorrectedMove),J=V.find((W)=>j.some((Y)=>Y!==W)),Z=j.find((W)=>W!==J);if(J&&Z)return{fromScheme:J,toScheme:Z};return}function _D(G){let D=n([G.episodeShape.relevantPriorMove,G.episodeShape.observedOutcome].join(" ")),H=n([G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="path"?G.exactSurface.value:void 0].join(" "));for(let $ of D){let M=t($);if(!M)continue;for(let V of H){let j=PG(V),J=t(V);if(!j||!J||J===M||V===$)continue;return{forbiddenRoot:M,safeAnchor:j,safeExample:V}}}return}function KD(G,D){let H=R([G.episodeShape.safeCorrectedMove,G.episodeShape.observedOutcome,G.episodeShape.relevantPriorMove].join(" ")),$=A(H,D)?.guard;if(!$)return;return{...$.allowedStates.length>0?{allowedWhen:$.allowedStates}:{},fallbackInstruction:`Check ${$.check} first; warn or defer unless the required state is available.`,precondition:$.check,...$.subject?{subject:$.subject}:{}}}function wD(G,D){let H=[G.episodeShape.safeCorrectedMove,G.exactSurface?.kind==="format"?G.exactSurface.value:void 0].filter((J)=>Boolean(J)).join(" ");if(!H)return;let $=A(H,D),M=$?.formatPrefix,V=$?.formatSuffix,j=E([M,V].filter((J)=>Boolean(J)));if(!M&&!V&&j.length===0)return;return{exactFragments:{...M?{prefixes:[M]}:{},...j.length>0?{required:j}:{},...V?{suffixes:[V]}:{}},kind:"rewrite_output_slot"}}function RD(G,D){let H=[];for(let $ of G){let M=$.exemplar;for(let Q of JD(M,D)){let K=jD(Q);H.push({kind:"require_warning",preferredAlternatives:[Q.preferred],warningMessage:K}),H.push({fallbackAnswer:K,forbiddenFragments:[Q.forbidden],kind:"block_surface"})}let V=WD(M);if(V)H.push(V);let j=XD(M);if(j)H.push(j);let J=UD(M);if(J)H.push({kind:"rewrite_output_slot",replacementPairs:[J]}),H.push({fallbackAnswer:`Warn first and use ${J.to} instead of ${J.from}.`,forbiddenFragments:[J.from],kind:"block_surface",replacementPairs:[J]});let Z=wD(M,D);if(Z)H.push(Z);let W=QD(M,D);if(W){let Q=`${W.fromScheme}://`,K=`${W.toScheme}://`,_=W.host&&W.toUrl?{example:W.toUrl,host:W.host,pathPlacement:"path_after_host",scheme:W.toScheme}:void 0;H.push({kind:"rewrite_output_slot",replacementPairs:[{from:Q,to:K}],..._?{urlTemplate:_}:{}}),H.push({forbiddenFragments:[Q],fallbackAnswer:`Warn first and offer the ${W.toScheme} URL instead of the ${W.fromScheme} URL.`,kind:"block_surface",replacementPairs:[{from:Q,to:K}]}),H.push({kind:"require_warning",..._?{urlTemplate:_}:{},warningMessage:`If the current probe requests a ${W.fromScheme} URL, warn first and offer the ${W.toScheme} URL instead.`})}let Y=_D(M);if(Y){let Q={anchor:Y.safeAnchor,example:Y.safeExample,variableSegment:"filename"};H.push({kind:"rewrite_output_slot",pathTemplate:Q}),H.push({forbiddenFragments:[`${Y.forbiddenRoot}/`,Y.forbiddenRoot],fallbackAnswer:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to ${Y.safeExample} or another safe path under ${Y.safeAnchor}.`,kind:"block_surface"}),H.push({kind:"require_warning",pathTemplate:Q,warningMessage:`Refuse the unsafe ${Y.forbiddenRoot} path and redirect to a safe path under ${Y.safeAnchor}.`})}let U=KD(M,D);if(U)H.push({...U.allowedWhen?{allowedWhen:U.allowedWhen}:{},fallbackBehavior:{warningMessage:U.fallbackInstruction},kind:"require_precondition_check",precondition:U.precondition,...U.subject?{subject:U.subject}:{}})}return l0(H)}function u0(G){if(G.queryIntent?.requestedSurface!=="text_response")return;let H=E(G.selections.flatMap((Z)=>{let W=Z.exemplar;return[W.episodeShape.safeCorrectedMove,W.episodeShape.relevantPriorMove,W.exactSurface?.kind==="format"?W.exactSurface.value:void 0,G.hypothesis?.stableFields.filter((Y)=>/^(?:path_root|required_prefix|required_suffix|surface|url_host)=/u.test(Y)).join(". ")].filter((Y)=>Boolean(Y&&Y.trim()))})).map((Z)=>d0({appliesTo:G.queryIntent?.goal,exemplarCount:G.selections.length,kind:MD(Z),language:G.language,languageContext:G.languageContext,rule:Z})),$=y0(H),M=l0([...$?.operations??[],...RD(G.selections,G.language)]),V=G.selections.map((Z)=>A([Z.exemplar.episodeShape.observedOutcome,Z.exemplar.episodeShape.relevantPriorMove,Z.exemplar.episodeShape.safeCorrectedMove,Z.exemplar.retrievalText].join(" "),G.language)?.responseStyle),j=V.includes("bullets"),J=!j&&V.includes("brief");return M.length>0||J||j?{...j?{bulletOnly:!0}:{},...J?{brevityOnly:!0}:{},concise:!0,operations:M}:void 0}function i(G){if(G.queryIntent.requestedSurface!=="text_response")return;let D=G.exemplars.map(($,M)=>({exemplar:$,probability:$.confidence,prototypeId:`fallback-${M}`,score:$.confidence})),H=u0({language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:D});if(!H)return;return{promptPayload:G.language.render({key:"behavioral_controls_available"},G.languageContext),retrievalText:G.exemplars.map(($)=>$.retrievalText).join(`
`),textResponsePlan:H}}function TD(G){if(G.selections.length===0)return;let D=u0({hypothesis:G.hypothesis,language:G.language,languageContext:G.languageContext,queryIntent:G.queryIntent,selections:G.selections}),H=x0(D),$=(j,J)=>G.language.render({key:j,values:J},G.languageContext),M=[$("behavioral_relevant_prior_examples"),...G.selections.flatMap(({exemplar:j},J)=>{let Z=[$("behavioral_example",{index:J+1}),`${$("behavioral_situation")} ${B(j.episodeShape.cue)}`,`${$("behavioral_successful_move")} ${B(j.episodeShape.relevantPriorMove)}`,`${$("behavioral_observed_outcome")} ${B(j.episodeShape.observedOutcome)}`];if(j.episodeShape.safeCorrectedMove)Z.push(`${$("behavioral_safe_corrected_move")} ${B(j.episodeShape.safeCorrectedMove)}`);let W=$D(j);if(W)Z.push(`${$("behavioral_exact_surface")} ${B(W)}`);return Z}),G.execution.hypothesisSketch,H.length>0?[$("behavioral_raw_response_control"),...H].join(`
`):void 0].join(`
`),V=G.selections.map(({exemplar:j})=>j.retrievalText).join(`
`);return{...G.execution.computedResponse?{computedResponse:G.execution.computedResponse}:{},...G.execution.hypothesisSketch?{hypothesisSketch:G.execution.hypothesisSketch}:{},promptPayload:M,retrievalText:V,...D?{textResponsePlan:D}:{}}}function iD(G){return{exemplarCount:G.exemplars.length,hardNegativeCount:G.hardNegativePairs.length,interferenceCount:G.interferenceLedger.length,prototypeCount:G.prototypes.length}}import{createHmac as BD,randomBytes as AD}from"node:crypto";var ED=16,a0="hmac-sha256:0000000000000000000000000000000000000000000000000000000000000000";function g(G,D,H){if(D===void 0)return;return`hmac-sha256:${BD("sha256",H).update(G).update(":").update(D).digest("hex")}`}function LD(){return{userIdHash:a0}}function r0(G,D){return{userIdHash:g("userIdHash",G.userId,D)??a0,tenantIdHash:g("tenantIdHash",G.tenantId,D),workspaceIdHash:g("workspaceIdHash",G.workspaceId,D),agentIdHash:g("agentIdHash",G.agentId,D),sessionIdHash:g("sessionIdHash",G.sessionId,D)}}function Z0(G){if(!G)return;let D=Object.entries(G).filter(([,H])=>typeof H==="string"||typeof H==="number"||typeof H==="boolean");return D.length>0?Object.fromEntries(D):void 0}function c(G,D){return Z0({...G??{},...D??{}})}function ND(G){if(!G||G.length===0)return;let D=new Set,H=[];for(let $ of G){let M=`${$.type}:${$.id}`;if(D.has(M))continue;D.add(M),H.push($)}return H}function bD(G){if(G instanceof Error)return{errorType:G.name};return{errorType:typeof G}}function kD(G){if(G?.scopeDigestSecret!==void 0){if(G.scopeDigestSecret.length<ED)throw Error("GoodMemory observability scopeDigestSecret must be at least 16 characters.");return G.scopeDigestSecret}return AD(32).toString("base64url")}function p0(G){console.error("GoodMemory trace sink failed",G instanceof Error?G.name:typeof G)}function OD(G){return typeof G==="object"&&G!==null&&"then"in G&&typeof G.then==="function"}function eD(G,D){let H=G?.traceSink,$=kD(G);async function M(j){if(!H)return;try{let J=H.emit(j);if(OD(J))Promise.resolve(J).catch(p0)}catch(J){p0(J)}}function V(j){return{traceId:j.traceId,spanId:j.spanId,name:j.name,status:j.status,scopeDigest:j.scopeDigest,attributes:Z0(j.attributes),links:ND(j.links),redaction:{containsRawUserText:!1},occurredAt:D().toISOString()}}return{enabled:Boolean(H),digestScope:(j)=>r0(j,$),async start(j){let J=j.scopeDigest??(j.scope?r0(j.scope,$):LD());if(!H)return{scopeDigest:J,async succeeded(){},async failed(){},async blocked(){}};let Z=crypto.randomUUID(),W=crypto.randomUUID(),Y=Z0(j.attributes);return M(V({attributes:Y,name:j.name,scopeDigest:J,spanId:W,status:"started",traceId:Z})),{traceId:Z,scopeDigest:J,succeeded:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"succeeded",traceId:Z})),failed:(U)=>M(V({attributes:c(c(Y,U.attributes),bD(U.error)),links:U.links,name:j.name,scopeDigest:J,spanId:W,status:"failed",traceId:Z})),blocked:(U)=>M(V({attributes:c(Y,U?.attributes),links:U?.links,name:j.name,scopeDigest:J,spanId:W,status:"blocked",traceId:Z}))}}}}
export{FD as pa,SD as qa,q as ra,U0 as sa,ID as ta,zD as ua,DG as va,qD as wa,w0 as xa,hD as ya,vD as za,pD as Aa,aD as Ba,iD as Ca,eD as Da};
function r(n){if(n===void 0)return;let e=n.trim();return e.length>0?e:void 0}function t(n){let e=n.userId.trim();if(e.length===0)throw Error("MemoryScope requires a non-empty userId");return{userId:e,tenantId:r(n.tenantId),workspaceId:r(n.workspaceId),agentId:r(n.agentId),sessionId:r(n.sessionId)}}function o(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId??""].join("::")}function d(n){let e=t(n);return[e.userId,e.tenantId??"",e.workspaceId??"",e.agentId??"",e.sessionId].map((i)=>i??"").join("::")}function s(n,e){return o(n)===o(e)}
export{t as Vb,o as Wb,d as Xb,s as Yb};
import{createRequire as k}from"node:module";var g=Object.create;var{getPrototypeOf:h,defineProperty:f,getOwnPropertyNames:i}=Object;var j=Object.prototype.hasOwnProperty;var l=(a,b,c)=>{c=a!=null?g(h(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of i(a))if(!j.call(d,e))f(d,e,{get:()=>a[e],enumerable:!0});return d};var m=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var n=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:(d)=>b[c]=()=>d})};var p=k(import.meta.url);
export{l as $b,m as ac,n as bc,p as cc};
var g="unchanged-delete-v1";function p(e){return e.projectionBatchSemantics==="unchanged-delete-v1"&&typeof e.writeBatchIfUnchanged==="function"}function f(e){if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document query page limit must be a positive integer.");a(e.filter)}function d(e){if(e.field.trim().length===0)throw Error("Document text search field must be non-empty.");if(!Number.isSafeInteger(e.limit)||e.limit<=0)throw Error("Document text search limit must be a positive integer.");a(e.filter)}function a(e){for(let t of Object.values(e??{}))if(t!==null&&typeof t!=="boolean"&&typeof t!=="string"&&(typeof t!=="number"||!Number.isFinite(t)))throw Error("Storage filters only support scalar equality values.")}function S(e,t){if(!t)return!0;let o=e;return Object.entries(t).every(([n,r])=>o[n]===r)}function D(e,t){return{...e,...t}}var l=/[\p{L}\p{N}]+/gu;function i(e){return(e.normalize("NFKC").toLowerCase().match(l)??[]).filter((t)=>t.length>0)}function h(e){return[...new Set(i(e))].map((t)=>`"${t.replaceAll('"','""')}"`).join(" OR ")}function y(e){let t=[...new Set(i(e))];return{substrings:t.map((o)=>`%${o}%`),tsQuery:t.join(" | ")}}function T(e,t){let o=e[t];return typeof o==="string"?o:void 0}function b(e,t){let o=[...new Set(i(e))];if(o.length===0)return 0;let n=i(t),r=new Map;for(let c of n)r.set(c,(r.get(c)??0)+1);let s=0,u=0;for(let c of o){let m=r.get(c)??0;if(m>0)s+=1,u+=m}if(s===0)return 0;return s/o.length+u/Math.max(1,n.length)}
export{g as Jb,p as Kb,f as Lb,d as Mb,a as Nb,S as Ob,D as Pb,i as Qb,h as Rb,y as Sb,T as Tb,b as Ub};

Sorry, the diff of this file is too big to display

import{ac as I}from"./chunk-eqpe4gcb.js";var X=I((Y,H)=>{var{defineProperty:z,getOwnPropertyDescriptor:K,getOwnPropertyNames:L}=Object,Q=Object.prototype.hasOwnProperty,R=(j,b)=>{for(var v in b)z(j,v,{get:b[v],enumerable:!0})},U=(j,b,v,B)=>{if(b&&typeof b==="object"||typeof b==="function"){for(let q of L(b))if(!Q.call(j,q)&&q!==v)z(j,q,{get:()=>b[q],enumerable:!(B=K(b,q))||B.enumerable})}return j},W=(j)=>U(z({},"__esModule",{value:!0}),j),F={};R(F,{VercelOidcTokenError:()=>G});H.exports=W(F);class G extends Error{constructor(j,b){super(j);this.name="VercelOidcTokenError",this.cause=b}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});
export{X as _b};
import{Aa as i,Ba as n,Da as t,pa as _,qa as L}from"./chunk-963r53yf.js";import{Ha as e,Ia as QQ}from"./chunk-8d816xbx.js";import{db as p,eb as u,gb as w,ib as a,yb as q}from"./chunk-0h5pry7v.js";import{Ib as m}from"./chunk-jr0h5wkn.js";import{Wb as k}from"./chunk-c28647f0.js";import{createHash as TQ}from"node:crypto";import{createHmac as HQ}from"node:crypto";var GQ=24,UQ=1200,R=100,f=new Set(["profile","preference","fact","feedback","episode","evidence","experience","reference","archive","proposal","promotion","runtime-journal","runtime-spill","writeback-event"]);function WQ(Q){if(!f.has(Q.recordKind))throw Error(`Unsupported GoodMemory record kind: ${Q.recordKind}`);if(!Q.scopeDigest||Q.scopeDigest.includes(":"))throw Error("GoodMemory recordRef requires a non-empty colon-free scopeDigest.");if(!Q.id)throw Error("GoodMemory recordRef requires a non-empty id.");return`gmrec:v1:${Q.scopeDigest}:${Q.recordKind}:${encodeURIComponent(Q.id)}`}function JQ(Q){let Z=/^gmrec:v1:([^:]+):([^:]+):(.+)$/u.exec(Q);if(!Z)return null;let[,$,H,W]=Z;if(!f.has(H))return null;try{return{id:decodeURIComponent(W),recordKind:H,scopeDigest:$}}catch{return null}}function b(Q){return`scope_${HQ("sha256",Q.secret).update(k(Q.scope)).digest("hex").slice(0,32)}`}function x(Q){if(Q.scopeDigestSecret.trim().length<16)throw Error("ProgressiveRecallService requires a stable scopeDigestSecret.");let Z=Q.maxDetailPreviewChars??UQ,$=Q.now??(()=>new Date),H=Q.language??q(Q.memory)?.language;if(!H)throw Error("ProgressiveRecallService requires the memory LanguageService.");let W=H,Y=W.resolveFromText({text:""}),O=new Map;async function j(U){let K=U.retrievalProfile??(U.includeRuntime===!0?"coding_agent":void 0),N=await Q.memory.recall({retrievalProfile:K,locale:U.locale,query:U.query??"",scope:U.scope}),J=b({scope:U.scope,secret:Q.scopeDigestSecret}),X=N.metadata.locale??U.locale??Y.locale;return{candidates:XQ({includeRuntime:U.includeRuntime,language:W,locale:X,maxDetailPreviewChars:Z,recall:N,scope:U.scope}),generatedAt:$().toISOString(),locale:X,scopeDigest:J}}function M(U){let K=O.get(U.scopeDigest)??new Map;if(U.includeRuntime!==!0){for(let[J,X]of K)if(X.candidate.source==="runtime")K.delete(J)}let N=$().getTime();for(let J of U.selected)K.set(J.record.recordRef,{candidate:J.candidate,lastSeenAt:N});OQ(K),O.set(U.scopeDigest,K)}async function G(U){let{candidates:K,generatedAt:N,locale:J,scopeDigest:X}=await j({includeRuntime:U.includeRuntime,locale:U.locale,query:U.query,retrievalProfile:U.retrievalProfile,scope:U.scope}),V=K.map((B)=>({candidate:B,record:BQ({candidate:B,language:W,locale:J,query:U.query,scopeDigest:X})})).sort((B,P)=>AQ(B.record,P.record)),A=NQ({limit:U.limit??GQ,ranked:V});return M({includeRuntime:U.includeRuntime,scopeDigest:X,selected:A}),{generatedAt:N,locale:J,query:U.query,records:A.map((B)=>B.record),scopeDigest:X,totalRecordCount:K.length}}async function z(U){let K=await G(U),N=U.recordsPerBucket??6,J=new Map;for(let X of K.records){let V=DQ(X.occurredAt,W,K.locale??Y.locale),A=J.get(V)??[];if(A.length<N)A.push(X);J.set(V,A)}return{buckets:Array.from(J,([X,V])=>({label:X,records:V})),locale:K.locale,scopeDigest:K.scopeDigest,totalRecordCount:K.totalRecordCount}}async function F(U){let K=b({scope:U.scope,secret:Q.scopeDigestSecret}),N=O.get(K)??new Map,J=[];for(let X of U.recordRefs){let V=JQ(X);if(!V)throw Error(`Invalid GoodMemory recordRef: ${X}`);if(V.scopeDigest!==K)throw Error(`GoodMemory recordRef ${X} does not belong to the requested scope.`);let A=N.get(X);if(!A)throw Error(`GoodMemory recordRef ${X} is not available in the current progressive recall visibility set.`);let B=A.candidate,P={occurredAt:B.occurredAt,recordKind:B.recordKind,recordRef:X,title:B.title,summary:B.summary,detail:B.detail,estimatedTokens:_(JSON.stringify(B.detail))};J.push(P)}return{records:J,scopeDigest:K}}return{searchRecallIndex:G,buildRecallTimeline:z,getProgressiveRecords:F,renderProgressiveContext(U){let K=U.maxRecords??10,N=U.maxTokens?Math.max(1,Math.floor(U.maxTokens)):void 0,J=U.index.records.slice(0,K),X=U.index.locale??Y.locale,V=KQ(U,Boolean(N),W,X),A=[];for(let $Q of J){let T=zQ({header:V,lines:A,maxTokens:N,record:$Q,recordIndex:A.length,language:W,locale:X});if(!T)break;A.push(T)}let B=Math.max(0,U.index.records.length-A.length),P=B>0&&!I({header:V,lines:A,maxTokens:N,footer:[W.render({key:"omitted_records",values:{count:B}},X)]})?[W.render({key:"omitted_records",values:{count:B}},X)]:[],ZQ=[...V,...A,...P].join(`
`),h=VQ(ZQ,N);return{content:h,estimatedTokens:_(h),omittedRecordCount:B}}}}function XQ(Q){let Z=[],$=(Y,O)=>Q.language.render(O?{key:Y,values:O}:{key:Y},Q.locale),H=(Y)=>{Z.push(jQ(Y,Q.scope,Q.maxDetailPreviewChars))},W=Q.recall.profile;if(W)H({detail:{activeContext:W.activeContext,expertise:W.expertise,identity:v(W.identity,Q.scope),version:W.version},id:"profile",occurredAt:W.updatedAt,recordKind:"profile",source:"durable",summary:[...W.activeContext.goals,...W.activeContext.currentProjects].join("; "),title:$("profile")});for(let Y of Q.recall.preferences)H({detail:{category:Y.category,confidence:Y.confidence,lifecycle:Y.lifecycle,tags:Y.tags,value:Y.value},id:Y.id,occurredAt:Y.updatedAt,recordKind:"preference",source:"durable",summary:MQ(Y.value),title:`${$("preference")}: ${Y.category}`});for(let Y of Q.recall.facts)H({detail:{category:Y.category,confidence:Y.confidence,content:Y.content,factKind:Y.factKind,importance:Y.importance,lifecycle:Y.lifecycle,subject:Y.subject,tags:Y.tags},id:Y.id,occurredAt:Y.updatedAt,recordKind:"fact",source:"durable",summary:Y.content,title:qQ($("fact_item"),Y.subject??Y.category)});for(let Y of Q.recall.feedback)H({detail:{appliesTo:Y.appliesTo,confidence:Y.confidence,kind:Y.kind,lifecycle:Y.lifecycle,rule:Y.rule,tags:Y.tags,why:Y.why},id:Y.id,occurredAt:Y.updatedAt,recordKind:"feedback",source:"durable",summary:Y.rule,title:`${$("feedback")}: ${Y.kind}`});for(let Y of Q.recall.references)H({detail:{confidence:Y.confidence,description:Y.description,pointer:Y.pointer,referenceKind:Y.referenceKind,subject:Y.subject,tags:Y.tags,title:Y.title},id:Y.id,occurredAt:Y.updatedAt,recordKind:"reference",source:"durable",summary:Y.description??Y.pointer,title:Y.title});for(let Y of Q.recall.episodes)H({detail:{confidence:Y.confidence,keyDecisions:Y.keyDecisions,summary:Y.summary,topics:Y.topics,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt??Y.createdAt,recordKind:"episode",source:"durable",summary:Y.summary,title:$("episode_item")});for(let Y of Q.recall.archives)H({detail:{keyDecisions:Y.keyDecisions,referencedArtifacts:Y.referencedArtifacts,sourceSessionCount:Y.sourceSessionIds.length,summary:Y.summary,unresolvedItems:Y.unresolvedItems},id:Y.id,occurredAt:Y.archivedAt,recordKind:"archive",source:"durable",summary:Y.summary,title:Y.summary});for(let Y of Q.recall.evidence)H({detail:{excerpt:Y.excerpt,kind:Y.kind,linkedArchiveIds:Y.linkedArchiveIds,linkedMemoryIds:Y.linkedMemoryIds,sourceUri:Y.sourceUri},id:Y.id,occurredAt:Y.createdAt,recordKind:"evidence",source:"durable",summary:Y.excerpt,title:`${$("evidence")}: ${Y.kind}`});if(Q.includeRuntime===!0&&Q.recall.journal){let Y=Q.recall.journal;H({detail:{currentState:Y.currentState,errorsAndCorrections:Y.errorsAndCorrections,filesAndFunctions:Y.filesAndFunctions,keyResults:Y.keyResults,learnings:Y.learnings,taskSpecification:Y.taskSpecification,title:Y.title,workflow:Y.workflow,worklog:Y.worklog},id:"current",occurredAt:Y.updatedAt,recordKind:"runtime-journal",source:"runtime",summary:Y.currentState??Y.title??Y.worklog[0]??$("journal"),title:Y.title??$("journal")})}if(Q.includeRuntime===!0&&Q.recall.workingMemory){let Y=Q.recall.workingMemory;H({detail:{constraints:Y.constraints,currentGoal:Y.currentGoal,openLoops:Y.openLoops,state:Y.state,temporaryDecisions:Y.temporaryDecisions,toolState:Y.toolState},id:"working-memory",occurredAt:Y.updatedAt,recordKind:"runtime-journal",required:!0,source:"runtime",summary:[Y.currentGoal?`${$("current_goal")}: ${Y.currentGoal}`:void 0,Y.openLoops.length>0?`${$("open_loops")}: ${Y.openLoops.join(", ")}`:void 0].filter(SQ).join("; ")||$("working_memory"),title:$("working_memory")})}return Z}function KQ(Q,Z,$,H){if(Z)return[$.render({key:"progressive_recall"},H),`scopeDigest: ${Q.index.scopeDigest}`,$.render({key:"progressive_detail_instruction_compact"},H)];return[$.render({key:"progressive_recall"},H),`query: ${Q.query??Q.index.query??$.render({key:"none"},H)}`,`scopeDigest: ${Q.index.scopeDigest}`,`retrievalProfile: ${Q.retrievalProfile??$.render({key:"default_label"},H)}`,$.render({key:"progressive_detail_instruction"},H)]}function NQ(Q){let Z=Math.max(1,Math.floor(Q.limit)),$=new Map;for(let H of Q.ranked)if(H.candidate.required)$.set(H.record.recordRef,H);for(let H of Q.ranked){if($.size>=Z)break;$.set(H.record.recordRef,H)}return Array.from($.values()).slice(0,Z)}function zQ(Q){let Z=Q.maxTokens?[160,96,48,0]:[260];for(let $ of Z){let H=FQ({record:Q.record,recordIndex:Q.recordIndex,summaryMaxChars:$,language:Q.language,locale:Q.locale});if(!I({header:Q.header,lines:[...Q.lines,H],maxTokens:Q.maxTokens}))return H}return null}function FQ(Q){let Z=[`${Q.recordIndex+1}. ${Q.record.title}`,`${Q.language.render({key:"record_kind"},Q.locale)}: ${Q.record.recordKind}`,`${Q.language.render({key:"record_ref"},Q.locale)}: ${Q.record.recordRef}`];if(Q.summaryMaxChars>0)Z.push(`${Q.language.render({key:"summary"},Q.locale)}: ${E(Q.record.summary,Q.summaryMaxChars)}`);return Z.push(`${Q.language.render({key:"detail_tokens"},Q.locale)}: ${Q.record.estimatedDetailTokens}`),Z.join(" | ")}function I(Q){if(!Q.maxTokens)return!1;return _([...Q.header,...Q.lines,...Q.footer??[]].join(`
`))>Q.maxTokens}function VQ(Q,Z){if(!Z||_(Q)<=Z)return Q;let $="...",H=_($);if(Z<=H)return L(Q,Z);return`${L(Q,Z-H).trimEnd()}${$}`}function BQ(Q){let Z=E(Q.candidate.summary,260),$=E(Q.candidate.title,120),H=WQ({id:Q.candidate.id,recordKind:Q.candidate.recordKind,scopeDigest:Q.scopeDigest}),W=[$,Z].join(" ");return{estimatedDetailTokens:_(JSON.stringify(Q.candidate.detail)),estimatedIndexTokens:_(W),occurredAt:Q.candidate.occurredAt,recordKind:Q.candidate.recordKind,recordRef:H,score:LQ(W,Q.query,Q.language,Q.locale),source:Q.candidate.source,summary:Z,title:$}}function AQ(Q,Z){if(Z.score!==Q.score)return Z.score-Q.score;return y(Z.occurredAt)-y(Q.occurredAt)}function OQ(Q){if(Q.size<=R)return;let Z=new Set(Array.from(Q).sort(($,H)=>H[1].lastSeenAt-$[1].lastSeenAt).slice(0,R).map(([$])=>$));for(let $ of Q.keys())if(!Z.has($))Q.delete($)}function jQ(Q,Z,$){return{...Q,detail:_Q(v(Q.detail,Z),$),summary:D(Q.summary,Z),title:D(Q.title,Z)}}function v(Q,Z){return S(Q,Z)}function S(Q,Z){if(typeof Q==="string")return D(Q,Z);if(Array.isArray(Q))return Q.map(($)=>S($,Z));if(Q&&typeof Q==="object"){let $={};for(let[H,W]of Object.entries(Q)){if(PQ(H)||H==="normalizedTranscript")continue;$[H]=S(W,Z)}return $}return Q}function _Q(Q,Z){let $=JSON.stringify(Q);if($.length<=Z)return Q;return{preview:`${$.slice(0,Z)}...`,truncated:!0}}function PQ(Q){return["agentId","scope","scopeLineage","sessionId","sourceSessionIds","tenantId","userId","workspaceId"].includes(Q)}function D(Q,Z){let $=[[Z.userId,"[user]"],[Z.tenantId,"[tenant]"],[Z.workspaceId,"[workspace]"],[Z.agentId,"[agent]"],[Z.sessionId,"[session]"]],H=Q;for(let[W,Y]of $){if(!W)continue;H=H.split(W).join(Y)}return H}function qQ(Q,Z){return`${Q}: ${Z}`}function MQ(Q){if(typeof Q==="string")return Q;return JSON.stringify(Q)}function E(Q,Z){let $=Q.trim();if($.length<=Z)return $;return`${$.slice(0,Z-3).trimEnd()}...`}function LQ(Q,Z,$,H){let W=$.tokenize(Z??"",H,{excludeStopwords:!0});if(W.length===0)return 0;let Y=new Set($.tokenize(Q,H,{excludeStopwords:!0}));return W.reduce((O,j)=>O+(Y.has(j)?1:0),0)}function y(Q){if(!Q)return 0;let Z=Date.parse(Q);return Number.isNaN(Z)?0:Z}function SQ(Q){return Q!==void 0}function DQ(Q,Z,$){if(!Q)return Z.render({key:"undated"},$);let H=Date.parse(Q);if(Number.isNaN(H))return Z.render({key:"undated"},$);return new Date(H).toISOString().slice(0,10)}var EQ=/sk-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9_]{16,}/u,wQ=/\[redacted-(?:email|url-auth)\]/gu,g=m();function CQ(Q,Z=g){let $=Z.resolveFromText({text:Q});return hQ(Q,Z.analyzeContent(Q,$))}function hQ(Q,Z){return EQ.test(Q)||Z.sensitiveCredential}function d(Q,Z=g){if(!CQ(Q,Z))return Q;return[...new Set([...Q.match(wQ)??[],"[redacted-secret]"])].join(" ")}var RQ=160,bQ=10,yQ=240;function C(Q){let Z=Q?.trim();return Z?Z:null}function s(Q){for(let Z=Q.length-1;Z>=0;Z-=1){let $=Q[Z];if($?.role!=="user")continue;let H=C($.content);if(H)return H}return null}function kQ(Q,Z){if(Q.length<=Z)return Q;return`${Q.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function YQ(Q,Z){return kQ(d(Q.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[redacted-email]").replace(/\bsk-[A-Za-z0-9_-]{6,}\b/gu,"[redacted-secret]"),Z).replace(/\s+/gu," ").trim(),yQ)}function fQ(Q){let Z=[Q.userText?`user: ${Q.userText}`:void 0,Q.assistantText?`assistant: ${Q.assistantText}`:void 0].filter(($)=>Boolean($));if(Z.length===0)return null;return YQ(Z.join(" | "),Q.language)}function c(Q){return{kind:"remember_candidate",preview:Q.preview,rawTranscriptPersisted:!1,reason:Q.reason}}function o(Q){return{jobId:`runtime-kit-candidate-${TQ("sha256").update(Q).digest("hex").slice(0,16)}`,operation:"remember",payloadPreview:Q,rawTranscriptPersisted:!1,reason:"after_model_call",status:"candidate"}}function r(Q){return Q?.mode==="selective"&&Q.annotation==="durable_candidate"&&Q.policy==="allow"}function xQ(Q){return{scope:Q.scope,locale:Q.locale,messages:[{role:"user",content:Q.userText},{role:"assistant",content:Q.assistantText}],annotations:[{messageIndex:1,remember:"always",confirmed:!0,reason:"runtime-kit selective writeback approved by host annotation and policy"}]}}function l(Q){return{mode:Q,content:"",estimatedTokens:0,omittedSections:[]}}function IQ(Q){return{mode:"fragment",content:Q.builtContext.content,estimatedTokens:Q.builtContext.estimatedTokens,omittedSections:[...Q.builtContext.omittedSections]}}function vQ(Q){let Z=p({appliesTo:Q.retrievalProfile==="coding_agent"?"coding_agent":"general_response",feedback:Q.feedback,query:Q.query,surface:"text_response"}),$=u(Z),H=[...w($),...w(Q.rawCarryover?.packet?.textResponsePlan)],W=a(Z.filter(({policy:O})=>O.enactmentSurface!=="text_response"||!O.applicability.textResponsePlan));if(H.length===0&&W.length===0&&!Q.rawCarryover?.packet?.promptPayload)return IQ({builtContext:Q.builtContext});if(Q.rawCarryover?.debug.mode==="exemplar_only"&&H.length===0&&W.length===0&&Q.rawCarryover.packet?.promptPayload)return{mode:"fragment",content:Q.rawCarryover.packet.promptPayload,estimatedTokens:_(Q.rawCarryover.packet.promptPayload),omittedSections:[]};let Y=[Q.builtContext.content,Q.rawCarryover?.packet?.promptPayload,H.length>0?["Structured response control:","Apply the following controls implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...H].join(`
`):void 0,W.length>0?["Behavioral steering:","Apply the following guidance implicitly. Do not mention memory, earlier notes, or learned rules unless the user directly asks.",...W].join(`
`):void 0].filter((O)=>typeof O==="string"&&O.trim().length>0).join(`
`);return{mode:"fragment",content:Y,estimatedTokens:_(Y),omittedSections:[...Q.builtContext.omittedSections]}}function mQ(Q){if(Q.progressiveRecall)return Q.progressiveRecall;if(!Q.progressive)return null;return x({memory:Q.memory,scopeDigestSecret:Q.progressive.scopeDigestSecret,maxDetailPreviewChars:Q.progressive.maxDetailPreviewChars})}async function gQ(Q,Z){if(!Q)return;try{await Q(Z)}catch($){console.error("GoodMemory runtime-kit event callback failed.",$)}}function dQ(Q){return e({id:`${Q.hostKind}-runtime-kit`,hostKind:Q.hostKind,memory:Q.memory})}function GY(Q){let Z=q(Q.memory)?.language,$=mQ(Q),H=Q.defaultContextMode??"fragment",W=Q.defaultMaxMemoryTokens??RQ,Y=t({scopeDigestSecret:Q.scopeDigestSecret??Q.progressive?.scopeDigestSecret},()=>new Date);async function O(G){return await gQ(Q.onRuntimeEvent,G),G}async function j(G,z){return await O({...z,scopeDigest:Y.digestScope(G)})}async function M(G,z){let F=await Q.memory.recall({scope:G.scope,query:z,locale:G.locale,retrievalProfile:G.retrievalProfile,ignoreMemory:!1,...Q.evidenceLedgerFormat?{includeEvidence:!0}:{}}),U=await Q.memory.buildContext({recall:F,output:"system_prompt_fragment",maxTokens:G.maxMemoryTokens??W,...Q.evidenceLedgerFormat?{evidenceLedgerFormat:Q.evidenceLedgerFormat}:{}}),K=await(async()=>{try{let N=G.includeRuntime===!1?null:await Q.memory.runtime.getState({scope:G.scope}).catch(()=>null),J=await Q.memory.exportMemory({includeRuntime:G.includeRuntime,scope:G.scope}),X=(G.retrievalProfile??"general_chat")==="coding_agent"?"host_action":"text_response",V=N?.state?.buffer?.messages?.map((B)=>({content:B.content,role:B.role})).filter((B)=>B.content.trim().length>0)??[],A=i({memoryExport:{durable:{archives:J.durable.archives,episodes:J.durable.episodes,experiences:J.durable.experiences},scope:J.scope},recallHints:{candidateTraces:F.metadata.candidateTraces,hits:F.metadata.hits},runtimeMessages:V,surfaceHint:X});return n({index:A,maxExemplars:X==="host_action"?4:3,query:z,surfaceFamily:X})}catch{return}})();return{context:vQ({builtContext:U,feedback:F.feedback,query:z,rawCarryover:K,retrievalProfile:G.retrievalProfile??"general_chat"}),recall:F}}return{async sessionStart(G){let z=await Q.memory.runtime.startSession({scope:G.scope}),F=await j(G.scope,{phase:"sessionStart",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async beforeModelCall(G){let z=G.contextMode??H;if(G.ignoreMemory){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"ignore_memory",contextMode:z});return{context:l(z),events:[N]}}let F=C(G.query)??s(G.messages??[]);if(!F){let N=await j(G.scope,{phase:"beforeModelCall",status:"skipped",reason:"no_query",contextMode:z});return{context:l(z),events:[N]}}if(z==="progressive"&&$){let N=await $.searchRecallIndex({scope:G.scope,query:F,includeRuntime:G.includeRuntime,retrievalProfile:G.retrievalProfile}),J=$.renderProgressiveContext({index:N,query:F,retrievalProfile:G.retrievalProfile,maxRecords:G.maxProgressiveRecords??bQ,maxTokens:G.maxMemoryTokens??W}),X=await j(G.scope,{phase:"beforeModelCall",status:J.content.trim()?"applied":"skipped",reason:J.content.trim()?void 0:"empty_context",contextMode:"progressive"});return{context:{mode:"progressive",content:J.content,estimatedTokens:J.estimatedTokens,omittedSections:J.omittedRecordCount>0?[`records:${J.omittedRecordCount}`]:[],recordRefs:N.records.map((V)=>V.recordRef)},events:[X]}}let U=await M(G,F),K=await j(G.scope,{phase:"beforeModelCall",status:U.context.content.trim()?"applied":"skipped",reason:U.context.content.trim()?void 0:"empty_context",contextMode:"fragment",fallbackReason:z==="progressive"?"progressive_unavailable":void 0});return{context:U.context,recall:U.recall,events:[K]}},async afterModelCall(G){let z=G.writeback??{mode:"observe"},F=z.mode??"observe",U=C(G.assistantText),K=s(G.messages),N=fQ({assistantText:U,language:Z,userText:K}),J=[],X=[],V;if(F==="observe"&&N)J.push(c({preview:N,reason:"observe"})),X.push(o(N));else if(F==="selective"&&!r(z)&&N)J.push(c({preview:N,reason:"selective_not_allowed"})),X.push(o(N));else if(r(z)&&U&&K)V=await Q.memory.remember(xQ({scope:G.scope,locale:G.locale,userText:K,assistantText:U}));let A=await j(G.scope,{phase:"afterModelCall",status:V||J.length>0?"applied":"skipped",reason:F==="off"?"writeback_off":V||J.length>0?void 0:"no_candidate"});return{boundedJobs:X,candidates:J,events:[A],...V?{rememberResult:V}:{},trace:{candidateCount:J.length,rawTranscriptPersisted:!1,rememberCalled:Boolean(V)}}},async sessionEnd(G){let z=await Q.memory.runtime.endSession({scope:G.scope,archive:G.archive??"off"}),F=await j(G.scope,{phase:"sessionEnd",status:"succeeded",traceId:z.traceId});return{state:z.state,traceId:z.traceId,events:[F]}},async preAction(G){let F=await(Q.hostAdapter??dQ({hostKind:G.intent.hostKind,memory:Q.memory})).assessAction(G.intent),U=QQ({assessment:F,intent:G.intent}),K=await j(G.intent.scope,{phase:"preAction",status:"applied",reason:F.decision});return{assessment:F,executionPlan:U,events:[K]}},async observeToolResult(G){let z=YQ(`${G.toolName}: ${G.summary}`,Z),F=await Q.memory.runtime.updateSessionJournal({scope:G.scope,patch:{appendWorklog:[z]}}),U=await j(G.scope,{phase:"observeToolResult",status:"applied"});return{journal:F.journal,events:[U]}}}}
export{GY as oa};

Sorry, the diff of this file is too big to display

import{Ib as K}from"./chunk-jr0h5wkn.js";var C=K(),P="semantic_recall_inactive",_="semantic recall inactive — set strategy:hybrid + RETRIEVAL_PRESET";function JB(B){let $=[...B.existingMessages??[]];for(let J of B.warnings??[])if(J===P&&!$.includes(_))$.push(_);return $}function q(B){return B??"general_chat"}function A(B){let $=B.strategy??"auto",J=B.availability?.semanticSearch===!0,Z=B.availability?.llmRouting===!0;if($==="auto"){let j=Boolean(B.autoSignals&&(B.autoSignals.retrievalProfile==="coding_agent"||B.autoSignals.continuation||B.autoSignals.referenceSeeking||B.autoSignals.actionDriving||B.autoSignals.requestedSlots.some((k)=>k==="blocker"||k==="open_loop"||k==="reference")||B.autoSignals.supportSlots.includes("project_state_support")));if(J&&(B.autoStrategyBias==="hybrid"||j))return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:j?"auto routing enabled hybrid recall because the query needs continuation, references, or action-driving semantic support while keeping rules-first priorities as the hard floor.":"auto routing enabled hybrid recall because the recommended retrieval preset biases auto routing to hybrid whenever semantic search is available, keeping rules-first priorities as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",...B.autoStrategyBias==="hybrid"?{warningMessages:[_],warnings:[P]}:{},summary:J?"auto routing kept deterministic rules-only recall because the query is profile/procedural/general assistance and does not need semantic tie-breaking.":"auto routing kept deterministic rules-only recall because semantic search is unavailable.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if($==="rules-only")return{requestedStrategy:$,resolvedStrategy:"rules-only",summary:"rules-only default keeps lexical, runtime, and procedural priors as the hard floor.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1};if($==="hybrid"){if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",summary:"hybrid routing keeps rules-first priorities primary and only enables semantic tie-breaking around them.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"semantic_search_unavailable",warningMessages:[_],warnings:[P],summary:"hybrid routing was requested but semantic search is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}if(Z)return{requestedStrategy:$,resolvedStrategy:"llm-assisted",summary:"llm-assisted routing keeps rules-first priorities primary and only allows model refinement after the deterministic floor is established.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:J,llmRefinement:!0};if(J)return{requestedStrategy:$,resolvedStrategy:"hybrid",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but model refinement is unavailable, so routing falls back to hybrid semantic tie-breaking.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!0,llmRefinement:!1};return{requestedStrategy:$,resolvedStrategy:"rules-only",fallbackReason:"llm_routing_unavailable",summary:"llm-assisted routing was requested but provider-backed assistance is unavailable, so routing falls back to deterministic rules-only behavior.",hardFloor:"lexical_runtime_procedural_priors",semanticTieBreaking:!1,llmRefinement:!1}}function ZB(B){let $=q(B.retrievalProfile),J=B.language??C,Z=B.locale??J.resolveFromText({text:B.query}).locale,j=B.queryAnalysis??J.analyzeQuery(B.query,Z),X=$==="coding_agent"||j.continuation,k=j.role,W=j.focus,V=j.blocker,O=j.openLoop,D=j.referenceSeeking,Q=j.actionDriving,h=[];if(k)h.push("role");if(W)h.push("focus");if(V)h.push("blocker");if(O)h.push("open_loop");if(D)h.push("reference");let w=[];if(Q&&(h.includes("role")||h.includes("focus")||h.includes("reference")))w.push("project_state_support");if(X)w.push("runtime_continuity");let G=A({strategy:B.strategy,autoStrategyBias:B.autoStrategyBias,availability:B.availability,autoSignals:{retrievalProfile:$,requestedSlots:h,supportSlots:w,continuation:X,referenceSeeking:D,actionDriving:Q}}),R=X||Q||D?["evidence"]:[];if(X)return{retrievalProfile:$,intent:"task_continuation",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["working_memory","session_journal","session_archive","episode","fact",...R,"feedback","profile"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X};return{retrievalProfile:$,intent:"general_assistance",strategy:G.resolvedStrategy,strategyExplanation:G,sourcePriorities:["profile","feedback","fact",...R,"episode","working_memory","session_journal"],requestedSlots:h,supportSlots:w,actionDriving:Q,referenceSeeking:D,continuation:X}}class N extends Error{stage;constructor(B){super(`Provider-backed recall failed during ${B.stage}.`,{cause:B.cause});this.name="ProviderBackedRecallError",this.stage=B.stage}}function XB(B){return B instanceof N}import{resolve as L}from"node:path";var b=["openai","anthropic"];function T(B){return b.includes(B)}var S=Symbol.for("goodmemory.embedding.hashed-lexical");function x(B){let $=B.extraction?.mode,J=$==="conversational"?"conversational":"default";if(B.retrieval?.preset===void 0)return{extractionMode:J,...B.providerRerankerConfigured?{providerRerankingStrategy:"pointwise"}:{},retrieval:{bm25Ranking:B.retrieval?.bm25Ranking,semanticCandidates:B.retrieval?.semanticCandidates}};if(B.adapters?.embeddingAdapter?.[S]===!0)throw Error(`retrieval.preset "recommended" accepts either no embedding adapter or a neural semantic adapter; createLocalEmbeddingAdapter() produces hashed-lexical vectors and would duplicate the preset's lexical channel as fake dense evidence. Remove that adapter, configure a neural endpoint (GOODMEMORY_EMBEDDING_* or providers.embedding), or remove retrieval.preset.`);let j=B.retrieval.semanticCandidates,X=B.embeddingEnabled?{...j,topK:j?.topK??16}:j,k={...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},maxCandidates:8,maxTotalFacts:10},W=B.providerRerankerConfigured||B.adapters?.reranker?{...B.retrieval.generalizedFusionChannels?{channels:B.retrieval.generalizedFusionChannels}:{},...B.retrieval.generalizedFusionMinRelativeStrength!==void 0?{minRelativeStrength:B.retrieval.generalizedFusionMinRelativeStrength}:{},maxCandidates:32,maxTotalFacts:32}:void 0,V=J,O;if($!==void 0)O=$==="conversational"?"conversational":"kept_existing";else if(B.adapters?.assistedExtractor)O="kept_existing";else if(B.assistedExtractorModelConfigured)V="conversational",O="conversational";else O="unavailable";return{extractionMode:V,...B.providerRerankerConfigured?{providerRerankingStrategy:"listwise"}:{},retrieval:{autoStrategyBias:"hybrid",bm25Ranking:B.retrieval.bm25Ranking,generalizedFusion:k,preset:{active:!0,extraction:O,requested:"recommended"},...W?{rerankGeneralizedFusion:W}:{},semanticCandidates:X}}}var y=".goodmemory/memory.sqlite",f="GOODMEMORY_STORAGE_PROVIDER",m="GOODMEMORY_STORAGE_URL",H="GOODMEMORY_EMBEDDING",z="GOODMEMORY_ASSISTED_EXTRACTOR";function Y(B){if(!B)return;let $=B.trim();return $.length>0?$:void 0}function c(B){return B?.provider!==void 0||Y(B?.url)!==void 0}function v(B){return Boolean(B?.assistedExtractor||B?.documentStore||B?.embeddingAdapter||B?.reranker||B?.recallPlanner||B?.sessionStore||B?.vectorStore)}function g(B){let $=[];if(B?.documentStore)$.push("documentStore");if(B?.sessionStore)$.push("sessionStore");if(B?.vectorStore)$.push("vectorStore");return $}function U(B){let $=B;if($===void 0||$==="memory"||$==="sqlite"||$==="postgres")return $;throw Error(`Unsupported storage provider: ${$}. Expected memory|sqlite|postgres.`)}function d(B,$){let J=Y(B?.url);if(B?.provider!==void 0||J!==void 0)return{provider:U(B?.provider),url:J};return{provider:U(Y($[f])),url:Y($[m])}}function l(){return typeof globalThis.Bun<"u"}function s(){return typeof globalThis.Bun<"u"}function E(B){let $=B?.builtInSQLite??B?.localDefaultSQLite??l(),J=B?.builtInPostgres??s(),Z=B?.localDefaultSQLite??$;return{builtInPostgres:J,builtInSQLite:$,localDefaultSQLite:Z}}function a(B){return/^(?:postgres|postgresql):\/\//i.test(B.trim())}function F(B,$=process.cwd()){let J=Y(B);if(!J)return L($,y);return J===":memory:"?J:L($,J)}function p(B){let $=B.env??process.env,J=B.cwd??process.cwd(),Z=E(B.runtimeCapabilities).localDefaultSQLite,j=d(B.storage,$),X=j.provider,k=j.url;if(X==="memory")return{mode:"explicit",storage:{provider:"memory"}};if(X==="sqlite")return{mode:"explicit",storage:{provider:"sqlite",url:F(k,J)}};if(X==="postgres"){if(!k)throw Error("Postgres storage provider requires storage.url to be configured.");return{mode:"explicit",storage:{provider:"postgres",url:k}}}if(k&&a(k)){if(!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:k};return{mode:"auto",postgresUrl:k,sqliteUrl:F(void 0,J)}}if(!k&&!Z)return{mode:"auto",fallbackProvider:"memory",postgresUrl:void 0};return{mode:"auto",postgresUrl:void 0,sqliteUrl:F(k,J)}}function I(B){let $=B.env??process.env,J=E(B.runtimeCapabilities),Z=B.config.adapters?.embeddingAdapter?null:o(B.config.providers?.embedding)??n($),j=B.config.adapters?.assistedExtractor?null:r(B.config.providers?.extraction)??t($),X=B.config.adapters?.reranker?null:u(B.config.providers?.reranking),k=Boolean(B.config.adapters?.embeddingAdapter||Z),W=x({adapters:B.config.adapters,assistedExtractorModelConfigured:Boolean(j),embeddingEnabled:k,extraction:B.config.providers?.extraction,providerRerankerConfigured:Boolean(X),retrieval:B.config.retrieval});return{assistedExtractionEnabled:Boolean(B.config.adapters?.assistedExtractor||j),assistedExtractorModelConfig:j,embeddingEnabled:k,embeddingModelConfig:Z,rerankerModelConfig:X,rerankingEnabled:Boolean(B.config.adapters?.reranker||X),...W.providerRerankingStrategy?{providerRerankingStrategy:W.providerRerankingStrategy}:{},extractionMode:W.extractionMode,retrieval:W.retrieval,explicitAdaptersConfigured:v(B.config.adapters),explicitStorageConfigured:c(B.config.storage),runtimeCapabilities:J,storageAdapterOverrides:g(B.config.adapters),storagePlan:p({storage:B.config.storage,env:$,cwd:B.cwd,runtimeCapabilities:J})}}function u(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0||!$||!J||!Z)throw Error(`Missing required providers.reranking configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported reranking provider: ${$}. Expected one of openai|anthropic.`);return{apiKey:Z,baseURL:j,model:J,provider:$}}function o(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.embedding configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function r(B){if(!B)return null;let $=Y(B.provider),J=Y(B.model),Z=Y(B.apiKey),j=Y(B.baseURL),X=[!$?"provider":null,!J?"model":null,!Z?"apiKey":null].filter(Boolean);if(X.length>0)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required providers.extraction configuration fields: ${X.join(", ")}`);if(!T($))throw Error(`Unsupported extraction provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function n(B=process.env){let $=Y(B[`${H}_PROVIDER`]),J=Y(B[`${H}_MODEL`]),Z=Y(B[`${H}_API_KEY`]),j=Y(B[`${H}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${H}_PROVIDER`:null,!J?`${H}_MODEL`:null,!Z?`${H}_API_KEY`:null].filter(Boolean);if(k.length>0){let D=j&&k.length===1&&!Z?" (local OpenAI-compatible endpoints such as Ollama accept any placeholder value, e.g. GOODMEMORY_EMBEDDING_API_KEY=ollama)":"";throw Error(`Missing required ${H} environment variables: ${k.join(", ")}${D}`)}if(!$||!J||!Z)throw Error(`Missing required ${H} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported embedding provider: ${$}. Expected one of openai.`);if($!=="openai")throw Error(`Unsupported embedding provider: ${$}. GoodMemory currently supports openai embeddings only.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}function t(B=process.env){let $=Y(B[`${z}_PROVIDER`]),J=Y(B[`${z}_MODEL`]),Z=Y(B[`${z}_API_KEY`]),j=Y(B[`${z}_BASE_URL`]);if(!Boolean($||J||Z||j))return null;let k=[!$?`${z}_PROVIDER`:null,!J?`${z}_MODEL`:null,!Z?`${z}_API_KEY`:null].filter(Boolean);if(k.length>0)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!$||!J||!Z)throw Error(`Missing required ${z} environment variables: ${k.join(", ")}`);if(!T($))throw Error(`Unsupported assisted extractor provider: ${$}. Expected one of openai|anthropic.`);return{provider:$,model:J,apiKey:Z,baseURL:j}}var M=Symbol.for("goodmemory.runtime.info");function e(B){let{runtimeCapabilities:$,storageAdapterOverrides:J,storagePlan:Z}=B;if(J.length>0)return{mode:"adapter",primaryProvider:"adapter",durability:"adapter_defined",overriddenStores:[...J]};if(Z.mode==="explicit"){if(Z.storage.provider==="memory")return{mode:"explicit",primaryProvider:"memory",durability:"ephemeral",postgresConfigured:!1};if(Z.storage.provider==="sqlite"){if(!$.builtInSQLite)return{mode:"explicit",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.storage.url,unavailableReason:"runtime_without_builtin_sqlite"};return{mode:"explicit",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.storage.url}}if(!$.builtInPostgres)return{mode:"explicit",primaryProvider:"postgres",durability:"unavailable",postgresConfigured:!0,unavailableReason:"runtime_without_builtin_postgres"};return{mode:"explicit",primaryProvider:"postgres",durability:"durable",postgresConfigured:!0}}if("sqliteUrl"in Z){if(!Z.postgresUrl&&!$.builtInSQLite)return{mode:"auto",primaryProvider:"sqlite",durability:"unavailable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl,unavailableReason:"runtime_without_builtin_sqlite"};if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"sqlite",durability:"durable",postgresConfigured:!0,sqliteUrl:Z.sqliteUrl};return{mode:"auto",primaryProvider:"sqlite",durability:"durable",postgresConfigured:!1,sqliteUrl:Z.sqliteUrl}}if(Z.postgresUrl)return{mode:"auto",primaryProvider:"postgres",fallbackProvider:"memory",durability:"conditional",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!0};return{mode:"auto",primaryProvider:"memory",durability:"ephemeral",fallbackReason:"runtime_without_local_sqlite",postgresConfigured:!1}}function i(B){return{assistedExtractionEnabled:B.assistedExtractionEnabled,embeddingEnabled:B.embeddingEnabled,explicitAdaptersConfigured:B.explicitAdaptersConfigured,explicitStorageConfigured:B.explicitStorageConfigured,...B.retrieval.preset?{retrievalPreset:B.retrieval.preset}:{},storage:e(B)}}function TB(B){return i(I(B))}function VB(B,$){return B[M]=$,B}function QB(B){return B[M]}
export{P as ca,JB as da,q as ea,A as fa,ZB as ga,N as ha,XB as ia,I as ja,i as ka,TB as la,VB as ma,QB as na};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display