adam-agent-server 1.17.0 → 1.18.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/approval-handler-BWA7UIKN.js +1 -0
- package/dist/{artifacts-DMY2MI2F.js → artifacts-MAYKOTA2.js} +1 -1
- package/dist/audit-diagnostics-K3LUWXTI.js +1 -0
- package/dist/audit-manager-6WL2V6JG.js +1 -0
- package/dist/bree-engine-KYD4GKQK.js +1 -0
- package/dist/{channels-VYNJFXDD.js → channels-2TWTBE6Y.js} +1 -1
- package/dist/channels-PWDSTYNR.js +1 -0
- package/dist/{chat-tool-calls-WQGFYTUV.js → chat-tool-calls-WJDFQ54U.js} +1 -1
- package/dist/{chunk-P76VP2UH.js → chunk-2A2TXYT3.js} +5 -5
- package/dist/chunk-2CE2WUUZ.js +1 -0
- package/dist/{chunk-YEBC67DJ.js → chunk-2JIQT2CI.js} +1 -1
- package/dist/chunk-3MROEPGR.js +1 -0
- package/dist/{chunk-725BGAO2.js → chunk-3UFEOB6P.js} +1 -1
- package/dist/{chunk-VVBN35YG.js → chunk-47HJPIUA.js} +1 -1
- package/dist/{chunk-PBKZDNNV.js → chunk-4JHACUZY.js} +1 -1
- package/dist/{chunk-D5PAJ3CB.js → chunk-6WQFYV3N.js} +1 -1
- package/dist/{chunk-BRUHXRKK.js → chunk-AUSR5JYV.js} +1 -1
- package/dist/{chunk-ED2JAMEN.js → chunk-BE653A45.js} +1 -1
- package/dist/{chunk-3RITIMKB.js → chunk-BMCNQGUH.js} +1 -1
- package/dist/{chunk-32D5GWJD.js → chunk-HRPMRWHD.js} +1 -1
- package/dist/{chunk-QWIBCFPC.js → chunk-IEBAOZED.js} +2 -2
- package/dist/{chunk-OII5SDMS.js → chunk-JROGEBP5.js} +1 -1
- package/dist/{chunk-DCTNMUQ5.js → chunk-JYZTIE2J.js} +1 -1
- package/dist/{chunk-5WBFQMJL.js → chunk-JZBXLN7M.js} +1 -1
- package/dist/{chunk-A2S67EQG.js → chunk-KS24764D.js} +2 -2
- package/dist/{chunk-WDSCTXT7.js → chunk-LCD5DVS6.js} +1 -1
- package/dist/{chunk-3GK65T2V.js → chunk-LKGYQJMS.js} +1 -1
- package/dist/{chunk-FMJVKJJE.js → chunk-MTRLUW7Z.js} +1 -1
- package/dist/{chunk-3VUEB67V.js → chunk-NSUXJ2VA.js} +1 -1
- package/dist/{chunk-73GP6K5S.js → chunk-NUOTFUNF.js} +1 -1
- package/dist/chunk-NXGR3PRY.js +1 -0
- package/dist/{chunk-4WJ2VSEJ.js → chunk-O6L4UVLV.js} +1 -1
- package/dist/{chunk-UUJ24BNJ.js → chunk-OBD4245G.js} +1 -1
- package/dist/{chunk-TNBQFCXR.js → chunk-QTGAK62Z.js} +2 -2
- package/dist/{chunk-K3HWZBE5.js → chunk-QYI44EP6.js} +1 -1
- package/dist/{chunk-MQTK4Q6M.js → chunk-SGLZAIVL.js} +1 -1
- package/dist/chunk-SKHMWKJT.js +80 -0
- package/dist/{chunk-TO27F23C.js → chunk-T2Z2JDPY.js} +1 -1
- package/dist/chunk-TA5PFK5C.js +5 -0
- package/dist/{chunk-UAF4KNXE.js → chunk-TWOJVEO7.js} +2 -2
- package/dist/{chunk-NV5ZXKKF.js → chunk-UCUELFCS.js} +1 -1
- package/dist/{chunk-2WPUKCDA.js → chunk-V2MMQ3SH.js} +1 -1
- package/dist/{chunk-7IXYCDUF.js → chunk-VPMHZJS2.js} +1 -1
- package/dist/{chunk-3R7VGMAK.js → chunk-VWX2B6OM.js} +1 -1
- package/dist/{chunk-VARIYH6K.js → chunk-WY5BOCQP.js} +98 -37
- package/dist/{chunk-2RBYM3X7.js → chunk-XAPJJAJQ.js} +1 -1
- package/dist/{chunk-A57SY3E4.js → chunk-Z2APBKIT.js} +1 -1
- package/dist/chunk-ZJ3TS4FL.js +182 -0
- package/dist/{chunk-VSSKQAG5.js → chunk-ZQN6JZIJ.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{config-ZDKMTZJC.js → config-U624HJKI.js} +1 -1
- package/dist/config-X7A6NA73.js +1 -0
- package/dist/{db-LIKGSZCL.js → db-XODNIJSJ.js} +1 -1
- package/dist/{delivery-log-2ILFP673.js → delivery-log-QMQQHES4.js} +1 -1
- package/dist/engine-OQXDHA2R.js +1 -0
- package/dist/{evolution-audit-BDQM6NAX.js → evolution-audit-XF4KZZMP.js} +1 -1
- package/dist/execution-tools-BR4T4MMW.js +1 -0
- package/dist/{external-api-7GB3U775.js → external-api-435WH6V3.js} +1 -1
- package/dist/index.js +65 -45
- package/dist/{learner-V2HBTRAE.js → learner-4CJ7BSCN.js} +1 -1
- package/dist/{memories-B3QGTYLX.js → memories-NJFKSOL5.js} +1 -1
- package/dist/{memory-extractor-RYZ3VU7A.js → memory-extractor-UQI75BBK.js} +1 -1
- package/dist/{memory-gc-5AYND3RL.js → memory-gc-NTZVUGJX.js} +1 -1
- package/dist/memory-service-3RLVOF2C.js +1 -0
- package/dist/outbound-gateway-NJNSN2ZX.js +1 -0
- package/dist/presets-SUJRFRJC.js +1 -0
- package/dist/{reflection-job-P6GIQVQN.js → reflection-job-F4BZA2E3.js} +1 -1
- package/dist/role-presets-VEYTGYA4.js +1 -0
- package/dist/role-workspace-AIVHPX5P.js +1 -0
- package/dist/{roles-B6YC4GDC.js → roles-WDMUBWQP.js} +1 -1
- package/dist/runtime-OMLPOMCA.js +1 -0
- package/dist/session-manager-XFUKWEC7.js +1 -0
- package/dist/skill-registry-LARMNUT5.js +1 -0
- package/dist/{task-templates-MNCF7JON.js → task-templates-BIVCRNXA.js} +1 -1
- package/dist/template-dispatch-6FPJQN6A.js +1 -0
- package/package.json +1 -1
- package/web/dist/assets/{ArtifactDetail-Dt_xkaYJ.js → ArtifactDetail-DDTEAl2E.js} +1 -1
- package/web/dist/assets/{Artifacts-DlPMk9VQ.js → Artifacts-BrhnC1Ef.js} +1 -1
- package/web/dist/assets/{ChannelDetail-kYtMmy6P.js → ChannelDetail-D0FBZoAX.js} +1 -1
- package/web/dist/assets/{Channels-BppR0Qc_.js → Channels-Cztxvsa2.js} +1 -1
- package/web/dist/assets/{Chat-BLVREMCu.js → Chat-Ce72TtUi.js} +2 -2
- package/web/dist/assets/Cost-K8-4xqBe.js +4 -0
- package/web/dist/assets/{Dashboard-XURc0f15.js → Dashboard-BXqFb_Vr.js} +1 -1
- package/web/dist/assets/{EnvVarEditor-DR-bSU0w.js → EnvVarEditor-FiiJazzp.js} +1 -1
- package/web/dist/assets/{EventDefDetail-DtkbGbQ0.js → EventDefDetail-C3S1G0K8.js} +1 -1
- package/web/dist/assets/{Events-C_J4jvDh.js → Events-BKxqZ9j6.js} +1 -1
- package/web/dist/assets/{Evolution-CEaSpRAm.js → Evolution-DFcSm6Rw.js} +1 -1
- package/web/dist/assets/{ExtensionDetail-D5Qfq-W4.js → ExtensionDetail-C8aPpyLv.js} +1 -1
- package/web/dist/assets/Extensions-MLZk05j0.js +1 -0
- package/web/dist/assets/{FeatureRequests-D8WEYtoU.js → FeatureRequests-D_4XaQ7F.js} +1 -1
- package/web/dist/assets/{GoalDetail-DnMS_WWw.js → GoalDetail-DVU7c0aR.js} +1 -1
- package/web/dist/assets/{Goals-BeKwpAss.js → Goals-D3h4WMjU.js} +1 -1
- package/web/dist/assets/LineChart-Ck1vfYHs.js +33 -0
- package/web/dist/assets/{Logs-BfXBv-dV.js → Logs-D5MQv6Yw.js} +1 -1
- package/web/dist/assets/{Memories-QRH7O8qP.js → Memories-Dls71I2i.js} +1 -1
- package/web/dist/assets/{Mistakes-mXU9PXft.js → Mistakes-BZcTg0vP.js} +1 -1
- package/web/dist/assets/{Plugins-C8v4AsvM.js → Plugins-CwCHGzI6.js} +1 -1
- package/web/dist/assets/RoleDetail-B2M6ALSl.js +3 -0
- package/web/dist/assets/{Roles-B8dQCKuS.js → Roles-FEHqm_Jf.js} +1 -1
- package/web/dist/assets/Settings-rdVQMfqX.js +1 -0
- package/web/dist/assets/{Strategies-DFUWEKfU.js → Strategies-CwJ9JQ-X.js} +1 -1
- package/web/dist/assets/{Switch-BcS5rOWb.js → Switch-1JjR4Imr.js} +1 -1
- package/web/dist/assets/{TaskDetail-BdhBhvKg.js → TaskDetail-h12WxjfG.js} +1 -1
- package/web/dist/assets/{Work-D-t80Ekv.js → Work-CfzFRSZX.js} +1 -1
- package/web/dist/assets/api-BP4ZP9kk.js +1 -0
- package/web/dist/assets/index-CXEJd-0s.js +12 -0
- package/web/dist/assets/index-CarTGiGO.css +2 -0
- package/web/dist/assets/{usePluginsWithUsage-DE13JW16.js → usePluginsWithUsage-4iLJAPjH.js} +1 -1
- package/web/dist/index.html +3 -3
- package/dist/approval-handler-FONN2EGB.js +0 -1
- package/dist/audit-diagnostics-D4M4SA5O.js +0 -1
- package/dist/audit-manager-YEOJRE6K.js +0 -1
- package/dist/bree-engine-RGTBKKFE.js +0 -1
- package/dist/channels-WFU4CVGW.js +0 -1
- package/dist/chunk-2V2H5PG5.js +0 -182
- package/dist/chunk-4G2OZPP5.js +0 -1
- package/dist/chunk-CFPXWGFD.js +0 -1
- package/dist/chunk-FJ3DUJXO.js +0 -1
- package/dist/chunk-OH6VBBDV.js +0 -1
- package/dist/chunk-SJTIMT5U.js +0 -5
- package/dist/config-GRL6O2ZY.js +0 -1
- package/dist/engine-JVPM3XE5.js +0 -1
- package/dist/execution-tools-7MK257DY.js +0 -1
- package/dist/memory-service-XI3JZQ4E.js +0 -1
- package/dist/outbound-gateway-O27KKVOI.js +0 -1
- package/dist/presets-UAH3OG3C.js +0 -1
- package/dist/role-presets-RVYTO5FS.js +0 -1
- package/dist/role-workspace-KOTVFJD3.js +0 -1
- package/dist/runtime-C3XN33A3.js +0 -1
- package/dist/session-manager-HO2ZCB47.js +0 -1
- package/dist/skill-registry-X2GY7SMI.js +0 -1
- package/dist/template-dispatch-BAMKX3QH.js +0 -1
- package/web/dist/assets/Extensions-B_egkUP1.js +0 -1
- package/web/dist/assets/RoleDetail-Ct-k3uoK.js +0 -35
- package/web/dist/assets/Settings-CqtCBP6I.js +0 -1
- package/web/dist/assets/api-BRfbZQSW.js +0 -1
- package/web/dist/assets/index-DWU9AURw.css +0 -2
- package/web/dist/assets/index-PIFMZAPo.js +0 -12
- /package/web/dist/assets/{NotFound-DuH6sFz7.js → NotFound-t66RIvqO.js} +0 -0
- /package/web/dist/assets/{Table-D2K039zr.js → Table-CvSmzzkm.js} +0 -0
- /package/web/dist/assets/{Tabs-BwyLSH2c.js → Tabs-DWk9HyNd.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as r,p as n}from"./chunk-
|
|
1
|
+
import{n as r,p as n}from"./chunk-WY5BOCQP.js";import{c,e as u}from"./chunk-5M6IGE5G.js";import{b as d,c as o}from"./chunk-5PELJRUQ.js";var D={};o(D,{listAuditDiagnostics:()=>A,recordAuditDiagnostic:()=>g});import{v4 as a}from"uuid";function g(e){let t={id:a(),source:e.source,severity:e.severity,traceId:e.traceId??c()??void 0,sourceId:e.sourceId,message:e.message,createdAt:e.createdAt??Date.now()};return r().prepare(`
|
|
2
2
|
INSERT INTO audit_diagnostics (id, source, severity, trace_id, source_id, message, created_at)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
4
4
|
`).run(t.id,t.source,t.severity,t.traceId??null,t.sourceId??null,t.message,t.createdAt),t}function A(e={}){let t=[],i=[];e.source&&(t.push("source = ?"),i.push(e.source)),e.traceId&&(t.push("trace_id = ?"),i.push(e.traceId));let s="SELECT * FROM audit_diagnostics";return t.length>0&&(s+=` WHERE ${t.join(" AND ")}`),s+=" ORDER BY created_at DESC",e.limit!==void 0&&(s+=" LIMIT ?",i.push(e.limit)),r().prepare(s).all(...i).map(m)}function m(e){return{id:e.id,source:e.source,severity:e.severity,traceId:e.trace_id??void 0,sourceId:e.source_id??void 0,message:e.message,createdAt:e.created_at}}var I=d(()=>{n();u()});export{g as a,A as b,D as c,I as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as D,g as Be}from"./chunk-
|
|
1
|
+
import{a as D,g as Be}from"./chunk-MTRLUW7Z.js";import{a as Te}from"./chunk-Z2APBKIT.js";import{b as ie}from"./chunk-4JHACUZY.js";import{e as Re,i as nt}from"./chunk-NSUXJ2VA.js";import{b as pe,k as me,m as re,s as oe}from"./chunk-VWX2B6OM.js";import{a as Oe}from"./chunk-L7JP7DUO.js";import{c as $e}from"./chunk-LKGYQJMS.js";import{b as Me}from"./chunk-T2Z2JDPY.js";import{a as Ne,b as fe,c as De,k as Pe}from"./chunk-V2MMQ3SH.js";import{D as ue,L as it,b as j,c as Ce,p as ot}from"./chunk-2A2TXYT3.js";import{a as J,b as ee,d as _e,j as ae,l as be,n as ge,o as ke,r as tt}from"./chunk-BE653A45.js";import{a as xe,b as te,c as we,d as ce,e as ve,f as de,j as Ee,l as Ae,n as K,p as le}from"./chunk-WY5BOCQP.js";import{c as Z,h as Ie}from"./chunk-EZLBMUQD.js";import{c as Se,e as rt}from"./chunk-5M6IGE5G.js";it();nt();ot();import{createSdkMcpServer as Ft,tool as M}from"@anthropic-ai/claude-agent-sdk";import{z as d}from"zod";import{v4 as he}from"uuid";tt();Ie();le();var st=Z("audit");function I(t){try{K().prepare(`
|
|
2
2
|
INSERT INTO artifact_access_log (
|
|
3
3
|
timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
|
|
4
4
|
size_bytes, outcome, error_reason
|
|
@@ -11,4 +11,4 @@ import{a as D,g as Be}from"./chunk-FMJVKJJE.js";import{a as Te}from"./chunk-A57S
|
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
12
12
|
`).run(e.id,e.traceId,e.sessionId??null,e.taskId??null,e.sourceMessageId??null,JSON.stringify(e.claims),e.declaredAt),e}function dr(t){return K().prepare(`
|
|
13
13
|
SELECT * FROM assistant_claims WHERE trace_id = ? ORDER BY declared_at ASC
|
|
14
|
-
`).all(t).map(mt)}function mt(t){return{id:t.id,traceId:t.trace_id,sessionId:t.session_id??void 0,taskId:t.task_id??void 0,sourceMessageId:t.source_message_id??void 0,claims:JSON.parse(t.claims_json),declaredAt:t.declared_at}}rt();import{execFile as Ot}from"child_process";import{promisify as Nt}from"util";import{isAbsolute as Dt,basename as Pt}from"path";import Ye from"vm";import{isAbsolute as ft}from"path";var P=class extends Error{constructor(e,r){super(`DSL parse error in "${e}": ${r}`),this.name="DslParseError"}},ht=/^[a-z][a-z0-9_.]*$/i,yt=/\.\./;function V(t){if(!ht.test(t))throw new P(t,`invalid handler key format "${t}" \u2014 must match [a-z][a-z0-9_.]*`);if(yt.test(t))throw new P(t,'handler key must not contain ".."')}function Ue(t){let e=t.trim();try{let n=JSON.parse(e);if(typeof n=="number"||typeof n=="string"||typeof n=="boolean")return n}catch{}let r=parseFloat(e);return Number.isNaN(r)?e:r}var It=/^([a-z][a-z0-9_.]*)\s+matches\s+\/(.+)\/([gimsuy]*)$/i,_t=/^([a-z][a-z0-9_.]*)\s*(<=|>=|==|!=)\s*(.+)$/i,bt=/^([a-z][a-z0-9_.]*)\s*(<|>)\s*(.+)$/i,gt=/^([a-z][a-z0-9_.]*)\s+between\s+(-?\d+(?:\.\d+)?)\s+and\s+(-?\d+(?:\.\d+)?)$/i,kt=/^([a-z][a-z0-9_.]*)\s+in\s+\[([^\]]+)\]$/i;function We(t){if(typeof t=="object"&&t!==null&&"script"in t){let r=String(t.script);if(!ft(r))throw new P(`{script: "${r}"}`,"script path must be absolute");return{kind:"script",scriptPath:r}}if(typeof t!="string")throw new P(String(t),"assertion must be a string or {script: string} object");let e=t.trim();if(!e)throw new P(e,"empty assertion string");{let r=It.exec(e);if(r){let n=r[1];return V(n),{kind:"matches",key:n,regexSource:r[2],regexFlags:r[3]??""}}}{let r=gt.exec(e);if(r){let n=r[1];return V(n),{kind:"between",key:n,min:parseFloat(r[2]),max:parseFloat(r[3])}}}{let r=kt.exec(e);if(r){let n=r[1];V(n);let a=r[2],c=[];for(let m of a.split(",")){let y=m.trim();if(y)try{let A=JSON.parse(y);typeof A=="number"||typeof A=="string"||typeof A=="boolean"?c.push(A):c.push(y)}catch{c.push(y)}}return{kind:"in",key:n,values:c}}}{let r=_t.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}{let r=bt.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}throw new P(e,"unrecognized assertion syntax \u2014 expected key <op> value, between, in [...], matches /.../, or {script: ...}")}import{execFile as wt,spawn as vt}from"child_process";import{promisify as Et}from"util";import{readFile as X}from"fs/promises";import{existsSync as At}from"fs";import{createHash as St}from"crypto";function xt(t){return typeof t=="number"?Number.isInteger(t)?t.toString():t.toFixed(4):JSON.stringify(t)}var L=class extends Error{constructor(r){super(`NO_HANDLER: ${r}, install relevant capability or remove assertion`);this.handlerKey=r;this.name="NoHandlerError"}handlerKey},C=class extends Error{constructor(r,n,a){super(`ASSERTION_FAILED: ${r}=${xt(n)}, expected ${a}`);this.handlerKey=r;this.measured=n;this.expected=a;this.name="AssertionFailedError"}handlerKey;measured;expected},g=class extends Error{constructor(r,n){super(`HANDLER_RUNTIME_ERROR: ${r}: ${n}`);this.handlerKey=r;this.detail=n;this.name="HandlerRuntimeError"}handlerKey;detail};var Ct=Et(wt);function z(t,e){if(!At(e))throw new g(t,`file not found: ${e}`)}async function Tt(t){try{return await Ct("ffprobe",t,{maxBuffer:10*1024*1024})}catch(e){throw e.code==="ENOENT"?new g("audio.*","ffprobe not found on PATH \u2014 install ffmpeg/ffprobe"):new g("audio.*",`ffprobe failed: ${e.message}`)}}async function Je(t,e){return new Promise((r,n)=>{let a=[],c=vt("ffmpeg",["-v","error","-i",t,"-f","s16le","-ar",String(e),"-ac","1","-"]);c.stdout.on("data",y=>a.push(y));let m="";c.stderr.on("data",y=>{m+=y.toString()}),c.on("error",y=>{y.code==="ENOENT"?n(new g("audio.*","ffmpeg not found on PATH \u2014 install ffmpeg/ffprobe")):n(new g("audio.*",`ffmpeg failed: ${y.message}`))}),c.on("close",y=>{y!==0?n(new g("audio.*",`ffmpeg exit ${y}: ${m.trim()}`)):r(Buffer.concat(a))})})}var Ve=new Map;async function Rt(t){let e=JSON.stringify(t);if(/"\$ref"\s*:\s*"https?:\/\//.test(e))throw new g("json.schema_valid","remote $ref not supported in schema");let r=St("sha256").update(e).digest("hex"),n=Ve.get(r);if(n)return n;let a=(await import("ajv")).default,m=new a({strict:!1,allErrors:!1}).compile(t);return Ve.set(r,m),m}var Xe={"audio.duration_s":async t=>{z("audio.duration_s",t);let{stdout:e}=await Tt(["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",t]),r=parseFloat(e.trim());if(!Number.isFinite(r))throw new g("audio.duration_s",`ffprobe returned non-numeric duration: ${e.trim()}`);return r},"audio.zc_rate_per_s":async t=>{z("audio.zc_rate_per_s",t);let e=24e3,r=await Je(t,e),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let m=1;m<n.length;m++)n[m-1]>=0!=n[m]>=0&&a++;let c=n.length/e;return c>0?a/c:0},"audio.rms":async t=>{z("audio.rms",t);let r=await Je(t,24e3),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let c=0;c<n.length;c++){let m=n[c]/32768;a+=m*m}return n.length>0?Math.sqrt(a/n.length):0},"markdown.word_count":async t=>{z("markdown.word_count",t);let e=await X(t,"utf-8");return e.trim().length===0?0:e.trim().split(/\s+/).length},"image.width_px":async t=>{z("image.width_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.width!="number")throw new g("image.width_px","could not determine image width");return n.width},"image.height_px":async t=>{z("image.height_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.height!="number")throw new g("image.height_px","could not determine image height");return n.height},"pdf.page_count":async t=>{z("pdf.page_count",t);let{PDFDocument:e}=await import("pdf-lib"),r=await X(t);return(await e.load(r,{ignoreEncryption:!0})).getPageCount()},"json.schema_valid":async(t,e)=>{if(z("json.schema_valid",t),!e||typeof e!="object"||!("schema"in e))throw new g("json.schema_valid","missing schema arg");let r=await Rt(e.schema),n=await X(t,"utf-8"),a;try{a=JSON.parse(n)}catch(c){throw new g("json.schema_valid",`file is not valid JSON: ${c.message}`)}return r(a)===!0}};var Mt=Nt(Ot);async function Ge(t,e,r={}){let n=r.handlerRegistry??Xe;for(let a=0;a<e.length;a++){let c=e[a],m=We(c);if(m.kind==="script"){await Bt(m.scriptPath,t);continue}let y=n[m.key];if(!y)throw new L(m.key);let A=r.handlerArgsByIndex?.[a],i=await y(t,A);$t(m,i)}}function $t(t,e){switch(t.kind){case"comparison":{let{key:r,op:n,value:a}=t,c=!1;if(n==="<"?c=e<a:n===">"?c=e>a:n==="<="?c=e<=a:n===">="?c=e>=a:n==="=="?c=e==a:n==="!="&&(c=e!=a),!c)throw new C(r,e,`${n} ${a}`);break}case"between":{let{key:r,min:n,max:a}=t;if(e<n||e>a)throw new C(r,e,`between ${n} and ${a}`);break}case"in":{let{key:r,values:n}=t;if(!n.includes(e))throw new C(r,e,`in [${n.join(", ")}]`);break}case"matches":{let{key:r,regexSource:n,regexFlags:a}=t;if(!zt(String(e),n,a,100))throw new C(r,e,`matches /${n}/${a}`);break}}}async function Bt(t,e){if(!Dt(t))throw new g("script",`script path must be absolute: ${t}`);try{await Mt(t,[e],{timeout:6e4,maxBuffer:1024*1024})}catch(r){let n=r;if(n.code==="ENOENT")throw new g("script",`script not found: ${t}`);let a=n.exitCode;throw new C("script:"+Pt(t),a??"error",n.stderr?.trim()??n.message)}}function zt(t,e,r,n){let a={value:t,regex:new RegExp(e,r),result:!1};Ye.createContext(a);try{return Ye.runInContext("result = regex.test(value)",a,{timeout:n}),a.result}catch(c){throw new g("matches",`regex evaluation timeout or error: ${c.message}`)}}le();var Kt="execution-tools",Pr="mcp__execution-tools__",Mr=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory"],$r=["mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],Br=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory","mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],U=Z("execution"),qt=/^[\p{L}0-9._-]{1,256}$/u,Ht=/^[\p{L}0-9._-]{1,128}$/u,ne=256*1024,Qe=/^[a-z]+\/[a-z0-9.+-]+$/;async function Ut(t){let{listChannels:e}=await import("./channels-VYNJFXDD.js"),r=e(),{listSessions:n}=await import("./session-manager-HO2ZCB47.js"),a=[...n("active"),...n("archived")],{getDefaultChatIdForChannel:c}=await import("./target-resolution-RLNUCT6M.js"),m=r.find(A=>A.name.toLowerCase().includes(t.toLowerCase()));if(!m)return null;let y=c(m,a)??"";return{channelId:m.id,chatId:y}}function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function se(t){return qt.test(t)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ye(t){return Ht.test(t)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function Ze(t,e,r){return t!==e?t:Y(r)}function et(t,e){let r=ie(t);if(!r)return null;let n=oe(r.templateId);return n?n.steps.find(m=>m.id===e)?.outputAs??null:null}var Wt=t=>{if(!t)return!1;let e=j(t);return!!(e?.parentId&&e.templateId&&e.stepId)};function co(t,e,r){let n=t?ue(t):void 0,a=r??(()=>{}),c=async()=>{if(!e)return{error:"artifact tools require a task context"};let i=j(e);if(!i)return{error:`task not found: ${e}`};let o=i.roleId??t;if(!o)return{error:"this template execution task has no role context"};let p=ue(o);return p?{taskId:e,roleId:o,roleWorkspacePath:Re(p.name)}:{error:`role not found: ${o}`}},m=async()=>{let i=await c();if("error"in i)return i;let o=j(i.taskId);return o.parentId?o.stepId?{executionId:o.parentId,stepId:o.stepId,roleId:i.roleId,roleWorkspacePath:i.roleWorkspacePath,taskId:i.taskId}:{error:"this task is not a TemplateExecution step (no step_id)"}:{error:"this task is not a TemplateExecution step (no execution context)"}},y=[...je(t),M("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:i}=await import("./channels-VYNJFXDD.js"),o=i();return l({channels:o.map(p=>({id:p.id,name:p.name,enabled:p.enabled,type:p.config?.type??"unknown"}))})}),M("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:d.string().describe("The channel name, e.g., 'WeChat on iPad' or 'Client Mail'"),message:d.string().describe("The message content to send")},async i=>{if(n?.allowedChannels!==void 0){if(n.allowedChannels.length===0)return l({error:"This role is not allowed to send to any channels"});if(!n.allowedChannels.some(u=>u.toLowerCase()===i.channelName.toLowerCase()))return l({error:`Channel "${i.channelName}" is not in the allowed channels list for this role`})}let o=await Ut(i.channelName);if(!o)return l({error:`Channel "${i.channelName}" not found or has no chatId available`});let{getOutboundGateway:p}=await import("./outbound-gateway-O27KKVOI.js"),s=await p().send({channelId:o.channelId,chatId:o.chatId,content:i.message,messageType:"reply"});return l({success:s.success,channelName:i.channelName})}),M("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream TemplateExecution steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),value:d.unknown().describe("The JSON value to persist (must be <= 256KB serialized)."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=se(i.key);if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:p}),l({error:p});let x=et(o.executionId,o.stepId),s=ie(o.executionId),h=s?oe(s.templateId):null,u=h?h.steps.some(_=>_.id===o.stepId):!1,w=i.key,$,G=h!=null&&h.steps.some(_=>!!_.outputAs);if(x===null&&u&&G){let _=`Step "${o.stepId}" in template "${s.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:o.taskId,stepId:o.stepId,templateId:s.templateId},"write_artifact: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:_}),l({error:_})}x&&i.key!==x&&(w=x,$=`key '${i.key}' replaced with step.outputAs '${x}'`,U.warn({taskId:o.taskId,llmKey:i.key,outputAs:x},"write_artifact: server key override"));let Q=h?.steps?.find(_=>_.id===o.stepId),T=Q?Be(Q,i.value):!1;try{let _=he(),v,S;if(T){let R=i.value;if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact text exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}S=Lt(xe(o.executionId),`${_}.bin`),jt(S,R,"utf8")}else{let R=JSON.stringify(i.value);if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact JSON exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}}return J({id:_,sourceKind:"template_step",executionId:o.executionId,stepId:o.stepId,key:w,...T?{kind:"file",blobPath:S,mime:"text/markdown",originalFilename:`${w}.md`}:{kind:"json",value:i.value},sizeBytes:v,createdAt:Date.now(),roleId:o.roleId,priority:i.priority}),D({toolName:"write_artifact",entityType:"artifact",verb:"create",entityId:_,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:_,key:w,kind:T?"file":"json",taskId:o.taskId}}],taskId:o.taskId,roleId:o.roleId}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:w,artifactId:_,sizeBytes:v,outcome:"success"}),l({success:!0,artifactId:_,sizeBytes:v,...$?{note:$}:{}})}catch(_){let v=_ instanceof Error?_.message:String(_);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"error",errorReason:v}),l({error:v})}}),M("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="json"){let u="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"denied",errorReason:u}),l({error:u})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"success"}),l({value:h.value,sizeBytes:h.sizeBytes})}),M("publish_artifact_file",'REQUIRED final action for any TemplateExecution step that produces a file deliverable. If your step declares outputAs and you finish work (writing audio/video/report/image to disk via Write, Edit, or Bash) WITHOUT calling this tool, the step is marked FAILED \u2014 downstream steps and delivery rules will not see your file, regardless of whether your work succeeded. "I wrote a file to my workspace" is NOT the same as "I published an artifact": the file must be registered through this call to count. Call this AFTER the file is fully written to disk, BEFORE ending your turn. The file is COPIED to template execution shared storage. USE for: generated audio, video, reports, images, large outputs. Do NOT use for small structured JSON values (<=256KB) \u2014 use write_artifact instead. sourcePath must be inside your role workspace (~/.adam/roles/<your-role>/...); if your file was written to an additionalDirectories location (InfoHub/PKOS/Code/etc.), Bash-copy it into the workspace first then publish from there. cleanup=true deletes the source after publish \u2014 only set when you no longer need the source file (the step becomes non-retryable through publish).',{key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),sourcePath:me.describe("Source file path in the Role workspace to publish as a TemplateExecution artifact."),mime:d.string().optional().describe("MIME type of the file (e.g., 'image/png', 'audio/mp3'). Auto-detected if omitted."),cleanup:d.boolean().optional().describe("If true, delete the source file after publishing. Only use when the source file is no longer needed."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic."),role:d.string().optional().describe("Logical artifact role. REQUIRED when the step's outputContract declares expectedArtifacts \u2014 use one of the declared roles (e.g. 'podcast', 'song'). Publishing more than the declared count for a role, or an undeclared role, is rejected.")},async i=>{let o=await c();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=j(o.taskId);if(!!!(p.parentId&&p.templateId&&p.stepId)){if(i.mime&&!Qe.test(i.mime))return l({error:`Invalid MIME type: ${i.mime}`});try{te(i.sourcePath,o.roleWorkspacePath,!0)}catch(b){return l({error:b instanceof Error?b.message:String(b)})}let f=he(),E=null,N=!1;try{let b=Ee({kind:"task",artifactId:f,sourcePath:i.sourcePath});E=b.blobPath;let W={id:f,sourceKind:"task_published",taskId:o.taskId,roleId:o.roleId,kind:"file",blobPath:E,mime:i.mime,originalFilename:Y(i.sourcePath),sizeBytes:b.sizeBytes,createdAt:Date.now(),priority:i.priority};return J(W),N=!0,i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:f,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:f,kind:"file",filename:Y(i.sourcePath),taskId:o.taskId,sourceKind:"task_published"}}],taskId:o.taskId,roleId:o.roleId}),U.info({taskId:o.taskId,roleId:o.roleId,artifactId:f,sizeBytes:b.sizeBytes},"publish_artifact_file task_published: success"),l({success:!0,artifactId:f,sizeBytes:b.sizeBytes})}catch(b){if(N)try{ae(f)}catch{}if(E)try{de(E)}catch{}let W=b instanceof Error?b.message:String(b);return U.warn({taskId:o.taskId,roleId:o.roleId,artifactId:f,err:b},"publish_artifact_file task_published: failed"),l({error:W})}}let s={executionId:p.parentId,stepId:p.stepId,roleId:o.roleId,roleWorkspacePath:o.roleWorkspacePath,taskId:o.taskId},h=se(i.key);if(h)return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:h}),l({error:h});if(i.mime&&!Qe.test(i.mime)){let f=`Invalid MIME type: ${i.mime}`;return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}let u=et(s.executionId,s.stepId),w=ie(s.executionId),$=w?oe(w.templateId):null,G=$?$.steps.find(f=>f.id===s.stepId)??null:null,Q=G!=null,T=i.key,_,v=$!=null&&$.steps.some(f=>!!f.outputAs);if(u===null&&Q&&v){let f=`Step "${s.stepId}" in template "${w.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:s.taskId,stepId:s.stepId,templateId:w.templateId},"publish_artifact_file: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}u&&i.key!==u&&(T=u,_=`key '${i.key}' replaced with step.outputAs '${u}'`,U.warn({taskId:s.taskId,llmKey:i.key,outputAs:u},"publish_artifact_file: server key override"));try{te(i.sourcePath,s.roleWorkspacePath,!0)}catch(f){let E=f instanceof Error?f.message:String(f);return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,outcome:"denied",errorReason:E}),l({error:E})}let S=he(),R=null,O=!1,F=null;try{let f=we({executionId:s.executionId,artifactId:S,sourcePath:i.sourcePath});R=f.blobPath;let E=G?.assertions??[];E.length>0&&await Ge(R,E);let N={id:S,sourceKind:"template_step",executionId:s.executionId,stepId:s.stepId,key:T,kind:"file",blobPath:R,mime:i.mime,originalFilename:Y(i.sourcePath),sizeBytes:f.sizeBytes,createdAt:Date.now(),roleId:s.roleId,priority:i.priority,...i.role!==void 0?{artifactRole:i.role}:{}};if(u&&v){let b=ee(s.executionId,s.stepId,u);if(!b)J(N),O=!0,F=N;else if(b.kind==="file")F=ke(s.executionId,s.stepId,u,b,{...N,key:Ze(i.key,u,i.sourcePath)}).childArtifact;else if(b.kind==="json"&&be(b.value))F=ge(s.executionId,s.stepId,u,{...N,key:Ze(i.key,u,i.sourcePath)}).childArtifact;else throw new Error(`Artifact key "${u}" already contains a non-collection JSON artifact`)}else J(N),O=!0,F=N;return i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:S,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:S,key:F?.key??T,kind:"file",filename:Y(i.sourcePath),taskId:s.taskId}}],taskId:s.taskId,roleId:s.roleId}),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:F?.key??T,artifactId:S,sizeBytes:f.sizeBytes,outcome:"success"}),l({success:!0,artifactId:S,sizeBytes:f.sizeBytes,..._?{note:_}:{}})}catch(f){if(O)try{ae(S)}catch{}if(R&&(!F||O))try{de(R)}catch{}let E=f instanceof Error?f.message:String(f);if(I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,artifactId:S,outcome:"error",errorReason:E}),f instanceof C||f instanceof L)try{let b=(K().prepare("SELECT COUNT(*) as n FROM step_logs WHERE task_id = ?").get(s.taskId)?.n??0)+1;Te({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:s.taskId,index:b,type:"validator_error",content:f.message,toolName:"publish_artifact_file",timestamp:Date.now()})}catch{}return l({error:E})}}),M("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),destPath:me.describe("Destination path in the Role workspace where the file will be copied.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});try{te(i.destPath,o.roleWorkspacePath,!1)}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:w}),l({error:w})}let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="file"||!h.blobPath){let u="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,outcome:"denied",errorReason:u}),l({error:u})}try{let u=ve({blobPath:h.blobPath,destPath:i.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,sizeBytes:u.sizeBytes,outcome:"success"}),l({success:!0,sizeBytes:u.sizeBytes,mime:h.mime,destPath:i.destPath})}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,outcome:"error",errorReason:w}),l({error:w})}}),M("list_artifacts","Discover artifacts published by upstream steps in this template execution. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:re.optional().describe("Filter to a specific TemplateExecution step (omit to list all artifacts in the execution).")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=i.stepId?ye(i.stepId):null;if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:p}),l({error:p});let x=_e(o.executionId,i.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:x.length,outcome:"success"}),l({artifacts:x.map(s=>({id:s.id,stepId:s.stepId,key:s.key,kind:s.kind,sizeBytes:s.sizeBytes,mime:s.mime,createdAt:s.createdAt}))})}),M("report_blocked","Report that the task cannot proceed due to a missing prerequisite (e.g., missing credential, missing input, missing target). This sets the task status to 'blocked', stores the reason for the UI to display, and aborts the execution loop.",{reason:d.string().describe("Short reason, e.g. 'missing_credential', 'missing_target', 'missing_input'"),missingPrereqs:d.array(d.string()).optional().describe("Specific keys/IDs that are missing, e.g. ['MINIMAX_API_KEY']"),resumeHint:d.string().optional().describe("How the user can unblock, e.g. 'set MINIMAX_API_KEY in role env'")},async i=>{if(!e)return l({error:"report_blocked requires a task context (taskId not available)"});let o=j(e);if(!o)return l({error:`task not found: ${e}`});let p={reason:i.reason,missingPrereqs:i.missingPrereqs,resumeHint:i.resumeHint};return Ce(e,{status:"blocked",blockReason:p,completedAt:Date.now()}),Oe.emit({type:"task_status_change",taskId:e,oldStatus:o.status,newStatus:"blocked"}),D({toolName:"report_blocked",entityType:"task",verb:"update",entityId:e,fieldChanges:[{path:"status",op:"set",before:o.status,after:"blocked"},{path:"blockReason",op:"set",before:void 0,after:i.reason},{path:"completedAt",op:"set",before:void 0,after:Date.now()}],taskId:e,roleId:o.roleId}),a(),l({success:!0,blocked:!0,reason:i.reason})}),M("commit_claim","Declare structured claims about what this worker task just did so the audit engine can verify against effect receipts. Call this in the SAME task turn before reporting completion text. Mirror of the ChatManager tool \u2014 workers may also need to declare claims for actions taken inside template execution steps.",{claims:d.array(d.object({verb:d.string().min(1).describe("What was done: 'send', 'update', 'create', 'delete', 'cancel', 'enable', 'disable', 'bind', 'unbind', etc."),entityType:d.string().min(1).describe("What kind of thing was affected: 'channel_message', 'task_template', 'task', 'goal', 'role', 'delivery_rule', 'plugin', 'mcp_binding', 'config_field', etc."),expected:d.discriminatedUnion("kind",[d.object({kind:d.literal("outbound").describe("Used when verb='send' \u2014 declares a channel message was sent."),target:d.object({channelId:d.string().min(1).describe("Channel that received the message."),chatId:d.string().min(1).optional().describe("Specific chat within the channel; omit for any chat.")}).describe("Where the message went."),attachmentCount:d.number().int().min(0).optional().describe("How many attachments were sent. Verifier requires receipt.attachmentCount >= this."),textPresent:d.boolean().optional().describe("Whether the message body had non-empty text. Verifier requires receipt.textChars > 0 when true.")}),d.object({kind:d.literal("field_change").describe("Used for single-entity updates \u2014 declares a specific field on a specific entity changed."),entityId:d.string().min(1).describe("Identifier of the entity that was changed."),fieldPath:d.string().min(1).describe("Dotted path to the field that changed, e.g. 'deliverTo', 'cron', 'config.timeout'."),op:d.enum(["set","list_add","list_remove"]).describe("How the field changed: scalar set, list append, or list removal."),added:d.array(d.unknown()).min(1).optional().describe("Items appended when op='list_add'. Verifier accepts a superset (receipt may have appended more items)."),removed:d.array(d.unknown()).min(1).optional().describe("Items removed when op='list_remove'. Verifier accepts a superset."),after:d.unknown().optional().describe("New value when op='set'. Verifier requires deep-equal match.")}),d.object({kind:d.literal("batch").describe("Used for batch operations like cancel-many or delete-many."),entityType:d.string().min(1).describe("Restrict matching to this entity type."),entityIds:d.array(d.string()).min(1).optional().describe("Specific entity IDs affected. Verifier checks receipt.entityIds is a superset."),scope:d.object({filter:d.string().min(1).describe("Free-text description of the filter applied (e.g., 'status=running AND role_id=role-x'). Verifier ignores this; human-readable only."),expectedCount:d.number().int().min(0).describe("Minimum number of entities expected to have been affected. Verifier requires receipt.scope.matchedCount >= this.")}).optional().describe("Filter+count for scope-based batches when individual IDs aren't enumerated.")})]).describe("Structured expectation matched against effect_receipts. Pick the kind that fits the action."),note:d.string().optional().describe("Free-text human note kept in the audit log only. Verifier ignores this.")})).min(1).max(20).describe("One or more claims declaring exactly what just happened. Each claim is verified independently against receipts.")},async i=>{let o=Se();if(!o)return l({error:"commit_claim requires an active trace context"});try{let p=He({traceId:o,taskId:e,claims:i.claims});return l({claimRowId:p.id,claimsCount:p.claims.length,declaredAt:p.declaredAt})}catch(p){let x=p instanceof Error?p.message:String(p);return l({error:x})}})],A=Wt(e)?y.filter(i=>i.name!=="list_channels"&&i.name!=="send_to_channel"):y;return Ft({name:Kt,version:"1.0.0",tools:A})}export{je as a,He as b,dr as c,Xe as d,Kt as e,Pr as f,Mr as g,$r as h,Br as i,qt as j,co as k};
|
|
14
|
+
`).all(t).map(mt)}function mt(t){return{id:t.id,traceId:t.trace_id,sessionId:t.session_id??void 0,taskId:t.task_id??void 0,sourceMessageId:t.source_message_id??void 0,claims:JSON.parse(t.claims_json),declaredAt:t.declared_at}}rt();import{execFile as Ot}from"child_process";import{promisify as Nt}from"util";import{isAbsolute as Dt,basename as Pt}from"path";import Ye from"vm";import{isAbsolute as ft}from"path";var P=class extends Error{constructor(e,r){super(`DSL parse error in "${e}": ${r}`),this.name="DslParseError"}},ht=/^[a-z][a-z0-9_.]*$/i,yt=/\.\./;function V(t){if(!ht.test(t))throw new P(t,`invalid handler key format "${t}" \u2014 must match [a-z][a-z0-9_.]*`);if(yt.test(t))throw new P(t,'handler key must not contain ".."')}function Ue(t){let e=t.trim();try{let n=JSON.parse(e);if(typeof n=="number"||typeof n=="string"||typeof n=="boolean")return n}catch{}let r=parseFloat(e);return Number.isNaN(r)?e:r}var It=/^([a-z][a-z0-9_.]*)\s+matches\s+\/(.+)\/([gimsuy]*)$/i,_t=/^([a-z][a-z0-9_.]*)\s*(<=|>=|==|!=)\s*(.+)$/i,bt=/^([a-z][a-z0-9_.]*)\s*(<|>)\s*(.+)$/i,gt=/^([a-z][a-z0-9_.]*)\s+between\s+(-?\d+(?:\.\d+)?)\s+and\s+(-?\d+(?:\.\d+)?)$/i,kt=/^([a-z][a-z0-9_.]*)\s+in\s+\[([^\]]+)\]$/i;function We(t){if(typeof t=="object"&&t!==null&&"script"in t){let r=String(t.script);if(!ft(r))throw new P(`{script: "${r}"}`,"script path must be absolute");return{kind:"script",scriptPath:r}}if(typeof t!="string")throw new P(String(t),"assertion must be a string or {script: string} object");let e=t.trim();if(!e)throw new P(e,"empty assertion string");{let r=It.exec(e);if(r){let n=r[1];return V(n),{kind:"matches",key:n,regexSource:r[2],regexFlags:r[3]??""}}}{let r=gt.exec(e);if(r){let n=r[1];return V(n),{kind:"between",key:n,min:parseFloat(r[2]),max:parseFloat(r[3])}}}{let r=kt.exec(e);if(r){let n=r[1];V(n);let a=r[2],c=[];for(let m of a.split(",")){let y=m.trim();if(y)try{let A=JSON.parse(y);typeof A=="number"||typeof A=="string"||typeof A=="boolean"?c.push(A):c.push(y)}catch{c.push(y)}}return{kind:"in",key:n,values:c}}}{let r=_t.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}{let r=bt.exec(e);if(r){let n=r[1];return V(n),{kind:"comparison",key:n,op:r[2],value:Ue(r[3])}}}throw new P(e,"unrecognized assertion syntax \u2014 expected key <op> value, between, in [...], matches /.../, or {script: ...}")}import{execFile as wt,spawn as vt}from"child_process";import{promisify as Et}from"util";import{readFile as X}from"fs/promises";import{existsSync as At}from"fs";import{createHash as St}from"crypto";function xt(t){return typeof t=="number"?Number.isInteger(t)?t.toString():t.toFixed(4):JSON.stringify(t)}var L=class extends Error{constructor(r){super(`NO_HANDLER: ${r}, install relevant capability or remove assertion`);this.handlerKey=r;this.name="NoHandlerError"}handlerKey},C=class extends Error{constructor(r,n,a){super(`ASSERTION_FAILED: ${r}=${xt(n)}, expected ${a}`);this.handlerKey=r;this.measured=n;this.expected=a;this.name="AssertionFailedError"}handlerKey;measured;expected},g=class extends Error{constructor(r,n){super(`HANDLER_RUNTIME_ERROR: ${r}: ${n}`);this.handlerKey=r;this.detail=n;this.name="HandlerRuntimeError"}handlerKey;detail};var Ct=Et(wt);function z(t,e){if(!At(e))throw new g(t,`file not found: ${e}`)}async function Tt(t){try{return await Ct("ffprobe",t,{maxBuffer:10*1024*1024})}catch(e){throw e.code==="ENOENT"?new g("audio.*","ffprobe not found on PATH \u2014 install ffmpeg/ffprobe"):new g("audio.*",`ffprobe failed: ${e.message}`)}}async function Je(t,e){return new Promise((r,n)=>{let a=[],c=vt("ffmpeg",["-v","error","-i",t,"-f","s16le","-ar",String(e),"-ac","1","-"]);c.stdout.on("data",y=>a.push(y));let m="";c.stderr.on("data",y=>{m+=y.toString()}),c.on("error",y=>{y.code==="ENOENT"?n(new g("audio.*","ffmpeg not found on PATH \u2014 install ffmpeg/ffprobe")):n(new g("audio.*",`ffmpeg failed: ${y.message}`))}),c.on("close",y=>{y!==0?n(new g("audio.*",`ffmpeg exit ${y}: ${m.trim()}`)):r(Buffer.concat(a))})})}var Ve=new Map;async function Rt(t){let e=JSON.stringify(t);if(/"\$ref"\s*:\s*"https?:\/\//.test(e))throw new g("json.schema_valid","remote $ref not supported in schema");let r=St("sha256").update(e).digest("hex"),n=Ve.get(r);if(n)return n;let a=(await import("ajv")).default,m=new a({strict:!1,allErrors:!1}).compile(t);return Ve.set(r,m),m}var Xe={"audio.duration_s":async t=>{z("audio.duration_s",t);let{stdout:e}=await Tt(["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",t]),r=parseFloat(e.trim());if(!Number.isFinite(r))throw new g("audio.duration_s",`ffprobe returned non-numeric duration: ${e.trim()}`);return r},"audio.zc_rate_per_s":async t=>{z("audio.zc_rate_per_s",t);let e=24e3,r=await Je(t,e),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let m=1;m<n.length;m++)n[m-1]>=0!=n[m]>=0&&a++;let c=n.length/e;return c>0?a/c:0},"audio.rms":async t=>{z("audio.rms",t);let r=await Je(t,24e3),n=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),a=0;for(let c=0;c<n.length;c++){let m=n[c]/32768;a+=m*m}return n.length>0?Math.sqrt(a/n.length):0},"markdown.word_count":async t=>{z("markdown.word_count",t);let e=await X(t,"utf-8");return e.trim().length===0?0:e.trim().split(/\s+/).length},"image.width_px":async t=>{z("image.width_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.width!="number")throw new g("image.width_px","could not determine image width");return n.width},"image.height_px":async t=>{z("image.height_px",t);let{imageSize:e}=await import("image-size"),r=await X(t),n=e(r);if(typeof n.height!="number")throw new g("image.height_px","could not determine image height");return n.height},"pdf.page_count":async t=>{z("pdf.page_count",t);let{PDFDocument:e}=await import("pdf-lib"),r=await X(t);return(await e.load(r,{ignoreEncryption:!0})).getPageCount()},"json.schema_valid":async(t,e)=>{if(z("json.schema_valid",t),!e||typeof e!="object"||!("schema"in e))throw new g("json.schema_valid","missing schema arg");let r=await Rt(e.schema),n=await X(t,"utf-8"),a;try{a=JSON.parse(n)}catch(c){throw new g("json.schema_valid",`file is not valid JSON: ${c.message}`)}return r(a)===!0}};var Mt=Nt(Ot);async function Ge(t,e,r={}){let n=r.handlerRegistry??Xe;for(let a=0;a<e.length;a++){let c=e[a],m=We(c);if(m.kind==="script"){await Bt(m.scriptPath,t);continue}let y=n[m.key];if(!y)throw new L(m.key);let A=r.handlerArgsByIndex?.[a],i=await y(t,A);$t(m,i)}}function $t(t,e){switch(t.kind){case"comparison":{let{key:r,op:n,value:a}=t,c=!1;if(n==="<"?c=e<a:n===">"?c=e>a:n==="<="?c=e<=a:n===">="?c=e>=a:n==="=="?c=e==a:n==="!="&&(c=e!=a),!c)throw new C(r,e,`${n} ${a}`);break}case"between":{let{key:r,min:n,max:a}=t;if(e<n||e>a)throw new C(r,e,`between ${n} and ${a}`);break}case"in":{let{key:r,values:n}=t;if(!n.includes(e))throw new C(r,e,`in [${n.join(", ")}]`);break}case"matches":{let{key:r,regexSource:n,regexFlags:a}=t;if(!zt(String(e),n,a,100))throw new C(r,e,`matches /${n}/${a}`);break}}}async function Bt(t,e){if(!Dt(t))throw new g("script",`script path must be absolute: ${t}`);try{await Mt(t,[e],{timeout:6e4,maxBuffer:1024*1024})}catch(r){let n=r;if(n.code==="ENOENT")throw new g("script",`script not found: ${t}`);let a=n.exitCode;throw new C("script:"+Pt(t),a??"error",n.stderr?.trim()??n.message)}}function zt(t,e,r,n){let a={value:t,regex:new RegExp(e,r),result:!1};Ye.createContext(a);try{return Ye.runInContext("result = regex.test(value)",a,{timeout:n}),a.result}catch(c){throw new g("matches",`regex evaluation timeout or error: ${c.message}`)}}le();var Kt="execution-tools",Pr="mcp__execution-tools__",Mr=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory"],$r=["mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],Br=["mcp__execution-tools__write_artifact","mcp__execution-tools__publish_artifact_file","mcp__execution-tools__send_to_channel","mcp__execution-tools__report_blocked","mcp__execution-tools__commit_claim","mcp__execution-tools__save_memory","mcp__execution-tools__delete_memory","mcp__execution-tools__list_channels","mcp__execution-tools__read_artifact","mcp__execution-tools__fetch_artifact_file","mcp__execution-tools__list_artifacts","mcp__execution-tools__search_memories"],U=Z("execution"),qt=/^[\p{L}0-9._-]{1,256}$/u,Ht=/^[\p{L}0-9._-]{1,128}$/u,ne=256*1024,Qe=/^[a-z]+\/[a-z0-9.+-]+$/;async function Ut(t){let{listChannels:e}=await import("./channels-2TWTBE6Y.js"),r=e(),{listSessions:n}=await import("./session-manager-XFUKWEC7.js"),a=[...n("active"),...n("archived")],{getDefaultChatIdForChannel:c}=await import("./target-resolution-RLNUCT6M.js"),m=r.find(A=>A.name.toLowerCase().includes(t.toLowerCase()));if(!m)return null;let y=c(m,a)??"";return{channelId:m.id,chatId:y}}function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function se(t){return qt.test(t)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ye(t){return Ht.test(t)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function Ze(t,e,r){return t!==e?t:Y(r)}function et(t,e){let r=ie(t);if(!r)return null;let n=oe(r.templateId);return n?n.steps.find(m=>m.id===e)?.outputAs??null:null}var Wt=t=>{if(!t)return!1;let e=j(t);return!!(e?.parentId&&e.templateId&&e.stepId)};function co(t,e,r){let n=t?ue(t):void 0,a=r??(()=>{}),c=async()=>{if(!e)return{error:"artifact tools require a task context"};let i=j(e);if(!i)return{error:`task not found: ${e}`};let o=i.roleId??t;if(!o)return{error:"this template execution task has no role context"};let p=ue(o);return p?{taskId:e,roleId:o,roleWorkspacePath:Re(p.name)}:{error:`role not found: ${o}`}},m=async()=>{let i=await c();if("error"in i)return i;let o=j(i.taskId);return o.parentId?o.stepId?{executionId:o.parentId,stepId:o.stepId,roleId:i.roleId,roleWorkspacePath:i.roleWorkspacePath,taskId:i.taskId}:{error:"this task is not a TemplateExecution step (no step_id)"}:{error:"this task is not a TemplateExecution step (no execution context)"}},y=[...je(t),M("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:i}=await import("./channels-2TWTBE6Y.js"),o=i();return l({channels:o.map(p=>({id:p.id,name:p.name,enabled:p.enabled,type:p.config?.type??"unknown"}))})}),M("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:d.string().describe("The channel name, e.g., 'WeChat on iPad' or 'Client Mail'"),message:d.string().describe("The message content to send")},async i=>{if(n?.allowedChannels!==void 0){if(n.allowedChannels.length===0)return l({error:"This role is not allowed to send to any channels"});if(!n.allowedChannels.some(u=>u.toLowerCase()===i.channelName.toLowerCase()))return l({error:`Channel "${i.channelName}" is not in the allowed channels list for this role`})}let o=await Ut(i.channelName);if(!o)return l({error:`Channel "${i.channelName}" not found or has no chatId available`});let{getOutboundGateway:p}=await import("./outbound-gateway-NJNSN2ZX.js"),s=await p().send({channelId:o.channelId,chatId:o.chatId,content:i.message,messageType:"reply"});return l({success:s.success,channelName:i.channelName})}),M("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream TemplateExecution steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),value:d.unknown().describe("The JSON value to persist (must be <= 256KB serialized)."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=se(i.key);if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:p}),l({error:p});let x=et(o.executionId,o.stepId),s=ie(o.executionId),h=s?oe(s.templateId):null,u=h?h.steps.some(_=>_.id===o.stepId):!1,w=i.key,$,G=h!=null&&h.steps.some(_=>!!_.outputAs);if(x===null&&u&&G){let _=`Step "${o.stepId}" in template "${s.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:o.taskId,stepId:o.stepId,templateId:s.templateId},"write_artifact: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:_}),l({error:_})}x&&i.key!==x&&(w=x,$=`key '${i.key}' replaced with step.outputAs '${x}'`,U.warn({taskId:o.taskId,llmKey:i.key,outputAs:x},"write_artifact: server key override"));let Q=h?.steps?.find(_=>_.id===o.stepId),T=Q?Be(Q,i.value):!1;try{let _=he(),v,S;if(T){let R=i.value;if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact text exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}S=Lt(xe(o.executionId),`${_}.bin`),jt(S,R,"utf8")}else{let R=JSON.stringify(i.value);if(v=Buffer.byteLength(R,"utf8"),v>ne){let O=`Artifact JSON exceeds ${ne} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:v,outcome:"denied",errorReason:O}),l({error:O})}}return J({id:_,sourceKind:"template_step",executionId:o.executionId,stepId:o.stepId,key:w,...T?{kind:"file",blobPath:S,mime:"text/markdown",originalFilename:`${w}.md`}:{kind:"json",value:i.value},sizeBytes:v,createdAt:Date.now(),roleId:o.roleId,priority:i.priority}),D({toolName:"write_artifact",entityType:"artifact",verb:"create",entityId:_,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:_,key:w,kind:T?"file":"json",taskId:o.taskId}}],taskId:o.taskId,roleId:o.roleId}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:w,artifactId:_,sizeBytes:v,outcome:"success"}),l({success:!0,artifactId:_,sizeBytes:v,...$?{note:$}:{}})}catch(_){let v=_ instanceof Error?_.message:String(_);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"error",errorReason:v}),l({error:v})}}),M("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="json"){let u="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"denied",errorReason:u}),l({error:u})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:h.id,sizeBytes:h.sizeBytes,outcome:"success"}),l({value:h.value,sizeBytes:h.sizeBytes})}),M("publish_artifact_file",'REQUIRED final action for any TemplateExecution step that produces a file deliverable. If your step declares outputAs and you finish work (writing audio/video/report/image to disk via Write, Edit, or Bash) WITHOUT calling this tool, the step is marked FAILED \u2014 downstream steps and delivery rules will not see your file, regardless of whether your work succeeded. "I wrote a file to my workspace" is NOT the same as "I published an artifact": the file must be registered through this call to count. Call this AFTER the file is fully written to disk, BEFORE ending your turn. The file is COPIED to template execution shared storage. USE for: generated audio, video, reports, images, large outputs. Do NOT use for small structured JSON values (<=256KB) \u2014 use write_artifact instead. sourcePath must be inside your role workspace (~/.adam/roles/<your-role>/...); if your file was written to an additionalDirectories location (InfoHub/PKOS/Code/etc.), Bash-copy it into the workspace first then publish from there. cleanup=true deletes the source after publish \u2014 only set when you no longer need the source file (the step becomes non-retryable through publish).',{key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),sourcePath:me.describe("Source file path in the Role workspace to publish as a TemplateExecution artifact."),mime:d.string().optional().describe("MIME type of the file (e.g., 'image/png', 'audio/mp3'). Auto-detected if omitted."),cleanup:d.boolean().optional().describe("If true, delete the source file after publishing. Only use when the source file is no longer needed."),priority:d.number().int().min(0).max(1e3).optional().describe("Lower = higher priority for delivery packing. Use 10 for primary deliverables (audio/video), 50 for text/markdown, 100 for images. Omit to use server-side heuristic."),role:d.string().optional().describe("Logical artifact role. REQUIRED when the step's outputContract declares expectedArtifacts \u2014 use one of the declared roles (e.g. 'podcast', 'song'). Publishing more than the declared count for a role, or an undeclared role, is rejected.")},async i=>{let o=await c();if("error"in o)return l({error:o.error});if(i.priority!==void 0&&(i.priority<0||i.priority>1e3||!Number.isInteger(i.priority)))return l({error:`Invalid priority: ${i.priority}. Must be an integer between 0 and 1000.`});let p=j(o.taskId);if(!!!(p.parentId&&p.templateId&&p.stepId)){if(i.mime&&!Qe.test(i.mime))return l({error:`Invalid MIME type: ${i.mime}`});try{te(i.sourcePath,o.roleWorkspacePath,!0)}catch(b){return l({error:b instanceof Error?b.message:String(b)})}let f=he(),E=null,N=!1;try{let b=Ee({kind:"task",artifactId:f,sourcePath:i.sourcePath});E=b.blobPath;let W={id:f,sourceKind:"task_published",taskId:o.taskId,roleId:o.roleId,kind:"file",blobPath:E,mime:i.mime,originalFilename:Y(i.sourcePath),sizeBytes:b.sizeBytes,createdAt:Date.now(),priority:i.priority};return J(W),N=!0,i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:f,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:f,kind:"file",filename:Y(i.sourcePath),taskId:o.taskId,sourceKind:"task_published"}}],taskId:o.taskId,roleId:o.roleId}),U.info({taskId:o.taskId,roleId:o.roleId,artifactId:f,sizeBytes:b.sizeBytes},"publish_artifact_file task_published: success"),l({success:!0,artifactId:f,sizeBytes:b.sizeBytes})}catch(b){if(N)try{ae(f)}catch{}if(E)try{de(E)}catch{}let W=b instanceof Error?b.message:String(b);return U.warn({taskId:o.taskId,roleId:o.roleId,artifactId:f,err:b},"publish_artifact_file task_published: failed"),l({error:W})}}let s={executionId:p.parentId,stepId:p.stepId,roleId:o.roleId,roleWorkspacePath:o.roleWorkspacePath,taskId:o.taskId},h=se(i.key);if(h)return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:h}),l({error:h});if(i.mime&&!Qe.test(i.mime)){let f=`Invalid MIME type: ${i.mime}`;return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}let u=et(s.executionId,s.stepId),w=ie(s.executionId),$=w?oe(w.templateId):null,G=$?$.steps.find(f=>f.id===s.stepId)??null:null,Q=G!=null,T=i.key,_,v=$!=null&&$.steps.some(f=>!!f.outputAs);if(u===null&&Q&&v){let f=`Step "${s.stepId}" in template "${w.templateId}" has no outputAs declared. This template must be migrated before its steps can publish artifacts. Operator action required: run \`pnpm tsx scripts/migrate-all-templates-outputAs.ts --apply\` from the project root, or have the operator ask ChatManager in chat to upgrade the template.`;return U.warn({taskId:s.taskId,stepId:s.stepId,templateId:w.templateId},"publish_artifact_file: step has no outputAs in migrated template"),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:f}),l({error:f})}u&&i.key!==u&&(T=u,_=`key '${i.key}' replaced with step.outputAs '${u}'`,U.warn({taskId:s.taskId,llmKey:i.key,outputAs:u},"publish_artifact_file: server key override"));try{te(i.sourcePath,s.roleWorkspacePath,!0)}catch(f){let E=f instanceof Error?f.message:String(f);return I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,outcome:"denied",errorReason:E}),l({error:E})}let S=he(),R=null,O=!1,F=null;try{let f=we({executionId:s.executionId,artifactId:S,sourcePath:i.sourcePath});R=f.blobPath;let E=G?.assertions??[];E.length>0&&await Ge(R,E);let N={id:S,sourceKind:"template_step",executionId:s.executionId,stepId:s.stepId,key:T,kind:"file",blobPath:R,mime:i.mime,originalFilename:Y(i.sourcePath),sizeBytes:f.sizeBytes,createdAt:Date.now(),roleId:s.roleId,priority:i.priority,...i.role!==void 0?{artifactRole:i.role}:{}};if(u&&v){let b=ee(s.executionId,s.stepId,u);if(!b)J(N),O=!0,F=N;else if(b.kind==="file")F=ke(s.executionId,s.stepId,u,b,{...N,key:Ze(i.key,u,i.sourcePath)}).childArtifact;else if(b.kind==="json"&&be(b.value))F=ge(s.executionId,s.stepId,u,{...N,key:Ze(i.key,u,i.sourcePath)}).childArtifact;else throw new Error(`Artifact key "${u}" already contains a non-collection JSON artifact`)}else J(N),O=!0,F=N;return i.cleanup===!0&&ce(i.sourcePath),D({toolName:"publish_artifact_file",entityType:"artifact",verb:"create",entityId:S,fieldChanges:[{path:"_entity",op:"set",before:null,after:{artifactId:S,key:F?.key??T,kind:"file",filename:Y(i.sourcePath),taskId:s.taskId}}],taskId:s.taskId,roleId:s.roleId}),I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:F?.key??T,artifactId:S,sizeBytes:f.sizeBytes,outcome:"success"}),l({success:!0,artifactId:S,sizeBytes:f.sizeBytes,..._?{note:_}:{}})}catch(f){if(O)try{ae(S)}catch{}if(R&&(!F||O))try{de(R)}catch{}let E=f instanceof Error?f.message:String(f);if(I({timestamp:Date.now(),taskId:s.taskId,roleId:s.roleId,executionId:s.executionId,stepId:s.stepId,tool:"publish_artifact_file",artifactKey:T,artifactId:S,outcome:"error",errorReason:E}),f instanceof C||f instanceof L)try{let b=(K().prepare("SELECT COUNT(*) as n FROM step_logs WHERE task_id = ?").get(s.taskId)?.n??0)+1;Te({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:s.taskId,index:b,type:"validator_error",content:f.message,toolName:"publish_artifact_file",timestamp:Date.now()})}catch{}return l({error:E})}}),M("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:re.describe("TemplateExecution step ID of the artifact's source step."),key:d.string().describe("Artifact key \u2014 a unique identifier for this value within the template execution."),destPath:me.describe("Destination path in the Role workspace where the file will be copied.")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=ye(i.stepId),x=se(i.key),s=p??x;if(s)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:s}),l({error:s});try{te(i.destPath,o.roleWorkspacePath,!1)}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:w}),l({error:w})}let h=ee(o.executionId,i.stepId,i.key);if(!h){let u=`no artifact at ${i.stepId}/${i.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"error",errorReason:u}),l({error:u})}if(h.kind!=="file"||!h.blobPath){let u="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,outcome:"denied",errorReason:u}),l({error:u})}try{let u=ve({blobPath:h.blobPath,destPath:i.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,sizeBytes:u.sizeBytes,outcome:"success"}),l({success:!0,sizeBytes:u.sizeBytes,mime:h.mime,destPath:i.destPath})}catch(u){let w=u instanceof Error?u.message:String(u);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:h.id,outcome:"error",errorReason:w}),l({error:w})}}),M("list_artifacts","Discover artifacts published by upstream steps in this template execution. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:re.optional().describe("Filter to a specific TemplateExecution step (omit to list all artifacts in the execution).")},async i=>{let o=await m();if("error"in o)return l({error:o.error});let p=i.stepId?ye(i.stepId):null;if(p)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:p}),l({error:p});let x=_e(o.executionId,i.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:x.length,outcome:"success"}),l({artifacts:x.map(s=>({id:s.id,stepId:s.stepId,key:s.key,kind:s.kind,sizeBytes:s.sizeBytes,mime:s.mime,createdAt:s.createdAt}))})}),M("report_blocked","Report that the task cannot proceed due to a missing prerequisite (e.g., missing credential, missing input, missing target). This sets the task status to 'blocked', stores the reason for the UI to display, and aborts the execution loop.",{reason:d.string().describe("Short reason, e.g. 'missing_credential', 'missing_target', 'missing_input'"),missingPrereqs:d.array(d.string()).optional().describe("Specific keys/IDs that are missing, e.g. ['MINIMAX_API_KEY']"),resumeHint:d.string().optional().describe("How the user can unblock, e.g. 'set MINIMAX_API_KEY in role env'")},async i=>{if(!e)return l({error:"report_blocked requires a task context (taskId not available)"});let o=j(e);if(!o)return l({error:`task not found: ${e}`});let p={reason:i.reason,missingPrereqs:i.missingPrereqs,resumeHint:i.resumeHint};return Ce(e,{status:"blocked",blockReason:p,completedAt:Date.now()}),Oe.emit({type:"task_status_change",taskId:e,oldStatus:o.status,newStatus:"blocked"}),D({toolName:"report_blocked",entityType:"task",verb:"update",entityId:e,fieldChanges:[{path:"status",op:"set",before:o.status,after:"blocked"},{path:"blockReason",op:"set",before:void 0,after:i.reason},{path:"completedAt",op:"set",before:void 0,after:Date.now()}],taskId:e,roleId:o.roleId}),a(),l({success:!0,blocked:!0,reason:i.reason})}),M("commit_claim","Declare structured claims about what this worker task just did so the audit engine can verify against effect receipts. Call this in the SAME task turn before reporting completion text. Mirror of the ChatManager tool \u2014 workers may also need to declare claims for actions taken inside template execution steps.",{claims:d.array(d.object({verb:d.string().min(1).describe("What was done: 'send', 'update', 'create', 'delete', 'cancel', 'enable', 'disable', 'bind', 'unbind', etc."),entityType:d.string().min(1).describe("What kind of thing was affected: 'channel_message', 'task_template', 'task', 'goal', 'role', 'delivery_rule', 'plugin', 'mcp_binding', 'config_field', etc."),expected:d.discriminatedUnion("kind",[d.object({kind:d.literal("outbound").describe("Used when verb='send' \u2014 declares a channel message was sent."),target:d.object({channelId:d.string().min(1).describe("Channel that received the message."),chatId:d.string().min(1).optional().describe("Specific chat within the channel; omit for any chat.")}).describe("Where the message went."),attachmentCount:d.number().int().min(0).optional().describe("How many attachments were sent. Verifier requires receipt.attachmentCount >= this."),textPresent:d.boolean().optional().describe("Whether the message body had non-empty text. Verifier requires receipt.textChars > 0 when true.")}),d.object({kind:d.literal("field_change").describe("Used for single-entity updates \u2014 declares a specific field on a specific entity changed."),entityId:d.string().min(1).describe("Identifier of the entity that was changed."),fieldPath:d.string().min(1).describe("Dotted path to the field that changed, e.g. 'deliverTo', 'cron', 'config.timeout'."),op:d.enum(["set","list_add","list_remove"]).describe("How the field changed: scalar set, list append, or list removal."),added:d.array(d.unknown()).min(1).optional().describe("Items appended when op='list_add'. Verifier accepts a superset (receipt may have appended more items)."),removed:d.array(d.unknown()).min(1).optional().describe("Items removed when op='list_remove'. Verifier accepts a superset."),after:d.unknown().optional().describe("New value when op='set'. Verifier requires deep-equal match.")}),d.object({kind:d.literal("batch").describe("Used for batch operations like cancel-many or delete-many."),entityType:d.string().min(1).describe("Restrict matching to this entity type."),entityIds:d.array(d.string()).min(1).optional().describe("Specific entity IDs affected. Verifier checks receipt.entityIds is a superset."),scope:d.object({filter:d.string().min(1).describe("Free-text description of the filter applied (e.g., 'status=running AND role_id=role-x'). Verifier ignores this; human-readable only."),expectedCount:d.number().int().min(0).describe("Minimum number of entities expected to have been affected. Verifier requires receipt.scope.matchedCount >= this.")}).optional().describe("Filter+count for scope-based batches when individual IDs aren't enumerated.")})]).describe("Structured expectation matched against effect_receipts. Pick the kind that fits the action."),note:d.string().optional().describe("Free-text human note kept in the audit log only. Verifier ignores this.")})).min(1).max(20).describe("One or more claims declaring exactly what just happened. Each claim is verified independently against receipts.")},async i=>{let o=Se();if(!o)return l({error:"commit_claim requires an active trace context"});try{let p=He({traceId:o,taskId:e,claims:i.claims});return l({claimRowId:p.id,claimsCount:p.claims.length,declaredAt:p.declaredAt})}catch(p){let x=p instanceof Error?p.message:String(p);return l({error:x})}})],A=Wt(e)?y.filter(i=>i.name!=="list_channels"&&i.name!=="send_to_channel"):y;return Ft({name:Kt,version:"1.0.0",tools:A})}export{je as a,He as b,dr as c,Xe as d,Kt as e,Pr as f,Mr as g,$r as h,Br as i,qt as j,co as k};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as c}from"./chunk-
|
|
1
|
+
import{h as c}from"./chunk-V2MMQ3SH.js";import{K as u,L as p}from"./chunk-2A2TXYT3.js";import{n as s,p as f}from"./chunk-WY5BOCQP.js";f();p();function r(e){return{id:e.id,roleId:e.role_id,content:e.content,isAnti:e.is_anti===1,evidenceObsIds:e.evidence_obs_ids?JSON.parse(e.evidence_obs_ids):[],embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,supersededBy:e.superseded_by??void 0,createdAt:e.created_at,lastUsedAt:e.last_used_at,lastValidatedAt:e.last_validated_at,scopeKey:e.scope_key??void 0,status:e.status,successEma:e.success_ema??void 0,injectCount:e.inject_count??0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function g(e){let t=s(),n=e.lastUsedAt??u(e.roleId);t.prepare(`
|
|
2
2
|
INSERT INTO beliefs (id, role_id, content,
|
|
3
3
|
is_anti, evidence_obs_ids, embedding, superseded_by,
|
|
4
4
|
created_at, last_used_at, last_validated_at,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as o,p as a}from"./chunk-
|
|
1
|
+
import{n as o,p as a}from"./chunk-WY5BOCQP.js";import{c as u,e as c}from"./chunk-5M6IGE5G.js";a();c();import{v4 as p}from"uuid";function R(t){o().prepare(`
|
|
2
2
|
INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source, trace_id)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
4
|
`).run(p(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection",t.traceId??u()??null)}function _(t=100,e=0){return o().prepare(`
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import{k as D}from"./chunk-IEBAOZED.js";import{c as L,p as K}from"./chunk-2A2TXYT3.js";import{a as M,e as E}from"./chunk-3MROEPGR.js";import{n as y,p as W}from"./chunk-WY5BOCQP.js";import{c as b,h as w}from"./chunk-EZLBMUQD.js";W();function N(m){if(m.length===0)return;let s=y(),e=s.prepare(`
|
|
2
|
+
INSERT OR IGNORE INTO llm_costs
|
|
3
|
+
(id, call_id, source, model, role_id, task_id, session_id, message_id,
|
|
4
|
+
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
|
|
5
|
+
cost_usd, priced, estimated, sdk_total_cost_usd, num_turns, created_at)
|
|
6
|
+
VALUES
|
|
7
|
+
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
+
`);s.transaction(i=>{for(let o of i)e.run(o.id,o.callId,o.source,o.model,o.roleId??null,o.taskId??null,o.sessionId??null,o.messageId??null,o.inputTokens,o.outputTokens,o.cacheReadTokens,o.cacheCreationTokens,o.costUsd,o.priced,o.estimated,o.sdkTotalCostUsd??null,o.numTurns??null,o.createdAt)})(m)}var R=new Set(["model","role","source","date"]),O=new Set(["day","week","month"]),B=new Set(["source","model"]);async function X(m){let{from:s,to:e,groupBy:c,granularity:i,trendStackBy:o}=m;if(!R.has(c))throw new Error(`Invalid groupBy: ${c}. Must be one of ${[...R].join(", ")}`);if(!O.has(i))throw new Error(`Invalid granularity: ${i}. Must be one of ${[...O].join(", ")}`);if(o!==void 0&&!B.has(o))throw new Error(`Invalid trendStackBy: ${o}. Must be one of ${[...B].join(", ")}`);let a=y(),p=`datetime(created_at / 1000 + (${Math.trunc(m.tzOffsetMinutes??0)*60}), 'unixepoch')`,d;c==="model"?d="model":c==="role"?d="COALESCE(role_id, 'system')":c==="source"?d="source":d=`strftime('%Y-%m-%d', ${p})`;let U=a.prepare(`
|
|
9
|
+
SELECT
|
|
10
|
+
${d} AS key,
|
|
11
|
+
SUM(cost_usd) AS costUsd,
|
|
12
|
+
SUM(input_tokens) AS inputTokens,
|
|
13
|
+
SUM(output_tokens) AS outputTokens,
|
|
14
|
+
SUM(cache_read_tokens) AS cacheReadTokens,
|
|
15
|
+
SUM(cache_creation_tokens) AS cacheCreationTokens,
|
|
16
|
+
COUNT(DISTINCT call_id) AS callCount
|
|
17
|
+
FROM llm_costs
|
|
18
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
19
|
+
GROUP BY key
|
|
20
|
+
ORDER BY costUsd DESC
|
|
21
|
+
`).all(s,e).map(n=>({key:n.key,costUsd:n.costUsd??0,inputTokens:n.inputTokens??0,outputTokens:n.outputTokens??0,cacheReadTokens:n.cacheReadTokens??0,cacheCreationTokens:n.cacheCreationTokens??0,callCount:n.callCount??0})),k=a.prepare(`
|
|
22
|
+
SELECT
|
|
23
|
+
SUM(cost_usd) AS totalCostUsd,
|
|
24
|
+
SUM(input_tokens) AS inputTokens,
|
|
25
|
+
SUM(output_tokens) AS outputTokens,
|
|
26
|
+
SUM(cache_read_tokens) AS cacheReadTokens,
|
|
27
|
+
SUM(cache_creation_tokens) AS cacheCreationTokens,
|
|
28
|
+
COUNT(DISTINCT call_id) AS callCount
|
|
29
|
+
FROM llm_costs
|
|
30
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
31
|
+
`).get(s,e),r=a.prepare(`
|
|
32
|
+
SELECT
|
|
33
|
+
COUNT(DISTINCT call_id) AS unpricedCallCount,
|
|
34
|
+
SUM(input_tokens + output_tokens) AS unpricedTokens
|
|
35
|
+
FROM llm_costs
|
|
36
|
+
WHERE created_at >= ? AND created_at <= ? AND priced = 0
|
|
37
|
+
`).get(s,e),f=a.prepare(`
|
|
38
|
+
SELECT model
|
|
39
|
+
FROM llm_costs
|
|
40
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
41
|
+
GROUP BY model
|
|
42
|
+
ORDER BY SUM(cost_usd) DESC
|
|
43
|
+
LIMIT 1
|
|
44
|
+
`).get(s,e),T;i==="day"?T="%Y-%m-%d":i==="week"?T="%Y-W%W":T="%Y-%m";let C=a.prepare(`
|
|
45
|
+
SELECT
|
|
46
|
+
strftime('${T}', ${p}) AS bucket,
|
|
47
|
+
SUM(cost_usd) AS costUsd,
|
|
48
|
+
COUNT(DISTINCT call_id) AS callCount
|
|
49
|
+
FROM llm_costs
|
|
50
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
51
|
+
GROUP BY bucket
|
|
52
|
+
ORDER BY bucket ASC
|
|
53
|
+
`).all(s,e),g,l;if(o!==void 0){let n=o==="source"?"source":"model",F=a.prepare(`
|
|
54
|
+
SELECT
|
|
55
|
+
strftime('${T}', ${p}) AS bucket,
|
|
56
|
+
${n} AS stackKey,
|
|
57
|
+
SUM(cost_usd) AS costUsd
|
|
58
|
+
FROM llm_costs
|
|
59
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
60
|
+
GROUP BY bucket, stackKey
|
|
61
|
+
ORDER BY bucket ASC
|
|
62
|
+
`).all(s,e),h=new Set,I=new Map;for(let S of F){let A=S.stackKey??"unknown";h.add(A);let _=I.get(S.bucket);_||(_={bucket:S.bucket},I.set(S.bucket,_)),_[A]=(_[A]??0)+(S.costUsd??0)}l=[...h],g=[...I.values()]}return{totalCostUsd:k?.totalCostUsd??0,callCount:k?.callCount??0,topModel:f?.model,tokens:{input:k?.inputTokens??0,output:k?.outputTokens??0,cacheRead:k?.cacheReadTokens??0,cacheCreation:k?.cacheCreationTokens??0},unpricedCallCount:r?.unpricedCallCount??0,unpricedTokens:r?.unpricedTokens??0,groups:U,trend:C.map(n=>({bucket:n.bucket,costUsd:n.costUsd??0,callCount:n.callCount??0})),...g?{trendStacked:g,trendStackKeys:l}:{}}}async function q(m){let{groupBy:s,groupKey:e,from:c,to:i}=m;if(!R.has(s))throw new Error(`Invalid groupBy: ${s}. Must be one of ${[...R].join(", ")}`);let o=y(),a,u;s==="model"?(a="model = ?",u=e):s==="role"?(a=e==="system"?"role_id IS NULL":"role_id = ?",u=e):s==="source"?(a="source = ?",u=e):(a=`strftime('%Y-%m-%d', datetime(created_at / 1000 + (${Math.trunc(m.tzOffsetMinutes??0)*60}), 'unixepoch')) = ?`,u=e);let p=s==="role"&&e==="system";return o.prepare(`
|
|
63
|
+
SELECT
|
|
64
|
+
call_id AS callId,
|
|
65
|
+
source,
|
|
66
|
+
model,
|
|
67
|
+
SUM(cost_usd) AS costUsd,
|
|
68
|
+
SUM(input_tokens) AS inputTokens,
|
|
69
|
+
SUM(output_tokens) AS outputTokens,
|
|
70
|
+
MIN(priced) AS priced,
|
|
71
|
+
MIN(created_at) AS createdAt,
|
|
72
|
+
MAX(task_id) AS taskId,
|
|
73
|
+
MAX(session_id) AS sessionId,
|
|
74
|
+
MAX(message_id) AS messageId
|
|
75
|
+
FROM llm_costs
|
|
76
|
+
WHERE created_at >= ? AND created_at <= ?
|
|
77
|
+
AND ${a}
|
|
78
|
+
GROUP BY call_id
|
|
79
|
+
ORDER BY createdAt DESC
|
|
80
|
+
`).all(p?[c,i]:[c,i,u]).map(t=>({callId:t.callId,source:t.source,model:t.model,costUsd:t.costUsd??0,inputTokens:t.inputTokens??0,outputTokens:t.outputTokens??0,priced:t.priced??0,createdAt:t.createdAt,...t.taskId?{taskId:t.taskId}:{},...t.sessionId?{sessionId:t.sessionId}:{},...t.messageId?{messageId:t.messageId}:{}}))}import{randomUUID as j}from"crypto";K();w();var x=b("store");async function $(m){let{source:s,recompute:e,callId:c,roleId:i,taskId:o,sessionId:a,messageId:u,numTurns:p,mirror:d=!0}=m,t=c??j(),U=Date.now();if(d)try{if(s==="task"&&o){let r=e.perModel.reduce((l,n)=>l+n.inputTokens,0),f=e.perModel.reduce((l,n)=>l+n.outputTokens,0),T=e.perModel.reduce((l,n)=>l+n.cacheReadTokens,0),C=e.perModel.reduce((l,n)=>l+n.cacheCreationTokens,0),g={input:r,output:f,cacheRead:T,cacheCreation:C};L(o,{costUsd:e.costUsd,tokenUsage:g,...p!==void 0?{numTurns:p}:{},costBreakdown:e})}else if(s==="chat"&&u){let r=e.perModel.reduce((g,l)=>g+l.inputTokens,0),f=e.perModel.reduce((g,l)=>g+l.outputTokens,0),T=JSON.stringify({input:r,output:f}),C=e.perModel[0]?.model??"unknown";D(u,{costUsd:e.costUsd,tokenUsage:T,model:C})}}catch(r){x.warn({err:r,source:s,taskId:o,messageId:u},"recordLlmCost mirror write failed")}if(e.perModel.length===0)return{callId:t,rowsInserted:0};let k=e.perModel.map((r,f)=>({id:`${t}-${f}`,callId:t,source:s,model:r.model,roleId:i,taskId:o,sessionId:a,messageId:u,inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens,cacheCreationTokens:r.cacheCreationTokens,costUsd:r.costUsd,priced:r.priced?1:0,estimated:r.estimated?1:0,sdkTotalCostUsd:e.sdkTotalCostUsd,numTurns:p,createdAt:U}));try{N(k)}catch(r){return x.warn({err:r,callId:t,source:s},"recordLlmCost insertLlmCostRows failed"),{callId:t,rowsInserted:0}}return{callId:t,rowsInserted:k.length}}w();import{query as z}from"@anthropic-ai/claude-agent-sdk";import*as P from"fs/promises";import*as Y from"path";import*as G from"os";var H=b("manager"),v=Y.join(G.homedir(),".adam","llm-eval");async function de(m,s){await P.mkdir(v,{recursive:!0});let e=typeof s=="string"?{systemPrompt:s}:s??{},c={cwd:v,maxTurns:e.maxTurns??3,maxBudgetUsd:e.maxBudgetUsd??.05,persistSession:!1};e.systemPrompt&&(c.systemPrompt=e.systemPrompt),e.model&&(c.model=e.model);let i=z({prompt:m,options:c}),o="",a,u,p;for await(let d of i){let t=d;t.type==="result"&&typeof t.result=="string"&&(o=t.result,typeof t.total_cost_usd=="number"&&(a=t.total_cost_usd),t.modelUsage&&typeof t.modelUsage=="object"&&(u=t.modelUsage),typeof t.num_turns=="number"&&(p=t.num_turns))}if(u)try{let d=E().pricing?.models??{},t=M(u,d,a);$({source:"eval",recompute:t,numTurns:p,mirror:!1})}catch(d){H.warn({err:d},"llm-eval: cost capture failed (non-fatal)")}return o}export{X as a,q as b,$ as c,de as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{e as O}from"./chunk-3MROEPGR.js";import{c as A,h as B}from"./chunk-EZLBMUQD.js";B();import*as c from"fs";import*as a from"path";import{homedir as R}from"os";import{createRequire as _}from"module";var k=A("embedding"),L=512,N=a.join(R(),".adam","models"),T={"bge-small-zh-v1.5":{repo:"Xenova/bge-small-zh-v1.5",onnxFile:"onnx/model.onnx",tokenizerFile:"tokenizer.json",dim:512},"paraphrase-multilingual-MiniLM-L12-v2":{repo:"Xenova/paraphrase-multilingual-MiniLM-L12-v2",onnxFile:"onnx/model.onnx",tokenizerFile:"tokenizer.json",dim:384}},S="bge-small-zh-v1.5",C="https://huggingface.co",y=null,j=null,I=null,M=!1,x=null;function E(){try{return O().memory?.embeddingModel??S}catch{return S}}function D(){let o=E();return T[o]??T[S]}function z(){let o=D(),e=a.join(N,o.repo.replace("/","_"));return c.existsSync(e)||c.mkdirSync(e,{recursive:!0}),e}async function v(o,e){if(c.existsSync(e))return;k.info({file:a.basename(e)},"Downloading model file");let t=await fetch(o);if(!t.ok)throw new Error(`Failed to download ${o}: ${t.status}`);let n=Buffer.from(await t.arrayBuffer());c.mkdirSync(a.dirname(e),{recursive:!0}),c.writeFileSync(e,n),k.info({file:a.basename(e),sizeMb:(n.length/1024/1024).toFixed(1)},"Downloaded")}async function $(){let o=D(),e=z(),t=a.join(e,"model.onnx"),n=a.join(e,"tokenizer.json"),i=`${C}/${o.repo}/resolve/main`;return await v(`${i}/${o.onnxFile}`,t),await v(`${i}/${o.tokenizerFile}`,n),{modelPath:t,tokenizerPath:n}}function P(){let o=_(import.meta.url),e=o.resolve("onnxruntime-web"),t=a.dirname(e),n=o(a.join(t,"ort.all.min.js"));return n.env.wasm.wasmPaths=t+"/",n}async function q(){if(M)throw x??new Error("Embedding session unavailable.");if(y&&j){let t=P(),n=z();return{session:y,ort:t,tokenizerPath:a.join(n,"tokenizer.json")}}if(I||(I=(async()=>{try{let{modelPath:t,tokenizerPath:n}=await $(),i=P();k.info({model:E()},"Loading ONNX inference session");let s=c.readFileSync(t),l=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);y=await i.InferenceSession.create(l,{executionProviders:["wasm"]}),j=JSON.parse(c.readFileSync(n,"utf-8")),k.info({model:E()},"Embedding session ready")}catch(t){throw M=!0,x=t instanceof Error?t:new Error(String(t)),k.warn({err:t},"Embedding session failed to load"),x}})()),await I,!y)throw x??new Error("Embedding session unavailable.");let o=P(),e=z();return{session:y,ort:o,tokenizerPath:a.join(e,"tokenizer.json")}}function X(o){let e=[];for(let t of o){let n=t.codePointAt(0)??0;if(n===0||n===65533)continue;if(new RegExp("^\\p{Cc}|\\p{Cf}","u").test(t)){(t===" "||t===`
|
|
2
2
|
`||t==="\r")&&e.push(" ");continue}n>=19968&&n<=40959||n>=13312&&n<=19903||n>=131072&&n<=173791||n>=173824&&n<=177983||n>=177984&&n<=178207||n>=178208&&n<=183983||n>=63744&&n<=64255||n>=194560&&n<=195103?e.push(" ",t," "):e.push(t)}return e.join("")}function G(o){let e=o.codePointAt(0)??0;return e>=33&&e<=47||e>=58&&e<=64||e>=91&&e<=96||e>=123&&e<=126?!0:new RegExp("^\\p{P}","u").test(o)}function U(o){let e=[];for(let t of o.split(/\s+/)){if(!t)continue;let n=[];for(let i of t)G(i)?(n.length>0&&(e.push(n.join("")),n=[]),e.push(i)):n.push(i);n.length>0&&e.push(n.join(""))}return e}function H(o,e,t){let n=Array.from(o);if(n.length>100)return[t];let i=[],s=0;for(;s<n.length;){let l=n.length,u=!1;for(;l>s;){let h=n.slice(s,l).join(""),d=s===0?h:"##"+h;if(d in e){i.push(e[d]),s=l,u=!0;break}l--}if(!u)return[t]}return i}function J(o,e,t=512){let n=e["[CLS]"]??101,i=e["[SEP]"]??102,s=e["[UNK]"]??100,l=e["[PAD]"]??0,u=X(o),h=U(u),d=[];for(let r of h){let b=H(r,e,s);d.push(...b)}let F=d.slice(0,t-2),w=[n,...F,i],m=w.length,f=new BigInt64Array(t),p=new BigInt64Array(t),g=new BigInt64Array(t);for(let r=0;r<t;r++)r<m?(f[r]=BigInt(w[r]),p[r]=1n):(f[r]=BigInt(l),p[r]=0n),g[r]=0n;return{inputIds:f,attentionMask:p,tokenTypeIds:g}}async function V(o){let{session:e,ort:t}=await q(),n=j.model.vocab,{inputIds:i,attentionMask:s,tokenTypeIds:l}=J(o,n),u=i.length,h={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",s,[1,u]),token_type_ids:new t.Tensor("int64",l,[1,u])},d=await e.run(h),w=(d.last_hidden_state??d[Object.keys(d)[0]]).data,m=L,f=new Float32Array(m),p=0;for(let r=0;r<u;r++)if(s[r]===1n){p++;for(let b=0;b<m;b++)f[b]+=w[r*m+b]}if(p>0)for(let r=0;r<m;r++)f[r]/=p;let g=0;for(let r=0;r<m;r++)g+=f[r]*f[r];if(g=Math.sqrt(g),g>0)for(let r=0;r<m;r++)f[r]/=g;return f}function Z(){if(M)return!1;if(y)return!0;try{let o=z();return c.existsSync(a.join(o,"model.onnx"))&&c.existsSync(a.join(o,"tokenizer.json"))}catch{return!1}}export{L as a,V as b,Z as c};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{n as a,p as o}from"./chunk-WY5BOCQP.js";o();function u(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count,sdkSessionId:t.sdk_session_id??void 0}}function d(t){a().prepare(`
|
|
2
|
+
INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
|
|
3
|
+
title, created_at, last_active_at, archived_at, message_count)
|
|
4
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
+
`).run(t.id,t.status,t.source.type,t.source.channelId??null,t.source.chatId??null,t.title??null,t.createdAt,t.lastActiveAt,t.archivedAt??null,t.messageCount)}function l(t){let s=a().prepare("SELECT * FROM chat_sessions WHERE id = ?").get(t);return s?u(s):void 0}function h(t,e){let s=a(),n=[],i=[];e.status!==void 0&&(n.push("status = ?"),i.push(e.status)),e.title!==void 0&&(n.push("title = ?"),i.push(e.title)),e.lastActiveAt!==void 0&&(n.push("last_active_at = ?"),i.push(e.lastActiveAt)),"archivedAt"in e&&(n.push("archived_at = ?"),i.push(e.archivedAt??null)),e.messageCount!==void 0&&(n.push("message_count = ?"),i.push(e.messageCount)),n.length!==0&&(i.push(t),s.prepare(`UPDATE chat_sessions SET ${n.join(", ")} WHERE id = ?`).run(...i))}function _(t,e=100,s=0){let n=a();return t?n.prepare("SELECT * FROM chat_sessions WHERE status = ? ORDER BY last_active_at DESC LIMIT ? OFFSET ?").all(t,e,s).map(u):n.prepare("SELECT * FROM chat_sessions ORDER BY last_active_at DESC LIMIT ? OFFSET ?").all(e,s).map(u)}function S(t){let s=a().prepare("SELECT * FROM chat_sessions WHERE status = 'active' AND source_type = ? AND source_channel_id IS ? AND source_chat_id IS ? LIMIT 1").get(t.type,t.channelId??null,t.chatId??null);return s?u(s):void 0}function p(t,e){a().prepare("UPDATE chat_sessions SET sdk_session_id = ? WHERE id = ?").run(e,t)}function E(t){a().prepare("DELETE FROM chat_sessions WHERE id = ?").run(t)}export{d as a,l as b,h as c,_ as d,S as e,p as f,E as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as K,c as k,d as L}from"./chunk-
|
|
1
|
+
import{b as K,c as k,d as L}from"./chunk-JYZTIE2J.js";import{a as te,e as re,g as ne}from"./chunk-HRPMRWHD.js";import{a as N,d as be}from"./chunk-OBD4245G.js";import{b as X,h as Q,i as Z}from"./chunk-4JHACUZY.js";import{s as G}from"./chunk-VWX2B6OM.js";import{a as w}from"./chunk-L7JP7DUO.js";import{c as R,h as ee}from"./chunk-6WQFYV3N.js";import{d as Y,r as ve}from"./chunk-BE653A45.js";import{n as S,p as _e}from"./chunk-WY5BOCQP.js";import{c as q,h as Ie}from"./chunk-EZLBMUQD.js";import{c as O,e as J}from"./chunk-5M6IGE5G.js";import{existsSync as Re}from"fs";import{createHash as Ce}from"crypto";import{isAbsolute as Ue}from"path";be();_e();J();import{v4 as Te}from"uuid";function oe(e){return{id:e.id,eventKey:e.event_key,sourceType:e.source_type,sourceId:e.source_id,taskId:e.task_id??void 0,templateId:e.template_id??void 0,templateName:e.template_name??void 0,messageType:e.message_type,viewerKey:e.viewer_key,title:e.title??void 0,contentPreview:e.content_preview,attachments:C(e.attachments_json),targets:C(e.targets_json),firstDeliveredAt:e.first_delivered_at,lastDeliveredAt:e.last_delivered_at,createdAt:e.created_at,traceId:e.trace_id??void 0}}function C(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function de(e){if(!e.viewerKey||e.viewerKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires viewerKey");if(!e.eventKey||e.eventKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires eventKey");if(!e.sourceId||e.sourceId.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires sourceId");let t=S(),r=Date.now(),n=e.deliveredAt??r,a=t.prepare("SELECT * FROM user_visible_events WHERE event_key = ?").get(e.eventKey);if(!a){let d=Te();return t.prepare(`
|
|
2
2
|
INSERT INTO user_visible_events (
|
|
3
3
|
id, event_key, source_type, source_id, task_id, template_id, template_name,
|
|
4
4
|
message_type, viewer_key, title, content_preview, attachments_json,
|
|
@@ -29,4 +29,4 @@ import{b as K,c as k,d as L}from"./chunk-DCTNMUQ5.js";import{a as te,e as re,g a
|
|
|
29
29
|
\u26A0\uFE0F \u56E0 ${n} \u90AE\u7BB1 ${a}MB \u4E0A\u9650\uFF0C\u4EE5\u4E0B\u4EA7\u7269\u672A\u9644\uFF1A
|
|
30
30
|
${s.join(`
|
|
31
31
|
`)}
|
|
32
|
-
`}function Oe(e){return e<1024?`${e} bytes`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}var B=class extends Error{constructor(r,n,a,s,o){super(`OutboundFirstAttachmentExceedsCap: artifactKey=${r} sizeBytes=${n} effectiveSizeBytes=${a} capBytes=${s} recipientDomain=${o}`);this.artifactKey=r;this.sizeBytes=n;this.effectiveSizeBytes=a;this.capBytes=s;this.recipientDomain=o;this.name="OutboundFirstAttachmentExceedsCap"}artifactKey;sizeBytes;effectiveSizeBytes;capBytes;recipientDomain};function xe(e){if(!e)return"";let t=e.lastIndexOf("@");return t<0||t===e.length-1?"":e.slice(t+1).toLowerCase().trim()}function De(e,t){return t.find(r=>r.id===e)?.key??e}function Se(e,t){return t.find(r=>r.artifactId===e)?.filename??e}function fe(e,t,r,n,a){let s=xe(t),o=ee(e,s),d=r.map(l=>({id:l.id,sizeBytes:l.sizeBytes??0,priority:l.priority??void 0,mime:l.mime??void 0})),i=me(d,o);if("firstItemOverflow"in i){let l=i.firstItemOverflow,h=De(l.id,r);return{ok:!1,error:new B(h,l.sizeBytes,Math.floor(l.sizeBytes*x),o,s).message}}let g=new Set(i.included.map(l=>l.id)),y=n.filter(l=>l.artifactId&&g.has(l.artifactId)),_=a;if(i.dropped.length>0){let l=i.dropped.map(h=>({filename:Se(h.id,n),sizeBytes:h.sizeBytes}));_=pe(a,l,o,s)}return{ok:!0,result:{perTargetAttachments:y,perTargetContent:_}}}var E=q("adam"),W=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;_laneTails=new Map;async _acquireLane(t,r){let n=`${t}:${r}`,a=this._laneTails.get(n)??Promise.resolve(),s,o=new Promise(d=>{s=d});return this._laneTails.set(n,o),o.then(()=>{this._laneTails.get(n)===o&&this._laneTails.delete(n)}),await a,s}isRecentlySent(t){return this._recentlySentIds.has(t)}async send(t){let{taskId:r,channelId:n,chatId:a,content:s,messageType:o,platform:d,webhookUrl:i,replyMarkup:g,replyToMessageId:y,quoteExcerpt:_,quoteTitle:l,mediaUrl:h,mediaType:A,attachments:D,dedupDiscriminator:z}=t,I=ge(o),ye=I!=="reply"&&!!r,u;if(ye){u=`${r}:${n??"none"}:${a??"none"}:${I}${z?`:${z}`:""}`;let f=this._dedupCache.get(u);if(f&&Date.now()-f.timestamp<300*1e3)return E.debug({dedupKey:u},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:f.logEntryId}}if(n){let f=Date.now(),v=6e4,p=this._rateLimitWindows.get(n);p||(p=[],this._rateLimitWindows.set(n,p));let P=f-v;for(;p.length>0&&p[0]<P;)p.shift();if(p.length>=60){let M=F();E.warn({channelId:n,count:p.length},"Rate limited, not sending");let b={type:"channel",channelId:n,chatId:a??""};return this._writeOutboundReceipt(t,b,s,"failure"),{success:!1,logEntryId:M,error:"rate_limited"}}p.push(f)}let he=d??(n?R(n)?.platform:void 0)??"unknown",H=i?s:te(s,he,r),c=F(),m={id:c,ruleId:void 0,taskId:r??void 0,status:"pending",target:n&&a?{type:"channel",channelId:n,chatId:a}:i?{type:"webhook",webhookUrl:i}:{type:"channel",channelId:n??"",chatId:a??""},content:H,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:I};K(m),u&&this._dedupCache.set(u,{logEntryId:c,timestamp:Date.now()});try{let f=Be(h);if(f)return k(c,"failed",f),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:f,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:f};if(i){let v=await fetch(i,{method:"POST",body:JSON.stringify({result:s,taskId:r,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(v.ok)return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,s),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,logEntryId:c};{let p=`Webhook returned ${v.status}`;return k(c,"failed",p),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:p,messageType:I}),{success:!1,logEntryId:c,error:p}}}else if(n&&a){let{getChannelManager:v}=await $e(),p=v();if(!p){let T="ChannelManager not available";return k(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:T}}let P={content:H,messageType:I,...g?{replyMarkup:g}:{},...y?{replyToMessageId:y}:{},..._?{quoteExcerpt:_}:{},...l?{quoteTitle:l}:{},...h?{mediaUrl:h}:{},...A?{mediaType:A}:{},...D?{attachments:D}:{}},M=await this._acquireLane(n,a),b;try{b=await p.sendMessage(n,a,P)}finally{M()}if(b===null){let T="Channel adapter send failed (returned null)";return k(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:T}}if(b&&(this._recentlySentIds.add(b),setTimeout(()=>this._recentlySentIds.delete(b),300*1e3)),b?.startsWith("queued-")){let T="queued_not_delivered";return u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"pending",error:T,messageType:I}),{success:!1,messageId:b,logEntryId:c,error:T}}return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,s),this._writeOutboundReceipt(t,m.target,s,"success"),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,messageId:b??void 0,logEntryId:c}}else{let v="No channelId/chatId or webhookUrl provided";return k(c,"failed",v),u&&this._dedupCache.delete(u),{success:!1,logEntryId:c,error:v}}}catch(f){let v=f instanceof Error?f.message:String(f);return k(c,"failed",v),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:v,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:v}}}_writeOutboundReceipt(t,r,n,a){if(r.type!=="channel"||!r.channelId)return;let s=O();if(!s){E.debug({taskId:t.taskId,channelId:r.channelId,outcome:a},"Outbound receipt skipped: no active trace context");return}let o=(t.attachments??[]).map(i=>i.artifactId).filter(i=>typeof i=="string"&&i.length>0),d=t.actorToolName??"OutboundGateway.send";try{Z({traceId:s,taskId:t.taskId,sessionId:t.sessionId,effectCategory:"outbound_message",verb:"send",entityType:"channel_message",target:{channelId:r.channelId,chatId:r.chatId,platform:t.platform},payload:{textChars:n.length,attachmentCount:t.attachments?.length??0,attachmentRefs:o.length>0?o:void 0},actor:{traceId:s,toolName:d,taskId:t.taskId},outcome:a})}catch(i){i instanceof Q?E.warn({errors:i.errors,taskId:t.taskId,channelId:r.channelId},"Outbound receipt validation failed"):E.warn({error:i instanceof Error?i.message:String(i),taskId:t.taskId},"Outbound receipt write failed")}}async redeliverExecutionTo(t){let r=t.includeArtifacts??!0,n=t.messageType??"result_delivery",a=t.dedupDiscriminator??`redelivery:${Date.now()}`,s=r?t.fileArtifacts??le(t.executionId):[],o=s.length>0?ue(s):void 0,d=[];for(let i of t.targets){let g=R(i.channelId);if(!g){d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:"",status:"failed",attachmentCount:0,error:`Channel not found: ${i.channelId}`});continue}let y=o,_=t.content;if(g.platform==="email"&&o&&o.length>0){let h=fe(i.channelId,i.chatId,s,o,t.content);if(!h.ok){let A=F(),D={type:"channel",channelId:i.channelId,chatId:i.chatId??""};K({id:A,ruleId:void 0,taskId:t.executionId,status:"pending",target:D,content:t.content,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:ge(n)}),k(A,"failed",h.error),d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:A,status:"failed",attachmentCount:0,error:h.error});continue}y=h.result.perTargetAttachments,_=h.result.perTargetContent}let l=await this.send({taskId:t.executionId,sessionId:t.sessionId,channelId:i.channelId,chatId:i.chatId,content:_,messageType:n,platform:g.platform,attachments:y,dedupDiscriminator:a,actorToolName:t.actorToolName});d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:l.logEntryId,status:l.success?"delivered":"failed",attachmentCount:y?.length??0,...l.error?{error:l.error}:{}})}return{deliveries:d}}_recordDeliveryLedgerAfterSuccess(t,r,n,a){if(Ve(n,t.taskId))try{let s=Pe(t,r);if(!s){N({source:"delivery_ledger",severity:"warning",sourceId:t.taskId,message:`Skipped user-visible delivery ledger write for ${n}: viewer identity unresolved`});return}let o=Me(t.taskId),d=Ne(a);de({eventKey:`${s}|${o.sourceId}|${n}|${d}`,sourceType:o.sourceType,sourceId:o.sourceId,taskId:t.taskId,templateId:o.templateId,templateName:o.templateName,messageType:n,viewerKey:s,title:o.templateName,contentPreview:a,attachments:(t.attachments??[]).map(Ke),targets:[Le(r)]})}catch(s){let o=s instanceof Error?s.message:String(s);E.warn({error:o,taskId:t.taskId,messageType:n},"User-visible delivery ledger write failed");try{N({source:"delivery_ledger",severity:"error",sourceId:t.taskId,message:o})}catch{}}}};function Ve(e,t){return t?!["reply","assistant_text","user_message","approval","approval_prompt"].includes(e):!1}function Pe(e,t){if(e.viewerKey)return e.viewerKey;if(t.type==="channel"&&t.channelId)return re({type:"channel",channelId:t.channelId,chatId:t.chatId})}function Me(e){let t=X(e);if(!t)return{sourceType:"task",sourceId:e};let r=G(t.templateId);return{sourceType:"template_execution",sourceId:t.id,templateId:t.templateId,templateName:r?.name}}function Ke(e){return{artifactId:e.artifactId,locator:e.locator,filename:e.filename,mimeType:e.mimeType??e.contentType,sizeBytes:e.sizeBytes,purpose:e.purpose,contentHash:e.contentHash}}function Le(e){if(e.type==="webhook")return{type:"webhook",webhookUrl:e.webhookUrl};let t=e.channelId?R(e.channelId):void 0;return{type:"channel",channelId:e.channelId,chatId:e.chatId,label:t?.name}}function Ne(e){return Ce("sha256").update(e).digest("hex")}var V=null;function $e(){return V||(V=import("./channels-WFU4CVGW.js")),V}function At(){V=null}function Be(e){if(!e)return;if(e.includes("://")&&!e.startsWith("file://"))return"mediaUrl must be a local file path";let t=e.startsWith("file://")?new URL(e).pathname:e;if(!Ue(t))return"mediaUrl must be absolute";if(!Re(t))return"mediaUrl file does not exist"}function ge(e){return e==="report"?"status_report":e==="deliver"?"result_delivery":e}var j=null;function Fe(){return j||(j=new W),j}function Et(e){return Fe().isRecentlySent(e)}export{qe as a,le as b,Ae as c,Ee as d,W as e,At as f,Fe as g,Et as h};
|
|
32
|
+
`}function Oe(e){return e<1024?`${e} bytes`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}var B=class extends Error{constructor(r,n,a,s,o){super(`OutboundFirstAttachmentExceedsCap: artifactKey=${r} sizeBytes=${n} effectiveSizeBytes=${a} capBytes=${s} recipientDomain=${o}`);this.artifactKey=r;this.sizeBytes=n;this.effectiveSizeBytes=a;this.capBytes=s;this.recipientDomain=o;this.name="OutboundFirstAttachmentExceedsCap"}artifactKey;sizeBytes;effectiveSizeBytes;capBytes;recipientDomain};function xe(e){if(!e)return"";let t=e.lastIndexOf("@");return t<0||t===e.length-1?"":e.slice(t+1).toLowerCase().trim()}function De(e,t){return t.find(r=>r.id===e)?.key??e}function Se(e,t){return t.find(r=>r.artifactId===e)?.filename??e}function fe(e,t,r,n,a){let s=xe(t),o=ee(e,s),d=r.map(l=>({id:l.id,sizeBytes:l.sizeBytes??0,priority:l.priority??void 0,mime:l.mime??void 0})),i=me(d,o);if("firstItemOverflow"in i){let l=i.firstItemOverflow,h=De(l.id,r);return{ok:!1,error:new B(h,l.sizeBytes,Math.floor(l.sizeBytes*x),o,s).message}}let g=new Set(i.included.map(l=>l.id)),y=n.filter(l=>l.artifactId&&g.has(l.artifactId)),_=a;if(i.dropped.length>0){let l=i.dropped.map(h=>({filename:Se(h.id,n),sizeBytes:h.sizeBytes}));_=pe(a,l,o,s)}return{ok:!0,result:{perTargetAttachments:y,perTargetContent:_}}}var E=q("adam"),W=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;_laneTails=new Map;async _acquireLane(t,r){let n=`${t}:${r}`,a=this._laneTails.get(n)??Promise.resolve(),s,o=new Promise(d=>{s=d});return this._laneTails.set(n,o),o.then(()=>{this._laneTails.get(n)===o&&this._laneTails.delete(n)}),await a,s}isRecentlySent(t){return this._recentlySentIds.has(t)}async send(t){let{taskId:r,channelId:n,chatId:a,content:s,messageType:o,platform:d,webhookUrl:i,replyMarkup:g,replyToMessageId:y,quoteExcerpt:_,quoteTitle:l,mediaUrl:h,mediaType:A,attachments:D,dedupDiscriminator:z}=t,I=ge(o),ye=I!=="reply"&&!!r,u;if(ye){u=`${r}:${n??"none"}:${a??"none"}:${I}${z?`:${z}`:""}`;let f=this._dedupCache.get(u);if(f&&Date.now()-f.timestamp<300*1e3)return E.debug({dedupKey:u},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:f.logEntryId}}if(n){let f=Date.now(),v=6e4,p=this._rateLimitWindows.get(n);p||(p=[],this._rateLimitWindows.set(n,p));let P=f-v;for(;p.length>0&&p[0]<P;)p.shift();if(p.length>=60){let M=F();E.warn({channelId:n,count:p.length},"Rate limited, not sending");let b={type:"channel",channelId:n,chatId:a??""};return this._writeOutboundReceipt(t,b,s,"failure"),{success:!1,logEntryId:M,error:"rate_limited"}}p.push(f)}let he=d??(n?R(n)?.platform:void 0)??"unknown",H=i?s:te(s,he,r),c=F(),m={id:c,ruleId:void 0,taskId:r??void 0,status:"pending",target:n&&a?{type:"channel",channelId:n,chatId:a}:i?{type:"webhook",webhookUrl:i}:{type:"channel",channelId:n??"",chatId:a??""},content:H,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:I};K(m),u&&this._dedupCache.set(u,{logEntryId:c,timestamp:Date.now()});try{let f=Be(h);if(f)return k(c,"failed",f),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:f,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:f};if(i){let v=await fetch(i,{method:"POST",body:JSON.stringify({result:s,taskId:r,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(v.ok)return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,s),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,logEntryId:c};{let p=`Webhook returned ${v.status}`;return k(c,"failed",p),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:p,messageType:I}),{success:!1,logEntryId:c,error:p}}}else if(n&&a){let{getChannelManager:v}=await $e(),p=v();if(!p){let T="ChannelManager not available";return k(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:T}}let P={content:H,messageType:I,...g?{replyMarkup:g}:{},...y?{replyToMessageId:y}:{},..._?{quoteExcerpt:_}:{},...l?{quoteTitle:l}:{},...h?{mediaUrl:h}:{},...A?{mediaType:A}:{},...D?{attachments:D}:{}},M=await this._acquireLane(n,a),b;try{b=await p.sendMessage(n,a,P)}finally{M()}if(b===null){let T="Channel adapter send failed (returned null)";return k(c,"failed",T),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:T,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:T}}if(b&&(this._recentlySentIds.add(b),setTimeout(()=>this._recentlySentIds.delete(b),300*1e3)),b?.startsWith("queued-")){let T="queued_not_delivered";return u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"pending",error:T,messageType:I}),{success:!1,messageId:b,logEntryId:c,error:T}}return L(c),this._recordDeliveryLedgerAfterSuccess(t,m.target,I,s),this._writeOutboundReceipt(t,m.target,s,"success"),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"delivered",messageType:I}),{success:!0,messageId:b??void 0,logEntryId:c}}else{let v="No channelId/chatId or webhookUrl provided";return k(c,"failed",v),u&&this._dedupCache.delete(u),{success:!1,logEntryId:c,error:v}}}catch(f){let v=f instanceof Error?f.message:String(f);return k(c,"failed",v),u&&this._dedupCache.delete(u),w.emit({type:"delivery_status_change",logEntryId:c,taskId:r,target:m.target,status:"failed",error:v,messageType:I}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:c,error:v}}}_writeOutboundReceipt(t,r,n,a){if(r.type!=="channel"||!r.channelId)return;let s=O();if(!s){E.debug({taskId:t.taskId,channelId:r.channelId,outcome:a},"Outbound receipt skipped: no active trace context");return}let o=(t.attachments??[]).map(i=>i.artifactId).filter(i=>typeof i=="string"&&i.length>0),d=t.actorToolName??"OutboundGateway.send";try{Z({traceId:s,taskId:t.taskId,sessionId:t.sessionId,effectCategory:"outbound_message",verb:"send",entityType:"channel_message",target:{channelId:r.channelId,chatId:r.chatId,platform:t.platform},payload:{textChars:n.length,attachmentCount:t.attachments?.length??0,attachmentRefs:o.length>0?o:void 0},actor:{traceId:s,toolName:d,taskId:t.taskId},outcome:a})}catch(i){i instanceof Q?E.warn({errors:i.errors,taskId:t.taskId,channelId:r.channelId},"Outbound receipt validation failed"):E.warn({error:i instanceof Error?i.message:String(i),taskId:t.taskId},"Outbound receipt write failed")}}async redeliverExecutionTo(t){let r=t.includeArtifacts??!0,n=t.messageType??"result_delivery",a=t.dedupDiscriminator??`redelivery:${Date.now()}`,s=r?t.fileArtifacts??le(t.executionId):[],o=s.length>0?ue(s):void 0,d=[];for(let i of t.targets){let g=R(i.channelId);if(!g){d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:"",status:"failed",attachmentCount:0,error:`Channel not found: ${i.channelId}`});continue}let y=o,_=t.content;if(g.platform==="email"&&o&&o.length>0){let h=fe(i.channelId,i.chatId,s,o,t.content);if(!h.ok){let A=F(),D={type:"channel",channelId:i.channelId,chatId:i.chatId??""};K({id:A,ruleId:void 0,taskId:t.executionId,status:"pending",target:D,content:t.content,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:ge(n)}),k(A,"failed",h.error),d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:A,status:"failed",attachmentCount:0,error:h.error});continue}y=h.result.perTargetAttachments,_=h.result.perTargetContent}let l=await this.send({taskId:t.executionId,sessionId:t.sessionId,channelId:i.channelId,chatId:i.chatId,content:_,messageType:n,platform:g.platform,attachments:y,dedupDiscriminator:a,actorToolName:t.actorToolName});d.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:l.logEntryId,status:l.success?"delivered":"failed",attachmentCount:y?.length??0,...l.error?{error:l.error}:{}})}return{deliveries:d}}_recordDeliveryLedgerAfterSuccess(t,r,n,a){if(Ve(n,t.taskId))try{let s=Pe(t,r);if(!s){N({source:"delivery_ledger",severity:"warning",sourceId:t.taskId,message:`Skipped user-visible delivery ledger write for ${n}: viewer identity unresolved`});return}let o=Me(t.taskId),d=Ne(a);de({eventKey:`${s}|${o.sourceId}|${n}|${d}`,sourceType:o.sourceType,sourceId:o.sourceId,taskId:t.taskId,templateId:o.templateId,templateName:o.templateName,messageType:n,viewerKey:s,title:o.templateName,contentPreview:a,attachments:(t.attachments??[]).map(Ke),targets:[Le(r)]})}catch(s){let o=s instanceof Error?s.message:String(s);E.warn({error:o,taskId:t.taskId,messageType:n},"User-visible delivery ledger write failed");try{N({source:"delivery_ledger",severity:"error",sourceId:t.taskId,message:o})}catch{}}}};function Ve(e,t){return t?!["reply","assistant_text","user_message","approval","approval_prompt"].includes(e):!1}function Pe(e,t){if(e.viewerKey)return e.viewerKey;if(t.type==="channel"&&t.channelId)return re({type:"channel",channelId:t.channelId,chatId:t.chatId})}function Me(e){let t=X(e);if(!t)return{sourceType:"task",sourceId:e};let r=G(t.templateId);return{sourceType:"template_execution",sourceId:t.id,templateId:t.templateId,templateName:r?.name}}function Ke(e){return{artifactId:e.artifactId,locator:e.locator,filename:e.filename,mimeType:e.mimeType??e.contentType,sizeBytes:e.sizeBytes,purpose:e.purpose,contentHash:e.contentHash}}function Le(e){if(e.type==="webhook")return{type:"webhook",webhookUrl:e.webhookUrl};let t=e.channelId?R(e.channelId):void 0;return{type:"channel",channelId:e.channelId,chatId:e.chatId,label:t?.name}}function Ne(e){return Ce("sha256").update(e).digest("hex")}var V=null;function $e(){return V||(V=import("./channels-PWDSTYNR.js")),V}function At(){V=null}function Be(e){if(!e)return;if(e.includes("://")&&!e.startsWith("file://"))return"mediaUrl must be a local file path";let t=e.startsWith("file://")?new URL(e).pathname:e;if(!Ue(t))return"mediaUrl must be absolute";if(!Re(t))return"mediaUrl file does not exist"}function ge(e){return e==="report"?"status_report":e==="deliver"?"result_delivery":e}var j=null;function Fe(){return j||(j=new W),j}function Et(e){return Fe().isRecentlySent(e)}export{qe as a,le as b,Ae as c,Ee as d,W as e,At as f,Fe as g,Et as h};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as V}from"./chunk-
|
|
1
|
+
import{d as V}from"./chunk-XAPJJAJQ.js";import{b as L}from"./chunk-Z2APBKIT.js";import{b as N,p as Z}from"./chunk-2A2TXYT3.js";import{n as d,p as k}from"./chunk-WY5BOCQP.js";import{c as F,h as X}from"./chunk-EZLBMUQD.js";Z();k();k();function Ee(e){d().prepare(`
|
|
2
2
|
INSERT INTO audit_violations
|
|
3
3
|
(id, step_task_id, execution_id, role_id, contract_field, layer, severity, message, metadata_json, created_at)
|
|
4
4
|
VALUES
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{D as M,L as D}from"./chunk-
|
|
1
|
+
import{D as M,L as D}from"./chunk-2A2TXYT3.js";import{n as u,p as O}from"./chunk-WY5BOCQP.js";O();D();function E(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function _(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function I(e){u().prepare(`
|
|
2
2
|
INSERT INTO memories (id, role_id, type, content, embedding, keywords,
|
|
3
3
|
importance, source_type, source_task_id, evidence,
|
|
4
4
|
created_at, last_accessed, retrieved_count, tier, superseded_by)
|