@oracle-agent/oracle 0.35.20 → 0.35.22
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/README.md +24 -1
- package/dist/agent-lifecycle.mjs +3 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +23 -17
- package/dist/assets/skills/oracle-mcp-install/SKILL.md +17 -22
- package/dist/assets/skills/protocol-api-key-integration/SKILL.md +14 -11
- package/dist/assets/skills/self-custodial-onchain-execution/SKILL.md +14 -13
- package/dist/assets/skills/trade-loop-circuit-breaker/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +36 -36
- package/dist/bin/oracle-data-mcp.mjs +17 -17
- package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +11 -11
- package/dist/bin/oracle-scan.mjs +15 -15
- package/dist/bin/oracle.mjs +19 -10
- package/dist/cli/commands/chat.mjs +200 -200
- package/dist/cli/commands/context.mjs +16 -0
- package/dist/cli/commands/doctor.mjs +7 -7
- package/dist/cli/commands/eval.mjs +113 -113
- package/dist/cli/commands/extension-policy.mjs +1 -1
- package/dist/cli/commands/governance-prepare.mjs +5 -0
- package/dist/cli/commands/lifecycle.mjs +17 -0
- package/dist/cli/commands/model.mjs +204 -204
- package/dist/cli/commands/portfolio-risk.mjs +4 -0
- package/dist/cli/commands/position-health.mjs +4 -0
- package/dist/cli/commands/quickstart.mjs +5 -5
- package/dist/cli/commands/safety-intelligence.mjs +4 -0
- package/dist/cli/commands/sign.mjs +1 -1
- package/dist/cli/commands/signer.mjs +22 -22
- package/dist/cli/commands/snipe.mjs +4 -4
- package/dist/cli/commands/swap.mjs +13 -13
- package/dist/cli/commands/tax-lots.mjs +4 -0
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/context-graph.mjs +3 -0
- package/dist/data/desk-data.mjs +34 -34
- package/dist/data/providers/lp-destination-discovery.mjs +6 -0
- package/dist/data/providers/lp-liquidity-ranker.mjs +1 -0
- package/dist/index.mjs +50 -48
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/runtime.mjs +1 -1
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/scanner/index.mjs +4 -4
- package/dist/tenant-rbac.mjs +1 -1
- package/dist/workflow-telemetry.mjs +1 -1
- package/package.json +5 -1
- package/public/eval-report.json +2 -2
- package/public/oracle-splash/brand/liquidlaunch.webp +0 -0
- package/public/oracle-splash/brand/markets.webp +0 -0
- package/public/oracle-splash/brand/motion.webp +0 -0
- package/public/oracle-splash/brand/nest.webp +0 -0
- package/public/oracle-splash/brand/outcome.webp +0 -0
- package/public/oracle-splash/brand/silhouette.webp +0 -0
- package/public/oracle-splash/brand/tradexyz.webp +0 -0
- package/public/oracle-splash/index.html +9 -9
- package/server.json +2 -2
- package/dist/assets/skills/oracle-best-execution.md +0 -27
- package/dist/assets/skills/oracle-desk.md +0 -27
- package/dist/assets/skills/oracle-receipts.md +0 -29
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import E from"node:fs";import
|
|
1
|
+
import E from"node:fs";import u from"node:path";import{homedir as g}from"node:os";var _=Object.freeze(["oracle_cli","memory_add","memory_remove","memory_search","skill_load","skill_create","skill_list","cron_add","cron_list","cron_remove","meta_analyze","web_fetch","web_search","file_read","file_write","mcp_list","mcp_call","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","learn_skill","workspace_artifact","research_artifact","portfolio_analyze","tax_lots","position_health","governance_prepare","safety_intelligence","portfolio_risk","trade_lifecycle","signal_score","vault_status","signer_status","signer_execute","signer_disarm","receipt_report","watch_create","watch_list","portfolio_snapshot","vision_analyze","browser_exec","xurl","knowledge_search"]),d="deny",O=256*1024,w=128,l=Object.freeze({version:1,source:"default",defaultDecision:d,allow:_,deny:Object.freeze([])});function s(e){let t=new Set;if(!Array.isArray(e))return t;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||r.length>w||t.add(r)}return t}function x(e){return{allow:!1,reason:e}}function p(e){return{allow:!0,reason:e}}var i="extension-prepare-only",f=Object.freeze(["oracle_cli","memory_search","skill_load","skill_list","web_fetch","web_search","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","research_artifact","portfolio_analyze","tax_lots","position_health","governance_prepare","safety_intelligence","portfolio_risk","trade_lifecycle","signal_score","vault_status","signer_status","receipt_report","watch_list","portfolio_snapshot","vision_analyze","knowledge_search"]),c=new Set(f);function y(e=process.env){return e?.ORACLE_EXECUTION_MODE===i}function m(e,t=process.env){if(!y(t))return p("allowed: normal Oracle execution mode");let o=typeof e?.name=="string"?e.name.trim():"";return!o||!c.has(o)?x(`denied: tool "${o||"unknown"}" is outside extension prepare-only mode`):p(`allowed: tool "${o}" is inside extension prepare-only mode`)}function a(e,t=process.env){if(!y(t))return e;let o=[...s(e?.allow)].filter(n=>c.has(n)),r=new Set([...s(e?.deny),..._.filter(n=>!c.has(n))]);return Object.freeze({version:1,source:`${String(e?.source||"default")}:extension-prepare-only`,defaultDecision:d,allow:Object.freeze(o),deny:Object.freeze([...r])})}function b(e=process.env){let t=e&&e.ORACLE_CONFIG_DIR||u.join(g(),".config","oracle");return u.join(t,"tool-policy.json")}function h(e=process.env){try{let t=b(e),o=E.readFileSync(t,"utf8");if(typeof o!="string"||o.length>O)return a(l,e);let r=JSON.parse(o);if(!r||typeof r!="object"||Array.isArray(r))return a(l,e);let n=Array.isArray(r.allow)?s(r.allow):s(_);return a(Object.freeze({version:1,source:t,defaultDecision:d,allow:Object.freeze([...n]),deny:Object.freeze([...s(r.deny)])}),e)}catch{return a(l,e)}}function A(e=process.env){let t={...e,ORACLE_EXECUTION_MODE:i},o=h(t);return{ok:m({name:"signer_execute",args:{}},t).allow===!1&&!o.allow.includes("signer_execute"),version:1,mode:i,signerExecute:!1,tools:f}}var T={name:"extension-policy",summary:"attest the extension prepare-only tool boundary",group:"system",usage:"oracle extension-policy --json",async run(e){if(e.argv.length!==1||e.argv[0]!=="--json")return process.stderr.write(`oracle extension-policy requires --json
|
|
2
2
|
`),1;let t=A();return process.stdout.write(`${JSON.stringify(t)}
|
|
3
3
|
`),t.ok?0:1}};export{T as default,A as extensionPolicyAttestation};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{wordlists as H}from"ethers";var D=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),F=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],J=new Set([12,15,18,21,24]);function q(e){let o=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return J.has(o.length)&&o.every(t=>H.en.getWordIndex(t)>=0)}var U=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,M=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,K=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function X(e){let o=_(e);return K.has(o)||M.test(o)}var A=class extends Error{constructor(o){super(`action receipt refused: secret-bearing field at ${o}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function _(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function W(e){let o=_(e);return[...D].some(t=>o.includes(t))}function Y(e,o,t){if(typeof o=="string"){if(F.some(n=>n.test(o))||q(o))throw new A(t);if(U.test(o)&&!X(e))throw new A(t)}}function x(e,o="$",t=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Y(t,e,o),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${o}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((r,s)=>x(r,`${o}[${s}]`,t));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${o}`);let n={};for(let r of Object.keys(e).sort()){let s=`${o}.${r}`;if(W(r))throw new A(s);e[r]!==void 0&&(n[r]=x(e[r],s,r))}return n}function u(e){return x(e)}var O=1,y="Unsigned prepare material only; no vote, signature, or broadcast occurred.",Z=Object.freeze(["proposal","delegation","vote"]),Q=Object.freeze(["pending","active","succeeded","queued","executed","defeated","canceled","expired","unknown"]),ee=Object.freeze(["for","against","abstain"]),te=Object.freeze(["delegate","undelegate"]),oe=new Set(Z),re=new Set(Q),ne=new Set(ee),se=new Set(te),ae=/[\u0000-\u001f\u007f]/,ie=new Set(["active"]),ce=new Set(["executed","defeated","canceled","expired"]),R=class extends Error{constructor(o,t="GOVERNANCE_PREPARE_INVALID"){super(`governance prepare: ${o}`),this.name="GovernancePrepareError",this.code=t}};function i(e,o){throw new R(e,o)}function b(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let o of Object.values(e))b(o);Object.freeze(e)}return e}function g(e,o){return(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&i(`${o} must be a plain object`),e}function p(e,o,{optional:t=!1,lower:n=!1}={}){if(e==null&&t)return null;typeof e!="string"&&i(`${o} must be a string`);let r=e.trim();return r||i(`${o} is required`),ae.test(r)&&i(`${o} contains control characters`),r.length>2048&&i(`${o} is too long`),n?r.toLowerCase():r}function f(e,o,{optional:t=!1,positive:n=!1}={}){if(e==null&&t)return null;typeof e=="number"&&i(`${o} must be an exact decimal string or BigInt; Number coercion is refused`,"GOVERNANCE_UNSAFE_NUMBER");let r;typeof e=="bigint"?r=e.toString():typeof e=="string"?r=e.trim():i(`${o} must be an exact decimal string or BigInt`),/^\d+$/.test(r)||i(`${o} must be a non-negative base-10 integer string`);let s=BigInt(r);return n&&s===0n&&i(`${o} must be positive`),s.toString()}function w(e,o){return e==null?null:p(e,o)}function m(e,o){for(let t of o)if(e[t]!==void 0)return e[t]}function pe(e,o="action"){let t=p(e,o,{lower:!0});return oe.has(t)||i(`${o} must be proposal, delegation, or vote`),t}function de(e,o="proposal.state"){e==null&&i(`${o} is required`,"GOVERNANCE_MISSING_PROPOSAL_STATE");let t=p(e,o,{lower:!0});return re.has(t)||i(`${o} is not a recognized proposal state`),t==="unknown"&&i(`${o} is unknown; voting and execution fail closed`,"GOVERNANCE_UNKNOWN_PROPOSAL_STATE"),t}function le(e){let o=p(e,"support",{lower:!0});return ne.has(o)||i("support must be for, against, or abstain"),o}function N(e,{accountRequired:o=!0}={}){return b({chain:p(m(e,["chain","chainId","network"]),"chain",{lower:!0}),governor:p(m(e,["governor","governorAddress","governance","contract"]),"governor"),account:p(m(e,["account","address","owner","voter","from","proposer"]),"account",{optional:!o})})}function $(e,o){let t=w(o.tenantId??e.tenantId,"tenantId");return t?{tenantId:t}:{}}function S(e,o,t="asOf"){return f(o.asOf??e.asOf,t)}function ue(e,o={}){u(e),u(o);let t=g(e,"proposal");g(o,"options");let n=S(t,o),r=N(t,{accountRequired:!1}),s=p(m(t,["proposalId","id"]),"proposalId"),c=de(m(t,["state","status","proposalState"])),a=w(t.title??t.name,"title"),l=w(t.description??t.body??t.summary,"description"),d=w(t.proposer,"proposer"),v=f(t.startBlock??t.start,"startBlock",{optional:!0}),h=f(t.endBlock??t.end,"endBlock",{optional:!0}),E=f(t.forVotes??t.votesFor,"forVotes",{optional:!0}),z=f(t.againstVotes??t.votesAgainst,"againstVotes",{optional:!0}),L=f(t.abstainVotes??t.votesAbstain,"abstainVotes",{optional:!0}),B={recordVersion:O,recordType:"governance-proposal",label:y,asOf:n,chain:r.chain,governor:r.governor,proposalId:s,state:c,votable:ie.has(c),terminal:ce.has(c),title:a,description:l,proposer:d,startBlock:v,endBlock:h,tallies:{forVotes:E,againstVotes:z,abstainVotes:L},occurred:!1,...$(t,o)};return b(B)}function fe(e,o={}){u(e),u(o);let t=g(e,"intent");g(o,"options");let n=S(t,o),r=N(t),s=t.mode??(t.action==="undelegate"?"undelegate":"delegate"),c=p(s,"mode",{lower:!0});se.has(c)||i("mode must be delegate or undelegate");let a=c==="undelegate"?w(t.delegatee??t.to,"delegatee"):p(t.delegatee??t.to,"delegatee"),l=f(m(t,["votingPower","votes","power","balance"]),"votingPower",{positive:!0}),d={recordVersion:O,recordType:"governance-delegation-intent",label:y,action:"delegation",mode:c,asOf:n,chain:r.chain,governor:r.governor,account:r.account,delegatee:c==="undelegate"?a??r.account:a,votingPower:l,occurred:!1,...$(t,o)};return b(d)}function ge(e,o={}){u(e),u(o);let t=g(e,"intent");g(o,"options");let n=S(t,o),r=ue(t.proposal??t,o);r.votable||i(`proposal ${r.proposalId} is ${r.state} and is not votable`,"GOVERNANCE_PROPOSAL_NOT_VOTABLE");let s=N({...t,chain:t.chain??r.chain,governor:t.governor??r.governor}),c=le(t.support??t.choice??t.vote),a=f(m(t,["votingPower","votes","power","weight"]),"votingPower",{positive:!0}),l=w(t.reason??t.comment,"reason"),d={recordVersion:O,recordType:"governance-vote-intent",label:y,action:"vote",asOf:n,chain:s.chain,governor:s.governor,account:s.account,proposalId:r.proposalId,proposalState:r.state,support:c,votingPower:a,reason:l,occurred:!1,voted:!1,signed:!1,broadcast:!1,proposal:r,...$(t,o)};return b(d)}function ye(e,o={}){u(e);let t=g(e,"intent"),n=S(t,o),r=N(t),s=p(t.title??t.name,"title"),c=p(t.description??t.body,"description"),a=t.targets;(!Array.isArray(a)||a.length===0)&&i("targets must be a non-empty array");let l=(t.values??a.map(()=>"0")).map((h,E)=>f(h,`values[${E}]`));l.length!==a.length&&i("values length must match targets");let d=(t.calldatas??t.data??[]).map((h,E)=>p(String(h),`calldatas[${E}]`));d.length!==a.length&&i("calldatas length must match targets");let v=f(m(t,["votingPower","proposalThreshold","threshold"]),"votingPower",{positive:!0});return b({recordVersion:O,recordType:"governance-proposal-intent",label:y,action:"proposal",asOf:n,chain:r.chain,governor:r.governor,account:r.account,title:s,description:c,targets:a.map((h,E)=>p(h,`targets[${E}]`)),values:l,calldatas:d,votingPower:v,occurred:!1,...$(t,o)})}function me(e,o,t){return e==="vote"?ge(o,t):e==="delegation"?fe(o,t):ye(o,t)}function he(e){return e.action==="vote"?[`Unsigned vote preview for proposal ${e.proposalId} on ${e.governor}.`,`Support: ${e.support}. Voting power: ${e.votingPower} (exact base units).`,`Proposal state is ${e.proposalState}. No ballot is submitted.`,y]:e.action==="delegation"?[`Unsigned ${e.mode} preview on ${e.governor}.`,`Account ${e.account} \u2192 ${e.delegatee}. Voting power: ${e.votingPower}.`,"No delegation transaction is signed or broadcast.",y]:[`Unsigned proposal preview on ${e.governor}: ${e.title}.`,`${e.targets.length} target(s). Voting power: ${e.votingPower}.`,"No proposal is submitted.",y]}function I(e={},o={}){u(e),u(o);let t=g(e,"intent");g(o,"options"),o.asOf==null&&t.asOf==null&&i("explicit asOf required","GOVERNANCE_MISSING_ASOF");let n=pe(t.action??t.type??o.action??Ee(t)),r=me(n,{...t,action:n},o);return b({recordVersion:O,recordType:"governance-preview",label:y,action:n,asOf:r.asOf,occurred:!1,voted:!1,signed:!1,broadcast:!1,executionReady:!1,signingReady:!1,broadcastReady:!1,lines:he(r),intent:r,...$(t,o)})}function Ee(e){if(e.support!=null||e.choice!=null||e.proposalId!=null)return"vote";if(e.delegatee!=null||e.mode==="delegate"||e.mode==="undelegate")return"delegation";if(e.targets!=null||e.title!=null)return"proposal";i("action is required")}import P from"node:fs";var V=1024*1024;function C(e=[],o={}){let t=[],n={};for(let r=0;r<e.length;r+=1){let s=e[r];if(!s.startsWith("--")){t.push(s);continue}let c=s.indexOf("="),a=s.slice(2,c===-1?void 0:c),l=o[a];if(!l)throw new TypeError(`unknown option --${a}`);if(Object.hasOwn(n,a))throw new TypeError(`duplicate option --${a}`);if(l==="boolean"){if(c!==-1)throw new TypeError(`option --${a} does not take a value`);n[a]=!0;continue}let d=c===-1?e[++r]:s.slice(c+1);if(d==null||d===""||d.startsWith("--"))throw new TypeError(`option --${a} requires a value`);n[a]=d}return{positionals:t,options:n}}function j(e,o="input"){if(!e)throw new TypeError(`${o} JSON path or - is required`);let t=e==="-"?P.readFileSync(0):P.readFileSync(e);if(t.length>V)throw new RangeError(`${o} exceeds ${V} bytes`);let n;try{n=JSON.parse(t.toString("utf8"))}catch(r){throw new TypeError(`${o} must be valid JSON: ${r.message}`)}if(!n||typeof n!="object"||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype)throw new TypeError(`${o} must be a JSON object`);return n}function k(e,o=process.stdout){o.write(`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function G(e,o=process.stderr){return o.write(`oracle: ${e instanceof Error?e.message:String(e)}
|
|
3
|
+
`),2}var T="oracle governance-prepare <input.json|-> --as-of <integer>",Re={name:"governance-prepare",summary:"preview a supplied governance intent without adapter calldata",group:"prepare",usage:T,async run(e){let o=e.argv??[];if(o.length===0||o.includes("--help")||o.includes("-h"))return process.stdout.write(`${T}
|
|
4
|
+
Semantic preview only. No adapter, calldata, vote, signature, or broadcast.
|
|
5
|
+
`),0;try{let{positionals:t,options:n}=C(o,{"as-of":"value"});if(t.length!==1||!n["as-of"])throw new TypeError(T);let r=j(t[0]);return k({preview:I(r,{asOf:n["as-of"]}),prepared:!1}),0}catch(t){return G(t)}}};export{Re as default};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{readFileSync as We}from"node:fs";import{homedir as $t}from"node:os";import{join as qt}from"node:path";import{createHash as Ke}from"node:crypto";var G=1,B=1,Qe=1,ye="local-owner",me="local-owner",et=Object.freeze(["owner","operator","agent","viewer"]),tt=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),ge=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),nt=Object.freeze(["owner"]),T=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Se=new Set(et),ie=new Set(tt),rt=new Set(Object.values(ge)),Ie=new Set(["user","service","local-owner"]),Ee=new Set(["verified-session","service-credential","desktop-session","owner-arm-token","local-owner"]),Z=/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/,be="tob1",Oe=new WeakSet,ot=new WeakMap,Ne=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),Yt=Object.freeze(Object.fromEntries(Object.entries(Ne).map(([e,n])=>[e,Object.freeze([...n])]))),v=class extends Error{constructor(n,t="invalid-context"){super(n),this.name="TenantContextError",this.code=t}};function re(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function W(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))W(n)}return e}function oe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(oe).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${oe(e[n])}`).join(",")}}`}function _e(e){return Ke("sha256").update(oe(e)).digest("hex")}function he(e,n,t){if(!re(e))throw new v(`${t} must be a plain object`);let r=Object.keys(e).filter(o=>!n.has(o));if(r.length)throw new v(`${t} has unknown fields: ${r.sort().join(", ")}`)}function we(e,n){let t=String(e??"").trim();if(!Z.test(t))throw new v(`${n} is invalid`);return t}function ve(e,n="assignedRoles"){if(!Array.isArray(e)||e.length===0)throw new v(`${n} must contain at least one trusted role`,"missing-role-assignment");let t=[...new Set(e.map(o=>String(o??"").trim()))].sort(),r=t.filter(o=>!Se.has(o));if(r.length)throw new v(`${n} contains unknown roles: ${r.join(", ")}`,"unknown-role");return t}function Te(e,n){return e.length===n.length&&e.every((t,r)=>t===n[r])}function it(e){if(!re(e)||e.schemaVersion!==G||!Z.test(e.tenantId||"")||typeof e.localCompatibility!="boolean")return!1;let n=e.actor;if(!re(n)||n.schemaVersion!==B||!Z.test(n.actorId||"")||!Ie.has(n.actorType)||!Ee.has(n.authSource)||!Array.isArray(n.roles)||n.roles.length===0)return!1;let t=[...new Set(n.roles)].sort();return t.every(r=>Se.has(r))&&Te(t,n.roles)}function st(e,{assignedTenantId:n,assignedActorId:t,assignedActorType:r,assignedAuthSource:o,assignedRoles:i,assignedContextDomains:a=null,localCompatibility:l=!1}={}){let E=e;if(he(E,new Set(["schemaVersion","tenantId","actor","localCompatibility"]),"tenant claims"),E.schemaVersion!=null&&E.schemaVersion!==G)throw new v("unsupported tenant context schema version","unsupported-version");if(![n,t,r,o].every(O=>O!=null))throw new v("trusted tenant and actor identity assignments are required","missing-trusted-identity");let A=E.actor??{};if(he(A,new Set(["schemaVersion","actorId","actorType","authSource","roles"]),"actor claims"),A.schemaVersion!=null&&A.schemaVersion!==B)throw new v("unsupported actor identity schema version","unsupported-version");let x=we(n,"tenantId"),$=we(t,"actorId"),q=String(r).trim(),M=String(o).trim();if(!Ie.has(q))throw new v("actorType is invalid");if(!Ee.has(M))throw new v("authSource is invalid");let D=ve(i);if(!Array.isArray(a)&&a!=null)throw new v("assignedContextDomains must be an array","invalid-domain-assignment");let z=a==null?D.includes("owner")?["*"]:[]:[...new Set(a.map(O=>String(O??"").trim()))].sort();if(z.some(O=>O!=="*"&&!/^[a-z0-9][a-z0-9._-]{0,95}$/.test(O)))throw new v("assignedContextDomains contains an invalid domain","invalid-domain-assignment");if(A.roles!==void 0){let O;try{O=ve(A.roles,"claimed roles")}catch{throw new v("claimed roles do not match the trusted assignment","forged-role")}if(!Te(O,D))throw new v("claimed roles do not match the trusted assignment","forged-role")}if(E.localCompatibility!==void 0&&E.localCompatibility!==l)throw new v("local compatibility may only be set by the trusted boundary","forged-local-compatibility");if([[E.tenantId,x],[A.actorId,$],[A.actorType,q],[A.authSource,M]].some(([O,te])=>O!==void 0&&String(O).trim()!==te))throw new v("claimed identity does not match the trusted assignment","forged-identity");let L=W({schemaVersion:G,tenantId:x,actor:{schemaVersion:B,actorId:$,actorType:q,authSource:M,roles:D},localCompatibility:l===!0});return Oe.add(L),ot.set(L,Object.freeze(z)),L}function ke({authSource:e="local-owner"}={}){if(!new Set(["local-owner","desktop-session","owner-arm-token"]).has(e))throw new v("local owner authSource is invalid");return st({schemaVersion:G,tenantId:ye,actor:{schemaVersion:B,actorId:me,actorType:"local-owner",authSource:e}},{assignedTenantId:ye,assignedActorId:me,assignedActorType:"local-owner",assignedAuthSource:e,assignedRoles:["owner"],localCompatibility:!0})}function J(e){return Oe.has(e)&&it(e)}function at(e){if(!J(e))throw new v("a resolved tenant context is required","unresolved-context");return e}function F(e){return Buffer.from(e,"utf8").toString("base64url")}function ne(e,n){if(!e||!/^[A-Za-z0-9_-]+$/.test(e))throw new v(`${n} binding is invalid`,"invalid-object-binding");let t=Buffer.from(e,"base64url").toString("utf8");if(!t||F(t)!==e)throw new v(`${n} binding is non-canonical`,"invalid-object-binding");return t}function Re(e){let n=String(e??"").trim();if(!n||n.length>256||/[\u0000-\u001f\u007f]/.test(n))throw new v("objectId is invalid","invalid-object-id");return n}function xe(e,n,t){at(e);let r=String(n??"").trim();if(!ie.has(r))throw new v("resource is unknown","unknown-resource");let o=Re(t);return`${be}.${F(e.tenantId)}.${F(r)}.${F(o)}`}function ct(e){let n=String(e??""),t=n.split(".");if(t.length!==4||t[0]!==be)throw new v("tenant-bound object id required","unbound-object");let r=ne(t[1],"tenant"),o=ne(t[2],"resource"),i=ne(t[3],"object");if(!Z.test(r)||!ie.has(o))throw new v("tenant-bound object id is invalid","invalid-object-binding");return Re(i),W({schemaVersion:1,tenantId:r,resource:o,objectId:i,boundId:n})}function dt(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e))return null;let n=Date.parse(e);return Number.isFinite(n)&&new Date(n).toISOString()===e?e:null}function Ae(e){let n={...e,decisionId:_e(e)};return W(n)}function lt({context:e,resource:n,action:t,objectId:r=null,decidedAt:o}={}){let i=dt(o),a={schemaVersion:Qe,recordType:"tenant.access-decision",decidedAt:i,tenantId:J(e)?e.tenantId:null,actor:J(e)?{actorId:e.actor.actorId,actorType:e.actor.actorType,authSource:e.actor.authSource,roles:[...e.actor.roles]}:null,request:{resource:typeof n=="string"?n:null,action:typeof t=="string"?t:null,objectRefHash:r==null?null:_e(String(r))}},l=S=>Ae({...a,allowed:!1,outcome:"deny",reason:S});if(e==null)return l(T.DENY_MISSING_CONTEXT);if(!J(e))return l(T.DENY_INVALID_CONTEXT);if(!i)return l(T.DENY_INVALID_REQUEST);if(!ie.has(n))return l(T.DENY_UNKNOWN_RESOURCE);if(!rt.has(t))return l(T.DENY_UNKNOWN_ACTION);if(r!=null){let S;try{S=ct(r)}catch{return l(T.DENY_UNBOUND_OBJECT)}if(S.tenantId!==e.tenantId)return l(T.DENY_TENANT_MISMATCH);if(S.resource!==n)return l(T.DENY_RESOURCE_MISMATCH)}if(t===ge.approve&&!e.actor.roles.some(A=>nt.includes(A)))return l(T.DENY_ROLE_PERMISSION);let E=`${n}:${t}`,_=e.actor.roles.some(S=>Ne[S]?.includes(E));return Ae({...a,allowed:_,outcome:_?"allow":"deny",reason:_?T.ALLOW_ROLE_PERMISSION:T.DENY_ROLE_PERMISSION})}function Ce(e){let n=lt(e);if(!n.allowed){let t=new v(`tenant access denied: ${n.reason}`,"access-denied");throw t.decision=n,t}return n}import{createHash as ut,randomUUID as ft}from"node:crypto";import{chmodSync as pt,closeSync as K,constants as H,existsSync as se,fsyncSync as ae,lstatSync as De,mkdirSync as je,openSync as ce,readFileSync as yt,renameSync as mt,unlinkSync as de,writeFileSync as ze}from"node:fs";import{dirname as Le,resolve as $e}from"node:path";function le(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(le).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${le(e[n])}`).join(",")}}`}function C(e){return ut("sha256").update(le(e)).digest("hex")}function k(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let n of Object.values(e))k(n)}return e}function ht(e,n,t){let r=$e(e),o=Le(r);if(je(o,{recursive:!0,mode:448}),se(r)){let a=De(r);if(!a.isFile()||a.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file")}let i=`${r}.${ft()}.tmp`;try{ze(i,`${JSON.stringify(n)}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"});let a=ce(i,H.O_RDONLY);try{ae(a)}finally{K(a)}mt(i,r),pt(r,384);let l;try{l=ce(o,H.O_RDONLY),ae(l)}finally{l!==void 0&&K(l)}}catch(a){try{se(i)&&de(i)}catch{}throw a}}function wt(e,n,t){if(!e||typeof e!="object"||Array.isArray(e))throw t("state must be an object","integrity-failed");if(e.schemaVersion!==n||!Array.isArray(e.events))throw t("state schema is invalid","integrity-failed");let r=null;for(let a=0;a<e.events.length;a+=1){let l=e.events[a];if(!l||typeof l!="object"||Array.isArray(l))throw t("event is invalid","integrity-failed");if(l.record&&typeof l.record.recordHash=="string"){let{recordHash:S,...A}=l.record;if(C(A)!==S)throw t("record hash integrity failed; state may be tampered","integrity-failed")}let{eventHash:E,..._}=l;if(l.sequence!==a+1||l.previousEventHash!==r||C(_)!==E)throw t("event hash chain integrity failed; state may be tampered","integrity-failed");r=E}let{stateHash:o,...i}=e;if(C(i)!==o)throw t("state hash integrity failed; state may be tampered","integrity-failed");return e}function X(e,n,t){if(!se(e)){let i={schemaVersion:n,events:[]};return{...i,stateHash:C(i)}}let r=De(e);if(!r.isFile()||r.isSymbolicLink())throw t("state path must be a regular non-symlink file","unsafe-file");if((r.mode&511)!==384)throw t("state file permissions must be 0600","unsafe-permissions");let o;try{o=JSON.parse(yt(e,"utf8"))}catch{throw t("state JSON is malformed","integrity-failed")}return wt(o,n,t)}function vt(e,n,t){let r=`${e}.lock`,o;try{o=ce(r,H.O_CREAT|H.O_EXCL|H.O_WRONLY,384),ze(o,`${JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})}
|
|
3
|
+
`,"utf8"),ae(o)}catch(i){if(o!==void 0){K(o);try{de(r)}catch{}}throw i?.code==="EEXIST"?n("state is locked by another writer","state-locked"):i}try{return t()}finally{try{K(o)}finally{de(r)}}}function qe({path:e,schemaVersion:n,fail:t}){if(typeof e!="string"||e.length<1||e.length>4096)throw t("bounded state path required","invalid-path");if(typeof t!="function")throw new TypeError("fail factory required");let r=$e(e);je(Le(r),{recursive:!0,mode:448});let o=X(r,n,t);function i(){let l={schemaVersion:n,events:o.events};o={...l,stateHash:C(l)},ht(r,o,t)}function a({tenantId:l,recordType:E,recordId:_,operation:S,occurredAt:A,record:x,expectedRecordHash:$=null}){return vt(r,t,()=>{if(o=X(r,n,t),(([...o.events].reverse().find(U=>U.record?.boundId===x?.boundId)??null)?.record?.recordHash??null)!==$)throw t("record changed concurrently; retry from current state","state-conflict");if(x&&typeof x.recordHash=="string"){let{recordHash:U,...L}=x;if(C(L)!==U)throw t("record hash is inconsistent","integrity-failed")}let D={sequence:o.events.length+1,previousEventHash:o.events.at(-1)?.eventHash??null,tenantId:l,recordType:E,recordId:_,operation:S,occurredAt:A,record:x},z=k({...D,eventHash:C(D)});return o={...o,events:[...o.events,z]},i(),z})}return Object.freeze({append:a,events:()=>(o=X(r,n,t),o.events.map(l=>structuredClone(l))),verify:()=>{try{return o=X(r,n,t),{ok:!0,count:o.events.length,stateHash:o.stateHash}}catch(l){return{ok:!1,reason:l?.code||"integrity-failed"}}},path:r})}var At=Object.freeze([/(?:^|\s)Bearer\s+\S+/i,/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,/\b(?:sk-|xprv|gh[pousr]_|github_pat_|AKIA|ASIA)[A-Za-z0-9_/-]{12,}\b/i,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/\b(?:0x)?[0-9a-f]{64}\b/i,/(?<![1-9A-HJ-NP-Za-km-z])[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}(?![1-9A-HJ-NP-Za-km-z])/,/(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{64,88}(?![1-9A-HJ-NP-Za-km-z])/]),gt=new Set(["apikey","key","token","accesstoken","secret","password","passwd","auth","authorization","bearer","signertoken","credential","credentials","clientsecret","privatekey","xapikey","accesskey","refreshtoken"]),St=Object.freeze(["apikey","accesskey","privatekey","clientsecret","accesstoken","refreshtoken","signertoken","credential","password","passwd","authorization","bearer","secret","token"]);function It(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toLowerCase()}function Et(e){let n;try{n=new URL(e)}catch{return!1}if(n.username||n.password)return!0;for(let t of n.searchParams.keys()){let r=It(t);if(gt.has(r)||St.some(o=>r.includes(o)))return!0}return!1}function Me(e){try{let n=decodeURIComponent(e);return n===e?null:n}catch{return null}}var bt=/[a-z][a-z0-9+.-]{1,15}(?::\/\/|%3a%2f%2f)\S+/gi;function Ot(e){return e.replace(/[),.;:!?'"\]}]+$/,"")}function Nt(e){let n=e.match(bt)||[];for(let t of n){let r=Ot(t),o=Me(r),i=o?Me(o):null;for(let a of[r,o,i])if(a&&Et(a))return!0}return!1}function ue(e){return typeof e!="string"||e.length===0?!1:At.some(n=>n.test(e))?!0:Nt(e)}var _t="oracle.agent-lifecycle/1",Tt="oracle.agent-lifecycle-state/1",kt=Object.freeze(["agent","tool","workflow","credential"]),Rt=Object.freeze(["active","quarantined","retired","pending_reactivation"]),Q=Object.freeze({inactivityMs:2160*60*60*1e3,maxEvalAgeMs:720*60*60*1e3}),xt=50,Ue=100,Ye=new Set(kt),Ge=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/,Ct=512,Pe=300*1e3,Dt=["authorization","apikey","accesskey","cookie","password","passphrase","secret","token","privatekey","seed","mnemonic","keystore","signature"],fe=class extends Error{constructor(n,t="invalid-agent-lifecycle"){super(`agent-lifecycle: ${n}`),this.name="AgentLifecycleError",this.code=t}};function f(e,n){return new fe(e,n)}function j(e,n){if(typeof e!="string")throw f(`${n} must be an ISO timestamp`,"invalid-time");let t=Date.parse(e);if(!Number.isFinite(t)||new Date(t).toISOString()!==e)throw f(`${n} must be an ISO timestamp`,"invalid-time");return e}function b(e,n){let t=String(e??"").trim();if(ue(t))throw f(`${n} contains secret-shaped material`,"secret-material");if(!Ge.test(t))throw f(`${n} is invalid`,"invalid-id");return t}function V(e,n,{required:t=!0}={}){let r=String(e??"").trim();if(t&&!r||r.length>Ct||/[\u0000-\u001f\u007f]/.test(r)||ue(r))throw f(`${n} is invalid or contains secret-shaped material`,"invalid-text");return r}function jt(e={}){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw f("metadata must be a plain object","invalid-metadata");let n=Object.keys(e).sort();if(n.length>24)throw f("metadata field limit exceeded","metadata-limit");let t={};for(let r of n){if(!/^[A-Za-z][A-Za-z0-9_.-]{0,47}$/.test(r))throw f(`metadata key ${r} is invalid`,"invalid-metadata");let o=r.replace(/[^a-z0-9]/gi,"").toLowerCase();if(Dt.some(a=>o.includes(a)))throw f(`metadata key ${r} is forbidden because it may contain a secret`,"secret-material");let i=e[r];if(typeof i=="string")t[r]=V(i,`metadata.${r}`,{required:!1});else if(typeof i=="boolean"||i===null)t[r]=i;else if(typeof i=="number"&&Number.isFinite(i))t[r]=i;else throw f(`metadata.${r} must be a scalar`,"invalid-metadata")}return t}function He(e=[]){if(!Array.isArray(e)||e.length>32)throw f("credentialRefs must be a bounded array","invalid-credentials");let n=new Set;return e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))throw f("credential reference is invalid","invalid-credentials");let r=Object.keys(t).filter(i=>!["ref","expiresAt"].includes(i));if(r.length)throw f(`credential reference has unknown fields: ${r.sort().join(", ")}`,"invalid-credentials");let o=b(V(t.ref,"credential ref"),"credential ref");if(n.has(o))throw f("credential references must be unique","invalid-credentials");return n.add(o),{ref:o,expiresAt:j(t.expiresAt,"credential expiresAt")}}).sort((t,r)=>t.ref.localeCompare(r.ref))}function zt(e={}){let n=e.inactivityMs??Q.inactivityMs,t=e.maxEvalAgeMs??Q.maxEvalAgeMs;if(!Number.isSafeInteger(n)||n<1440*60*1e3||n>3660*24*60*60*1e3)throw f("policy.inactivityMs is invalid","invalid-policy");if(!Number.isSafeInteger(t)||t<1||t>3660*24*60*60*1e3)throw f("policy.maxEvalAgeMs is invalid","invalid-policy");return{inactivityMs:n,maxEvalAgeMs:t}}function Ve(e){let n=e==null||e===""?xt:Number(e);if(!Number.isSafeInteger(n)||n<1||n>Ue)throw f(`limit must be an integer from 1 to ${Ue}`,"invalid-limit");return n}function Be(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Lt(e,n){if(typeof e!="string"||e.length<1||e.length>2048||!/^[A-Za-z0-9_-]+$/.test(e))throw f("cursor is invalid","invalid-cursor");let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw f("cursor is invalid","invalid-cursor")}let r=t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort():[],o=["after","checkedAt","entityType","kind","sequence","status","tenantId","version"].sort();if(JSON.stringify(r)!==JSON.stringify(o)||t.version!==1||t.kind!==n.kind||t.tenantId!==n.tenantId||t.entityType!==n.entityType||t.status!==n.status||!Number.isSafeInteger(t.sequence)||t.sequence<0||t.sequence>n.headSequence||typeof t.after!="string"||!Ge.test(t.after)||Be(t)!==e)throw f("cursor does not match this lifecycle query","invalid-cursor");try{j(t.checkedAt,"cursor checkedAt")}catch{throw f("cursor is invalid","invalid-cursor")}if(Date.parse(t.checkedAt)>Date.parse(n.authorizedAt))throw f("cursor timestamp is in the future","invalid-cursor");return t}function Je(e){let n=new Map;for(let t of e)n.set(`${t.tenantId}\0${t.recordId}`,t.record);return n}function Fe(e,{at:n=new Date().toISOString(),inactivityMs:t=Q.inactivityMs,maxEvalAgeMs:r=Q.maxEvalAgeMs}={}){let o=j(n,"at"),i=Date.parse(o),a=[];if(e.latestEval&&(e.latestEval.passed===!1||e.latestEval.score<e.latestEval.threshold)&&a.push("eval-below-threshold"),e.latestEval?.passed===!0&&i-Date.parse(e.latestEval.evaluatedAt)>r&&a.push("eval-stale"),(e.credentialRefs||[]).some(E=>Date.parse(E.expiresAt)<=i)&&a.push("credential-expired"),e.entityType==="credential"&&e.expiresAt&&Date.parse(e.expiresAt)<=i&&a.push("credential-expired"),a.length)return k({status:"quarantined",reasons:a.sort(),evaluatedAt:o});let l=e.lastUsedAt??e.registeredAt;return i-Date.parse(l)>=t?k({status:"retired",reasons:["inactive"],evaluatedAt:o}):k({status:"active",reasons:[],evaluatedAt:o})}function Ze({path:e,now:n=()=>new Date().toISOString(),policy:t={}}={}){let r=zt(t),o=qe({path:e,schemaVersion:Tt,fail:f});function i(){return j(n(),"now")}function a(s,y,p=i()){return Ce({context:s,resource:"lifecycle",action:y,decidedAt:p})}function l(s,y){return Je(o.events()).get(`${s.tenantId}\0${y}`)??null}function E({context:s,kind:y,cursor:p,checkedAt:d,entityType:u=null,status:c=null}){let m=o.events(),h=m.at(-1)?.sequence??0,g=p==null?null:Lt(p,{kind:y,tenantId:s.tenantId,entityType:u,status:c,headSequence:h,authorizedAt:d}),w=g?.sequence??h,I=g?.checkedAt??d,Y=g?.after??null;return{records:[...Je(m.filter(N=>N.sequence<=w)).values()].filter(N=>N.tenantId===s.tenantId).filter(N=>u==null||N.entityType===u).sort((N,P)=>N.entityId.localeCompare(P.entityId)).filter(N=>Y==null||N.entityId.localeCompare(Y)>0),sequence:w,checkedAt:I}}function _({items:s,hasMore:y,lastEntityId:p,kind:d,context:u,entityType:c=null,status:m=null,sequence:h,checkedAt:g}){let w=y?Be({version:1,kind:d,tenantId:u.tenantId,entityType:c,status:m,sequence:h,checkedAt:g,after:p}):null;return k({items:s,nextCursor:w,sequence:h})}function S(s,y){let p=Fe(s,{at:y,...r}),d=["quarantined","retired","pending_reactivation"].includes(s.status)&&p.status==="active",u=d?s.status:p.status,c=d?[...s.reasons||[]]:[...p.reasons];return k({...structuredClone(s),status:u,reasons:c,evaluatedAt:p.evaluatedAt})}function A(s,y,p,d=i()){let u=p.recordHash??null,c={...p};delete c.recordHash;let m=k({...c,recordHash:C(c)});return o.append({tenantId:s.tenantId,recordType:"lifecycle",recordId:m.entityId,operation:y,occurredAt:d,record:m,expectedRecordHash:u}),m}function x({context:s,input:y}={}){let p=i();a(s,"create",p);let d=b(y?.entityId,"entityId");if(l(s,d))throw f("entity already exists","duplicate-entity");let u=String(y?.entityType??"").trim();if(!Ye.has(u))throw f("entityType is invalid","invalid-entity-type");let c=He(y?.credentialRefs);if(u==="credential"&&c.length)throw f("credential entities cannot contain credentialRefs","invalid-credentials");let m=u==="credential"?j(y?.expiresAt,"expiresAt"):null,h=c.some(I=>Date.parse(I.expiresAt)<=Date.parse(p))||m!=null&&Date.parse(m)<=Date.parse(p),g=b(y?.ownerActorId,"ownerActorId"),w=b(s.actor.actorId,"registering actorId");if(!s.actor.roles.includes("owner")&&g!==w)throw f("only an owner may assign lifecycle ownership to another actor","owner-assignment-required");return A(s,"register",{schemaVersion:_t,tenantId:s.tenantId,boundId:xe(s,"lifecycle",d),entityId:d,entityType:u,label:V(y?.label,"label"),ownerActorId:g,registeredBy:w,credentialRefs:c,expiresAt:m,metadata:jt(y?.metadata),status:h?"quarantined":"active",reasons:h?["credential-expired"]:[],registeredAt:p,updatedAt:p,lastUsedAt:null,latestEval:null,reactivation:null,revision:1},p)}function $({context:s,entityId:y}={}){let p=i();a(s,"read",p);let d=l(s,b(y,"entityId"));return d?S(d,p):null}function q({context:s,entityType:y=null,status:p=null,limit:d=null,cursor:u=null}={}){let c=i();if(a(s,"read",c),y!=null&&!Ye.has(y))throw f("entityType is invalid","invalid-entity-type");if(p!=null&&!Rt.includes(p))throw f("status is invalid","invalid-status");let m=Ve(d),h=E({context:s,kind:"list",cursor:u,checkedAt:c,entityType:y,status:p}),g=h.records.map(I=>S(I,h.checkedAt)).filter(I=>p==null||I.status===p),w=g.slice(0,m).map(I=>k(structuredClone(I)));return _({items:w,hasMore:g.length>m,lastEntityId:w.at(-1)?.entityId??null,kind:"list",context:s,entityType:y,status:p,sequence:h.sequence,checkedAt:h.checkedAt})}function M({context:s,entityId:y,outcome:p,occurredAt:d=null}={}){let u=i();a(s,"update",u);let c=l(s,b(y,"entityId"));if(!c)throw f("entity not found","not-found");let m=new Set(["succeeded","failed","denied","cancelled","skipped"]),h=String(p??"").trim();if(!m.has(h))throw f("usage outcome is invalid","invalid-outcome");let g=j(d??u,"occurredAt"),w=S(c,u);if(w.status!=="active")throw(w.status!==c.status||JSON.stringify(w.reasons)!==JSON.stringify(c.reasons||[]))&&A(s,"usage-denied",{...c,status:w.status,reasons:[...w.reasons],evaluatedAt:w.evaluatedAt,updatedAt:u,revision:c.revision+1},u),f(`entity is not active: ${w.status}`,"entity-not-active");if(Date.parse(g)>Date.parse(u)+Pe)throw f("occurredAt is too far in the future","future-usage");if(c.lastUsedAt&&Date.parse(g)<Date.parse(c.lastUsedAt))throw f("occurredAt must be monotonic","non-monotonic-usage");return A(s,"usage",{...c,lastUsedAt:g,lastOutcome:h,updatedAt:u,revision:c.revision+1},u)}function D({context:s,entityId:y,suite:p,score:d,threshold:u,evaluatedAt:c=null}={}){let m=i();a(s,"update",m);let h=l(s,b(y,"entityId"));if(!h)throw f("entity not found","not-found");let g=Number(d),w=Number(u);if(![g,w].every(P=>Number.isFinite(P)&&P>=0&&P<=1))throw f("eval score and threshold must be from 0 to 1","invalid-eval");let I=j(c??m,"evaluatedAt");if(Date.parse(I)>Date.parse(m)+Pe)throw f("evaluatedAt is too far in the future","future-eval");if(h.latestEval&&Date.parse(I)<Date.parse(h.latestEval.evaluatedAt))throw f("evaluatedAt must be monotonic","non-monotonic-eval");let Y={suite:b(p,"eval suite"),score:g,threshold:w,evaluatedAt:I,evaluatorActorId:b(s.actor.actorId,"evaluatorActorId"),passed:g>=w},pe={...h,latestEval:Y},N=S(pe,m);return A(s,"eval",{...h,latestEval:Y,status:N.status,reasons:[...N.reasons],evaluatedAt:N.evaluatedAt,updatedAt:m,revision:h.revision+1},m)}function z({context:s,entityId:y,refs:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType==="credential")throw f("credential entities use updateCredentialExpiry","invalid-credentials");let m=He(p),h=m.some(g=>Date.parse(g.expiresAt)<=Date.parse(d));return A(s,"credential-refs",{...c,credentialRefs:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function U({context:s,entityId:y,expiresAt:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(c.entityType!=="credential")throw f("entity is not a credential","invalid-entity-type");let m=j(p,"expiresAt"),h=Date.parse(m)<=Date.parse(d);return A(s,"credential-expiry",{...c,expiresAt:m,status:h?"quarantined":c.status,reasons:h?[...new Set([...c.reasons||[],"credential-expired"])].sort():c.reasons,updatedAt:d,revision:c.revision+1},d)}function L({context:s,limit:y=null,cursor:p=null}={}){let d=i();a(s,"manage",d);let u=Ve(y),c=E({context:s,kind:"sweep",cursor:p,checkedAt:d}),m=c.checkedAt,h=[],g=c.records.slice(0,u);for(let w of g){let I=S(w,m);(I.status!==w.status||JSON.stringify(I.reasons)!==JSON.stringify(w.reasons||[]))&&A(s,"sweep",{...w,status:I.status,reasons:[...I.reasons],evaluatedAt:m,updatedAt:m,revision:w.revision+1},m),h.push({entityId:w.entityId,status:I.status,reasons:[...I.reasons],evaluatedAt:m})}return _({items:h.map(w=>k(w)),hasMore:c.records.length>u,lastEntityId:g.at(-1)?.entityId??null,kind:"sweep",context:s,sequence:c.sequence,checkedAt:m})}function O({context:s,entityId:y,reason:p}={}){let d=i();a(s,"update",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");let c=S(u,d);if(!["quarantined","retired"].includes(c.status))throw f("only quarantined or retired entities may request reactivation","invalid-transition");return A(s,"reactivation-requested",{...c,status:"pending_reactivation",reactivation:{requestedAt:d,requestedBy:b(s.actor.actorId,"requestedBy"),reason:V(p,"reactivation reason"),reviewedAt:null,reviewedBy:null,review:null},updatedAt:d,revision:c.revision+1},d)}function te({context:s,entityId:y,review:p}={}){let d=i();a(s,"approve",d);let u=l(s,b(y,"entityId"));if(!u)throw f("entity not found","not-found");if(u.status!=="pending_reactivation"||!u.reactivation)throw f("reactivation request is required","invalid-transition");let c=Fe(u,{at:d,...r});if(c.status!=="active")throw f(`reactivation remediation incomplete: ${c.reasons.join(", ")}`,"remediation-required");let m=d;return A(s,"reactivation-approved",{...u,status:"active",reasons:[],reactivation:{...u.reactivation,reviewedAt:m,reviewedBy:b(s.actor.actorId,"reviewedBy"),review:V(p,"reactivation review")},updatedAt:m,revision:u.revision+1},d)}return Object.freeze({register:x,get:$,list:q,recordUsage:M,recordEval:D,updateCredentialRefs:z,updateCredentialExpiry:U,sweep:L,requestReactivation:O,approveReactivation:te,verify:o.verify})}var ee=`oracle lifecycle <command> [options]
|
|
4
|
+
register <input.json|->
|
|
5
|
+
get --id ID
|
|
6
|
+
list [--type agent|tool|workflow|credential] [--status STATUS] [--limit N] [--cursor CURSOR]
|
|
7
|
+
usage --id ID --outcome OUTCOME [--occurred-at ISO]
|
|
8
|
+
eval --id ID --suite NAME --score N --threshold N [--evaluated-at ISO]
|
|
9
|
+
credentials --id ID <refs.json|->
|
|
10
|
+
credential-expiry --id ID --expires-at ISO
|
|
11
|
+
sweep [--limit N] [--cursor CURSOR]
|
|
12
|
+
reactivate-request --id ID --reason TEXT
|
|
13
|
+
reactivate-approve --id ID --review TEXT
|
|
14
|
+
verify
|
|
15
|
+
Options: --store PATH --inactivity-days N --limit N --cursor CURSOR`;function Mt(e){let n=[],t={},r=new Set(["store","id","type","status","outcome","occurred-at","suite","score","threshold","evaluated-at","expires-at","reason","review","inactivity-days","limit","cursor"]);for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--")){n.push(i);continue}let a=i.slice(2);if(!r.has(a)||e[o+1]==null)throw new TypeError(ee);t[a]=e[++o]}return{positionals:n,options:t}}function Xe(e){let n=e==="-"?We(0,"utf8"):We(e,"utf8");return JSON.parse(n)}function R(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
16
|
+
`)}var rn={name:"lifecycle",summary:"inventory and govern agent, tool, workflow, and credential lifecycles",group:"system",usage:ee,async run(e){let{positionals:n,options:t}=Mt(e.argv??[]),r=n[0];if(!r||["help","--help","-h"].includes(r))return process.stdout.write(`${ee}
|
|
17
|
+
`),0;let o=t["inactivity-days"]==null?90:Number(t["inactivity-days"]),i=Ze({path:t.store||qt($t(),".config","oracle","agent-lifecycle.json"),policy:{inactivityMs:o*24*60*60*1e3}}),a=ke();if(r==="register")R(i.register({context:a,input:Xe(n[1])}));else if(r==="get")R(i.get({context:a,entityId:t.id}));else if(r==="list")R(i.list({context:a,entityType:t.type||null,status:t.status||null,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="usage")R(i.recordUsage({context:a,entityId:t.id,outcome:t.outcome,occurredAt:t["occurred-at"]}));else if(r==="eval")R(i.recordEval({context:a,entityId:t.id,suite:t.suite,score:Number(t.score),threshold:Number(t.threshold),evaluatedAt:t["evaluated-at"]}));else if(r==="credentials")R(i.updateCredentialRefs({context:a,entityId:t.id,refs:Xe(n[1])}));else if(r==="credential-expiry")R(i.updateCredentialExpiry({context:a,entityId:t.id,expiresAt:t["expires-at"]}));else if(r==="sweep")R(i.sweep({context:a,limit:t.limit==null?void 0:Number(t.limit),cursor:t.cursor}));else if(r==="reactivate-request")R(i.requestReactivation({context:a,entityId:t.id,reason:t.reason}));else if(r==="reactivate-approve")R(i.approveReactivation({context:a,entityId:t.id,review:t.review}));else if(r==="verify")R(i.verify());else throw new TypeError(ee);return 0}};export{rn as default};
|