zam-core 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/app.js +828 -218
- package/dist/cli/app.js.map +1 -1
- package/dist/cli/commands/mcp.js +712 -234
- package/dist/cli/commands/mcp.js.map +1 -1
- package/dist/copilot-extension/extension.mjs +35 -0
- package/dist/copilot-extension/host.bundle.js +1 -1
- package/dist/copilot-extension/manifest.json +1 -1
- package/dist/copilot-extension/mcp-client.bundle.mjs +1 -1
- package/dist/index.d.ts +39 -1
- package/dist/index.js +79 -4
- package/dist/index.js.map +1 -1
- package/dist/ui/graph-panel.html +80 -40
- package/dist/ui/okf-panel.html +146 -21
- package/dist/vscode-extension/ZAM_Companion_0.15.0.vsix +0 -0
- package/dist/vscode-extension/extension.cjs +19 -18
- package/dist/vscode-extension/host.bundle.js +3 -2
- package/dist/vscode-extension/manifest.json +2 -2
- package/package.json +1 -1
- package/dist/vscode-extension/ZAM_Companion_0.13.0.vsix +0 -0
|
@@ -31,6 +31,16 @@ const APP_CONFIG = {
|
|
|
31
31
|
toolName: "zam_show_graph",
|
|
32
32
|
allowedTools: new Set(["zam_studio_bridge"]),
|
|
33
33
|
},
|
|
34
|
+
okf: {
|
|
35
|
+
title: "ZAM Knowledge Base",
|
|
36
|
+
toolName: "zam_okf_visualize",
|
|
37
|
+
allowedTools: new Set([
|
|
38
|
+
"zam_okf_catalog",
|
|
39
|
+
"zam_okf_read",
|
|
40
|
+
"zam_okf_read_citation",
|
|
41
|
+
"zam_okf_focus",
|
|
42
|
+
]),
|
|
43
|
+
},
|
|
34
44
|
settings: {
|
|
35
45
|
title: "ZAM Settings",
|
|
36
46
|
toolName: "zam_open_settings",
|
|
@@ -79,6 +89,11 @@ function compactObject(value) {
|
|
|
79
89
|
}
|
|
80
90
|
|
|
81
91
|
function buildToolArguments(kind, input) {
|
|
92
|
+
// `okf` takes no `user`: `zam_okf_visualize` is repo-scoped and its input
|
|
93
|
+
// schema only knows `bundle_dir`.
|
|
94
|
+
if (kind === "okf") {
|
|
95
|
+
return compactObject({ bundle_dir: input?.bundle_dir });
|
|
96
|
+
}
|
|
82
97
|
const common = { user: input?.user };
|
|
83
98
|
if (kind === "recall") {
|
|
84
99
|
return compactObject({ ...common, domain: input?.domain });
|
|
@@ -491,6 +506,26 @@ await joinSession({
|
|
|
491
506
|
open: (context) => openApp("graph", context),
|
|
492
507
|
onClose: closeApp,
|
|
493
508
|
}),
|
|
509
|
+
createCanvas({
|
|
510
|
+
id: "zam-knowledge",
|
|
511
|
+
displayName: "ZAM Knowledge Base",
|
|
512
|
+
description:
|
|
513
|
+
"Open the ZAM OKF knowledge-base visualizer MCP App in a hosted Copilot canvas.",
|
|
514
|
+
inputSchema: {
|
|
515
|
+
type: "object",
|
|
516
|
+
properties: {
|
|
517
|
+
bundle_dir: {
|
|
518
|
+
type: "string",
|
|
519
|
+
description:
|
|
520
|
+
"Bundle directory (default docs/okf under the zam server cwd).",
|
|
521
|
+
},
|
|
522
|
+
},
|
|
523
|
+
additionalProperties: false,
|
|
524
|
+
},
|
|
525
|
+
actions: [connectionStatusAction()],
|
|
526
|
+
open: (context) => openApp("okf", context),
|
|
527
|
+
onClose: closeApp,
|
|
528
|
+
}),
|
|
494
529
|
createCanvas({
|
|
495
530
|
id: "zam-settings",
|
|
496
531
|
displayName: "ZAM Settings",
|
|
@@ -71,4 +71,4 @@ var fg=Object.create;var Zn=Object.defineProperty;var mg=Object.getOwnPropertyDe
|
|
|
71
71
|
|
|
72
72
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function vs(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),m=f.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,l),a._zod.parent===d)for(let y in u)y==="$ref"||y==="allOf"||y in l||delete u[y];if(m.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let m in u)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(u[m])===JSON.stringify(f.def[m])&&delete u[m]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())o(a[0]);let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}Object.assign(n,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&n.id===s&&delete n.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?n.$defs=i:n.definitions=i);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:wr(e,"input",t.processors),output:wr(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function he(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return he(o.element,r);if(o.type==="set")return he(o.valueType,r);if(o.type==="lazy")return he(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return he(o.innerType,r);if(o.type==="intersection")return he(o.left,r)||he(o.right,r);if(o.type==="record"||o.type==="map")return he(o.keyType,r)||he(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:he(o.in,r)||he(o.out,r);if(o.type==="object"){for(let n in o.shape)if(he(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(he(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(he(n,r))return!0;return!!(o.rest&&he(o.rest,r))}return!1}var nd=(t,e={})=>r=>{let o=_s({...r,processors:e});return re(t,o),ys(o,t),vs(o,t)},wr=(t,e,r={})=>o=>{let{libraryOptions:n,target:s}=o??{},i=_s({...n??{},target:s,io:e,processors:r});return re(t,i),ys(i,t),vs(i,t)};var e_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sd=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(n.minLength=s),typeof i=="number"&&(n.maxLength=i),a&&(n.format=e_[a]??a,n.format===""&&delete n.format,a==="time"&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?n.pattern=l[0].source:l.length>1&&(n.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},id=(t,e,r,o)=>{let n=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?n.type="integer":n.type="number";let d=typeof l=="number"&&l>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";d?f?(n.minimum=l,n.exclusiveMinimum=!0):n.exclusiveMinimum=l:typeof s=="number"&&(n.minimum=s),p?f?(n.maximum=u,n.exclusiveMaximum=!0):n.exclusiveMaximum=u:typeof i=="number"&&(n.maximum=i),typeof c=="number"&&(n.multipleOf=c)},ad=(t,e,r,o)=>{r.type="boolean"};var cd=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var ud=(t,e,r,o)=>{r.not={}};var ld=(t,e,r,o)=>{};var dd=(t,e,r,o)=>{let n=t._zod.def,s=pr(n.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},pd=(t,e,r,o)=>{let n=t._zod.def,s=[];for(let i of n.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var fd=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var md=(t,e,r,o)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var hd=(t,e,r,o)=>{let n=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(n.minItems=i),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=re(s.element,e,{...o,path:[...o.path,"items"]})},gd=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object",n.properties={};let i=s.shape;for(let u in i)n.properties[u]=re(i[u],e,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let l=s.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(n.required=Array.from(c)),s.catchall?._zod.def.type==="never"?n.additionalProperties=!1:s.catchall?s.catchall&&(n.additionalProperties=re(s.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},_d=(t,e,r,o)=>{let n=t._zod.def,s=n.inclusive===!1,i=n.options.map((a,c)=>re(a,e,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},yd=(t,e,r,o)=>{let n=t._zod.def,s=re(n.left,e,{...o,path:[...o.path,"allOf",0]}),i=re(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var vd=(t,e,r,o)=>{let n=r,s=t._zod.def;n.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let l=re(s.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of c)n.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(n.propertyNames=re(s.keyType,e,{...o,path:[...o.path,"propertyNames"]})),n.additionalProperties=re(s.valueType,e,{...o,path:[...o.path,"additionalProperties"]});let u=i._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l)}},$d=(t,e,r,o)=>{let n=t._zod.def,s=re(n.innerType,e,o),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},bd=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType},wd=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},zd=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))},xd=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType;let i;try{i=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},Sd=(t,e,r,o)=>{let n=t._zod.def,s=n.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?n.out:n.in:n.out;re(i,e,o);let a=e.seen.get(t);a.ref=i},kd=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType,r.readOnly=!0};var $s=(t,e,r,o)=>{let n=t._zod.def;re(n.innerType,e,o);let s=e.seen.get(t);s.ref=n.innerType};function Dt(t){return!!t._zod}function Ae(t,e){return Dt(t)?_r(t,e):t.safeParse(e)}function To(t){if(!t)return;let e;if(Dt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Pd(t){if(Dt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let o=t.value;if(o!==void 0)return o}var xr={};uc(xr,{ZodISODate:()=>Td,ZodISODateTime:()=>Ed,ZodISODuration:()=>Rd,ZodISOTime:()=>Od,date:()=>ws,datetime:()=>bs,duration:()=>xs,time:()=>zs});var Ed=g("ZodISODateTime",(t,e)=>{Au.init(t,e),Q.init(t,e)});function bs(t){return Vl(Ed,t)}var Td=g("ZodISODate",(t,e)=>{qu.init(t,e),Q.init(t,e)});function ws(t){return Jl(Td,t)}var Od=g("ZodISOTime",(t,e)=>{Du.init(t,e),Q.init(t,e)});function zs(t){return Hl(Od,t)}var Rd=g("ZodISODuration",(t,e)=>{Mu.init(t,e),Q.init(t,e)});function xs(t){return Kl(Rd,t)}var u_=(t,e)=>{ho.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>$c(t,r)},flatten:{value:r=>vc(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Zt,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Zt,2)}},isEmpty:{get(){return t.issues.length===0}}})};var ke=g("ZodError",u_,{Parent:Error});var Id=go(ke),Nd=_o(ke),jd=gr(ke),Zd=yr(ke),Cd=bc(ke),Ad=wc(ke),qd=zc(ke),Dd=xc(ke),Md=Sc(ke),Ld=kc(ke),Fd=Pc(ke),Ud=Ec(ke);var Vd=new WeakMap;function Sr(t,e,r){let o=Object.getPrototypeOf(t),n=Vd.get(o);if(n||(n=new Set,Vd.set(o,n)),!n.has(e)){n.add(e);for(let s in r){let i=r[s];Object.defineProperty(o,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var te=g("ZodType",(t,e)=>(K.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:wr(t,"input"),output:wr(t,"output")}}),t.toJSONSchema=nd(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,o)=>Id(t,r,o,{callee:t.parse}),t.safeParse=(r,o)=>jd(t,r,o),t.parseAsync=async(r,o)=>Nd(t,r,o,{callee:t.parseAsync}),t.safeParseAsync=async(r,o)=>Zd(t,r,o),t.spa=t.safeParseAsync,t.encode=(r,o)=>Cd(t,r,o),t.decode=(r,o)=>Ad(t,r,o),t.encodeAsync=async(r,o)=>qd(t,r,o),t.decodeAsync=async(r,o)=>Dd(t,r,o),t.safeEncode=(r,o)=>Md(t,r,o),t.safeDecode=(r,o)=>Ld(t,r,o),t.safeEncodeAsync=async(r,o)=>Fd(t,r,o),t.safeDecodeAsync=async(r,o)=>Ud(t,r,o),Sr(t,"ZodType",{check(...r){let o=this.def;return this.clone(q.mergeDefs(o,{checks:[...o.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return Ce(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(X_(r,o))},superRefine(r,o){return this.check(ey(r,o))},overwrite(r){return this.check(at(r))},optional(){return ee(this)},exactOptional(){return L_(this)},nullable(){return Bd(this)},nullish(){return ee(Bd(this))},nonoptional(r){return K_(this,r)},array(){return C(this)},or(r){return G([this,r])},and(r){return Ro(this,r)},transform(r){return Gd(this,tp(r))},default(r){return V_(this,r)},prefault(r){return H_(this,r)},catch(r){return G_(this,r)},pipe(r){return Gd(this,r)},readonly(){return Q_(this)},describe(r){let o=this.clone();return vt.add(o,{description:r}),o},meta(...r){if(r.length===0)return vt.get(this);let o=this.clone();return vt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return vt.get(t)?.description},configurable:!0}),t)),Wd=g("_ZodString",(t,e)=>{zo.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,n,s)=>sd(t,o,n,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Sr(t,"_ZodString",{regex(...o){return this.check(is(...o))},includes(...o){return this.check(us(...o))},startsWith(...o){return this.check(ls(...o))},endsWith(...o){return this.check(ds(...o))},min(...o){return this.check(qt(...o))},max(...o){return this.check(Po(...o))},length(...o){return this.check(Eo(...o))},nonempty(...o){return this.check(qt(1,...o))},lowercase(o){return this.check(as(o))},uppercase(o){return this.check(cs(o))},trim(){return this.check(fs())},normalize(...o){return this.check(ps(...o))},toLowerCase(){return this.check(ms())},toUpperCase(){return this.check(hs())},slugify(){return this.check(gs())}})}),d_=g("ZodString",(t,e)=>{zo.init(t,e),Wd.init(t,e),t.email=r=>t.check(zl(p_,r)),t.url=r=>t.check(El(f_,r)),t.jwt=r=>t.check(Ul(E_,r)),t.emoji=r=>t.check(Tl(m_,r)),t.guid=r=>t.check(ss(Jd,r)),t.uuid=r=>t.check(xl(Oo,r)),t.uuidv4=r=>t.check(Sl(Oo,r)),t.uuidv6=r=>t.check(kl(Oo,r)),t.uuidv7=r=>t.check(Pl(Oo,r)),t.nanoid=r=>t.check(Ol(h_,r)),t.guid=r=>t.check(ss(Jd,r)),t.cuid=r=>t.check(Rl(g_,r)),t.cuid2=r=>t.check(Il(__,r)),t.ulid=r=>t.check(Nl(y_,r)),t.base64=r=>t.check(Ml(S_,r)),t.base64url=r=>t.check(Ll(k_,r)),t.xid=r=>t.check(jl(v_,r)),t.ksuid=r=>t.check(Zl($_,r)),t.ipv4=r=>t.check(Cl(b_,r)),t.ipv6=r=>t.check(Al(w_,r)),t.cidrv4=r=>t.check(ql(z_,r)),t.cidrv6=r=>t.check(Dl(x_,r)),t.e164=r=>t.check(Fl(P_,r)),t.datetime=r=>t.check(bs(r)),t.date=r=>t.check(ws(r)),t.time=r=>t.check(zs(r)),t.duration=r=>t.check(xs(r))});function h(t){return wl(d_,t)}var Q=g("ZodStringFormat",(t,e)=>{B.init(t,e),Wd.init(t,e)}),p_=g("ZodEmail",(t,e)=>{Eu.init(t,e),Q.init(t,e)});var Jd=g("ZodGUID",(t,e)=>{ku.init(t,e),Q.init(t,e)});var Oo=g("ZodUUID",(t,e)=>{Pu.init(t,e),Q.init(t,e)});var f_=g("ZodURL",(t,e)=>{Tu.init(t,e),Q.init(t,e)});var m_=g("ZodEmoji",(t,e)=>{Ou.init(t,e),Q.init(t,e)});var h_=g("ZodNanoID",(t,e)=>{Ru.init(t,e),Q.init(t,e)});var g_=g("ZodCUID",(t,e)=>{Iu.init(t,e),Q.init(t,e)});var __=g("ZodCUID2",(t,e)=>{Nu.init(t,e),Q.init(t,e)});var y_=g("ZodULID",(t,e)=>{ju.init(t,e),Q.init(t,e)});var v_=g("ZodXID",(t,e)=>{Zu.init(t,e),Q.init(t,e)});var $_=g("ZodKSUID",(t,e)=>{Cu.init(t,e),Q.init(t,e)});var b_=g("ZodIPv4",(t,e)=>{Lu.init(t,e),Q.init(t,e)});var w_=g("ZodIPv6",(t,e)=>{Fu.init(t,e),Q.init(t,e)});var z_=g("ZodCIDRv4",(t,e)=>{Uu.init(t,e),Q.init(t,e)});var x_=g("ZodCIDRv6",(t,e)=>{Vu.init(t,e),Q.init(t,e)});var S_=g("ZodBase64",(t,e)=>{Hu.init(t,e),Q.init(t,e)});var k_=g("ZodBase64URL",(t,e)=>{Ku.init(t,e),Q.init(t,e)});var P_=g("ZodE164",(t,e)=>{Bu.init(t,e),Q.init(t,e)});var E_=g("ZodJWT",(t,e)=>{Gu.init(t,e),Q.init(t,e)});var Yd=g("ZodNumber",(t,e)=>{es.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,n,s)=>id(t,o,n,s),Sr(t,"ZodNumber",{gt(o,n){return this.check(So(o,n))},gte(o,n){return this.check(br(o,n))},min(o,n){return this.check(br(o,n))},lt(o,n){return this.check(xo(o,n))},lte(o,n){return this.check($r(o,n))},max(o,n){return this.check($r(o,n))},int(o){return this.check(Hd(o))},safe(o){return this.check(Hd(o))},positive(o){return this.check(So(0,o))},nonnegative(o){return this.check(br(0,o))},negative(o){return this.check(xo(0,o))},nonpositive(o){return this.check($r(0,o))},multipleOf(o,n){return this.check(ko(o,n))},step(o,n){return this.check(ko(o,n))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function U(t){return Bl(Yd,t)}var T_=g("ZodNumberFormat",(t,e)=>{Wu.init(t,e),Yd.init(t,e)});function Hd(t){return Gl(T_,t)}var O_=g("ZodBoolean",(t,e)=>{Yu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ad(t,r,o,n)});function se(t){return Wl(O_,t)}var R_=g("ZodNull",(t,e)=>{Qu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>cd(t,r,o,n)});function Qd(t){return Yl(R_,t)}var I_=g("ZodUnknown",(t,e)=>{Xu.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ld(t,r,o,n)});function X(){return Ql(I_)}var N_=g("ZodNever",(t,e)=>{el.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ud(t,r,o,n)});function j_(t){return Xl(N_,t)}var Z_=g("ZodArray",(t,e)=>{tl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hd(t,r,o,n),t.element=e.element,Sr(t,"ZodArray",{min(r,o){return this.check(qt(r,o))},nonempty(r){return this.check(qt(1,r))},max(r,o){return this.check(Po(r,o))},length(r,o){return this.check(Eo(r,o))},unwrap(){return this.element}})});function C(t,e){return ed(Z_,t,e)}var Xd=g("ZodObject",(t,e)=>{nl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gd(t,r,o,n),q.defineLazy(t,"shape",()=>e.shape),Sr(t,"ZodObject",{keyof(){return ve(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:X()})},loose(){return this.clone({...this._zod.def,catchall:X()})},strict(){return this.clone({...this._zod.def,catchall:j_()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return q.extend(this,r)},safeExtend(r){return q.safeExtend(this,r)},merge(r){return q.merge(this,r)},pick(r){return q.pick(this,r)},omit(r){return q.omit(this,r)},partial(...r){return q.partial(rp,this,r[0])},required(...r){return q.required(op,this,r[0])}})});function b(t,e){let r={type:"object",shape:t??{},...q.normalizeParams(e)};return new Xd(r)}function ge(t,e){return new Xd({type:"object",shape:t,catchall:X(),...q.normalizeParams(e)})}var ep=g("ZodUnion",(t,e)=>{ts.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_d(t,r,o,n),t.options=e.options});function G(t,e){return new ep({type:"union",options:t,...q.normalizeParams(e)})}var C_=g("ZodDiscriminatedUnion",(t,e)=>{ep.init(t,e),sl.init(t,e)});function ks(t,e,r){return new C_({type:"union",options:e,discriminator:t,...q.normalizeParams(r)})}var A_=g("ZodIntersection",(t,e)=>{il.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yd(t,r,o,n)});function Ro(t,e){return new A_({type:"intersection",left:t,right:e})}var Kd=g("ZodRecord",(t,e)=>{al.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vd(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function H(t,e,r){return!e||!e._zod?new Kd({type:"record",keyType:h(),valueType:t,...q.normalizeParams(e)}):new Kd({type:"record",keyType:t,valueType:e,...q.normalizeParams(r)})}var Ss=g("ZodEnum",(t,e)=>{cl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(o,n,s)=>dd(t,o,n,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let s={};for(let i of o)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Ss({...e,checks:[],...q.normalizeParams(n),entries:s})},t.exclude=(o,n)=>{let s={...e.entries};for(let i of o)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Ss({...e,checks:[],...q.normalizeParams(n),entries:s})}});function ve(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new Ss({type:"enum",entries:r,...q.normalizeParams(e)})}var q_=g("ZodLiteral",(t,e)=>{ul.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>pd(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function S(t,e){return new q_({type:"literal",values:Array.isArray(t)?t:[t],...q.normalizeParams(e)})}var D_=g("ZodTransform",(t,e)=>{ll.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>md(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Nt(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(q.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(q.issue(i))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=n,r.fallback=!0,r)}});function tp(t){return new D_({type:"transform",transform:t})}var rp=g("ZodOptional",(t,e)=>{rs.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$s(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ee(t){return new rp({type:"optional",innerType:t})}var M_=g("ZodExactOptional",(t,e)=>{dl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$s(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function L_(t){return new M_({type:"optional",innerType:t})}var F_=g("ZodNullable",(t,e)=>{pl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$d(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Bd(t){return new F_({type:"nullable",innerType:t})}var U_=g("ZodDefault",(t,e)=>{fl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wd(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function V_(t,e){return new U_({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var J_=g("ZodPrefault",(t,e)=>{ml.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zd(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function H_(t,e){return new J_({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():q.shallowClone(e)}})}var op=g("ZodNonOptional",(t,e)=>{hl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bd(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function K_(t,e){return new op({type:"nonoptional",innerType:t,...q.normalizeParams(e)})}var B_=g("ZodCatch",(t,e)=>{gl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xd(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function G_(t,e){return new B_({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var np=g("ZodPipe",(t,e)=>{os.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>Sd(t,r,o,n),t.in=e.in,t.out=e.out});function Gd(t,e){return new np({type:"pipe",in:t,out:e})}var W_=g("ZodPreprocess",(t,e)=>{np.init(t,e),_l.init(t,e)}),Y_=g("ZodReadonly",(t,e)=>{yl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kd(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function Q_(t){return new Y_({type:"readonly",innerType:t})}var sp=g("ZodCustom",(t,e)=>{vl.init(t,e),te.init(t,e),t._zod.processJSONSchema=(r,o,n)=>fd(t,r,o,n)});function ip(t,e){return td(sp,t??(()=>!0),e)}function X_(t,e={}){return rd(sp,t,e)}function ey(t,e){return od(t,e)}function Ps(t,e){return new W_({type:"pipe",in:tp(t),out:e})}Se($l());var Ts="2025-11-25";var ap=[Ts,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ct="io.modelcontextprotocol/related-task",No="2.0",ne=ip(t=>t!==null&&(typeof t=="object"||typeof t=="function")),cp=G([h(),U().int()]),up=h(),IP=ge({ttl:U().optional(),pollInterval:U().optional()}),ty=b({ttl:U().optional()}),ry=b({taskId:h()}),Os=ge({progressToken:cp.optional(),[ct]:ry.optional()}),Pe=b({_meta:Os.optional()}),kr=Pe.extend({task:ty.optional()}),lp=t=>kr.safeParse(t).success,ae=b({method:h(),params:Pe.loose().optional()}),Oe=b({_meta:Os.optional()}),Re=b({method:h(),params:Oe.loose().optional()}),ce=ge({_meta:Os.optional()}),jo=G([h(),U().int()]),dp=b({jsonrpc:S(No),id:jo,...ae.shape}).strict(),Rs=t=>dp.safeParse(t).success,pp=b({jsonrpc:S(No),...Re.shape}).strict(),fp=t=>pp.safeParse(t).success,Is=b({jsonrpc:S(No),id:jo,result:ce}).strict(),Pr=t=>Is.safeParse(t).success;var O;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(O||(O={}));var Ns=b({jsonrpc:S(No),id:jo.optional(),error:b({code:U().int(),message:h(),data:X().optional()})}).strict();var mp=t=>Ns.safeParse(t).success;var hp=G([dp,pp,Is,Ns]),NP=G([Is,Ns]),$t=ce.strict(),oy=Oe.extend({requestId:jo.optional(),reason:h().optional()}),Zo=Re.extend({method:S("notifications/cancelled"),params:oy}),ny=b({src:h(),mimeType:h().optional(),sizes:C(h()).optional(),theme:ve(["light","dark"]).optional()}),Er=b({icons:C(ny).optional()}),Mt=b({name:h(),title:h().optional()}),gp=Mt.extend({...Mt.shape,...Er.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),sy=Ro(b({applyDefaults:se().optional()}),H(h(),X())),iy=Ps(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ro(b({form:sy.optional(),url:ne.optional()}),H(h(),X()).optional())),ay=ge({list:ne.optional(),cancel:ne.optional(),requests:ge({sampling:ge({createMessage:ne.optional()}).optional(),elicitation:ge({create:ne.optional()}).optional()}).optional()}),cy=ge({list:ne.optional(),cancel:ne.optional(),requests:ge({tools:ge({call:ne.optional()}).optional()}).optional()}),uy=b({experimental:H(h(),ne).optional(),sampling:b({context:ne.optional(),tools:ne.optional()}).optional(),elicitation:iy.optional(),roots:b({listChanged:se().optional()}).optional(),tasks:ay.optional(),extensions:H(h(),ne).optional()}),ly=Pe.extend({protocolVersion:h(),capabilities:uy,clientInfo:gp}),dy=ae.extend({method:S("initialize"),params:ly});var py=b({experimental:H(h(),ne).optional(),logging:ne.optional(),completions:ne.optional(),prompts:b({listChanged:se().optional()}).optional(),resources:b({subscribe:se().optional(),listChanged:se().optional()}).optional(),tools:b({listChanged:se().optional()}).optional(),tasks:cy.optional(),extensions:H(h(),ne).optional()}),js=ce.extend({protocolVersion:h(),capabilities:py,serverInfo:gp,instructions:h().optional()}),fy=Re.extend({method:S("notifications/initialized"),params:Oe.optional()});var Co=ae.extend({method:S("ping"),params:Pe.optional()}),my=b({progress:U(),total:ee(U()),message:ee(h())}),hy=b({...Oe.shape,...my.shape,progressToken:cp}),Ao=Re.extend({method:S("notifications/progress"),params:hy}),gy=Pe.extend({cursor:up.optional()}),Tr=ae.extend({params:gy.optional()}),Or=ce.extend({nextCursor:up.optional()}),_y=ve(["working","input_required","completed","failed","cancelled"]),Rr=b({taskId:h(),status:_y,ttl:G([U(),Qd()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:ee(U()),statusMessage:ee(h())}),bt=ce.extend({task:Rr}),yy=Oe.merge(Rr),Ir=Re.extend({method:S("notifications/tasks/status"),params:yy}),qo=ae.extend({method:S("tasks/get"),params:Pe.extend({taskId:h()})}),Do=ce.merge(Rr),Mo=ae.extend({method:S("tasks/result"),params:Pe.extend({taskId:h()})}),jP=ce.loose(),Lo=Tr.extend({method:S("tasks/list")}),Fo=Or.extend({tasks:C(Rr)}),Uo=ae.extend({method:S("tasks/cancel"),params:Pe.extend({taskId:h()})}),_p=ce.merge(Rr),yp=b({uri:h(),mimeType:ee(h()),_meta:H(h(),X()).optional()}),vp=yp.extend({text:h()}),Zs=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),$p=yp.extend({blob:Zs}),Nr=ve(["user","assistant"]),Lt=b({audience:C(Nr).optional(),priority:U().min(0).max(1).optional(),lastModified:xr.datetime({offset:!0}).optional()}),bp=b({...Mt.shape,...Er.shape,uri:h(),description:ee(h()),mimeType:ee(h()),size:ee(U()),annotations:Lt.optional(),_meta:ee(ge({}))}),vy=b({...Mt.shape,...Er.shape,uriTemplate:h(),description:ee(h()),mimeType:ee(h()),annotations:Lt.optional(),_meta:ee(ge({}))}),$y=Tr.extend({method:S("resources/list")}),Cs=Or.extend({resources:C(bp)}),by=Tr.extend({method:S("resources/templates/list")}),As=Or.extend({resourceTemplates:C(vy)}),qs=Pe.extend({uri:h()}),wy=qs,zy=ae.extend({method:S("resources/read"),params:wy}),Ds=ce.extend({contents:C(G([vp,$p]))}),Ms=Re.extend({method:S("notifications/resources/list_changed"),params:Oe.optional()}),xy=qs,Sy=ae.extend({method:S("resources/subscribe"),params:xy}),ky=qs,Py=ae.extend({method:S("resources/unsubscribe"),params:ky}),Ey=Oe.extend({uri:h()}),Ty=Re.extend({method:S("notifications/resources/updated"),params:Ey}),Oy=b({name:h(),description:ee(h()),required:ee(se())}),Ry=b({...Mt.shape,...Er.shape,description:ee(h()),arguments:ee(C(Oy)),_meta:ee(ge({}))}),Iy=Tr.extend({method:S("prompts/list")}),Ls=Or.extend({prompts:C(Ry)}),Ny=Pe.extend({name:h(),arguments:H(h(),h()).optional()}),jy=ae.extend({method:S("prompts/get"),params:Ny}),Fs=b({type:S("text"),text:h(),annotations:Lt.optional(),_meta:H(h(),X()).optional()}),Us=b({type:S("image"),data:Zs,mimeType:h(),annotations:Lt.optional(),_meta:H(h(),X()).optional()}),Vs=b({type:S("audio"),data:Zs,mimeType:h(),annotations:Lt.optional(),_meta:H(h(),X()).optional()}),Zy=b({type:S("tool_use"),name:h(),id:h(),input:H(h(),X()),_meta:H(h(),X()).optional()}),Cy=b({type:S("resource"),resource:G([vp,$p]),annotations:Lt.optional(),_meta:H(h(),X()).optional()}),Ay=bp.extend({type:S("resource_link")}),Js=G([Fs,Us,Vs,Ay,Cy]),qy=b({role:Nr,content:Js}),Hs=ce.extend({description:h().optional(),messages:C(qy)}),Ks=Re.extend({method:S("notifications/prompts/list_changed"),params:Oe.optional()}),Dy=b({title:h().optional(),readOnlyHint:se().optional(),destructiveHint:se().optional(),idempotentHint:se().optional(),openWorldHint:se().optional()}),My=b({taskSupport:ve(["required","optional","forbidden"]).optional()}),wp=b({...Mt.shape,...Er.shape,description:h().optional(),inputSchema:b({type:S("object"),properties:H(h(),ne).optional(),required:C(h()).optional()}).catchall(X()),outputSchema:b({type:S("object"),properties:H(h(),ne).optional(),required:C(h()).optional()}).catchall(X()).optional(),annotations:Dy.optional(),execution:My.optional(),_meta:H(h(),X()).optional()}),Ly=Tr.extend({method:S("tools/list")}),Bs=Or.extend({tools:C(wp)}),Ft=ce.extend({content:C(Js).default([]),structuredContent:H(h(),X()).optional(),isError:se().optional()}),ZP=Ft.or(ce.extend({toolResult:X()})),Fy=kr.extend({name:h(),arguments:H(h(),X()).optional()}),Uy=ae.extend({method:S("tools/call"),params:Fy}),Gs=Re.extend({method:S("notifications/tools/list_changed"),params:Oe.optional()}),zp=b({autoRefresh:se().default(!0),debounceMs:U().int().nonnegative().default(300)}),xp=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),Vy=Pe.extend({level:xp}),Jy=ae.extend({method:S("logging/setLevel"),params:Vy}),Hy=Oe.extend({level:xp,logger:h().optional(),data:X()}),Ky=Re.extend({method:S("notifications/message"),params:Hy}),By=b({name:h().optional()}),Gy=b({hints:C(By).optional(),costPriority:U().min(0).max(1).optional(),speedPriority:U().min(0).max(1).optional(),intelligencePriority:U().min(0).max(1).optional()}),Wy=b({mode:ve(["auto","required","none"]).optional()}),Yy=b({type:S("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:C(Js).default([]),structuredContent:b({}).loose().optional(),isError:se().optional(),_meta:H(h(),X()).optional()}),Qy=ks("type",[Fs,Us,Vs]),Io=ks("type",[Fs,Us,Vs,Zy,Yy]),Xy=b({role:Nr,content:G([Io,C(Io)]),_meta:H(h(),X()).optional()}),ev=kr.extend({messages:C(Xy),modelPreferences:Gy.optional(),systemPrompt:h().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:U().optional(),maxTokens:U().int(),stopSequences:C(h()).optional(),metadata:ne.optional(),tools:C(wp).optional(),toolChoice:Wy.optional()}),Ws=ae.extend({method:S("sampling/createMessage"),params:ev}),Ys=ce.extend({model:h(),stopReason:ee(ve(["endTurn","stopSequence","maxTokens"]).or(h())),role:Nr,content:Qy}),Qs=ce.extend({model:h(),stopReason:ee(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:Nr,content:G([Io,C(Io)])}),tv=b({type:S("boolean"),title:h().optional(),description:h().optional(),default:se().optional()}),rv=b({type:S("string"),title:h().optional(),description:h().optional(),minLength:U().optional(),maxLength:U().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:h().optional()}),ov=b({type:ve(["number","integer"]),title:h().optional(),description:h().optional(),minimum:U().optional(),maximum:U().optional(),default:U().optional()}),nv=b({type:S("string"),title:h().optional(),description:h().optional(),enum:C(h()),default:h().optional()}),sv=b({type:S("string"),title:h().optional(),description:h().optional(),oneOf:C(b({const:h(),title:h()})),default:h().optional()}),iv=b({type:S("string"),title:h().optional(),description:h().optional(),enum:C(h()),enumNames:C(h()).optional(),default:h().optional()}),av=G([nv,sv]),cv=b({type:S("array"),title:h().optional(),description:h().optional(),minItems:U().optional(),maxItems:U().optional(),items:b({type:S("string"),enum:C(h())}),default:C(h()).optional()}),uv=b({type:S("array"),title:h().optional(),description:h().optional(),minItems:U().optional(),maxItems:U().optional(),items:b({anyOf:C(b({const:h(),title:h()}))}),default:C(h()).optional()}),lv=G([cv,uv]),dv=G([iv,av,lv]),pv=G([dv,tv,rv,ov]),fv=kr.extend({mode:S("form").optional(),message:h(),requestedSchema:b({type:S("object"),properties:H(h(),pv),required:C(h()).optional()})}),mv=kr.extend({mode:S("url"),message:h(),elicitationId:h(),url:h().url()}),hv=G([fv,mv]),Xs=ae.extend({method:S("elicitation/create"),params:hv}),gv=Oe.extend({elicitationId:h()}),_v=Re.extend({method:S("notifications/elicitation/complete"),params:gv}),ei=ce.extend({action:ve(["accept","decline","cancel"]),content:Ps(t=>t===null?void 0:t,H(h(),G([h(),U(),se(),C(h())])).optional())}),yv=b({type:S("ref/resource"),uri:h()});var vv=b({type:S("ref/prompt"),name:h()}),$v=Pe.extend({ref:G([vv,yv]),argument:b({name:h(),value:h()}),context:b({arguments:H(h(),h()).optional()}).optional()}),bv=ae.extend({method:S("completion/complete"),params:$v});var ti=ce.extend({completion:ge({values:C(h()).max(100),total:ee(U().int()),hasMore:ee(se())})}),wv=b({uri:h().startsWith("file://"),name:h().optional(),_meta:H(h(),X()).optional()}),zv=ae.extend({method:S("roots/list"),params:Pe.optional()}),xv=ce.extend({roots:C(wv)}),Sv=Re.extend({method:S("notifications/roots/list_changed"),params:Oe.optional()}),CP=G([Co,dy,bv,Jy,jy,Iy,$y,by,zy,Sy,Py,Uy,Ly,qo,Mo,Lo,Uo]),AP=G([Zo,Ao,fy,Sv,Ir]),qP=G([$t,Ys,Qs,ei,xv,Do,Fo,bt]),DP=G([Co,Ws,Xs,zv,qo,Mo,Lo,Uo]),MP=G([Zo,Ao,Ky,Ty,Ms,Gs,Ks,Ir,_v]),LP=G([$t,js,ti,Hs,Ls,Cs,As,Ds,Ft,Bs,Do,Fo,bt]),E=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===O.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Es(n.elicitations,r)}return new t(e,r,o)}},Es=class extends E{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(O.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ut(t){return t==="completed"||t==="failed"||t==="cancelled"}var $E=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ri(t){let r=To(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Pd(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function oi(t,e){let r=Ae(t,e);if(!r.success)throw r.error;return r.data}var Rv=6e4,Vo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Zo,r=>{this._oncancel(r)}),this.setNotificationHandler(Ao,r=>{this._onprogress(r)}),this.setRequestHandler(Co,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qo,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new E(O.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Mo,async(r,o)=>{let n=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new E(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let i=await this._taskStore.getTask(s,o.sessionId);if(!i)throw new E(O.InvalidParams,`Task not found: ${s}`);if(!ut(i.status))return await this._waitForTaskUpdate(s,o.signal),await n();if(ut(i.status)){let a=await this._taskStore.getTaskResult(s,o.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[ct]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(Lo,async(r,o)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new E(O.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Uo,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new E(O.InvalidParams,`Task not found: ${r.params.taskId}`);if(ut(n.status))throw new E(O.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!s)throw new E(O.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(n){throw n instanceof E?n:new E(O.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,o,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),E.fromError(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=s=>{o?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{n?.(s,i),Pr(s)||mp(s)?this._onresponse(s):Rs(s)?this._onrequest(s,i):fp(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=E.fromError(O.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[ct]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:O.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=lp(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,u={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new E(O.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:O.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(c);return}s(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Pr(e))o(e);else{let i=new E(e.error.code,e.error.message,e.error.data);o(i)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Pr(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Pr(e))n(e);else{let i=E.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(i){yield{type:"error",error:i instanceof E?i:new E(O.InternalError,String(i))}}return}let s;try{let i=await this.request(e,bt,o);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new E(O.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},o);if(yield{type:"taskStatus",task:a},ut(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)}:a.status==="failed"?yield{type:"error",error:new E(O.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new E(O.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof E?i:new E(O.InternalError,String(i))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=w=>{l(w)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){d(w);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[ct]:c}});let m=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let z=w instanceof E?w:new E(O.RequestTimeout,String(w));l(z)};this._responseHandlers.set(p,w=>{if(!o?.signal?.aborted){if(w instanceof Error)return l(w);try{let z=Ae(r,w.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),o?.signal?.addEventListener("abort",()=>{m(o?.signal?.reason)});let _=o?.timeout??Rv,y=()=>m(E.fromError(O.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,o?.maxTotalTimeout,y,o?.resetTimeoutOnProgress??!1);let $=c?.taskId;if($){let w=z=>{let P=this._responseHandlers.get(p);P?P(z):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage($,{type:"request",message:f,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(p),l(z)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),l(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Do,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Fo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},_p,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ct]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[ct]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ct]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let o=ri(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,s)=>{let i=oi(e,n);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let o=ri(e);this._notificationHandlers.set(o,n=>{let s=oi(e,n);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&Rs(n.message)){let s=n.message.id,i=this._requestResolvers.get(s);i?(i(new E(O.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let o=this._options?.defaultTaskPollInterval??1e3;try{let n=await this._taskStore?.getTask(e);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,s)=>{if(r.aborted){s(new E(O.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(i),s(new E(O.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let s=await o.getTask(n,r);if(!s)throw new E(O.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,i)=>{await o.storeTaskResult(n,s,i,r);let a=await o.getTask(n,r);if(a){let c=Ir.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ut(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,s,i)=>{let a=await o.getTask(n,r);if(!a)throw new E(O.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(ut(a.status))throw new E(O.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,s,i,r);let c=await o.getTask(n,r);if(c){let u=Ir.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ut(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function Sp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function kp(t,e){let r={...t};for(let o in e){let n=o,s=e[n];if(s===void 0)continue;let i=r[n];Sp(i)&&Sp(s)?r[n]={...i,...s}:r[n]=s}return r}var yh=Cn(Ua(),1),vh=Cn(_h(),1);function jx(){let t=new yh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,vh.default)(t),t}var kn=class{constructor(e){this._ajv=e??jx()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Pn=class{constructor(e){this._client=e}async*callToolStream(e,r=Ft,o){let n=this._client,s={...o,task:o?.task??(n.isToolTask(e.name)?{}:void 0)},i=n.requestStream({method:"tools/call",params:e},r,s),a=n.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new E(O.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new E(O.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof E){yield{type:"error",error:l};return}yield{type:"error",error:new E(O.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._client.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,o){return this._client.requestStream(e,r,o)}};function $h(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function bh(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function En(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,o=t.properties;for(let n of Object.keys(o)){let s=o[n];r[n]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[n]=s.default),r[n]!==void 0&&En(s,r[n])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&En(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&En(r,e)}}function Zx(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Tn=class extends Vo{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new kn,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Gs,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ks,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ms,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Pn(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=kp(this._capabilities,e)}setRequestHandler(e,r){let n=To(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let s;if(Dt(n)){let a=n;s=a._zod?.def?.value??a.value}else{let a=n;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let l=Ae(Xs,c);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new E(O.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=Zx(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new E(O.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new E(O.InvalidParams,"Client does not support URL-mode elicitation requests");let m=await Promise.resolve(r(c,u));if(d.task){let w=Ae(bt,m);if(!w.success){let z=w.error instanceof Error?w.error.message:String(w.error);throw new E(O.InvalidParams,`Invalid task creation result: ${z}`)}return w.data}let _=Ae(ei,m);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new E(O.InvalidParams,`Invalid elicitation result: ${w}`)}let y=_.data,$=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&$&&this._capabilities.elicitation?.form?.applyDefaults)try{En($,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Ae(Ws,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new E(O.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let y=Ae(bt,p);if(!y.success){let $=y.error instanceof Error?y.error.message:String(y.error);throw new E(O.InvalidParams,`Invalid task creation result: ${$}`)}return y.data}let m=d.tools||d.toolChoice?Qs:Ys,_=Ae(m,p);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new E(O.InvalidParams,`Invalid sampling result: ${y}`)}return _.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:Ts,capabilities:this._capabilities,clientInfo:this._clientInfo}},js,r);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!ap.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){$h(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&bh(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},$t,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},ti,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},$t,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Hs,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Ls,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Cs,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},As,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Ds,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},$t,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},$t,r)}async callTool(e,r=Ft,o){if(this.isToolTaskRequired(e.name))throw new E(O.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this.request({method:"tools/call",params:e},r,o),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new E(O.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let i=s(n.structuredContent);if(!i.valid)throw new E(O.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof E?i:new E(O.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}let o=r.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(r.name),o==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let o=await this.request({method:"tools/list",params:e},Bs,r);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(e,r,o,n){let s=zp.safeParse(o);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=o,u=async()=>{if(!i){c(null,null);return}try{let d=await n();c(null,d)}catch(d){let p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var dg=Cn(ug(),1);import ic from"process";import{PassThrough as uS}from"stream";var Rn=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
73
73
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),cS(r)}clear(){this._buffer=void 0}};function cS(t){return hp.parse(JSON.parse(t))}function lg(t){return JSON.stringify(t)+`
|
|
74
|
-
`}var lS=ic.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function dS(){let t={};for(let e of lS){let r=ic.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var In=class{constructor(e){this._readBuffer=new Rn,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new uS)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,dg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...dS(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:ic.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",o=>{r(o),this.onerror?.(o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",o=>{this.onerror?.(o)}),this._process.stdout?.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),this._process.stdout?.on("error",o=>{this.onerror?.(o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(o=>{e.once("close",()=>{o()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(o=>setTimeout(o,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(o=>setTimeout(o,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let o=lg(e);this._process.stdin.write(o)?r():this._process.stdin.once("drain",r)})}};async function f1(t){let e=new In({command:t.command,args:t.args}),r=new Tn({name:"github-copilot-zam-mcp-app-host",version:"0.
|
|
74
|
+
`}var lS=ic.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function dS(){let t={};for(let e of lS){let r=ic.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var In=class{constructor(e){this._readBuffer=new Rn,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new uS)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,dg.default)(this._serverParams.command,this._serverParams.args??[],{env:{...dS(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:ic.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",o=>{r(o),this.onerror?.(o)}),this._process.on("spawn",()=>{e()}),this._process.on("close",o=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",o=>{this.onerror?.(o)}),this._process.stdout?.on("data",o=>{this._readBuffer.append(o),this.processReadBuffer()}),this._process.stdout?.on("error",o=>{this.onerror?.(o)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(o=>{e.once("close",()=>{o()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(o=>setTimeout(o,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(o=>setTimeout(o,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let o=lg(e);this._process.stdin.write(o)?r():this._process.stdin.once("drain",r)})}};async function f1(t){let e=new In({command:t.command,args:t.args}),r=new Tn({name:"github-copilot-zam-mcp-app-host",version:"0.15.0"});return await r.connect(e),{client:r,transport:e}}export{f1 as connectZam};
|
package/dist/index.d.ts
CHANGED
|
@@ -523,6 +523,16 @@ declare function updateCard(db: Database, cardId: string, updates: UpdateCardInp
|
|
|
523
523
|
/**
|
|
524
524
|
* Preview the review-log rows that will be removed when deleting a user's card.
|
|
525
525
|
*/
|
|
526
|
+
/**
|
|
527
|
+
* Reset the learning state of every user's card for a token back to the
|
|
528
|
+
* beginning (ADR 2026-07-18): when a concept changed on re-import, the old
|
|
529
|
+
* knowledge is irrelevant and must be learned fresh. Values mirror a
|
|
530
|
+
* brand-new card's schema defaults. `blocked` is left untouched — it is
|
|
531
|
+
* derived from prerequisites, not from learning progress.
|
|
532
|
+
*
|
|
533
|
+
* Returns the number of cards reset.
|
|
534
|
+
*/
|
|
535
|
+
declare function resetCardsForToken(db: Database, tokenId: string, now?: string): Promise<number>;
|
|
526
536
|
declare function getCardDeletionImpact(db: Database, tokenId: string, userId: string): Promise<CardDeletionImpact>;
|
|
527
537
|
/**
|
|
528
538
|
* Delete one user's card for a token. Review logs cascade via FK.
|
|
@@ -886,6 +896,12 @@ interface Token {
|
|
|
886
896
|
deprecated_at: string | null;
|
|
887
897
|
provider: string | null;
|
|
888
898
|
topic_id: string | null;
|
|
899
|
+
/** Maintenance state (ADR 2026-07-18): set when the token's source
|
|
900
|
+
* binding is unclear (stale source_link, ambiguous re-import). Cards of
|
|
901
|
+
* a token in maintenance leave the review queue; learning state is
|
|
902
|
+
* preserved. NULL = healthy. */
|
|
903
|
+
maintenance_at: string | null;
|
|
904
|
+
maintenance_reason: string | null;
|
|
889
905
|
}
|
|
890
906
|
interface CreateTokenInput {
|
|
891
907
|
slug: string;
|
|
@@ -925,6 +941,13 @@ interface ListTokensOptions {
|
|
|
925
941
|
* Filter by knowledge context name (e.g. "work-company").
|
|
926
942
|
*/
|
|
927
943
|
knowledgeContext?: string;
|
|
944
|
+
/**
|
|
945
|
+
* Filter by source-link base(s): tokens whose `source_link` is one of the
|
|
946
|
+
* bases exactly or `<base>#<anchor>` (the anchored form OKF imports
|
|
947
|
+
* write). Same matching rule as `getTokensBySourceLinkBase`, OR-ed over
|
|
948
|
+
* all bases. An empty array matches nothing.
|
|
949
|
+
*/
|
|
950
|
+
sourceLinkBases?: string[];
|
|
928
951
|
}
|
|
929
952
|
interface TokenDeleteImpact {
|
|
930
953
|
cards: number;
|
|
@@ -971,6 +994,21 @@ declare function updateToken(db: Database, slug: string, updates: UpdateTokenInp
|
|
|
971
994
|
* Throws if the token does not exist or is already deprecated.
|
|
972
995
|
*/
|
|
973
996
|
declare function deprecateToken(db: Database, slug: string): Promise<Token>;
|
|
997
|
+
/**
|
|
998
|
+
* All non-deprecated tokens whose source_link is `base` or `base#<anchor>`
|
|
999
|
+
* — i.e. the tokens previously imported from one OKF article (ADR
|
|
1000
|
+
* 2026-07-18). `base` is matched literally, not as a pattern.
|
|
1001
|
+
*/
|
|
1002
|
+
declare function getTokensBySourceLinkBase(db: Database, base: string): Promise<Token[]>;
|
|
1003
|
+
/**
|
|
1004
|
+
* Put a token into maintenance (ADR 2026-07-18): its source binding needs
|
|
1005
|
+
* repair — manually or via doctor auto-heal — and its cards leave the
|
|
1006
|
+
* review queue until cleared. Learning state is preserved. Idempotent:
|
|
1007
|
+
* re-entering maintenance refreshes the timestamp and reason.
|
|
1008
|
+
*/
|
|
1009
|
+
declare function setTokenMaintenance(db: Database, slug: string, reason: string): Promise<Token>;
|
|
1010
|
+
/** Clear a token's maintenance state — its cards re-enter scheduling. */
|
|
1011
|
+
declare function clearTokenMaintenance(db: Database, slug: string): Promise<Token>;
|
|
974
1012
|
/**
|
|
975
1013
|
* Preview the rows that will be removed or updated when deleting a token.
|
|
976
1014
|
*/
|
|
@@ -2580,4 +2618,4 @@ declare function resolveAllBeliefPaths(db: Database): Promise<string[]>;
|
|
|
2580
2618
|
*/
|
|
2581
2619
|
declare function resolveAllGoalPaths(db: Database): Promise<string[]>;
|
|
2582
2620
|
|
|
2583
|
-
export { type ADOConfig, type ADOCredentials, ALL_CAPABILITIES, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, BUILT_IN_SENSITIVE_MATCHERS, type BloomLevel$1 as BloomLevel, type CapabilityFlags, type CaptureDecision, type CaptureDenialReason, type CaptureRequest, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConfirmFoundationsResult, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateKnowledgeContextInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, type CurriculumCardInput, type CurriculumTopicCard, DEFAULT_OBSERVER_POLICY, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseTargetInfo, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EmbeddedTokenRow, type EmbeddingCoverage, type EmbeddingStaleness, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type FoundationProposalInput, type FoundationSuggestion, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type HybridScoredToken, type HybridSearchOptions, type ImportCurriculumResult, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type KnowledgeContext, type ListTokensOptions, type LocalLLMRunner, type LogStepInput, type MachineAgentConfig, type MachineAiConfig, type MachineCompanionConfig, type MachineCompanionConfigUpdate, type MachineProviderRecord, type MachineRoleBinding, type ModelCapability, type ModelEntry, type MonitorEvent, type Neighborhood, type NeighborhoodToken, OBSERVER_POLICY_UNSET_HINT, OBSERVER_POLICY_VERSION, type ObservationRating, type ObserverConsent, type ObserverPolicy, type ObserverRetention, type ObserverScope, type ObserverSettingKey, type OllamaDetectionOptions, type PersonalCard, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, type QuestionSource, REVIEW_CONTEXT_CACHE_TTL_MS, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedCaptureTarget, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SIDECAR_POLICY_FILE, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SidecarPrivacyPolicy, type SkillProposal, type SkillSource, type SnapshotManifest, type SourceProposalInput, type SplitProposalInput, type Statement, type SuggestFoundationsOptions, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenEmbedding, type TokenNeedingEmbedding, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateKnowledgeContextInput, type UpdateStep, type UpdateStepKind, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, type WorkspaceConfig, type WorkspaceKind, type WorkspaceSourceControl, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, applySourceProposals, assignTokenToContext, buildAncestorMap, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearProviderApiKey, clearReviewContextCache, clearTursoCredentials, compareVersions, computeContentHash, confirmCardSplit, confirmFoundations, confirmSourceImport, cosineSimilarity, countUserCardsForCurriculumTopic, createAgentSkill, createFSRS, createGoal, createKnowledgeContext, createToken, decidePostCapture, decidePreCapture, decideUpdate, decodeEmbedding, deleteCardForUser, deleteCurriculumCardForUser, deleteKnowledgeContext, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, embeddingContentForToken, emptyCapabilityFlags, encodeEmbedding, endSession, ensureCard, ensureMachineAiModelsMigrated, ensureMachineProviderRolesSanitized, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateTokenSlug, generateZshHooks, generateZshUnhooks, getADOCredentials, getActiveWorkspace, getActiveWorkspaceContext, getActiveWorkspaceId, getAgentConnectAutoDone, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getCompanionCollapsed, getCompanionSelectedAntigravityEvaluatorId, getCompanionSelectedAntigravityModelId, getCompanionSelectedEvaluatorId, getCompanionSelectedUserId, getCompanionSelectedVscodeEvaluatorId, getCompanionSelectedVscodeModelId, getConfiguredWorkspaces, getDatabaseTargetInfo, getDefaultDbPath, getDependents, getDisplayTitle, getDomainCompetence, getDueCards, getEmbeddingCoverage, getGoal, getGoalTree, getInstallChannel, getInstallMode, getKnowledgeContextById, getKnowledgeContextByName, getLastRepairedVersion, getMachineAiConfig, getMachineAiModels, getMachineCompanionConfig, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getProviderApiKey, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getShortSlug, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenEmbedding, getTokenNeighborhood, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importCurriculumCards, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isObserverPolicyConfigured, isOllamaInstalled, isUiObservationReport, listAgentSkills, listContextsForToken, listEmbeddedTokens, listGoals, listKnowledgeContexts, listPersonalCards, listProviderApiKeyRefs, listTokens, listTokensNeedingEmbedding, listUserCardsForCurriculumTopic, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchBuiltInSensitive, matchDenylist, matchesFilePath, migrateMachineRolesToModels, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseObserverList, parseObserverPolicy, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, planUpdate, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, removeConfiguredWorkspace, resolveAllBeliefPaths, resolveAllGoalPaths, resolveObserverPolicy, resolveOllamaCommand, resolveReference, resolveRepoPath, resolveReviewContext, saveConfiguredWorkspaces, saveCredentials, saveInstallConfig, saveMachineAiConfig, saveMachineAiModels, saveMachineCompanionConfig, searchTokensHybrid, serializeGoal, setADOCredentials, setActiveWorkspaceContext, setActiveWorkspaceId, setAgentConnectAutoDone, setCompanionCollapsed, setCompanionSelectedAntigravityEvaluatorId, setCompanionSelectedAntigravityModelId, setCompanionSelectedEvaluatorId, setCompanionSelectedUserId, setCompanionSelectedVscodeEvaluatorId, setCompanionSelectedVscodeModelId, setInstallChannel, setInstallMode, setLastRepairedVersion, setProviderApiKey, setSetting, setTursoCredentials, slugify, startSession, suggestFoundations, syncObserverSidecarPolicy, t, toSidecarPrivacyPolicy, tokenMatchesCurriculumTopicScope, uiObservationLogExists, uiObservationTimeSpan, unassignTokenFromContext, unblockReady, updateCard, updateGoalStatus, updateKnowledgeContext, updateMachineCompanionConfig, updateToken, upsertConfiguredWorkspace, upsertTokenEmbedding, verifySnapshot, wouldCreateCycle, writeMonitorEvent };
|
|
2621
|
+
export { type ADOConfig, type ADOCredentials, ALL_CAPABILITIES, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, BUILT_IN_SENSITIVE_MATCHERS, type BloomLevel$1 as BloomLevel, type CapabilityFlags, type CaptureDecision, type CaptureDenialReason, type CaptureRequest, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConfirmFoundationsResult, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateKnowledgeContextInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, type CurriculumCardInput, type CurriculumTopicCard, DEFAULT_OBSERVER_POLICY, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseTargetInfo, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EmbeddedTokenRow, type EmbeddingCoverage, type EmbeddingStaleness, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type FoundationProposalInput, type FoundationSuggestion, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type HybridScoredToken, type HybridSearchOptions, type ImportCurriculumResult, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type KnowledgeContext, type ListTokensOptions, type LocalLLMRunner, type LogStepInput, type MachineAgentConfig, type MachineAiConfig, type MachineCompanionConfig, type MachineCompanionConfigUpdate, type MachineProviderRecord, type MachineRoleBinding, type ModelCapability, type ModelEntry, type MonitorEvent, type Neighborhood, type NeighborhoodToken, OBSERVER_POLICY_UNSET_HINT, OBSERVER_POLICY_VERSION, type ObservationRating, type ObserverConsent, type ObserverPolicy, type ObserverRetention, type ObserverScope, type ObserverSettingKey, type OllamaDetectionOptions, type PersonalCard, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, type QuestionSource, REVIEW_CONTEXT_CACHE_TTL_MS, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedCaptureTarget, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SIDECAR_POLICY_FILE, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SidecarPrivacyPolicy, type SkillProposal, type SkillSource, type SnapshotManifest, type SourceProposalInput, type SplitProposalInput, type Statement, type SuggestFoundationsOptions, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenEmbedding, type TokenNeedingEmbedding, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateKnowledgeContextInput, type UpdateStep, type UpdateStepKind, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, type WorkspaceConfig, type WorkspaceKind, type WorkspaceSourceControl, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, applySourceProposals, assignTokenToContext, buildAncestorMap, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearProviderApiKey, clearReviewContextCache, clearTokenMaintenance, clearTursoCredentials, compareVersions, computeContentHash, confirmCardSplit, confirmFoundations, confirmSourceImport, cosineSimilarity, countUserCardsForCurriculumTopic, createAgentSkill, createFSRS, createGoal, createKnowledgeContext, createToken, decidePostCapture, decidePreCapture, decideUpdate, decodeEmbedding, deleteCardForUser, deleteCurriculumCardForUser, deleteKnowledgeContext, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, embeddingContentForToken, emptyCapabilityFlags, encodeEmbedding, endSession, ensureCard, ensureMachineAiModelsMigrated, ensureMachineProviderRolesSanitized, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateTokenSlug, generateZshHooks, generateZshUnhooks, getADOCredentials, getActiveWorkspace, getActiveWorkspaceContext, getActiveWorkspaceId, getAgentConnectAutoDone, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getCompanionCollapsed, getCompanionSelectedAntigravityEvaluatorId, getCompanionSelectedAntigravityModelId, getCompanionSelectedEvaluatorId, getCompanionSelectedUserId, getCompanionSelectedVscodeEvaluatorId, getCompanionSelectedVscodeModelId, getConfiguredWorkspaces, getDatabaseTargetInfo, getDefaultDbPath, getDependents, getDisplayTitle, getDomainCompetence, getDueCards, getEmbeddingCoverage, getGoal, getGoalTree, getInstallChannel, getInstallMode, getKnowledgeContextById, getKnowledgeContextByName, getLastRepairedVersion, getMachineAiConfig, getMachineAiModels, getMachineCompanionConfig, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getProviderApiKey, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getShortSlug, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenEmbedding, getTokenNeighborhood, getTokensBySourceLinkBase, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importCurriculumCards, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isObserverPolicyConfigured, isOllamaInstalled, isUiObservationReport, listAgentSkills, listContextsForToken, listEmbeddedTokens, listGoals, listKnowledgeContexts, listPersonalCards, listProviderApiKeyRefs, listTokens, listTokensNeedingEmbedding, listUserCardsForCurriculumTopic, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchBuiltInSensitive, matchDenylist, matchesFilePath, migrateMachineRolesToModels, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseObserverList, parseObserverPolicy, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, planUpdate, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, removeConfiguredWorkspace, resetCardsForToken, resolveAllBeliefPaths, resolveAllGoalPaths, resolveObserverPolicy, resolveOllamaCommand, resolveReference, resolveRepoPath, resolveReviewContext, saveConfiguredWorkspaces, saveCredentials, saveInstallConfig, saveMachineAiConfig, saveMachineAiModels, saveMachineCompanionConfig, searchTokensHybrid, serializeGoal, setADOCredentials, setActiveWorkspaceContext, setActiveWorkspaceId, setAgentConnectAutoDone, setCompanionCollapsed, setCompanionSelectedAntigravityEvaluatorId, setCompanionSelectedAntigravityModelId, setCompanionSelectedEvaluatorId, setCompanionSelectedUserId, setCompanionSelectedVscodeEvaluatorId, setCompanionSelectedVscodeModelId, setInstallChannel, setInstallMode, setLastRepairedVersion, setProviderApiKey, setSetting, setTokenMaintenance, setTursoCredentials, slugify, startSession, suggestFoundations, syncObserverSidecarPolicy, t, toSidecarPrivacyPolicy, tokenMatchesCurriculumTopicScope, uiObservationLogExists, uiObservationTimeSpan, unassignTokenFromContext, unblockReady, updateCard, updateGoalStatus, updateKnowledgeContext, updateMachineCompanionConfig, updateToken, upsertConfiguredWorkspace, upsertTokenEmbedding, verifySnapshot, wouldCreateCycle, writeMonitorEvent };
|
package/dist/index.js
CHANGED
|
@@ -547,7 +547,13 @@ CREATE TABLE IF NOT EXISTS tokens (
|
|
|
547
547
|
-- validated in code, not via CHECK. Column default is 'llm' so unlabeled
|
|
548
548
|
-- writes (pre-M013 rows, old snapshot restores) count as LLM-era content;
|
|
549
549
|
-- createToken() defaults to 'manual' for API callers instead.
|
|
550
|
-
question_source TEXT NOT NULL DEFAULT 'llm'
|
|
550
|
+
question_source TEXT NOT NULL DEFAULT 'llm',
|
|
551
|
+
-- Maintenance state (ADR 2026-07-18): when set, the token's binding to
|
|
552
|
+
-- its source is unclear (e.g. stale source_link after an article split,
|
|
553
|
+
-- or an ambiguous re-import). Cards of a token in maintenance are
|
|
554
|
+
-- excluded from scheduling until repaired; learning state is preserved.
|
|
555
|
+
maintenance_at TEXT,
|
|
556
|
+
maintenance_reason TEXT
|
|
551
557
|
);
|
|
552
558
|
|
|
553
559
|
-- Prerequisite dependency graph: "to learn A, first know B"
|
|
@@ -1097,6 +1103,10 @@ async function runMigrations(db) {
|
|
|
1097
1103
|
`ALTER TABLE tokens ADD COLUMN question_source TEXT NOT NULL DEFAULT 'llm'`
|
|
1098
1104
|
);
|
|
1099
1105
|
}
|
|
1106
|
+
if (tokenCols.length > 0 && !tokenCols.some((c) => c.name === "maintenance_at")) {
|
|
1107
|
+
await db.exec(`ALTER TABLE tokens ADD COLUMN maintenance_at TEXT`);
|
|
1108
|
+
await db.exec(`ALTER TABLE tokens ADD COLUMN maintenance_reason TEXT`);
|
|
1109
|
+
}
|
|
1100
1110
|
}
|
|
1101
1111
|
|
|
1102
1112
|
// src/kernel/db/snapshot.ts
|
|
@@ -1547,6 +1557,23 @@ async function updateCard(db, cardId, updates) {
|
|
|
1547
1557
|
}
|
|
1548
1558
|
return await db.prepare("SELECT * FROM cards WHERE id = ?").get(cardId);
|
|
1549
1559
|
}
|
|
1560
|
+
async function resetCardsForToken(db, tokenId, now) {
|
|
1561
|
+
const ts = now ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1562
|
+
const result = await db.prepare(
|
|
1563
|
+
`UPDATE cards SET
|
|
1564
|
+
stability = 0.0,
|
|
1565
|
+
difficulty = 0.5,
|
|
1566
|
+
elapsed_days = 0.0,
|
|
1567
|
+
scheduled_days = 0.0,
|
|
1568
|
+
reps = 0,
|
|
1569
|
+
lapses = 0,
|
|
1570
|
+
state = 'new',
|
|
1571
|
+
due_at = ?,
|
|
1572
|
+
last_review_at = NULL
|
|
1573
|
+
WHERE token_id = ?`
|
|
1574
|
+
).run(ts, tokenId);
|
|
1575
|
+
return result.changes;
|
|
1576
|
+
}
|
|
1550
1577
|
async function getCardDeletionImpact(db, tokenId, userId) {
|
|
1551
1578
|
const card = await getCard(db, tokenId, userId);
|
|
1552
1579
|
if (!card) {
|
|
@@ -1569,7 +1596,8 @@ async function getDueCards(db, userId, now, domain, knowledgeContext) {
|
|
|
1569
1596
|
let sql = `SELECT c.*, t.slug, t.concept, t.domain, t.bloom_level
|
|
1570
1597
|
FROM cards c
|
|
1571
1598
|
JOIN tokens t ON t.id = c.token_id
|
|
1572
|
-
WHERE c.user_id = ? AND c.blocked = 0 AND c.due_at <=
|
|
1599
|
+
WHERE c.user_id = ? AND c.blocked = 0 AND c.due_at <= ?
|
|
1600
|
+
AND t.maintenance_at IS NULL`;
|
|
1573
1601
|
const params = [userId, cutoff];
|
|
1574
1602
|
if (domain) {
|
|
1575
1603
|
sql += " AND t.domain = ?";
|
|
@@ -1861,6 +1889,38 @@ async function deprecateToken(db, slug) {
|
|
|
1861
1889
|
).run(now, now, slug);
|
|
1862
1890
|
return await getTokenBySlug(db, slug);
|
|
1863
1891
|
}
|
|
1892
|
+
async function getTokensBySourceLinkBase(db, base) {
|
|
1893
|
+
return await db.prepare(
|
|
1894
|
+
`SELECT * FROM tokens
|
|
1895
|
+
WHERE (source_link = ? OR source_link LIKE ? || '#%' ESCAPE '\\')
|
|
1896
|
+
AND deprecated_at IS NULL`
|
|
1897
|
+
).all(base, escapeLike(base));
|
|
1898
|
+
}
|
|
1899
|
+
function escapeLike(value) {
|
|
1900
|
+
return value.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
|
1901
|
+
}
|
|
1902
|
+
async function setTokenMaintenance(db, slug, reason) {
|
|
1903
|
+
const token = await getTokenBySlug(db, slug);
|
|
1904
|
+
if (!token) {
|
|
1905
|
+
throw new Error(`Token not found: ${slug}`);
|
|
1906
|
+
}
|
|
1907
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1908
|
+
await db.prepare(
|
|
1909
|
+
"UPDATE tokens SET maintenance_at = ?, maintenance_reason = ?, updated_at = ? WHERE slug = ?"
|
|
1910
|
+
).run(now, reason, now, slug);
|
|
1911
|
+
return await getTokenBySlug(db, slug);
|
|
1912
|
+
}
|
|
1913
|
+
async function clearTokenMaintenance(db, slug) {
|
|
1914
|
+
const token = await getTokenBySlug(db, slug);
|
|
1915
|
+
if (!token) {
|
|
1916
|
+
throw new Error(`Token not found: ${slug}`);
|
|
1917
|
+
}
|
|
1918
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1919
|
+
await db.prepare(
|
|
1920
|
+
"UPDATE tokens SET maintenance_at = NULL, maintenance_reason = NULL, updated_at = ? WHERE slug = ?"
|
|
1921
|
+
).run(now, slug);
|
|
1922
|
+
return await getTokenBySlug(db, slug);
|
|
1923
|
+
}
|
|
1864
1924
|
async function getTokenDeleteImpact(db, slug) {
|
|
1865
1925
|
const token = await getTokenBySlug(db, slug);
|
|
1866
1926
|
if (!token) {
|
|
@@ -1988,6 +2048,15 @@ async function listTokens(db, options) {
|
|
|
1988
2048
|
)`);
|
|
1989
2049
|
params.push(options.knowledgeContext);
|
|
1990
2050
|
}
|
|
2051
|
+
if (options?.sourceLinkBases) {
|
|
2052
|
+
const clauses = options.sourceLinkBases.map(
|
|
2053
|
+
() => `(source_link = ? OR source_link LIKE ? || '#%' ESCAPE '\\')`
|
|
2054
|
+
);
|
|
2055
|
+
whereClauses.push(clauses.length ? `(${clauses.join(" OR ")})` : "0 = 1");
|
|
2056
|
+
for (const base of options.sourceLinkBases) {
|
|
2057
|
+
params.push(base, escapeLike(base));
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
1991
2060
|
const orderBy = options?.domain || options?.domainPrefix ? "ORDER BY bloom_level, slug" : "ORDER BY bloom_level, domain, slug";
|
|
1992
2061
|
const sql = `SELECT * FROM tokens WHERE ${whereClauses.join(" AND ")} ${orderBy}`;
|
|
1993
2062
|
const tokens = await db.prepare(sql).all(...params);
|
|
@@ -5027,7 +5096,8 @@ async function buildReviewQueue(db, options) {
|
|
|
5027
5096
|
AND c.blocked = 0
|
|
5028
5097
|
AND c.due_at <= ?
|
|
5029
5098
|
AND c.state IN ('review', 'relearning', 'learning')
|
|
5030
|
-
AND t.deprecated_at IS NULL
|
|
5099
|
+
AND t.deprecated_at IS NULL
|
|
5100
|
+
AND t.maintenance_at IS NULL`;
|
|
5031
5101
|
const dueParams = [options.userId, nowISO];
|
|
5032
5102
|
if (options.knowledgeContext) {
|
|
5033
5103
|
dueSql += ` AND EXISTS (
|
|
@@ -5057,7 +5127,8 @@ async function buildReviewQueue(db, options) {
|
|
|
5057
5127
|
WHERE c.user_id = ?
|
|
5058
5128
|
AND c.blocked = 0
|
|
5059
5129
|
AND c.state = 'new'
|
|
5060
|
-
AND t.deprecated_at IS NULL
|
|
5130
|
+
AND t.deprecated_at IS NULL
|
|
5131
|
+
AND t.maintenance_at IS NULL`;
|
|
5061
5132
|
const newParams = [options.userId];
|
|
5062
5133
|
if (options.knowledgeContext) {
|
|
5063
5134
|
newSql += ` AND EXISTS (
|
|
@@ -6679,6 +6750,7 @@ export {
|
|
|
6679
6750
|
clearADOCredentials,
|
|
6680
6751
|
clearProviderApiKey,
|
|
6681
6752
|
clearReviewContextCache,
|
|
6753
|
+
clearTokenMaintenance,
|
|
6682
6754
|
clearTursoCredentials,
|
|
6683
6755
|
compareVersions,
|
|
6684
6756
|
computeContentHash,
|
|
@@ -6787,6 +6859,7 @@ export {
|
|
|
6787
6859
|
getTokenDeleteImpact,
|
|
6788
6860
|
getTokenEmbedding,
|
|
6789
6861
|
getTokenNeighborhood,
|
|
6862
|
+
getTokensBySourceLinkBase,
|
|
6790
6863
|
getTursoCredentials,
|
|
6791
6864
|
getUiObservationPath,
|
|
6792
6865
|
getUiObserverDir,
|
|
@@ -6841,6 +6914,7 @@ export {
|
|
|
6841
6914
|
readMonitorLog,
|
|
6842
6915
|
readUiObservationLog,
|
|
6843
6916
|
removeConfiguredWorkspace,
|
|
6917
|
+
resetCardsForToken,
|
|
6844
6918
|
resolveAllBeliefPaths,
|
|
6845
6919
|
resolveAllGoalPaths,
|
|
6846
6920
|
resolveObserverPolicy,
|
|
@@ -6872,6 +6946,7 @@ export {
|
|
|
6872
6946
|
setLastRepairedVersion,
|
|
6873
6947
|
setProviderApiKey,
|
|
6874
6948
|
setSetting,
|
|
6949
|
+
setTokenMaintenance,
|
|
6875
6950
|
setTursoCredentials,
|
|
6876
6951
|
slugify,
|
|
6877
6952
|
startSession,
|