eve 0.54.2 → 0.54.4

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.
Files changed (146) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/cli/commands/init-agent-workspace.js +1 -1
  3. package/dist/src/cli/commands/init-project.d.ts +46 -0
  4. package/dist/src/cli/commands/init-project.js +1 -0
  5. package/dist/src/cli/commands/init-self-modification.d.ts +7 -0
  6. package/dist/src/cli/commands/init-self-modification.js +1 -0
  7. package/dist/src/cli/commands/init-target.js +2 -2
  8. package/dist/src/cli/commands/init-telemetry.d.ts +6 -0
  9. package/dist/src/cli/commands/init-telemetry.js +1 -0
  10. package/dist/src/cli/commands/init.d.ts +3 -0
  11. package/dist/src/cli/commands/init.js +1 -1
  12. package/dist/src/cli/dev/tui/setup-commands.js +1 -1
  13. package/dist/src/cli/telemetry/index.d.ts +1 -1
  14. package/dist/src/compiled/.vendor-stamp.json +8 -6
  15. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
  16. package/dist/src/compiled/@ai-sdk/google/index.js +7 -7
  17. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  18. package/dist/src/compiled/@ai-sdk/openai/index.js +4 -4
  19. package/dist/src/compiled/@opentelemetry/api/index.d.ts +2 -0
  20. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +26 -0
  21. package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +41 -0
  22. package/dist/src/compiled/@workflow/core/index.js +2 -2
  23. package/dist/src/compiled/@workflow/core/replay-divergence.d.ts +25 -0
  24. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +75 -1
  25. package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +30 -8
  26. package/dist/src/compiled/@workflow/core/runtime/quickjs-log-view.d.ts +129 -0
  27. package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +2 -21
  28. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +0 -22
  29. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  30. package/dist/src/compiled/@workflow/core/serialization.d.ts +2 -2
  31. package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +2 -0
  32. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +36 -0
  33. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  34. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  35. package/dist/src/compiled/@workflow/world/analytics.d.ts +23 -23
  36. package/dist/src/compiled/@workflow/world/events.d.ts +4 -2
  37. package/dist/src/compiled/@workflow/world/queue.d.ts +84 -0
  38. package/dist/src/compiled/@workflow/world-local/index.js +5 -5
  39. package/dist/src/compiled/@workflow/world-vercel/index.js +18 -13
  40. package/dist/src/compiled/_chunks/workflow/attribute-changes-BAcgmlXp.js +20 -0
  41. package/dist/src/compiled/_chunks/workflow/coerce-ro2dOxbr.js +1 -0
  42. package/dist/src/compiled/_chunks/workflow/dist-KPieTJHT.js +25 -0
  43. package/dist/src/compiled/_chunks/workflow/dist-PLkAQ-U7.js +2 -0
  44. package/dist/src/compiled/_chunks/workflow/frames-BvATzM2t.js +3 -0
  45. package/dist/src/compiled/_chunks/workflow/{functions-C02-JHBK.js → functions-wMCGZAVk.js} +1 -1
  46. package/dist/src/compiled/_chunks/workflow/resume-hook-BEHe0Uut.js +1 -0
  47. package/dist/src/compiled/_chunks/workflow/run-ChHLjaCt.js +1 -0
  48. package/dist/src/compiled/_chunks/workflow/schemas-DR7NTzNe.js +50 -0
  49. package/dist/src/compiled/_chunks/workflow/sleep-BB2HuVie.js +1 -0
  50. package/dist/src/compiled/_chunks/workflow/{wrapper-BxECO5nh.js → wrapper-CKui_eTd.js} +2 -2
  51. package/dist/src/compiled/_chunks/workflow/ws-transport-CVezyWwZ.js +1 -0
  52. package/dist/src/compiled/just-secrets/LICENSE +21 -0
  53. package/dist/src/compiled/just-secrets/index.d.ts +20 -0
  54. package/dist/src/compiled/just-secrets/index.js +2 -0
  55. package/dist/src/compiled/just-secrets/windows.ps1 +138 -0
  56. package/dist/src/compiler/extension-compatibility.d.ts +12 -12
  57. package/dist/src/compiler/extension-compatibility.js +1 -1
  58. package/dist/src/compiler/normalize-manifest-helpers.d.ts +2 -1
  59. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  60. package/dist/src/compiler/normalize-manifest.js +1 -1
  61. package/dist/src/compiler/resolve-workspace-subagent.d.ts +13 -0
  62. package/dist/src/compiler/resolve-workspace-subagent.js +1 -0
  63. package/dist/src/context/dynamic-model-lifecycle.d.ts +0 -6
  64. package/dist/src/context/dynamic-model-lifecycle.js +1 -1
  65. package/dist/src/context/dynamic-resolve-context.js +1 -1
  66. package/dist/src/context/effective-model.d.ts +5 -0
  67. package/dist/src/context/effective-model.js +1 -0
  68. package/dist/src/context/keys.d.ts +2 -0
  69. package/dist/src/context/keys.js +1 -1
  70. package/dist/src/dynamic/definition.d.ts +4 -0
  71. package/dist/src/eve-channel/index.js +1 -1
  72. package/dist/src/eve-channel/types.d.ts +9 -7
  73. package/dist/src/execution/durable-session-migrations/snapshot.d.ts +0 -16
  74. package/dist/src/execution/durable-session-migrations/snapshot.js +1 -1
  75. package/dist/src/execution/eve-workflow-attributes.d.ts +1 -1
  76. package/dist/src/execution/run-session-limits.js +1 -1
  77. package/dist/src/execution/session.js +1 -1
  78. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  79. package/dist/src/execution/workflow-steps.js +1 -1
  80. package/dist/src/harness/compaction.js +1 -1
  81. package/dist/src/harness/messages.d.ts +1 -1
  82. package/dist/src/harness/messages.js +1 -1
  83. package/dist/src/harness/step-hooks.d.ts +16 -10
  84. package/dist/src/harness/step-hooks.js +1 -1
  85. package/dist/src/harness/tool-loop.js +2 -2
  86. package/dist/src/instrumentation/parent-lineage.js +1 -1
  87. package/dist/src/internal/application/package.js +1 -1
  88. package/dist/src/internal/nitro/routes/index.d.ts +6 -0
  89. package/dist/src/internal/nitro/routes/index.js +7 -7
  90. package/dist/src/internal/vercel/assemble-eve-services.js +1 -1
  91. package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
  92. package/dist/src/internal/vercel/build-multi-agent-landing-page.d.ts +3 -0
  93. package/dist/src/internal/vercel/build-multi-agent-landing-page.js +1 -0
  94. package/dist/src/internal/vercel/eve-service-contribution.d.ts +4 -0
  95. package/dist/src/internal/vercel/eve-service-contribution.js +1 -1
  96. package/dist/src/internal/vercel/vercel-services-config.js +1 -1
  97. package/dist/src/protocol/baggage.d.ts +6 -0
  98. package/dist/src/protocol/baggage.js +1 -1
  99. package/dist/src/protocol/traceparent.d.ts +13 -0
  100. package/dist/src/protocol/traceparent.js +1 -1
  101. package/dist/src/public/definitions/workspace-agent.d.ts +25 -0
  102. package/dist/src/public/definitions/workspace-agent.js +1 -0
  103. package/dist/src/public/index.d.ts +1 -0
  104. package/dist/src/public/index.js +1 -1
  105. package/dist/src/public/models/openai/chatgpt/codex-app-server.d.ts +41 -0
  106. package/dist/src/public/models/openai/chatgpt/codex-app-server.js +1 -0
  107. package/dist/src/public/models/openai/chatgpt/credential-store.d.ts +26 -4
  108. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  109. package/dist/src/public/models/openai/chatgpt/oauth.d.ts +6 -4
  110. package/dist/src/public/models/openai/chatgpt/token-broker.d.ts +7 -7
  111. package/dist/src/public/models/openai/chatgpt/token-broker.js +1 -1
  112. package/dist/src/public/models/openai/chatgpt/token.d.ts +13 -0
  113. package/dist/src/public/models/openai/chatgpt/token.js +1 -0
  114. package/dist/src/public/models/openai/chatgpt/transport.d.ts +2 -1
  115. package/dist/src/public/models/openai/index.d.ts +3 -2
  116. package/dist/src/public/vercel/index.d.ts +50 -0
  117. package/dist/src/public/vercel/index.js +1 -0
  118. package/dist/src/self-modification/setup.js +7 -2
  119. package/dist/src/setup/flows/chatgpt-auth.d.ts +2 -1
  120. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  121. package/dist/src/setup/flows/model.d.ts +0 -2
  122. package/dist/src/setup/flows/model.js +1 -1
  123. package/dist/src/setup/scaffold/create/project.js +1 -1
  124. package/dist/src/subagents/remote-dispatch.d.ts +3 -1
  125. package/dist/src/subagents/remote-dispatch.js +1 -1
  126. package/dist/src/tracing/agent-otel-attributes.js +1 -1
  127. package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
  128. package/docs/agent-config.md +3 -3
  129. package/docs/guides/deployment/vercel.mdx +52 -1
  130. package/docs/guides/dynamic-capabilities.md +19 -7
  131. package/docs/guides/instrumentation-providers.md +1 -1
  132. package/docs/guides/instrumentation.md +25 -6
  133. package/docs/guides/remote-agents.md +5 -5
  134. package/docs/reference/cli.md +2 -2
  135. package/docs/reference/telemetry.md +1 -1
  136. package/docs/reference/typescript-api.md +14 -7
  137. package/docs/subagents/index.mdx +31 -0
  138. package/package.json +13 -6
  139. package/dist/src/compiled/_chunks/workflow/attribute-changes-C6H-fRVP.js +0 -20
  140. package/dist/src/compiled/_chunks/workflow/dist-DDeH-1ER.js +0 -40
  141. package/dist/src/compiled/_chunks/workflow/dist-DhncQSl7.js +0 -74
  142. package/dist/src/compiled/_chunks/workflow/frames-DsEqSDes.js +0 -3
  143. package/dist/src/compiled/_chunks/workflow/resume-hook-BRDLAb67.js +0 -1
  144. package/dist/src/compiled/_chunks/workflow/run-BM2OFphk.js +0 -1
  145. package/dist/src/compiled/_chunks/workflow/sleep-6cG0F99-.js +0 -1
  146. package/dist/src/compiled/_chunks/workflow/ws-transport-DuK82LLz.js +0 -1
@@ -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: 35;
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: 33;
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: 35;
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, 35];
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: 12;
62
- readonly supported: readonly [3, 4, 6, 7, 8, 9, 10, 11, 12];
61
+ readonly current: 14;
62
+ readonly supported: readonly [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14];
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";
@@ -67,8 +67,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
67
67
  };
68
68
  };
69
69
  readonly connection: {
70
- readonly current: 15;
71
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15];
70
+ readonly current: 16;
71
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16];
72
72
  readonly dropped: {
73
73
  readonly 9: "Dynamic connection resolvers no longer receive conversation or channel continuation data";
74
74
  readonly 10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
@@ -96,8 +96,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
96
96
  readonly dropped: {};
97
97
  };
98
98
  readonly dynamicSkill: {
99
- readonly current: 17;
100
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17];
99
+ readonly current: 18;
100
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18];
101
101
  readonly dropped: {
102
102
  readonly 13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
103
103
  };
@@ -108,8 +108,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
108
108
  readonly dropped: {};
109
109
  };
110
110
  readonly dynamicInstructions: {
111
- readonly current: 18;
112
- readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18];
111
+ readonly current: 19;
112
+ readonly supported: readonly [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19];
113
113
  readonly dropped: {
114
114
  readonly 14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.";
115
115
  };
@@ -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:35,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,28,29,30,31,32,34,35],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:33,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],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:12,supported:[3,4,6,7,8,9,10,11,12],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
+ 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:35,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,35],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:14,supported:[3,4,6,7,8,9,10,11,12,13,14],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:16,supported:[1,2,3,4,5,6,7,8,11,12,13,14,15,16],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:18,supported:[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18],dropped:{13:`Message and reasoning append events now expose deltas instead of cumulative snapshots.`}},instructions:{current:2,supported:[1,2],dropped:{}},dynamicInstructions:{current:19,supported:[1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19],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,20 +1,14 @@
1
1
  import type { ModelMessage } from "ai";
2
2
  import type { AlsContext } from "#context/container.js";
3
- import type { ContextKey } from "#context/key.js";
4
- import { type LiveDynamicModelSelection } from "#context/keys.js";
5
3
  import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
6
4
  import type { RuntimeDynamicModelReference } from "#runtime/agent/bootstrap.js";
7
5
  import { type RuntimeModelResolutionScope } from "#runtime/agent/resolve-model.js";
8
- export type ActiveDynamicModelSelection = LiveDynamicModelSelection;
9
6
  export declare class DynamicModelSelectionError extends Error {
10
7
  readonly code = "EVE_DYNAMIC_MODEL_SELECTION_FAILED";
11
8
  readonly name = "DynamicModelSelectionError";
12
9
  constructor(error: unknown);
13
10
  }
14
11
  export declare function isDynamicModelSelectionError(error: unknown): error is DynamicModelSelectionError;
15
- export declare function getActiveDynamicModelSelection(ctx: {
16
- get<T>(key: ContextKey<T>): T | undefined;
17
- }): ActiveDynamicModelSelection | null;
18
12
  export declare function dispatchDynamicModelEvent(input: {
19
13
  readonly ctx: AlsContext;
20
14
  readonly dynamicModel: RuntimeDynamicModelReference | undefined;
@@ -1 +1 @@
1
- import{LiveStepDynamicModelSelectionKey,SessionDynamicModelReferenceKey,TurnDynamicModelReferenceKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{isMockModel}from"#internal/mock-model-identity.js";import{loadDynamicRuntimeModelDefinition,resolveRuntimeModelSelection,shouldMockAuthoredRuntimeModels}from"#runtime/agent/resolve-model.js";const ALLOWED_DYNAMIC_MODEL_EVENTS=new Set([`session.started`,`turn.started`,`step.started`]),DYNAMIC_MODEL_SELECTION_ERROR_CODE=`EVE_DYNAMIC_MODEL_SELECTION_FAILED`;var DynamicModelSelectionError=class extends Error{code=DYNAMIC_MODEL_SELECTION_ERROR_CODE;name=`DynamicModelSelectionError`;constructor(e){super(toErrorMessage(e),{cause:e})}};function isDynamicModelSelectionError(e){return e instanceof DynamicModelSelectionError||typeof e==`object`&&!!e&&e.code===DYNAMIC_MODEL_SELECTION_ERROR_CODE}function isDynamicModelEventName(e){return ALLOWED_DYNAMIC_MODEL_EVENTS.has(e)}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicModelReferenceKey;case`turn.started`:return TurnDynamicModelReferenceKey;case`step.started`:return}}function getActiveDynamicModelSelection(e){let t=e.get(LiveStepDynamicModelSelectionKey);if(t!=null)return t;let n=e.get(TurnDynamicModelReferenceKey);if(n!=null)return{reference:n};let r=e.get(SessionDynamicModelReferenceKey);return r==null?null:{reference:r}}async function dispatchDynamicModelEvent(e){if(e.dynamicModel!==void 0&&isDynamicModelEventName(e.event.type)&&e.dynamicModel.eventNames.includes(e.event.type)){setSelectionForEvent(e.ctx,e.event.type,null);try{let t=(await loadDynamicRuntimeModelDefinition({dynamicModel:e.dynamicModel,scope:e.scope})).events[e.event.type];if(t===void 0)throw Error(`Dynamic model resolver is missing its compiled "${e.event.type}" handler.`);let n=await t(e.event,buildResolveContext(e.ctx,e.messages)),r=await resolveRuntimeModelSelection({durability:e.event.type===`step.started`?`live`:`durable`,selection:n,state:e.ctx});setSelectionForEvent(e.ctx,e.event.type,r)}catch(e){throw isDynamicModelSelectionError(e)?e:new DynamicModelSelectionError(e)}}}function setSelectionForEvent(e,t,n){if(t===`step.started`){let t=n!==null&&n.model!==void 0&&!isMockModel(n.model)&&shouldMockAuthoredRuntimeModels()?{reference:n.reference}:n;e.setVirtualContext(LiveStepDynamicModelSelectionKey,t);return}let r=durableKeyForEvent(t);r!==void 0&&e.set(r,n?.reference??null)}export{DynamicModelSelectionError,dispatchDynamicModelEvent,getActiveDynamicModelSelection,isDynamicModelSelectionError};
1
+ import{LiveStepDynamicModelSelectionKey,SessionDynamicModelReferenceKey,TurnDynamicModelReferenceKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{buildResolveContext}from"#context/dynamic-resolve-context.js";import{isMockModel}from"#internal/mock-model-identity.js";import{loadDynamicRuntimeModelDefinition,resolveRuntimeModelSelection,shouldMockAuthoredRuntimeModels}from"#runtime/agent/resolve-model.js";const ALLOWED_DYNAMIC_MODEL_EVENTS=new Set([`session.started`,`turn.started`,`step.started`]),DYNAMIC_MODEL_SELECTION_ERROR_CODE=`EVE_DYNAMIC_MODEL_SELECTION_FAILED`;var DynamicModelSelectionError=class extends Error{code=DYNAMIC_MODEL_SELECTION_ERROR_CODE;name=`DynamicModelSelectionError`;constructor(e){super(toErrorMessage(e),{cause:e})}};function isDynamicModelSelectionError(e){return e instanceof DynamicModelSelectionError||typeof e==`object`&&!!e&&e.code===DYNAMIC_MODEL_SELECTION_ERROR_CODE}function isDynamicModelEventName(e){return ALLOWED_DYNAMIC_MODEL_EVENTS.has(e)}function durableKeyForEvent(e){switch(e){case`session.started`:return SessionDynamicModelReferenceKey;case`turn.started`:return TurnDynamicModelReferenceKey;case`step.started`:return}}async function dispatchDynamicModelEvent(e){if(e.dynamicModel!==void 0&&isDynamicModelEventName(e.event.type)&&e.dynamicModel.eventNames.includes(e.event.type)){setSelectionForEvent(e.ctx,e.event.type,null);try{let t=(await loadDynamicRuntimeModelDefinition({dynamicModel:e.dynamicModel,scope:e.scope})).events[e.event.type];if(t===void 0)throw Error(`Dynamic model resolver is missing its compiled "${e.event.type}" handler.`);let n=await t(e.event,buildResolveContext(e.ctx,e.messages)),r=await resolveRuntimeModelSelection({durability:e.event.type===`step.started`?`live`:`durable`,selection:n,state:e.ctx});setSelectionForEvent(e.ctx,e.event.type,r)}catch(e){throw isDynamicModelSelectionError(e)?e:new DynamicModelSelectionError(e)}}}function setSelectionForEvent(e,t,n){if(t===`step.started`){let t=n!==null&&n.model!==void 0&&!isMockModel(n.model)&&shouldMockAuthoredRuntimeModels()?{reference:n.reference}:n;e.setVirtualContext(LiveStepDynamicModelSelectionKey,t);return}let r=durableKeyForEvent(t);r!==void 0&&e.set(r,n?.reference??null)}export{DynamicModelSelectionError,dispatchDynamicModelEvent,isDynamicModelSelectionError};
@@ -1 +1 @@
1
- import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";function buildResolveContext(e,t){let n=e.get(SessionIdKey)??``,r=e.get(AuthKey)??null,i=e.get(InitiatorAuthKey)??null,a=e.get(ChannelKey),o=e.get(ContinuationTokenKey),s=e.get(ChannelInstrumentationKey);return{session:{id:n,auth:{current:r,initiator:i}},channel:{kind:a===void 0?void 0:getAdapterKind(a),continuationToken:o,metadata:s?.metadata},messages:t}}export{buildResolveContext};
1
+ import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getEffectiveModelSelection}from"#context/effective-model.js";function buildResolveContext(e,t){let n=e.get(SessionIdKey)??``,r=e.get(AuthKey)??null,i=e.get(InitiatorAuthKey)??null,a=e.get(ChannelKey),o=e.get(ContinuationTokenKey),s=e.get(ChannelInstrumentationKey),c=getEffectiveModelSelection(e);return{model:c===null?null:{id:c.reference.id},session:{id:n,auth:{current:r,initiator:i}},channel:{kind:a===void 0?void 0:getAdapterKind(a),continuationToken:o,metadata:s?.metadata},messages:t}}export{buildResolveContext};
@@ -0,0 +1,5 @@
1
+ import type { ContextKey } from "#context/key.js";
2
+ import { type LiveDynamicModelSelection } from "#context/keys.js";
3
+ export declare function getEffectiveModelSelection(ctx: {
4
+ get<T>(key: ContextKey<T>): T | undefined;
5
+ }): LiveDynamicModelSelection | null;
@@ -0,0 +1 @@
1
+ import{LiveStepDynamicModelSelectionKey,SessionDynamicModelReferenceKey,StaticModelReferenceKey,TurnDynamicModelReferenceKey}from"#context/keys.js";function getEffectiveModelSelection(e){let t=e.get(LiveStepDynamicModelSelectionKey);if(t!=null)return t;let n=e.get(TurnDynamicModelReferenceKey);if(n!=null)return{reference:n};let r=e.get(SessionDynamicModelReferenceKey);if(r!=null)return{reference:r};let i=e.get(StaticModelReferenceKey);if(i===void 0)throw Error(`Effective model resolution requires initialized static model state.`);return i===null?null:{reference:i}}export{getEffectiveModelSelection};
@@ -109,6 +109,8 @@ export declare const SessionCallbackKey: ContextKey<SessionCallback>;
109
109
  export declare const SessionKey: ContextKey<Session>;
110
110
  export declare const SandboxKey: ContextKey<SandboxAccess>;
111
111
  export declare const HandleEventKey: ContextKey<HandleEventFn>;
112
+ /** Static model configured for the effective turn agent, or `null` for a dynamic-only agent. */
113
+ export declare const StaticModelReferenceKey: ContextKey<Readonly<import("../shared/agent-definition.ts").InternalAgentModelDefinition> | null>;
112
114
  /** Session-scoped dynamic model selection (from `session.started`). */
113
115
  export declare const SessionDynamicModelReferenceKey: ContextKey<Readonly<import("../shared/agent-definition.ts").InternalAgentModelDefinition> | null>;
114
116
  /** Turn-scoped dynamic model selection (from `turn.started`). */
@@ -1 +1 @@
1
- import{ContextKey}from"#context/key.js";import{SESSION_INBOX_CONTEXT_KEY}from"#execution/wire/session-inbox-contract.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),TurnTaskDeliveryKey=new ContextKey(`eve.turnTaskDelivery`),HistoryStateKey=new ContextKey(`eve.historyState`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),ActivityObserverKey=new ContextKey(`eve.activityObserver`),ActivityRootTurnIdKey=new ContextKey(`eve.activityRootTurnId`),ActivityPendingBlockersKey=new ContextKey(`eve.activityPendingBlockers`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,ActivityObserverKey,ActivityPendingBlockersKey,ActivityRootTurnIdKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,ModeKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,ScheduleIdKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionTraceSeedKey,StepDynamicToolMetadataKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey,TurnTaskDeliveryKey};
1
+ import{ContextKey}from"#context/key.js";import{SESSION_INBOX_CONTEXT_KEY}from"#execution/wire/session-inbox-contract.js";import{SESSION_CALLBACK_CONTEXT_KEY_NAME}from"#context/key-names.js";const AuthKey=new ContextKey(`eve.auth`),InitiatorAuthKey=new ContextKey(`eve.initiatorAuth`),SessionIdKey=new ContextKey(`eve.sessionId`),ConversationIdKey=new ContextKey(`eve.conversationId`),SessionInboxKey=new ContextKey(SESSION_INBOX_CONTEXT_KEY),ContinuationTokenKey=new ContextKey(`eve.continuationToken`),ChannelRequestIdKey=new ContextKey(`eve.channelRequestId`),LocalDevRequestKey=new ContextKey(`eve.internal.localDevRequest`),ScheduleIdKey=new ContextKey(`eve.scheduleId`),ChannelDeliveryKey=new ContextKey(`eve.channelDelivery`),TurnDeliveryIdsKey=new ContextKey(`eve.turnDeliveryIds`),TurnTaskDeliveryKey=new ContextKey(`eve.turnTaskDelivery`),HistoryStateKey=new ContextKey(`eve.historyState`),ActiveChannelDeliveriesKey=new ContextKey(`eve.activeChannelDeliveries`),ChannelInstrumentationKey=new ContextKey(`eve.channelInstrumentation`),ModeKey=new ContextKey(`eve.mode`),ParentSessionKey=new ContextKey(`eve.parentSession`),ParentTraceContextKey=new ContextKey(`eve.parentTraceContext`),SessionTraceSeedKey=new ContextKey(`eve.sessionTraceSeed`),OtelTraceEnabledKey=new ContextKey(`eve.otelTraceEnabled`),CapabilitiesKey=new ContextKey(`eve.capabilities`),ActivityObserverKey=new ContextKey(`eve.activityObserver`),ActivityRootTurnIdKey=new ContextKey(`eve.activityRootTurnId`),ActivityPendingBlockersKey=new ContextKey(`eve.activityPendingBlockers`),SessionCallbackKey=new ContextKey(SESSION_CALLBACK_CONTEXT_KEY_NAME),SessionKey=new ContextKey(`eve.session`),SandboxKey=new ContextKey(`eve.sandbox`),HandleEventKey=new ContextKey(`eve.internal.handleEvent`),StaticModelReferenceKey=new ContextKey(`eve.staticModelReference`),SessionDynamicModelReferenceKey=new ContextKey(`eve.sessionDynamicModelReference`),TurnDynamicModelReferenceKey=new ContextKey(`eve.turnDynamicModelReference`),RuntimeModelMetadataCacheKey=new ContextKey(`eve.runtimeModelMetadataCache`),LiveStepDynamicModelSelectionKey=new ContextKey(`eve.liveStepDynamicModelSelection`),SessionDynamicToolMetadataKey=new ContextKey(`eve.sessionDynamicToolMetadata`),SessionDynamicToolRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicToolRuntimeRevision`),TurnDynamicToolMetadataKey=new ContextKey(`eve.turnDynamicToolMetadata`),TurnMemoryLocksKey=new ContextKey(`eve.memory.turnLocks`),PreparedMemoryPreambleKey=new ContextKey(`eve.memory.preparedPreamble`),PendingMemoryCommitKey=new ContextKey(`eve.memory.pendingCommit`),PreparedMemoryCompactionKey=new ContextKey(`eve.memory.preparedCompaction`),StepDynamicToolMetadataKey=new ContextKey(`eve.stepDynamicToolMetadata`),SessionDynamicSubagentSelectionsKey=new ContextKey(`eve.sessionDynamicSubagentSelections`),TurnDynamicSubagentSelectionsKey=new ContextKey(`eve.turnDynamicSubagentSelections`),SessionDynamicSubagentRuntimeRevisionKey=new ContextKey(`eve.sessionDynamicSubagentRuntimeRevision`),DynamicSubagentAgentConfigKey=new ContextKey(`eve.dynamicSubagentAgentConfig`),DynamicSkillManifestKey=new ContextKey(`eve.dynamicSkillManifest`),SessionDynamicInstructionsKey=new ContextKey(`eve.sessionDynamicInstructions`),TurnDynamicInstructionsKey=new ContextKey(`eve.turnDynamicInstructions`),DynamicInstructionResolveMessagesKey=new ContextKey(`eve.dynamicInstructionResolveMessages`),PendingDynamicInstructionUserMessagesKey=new ContextKey(`eve.pendingDynamicInstructionUserMessages`);export{ActiveChannelDeliveriesKey,ActivityObserverKey,ActivityPendingBlockersKey,ActivityRootTurnIdKey,AuthKey,CapabilitiesKey,ChannelDeliveryKey,ChannelInstrumentationKey,ChannelRequestIdKey,ContinuationTokenKey,ConversationIdKey,DynamicInstructionResolveMessagesKey,DynamicSkillManifestKey,DynamicSubagentAgentConfigKey,HandleEventKey,HistoryStateKey,InitiatorAuthKey,LiveStepDynamicModelSelectionKey,LocalDevRequestKey,ModeKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,PendingDynamicInstructionUserMessagesKey,PendingMemoryCommitKey,PreparedMemoryCompactionKey,PreparedMemoryPreambleKey,RuntimeModelMetadataCacheKey,SandboxKey,ScheduleIdKey,SessionCallbackKey,SessionDynamicInstructionsKey,SessionDynamicModelReferenceKey,SessionDynamicSubagentRuntimeRevisionKey,SessionDynamicSubagentSelectionsKey,SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,SessionInboxKey,SessionKey,SessionTraceSeedKey,StaticModelReferenceKey,StepDynamicToolMetadataKey,TurnDeliveryIdsKey,TurnDynamicInstructionsKey,TurnDynamicModelReferenceKey,TurnDynamicSubagentSelectionsKey,TurnDynamicToolMetadataKey,TurnMemoryLocksKey,TurnTaskDeliveryKey};
@@ -24,6 +24,10 @@ export declare const ALLOWED_DYNAMIC_CONNECTION_EVENTS: ReadonlySet<string>;
24
24
  * the session context inside tool `execute` functions.
25
25
  */
26
26
  export interface DynamicResolveContext {
27
+ /** Effective model for this resolver, or `null` before dynamic model selection. */
28
+ readonly model: {
29
+ readonly id: string;
30
+ } | null;
27
31
  readonly session: {
28
32
  readonly id: string;
29
33
  readonly auth: SessionAuth;
@@ -1 +1 @@
1
- import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest,handleLegacyConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{routeAuth}from"#public/channels/auth.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),GET(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,handleLegacyConnectionCallbackRequest),POST(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,handleLegacyConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),u=checkUploadPolicy(c,t);if(u!==null)return u;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let d=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(d!==void 0){let e=await r.resolveSession(d);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let f=l===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),p=s.accepted&&l!==void 0&&(l.traceFlags&1)==1?typeof f==`object`?f:f===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,m=l;p!==void 0&&l!==void 0&&(m={...l,forwardedTracePolicy:p}),f===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof f==`object`&&(p===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:f.originAudience,ceiling:formatTraceContentCeiling(f.ceiling),forwarder:i.principalId}));let h=await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(h instanceof Response)return h;let g=readRouteSessionCreator(r);if(g===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let _;try{_=await g({activityObserver:c.activityObserver,auth:h.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:d,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:h.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parentTraceContext:m,title:h.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:_.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:_.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.auth}let p;try{let e=r(o),t=attachClientContext({activityObserver:l.activityObserver,auth:f,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy},l.context);p=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return p.status===`session_not_active`?Response.json({code:`session_not_active`,error:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409}):Response.json({ok:!0,sessionId:p.sessionId,status:`accepted`,deliveryId:p.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:p.sessionId},status:202})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let m=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),h=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=m.headers.get(e);t!==null&&h.set(e,t)}return new Response(m.body,{headers:h,status:m.status,statusText:m.statusText})})],events:e.events})}export{eveChannel};
1
+ import{EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_HEALTH_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,EVE_SESSION_CANCEL_ROUTE_PATTERN,EVE_SESSION_CLEAR_ROUTE_PATTERN,EVE_SESSION_COMPACT_ROUTE_PATTERN,EVE_SESSION_RESET_ROUTE_PATTERN,EVE_SESSION_ROUTE_PATH,EVE_SESSION_ROUTE_PATTERN,EVE_SESSION_STREAM_ROUTE_PATTERN,EVE_SUBAGENT_STREAM_ROUTE_PATTERN,EVE_TASK_INPUT_ROUTE_PATTERN,createEveSessionStreamRoutePath,createEveSubagentStreamRoutePath}from"#protocol/routes.js";import{attachClientContext}from"#internal/client-context.js";import{createLogger,logError}from"#internal/logging.js";import{EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER}from"#protocol/message.js";import{DELETE,GET,HEAD,PATCH,POST,PUT,defineChannel}from"#public/definitions/channel.js";import{resolveForwardedPrincipal}from"#channel/forwarded-principal.js";import{handleConnectionCallbackRequest,handleLegacyConnectionCallbackRequest}from"#execution/connections/callback-route.js";import{handleActivityRequest}from"#execution/activity-route.js";import{handleSessionCallbackRequest}from"#subagents/callback-route.js";import{handleTaskInputResponseRequest}from"#execution/task-input-response-route.js";import{WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest}from"#execution/workflow-webhook-route.js";import{readAgentInfoRouteResponse,readRemoteAgentStreamHeadersResolver,readRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{parseTraceparent,readAgentDispatchTraceContext}from"#protocol/traceparent.js";import{readForwardedAudienceBaggage,readForwardedParentSessionBaggage}from"#protocol/baggage.js";import{readConversationBaggage}from"#tracing/conversation-context.js";import{FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";import{routeAuth}from"#public/channels/auth.js";import{mergeUploadPolicy}from"#public/channels/upload-policy.js";import{checkUploadPolicy,createSessionStreamResponse,deriveOperationContinuationToken,parseCancelTurnBody,parseCreateBody,parseIncludeTailIndex,parseJsonRequest,parseResetBody,parseSessionControlBody,parseSessionMessageBody,parseStartIndex,rejectSessionContinuationToken,requireSessionId}from"#eve-channel/request.js";import{findRemoteSubagentBinding,healthResponse,normalizeEveCors,resolveOnMessage}from"#eve-channel/support.js";export*from"#eve-channel/types.js";const log=createLogger(`eve.channel`);function eveChannel(e){let t=mergeUploadPolicy(e.uploadPolicy);return defineChannel({cors:normalizeEveCors(e.cors),turnPolicy:e.turnPolicy,routes:[GET(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),HEAD(EVE_HEALTH_ROUTE_PATH,async()=>healthResponse()),GET(EVE_INFO_ROUTE_PATH,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=readAgentInfoRouteResponse(n);return i===void 0?Response.json({error:`Agent info route requires internal channel dispatch context.`,ok:!1},{status:500}):await i()}),GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,handleConnectionCallbackRequest),GET(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,handleLegacyConnectionCallbackRequest),POST(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,handleLegacyConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN,handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN,handleSessionCallbackRequest),POST(EVE_TASK_INPUT_ROUTE_PATTERN,handleTaskInputResponseRequest),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN,handleWorkflowWebhookRequest),POST(EVE_SESSION_ROUTE_PATH,async(n,r)=>{let i=await routeAuth(n,e.auth);if(i instanceof Response)return i;let a=await parseJsonRequest(n);if(a instanceof Response)return a;let o=rejectSessionContinuationToken(a);if(o!==null)return o;let s=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:i,payload:a});if(s instanceof Response)return s;let c=parseCreateBody(a);if(c instanceof Response)return c;let l=c.callback===void 0?`absent`:readForwardedParentSessionBaggage(n.headers.get(`baggage`)),u;if(typeof l==`object`){if(l.callId!==c.callback?.callId)log.warn(`ignoring remote parent lineage with a mismatched callback`,{forwarder:i.principalId});else{let t=s.accepted;if(!t&&e.trustedForwarders!==void 0)try{t=await e.trustedForwarders(i)}catch(e){let t=logError(log,`trustedForwarders handler failed`,e,{forwarder:i.principalId});return Response.json({error:`trustedForwarders handler failed.`,errorId:t,ok:!1},{status:500})}t?u=l:log.warn(`ignoring remote parent lineage from an untrusted forwarder`,{forwarder:i.principalId})}}else l===`malformed`&&log.warn(`ignoring malformed remote parent lineage`,{forwarder:i.principalId});let d=c.callback===void 0?void 0:parseTraceparent(n.headers.get(`traceparent`)),f=c.callback===void 0?void 0:readAgentDispatchTraceContext(n.headers.get(`tracestate`),d)??d,p=checkUploadPolicy(c,t);if(p!==null)return p;if(c.operationId!==void 0&&s.auth.principalType===`anonymous`)return Response.json({error:`operationId requires an authenticated principal.`,ok:!1},{status:400});let m=c.operationId===void 0?void 0:await deriveOperationContinuationToken({auth:s.auth,operationId:c.operationId});if(m!==void 0){let e=await r.resolveSession(m);if(e!==void 0)return Response.json({ok:!0,sessionId:e.id,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:e.id},status:202})}let h=d===void 0?`absent`:readForwardedAudienceBaggage(n.headers.get(`baggage`)),g=s.accepted&&d!==void 0&&(d.traceFlags&1)==1?typeof h==`object`?h:h===`malformed`?FAIL_CLOSED_FORWARDED_TRACE_ASSERTION:void 0:void 0,_=f;g!==void 0&&f!==void 0&&(_={...f,forwardedTracePolicy:g}),h===`malformed`?log.warn(`using metadata-only policy for malformed forwarded audience baggage`,{forwarder:i.principalId}):typeof h==`object`&&(g===void 0?log.warn(`ignoring forwarded trace policy without an accepted sampled principal`,{forwarder:i.principalId}):log.info(`accepted forwarded trace policy`,{audience:h.originAudience,ceiling:formatTraceContentCeiling(h.ceiling),forwarder:i.principalId}));let v=await resolveOnMessage({auth:s.auth,config:e,message:c.message,request:n});if(v instanceof Response)return v;let y=readRouteSessionCreator(r);if(y===void 0)return Response.json({error:`Session creation requires internal channel dispatch context.`,ok:!1},{status:500});let b;try{b=await y({activityObserver:c.activityObserver,auth:v.auth,capabilities:c.capabilities??(c.mode===`task`?void 0:{requestInput:!0}),callback:c.callback,continuationToken:m,initiatorAuth:s.accepted?s.initiatorAuth:void 0,input:attachClientContext({message:c.message,context:v.context,outputSchema:c.outputSchema},c.context),mode:c.mode??`conversation`,conversationId:c.callback===void 0?void 0:readConversationBaggage(n.headers.get(`baggage`)),parent:u,parentTraceContext:_,title:v.title})}catch(e){let t=logError(log,`session-create request failed`,e);return Response.json({error:`Failed to create the session.`,errorId:t,ok:!1},{status:500})}return Response.json({ok:!0,sessionId:b.sessionId,status:`accepted`},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:b.sessionId},status:202})}),POST(EVE_SESSION_ROUTE_PATTERN,async(n,{attachSession:r,params:i})=>{let a=await routeAuth(n,e.auth);if(a instanceof Response)return a;let o=requireSessionId(i);if(o instanceof Response)return o;let s=await parseJsonRequest(n);if(s instanceof Response)return s;let c=await resolveForwardedPrincipal({trustedForwarders:e.trustedForwarders,forwarder:a,payload:s});if(c instanceof Response)return c;let l=parseSessionMessageBody(s);if(l instanceof Response)return l;let u=checkUploadPolicy(l,t);if(u!==null)return u;let d,f=c.auth;if(l.message!==void 0){let t=await resolveOnMessage({auth:c.auth,config:e,message:l.message,request:n,sessionId:o});if(t instanceof Response)return t;d=t.context,f=t.auth}let p;try{let e=r(o),t=attachClientContext({activityObserver:l.activityObserver,auth:f,callback:l.callback,context:d,outputSchema:l.outputSchema,turnPolicy:l.turnPolicy},l.context);p=l.inputResponses===void 0?await e.send(l.message,t):await e.respond(l.inputResponses,t)}catch(e){let t=logError(log,`session-message request failed`,e,{sessionId:o});return Response.json({error:`Failed to send the session message.`,errorId:t,ok:!1},{status:500})}return p.status===`session_not_active`?Response.json({code:`session_not_active`,error:`The session is no longer active.`,ok:!1},{headers:{"cache-control":`no-store`},status:409}):Response.json({ok:!0,sessionId:p.sessionId,status:`accepted`,deliveryId:p.deliveryId},{headers:{"cache-control":`no-store`,[EVE_SESSION_ID_HEADER]:p.sessionId},status:202})}),POST(EVE_SESSION_CANCEL_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseCancelTurnBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).cancel({taskId:o.taskId,tasks:o.tasks,turnId:o.turnId})}catch(e){let t=logError(log,`cancel-turn request failed`,e,{sessionId:a});return Response.json({error:`Failed to cancel the turn.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_turn`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_COMPACT_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).compact()}catch(e){let t=logError(log,`session-compaction request failed`,e,{sessionId:a});return Response.json({error:`Failed to compact the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_CLEAR_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseSessionControlBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).clear()}catch(e){let t=logError(log,`session-clear request failed`,e,{sessionId:a});return Response.json({error:`Failed to clear the session context.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`accepted`?{ok:!0,sessionId:s.sessionId,status:`accepted`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`},status:s.status===`accepted`?202:200})}),POST(EVE_SESSION_RESET_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);if(a instanceof Response)return a;let o=await parseResetBody(t);if(o instanceof Response)return o;let s;try{s=await n(a).reset({reason:o.reason})}catch(e){let t=logError(log,`session-reset request failed`,e,{sessionId:a});return Response.json({error:`Failed to reset the session.`,errorId:t,ok:!1},{status:500})}return Response.json(s.status===`reset`?{ok:!0,previousSessionId:s.previousSessionId,status:`reset`}:{ok:!0,status:`no_active_session`},{headers:{"cache-control":`no-store`}})}),GET(EVE_SESSION_STREAM_ROUTE_PATTERN,async(t,{attachSession:n,params:r})=>{let i=await routeAuth(t,e.auth);if(i instanceof Response)return i;let a=requireSessionId(r);return a instanceof Response?a:await createSessionStreamResponse(t,n(a))}),GET(EVE_SUBAGENT_STREAM_ROUTE_PATTERN,async(t,n)=>{let r=await routeAuth(t,e.auth);if(r instanceof Response)return r;let i=n.params.parentSessionId,a=n.params.callId,o=n.params.childSessionId;if(!i||!a||!o)return Response.json({error:`Missing subagent stream coordinates.`,ok:!1},{status:400});let s=parseStartIndex(t);if(s instanceof Response)return s;let c=parseIncludeTailIndex(t),l=createEveSubagentStreamRoutePath({callId:a,childSessionId:o,parentSessionId:i}),u;try{let e=n.attachSession(i),t=await findRemoteSubagentBinding({callId:a,childSessionId:o,childStreamPath:l,parentSessionId:i,parent:e});if(t===void 0)throw Error(`Remote subagent binding not found.`);u=t}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let d=readRemoteAgentStreamHeadersResolver(n);if(d===void 0)return Response.json({error:`Subagent stream proxy requires internal channel dispatch context.`,ok:!1},{status:500});let f;try{f=await d({name:u.data.toolName,resolverId:u.data.remote.resolverId,url:u.data.remote.url})}catch{return Response.json({error:`Subagent stream not found.`,ok:!1},{status:404})}let p=new URL(createEveSessionStreamRoutePath(o).replace(/^\/+/,``),`${u.data.remote.url.replace(/\/+$/,``)}/`);s!==void 0&&p.searchParams.set(`startIndex`,String(s)),c&&p.searchParams.set(`includeTailIndex`,`1`);let m=await fetch(p,{cache:`no-store`,headers:f,redirect:`manual`,signal:t.signal}),h=new Headers;for(let e of[`cache-control`,`content-type`,`x-accel-buffering`,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER]){let t=m.headers.get(e);t!==null&&h.set(e,t)}return new Response(m.body,{headers:h,status:m.status,statusText:m.statusText})})],events:e.events})}export{eveChannel};
@@ -78,12 +78,13 @@ export interface EveChannelInput {
78
78
  readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];
79
79
  /**
80
80
  * The trusted-forwarders policy: which transport-authenticated callers may
81
- * assert a forwarded principal or callback-marked public trace audience. The predicate
82
- * receives the *verified* route-auth principal of the forwarder — who is
83
- * asserting, never what is asserted — and must match it precisely (for example
84
- * `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).
85
- * A permissive predicate lets any authenticated forwarder assert any
86
- * principal and public trace audience.
81
+ * assert a forwarded principal, callback-marked public trace audience, or
82
+ * remote parent lineage. The predicate receives the *verified* route-auth
83
+ * principal of the forwarder — who is asserting, never what is asserted —
84
+ * and must match it precisely (for example `(forwarder) =>
85
+ * forwarder.subject === vercelSubject({ teamSlug, projectName })`). A
86
+ * permissive predicate lets any authenticated forwarder assert any principal,
87
+ * public trace audience, or remote lineage.
87
88
  *
88
89
  * When a trusted forwarder's assertion is accepted on session creation, the
89
90
  * forwarded principal replaces `session.auth.current` and
@@ -92,7 +93,8 @@ export interface EveChannelInput {
92
93
  * forwarder is recorded on accepted contexts as the `eve:forwarded-by`
93
94
  * attribute. An accepted public audience is evaluated by this deployment's
94
95
  * trace policies; the default records model and tool content. Omit the option
95
- * to reject forwarded principals with 403 and ignore forwarded audience.
96
+ * to reject forwarded principals with 403 and ignore forwarded audience and
97
+ * remote lineage.
96
98
  */
97
99
  readonly trustedForwarders?: TrustedForwarders;
98
100
  /**
@@ -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