eve 0.54.2 → 0.54.3
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/CHANGELOG.md +9 -0
- package/dist/src/cli/dev/tui/setup-commands.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +3 -1
- package/dist/src/compiled/just-secrets/LICENSE +21 -0
- package/dist/src/compiled/just-secrets/index.d.ts +20 -0
- package/dist/src/compiled/just-secrets/index.js +2 -0
- package/dist/src/compiled/just-secrets/windows.ps1 +138 -0
- package/dist/src/compiler/extension-compatibility.d.ts +6 -6
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/normalize-manifest-helpers.d.ts +2 -1
- package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/resolve-workspace-subagent.d.ts +13 -0
- package/dist/src/compiler/resolve-workspace-subagent.js +1 -0
- package/dist/src/execution/durable-session-migrations/snapshot.d.ts +0 -16
- package/dist/src/execution/durable-session-migrations/snapshot.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/messages.d.ts +1 -1
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/step-hooks.d.ts +16 -10
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/routes/index.d.ts +6 -0
- package/dist/src/internal/nitro/routes/index.js +7 -7
- package/dist/src/internal/vercel/assemble-eve-services.js +1 -1
- package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
- package/dist/src/internal/vercel/build-multi-agent-landing-page.d.ts +3 -0
- package/dist/src/internal/vercel/build-multi-agent-landing-page.js +1 -0
- package/dist/src/internal/vercel/eve-service-contribution.d.ts +4 -0
- package/dist/src/internal/vercel/eve-service-contribution.js +1 -1
- package/dist/src/public/definitions/workspace-agent.d.ts +25 -0
- package/dist/src/public/definitions/workspace-agent.js +1 -0
- package/dist/src/public/index.d.ts +1 -0
- package/dist/src/public/index.js +1 -1
- package/dist/src/public/models/openai/chatgpt/credential-store.d.ts +22 -4
- package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
- package/dist/src/public/models/openai/chatgpt/oauth.d.ts +6 -4
- package/dist/src/public/models/openai/chatgpt/token-broker.js +1 -1
- package/dist/src/setup/flows/chatgpt-auth.js +1 -1
- package/dist/src/setup/flows/model.d.ts +0 -2
- package/dist/src/setup/flows/model.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/docs/guides/instrumentation.md +9 -0
- package/docs/reference/typescript-api.md +7 -3
- package/docs/subagents/index.mdx +31 -0
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# eve
|
|
2
2
|
|
|
3
|
+
## 0.54.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 6cb22a4: Store ChatGPT refresh credentials in the OS credential store using vendored just-secrets, with access tokens kept in memory. Existing users must sign in once through eve; a successful save removes the old plaintext session file. ChatGPT sign-in now remains inside the model setup panel while browser authentication is in progress.
|
|
8
|
+
- c5bb66f: fix(eve): align internal AI SDK step lifecycle hooks with the current `onStepStart` and `onStepEnd` callback names
|
|
9
|
+
- fb6750f: Resume sessions whose history predates user-message provenance instead of failing with a missing-kind error. Existing unclassified messages retain their content and are marked `legacy.unknown`, without treating unknown framework input as a new human request after compaction.
|
|
10
|
+
- eaf8895: Add `defineWorkspaceAgent()` for delegating to a workspace peer by name. It selects Vercel routing and OIDC automatically on Vercel, accepts explicit transport overrides elsewhere, and uses the peer agent's description by default.
|
|
11
|
+
|
|
3
12
|
## 0.54.2
|
|
4
13
|
|
|
5
14
|
### Patch Changes
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{formatRegistrySessionResult,registryItemProgress,registryResultTone}from"./registry-result-message.js";import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{RegistryFlowFailedError,runRegistryFlow}from"#setup/flows/registry.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},add:{title:`Add to your agent`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function muteableRenderer(e,t,n){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readModelEditor:n=>t()?Promise.resolve(void 0):e.readModelEditor(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setNavigation:n=>{t()||e.setNavigation?.(n)},setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},replaceContent:n=>{t()||e.replaceContent?.(n)},renderOutput:n=>{t()||e.renderOutput(n)},withInheritedStdio:t=>e.withInheritedStdio(t),withExclusiveTerminal:e=>n?.(e)??e()}}async function runTuiSetupCommand(e){let{command:t}=e,n=!1,r=new AbortController,i=muteableRenderer(e.renderer,()=>n,e.withExclusiveTerminal),a=(e.createPrompter??createTuiPrompter)(i),cancelActiveRegistryItem,runRegistryItem=async e=>{let t=new AbortController;cancelActiveRegistryItem=()=>t.abort(new WizardCancelledError);try{return await e(AbortSignal.any([r.signal,t.signal]))}finally{cancelActiveRegistryItem=void 0}},o=e.renderer.waitForInterrupt(),s=executeSetupCommand(e,a,i,r.signal,runRegistryItem),c=s.then(e=>({kind:`outcome`,value:e}));try{for(;;){let i=!1;try{let e=await Promise.race([c,o.promise.then(e=>({kind:`interrupt`,interrupt:e}))]);if(e.kind===`outcome`)return e.value;if(t===`add`&&e.interrupt===`escape`&&cancelActiveRegistryItem!==void 0)cancelActiveRegistryItem(),i=!0;else{n=!0,r.abort(new WizardCancelledError);let e=await s;return e.partial===!0?e:{...e,message:`/${t} interrupted.`,tone:`error`,preserveFlowDiagnostics:!0}}}finally{o.dispose()}i&&(o=e.renderer.waitForInterrupt())}}finally{e.renderer.setStatus(void 0)}}async function executeSetupCommand(e,t,n,r,i){let{command:a,appRoot:o}=e,s={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runRegistryFlow,runDeployFlow,...e.flows};try{switch(a){case`vc:install`:return installVercelCliResultMessage(await s.runInstallVercelCliFlow({appRoot:o,prompter:t,signal:r}));case`vc:login`:return loginResultMessage(await s.runLoginFlow({appRoot:o,prompter:t,signal:r}));case`model`:{let pickProvider=e=>n.readProviderPicker(e),i={appRoot:e.agentRoot??o,environmentRoot:o,prompter:t,signal:r,chatGptAccountLabel:e.chatGptAccountLabel,deps:{pickModelSettings:e=>n.readModelEditor(e),runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider,recoverHumanAction:e=>recoverVercelHumanAction(e,s,{appRoot:o,prompter:t,signal:r})})}};e.initialModelStep!==void 0&&(i.initialStep=e.initialModelStep),e.onOnboardingScreen!==void 0&&(i.onScreen=t=>e.onOnboardingScreen?.({screen:t}))
|
|
1
|
+
import{formatRegistrySessionResult,registryItemProgress,registryResultTone}from"./registry-result-message.js";import{createTuiPrompter}from"./tui-prompter.js";import{runDeployFlow}from"#setup/flows/deploy.js";import{WizardCancelledError}from"#setup/step.js";import{runLoginFlow}from"#setup/flows/login.js";import{HumanActionRequiredError}from"#setup/human-action.js";import{runInstallVercelCliFlow}from"#setup/flows/install-vercel-cli.js";import{runModelFlow}from"#setup/flows/model.js";import{runProviderFlow}from"#setup/flows/provider.js";import{RegistryFlowFailedError,runRegistryFlow}from"#setup/flows/registry.js";const SETUP_FLOW_CONFIG={"vc:install":{title:`Install the Vercel CLI`,indicator:`pulse`},"vc:login":{title:`Log in to Vercel`,indicator:`pulse`},model:{title:`Configure the agent model`,indicator:`pulse`},add:{title:`Add to your agent`,indicator:`pulse`},deploy:{title:`Deploy to Vercel`,indicator:`spinner`}};function muteableRenderer(e,t,n){return{readSelect:n=>t()?Promise.resolve(void 0):e.readSelect(n),readEditableSelect:n=>t()?Promise.resolve(void 0):e.readEditableSelect(n),readProviderPicker:n=>t()?Promise.resolve(void 0):e.readProviderPicker(n),readModelEditor:n=>t()?Promise.resolve(void 0):e.readModelEditor(n),readText:n=>t()?Promise.resolve(void 0):e.readText(n),readAcknowledge:n=>t()?Promise.resolve():e.readAcknowledge(n),readChoice:n=>t()?{choice:Promise.resolve(void 0),close:()=>{}}:e.readChoice(n),setNavigation:n=>{t()||e.setNavigation?.(n)},setStatus:n=>{t()||e.setStatus(n)},renderLine:(n,r)=>{(!t()||r===`warning`||r===`error`)&&e.renderLine(n,r)},replaceContent:n=>{t()||e.replaceContent?.(n)},renderOutput:n=>{t()||e.renderOutput(n)},withInheritedStdio:t=>e.withInheritedStdio(t),withExclusiveTerminal:e=>n?.(e)??e()}}async function runTuiSetupCommand(e){let{command:t}=e,n=!1,r=new AbortController,i=muteableRenderer(e.renderer,()=>n,e.withExclusiveTerminal),a=(e.createPrompter??createTuiPrompter)(i),cancelActiveRegistryItem,runRegistryItem=async e=>{let t=new AbortController;cancelActiveRegistryItem=()=>t.abort(new WizardCancelledError);try{return await e(AbortSignal.any([r.signal,t.signal]))}finally{cancelActiveRegistryItem=void 0}},o=e.renderer.waitForInterrupt(),s=executeSetupCommand(e,a,i,r.signal,runRegistryItem),c=s.then(e=>({kind:`outcome`,value:e}));try{for(;;){let i=!1;try{let e=await Promise.race([c,o.promise.then(e=>({kind:`interrupt`,interrupt:e}))]);if(e.kind===`outcome`)return e.value;if(t===`add`&&e.interrupt===`escape`&&cancelActiveRegistryItem!==void 0)cancelActiveRegistryItem(),i=!0;else{n=!0,r.abort(new WizardCancelledError);let e=await s;return e.partial===!0?e:{...e,message:`/${t} interrupted.`,tone:`error`,preserveFlowDiagnostics:!0}}}finally{o.dispose()}i&&(o=e.renderer.waitForInterrupt())}}finally{e.renderer.setStatus(void 0)}}async function executeSetupCommand(e,t,n,r,i){let{command:a,appRoot:o}=e,s={runInstallVercelCliFlow,runLoginFlow,runModelFlow,runRegistryFlow,runDeployFlow,...e.flows};try{switch(a){case`vc:install`:return installVercelCliResultMessage(await s.runInstallVercelCliFlow({appRoot:o,prompter:t,signal:r}));case`vc:login`:return loginResultMessage(await s.runLoginFlow({appRoot:o,prompter:t,signal:r}));case`model`:{let pickProvider=e=>n.readProviderPicker(e),i={appRoot:e.agentRoot??o,environmentRoot:o,prompter:t,signal:r,chatGptAccountLabel:e.chatGptAccountLabel,deps:{pickModelSettings:e=>n.readModelEditor(e),runProviderFlow:e=>runProviderFlow({...e,picker:pickProvider,recoverHumanAction:e=>recoverVercelHumanAction(e,s,{appRoot:o,prompter:t,signal:r})})}};e.initialModelStep!==void 0&&(i.initialStep=e.initialModelStep),e.onOnboardingScreen!==void 0&&(i.onScreen=t=>e.onOnboardingScreen?.({screen:t}));let a=await s.runModelFlow(i);if(a.kind===`cancelled`)return{message:a.discardedDraft===!0?`/model dismissed. Drafted changes were discarded; Done commits them.`:`/model dismissed.`,cancelled:!0,preserveFlowDiagnostics:!1};let c=[];a.modelMessage!==void 0&&c.push(a.modelMessage),a.providerSelection!==void 0&&c.push(providerSelectionMessage(a.providerSelection));let l={message:c.join(`
|
|
2
2
|
`),preserveFlowDiagnostics:!1};return a.accessChanged&&(l.effect={kind:`model-access-changed`}),l}case`add`:{let a=await s.runRegistryFlow({appRoot:o,prompter:t,signal:r,initialAddress:e.initialRegistryAddress,plannerContext:e.registryPlannerContext,onScreen:e.onOnboardingScreen,onItemStart:registryItemProgress(n),runItem:i});if(a.kind===`cancelled`)return{message:`/add dismissed.`,cancelled:!0,preserveFlowDiagnostics:!0};let c=a.result,l=registryResultTone(c),u=c.items.length>0||c.failures.length>0||c.outcomes!==void 0?formatRegistrySessionResult(c):`No integrations selected.`,d={message:l===`error`?`/add failed — ${u}`:u,preserveFlowDiagnostics:!0};return c.cancelled===!0?(d.partial=!0,d.tone=`error`):l!==void 0&&(d.tone=l),c.deployed===`production`&&(d.effect={kind:`deployed`}),d}case`deploy`:{let e=await s.runDeployFlow({appRoot:o,prompter:t,interactive:!0,signal:r});return e.kind===`cancelled`?{message:`/deploy dismissed.`,preserveFlowDiagnostics:!0}:e.kind===`needs-link`?{message:`Not linked to a Vercel project — run /model to connect one first.`,preserveFlowDiagnostics:!0}:e.kind===`local-model`?{message:`ChatGPT subscription models are local-only. Switch to an AI Gateway or server-authenticated model before deploying.`,preserveFlowDiagnostics:!0}:{message:e.productionUrl===void 0?`Deployed.`:`Deployed: ${e.productionUrl}`,preserveFlowDiagnostics:!0,effect:{kind:`deployed`}}}}}catch(e){if(e instanceof WizardCancelledError)return{message:`/${a} dismissed.`,cancelled:!0,preserveFlowDiagnostics:a!==`model`};let n=e instanceof RegistryFlowFailedError?e.cause:e,i=await vercelCliUpgradeOutcome(n,a,s,{appRoot:o,prompter:t,signal:r});if(i!==void 0)return withRegistryResults(i,e);let c=vercelActionOutcome(n,a);return c===void 0?e instanceof RegistryFlowFailedError?{message:`${formatRegistrySessionResult(e.completed)}\n\n${e.message}`,partial:!0,tone:`error`,preserveFlowDiagnostics:!0}:{message:`/${a} failed: ${e instanceof Error?e.message:String(e)}`,tone:`error`,preserveFlowDiagnostics:!0}:withRegistryResults(c,e)}}async function recoverVercelHumanAction(e,t,n){let r=e.action.kind;if(r!==`vercel-cli-missing`&&r!==`vercel-cli-upgrade`&&r!==`vercel-login`&&r!==`vercel-forbidden`)throw e;let i=r===`vercel-cli-missing`?{label:`Install Vercel CLI`,message:`The Vercel CLI is required. Install it now?`}:r===`vercel-cli-upgrade`?{label:`Upgrade Vercel CLI`,message:`Your Vercel CLI needs an update. Upgrade it now?`}:{label:r===`vercel-forbidden`?`Re-authenticate with Vercel`:`Log in to Vercel`,message:r===`vercel-forbidden`?`Vercel denied access to that team. Re-authenticate and continue?`:`You need to log in to Vercel to continue.`},a;try{a=await n.prompter.select({message:i.message,options:[{value:`repair`,label:`${i.label} and continue`},{value:`cancel`,label:`Choose another option`}],initialValue:`repair`})}catch{return`cancel`}if(a===`cancel`)return`cancel`;if(r===`vercel-cli-missing`||r===`vercel-cli-upgrade`){let e=await t.runInstallVercelCliFlow({appRoot:n.appRoot,prompter:n.prompter,signal:n.signal,upgrade:r===`vercel-cli-upgrade`});return e.kind===`installed`||e.kind===`already`?`retry`:(n.prompter.log.warning(e.kind===`failed`&&e.reason!==void 0?`Couldn't ${r===`vercel-cli-upgrade`?`upgrade`:`install`} the Vercel CLI: ${e.reason}`:`Couldn't ${r===`vercel-cli-upgrade`?`upgrade`:`install`} the Vercel CLI.`),`cancel`)}let o=await t.runLoginFlow({appRoot:n.appRoot,prompter:n.prompter,signal:n.signal,force:r===`vercel-forbidden`});return n.prompter.replaceContent?.(),o.kind===`logged-in`||o.kind===`already`?`retry`:`cancel`}function withRegistryResults(e,t){return t instanceof RegistryFlowFailedError?{...e,message:`${formatRegistrySessionResult(t.completed)}\n\n${e.message}`,partial:!0,tone:`error`,preserveFlowDiagnostics:!0}:e}async function vercelCliUpgradeOutcome(e,t,n,r){if(!(e instanceof HumanActionRequiredError)||e.action.kind!==`vercel-cli-upgrade`)return;let i;try{i=await r.prompter.select({message:`Your Vercel CLI needs an update to list your teams. Upgrade now?`,options:[{value:`upgrade`,label:`Upgrade Vercel CLI`,description:`Run the Vercel CLI's native upgrader`},{value:`later`,label:`Not now`}],initialValue:`upgrade`})}catch{i=`later`}if(i===`later`)return{message:`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`,tone:`error`,preserveFlowDiagnostics:!0};let a;try{a=await n.runInstallVercelCliFlow({appRoot:r.appRoot,prompter:r.prompter,signal:r.signal,upgrade:!0})}catch(e){return{message:vercelCliUpgradeFailureMessage(t,errorMessage(e)),tone:`error`,preserveFlowDiagnostics:!0}}switch(a.kind){case`installed`:return{message:`Upgraded the Vercel CLI. Retry /${t}.`,tone:`error`,preserveFlowDiagnostics:!1};case`failed`:return{message:vercelCliUpgradeFailureMessage(t,a.reason),tone:`error`,preserveFlowDiagnostics:!0};case`cancelled`:return{message:`Vercel CLI upgrade cancelled — run \`vercel upgrade\`, then retry /${t}.`,tone:`error`,preserveFlowDiagnostics:!0};case`already`:return{message:`The Vercel CLI is already up to date. Retry /${t}.`,tone:`error`,preserveFlowDiagnostics:!1}}}function errorMessage(e){let t=(e instanceof Error?e.message:String(e)).replace(/\s+/gu,` `).trim();return t.length<=240?t:`${t.slice(0,239)}…`}function vercelCliUpgradeFailureMessage(e,t){return`Couldn't upgrade the Vercel CLI${t===void 0||t===``?``:` (${t})`} — run \`vercel upgrade\`, then retry /${e}.`}function vercelActionOutcome(e,t){if(!(e instanceof HumanActionRequiredError))return;let n=vercelActionMessage(e.action.kind,t);return n===void 0?void 0:{message:n,tone:`error`,preserveFlowDiagnostics:!0}}function vercelActionMessage(e,t){switch(e){case`vercel-login`:return`You're not logged in to Vercel — run /vc:login, then retry /${t}.`;case`vercel-forbidden`:return`Vercel denied access to that team — run /vc:login to re-authenticate (for example to complete SSO), or pick a team you can access, then retry /${t}.`;case`vercel-cli-missing`:return`The Vercel CLI isn't installed — run /vc:install to install it, then retry /${t}.`;case`vercel-cli-upgrade`:return`The Vercel CLI needs an update — run \`vercel upgrade\`, then retry /${t}.`;default:return}}function installVercelCliResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:install dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`The Vercel CLI is already installed.`,preserveFlowDiagnostics:!1};case`failed`:return{message:"Couldn't install the Vercel CLI — install it manually with `npm i -g vercel@latest`.",preserveFlowDiagnostics:!0};case`installed`:return{message:`Installed the Vercel CLI. Run /vc:login next.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}}}}function loginResultMessage(e){switch(e.kind){case`cancelled`:return{message:`/vc:login dismissed.`,preserveFlowDiagnostics:!1};case`already`:return{message:`You're already logged in to Vercel.`,preserveFlowDiagnostics:!1};case`cli-missing`:return{message:`The Vercel CLI isn't installed — run /vc:install to install it, then retry /vc:login.`,preserveFlowDiagnostics:!0};case`failed`:return{message:`Vercel login didn't complete — run /vc:login to try again.`,preserveFlowDiagnostics:!0};case`logged-in`:return{message:`Logged in to Vercel.`,preserveFlowDiagnostics:!1,effect:{kind:`refresh-identity`}};case`unavailable`:return{message:`Couldn't reach Vercel — check your connection, then retry /vc:login.`,preserveFlowDiagnostics:!0}}}function providerSelectionMessage(e){return e===`chatgpt`?`ChatGPT subscription selected.`:e===`ai-gateway-project`?`AI Gateway via Project selected.`:`AI Gateway via API key selected.`}export{SETUP_FLOW_CONFIG,runTuiSetupCommand};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"moduleFingerprints": {
|
|
3
3
|
"@eve/catalog": "1a52c83c427f093856c0f21512b04d1546e959c80bb1c58672520cbead580260",
|
|
4
|
+
"just-secrets": "1ce67d437d0bb06df02e4e99180a3c5f5edf0010314010226e97b96d462bba5d",
|
|
4
5
|
"@workflow/world-local": "eeaeed751310cf36666c3daa07f305f431710951b0523b97dcdca3d6e69b1061"
|
|
5
6
|
},
|
|
6
7
|
"moduleVersions": {
|
|
@@ -22,6 +23,7 @@
|
|
|
22
23
|
"jose": "6.2.3",
|
|
23
24
|
"jsonc-parser": "3.3.1",
|
|
24
25
|
"@types/json-schema": "7.0.15",
|
|
26
|
+
"just-secrets": "0.0.2",
|
|
25
27
|
"marked": "17.0.6",
|
|
26
28
|
"@ai-sdk/mcp": "2.0.45",
|
|
27
29
|
"@modelcontextprotocol/server": "2.0.0",
|
|
@@ -54,7 +56,7 @@
|
|
|
54
56
|
"zod": "4.5.4",
|
|
55
57
|
"zod-validation-error": "5.0.0"
|
|
56
58
|
},
|
|
57
|
-
"scriptHash": "
|
|
59
|
+
"scriptHash": "832a583779021f10d8b9100f7d883ef4de7cfd94825559893b77288327735ec8",
|
|
58
60
|
"toolVersions": {
|
|
59
61
|
"rolldown": "1.2.7",
|
|
60
62
|
"typescript": "7.0.2"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vercel, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Identifies a credential within a service. */
|
|
2
|
+
export interface SecretsOptions {
|
|
3
|
+
service: string;
|
|
4
|
+
name: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface Secrets {
|
|
8
|
+
/** Returns the stored secret, or null when it does not exist. */
|
|
9
|
+
get(options: SecretsOptions): Promise<string | null>;
|
|
10
|
+
get(service: string, name: string): Promise<string | null>;
|
|
11
|
+
/** Creates or replaces a secret in the native credential store. */
|
|
12
|
+
set(options: SecretsOptions & { value: string }): Promise<void>;
|
|
13
|
+
set(service: string, name: string, value: string): Promise<void>;
|
|
14
|
+
/** Returns true when deleted, or false when it does not exist. */
|
|
15
|
+
delete(options: SecretsOptions): Promise<boolean>;
|
|
16
|
+
delete(service: string, name: string): Promise<boolean>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Native secret storage for Node.js 22+, using OS-provided credential tools. */
|
|
20
|
+
export declare const secrets: Secrets;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{spawn as e}from"node:child_process";import{readFile as t}from"node:fs/promises";import n from"node:path";function r(e,t=`ERR_SECRETS_STORE`){return Object.assign(Error(e),{code:t})}function i(t,n,{input:i=``,timeout:a=6e4,maxOutput:o=1048576}={}){return new Promise((s,c)=>{let l;try{l=e(t,n,{shell:!1,windowsHide:!0,stdio:[`pipe`,`pipe`,`pipe`],cwd:void 0})}catch{c(r(`Could not start the OS credential tool.`,`ERR_SECRETS_UNAVAILABLE`));return}let u=[],d=[],f=0,p,m,h=!1,g=(e,t)=>{if(!h){h=!0,clearTimeout(v);for(let e of[...u,...d])e.fill(0);u.length=d.length=0,e?c(e):s(t)}},_=e=>{p??=e,l.kill(`SIGKILL`),l.stdin.destroy(),l.stdout.destroy(),l.stderr.destroy(),g(p)},v=setTimeout(()=>_(r(`The OS credential tool timed out. Unlock your credential store and retry.`,`ERR_SECRETS_TIMEOUT`)),a);for(let[e,t]of[[l.stdout,u],[l.stderr,d]])e.on(`data`,e=>{if(h){e.fill(0);return}f+=e.length,f>o?(e.fill(0),_(r(`The OS credential tool exceeded its output limit.`,`ERR_SECRETS_OUTPUT_LIMIT`))):t.push(e)}),e.on(`error`,()=>_(r(`Could not read the OS credential tool response.`)));l.on(`error`,e=>{let t=e.code===`EACCES`||e.code===`EPERM`?`ERR_SECRETS_ACCESS_DENIED`:`ERR_SECRETS_UNAVAILABLE`;g(r(`Could not start the OS credential tool. Check its installation and permissions.`,t))}),l.stdin.on(`error`,()=>{m=r(`Could not send input to the OS credential tool.`)}),l.on(`close`,(e,t)=>{if(h)return;if(t!==null||!Number.isInteger(e)){g(r(`The OS credential tool terminated unexpectedly.`));return}if(e===0&&m){g(m);return}let n=Buffer.concat(u),i=Buffer.concat(d),a={code:e,stdout:n.toString(`utf8`),stderr:i.toString(`utf8`)};n.fill(0),i.fill(0),g(void 0,a)}),l.stdin.end(i)})}const a=`/usr/bin/security`,o=`secrets:v1:`,s=e=>o+Buffer.from(e,`utf8`).toString(`base64`),c=e=>`"`+e.replaceAll(`\\`,`\\\\`).replaceAll(`"`,`\\"`)+`"`,l=`macOS Keychain operation failed. Check Keychain access and unlock your login keychain.`;function u({run:e=i,keychain:t=`login.keychain-db`}={}){if(/[\r\n\0]/u.test(t))throw TypeError(`Invalid keychain path.`);let n=(e,t)=>[`-s`,s(e),`-a`,s(t)];function u(e,t=!1){if(t&&e.code===44)return!1;if(e.code!==0){let t=e.code===36||e.code===128?`ERR_SECRETS_ACCESS_DENIED`:`ERR_SECRETS_STORE`;throw r(l,t)}return!0}let d=async()=>u(await e(a,[`-q`,`show-keychain-info`,t]));return{async get(i,s){await d();let c=await e(a,[`-q`,`find-generic-password`,...n(i,s),`-w`,t]);if(!u(c,!0))return null;let f=c.stdout.replace(/\n$/u,``);if(!f.startsWith(o))throw r(l);let p=f.slice(11),m=Buffer.from(p,`base64`),h=m.toString(`utf8`);if(m.length>2560||m.toString(`base64`)!==p||!Buffer.from(h,`utf8`).equals(m))throw r(l);return h},async set(i,o,f){let p=[`add-generic-password`,`-U`,...n(i,o),`-w`,s(f),t].map(c).join(` `)+`
|
|
2
|
+
`;if(Buffer.byteLength(p)>=4096)throw RangeError(`The combined service, name, and value exceed the macOS command limit.`);await d();let m=await e(a,[`-q`,`-i`],{input:p});if(u(m),m.stderr!==``||m.stdout!==``)throw r(l)},async delete(r,i){return await d(),u(await e(a,[`-q`,`delete-generic-password`,...n(r,i),t]),!0)}}}const d=`Linux credential operation failed; ensure /usr/bin/secret-tool and an unlocked Secret Service session are available`,f=`secrets:v1:`,p=new Set([`ERR_SECRETS_UNAVAILABLE`,`ERR_SECRETS_TIMEOUT`,`ERR_SECRETS_OUTPUT_LIMIT`,`ERR_SECRETS_STORE`,`ERR_SECRETS_ACCESS_DENIED`]);function m(e){return f+Buffer.from(e,`utf8`).toString(`base64`)}function h(e){if(!e.startsWith(f)||e.length>3427)throw r(d);let t=e.slice(11),n=Buffer.from(t,`base64`),i=n.toString(`utf8`);if(n.length>2560||n.toString(`base64`)!==t||!Buffer.from(i,`utf8`).equals(n))throw r(d);return i}function g({run:e=i}={}){async function t(t,n,i,a){let o=[`application`,`secrets`,`service`,m(n),`name`,m(i)],s;try{s=await e(`/usr/bin/secret-tool`,[t,...t===`store`?[`--label=secrets`]:t===`search`?[`--all`,`--unlock`]:[],`--`,...o],{input:t===`store`?m(a):``})}catch(e){let t=p.has(e?.code)?e.code:e?.code===`ENOENT`?`ERR_SECRETS_UNAVAILABLE`:e?.code===`EACCES`||e?.code===`EPERM`?`ERR_SECRETS_ACCESS_DENIED`:`ERR_SECRETS_STORE`;throw r(d,t)}if(!s||!Number.isInteger(s.code)||typeof s.stdout!=`string`||typeof s.stderr!=`string`||s.code!==0)throw r(d);if(t===`search`){let e=new Set([0,2,4].map(e=>`attribute.${o[e]} = ${o[e+1]}\n`));if((s.stderr.match(/[^\n]*\n|[^\n]+$/g)??[]).some(t=>!e.has(t)))throw r(d);if(s.stdout===``&&s.stderr===``)return!1;let t=/\[[^\r\n\]]+\]\nlabel = [^\r\n]*\nsecret = (secrets:v1:[A-Za-z0-9+/=]*)\ncreated = [^\r\n]*\nmodified = [^\r\n]*\n(?:schema = [^\r\n]*\n)?/gy,n=0,i;for(;(i=t.exec(s.stdout))!==null;)h(i[1]),n=t.lastIndex;if(n===0||n!==s.stdout.length)throw r(d);return!0}if(s.stderr!==``||t!==`lookup`&&s.stdout!==``)throw r(d);return t!==`lookup`||h(s.stdout)}return{async get(e,n){return await t(`search`,e,n)?t(`lookup`,e,n):null},async set(e,n,r){await t(`store`,e,n,r)},async delete(e,n){if(!await t(`search`,e,n))return!1;if(await t(`clear`,e,n),await t(`search`,e,n))throw r(d);return!0}}}const _=new URL(`./windows.ps1`,import.meta.url),v=`Windows credential operation failed`,y=new Set([`ERR_SECRETS_UNAVAILABLE`,`ERR_SECRETS_TIMEOUT`,`ERR_SECRETS_OUTPUT_LIMIT`,`ERR_SECRETS_STORE`,`ERR_SECRETS_ACCESS_DENIED`]);function b({run:e=i}={}){let a;async function o(i,o,s,c){let l=process.env.SystemRoot??process.env.SYSTEMROOT;if(typeof l!=`string`||!/^[a-z]:\\/i.test(l)||l.includes(`\0`))throw r(`Windows PowerShell is unavailable`,`ERR_SECRETS_UNAVAILABLE`);let u=n.win32.join(l,`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`),d;try{a??=t(_,`utf8`).then(e=>Buffer.from(e,`utf16le`).toString(`base64`)),d=await e(u,[`-NoLogo`,`-NoProfile`,`-NonInteractive`,`-InputFormat`,`Text`,`-OutputFormat`,`Text`,`-EncodedCommand`,await a],{input:JSON.stringify({operation:i,service:o,name:s,...i===`set`?{value:c}:{}})})}catch(e){throw r(v,y.has(e?.code)?e.code:`ERR_SECRETS_STORE`)}let f;try{if(!d||!Number.isInteger(d.code)||typeof d.stdout!=`string`||(f=JSON.parse(d.stdout),!f||typeof f!=`object`||Array.isArray(f)||Object.keys(f).length!==1))throw null}catch{throw r(v)}if(d.code!==0){if(f.error===1168&&i!==`set`)return i===`get`&&null;let e=f.error===5?`ERR_SECRETS_ACCESS_DENIED`:f.error===1312||f.error===50||f.error===`ERR_SECRETS_UNAVAILABLE`?`ERR_SECRETS_UNAVAILABLE`:`ERR_SECRETS_STORE`;throw r(v,e)}if(d.stderr!==``||!Object.hasOwn(f,`value`))throw r(v);if(i===`get`){if(f.value!==null&&(typeof f.value!=`string`||!f.value.isWellFormed()||Buffer.byteLength(f.value,`utf8`)>2560))throw r(v);return f.value}if(i===`delete`&&typeof f.value==`boolean`)return f.value;if(i!==`set`||f.value!==!0)throw r(v)}return{get:(e,t)=>o(`get`,e,t),set:(e,t,n)=>o(`set`,e,t,n),delete:(e,t)=>o(`delete`,e,t)}}function x(e,t,n){if(typeof e!=`string`)throw TypeError(`${t} must be a string.`);if(!e.isWellFormed())throw TypeError(`${t} must contain valid Unicode.`);if(t!==`value`&&e.length===0)throw TypeError(`${t} must not be empty.`);if(Buffer.byteLength(e,`utf8`)>n)throw RangeError(`${t} must not exceed ${n} UTF-8 bytes.`);return e}function S(e,t){let n=e[0]!==null&&typeof e[0]==`object`&&!Array.isArray(e[0]);if(e.length!==(n?1:t?3:2))throw TypeError(`Expected an options object or service, name`+(t?`, value.`:`.`));let r=n?e[0]:{service:e[0],name:e[1],value:e[2]};return[x(r.service,`service`,256),x(r.name,`name`,256),...t?[x(r.value,`value`,2560)]:[]]}function C(){switch(process.platform){case`darwin`:return u();case`linux`:return g();case`win32`:return b();default:throw r(`Native secret storage is supported on macOS, Linux, and Windows.`,`ERR_SECRETS_UNSUPPORTED`)}}function w(e=C){let t,n=()=>t??=e();return Object.freeze({async get(...e){let t=S(e,!1);return n().get(...t)},async set(...e){let t=S(e,!0);await n().set(...t)},async delete(...e){let t=S(e,!1);return n().delete(...t)}})}const T=w();export{T as secrets};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
$ErrorActionPreference = 'Stop'
|
|
2
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
3
|
+
try {
|
|
4
|
+
if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
|
|
5
|
+
throw 'Unavailable'
|
|
6
|
+
}
|
|
7
|
+
[Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false, $true)
|
|
8
|
+
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false, $true)
|
|
9
|
+
Add-Type -TypeDefinition @'
|
|
10
|
+
using System;
|
|
11
|
+
using System.ComponentModel;
|
|
12
|
+
using System.Runtime.InteropServices;
|
|
13
|
+
using System.Text;
|
|
14
|
+
|
|
15
|
+
public static class SecretsCredentials {
|
|
16
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
17
|
+
private struct Credential {
|
|
18
|
+
public uint Flags;
|
|
19
|
+
public uint Type;
|
|
20
|
+
public IntPtr TargetName;
|
|
21
|
+
public IntPtr Comment;
|
|
22
|
+
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
|
23
|
+
public uint CredentialBlobSize;
|
|
24
|
+
public IntPtr CredentialBlob;
|
|
25
|
+
public uint Persist;
|
|
26
|
+
public uint AttributeCount;
|
|
27
|
+
public IntPtr Attributes;
|
|
28
|
+
public IntPtr TargetAlias;
|
|
29
|
+
public IntPtr UserName;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
[DllImport("advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
|
|
33
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
34
|
+
private static extern bool CredWrite(ref Credential credential, uint flags);
|
|
35
|
+
[DllImport("advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
|
|
36
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
37
|
+
private static extern bool CredRead(string target, uint type, uint flags, out IntPtr credential);
|
|
38
|
+
[DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
|
|
39
|
+
[return: MarshalAs(UnmanagedType.Bool)]
|
|
40
|
+
private static extern bool CredDelete(string target, uint type, uint flags);
|
|
41
|
+
[DllImport("advapi32.dll", ExactSpelling = true)]
|
|
42
|
+
private static extern void CredFree(IntPtr credential);
|
|
43
|
+
|
|
44
|
+
private static readonly Encoding Utf8 = new UTF8Encoding(false, true);
|
|
45
|
+
private static void Zero(IntPtr pointer, int length) {
|
|
46
|
+
if (pointer != IntPtr.Zero) for (int i = 0; i < length; i++) Marshal.WriteByte(pointer, i, 0);
|
|
47
|
+
}
|
|
48
|
+
public static string Target(string service, string name) {
|
|
49
|
+
// Length framing avoids both delimiter collisions and JSON serializer differences.
|
|
50
|
+
byte[] a = Utf8.GetBytes(service), b = Utf8.GetBytes(name);
|
|
51
|
+
if (a.Length > 256 || b.Length > 256) throw new ArgumentException();
|
|
52
|
+
byte[] framed = new byte[4 + a.Length + b.Length];
|
|
53
|
+
framed[0] = (byte)(a.Length >> 8); framed[1] = (byte)a.Length;
|
|
54
|
+
framed[2] = (byte)(b.Length >> 8); framed[3] = (byte)b.Length;
|
|
55
|
+
Buffer.BlockCopy(a, 0, framed, 4, a.Length);
|
|
56
|
+
Buffer.BlockCopy(b, 0, framed, 4 + a.Length, b.Length);
|
|
57
|
+
// Credential targets are case-insensitive; hex preserves identity under case folding.
|
|
58
|
+
string target = "secrets:" + BitConverter.ToString(framed).Replace("-", "").ToLowerInvariant();
|
|
59
|
+
if (target.Length > 32767) throw new ArgumentException();
|
|
60
|
+
return target;
|
|
61
|
+
}
|
|
62
|
+
public static void Write(string target, string value) {
|
|
63
|
+
byte[] bytes = Utf8.GetBytes(value);
|
|
64
|
+
IntPtr blob = IntPtr.Zero, targetPointer = IntPtr.Zero;
|
|
65
|
+
try {
|
|
66
|
+
if (bytes.Length > 2560) throw new ArgumentException();
|
|
67
|
+
targetPointer = Marshal.StringToCoTaskMemUni(target);
|
|
68
|
+
// Allocate one byte even for an empty secret; its native length remains zero.
|
|
69
|
+
blob = Marshal.AllocHGlobal(Math.Max(1, bytes.Length));
|
|
70
|
+
Marshal.WriteByte(blob, 0, 0);
|
|
71
|
+
if (bytes.Length != 0) Marshal.Copy(bytes, 0, blob, bytes.Length);
|
|
72
|
+
Credential credential = new Credential {
|
|
73
|
+
Type = 1, TargetName = targetPointer, CredentialBlob = blob,
|
|
74
|
+
CredentialBlobSize = (uint)bytes.Length, Persist = 3
|
|
75
|
+
};
|
|
76
|
+
if (!CredWrite(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
77
|
+
} finally {
|
|
78
|
+
if (blob != IntPtr.Zero) { Zero(blob, Math.Max(1, bytes.Length)); Marshal.FreeHGlobal(blob); }
|
|
79
|
+
if (targetPointer != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(targetPointer);
|
|
80
|
+
Array.Clear(bytes, 0, bytes.Length);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
public static string Read(string target) {
|
|
84
|
+
IntPtr pointer = IntPtr.Zero;
|
|
85
|
+
Credential credential = new Credential();
|
|
86
|
+
byte[] bytes = null;
|
|
87
|
+
try {
|
|
88
|
+
if (!CredRead(target, 1, 0, out pointer)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
89
|
+
credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
|
|
90
|
+
if (credential.CredentialBlobSize > 2560 || (credential.CredentialBlobSize != 0 && credential.CredentialBlob == IntPtr.Zero)) throw new ArgumentException();
|
|
91
|
+
bytes = new byte[(int)credential.CredentialBlobSize];
|
|
92
|
+
if (bytes.Length != 0) Marshal.Copy(credential.CredentialBlob, bytes, 0, bytes.Length);
|
|
93
|
+
return Utf8.GetString(bytes);
|
|
94
|
+
} finally {
|
|
95
|
+
if (bytes != null) Array.Clear(bytes, 0, bytes.Length);
|
|
96
|
+
if (pointer != IntPtr.Zero) {
|
|
97
|
+
try {
|
|
98
|
+
// Rejected native lengths must not turn cleanup into an unbounded write.
|
|
99
|
+
Zero(credential.CredentialBlob, (int)Math.Min(credential.CredentialBlobSize, 2560u));
|
|
100
|
+
} finally { CredFree(pointer); }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
public static bool Delete(string target) {
|
|
105
|
+
if (!CredDelete(target, 1, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
'@
|
|
110
|
+
$request = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
111
|
+
if ($request.service -isnot [string] -or $request.name -isnot [string]) { throw 'Invalid request' }
|
|
112
|
+
$target = [SecretsCredentials]::Target($request.service, $request.name)
|
|
113
|
+
switch -CaseSensitive ($request.operation) {
|
|
114
|
+
'get' { $value = [SecretsCredentials]::Read($target) }
|
|
115
|
+
'set' {
|
|
116
|
+
if ($request.value -isnot [string]) { throw 'Invalid request' }
|
|
117
|
+
[SecretsCredentials]::Write($target, $request.value)
|
|
118
|
+
$value = $true
|
|
119
|
+
}
|
|
120
|
+
'delete' { $value = [SecretsCredentials]::Delete($target) }
|
|
121
|
+
default { throw 'Invalid request' }
|
|
122
|
+
}
|
|
123
|
+
[Console]::Out.WriteLine((ConvertTo-Json -Compress -InputObject @{ value = $value }))
|
|
124
|
+
exit 0
|
|
125
|
+
} catch {
|
|
126
|
+
# Never serialize exception messages: native and PowerShell errors can contain input.
|
|
127
|
+
$code = 'ERR_SECRETS_STORE'
|
|
128
|
+
if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
|
|
129
|
+
# Full-language APIs may themselves be forbidden, so use only a fixed ASCII literal.
|
|
130
|
+
Write-Output '{"error":"ERR_SECRETS_UNAVAILABLE"}'
|
|
131
|
+
exit 1
|
|
132
|
+
}
|
|
133
|
+
$exception = $_.Exception
|
|
134
|
+
while ($null -ne $exception.InnerException) { $exception = $exception.InnerException }
|
|
135
|
+
if ($exception -is [System.ComponentModel.Win32Exception]) { $code = $exception.NativeErrorCode }
|
|
136
|
+
[Console]::Out.WriteLine((ConvertTo-Json -Compress -InputObject @{ error = $code }))
|
|
137
|
+
exit 1
|
|
138
|
+
}
|
|
@@ -11,8 +11,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
11
11
|
readonly dropped: {};
|
|
12
12
|
};
|
|
13
13
|
readonly tool: {
|
|
14
|
-
readonly current:
|
|
15
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35];
|
|
14
|
+
readonly current: 36;
|
|
15
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 36];
|
|
16
16
|
readonly dropped: {
|
|
17
17
|
readonly 14: "TaskExec.delegated was removed; migrate to workflow-backed background tools";
|
|
18
18
|
readonly 15: "TaskExec replaces stageEffect with send";
|
|
@@ -32,8 +32,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
32
32
|
};
|
|
33
33
|
};
|
|
34
34
|
readonly dynamicTool: {
|
|
35
|
-
readonly current:
|
|
36
|
-
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32, 33];
|
|
35
|
+
readonly current: 34;
|
|
36
|
+
readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32, 33, 34];
|
|
37
37
|
readonly dropped: {
|
|
38
38
|
readonly 21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
|
|
39
39
|
readonly 23: "TaskExec.delegated was removed; migrate to workflow-backed background tools";
|
|
@@ -58,8 +58,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
58
58
|
};
|
|
59
59
|
};
|
|
60
60
|
readonly subagent: {
|
|
61
|
-
readonly current:
|
|
62
|
-
readonly supported: readonly [3, 4, 6, 7, 8, 9, 10, 11, 12];
|
|
61
|
+
readonly current: 13;
|
|
62
|
+
readonly supported: readonly [3, 4, 6, 7, 8, 9, 10, 11, 12, 13];
|
|
63
63
|
readonly dropped: {
|
|
64
64
|
readonly 1: "Persistent subagent sessions are now the default and the experimental opt-in was removed";
|
|
65
65
|
readonly 2: "Persistent subagent sessions are now the default and the experimental opt-in was removed";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:
|
|
1
|
+
import{readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=2,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:36,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,28,29,30,31,32,34,35,36],dropped:{14:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,15:`TaskExec replaces stageEffect with send`,16:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,17:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,18:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,19:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,20:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,21:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,22:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,33:`ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types`}},dynamicTool:{current:34,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,28,29,30,31,32,33,34],dropped:{21:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`,23:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,24:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,25:`TaskExec.delegated was removed; migrate to workflow-backed background tools`,26:`Background tools now use task yield descriptors`,27:`TaskExec.delegated was removed; migrate to workflow-backed background tools`}},channel:{current:19,supported:[1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19],dropped:{12:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},schedule:{current:11,supported:[1,2,3,4,6,7,8,9,10,11],dropped:{5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},subagent:{current:13,supported:[3,4,6,7,8,9,10,11,12,13],dropped:{1:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,2:`Persistent subagent sessions are now the default and the experimental opt-in was removed`,5:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},connection:{current:15,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15],dropped:{9:`Dynamic connection resolvers no longer receive conversation or channel continuation data`,10:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},hook:{current:22,supported:[10,11,12,13,14,15,17,18,19,20,21,22],dropped:{1:`Model identity moved from session.started runtime metadata to step.started call attribution.`,2:`Model identity moved from session.started runtime metadata to step.started call attribution.`,3:`Model identity moved from session.started runtime metadata to step.started call attribution.`,4:`Model identity moved from session.started runtime metadata to step.started call attribution.`,5:`Model identity moved from session.started runtime metadata to step.started call attribution.`,6:`Model identity moved from session.started runtime metadata to step.started call attribution.`,7:`Model identity moved from session.started runtime metadata to step.started call attribution.`,8:`Model identity moved from session.started runtime metadata to step.started call attribution.`,9:`Model identity moved from session.started runtime metadata to step.started call attribution.`,16:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:17,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:18,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18],dropped:{14:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},config:{current:1,supported:[1],dropped:{}},state:{current:5,supported:[1,2,3,4,5],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestV1Schema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict(),extensionCompatibilityManifestV2Schema=extensionCompatibilityManifestV1Schema.extend({formatVersion:z.literal(2),build:z.object({externalDependencies:z.array(z.string().min(1)).readonly()}).strict().optional()}),extensionCompatibilityManifestSchema=z.union([extensionCompatibilityManifestV1Schema,extensionCompatibilityManifestV2Schema]);function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,t){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(t),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentSourceManifest, LocalSubagentSourceRef } from "#discover/manifest.js";
|
|
2
|
-
import type { CompiledAgentDefinition, CompiledExtensionMount, CompiledRemoteAgentNode } from "#compiler/manifest.js";
|
|
2
|
+
import type { CompiledAgentDefinition, CompiledExtensionMount, CompiledRemoteAgentNode, CompiledSubagentNode } from "#compiler/manifest.js";
|
|
3
3
|
import type { ModuleSourceRef } from "#shared/source-ref.js";
|
|
4
4
|
import { normalizeSubagentConfig } from "#compiler/normalize-subagent.js";
|
|
5
5
|
import { type AgentModuleCandidate, type AgentSourceOwner, type AgentSourceRegistry, type ComposedAgentModuleCandidates, type CompiledModuleBinding } from "#compiler/source-graph.js";
|
|
@@ -13,6 +13,7 @@ export declare function withExtensionNamespace<T extends {
|
|
|
13
13
|
readonly extensionNamespace?: string;
|
|
14
14
|
}>(definition: T, owner: AgentSourceOwner): T;
|
|
15
15
|
export declare function assertUniqueBy<T>(values: readonly T[], identity: (value: T) => string, label: string): void;
|
|
16
|
+
export declare function withDiagnosticsSummary(subagents: readonly CompiledSubagentNode[], diagnosticsSummary: import("#discover/diagnostics.js").DiscoverDiagnosticsSummary): CompiledSubagentNode[];
|
|
16
17
|
export declare function expectSubagentDescription(config: CompiledAgentDefinition, source: LocalSubagentSourceRef): string;
|
|
17
18
|
export declare function createCompiledRemoteAgent(input: {
|
|
18
19
|
readonly binding: CompiledModuleBinding;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{posix}from"node:path";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{canonicalSourceSlot}from"#compiler/source-graph.js";import{mountRefNamespace,packageStateNamespace}from"#discover/extensions.js";import"#compiler/normalize-subagent.js";function collectSelectedSourceIds(e){return new Set([...e.selected.values()].map(e=>e.sourceId))}function assertRootOnlyConfig(e,t,n){if(!t&&e.experimental?.workflow?.world!==void 0)throw Error(`Workflow world configuration is only supported on the root agent config. Remove "experimental.workflow.world" from "${n}".`)}function assertApplicationOverlayCanApplyToAllNodes(e){let t=e.find(e=>{let t=canonicalSourceSlot(e);return t===`agent`||t.startsWith(`channels/`)||t.startsWith(`schedules/`)||t.startsWith(`subagents/`)||t.startsWith(`extensions/`)});if(t!==void 0)throw Error(`Application programmatic source registered for all local nodes cannot declare "${t}".`)}function assertUniqueRegistryIds(e){let t=new Set;for(let n of e)for(let e of n.sources.keys()){if(t.has(e))throw Error(`Programmatic agent source id "${e}" is registered more than once.`);t.add(e)}}function assertRootOwnedSpecialTool(e,t){if(e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`${t} can only be enabled on the root agent.`);assertNonExtensionSpecialTool(e,t)}function assertNonExtensionSpecialTool(e,t){if(e.owner.kind===`extension`)throw Error(`${t} cannot be configured by an extension source.`)}function withExtensionNamespace(e,t){return t.kind===`extension`?{...e,extensionNamespace:t.namespace}:e}function assertUniqueBy(e,t,n){let r=new Set;for(let i of e){let e=t(i);if(r.has(e))throw Error(`Compiled ${n} "${e}" is declared more than once.`);r.add(e)}}function expectSubagentDescription(e,t){if(e.description===void 0||e.description.trim().length===0)throw Error(`Subagent "${t.logicalPath}" must define a non-empty description.`);return e.description}function createCompiledRemoteAgent(e){let t=e.source.logicalPath.endsWith(`.ts`)||e.source.logicalPath.endsWith(`.js`)?e.source.logicalPath:posix.join(e.source.logicalPath,`agent.ts`),n=e.source.sourceId,r={backing:e.binding.backing,logicalPath:t,owner:e.owner,usage:e.binding.usage},i={backing:{kind:`resource`,sourcePath:e.source.entryPath},binding:r,description:e.definition.description,entryPath:e.source.entryPath,logicalPath:t,name:e.source.subagentId,nodeId:e.nodeId,owner:e.owner,parentNodeId:e.parentNodeId,path:e.definition.path,rootPath:e.source.rootPath,sourceId:n,sourceKind:`module`};return e.sourceRef.exportName!==void 0&&Object.assign(i,{exportName:e.sourceRef.exportName}),e.definition.outputSchema!==void 0&&Object.assign(i,{outputSchema:e.definition.outputSchema}),e.definition.url!==void 0&&Object.assign(i,{url:e.definition.url}),i}function compileExtensionMounts(e,t){let n=collectSelectedSourceIds(t);return e.resolvedExtensions.flatMap(t=>{let r=e.extensions.find(e=>mountRefNamespace(e.logicalPath)===t.namespace);return r===void 0||!n.has(r.sourceId)?[]:[{externalDependencies:[...t.externalDependencies],mountLogicalPath:r.logicalPath,mountSourceId:r.sourceId,namespace:t.namespace,packageName:t.packageName,packageNamespace:packageStateNamespace(t.packageName),sourceRoot:t.sourceRoot}]})}function mergeExternalDependencies(...e){return[...new Set(e.flatMap(e=>e??[]))]}export{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace};
|
|
1
|
+
import{posix}from"node:path";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{canonicalSourceSlot}from"#compiler/source-graph.js";import{mountRefNamespace,packageStateNamespace}from"#discover/extensions.js";import"#compiler/normalize-subagent.js";function collectSelectedSourceIds(e){return new Set([...e.selected.values()].map(e=>e.sourceId))}function assertRootOnlyConfig(e,t,n){if(!t&&e.experimental?.workflow?.world!==void 0)throw Error(`Workflow world configuration is only supported on the root agent config. Remove "experimental.workflow.world" from "${n}".`)}function assertApplicationOverlayCanApplyToAllNodes(e){let t=e.find(e=>{let t=canonicalSourceSlot(e);return t===`agent`||t.startsWith(`channels/`)||t.startsWith(`schedules/`)||t.startsWith(`subagents/`)||t.startsWith(`extensions/`)});if(t!==void 0)throw Error(`Application programmatic source registered for all local nodes cannot declare "${t}".`)}function assertUniqueRegistryIds(e){let t=new Set;for(let n of e)for(let e of n.sources.keys()){if(t.has(e))throw Error(`Programmatic agent source id "${e}" is registered more than once.`);t.add(e)}}function assertRootOwnedSpecialTool(e,t){if(e.nodeId!==ROOT_COMPILED_AGENT_NODE_ID)throw Error(`${t} can only be enabled on the root agent.`);assertNonExtensionSpecialTool(e,t)}function assertNonExtensionSpecialTool(e,t){if(e.owner.kind===`extension`)throw Error(`${t} cannot be configured by an extension source.`)}function withExtensionNamespace(e,t){return t.kind===`extension`?{...e,extensionNamespace:t.namespace}:e}function assertUniqueBy(e,t,n){let r=new Set;for(let i of e){let e=t(i);if(r.has(e))throw Error(`Compiled ${n} "${e}" is declared more than once.`);r.add(e)}}function withDiagnosticsSummary(e,t){return e.map(e=>(e.configResolver,{...e,agent:{...e.agent,diagnosticsSummary:t}}))}function expectSubagentDescription(e,t){if(e.description===void 0||e.description.trim().length===0)throw Error(`Subagent "${t.logicalPath}" must define a non-empty description.`);return e.description}function createCompiledRemoteAgent(e){let t=e.source.logicalPath.endsWith(`.ts`)||e.source.logicalPath.endsWith(`.js`)?e.source.logicalPath:posix.join(e.source.logicalPath,`agent.ts`),n=e.source.sourceId,r={backing:e.binding.backing,logicalPath:t,owner:e.owner,usage:e.binding.usage},i={backing:{kind:`resource`,sourcePath:e.source.entryPath},binding:r,description:e.definition.description,entryPath:e.source.entryPath,logicalPath:t,name:e.source.subagentId,nodeId:e.nodeId,owner:e.owner,parentNodeId:e.parentNodeId,path:e.definition.path,rootPath:e.source.rootPath,sourceId:n,sourceKind:`module`};return e.sourceRef.exportName!==void 0&&Object.assign(i,{exportName:e.sourceRef.exportName}),e.definition.outputSchema!==void 0&&Object.assign(i,{outputSchema:e.definition.outputSchema}),e.definition.url!==void 0&&Object.assign(i,{url:e.definition.url}),i}function compileExtensionMounts(e,t){let n=collectSelectedSourceIds(t);return e.resolvedExtensions.flatMap(t=>{let r=e.extensions.find(e=>mountRefNamespace(e.logicalPath)===t.namespace);return r===void 0||!n.has(r.sourceId)?[]:[{externalDependencies:[...t.externalDependencies],mountLogicalPath:r.logicalPath,mountSourceId:r.sourceId,namespace:t.namespace,packageName:t.packageName,packageNamespace:packageStateNamespace(t.packageName),sourceRoot:t.sourceRoot}]})}function mergeExternalDependencies(...e){return[...new Set(e.flatMap(e=>e??[]))]}export{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withDiagnosticsSummary,withExtensionNamespace};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{canonicalSourceSlot,composeAgentModuleCandidates,createAgentModuleBinding,createProgrammaticModuleCandidates,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,isAgentModuleCandidate}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry,memoryWrapperTemplate}from"#framework/sources/registry.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{NodeModuleEvaluationContext,markConfigRuntimeEntries}from"#compiler/module-lifecycle.js";import{assertInstrumentationLayoutConfig}from"#compiler/instrumentation-layout-config.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{applyDefaultToolPolicy,assertFrameworkToolPolicy}from"#compiler/default-tool-policy.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{compileMemoryDefinition,deriveMemorySlot}from"#compiler/normalize-memory.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{createCompiledChannelRoutePlan}from"#compiler/channel-route-plan.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,t={}){let n=[frameworkAgentSourceRegistry,...t.sourceRegistries??[]];assertUniqueRegistryIds(n);let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:n},i=t.diagnostics??[],a=await new AgentGraphCompiler(r,n,i).compileStaticNode({inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,owner:{kind:`application`}}),o=summarizeCompilerDiagnostics(i),s=a.descendants.map(e=>(e.configResolver,{...e,agent:{...e.agent,diagnosticsSummary:o}}));return createCompiledAgentManifest({...a.manifest,diagnosticsSummary:o,subagents:s})}var AgentGraphCompiler=class{context;registries;diagnostics;constructor(e,t,n){this.context=e,this.registries=t,this.diagnostics=n}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId),applyDefaultToolPolicy(t,n);let r=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));r.length>0&&(n={...n,build:{...n.build,externalDependencies:r}});let i=finalizeNodeSourceState(t,r);markConfigRuntimeEntries(n,i.evaluation),assertInstrumentationLayoutConfig(n,i);let a=await this.compileResources(e,i),o=await this.compileChildren(e,i,r),s=createCompiledAgentNodeManifest({...a,config:n,remoteAgents:o.remoteAgents});return{descendants:o.nodes,manifest:s}}async compileChildren(e,t,n){let r=[],i=[],a=collectSelectedSourceIds(t.composed),o=t.projected.subagents.filter(e=>a.has(e.candidate.sourceId));for(let t of o){let a=t.source,o=createCompiledSubagentNodeId(e.nodeId,a.sourceId),s={extensionScope:t.extensionScope??e.extensionScope,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:a.manifest,nodeId:o,owner:t.owner,parentNodeId:e.nodeId},c=await this.createPhaseOneNodeSourceState(s,n),l=normalizeSubagentConfig(c.selectedConfig.definition,`Expected the subagent config export "${c.selectedConfig.source.exportName??`default`}" from "${a.entryPath}" to match the public eve shape.`);if(l.kind===`remote`){assertRemoteAgentDefinitionHasNoLocalPackageEntries(a);let n=c.selectedConfig.source.sourceId;c.evaluation.setBindings({[n]:c.selectedConfig.binding}),c.evaluation.requireRuntimeEntry(n);let r=c.evaluation.finalizeBindings()[n];if(r===void 0)throw Error(`Remote subagent "${o}" has no finalized config binding.`);i.push(createCompiledRemoteAgent({binding:r,definition:l,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,source:a,sourceRef:c.selectedConfig.source}));continue}let u,d;l.kind===`local`?(u=await compileAgentConfig(a.manifest,this.context,{binding:c.selectedConfig.binding,definition:l.definition,source:c.selectedConfig.source}),assertRootOnlyConfig(u,!1,a.manifest.agentId),applyDefaultToolPolicy(c,u)):d=l.build?.externalDependencies;let f=mergeExternalDependencies(n,u?.build?.externalDependencies,d,a.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));u!==void 0&&f.length>0&&(u={...u,build:{...u.build,externalDependencies:f}});let p=finalizeNodeSourceState(c,f);u===void 0?p.evaluation.requireRuntimeEntry(c.selectedConfig.source.sourceId):markConfigRuntimeEntries(u,p.evaluation),u!==void 0&&assertInstrumentationLayoutConfig(u,p);let m=await this.compileResources(s,p),h=await this.compileChildren(s,p,f),g={backing:t.candidate.backing,entryPath:a.entryPath,logicalPath:a.logicalPath,name:a.subagentId,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,rootPath:a.rootPath,sourceId:a.sourceId,sourceKind:`module`},_;_=u===void 0?{...g,agent:createCompiledAgentResources({...m,remoteAgents:h.remoteAgents}),configResolver:{build:l.kind===`dynamic`?l.build:void 0,eventNames:l.kind===`dynamic`?l.eventNames:[],exportName:c.selectedConfig.source.exportName,logicalPath:c.selectedConfig.source.logicalPath,sourceId:c.selectedConfig.source.sourceId,sourceKind:`module`}}:{...g,agent:createCompiledAgentNodeManifest({...m,config:u,remoteAgents:h.remoteAgents}),description:expectSubagentDescription(u,a)},r.push(_,...h.nodes)}return{nodes:r,remoteAgents:i}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...n.candidates,...i].filter(e=>e.backing.kind!==`resource`&&(canonicalSourceSlot(e.logicalPath)===`memory`||canonicalSourceSlot(e.logicalPath).startsWith(`memory/`))).map(e=>{let t=deriveMemorySlot(e.logicalPath);return instantiateProgrammaticTemplate({anchor:e,dependencies:{memory:e},logicalPath:`tools/${t}.ts`,owner:{feature:`memory`,kind:`framework`},parameters:{memoryExportName:e.exportName??`default`,memoryLogicalPath:e.logicalPath,slot:t},template:memoryWrapperTemplate})}),o=[...r,...n.candidates,...a,...i],s=composeAgentModuleCandidates(o),c=projectSelectedSources({candidates:s.selected.values(),resources:n.resources});return{composed:s,orderedCandidates:o,projected:n,sourcesBySourceId:new Map(c.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t),r=new NodeModuleEvaluationContext(this.registries);return r.setBindings(Object.fromEntries([...n.composed.selected.values()].filter(isAgentModuleCandidate).map(e=>[e.sourceId,createAgentModuleBinding(e)]))),{evaluation:r,graph:n,selectedConfig:await this.loadSelectedConfig(n,r)}}async loadSelectedConfig(e,t){let n=e.composed.selected.get(`agent`);if(n===void 0||!isAgentModuleCandidate(n))throw Error(`Every local agent node requires a selected module-backed agent.ts source.`);let r=createAgentModuleBinding(n),i=e.sourcesBySourceId.get(n.sourceId);if(i?.source.sourceKind!==`module`)throw Error(`Selected agent config source "${n.sourceId}" was not projected.`);let a=i.source;return{binding:r,candidate:n,definition:await loadModuleBackedDefinition({binding:r,kind:`agent config`,loadNamespace:t.loadNamespace,source:a}),source:a}}async compileResources(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m,h,g,_=collectSelectedSourceIds(t.composed),v=t.evaluation.loadNamespace;for(let y of t.orderedCandidates){if(!_.has(y.sourceId))continue;let b=t.sourcesBySourceId.get(y.sourceId);if(b===void 0)continue;let x=t.bindings[y.sourceId],S={binding:x,loadNamespace:v,owner:y.owner};switch(b.kind){case`config`:case`extension`:break;case`channel`:{let n=await compileChannelDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});n.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:y,composed:t.composed}),delete t.bindings[y.sourceId],_.delete(y.sourceId)):p.push(...n.definitions);break}case`connection`:{let n=await compileConnectionDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});n.kind===`connection`?c.push(n.definition):l.push(withExtensionNamespace(n.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId);break}case`hook`:d.push(await compileHookEntry(b.source,{binding:x,loadNamespace:v})),t.evaluation.requireRuntimeEntry(y.sourceId);break;case`instructions`:{let n=await compileInstructionsEntry(e.manifest.agentRoot,b.source,S);n.kind===`instructions`?o.push(n.definition):(s.push(n.definition),t.evaluation.requireRuntimeEntry(y.sourceId));break}case`instrumentation`:h=b.source,t.evaluation.requireRuntimeEntry(y.sourceId);break;case`memory`:u.push(await compileMemoryDefinition(b.source,{binding:x,loadNamespace:v})),t.evaluation.requireRuntimeEntry(y.sourceId);break;case`sandbox`:m=await compileSandboxDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v}),m.inheritsParent||t.evaluation.requireRuntimeEntry(y.sourceId);break;case`schedule`:{let n=await compileScheduleDefinition(e.manifest.agentRoot,b.source,S);f.push(n),n.sourceKind===`module`&&n.hasRun&&t.evaluation.requireRuntimeEntry(y.sourceId);break}case`skill`:{let n=await compileSkillSource(e.manifest.agentRoot,b.source,S);n.kind===`skill`?i.push(n.definition):(a.push(withExtensionNamespace(n.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId));break}case`tool`:{let i=await compileToolEntry(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});assertFrameworkToolPolicy(y,i),i.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:y,composed:t.composed}),delete t.bindings[y.sourceId],_.delete(y.sourceId)):i.kind===`tool`?(n.push(i.definition),i.definition.hasExecute&&t.evaluation.requireRuntimeEntry(y.sourceId)):i.kind===`dynamic-tool`?(r.push(withExtensionNamespace(i.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId)):i.kind===`workflow-tool`?(assertRootOwnedSpecialTool(y,`Workflow`),g={...b.source,maxSubagents:i.maxSubagents}):(assertNonExtensionSpecialTool(y,`Web search`),n.push(i.definition));break}}}if(m===void 0)throw Error(`Agent node "${e.nodeId}" has no selected sandbox source.`);assertUniqueBy(n,e=>e.name,`tool name`),assertUniqueBy(r,e=>e.slug,`dynamic tool slug`),assertUniqueBy(c,e=>e.connectionName,`connection name`),assertUniqueBy(l,e=>e.slug,`dynamic connection slug`),assertUniqueBy(i,e=>e.name,`skill name`);let y=createCompiledChannelRoutePlan({bindings:t.bindings,channels:p,diagnostics:this.diagnostics,nodeId:e.nodeId,sources:Object.fromEntries(t.orderedCandidates.map(e=>[e.sourceId,describeAgentSourceCandidate(e)]))});for(let e of y.effective)t.evaluation.requireRuntimeEntry(e.sourceId);let b=compileExtensionMounts(e.manifest,t.composed);for(let e of b)t.evaluation.requireRuntimeEntry(e.mountSourceId);let x=t.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,bindings:x,channelRoutes:y,connections:c,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicConnections:l,dynamicInstructions:s,dynamicSkills:a,dynamicTools:r,extensionMounts:b,hooks:d,memories:u,instructions:o,instrumentation:h,sandbox:m,sandboxWorkspaces:e.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:f,skills:i,sourceComposition:t.composed.composition,tools:n,workflowTool:g})}};export{compileAgentManifest};
|
|
1
|
+
import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,createCompiledSubagentNodeId}from"#compiler/manifest.js";import{summarizeCompilerDiagnostics}from"#compiler/diagnostics.js";import{canonicalSourceSlot,composeAgentModuleCandidates,createAgentModuleBinding,createProgrammaticModuleCandidates,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,isAgentModuleCandidate}from"#compiler/source-graph.js";import{frameworkAgentSourceRegistry,memoryWrapperTemplate}from"#framework/sources/registry.js";import{assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,collectSelectedSourceIds,compileExtensionMounts,createCompiledRemoteAgent,expectSubagentDescription,mergeExternalDependencies,withDiagnosticsSummary,withExtensionNamespace}from"#compiler/normalize-manifest-helpers.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{assertRemoteAgentDefinitionHasNoLocalPackageEntries,normalizeSubagentConfig}from"#compiler/normalize-subagent.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{NodeModuleEvaluationContext,markConfigRuntimeEntries}from"#compiler/module-lifecycle.js";import{assertInstrumentationLayoutConfig}from"#compiler/instrumentation-layout-config.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{applyDefaultToolPolicy,assertFrameworkToolPolicy}from"#compiler/default-tool-policy.js";import{resolveWorkspaceSubagentDefinition}from"#compiler/resolve-workspace-subagent.js";import{workspaceSubagentName}from"#public/definitions/workspace-agent.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileInstructionsEntry}from"#compiler/normalize-instructions.js";import{compileMemoryDefinition,deriveMemorySlot}from"#compiler/normalize-memory.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileToolEntry}from"#compiler/normalize-tool.js";import{createCompiledChannelRoutePlan}from"#compiler/channel-route-plan.js";import{finalizeNodeSourceState}from"#compiler/node-source-state.js";import{projectAgentSources,projectSelectedSources}from"#compiler/project-sources.js";async function compileAgentManifest(e,t={}){let n=[frameworkAgentSourceRegistry,...t.sourceRegistries??[]];assertUniqueRegistryIds(n);let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot),registries:n},i=t.diagnostics??[],a=await new AgentGraphCompiler(r,n,i).compileStaticNode({inheritedExternalDependencies:[],isRoot:!0,layer:`application`,manifest:e,nodeId:ROOT_COMPILED_AGENT_NODE_ID,owner:{kind:`application`}}),o=summarizeCompilerDiagnostics(i),s=withDiagnosticsSummary(a.descendants,o);return createCompiledAgentManifest({...a.manifest,diagnosticsSummary:o,subagents:s})}var AgentGraphCompiler=class{context;registries;diagnostics;constructor(e,t,n){this.context=e,this.registries=t,this.diagnostics=n}async compileStaticNode(e){let t=await this.createPhaseOneNodeSourceState(e,e.inheritedExternalDependencies),n=await compileAgentConfig(e.manifest,this.context,{binding:t.selectedConfig.binding,definition:t.selectedConfig.definition,source:t.selectedConfig.source});assertRootOnlyConfig(n,e.isRoot,e.manifest.agentId),applyDefaultToolPolicy(t,n);let r=mergeExternalDependencies(e.inheritedExternalDependencies,n.build?.externalDependencies,e.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));r.length>0&&(n={...n,build:{...n.build,externalDependencies:r}});let i=finalizeNodeSourceState(t,r);markConfigRuntimeEntries(n,i.evaluation),assertInstrumentationLayoutConfig(n,i);let a=await this.compileResources(e,i),o=await this.compileChildren(e,i,r),s=createCompiledAgentNodeManifest({...a,config:n,remoteAgents:o.remoteAgents});return{descendants:o.nodes,manifest:s}}async compileChildren(e,t,n){let r=[],i=[],a=collectSelectedSourceIds(t.composed),o=t.projected.subagents.filter(e=>a.has(e.candidate.sourceId));for(let t of o){let a=t.source,o=createCompiledSubagentNodeId(e.nodeId,a.sourceId),s={extensionScope:t.extensionScope??e.extensionScope,inheritedExternalDependencies:n,isRoot:!1,layer:t.candidate.layer,manifest:a.manifest,nodeId:o,owner:t.owner,parentNodeId:e.nodeId},c=await this.createPhaseOneNodeSourceState(s,n),l=normalizeSubagentConfig(c.selectedConfig.definition,`Expected the subagent config export "${c.selectedConfig.source.exportName??`default`}" from "${a.entryPath}" to match the public eve shape.`);if(l.kind===`remote`){let n=workspaceSubagentName(c.selectedConfig.definition),r=n===void 0?l:await resolveWorkspaceSubagentDefinition({definition:l,name:n,registries:this.registries,source:a});assertRemoteAgentDefinitionHasNoLocalPackageEntries(a);let s=c.selectedConfig.source.sourceId;c.evaluation.setBindings({[s]:c.selectedConfig.binding}),c.evaluation.requireRuntimeEntry(s);let u=c.evaluation.finalizeBindings()[s];if(u===void 0)throw Error(`Remote subagent "${o}" has no finalized config binding.`);i.push(createCompiledRemoteAgent({binding:u,definition:r,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,source:a,sourceRef:c.selectedConfig.source}));continue}let u,d;l.kind===`local`?(u=await compileAgentConfig(a.manifest,this.context,{binding:c.selectedConfig.binding,definition:l.definition,source:c.selectedConfig.source}),assertRootOnlyConfig(u,!1,a.manifest.agentId),applyDefaultToolPolicy(c,u)):d=l.build?.externalDependencies;let f=mergeExternalDependencies(n,u?.build?.externalDependencies,d,a.manifest.resolvedExtensions.flatMap(e=>e.externalDependencies));u!==void 0&&f.length>0&&(u={...u,build:{...u.build,externalDependencies:f}});let p=finalizeNodeSourceState(c,f);u===void 0?p.evaluation.requireRuntimeEntry(c.selectedConfig.source.sourceId):markConfigRuntimeEntries(u,p.evaluation),u!==void 0&&assertInstrumentationLayoutConfig(u,p);let m=await this.compileResources(s,p),h=await this.compileChildren(s,p,f),g={backing:t.candidate.backing,entryPath:a.entryPath,logicalPath:a.logicalPath,name:a.subagentId,nodeId:o,owner:t.owner,parentNodeId:e.nodeId,rootPath:a.rootPath,sourceId:a.sourceId,sourceKind:`module`},_;_=u===void 0?{...g,agent:createCompiledAgentResources({...m,remoteAgents:h.remoteAgents}),configResolver:{build:l.kind===`dynamic`?l.build:void 0,eventNames:l.kind===`dynamic`?l.eventNames:[],exportName:c.selectedConfig.source.exportName,logicalPath:c.selectedConfig.source.logicalPath,sourceId:c.selectedConfig.source.sourceId,sourceKind:`module`}}:{...g,agent:createCompiledAgentNodeManifest({...m,config:u,remoteAgents:h.remoteAgents}),description:expectSubagentDescription(u,a)},r.push(_,...h.nodes)}return{nodes:r,remoteAgents:i}}composeNodeSources(e,t){let n=projectAgentSources({externalDependencies:t,extensionScope:e.extensionScope,layer:e.layer,manifest:e.manifest,nodeId:e.nodeId,owner:e.owner}),r=[],i=[];for(let t of this.registries){let n=t===frameworkAgentSourceRegistry;for(let a of t.registrations){if(a.applyTo===`root`&&!e.isRoot)continue;!n&&a.applyTo===`all-local-nodes`&&assertApplicationOverlayCanApplyToAllNodes(a.source.modules.map(e=>e.logicalPath));let t=createProgrammaticModuleCandidates({layer:n?`framework-default`:`application`,nodeId:e.nodeId,owner:n?{feature:a.source.id,kind:`framework`}:{kind:`application`},registration:a});(n?r:i).push(...t)}}let a=[...n.candidates,...i].filter(e=>e.backing.kind!==`resource`&&(canonicalSourceSlot(e.logicalPath)===`memory`||canonicalSourceSlot(e.logicalPath).startsWith(`memory/`))).map(e=>{let t=deriveMemorySlot(e.logicalPath);return instantiateProgrammaticTemplate({anchor:e,dependencies:{memory:e},logicalPath:`tools/${t}.ts`,owner:{feature:`memory`,kind:`framework`},parameters:{memoryExportName:e.exportName??`default`,memoryLogicalPath:e.logicalPath,slot:t},template:memoryWrapperTemplate})}),o=[...r,...n.candidates,...a,...i],s=composeAgentModuleCandidates(o),c=projectSelectedSources({candidates:s.selected.values(),resources:n.resources});return{composed:s,orderedCandidates:o,projected:n,sourcesBySourceId:new Map(c.map(e=>[e.candidate.sourceId,e])),subagentsBySourceId:new Map(n.subagents.map(e=>[e.candidate.sourceId,e]))}}async createPhaseOneNodeSourceState(e,t){let n=this.composeNodeSources(e,t),r=new NodeModuleEvaluationContext(this.registries);return r.setBindings(Object.fromEntries([...n.composed.selected.values()].filter(isAgentModuleCandidate).map(e=>[e.sourceId,createAgentModuleBinding(e)]))),{evaluation:r,graph:n,selectedConfig:await this.loadSelectedConfig(n,r)}}async loadSelectedConfig(e,t){let n=e.composed.selected.get(`agent`);if(n===void 0||!isAgentModuleCandidate(n))throw Error(`Every local agent node requires a selected module-backed agent.ts source.`);let r=createAgentModuleBinding(n),i=e.sourcesBySourceId.get(n.sourceId);if(i?.source.sourceKind!==`module`)throw Error(`Selected agent config source "${n.sourceId}" was not projected.`);let a=i.source;return{binding:r,candidate:n,definition:await loadModuleBackedDefinition({binding:r,kind:`agent config`,loadNamespace:t.loadNamespace,source:a}),source:a}}async compileResources(e,t){let n=[],r=[],i=[],a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m,h,g,_=collectSelectedSourceIds(t.composed),v=t.evaluation.loadNamespace;for(let y of t.orderedCandidates){if(!_.has(y.sourceId))continue;let b=t.sourcesBySourceId.get(y.sourceId);if(b===void 0)continue;let x=t.bindings[y.sourceId],S={binding:x,loadNamespace:v,owner:y.owner};switch(b.kind){case`config`:case`extension`:break;case`channel`:{let n=await compileChannelDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});n.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:y,composed:t.composed}),delete t.bindings[y.sourceId],_.delete(y.sourceId)):p.push(...n.definitions);break}case`connection`:{let n=await compileConnectionDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});n.kind===`connection`?c.push(n.definition):l.push(withExtensionNamespace(n.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId);break}case`hook`:d.push(await compileHookEntry(b.source,{binding:x,loadNamespace:v})),t.evaluation.requireRuntimeEntry(y.sourceId);break;case`instructions`:{let n=await compileInstructionsEntry(e.manifest.agentRoot,b.source,S);n.kind===`instructions`?o.push(n.definition):(s.push(n.definition),t.evaluation.requireRuntimeEntry(y.sourceId));break}case`instrumentation`:h=b.source,t.evaluation.requireRuntimeEntry(y.sourceId);break;case`memory`:u.push(await compileMemoryDefinition(b.source,{binding:x,loadNamespace:v})),t.evaluation.requireRuntimeEntry(y.sourceId);break;case`sandbox`:m=await compileSandboxDefinition(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v}),m.inheritsParent||t.evaluation.requireRuntimeEntry(y.sourceId);break;case`schedule`:{let n=await compileScheduleDefinition(e.manifest.agentRoot,b.source,S);f.push(n),n.sourceKind===`module`&&n.hasRun&&t.evaluation.requireRuntimeEntry(y.sourceId);break}case`skill`:{let n=await compileSkillSource(e.manifest.agentRoot,b.source,S);n.kind===`skill`?i.push(n.definition):(a.push(withExtensionNamespace(n.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId));break}case`tool`:{let i=await compileToolEntry(e.manifest.agentRoot,b.source,{binding:x,loadNamespace:v});assertFrameworkToolPolicy(y,i),i.kind===`disabled`?(t.composed=disableComposedCandidate({candidate:y,composed:t.composed}),delete t.bindings[y.sourceId],_.delete(y.sourceId)):i.kind===`tool`?(n.push(i.definition),i.definition.hasExecute&&t.evaluation.requireRuntimeEntry(y.sourceId)):i.kind===`dynamic-tool`?(r.push(withExtensionNamespace(i.definition,y.owner)),t.evaluation.requireRuntimeEntry(y.sourceId)):i.kind===`workflow-tool`?(assertRootOwnedSpecialTool(y,`Workflow`),g={...b.source,maxSubagents:i.maxSubagents}):(assertNonExtensionSpecialTool(y,`Web search`),n.push(i.definition));break}}}if(m===void 0)throw Error(`Agent node "${e.nodeId}" has no selected sandbox source.`);assertUniqueBy(n,e=>e.name,`tool name`),assertUniqueBy(r,e=>e.slug,`dynamic tool slug`),assertUniqueBy(c,e=>e.connectionName,`connection name`),assertUniqueBy(l,e=>e.slug,`dynamic connection slug`),assertUniqueBy(i,e=>e.name,`skill name`);let y=createCompiledChannelRoutePlan({bindings:t.bindings,channels:p,diagnostics:this.diagnostics,nodeId:e.nodeId,sources:Object.fromEntries(t.orderedCandidates.map(e=>[e.sourceId,describeAgentSourceCandidate(e)]))});for(let e of y.effective)t.evaluation.requireRuntimeEntry(e.sourceId);let b=compileExtensionMounts(e.manifest,t.composed);for(let e of b)t.evaluation.requireRuntimeEntry(e.mountSourceId);let x=t.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot:e.manifest.agentRoot,appRoot:e.manifest.appRoot,bindings:x,channelRoutes:y,connections:c,diagnosticsSummary:summarizeCompilerDiagnostics(this.diagnostics),dynamicConnections:l,dynamicInstructions:s,dynamicSkills:a,dynamicTools:r,extensionMounts:b,hooks:d,memories:u,instructions:o,instrumentation:h,sandbox:m,sandboxWorkspaces:e.manifest.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:f,skills:i,sourceComposition:t.composed.composition,tools:n,workflowTool:g})}};export{compileAgentManifest};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LocalSubagentSourceRef } from "#discover/manifest.js";
|
|
2
|
+
import type { NormalizedSubagentConfig } from "#compiler/normalize-subagent.js";
|
|
3
|
+
import type { AgentSourceRegistry } from "#compiler/source-graph.js";
|
|
4
|
+
export declare function resolveWorkspaceSubagentDefinition(input: {
|
|
5
|
+
readonly definition: Extract<NormalizedSubagentConfig, {
|
|
6
|
+
readonly kind: "remote";
|
|
7
|
+
}>;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly registries: readonly AgentSourceRegistry[];
|
|
10
|
+
readonly source: LocalSubagentSourceRef;
|
|
11
|
+
}): Promise<Extract<NormalizedSubagentConfig, {
|
|
12
|
+
readonly kind: "remote";
|
|
13
|
+
}>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createCompiledBindingNamespaceLoader}from"#compiler/load-binding-namespace.js";import{discoverAgent}from"#discover/discover-agent.js";import{findEveProjectContext}from"#internal/project-context.js";import{normalizeAgentDefinition}from"#internal/authored-definition/core.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function resolveWorkspaceSubagentDefinition(e){let t=await findEveProjectContext(e.source.rootPath);if(t?.kind!==`workspace-member`)throw Error(`Workspace subagent "${e.source.logicalPath}" must be authored by an agent workspace member.`);let n=t.workspace.members.find(t=>t.name===e.name);if(n===void 0)throw Error(`Workspace subagent "${e.source.logicalPath}" targets unknown workspace member ${JSON.stringify(e.name)}.`);if(e.definition.description.trim().length>0)return e.definition;let{resolveDiscoveryProject:r}=await import(`#discover/project.js`),i=await r(n.appRoot),a=(await discoverAgent({agentRoot:i.agentRoot,appRoot:i.appRoot})).manifest.configModule;if(a===void 0)throw Error(`Workspace member ${JSON.stringify(e.name)} has no agent config module.`);let o={backing:{externalDependencies:[],kind:`filesystem`,sourcePath:`${i.agentRoot}/${a.logicalPath}`},logicalPath:a.logicalPath,owner:{kind:`application`}},s=normalizeAgentDefinition(await loadModuleBackedDefinition({binding:o,kind:`agent config`,loadNamespace:createCompiledBindingNamespaceLoader({bindings:{[a.sourceId]:o},registries:e.registries}),source:a}),`Expected workspace member ${JSON.stringify(e.name)} agent config to match the public eve shape.`);if(s.description===void 0||s.description.trim().length===0)throw Error(`Workspace member ${JSON.stringify(e.name)} must define a non-empty description.`);return{...e.definition,description:s.description}}export{resolveWorkspaceSubagentDefinition};
|
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable session snapshot migrations.
|
|
3
|
-
*
|
|
4
|
-
* ## Adding a new snapshot version
|
|
5
|
-
*
|
|
6
|
-
* When a shape change cannot be expressed as a purely additive field:
|
|
7
|
-
*
|
|
8
|
-
* 1. Bump `DURABLE_SESSION_VERSION` in `durable-session-store.ts`.
|
|
9
|
-
* 2. Update {@link DurableSessionSnapshot}, {@link DurableSession},
|
|
10
|
-
* `projectToDurableSession`, and `hydrateDurableSession`.
|
|
11
|
-
* 3. Add `snapshot-v{N}-to-v{N+1}.ts` exporting one
|
|
12
|
-
* {@link VersionMigration} (`from: N`, `to: N + 1`, pure
|
|
13
|
-
* function, stamps the new `version`).
|
|
14
|
-
* 4. Append the migration to {@link snapshotMigrations}.
|
|
15
|
-
* 5. Cover it in `snapshot.test.ts`.
|
|
16
|
-
*/
|
|
17
1
|
import type { DurableSessionSnapshot } from "#execution/durable-session-store.js";
|
|
18
2
|
/**
|
|
19
3
|
* Migrates a {@link DurableSessionSnapshot} up to
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runMigrationChain}from"./chain.js";import{DURABLE_SESSION_VERSION}from"#execution/durable-session-store.js";const snapshotMigrations=[];function migrateDurableSessionSnapshot(e){
|
|
1
|
+
import{runMigrationChain}from"./chain.js";import{validateHarnessModelMessages}from"#harness/messages.js";import{DURABLE_SESSION_VERSION}from"#execution/durable-session-store.js";const snapshotMigrations=[];function migrateDurableSessionSnapshot(e){let t=runMigrationChain({label:`durable session snapshot`,migrations:snapshotMigrations,targetVersion:DURABLE_SESSION_VERSION,value:e}),n=t.session.history.map(e=>e.role===`user`&&!(`kind`in e)?{...e,kind:`legacy.unknown`}:e);return{...t,session:{...t.session,history:validateHarnessModelMessages(n)}}}export{migrateDurableSessionSnapshot};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.54.
|
|
1
|
+
import{sleep}from"#compiled/@workflow/core/index.js";async function executeSleepTool(e){"use workflow";return await sleep(Math.ceil(e.seconds*1e3)),{waitedSeconds:e.seconds}}executeSleepTool.workflowId=`workflow//eve@0.54.3//executeSleepTool`;export{executeSleepTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createFrameworkUserMessage,isFrameworkUserMessage}from"#harness/messages.js";import{generateText}from"ai";import{COMPACTION_CHECKPOINT_MARKER,COMPACTION_PROMPT_ENVELOPE,COMPACTION_RESUMPTION_MESSAGE,TRANSCRIPT_PAYLOAD_LIMIT,createCompactionPrompt,sliceUtf16Safe,stubContentOutputFileParts}from"#harness/compaction-prompt.js";import{estimateTokens}from"#harness/token-estimate.js";const COMPACTION_PROMPT_OVERHEAD_TOKENS=estimateTokens([{content:COMPACTION_PROMPT_ENVELOPE.system,role:`system`},createFrameworkUserMessage(`context.compaction`,COMPACTION_PROMPT_ENVELOPE.prompt)]);function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return e.length>0&&getInputTokenCount(e,t)+COMPACTION_PROMPT_OVERHEAD_TOKENS>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}const COMPACTION_HEURISTICS=[toolResultCapHeuristic];function toolResultCapHeuristic(e){let t=withResumptionGuard([...e.previousCheckpoint===void 0?[]:[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:e.previousCheckpoint,role:`assistant`}],...capToolResults(e.older),...e.recent],e.conversation,e.config.threshold);return evaluateThreshold(t,e.config,`should-compact`,e.tokenEstimateAdjustment).type===`within-limit`?{messages:t,type:`within-limit`}:{type:`insufficient`}}function evaluateThreshold(e,t,n,r=0){let i=n===`should-compact`?COMPACTION_PROMPT_OVERHEAD_TOKENS:0,a=estimateTokens(e)+i+r;return{estimatedTokens:a,type:a<=t.threshold?`within-limit`:`over-limit`}}async function compactMessages(e,t,n,r,i,a,o,s=!1){let{conversation:c,previousCheckpoint:l}=extractPreviousCheckpoint(e),u=selectRecentWindowSize(c,s?{...n,recentWindowSize:1}:n);if(!s){let{older:t,recent:r}=splitMessagesForCompaction(c,u);if(t.length===0&&l===void 0)return keepNonToolResultMessages(r);let i=Math.max(0,getInputTokenCount(e,n)-estimateTokens(e));for(let e of COMPACTION_HEURISTICS){let a=e({config:n,conversation:c,older:t,previousCheckpoint:l,recent:r,tokenEstimateAdjustment:i});if(a.type===`within-limit`)return a.messages}}for(;;){let{older:e,recent:s}=splitMessagesForCompaction(c,u),d=createCompactionPrompt({messages:e,previousCheckpoint:l,transcriptBudgetTokens:n.threshold}),f=await generateText({abortSignal:o,headers:a,messages:[createFrameworkUserMessage(`context.compaction`,d.prompt)],model:t,providerOptions:r,system:d.system,telemetry:i?{...i,functionId:`eve.compaction`}:void 0,temperature:0});if(f.text.trim().length===0)throw Error(`The compaction model returned an empty summary. Finish reason: ${f.finishReason}.`);let p=[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:f.text,role:`assistant`}],m=withResumptionGuard([...p,...s],c,n.threshold);if(evaluateThreshold(m,n,`estimate`).type===`within-limit`)return m;let h=withResumptionGuard([...p,...keepNonToolResultMessages(s)],c,n.threshold);if(evaluateThreshold(h,n,`estimate`).type===`within-limit`||u===0)return h;--u}}function capToolResults(e){return e.map(e=>{if(e.role!==`tool`||typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-result`)return e;let n=stubContentOutputFileParts(e.output),r=JSON.stringify(n)??``;return r.length<=TRANSCRIPT_PAYLOAD_LIMIT?n===e.output?e:(t=!0,{...e,output:n}):(t=!0,{...e,output:{type:`text`,value:`[Truncated by eve: tool result reduced during context compaction. Re-run the tool if you need the full output.]\n\n${sliceUtf16Safe(r,TRANSCRIPT_PAYLOAD_LIMIT)}`}})});return t?{...e,content:n}:e})}function withResumptionGuard(e,t,n){let r=e.at(-1)?.role,i=findLastRealUserMessage(t),a=i!==void 0&&e.some(e=>e.role===`user`&&e.content===i.content);return r!==void 0&&r!==`assistant`?r===`tool`&&i!==void 0&&!a&&estimateTokens([i])<=n?[...e,i]:e:[...e,i!==void 0&&!a?i:createFrameworkUserMessage(`execution.continuation`,COMPACTION_RESUMPTION_MESSAGE)]}function findLastRealUserMessage(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`&&typeof n.content==`string`&&!isFrameworkUserMessage(n))return n}}function extractPreviousCheckpoint(e){let t=e[0],n=e[1];return t?.role!==`user`||t.content!==COMPACTION_CHECKPOINT_MARKER||n?.role!==`assistant`?{conversation:[...e],previousCheckpoint:void 0}:{conversation:e.slice(2),previousCheckpoint:assistantMessageText(n)}}function keepNonToolResultMessages(e){let t=[];for(let n of e)if(n.role!==`tool`){if(n.role===`assistant`){let e=assistantMessageText(n);e.length>0&&t.push({content:e,role:`assistant`});continue}t.push(n)}return t}function assistantMessageText(e){return typeof e.content==`string`?e.content.trim():e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim()}function selectRecentWindowSize(e,t){let n=Math.min(t.recentWindowSize,Math.max(e.length-1,0)),r=resolveCompactionSummaryReserve(t),i=0,a=0;for(let o=e.length-1;o>=0&&i<n;--o){let n=e[o];if(n===void 0)continue;let s=estimateTokens([n]);if(a+s+r>t.threshold)break;a+=s,i+=1}return i}function resolveCompactionSummaryReserve(e){return Math.min(2048,Math.max(64,Math.floor(e.threshold/4)))}function splitMessagesForCompaction(e,t){if(t<=0)return{older:[...e],recent:[]};let n=e.length-t;for(;n<e.length&&e[n]?.role===`tool`;)n+=1;return{older:e.slice(0,n),recent:e.slice(n)}}export{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact};
|
|
1
|
+
import{createFrameworkUserMessage,isFrameworkUserMessage,isUserModelMessage}from"#harness/messages.js";import{generateText}from"ai";import{COMPACTION_CHECKPOINT_MARKER,COMPACTION_PROMPT_ENVELOPE,COMPACTION_RESUMPTION_MESSAGE,TRANSCRIPT_PAYLOAD_LIMIT,createCompactionPrompt,sliceUtf16Safe,stubContentOutputFileParts}from"#harness/compaction-prompt.js";import{estimateTokens}from"#harness/token-estimate.js";const COMPACTION_PROMPT_OVERHEAD_TOKENS=estimateTokens([{content:COMPACTION_PROMPT_ENVELOPE.system,role:`system`},createFrameworkUserMessage(`context.compaction`,COMPACTION_PROMPT_ENVELOPE.prompt)]);function getInputTokenCount(e,t){let n=t.lastKnownInputTokens,r=t.lastKnownPromptMessageCount;return n===void 0||r===void 0||!Number.isInteger(r)||r<0||r>e.length?estimateTokens(e):n+estimateTokens(e.slice(r))}function shouldCompact(e,t){return e.length>0&&getInputTokenCount(e,t)+COMPACTION_PROMPT_OVERHEAD_TOKENS>t.threshold}async function resolveCompactionModel(e){let t=e.compactionModelReference??e.modelReference;return{model:t===e.modelReference?e.model:await e.resolveModel(t),providerOptions:t.providerOptions}}const COMPACTION_HEURISTICS=[toolResultCapHeuristic];function toolResultCapHeuristic(e){let t=withResumptionGuard([...e.previousCheckpoint===void 0?[]:[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:e.previousCheckpoint,role:`assistant`}],...capToolResults(e.older),...e.recent],e.conversation,e.config.threshold);return evaluateThreshold(t,e.config,`should-compact`,e.tokenEstimateAdjustment).type===`within-limit`?{messages:t,type:`within-limit`}:{type:`insufficient`}}function evaluateThreshold(e,t,n,r=0){let i=n===`should-compact`?COMPACTION_PROMPT_OVERHEAD_TOKENS:0,a=estimateTokens(e)+i+r;return{estimatedTokens:a,type:a<=t.threshold?`within-limit`:`over-limit`}}async function compactMessages(e,t,n,r,i,a,o,s=!1){let{conversation:c,previousCheckpoint:l}=extractPreviousCheckpoint(e),u=selectRecentWindowSize(c,s?{...n,recentWindowSize:1}:n);if(!s){let{older:t,recent:r}=splitMessagesForCompaction(c,u);if(t.length===0&&l===void 0)return keepNonToolResultMessages(r);let i=Math.max(0,getInputTokenCount(e,n)-estimateTokens(e));for(let e of COMPACTION_HEURISTICS){let a=e({config:n,conversation:c,older:t,previousCheckpoint:l,recent:r,tokenEstimateAdjustment:i});if(a.type===`within-limit`)return a.messages}}for(;;){let{older:e,recent:s}=splitMessagesForCompaction(c,u),d=createCompactionPrompt({messages:e,previousCheckpoint:l,transcriptBudgetTokens:n.threshold}),f=await generateText({abortSignal:o,headers:a,messages:[createFrameworkUserMessage(`context.compaction`,d.prompt)],model:t,providerOptions:r,system:d.system,telemetry:i?{...i,functionId:`eve.compaction`}:void 0,temperature:0});if(f.text.trim().length===0)throw Error(`The compaction model returned an empty summary. Finish reason: ${f.finishReason}.`);let p=[createFrameworkUserMessage(`context.compaction`,COMPACTION_CHECKPOINT_MARKER),{content:f.text,role:`assistant`}],m=withResumptionGuard([...p,...s],c,n.threshold);if(evaluateThreshold(m,n,`estimate`).type===`within-limit`)return m;let h=withResumptionGuard([...p,...keepNonToolResultMessages(s)],c,n.threshold);if(evaluateThreshold(h,n,`estimate`).type===`within-limit`||u===0)return h;--u}}function capToolResults(e){return e.map(e=>{if(e.role!==`tool`||typeof e.content==`string`)return e;let t=!1,n=e.content.map(e=>{if(e.type!==`tool-result`)return e;let n=stubContentOutputFileParts(e.output),r=JSON.stringify(n)??``;return r.length<=TRANSCRIPT_PAYLOAD_LIMIT?n===e.output?e:(t=!0,{...e,output:n}):(t=!0,{...e,output:{type:`text`,value:`[Truncated by eve: tool result reduced during context compaction. Re-run the tool if you need the full output.]\n\n${sliceUtf16Safe(r,TRANSCRIPT_PAYLOAD_LIMIT)}`}})});return t?{...e,content:n}:e})}function withResumptionGuard(e,t,n){let r=e.at(-1)?.role,i=findLastRealUserMessage(t),a=i!==void 0&&e.some(e=>e.role===`user`&&e.content===i.content);return r!==void 0&&r!==`assistant`?r===`tool`&&i!==void 0&&!a&&estimateTokens([i])<=n?[...e,i]:e:[...e,i!==void 0&&!a?i:createFrameworkUserMessage(`execution.continuation`,COMPACTION_RESUMPTION_MESSAGE)]}function findLastRealUserMessage(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role===`user`&&typeof n.content==`string`&&!(isFrameworkUserMessage(n)||isUserModelMessage(n)&&n.kind===`legacy.unknown`))return n}}function extractPreviousCheckpoint(e){let t=e[0],n=e[1];return t?.role!==`user`||t.content!==COMPACTION_CHECKPOINT_MARKER||n?.role!==`assistant`?{conversation:[...e],previousCheckpoint:void 0}:{conversation:e.slice(2),previousCheckpoint:assistantMessageText(n)}}function keepNonToolResultMessages(e){let t=[];for(let n of e)if(n.role!==`tool`){if(n.role===`assistant`){let e=assistantMessageText(n);e.length>0&&t.push({content:e,role:`assistant`});continue}t.push(n)}return t}function assistantMessageText(e){return typeof e.content==`string`?e.content.trim():e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim()}function selectRecentWindowSize(e,t){let n=Math.min(t.recentWindowSize,Math.max(e.length-1,0)),r=resolveCompactionSummaryReserve(t),i=0,a=0;for(let o=e.length-1;o>=0&&i<n;--o){let n=e[o];if(n===void 0)continue;let s=estimateTokens([n]);if(a+s+r>t.threshold)break;a+=s,i+=1}return i}function resolveCompactionSummaryReserve(e){return Math.min(2048,Math.max(64,Math.floor(e.threshold/4)))}function splitMessagesForCompaction(e,t){if(t<=0)return{older:[...e],recent:[]};let n=e.length-t;for(;n<e.length&&e[n]?.role===`tool`;)n+=1;return{older:e.slice(0,n),recent:e.slice(n)}}export{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact};
|
|
@@ -4,7 +4,7 @@ import type { StepInput } from "#harness/types.js";
|
|
|
4
4
|
/** Reason a framework-authored user-role message was added to model history. */
|
|
5
5
|
export type FrameworkMessageKind = "context.instruction" | "context.state" | "context.compaction" | "memory.load" | "execution.background_task" | "execution.continuation" | "execution.retry";
|
|
6
6
|
/** Semantic classification for every user-role message in model history. */
|
|
7
|
-
export type UserMessageKind = "user" | FrameworkMessageKind;
|
|
7
|
+
export type UserMessageKind = "user" | "legacy.unknown" | FrameworkMessageKind;
|
|
8
8
|
/** A user-role message that is safe to retain in framework model history. */
|
|
9
9
|
export type UserModelMessage = Extract<ModelMessage, {
|
|
10
10
|
readonly role: "user";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{attachClientContext,readClientContext}from"#internal/client-context.js";function createUserMessage(e,t,n){let r={content:t,kind:e,role:`user`};return n===void 0?r:{...r,metadata:n}}function createFrameworkUserMessage(e,t,n){return createUserMessage(e,t,n)}function isUserMessageKind(e){return e===`user`||isFrameworkMessageKind(e)}function isUserModelMessage(e){if(e.role!==`user`)return!1;let{kind:t}=e;return isUserMessageKind(t)}function isFrameworkUserMessage(e){return isUserModelMessage(e)&&e.kind
|
|
1
|
+
import{attachClientContext,readClientContext}from"#internal/client-context.js";function createUserMessage(e,t,n){let r={content:t,kind:e,role:`user`};return n===void 0?r:{...r,metadata:n}}function createFrameworkUserMessage(e,t,n){return createUserMessage(e,t,n)}function isUserMessageKind(e){return e===`user`||e===`legacy.unknown`||isFrameworkMessageKind(e)}function isUserModelMessage(e){if(e.role!==`user`)return!1;let{kind:t}=e;return isUserMessageKind(t)}function isFrameworkUserMessage(e){return isUserModelMessage(e)&&isFrameworkMessageKind(e.kind)}function validateHarnessModelMessages(e){let t=[];for(let n of e){if(n.role!==`user`){t.push(n);continue}if(!isUserModelMessage(n))throw TypeError(`Expected every user-role model message to have a kind.`);t.push(n)}return t}function isFrameworkMessageKind(e){return e===`context.instruction`||e===`context.state`||e===`context.compaction`||e===`memory.load`||e===`execution.background_task`||e===`execution.continuation`||e===`execution.retry`}function markFrameworkStepInput(e,t){return{...e,frameworkMessageKind:t}}function frameworkMessageKindForStepInput(e){if(e===void 0)return;let{frameworkMessageKind:t}=e;return isFrameworkMessageKind(t)?t:void 0}function coalesceTurnInputs(e,t){let n=coalesceInputResponses({a:e.inputResponses,b:t.inputResponses}),r=coalesceMessage({a:e.message,b:t.message}),i=coalesceContext({a:e.context,b:t.context}),a=coalesceFrameworkMessageKind({a:e,b:t}),o=coalesceContext({a:readClientContext(e),b:readClientContext(t)}),s=t.outputSchema??e.outputSchema,c={};return n!==void 0&&(c.inputResponses=n),r!==void 0&&(c.message=r),i!==void 0&&(c.context=i),s!==void 0&&(c.outputSchema=s),attachClientContext(a===void 0?c:markFrameworkStepInput(c,a),o)}function normalizeUserContent(e){if(e===void 0)return;if(typeof e==`string`)return e.trim().length>0?e:void 0;let t=e.filter(e=>e.type!==`text`||e.text.trim().length>0);if(t.length!==0)return t.length===e.length?e:t}function normalizeModelMessages(e){return e.flatMap(e=>{if(typeof e.content==`string`)return e.content.trim().length>0?[e]:[];let t=e.content.filter(e=>e.type!==`text`||e.text.trim().length>0);return t.length===0?[]:t.length===e.content.length?[e]:[{...e,content:t}]})}function resolveAssistantStepText(e,t){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`)continue;let r=extractMessageText(n);if(r.trim().length>0)return r}return t!==void 0&&t.trim().length>0?t:null}function extractMessageText(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.flatMap(e=>typeof e==`string`?[e]:`type`in e&&e.type===`text`&&typeof e.text==`string`?[e.text]:[]).join(``):``}function coalesceInputResponses(e){let t=e.a??[],n=e.b??[];if(t.length!==0||n.length!==0)return[...t,...n]}function coalesceContext(e){let t=e.a??[],n=e.b??[];if(t.length!==0||n.length!==0)return[...t,...n]}function coalesceFrameworkMessageKind(e){let t=frameworkMessageKindForStepInput(e.a),n=frameworkMessageKindForStepInput(e.b);return e.a.message===void 0?n:e.b.message===void 0||t===n?t:void 0}function coalesceMessage(e){let t=normalizeUserContent(e.a),n=normalizeUserContent(e.b);return t===void 0?n:n===void 0?t:appendUserContent({appended:n,existing:t})}function appendUserContent(e){return typeof e.existing==`string`&&typeof e.appended==`string`?`${e.existing}\n\n${e.appended}`:[...toUserContentArray(e.existing),...toUserContentArray(e.appended)]}function toUserContentArray(e){return typeof e==`string`?e.length>0?[{type:`text`,text:e}]:[]:Array.isArray(e)?[...e]:[]}function coalesceDeliveries(e){let[t,...n]=e;if(t===void 0)throw Error(`Cannot coalesce an empty delivery batch.`);let r=t.auth,i=t.caller,a=[...t.payloads],o=[...t.deliveryMetadata??[]];for(let e of n){let t=a.length;if(e.auth!==void 0&&(r=e.auth),e.caller!==void 0){if(i!==void 0)throw Error(`Cannot coalesce deliveries from different turns.`);i=e.caller}a.push(...e.payloads),o.push(...(e.deliveryMetadata??[]).map(e=>({...e,payloadIndex:e.payloadIndex+t})))}return{...t,auth:r,caller:i,deliveryMetadata:o.length===0?void 0:o,payloads:a}}export{appendUserContent,coalesceDeliveries,coalesceTurnInputs,createFrameworkUserMessage,createUserMessage,frameworkMessageKindForStepInput,isFrameworkMessageKind,isFrameworkUserMessage,isUserMessageKind,isUserModelMessage,markFrameworkStepInput,normalizeModelMessages,normalizeUserContent,resolveAssistantStepText,validateHarnessModelMessages};
|