eve 0.45.1 → 0.45.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@vercel/blob/client.d.ts +487 -0
- package/dist/src/compiled/@vercel/blob/create-folder-BM6BTlko.d.ts +471 -0
- package/dist/src/compiled/@vercel/blob/index.d.ts +573 -0
- package/dist/src/compiled/@vercel/blob/index.js +43 -0
- package/dist/src/compiled/@vercel/blob/license.md +201 -0
- package/dist/src/compiler/model-catalog.d.ts +1 -1
- package/dist/src/compiler/model-catalog.js +1 -1
- package/dist/src/harness/hitl/approval-prompt.d.ts +2 -0
- package/dist/src/harness/hitl/approval-prompt.js +3 -2
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/internal/application/compiled-artifacts.js +4 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/workflow/development-world-server.js +1 -1
- package/dist/src/internal/workflow/local-world-delivery-timeouts.d.ts +7 -0
- package/dist/src/internal/workflow/local-world-delivery-timeouts.js +1 -0
- package/dist/src/public/memory/file/backend.d.ts +37 -0
- package/dist/src/public/memory/file/backend.js +1 -0
- package/dist/src/public/memory/file/backends/default.d.ts +7 -0
- package/dist/src/public/memory/file/backends/default.js +1 -0
- package/dist/src/public/memory/file/backends/in-memory.d.ts +6 -0
- package/dist/src/public/memory/file/backends/in-memory.js +1 -0
- package/dist/src/public/memory/file/backends/lazy.d.ts +3 -0
- package/dist/src/public/memory/file/backends/lazy.js +1 -0
- package/dist/src/public/memory/file/backends/vercel-blob.d.ts +14 -0
- package/dist/src/public/memory/file/backends/vercel-blob.js +1 -0
- package/dist/src/public/memory/file/index.d.ts +3 -0
- package/dist/src/public/memory/file/index.js +1 -0
- package/dist/src/public/memory/file/provider.d.ts +14 -0
- package/dist/src/public/memory/file/provider.js +6 -0
- package/dist/src/public/memory/file/vercel.d.ts +1 -0
- package/dist/src/public/memory/file/vercel.js +1 -0
- package/dist/src/setup/integrations/linq/connect.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/docs/memory.md +69 -4
- package/docs/reference/typescript-api.md +5 -0
- package/package.json +12 -1
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2023 Vercel, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -27,6 +27,6 @@ export interface CompiledRuntimeModelCatalogLoader {
|
|
|
27
27
|
export declare function resolveCompiledRuntimeModelCatalogCachePath(appRoot: string): string;
|
|
28
28
|
/**
|
|
29
29
|
* Creates a per-build loader that caches the AI Gateway model catalog in
|
|
30
|
-
* memory and on disk.
|
|
30
|
+
* memory and on disk, with stale-on-error fallback.
|
|
31
31
|
*/
|
|
32
32
|
export declare function createCompiledRuntimeModelCatalogLoader(appRoot: string): CompiledRuntimeModelCatalogLoader;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{AI_GATEWAY_MODELS_CATALOG_URL,vercelGatewayFetch}from"#internal/gateway.js";import{catalogModelProviderSchema,catalogModelSchema,catalogModelSchema as catalogModelSchema$1,findCatalogModelByProviderModelId,findCatalogModelBySlug,modelCatalogLimitsFromProvider,modelCatalogResponseSchema,modelCatalogResponseSchema as modelCatalogResponseSchema$1,normalizeCatalogModelId}from"#internal/model-catalog.js";const COMPILED_RUNTIME_MODEL_CATALOG_CACHE_KIND=`eve-model-catalog-cache`;z.object({contextWindowTokens:z.number().int().positive(),maxOutputTokens:z.number().int().positive().optional()}).strict();const compiledRuntimeModelCatalogCacheSchema=z.object({fetchedAt:z.string(),kind:z.literal(COMPILED_RUNTIME_MODEL_CATALOG_CACHE_KIND),models:z.array(catalogModelSchema$1),providerAliases:z.record(z.string(),z.string()),version:z.literal(2)}).strict(),builtInCompiledRuntimeModelLimitsById=new Map([[`anthropic/claude-opus-4.7`,{contextWindowTokens:2e5,maxOutputTokens:32e3}],[`openai/gpt-5.4`,{contextWindowTokens:4e5,maxOutputTokens:128e3}],[`openai/gpt-5.4-mini`,{contextWindowTokens:4e5,maxOutputTokens:128e3}]]);function resolveCompiledRuntimeModelCatalogCachePath(e){return join(e,`.eve`,`cache`,`model-catalog.json`)}function createCompiledRuntimeModelCatalogLoader(e){let t=null,n=null,r=null,getCachedCatalog=async()=>(t??=readModelCatalogCache(e),await t),getFetchedCatalog=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=fetchAndPersistModelCatalog(e).then(e=>(t=Promise.resolve(e),e));try{return await r}catch(e){throw n=e,e}},resolveModelsFromCacheOrFetch=async
|
|
1
|
+
import{mkdir,readFile,writeFile}from"node:fs/promises";import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{AI_GATEWAY_MODELS_CATALOG_URL,vercelGatewayFetch}from"#internal/gateway.js";import{catalogModelProviderSchema,catalogModelSchema,catalogModelSchema as catalogModelSchema$1,findCatalogModelByProviderModelId,findCatalogModelBySlug,modelCatalogLimitsFromProvider,modelCatalogResponseSchema,modelCatalogResponseSchema as modelCatalogResponseSchema$1,normalizeCatalogModelId}from"#internal/model-catalog.js";const COMPILED_RUNTIME_MODEL_CATALOG_CACHE_KIND=`eve-model-catalog-cache`;z.object({contextWindowTokens:z.number().int().positive(),maxOutputTokens:z.number().int().positive().optional()}).strict();const compiledRuntimeModelCatalogCacheSchema=z.object({fetchedAt:z.string(),kind:z.literal(COMPILED_RUNTIME_MODEL_CATALOG_CACHE_KIND),models:z.array(catalogModelSchema$1),providerAliases:z.record(z.string(),z.string()),version:z.literal(2)}).strict(),builtInCompiledRuntimeModelLimitsById=new Map([[`anthropic/claude-opus-4.7`,{contextWindowTokens:2e5,maxOutputTokens:32e3}],[`openai/gpt-5.4`,{contextWindowTokens:4e5,maxOutputTokens:128e3}],[`openai/gpt-5.4-mini`,{contextWindowTokens:4e5,maxOutputTokens:128e3}]]);function resolveCompiledRuntimeModelCatalogCachePath(e){return join(e,`.eve`,`cache`,`model-catalog.json`)}function createCompiledRuntimeModelCatalogLoader(e){let t=null,n=null,r=null,getCachedCatalog=async()=>(t??=readModelCatalogCache(e),await t),getFetchedCatalog=async()=>{if(n!==null)throw n;if(r!==null)return await r;r=fetchAndPersistModelCatalog(e).then(e=>(t=Promise.resolve(e),e));try{return await r}catch(e){throw n=e,e}},resolveModelsFromCacheOrFetch=async e=>{let t=await getCachedCatalog();if(e?.forceRefresh!==!0&&t!==null&&isCacheFresh(t))return t;try{return await getFetchedCatalog()}catch(e){if(t!==null)return t;throw e}};return{async getModelLimits(e){let t=normalizeCatalogModelId(e),n=builtInCompiledRuntimeModelLimitsById.get(t);if(n!==void 0)return n;let r=await resolveModelsFromCacheOrFetch();if(r===null)return null;let i=findCatalogModelBySlug(r.models,t);if(i===void 0){if(r=await resolveModelsFromCacheOrFetch({forceRefresh:!0}),r===null)return null;i=findCatalogModelBySlug(r.models,t)}if(i!==void 0)for(let e of i.providers){let t=modelCatalogLimitsFromProvider(e);if(t!==null)return t}return null},async getByProviderModelId(e,t){let n=await resolveModelsFromCacheOrFetch();if(n===null)return null;let r=findCatalogModelByProviderModelId({models:n.models,provider:e,providerAliases:n.providerAliases,providerModelId:t});if(r===null){if(n=await resolveModelsFromCacheOrFetch({forceRefresh:!0}),n===null)return null;r=findCatalogModelByProviderModelId({models:n.models,provider:e,providerAliases:n.providerAliases,providerModelId:t})}if(r!==null){let e=modelCatalogLimitsFromProvider(r.provider);if(e!==null)return{slug:r.model.slug,limits:e}}return null}}}async function fetchAndPersistModelCatalog(t){let r=await vercelGatewayFetch(AI_GATEWAY_MODELS_CATALOG_URL);if(!r.ok)throw Error(`AI Gateway model catalog request failed with HTTP ${r.status} ${r.statusText}.`);let a=modelCatalogResponseSchema$1.safeParse(await r.json());if(!a.success)throw Error(`AI Gateway model catalog response did not match the expected schema.`);let o={fetchedAt:new Date().toISOString(),kind:COMPILED_RUNTIME_MODEL_CATALOG_CACHE_KIND,models:a.data.models,providerAliases:a.data.providerAliases,version:2};try{let r=resolveCompiledRuntimeModelCatalogCachePath(t);await mkdir(join(t,`.eve`,`cache`),{recursive:!0}),await writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`)}catch{}return o}async function readModelCatalogCache(e){try{let n=await readFile(resolveCompiledRuntimeModelCatalogCachePath(e),`utf8`),r=compiledRuntimeModelCatalogCacheSchema.safeParse(JSON.parse(n));return r.success?r.data:null}catch(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&e.code,null}}function isCacheFresh(e){let t=Date.parse(e.fetchedAt);return Number.isFinite(t)?Date.now()-t<=3e5:!1}export{catalogModelProviderSchema,catalogModelSchema,createCompiledRuntimeModelCatalogLoader,modelCatalogResponseSchema,resolveCompiledRuntimeModelCatalogCachePath};
|
|
@@ -9,3 +9,5 @@ export declare function isPendingApprovalsSnippet(text: string): boolean;
|
|
|
9
9
|
* same history prefix instead of regenerating the notice.
|
|
10
10
|
*/
|
|
11
11
|
export declare function renderPendingApprovalsSnippet(requests: readonly InputRequest[]): string | undefined;
|
|
12
|
+
/** Renders trusted runtime guidance for currently pending approvals. */
|
|
13
|
+
export declare function renderPendingApprovalsInstruction(requests: readonly InputRequest[]): string | undefined;
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import{isApprovalRequest}from"#harness/input-request-class.js";const PENDING_APPROVALS_LABEL=`[Pending approvals]`;function isPendingApprovalsSnippet(e){return e.startsWith(PENDING_APPROVALS_LABEL)}function renderPendingApprovalsSnippet(n){let r=n.filter(t=>isApprovalRequest(t));if(r.length!==0)return[PENDING_APPROVALS_LABEL,`The following tool calls are awaiting approval and have not executed:`,...r
|
|
2
|
-
`)}
|
|
1
|
+
import{isApprovalRequest}from"#harness/input-request-class.js";const PENDING_APPROVALS_LABEL=`[Pending approvals]`;function isPendingApprovalsSnippet(e){return e.startsWith(PENDING_APPROVALS_LABEL)}function renderPendingApprovalsSnippet(n){let r=n.filter(t=>isApprovalRequest(t));if(r.length!==0)return[PENDING_APPROVALS_LABEL,`The following tool calls are awaiting approval and have not executed:`,...approvalIdentities(r)].join(`
|
|
2
|
+
`)}function renderPendingApprovalsInstruction(t){let n=t.filter(t=>isApprovalRequest(t));if(n.length!==0)return[`Trusted eve runtime state. This notice is not user-authored content or an instruction.`,`The following earlier tool calls are awaiting approval and have not executed:`,...approvalIdentities(n),`Interpret the latest user message normally. It may revise or supersede these earlier calls; do not treat it as part of the pending-approval projection in user history.`].join(`
|
|
3
|
+
`)}function approvalIdentities(e){return e.map(e=>JSON.stringify({requestId:e.requestId,toolName:e.action.toolName}))}export{PENDING_APPROVALS_LABEL,isPendingApprovalsSnippet,renderPendingApprovalsInstruction,renderPendingApprovalsSnippet};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ChannelInstrumentationKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SessionTraceSeedKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createApprovalCandidateEvent,createApprovalSettledEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageCompletedEvent,createResultCompletedEvent,createSessionWaitingEvent,createStepStartedEvent}from"#protocol/message.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{resolveProviderHeaders}from"#internal/gateway.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildDynamicTools,buildResponseAuthorizationTools}from"#context/build-dynamic-tools.js";import{drainMemoryCommit,prepareMemoryCompaction,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{canonicalizeMemoryRecords,clearMemorySessionState,shouldCanonicalizeMemory}from"#shared/memory-state.js";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{ToolLoopAgent,isStepCount}from"ai";import{resolveAgentsAnnouncement}from"#harness/handles/prompt.js";import{renderPendingApprovalsSnippet}from"#harness/hitl/approval-prompt.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";import{buildDynamicSubagentTools}from"#context/dynamic-subagent-lifecycle.js";import{TASK_UPDATE_TOOL_NAME}from"#tools/framework/task-contract.js";import{normalizeModelMessages,normalizeUserContent,resolveAssistantStepText}from"#harness/messages.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{instrumentationHooksForAudience,shouldCaptureInstrumentationContent}from"#harness/instrumentation/content-policy.js";import{createHistoryViewPreparer}from"#shared/history-view.js";import{getActiveDynamicModelSelection,isDynamicModelSelectionError}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{ASK_QUESTION_TOOL_NAME}from"#harness/request-input-tool.js";import{getSupersededAuthorizationChallenges,isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{appendPendingInputBatch,consumeDeferredStepInput,getApprovedTools,getPendingInputRequestIds,hasDeferredStepInput,hasPendingApprovalBatch,hasStepInput,resolvePendingInput}from"#harness/input-requests.js";import{activeTurnId}from"#harness/active-turn-id.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#harness/instrumentation/native-events.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createBackgroundToolCallBatch}from"#harness/background-tools.js";import{buildDynamicInstructionMessages,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{TASK_DELIVERY_INITIATING_INSTRUCTION,TASK_DELIVERY_PENDING_INSTRUCTION,TASK_DELIVERY_SETTLED_INSTRUCTION}from"#tasks/delivery-context.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{resolveParentLineage}from"#harness/parent-lineage.js";import{prepareTurnTraceContext}from"#harness/prepare-trace-context.js";import{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools,resolveWorkflowSandboxBridgeRequestLimit}from"#harness/workflow-sandbox.js";import{attemptIdempotencyKey}from"#harness/instrumentation/lifecycle.js";import{getApprovalAuditState,markApprovalCandidateHistoryEventEmitted,markApprovalCandidatePendingEventEmitted,markApprovalSettlementEventEmitted}from"#harness/approval-candidates.js";import{queueDeferredStepInput}from"#harness/pending-input-batches.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{getInvalidToolCallInputError,isInvalidToolCall}from"#harness/tool-call-input-errors.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,extractUpstreamRejectionMessage,isNoOutputGeneratedError}from"#harness/model-call-error.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{mergeProviderSafetyIdentifier}from"#harness/provider-safety.js";import{requireSessionModelReference}from"#harness/types.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{applySessionLimitContinuation,enforceSessionTokenLimit}from"#harness/session-limit-enforcement.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{coordinateApprovalDelivery,shouldPrepareApprovalPolicyTools}from"#harness/approval-delivery-coordinator.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation/runtime-context.js";import{createAiSdkHookBridge}from"#harness/ai-sdk-hook-bridge.js";import{convertStaleResponsesToUserMessage,dropStaleSessionLimitContinuationResponses}from"#harness/stale-input-responses.js";import{getInstrumentationConfig}from"#harness/instrumentation/config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#harness/ai-sdk-telemetry.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#harness/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n,r,i){if(e===void 0&&
|
|
1
|
+
import{createErrorId,createLogger,formatError,logError,recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{isScheduleAppAuth}from"#channel/schedule-auth.js";import{AuthKey,ChannelInstrumentationKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SessionTraceSeedKey,TurnTaskDeliveryKey,TurnTaskStateKey}from"#context/keys.js";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{toErrorMessage}from"#shared/errors.js";import{createActionResultEvent,createApprovalCandidateEvent,createApprovalSettledEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createContextClearedEvent,createInputRequestedEvent,createInputResolvedEvent,createMessageCompletedEvent,createResultCompletedEvent,createSessionWaitingEvent,createStepStartedEvent}from"#protocol/message.js";import{summarizeKnownError}from"#harness/semantic-errors/index.js";import{resolveProviderHeaders}from"#internal/gateway.js";import{formatLanguageModelGatewayId}from"#internal/runtime-model.js";import{contextStorage}from"#context/container.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildDynamicTools,buildResponseAuthorizationTools}from"#context/build-dynamic-tools.js";import{drainMemoryCommit,prepareMemoryCompaction,prepareMemoryPreamble}from"#context/memory-lifecycle.js";import{canonicalizeMemoryRecords,clearMemorySessionState,shouldCanonicalizeMemory}from"#shared/memory-state.js";import{advanceStep,emitFailedStep,emitRecoverableFailedTurn,emitStepStarted,emitStreamContent,emitTurnEpilogue,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{ToolLoopAgent,isStepCount}from"ai";import{resolveAgentsAnnouncement}from"#harness/handles/prompt.js";import{renderPendingApprovalsInstruction,renderPendingApprovalsSnippet}from"#harness/hitl/approval-prompt.js";import{getAgentHandleStore}from"#harness/handles/store.js";import{readTaskIdFromInboxToken}from"#tasks/task-inbox-token.js";import{buildDynamicSubagentTools}from"#context/dynamic-subagent-lifecycle.js";import{TASK_UPDATE_TOOL_NAME}from"#tools/framework/task-contract.js";import{normalizeModelMessages,normalizeUserContent,resolveAssistantStepText}from"#harness/messages.js";import{createRuntimeActionRequestFromToolCall,resolvePendingRuntimeActions,setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{clearPendingWorkflowInterrupt,getPendingWorkflowInterrupt,setPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getWorkflowRuntimeActionInterrupts,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{instrumentationHooksForAudience,shouldCaptureInstrumentationContent}from"#harness/instrumentation/content-policy.js";import{evaluateTracePolicy,isSampledTrace}from"#tracing/sampled-trace.js";import{createHistoryViewPreparer}from"#shared/history-view.js";import{getActiveDynamicModelSelection,isDynamicModelSelectionError}from"#context/dynamic-model-lifecycle.js";import{getInstrumentationRuntime}from"#harness/instrumentation/runtime.js";import{ASK_QUESTION_TOOL_NAME}from"#harness/request-input-tool.js";import{getSupersededAuthorizationChallenges,isAuthorizationSignal,setPendingAuthorization}from"#harness/authorization.js";import{appendPendingInputBatch,consumeDeferredStepInput,getApprovedTools,getPendingInputRequestIds,hasDeferredStepInput,hasPendingApprovalBatch,hasStepInput,resolvePendingInput}from"#harness/input-requests.js";import{activeTurnId}from"#harness/active-turn-id.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#harness/instrumentation/native-events.js";import{accumulateTurnUsage,getTurnUsageState,setTurnUsageState}from"#harness/turn-tag-state.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createBackgroundToolCallBatch}from"#harness/background-tools.js";import{buildDynamicInstructionMessages,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble}from"#context/dynamic-instruction-lifecycle.js";import{PendingSkillAnnouncementKey}from"#context/dynamic-skill-lifecycle.js";import{TASK_DELIVERY_INITIATING_INSTRUCTION,TASK_DELIVERY_PENDING_INSTRUCTION,TASK_DELIVERY_SETTLED_INSTRUCTION}from"#tasks/delivery-context.js";import{hydrateSandboxAttachments,stageAttachmentsToSandbox}from"#harness/attachment-staging.js";import{resolveParentLineage}from"#harness/parent-lineage.js";import{prepareTurnTraceContext}from"#harness/prepare-trace-context.js";import{getWorkflowContinuationSecurity,readWorkflowContinuationSecurity}from"#harness/workflow-continuation-security.js";import{buildWorkflowHostTools,resolveWorkflowSandboxBridgeRequestLimit}from"#harness/workflow-sandbox.js";import{attemptIdempotencyKey}from"#harness/instrumentation/lifecycle.js";import{getApprovalAuditState,markApprovalCandidateHistoryEventEmitted,markApprovalCandidatePendingEventEmitted,markApprovalSettlementEventEmitted}from"#harness/approval-candidates.js";import{getPendingInputBatches,queueDeferredStepInput}from"#harness/pending-input-batches.js";import{CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,hasEmptyDeliverySentinel}from"#shared/empty-delivery.js";import{createToolResultMessagePartFromToolError}from"#harness/action-result-helpers.js";import{getInvalidToolCallInputError,isInvalidToolCall}from"#harness/tool-call-input-errors.js";import{EmptyModelResponseError,classifyModelCallError,extractModelCallErrorDetails,extractUnsupportedProviderToolTypes,extractUpstreamRejectionMessage,isNoOutputGeneratedError}from"#harness/model-call-error.js";import{readToolInterrupt}from"#harness/tool-interrupts.js";import{extractQuestionInputRequests,extractToolApprovalInputRequests}from"#harness/input-extraction.js";import{applyLastToolCacheBreakpoint,applySystemCacheBreakpoint,detectPromptCachePath,getAnthropicCacheMarker}from"#harness/prompt-cache.js";import{mergeProviderSafetyIdentifier}from"#harness/provider-safety.js";import{requireSessionModelReference}from"#harness/types.js";import{createWorkflowLifecycle}from"#harness/workflow-lifecycle.js";import{compactMessages,getInputTokenCount,resolveCompactionModel,shouldCompact}from"#harness/compaction.js";import{applySessionLimitContinuation,enforceSessionTokenLimit}from"#harness/session-limit-enforcement.js";import{setEveAttributes}from"#runtime/attributes/emit.js";import{coordinateApprovalDelivery,shouldPrepareApprovalPolicyTools}from"#harness/approval-delivery-coordinator.js";import{buildTelemetryRuntimeContext}from"#harness/instrumentation/runtime-context.js";import{createAiSdkHookBridge}from"#harness/ai-sdk-hook-bridge.js";import{convertStaleResponsesToUserMessage,dropStaleSessionLimitContinuationResponses}from"#harness/stale-input-responses.js";import{getInstrumentationConfig}from"#harness/instrumentation/config.js";import{normalizeProviderToolHistory}from"#harness/provider-tool-history.js";import{extractWorkflowStreamWriteErrorDetails}from"#harness/workflow-stream-error.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#harness/ai-sdk-telemetry.js";import{getAdvertisedTools}from"#harness/advertised-tools.js";import{resolveFrameworkToolFromUpstreamType}from"#harness/provider-tools.js";import{buildStepHooks,emitStepActions}from"#harness/step-hooks.js";import{buildToolApproval,buildToolSetFromDefinitions,buildToolSetWithProviderTools}from"#harness/tools.js";import{continueWorkflowSandboxInterrupt,getWorkflowSandboxInterrupt,unwrapWorkflowSandboxResult}from"#shared/workflow-sandbox.js";import{FINAL_OUTPUT_TOOL_NAME,buildFinalOutputTool}from"#harness/final-output.js";const environment=process.env.NODE_ENV??`unknown`,eveVersion=resolveInstalledPackageInfo().version,log=createLogger(`harness.tool-loop`);function logToolExecutionError(e){e.toolOutput.type===`tool-error`&&logError(log,`tool execution failed`,e.toolOutput.error,{toolName:e.toolCall.toolName,toolCallId:e.toolCall.toolCallId})}function enrichTelemetry(e,t,n,r,i,a){if(!e||t===void 0&&a===void 0)return;let o={};for(let e of Object.keys(i??{}))o[e]=!0;return{functionId:t?.functionId??r,includeRuntimeContext:o,integrations:a===void 0?void 0:[a,...getRegisteredTelemetryIntegrations()],isEnabled:!0,recordInputs:shouldCaptureInstrumentationContent(n)&&(t?.recordInputs??!1),recordOutputs:shouldCaptureInstrumentationContent(n)&&(t?.recordOutputs??!1)}}function mergeSystemInstructions(e){if(e.length===0)return;if(e.length===1)return{...e[0]};let t;for(let n of e)n.providerOptions!==void 0&&(t={...t,...n.providerOptions});let n={role:`system`,content:e.map(e=>e.content).join(`
|
|
2
2
|
|
|
3
|
-
`)};return t!==void 0&&(n.providerOptions=t),n}function buildGatewayAttributionHeaders(e,t){let n=resolveProviderHeaders(e);if(n===void 0)return;let r=t?.agentName??t?.agentId,i=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,a=i?`https://${i}`:void 0,o={...n};return r&&(o[`x-title`]=r),a&&(o[`http-referer`]=a),o}async function resolveActiveRuntimeModel(e){if(e.ctx===void 0){let t=e.session.agent.modelReference;if(t===void 0)throw Error(`Dynamic model selection is unavailable outside an eve runtime context.`);return{model:await e.config.resolveModel(t),session:e.session}}let t=getActiveDynamicModelSelection(e.ctx);if(t===null){let t=e.session.agent.modelReference;if(e.session.agent.dynamicModel===!0||t===void 0)throw Error(`Dynamic model selection is required before model-dependent work begins. Add a matching resolver handler that returns a concrete model.`);return{model:await e.config.resolveModel(t),session:e.session}}return{model:t.model===void 0?await e.config.resolveModel(t.reference):t.model,session:updateSessionModelReference(e.session,t.reference)}}function updateSessionModelReference(e,t){return{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t})}}function updateCompactionThresholdForModelReference(e){return e.modelReference.contextWindowTokens===void 0?e.compaction:{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*(e.compaction.thresholdPercent??.9)))}}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({isRemote:!0,traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function buildHarnessToolsWithDynamicSubagents(e,t){let n=new Map(e);if(t===void 0)return n;for(let e of buildDynamicSubagentTools(t)){if(n.has(e.name))throw Error(`Dynamic subagent "${e.name}" collides with another runtime-visible tool name.`);n.set(e.name,e)}return n}function createToolLoopHarness(t){let n=t.handleEvent,h=getInstrumentationRuntime(),b=h?.otelSettings,te=getInstrumentationConfig(),ne=h?.runtimeContextResolvers;b!==void 0&&ensureOtelIntegration();let S=b===void 0?void 0:trace.getTracer(`eve`),C=t.runtimeIdentity?.agentName;async function runStep(e,t){let n;if(S&&hasStepInput(t)){let t=b?.functionId??C,r={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(r[`ai.telemetry.functionId`]=t),n=S.startSpan(`ai.eve.turn`,{attributes:r})}let r=resolveStepOtelContext(S,n,e),executeStep=()=>executeStepBody(e,t,n);try{return r?await context.with(r,executeStep):await executeStep()}finally{n?.end()}}async function executeStepBody(h,S,w){let E=h,ce=createHistoryViewPreparer({previous:t.historyView,projector:t.historyProjector});ce(E.history,E.state);let projectHistory=(e,t)=>ce(e,t).messages;w&&(E=setTurnTraceState(E,w.spanContext()));let D=getHarnessEmissionState(E.state),O=contextStorage.getStore(),k=O?.get(ChannelInstrumentationKey),A=normalizeChannelAudience(k?.metadata.audience),j=instrumentationHooksForAudience(t.instrumentation?.hooks,A),M=O?.get(ParentSessionKey),le=O?.get(ChannelKey),ue=O?.get(SessionCallbackKey),de=M!==void 0||ue!==void 0,N=(ue?.taskId!==void 0||readTaskIdFromInboxToken(String(le?.state?.parentContinuationToken??``))!==void 0)&&t.tools.has(TASK_UPDATE_TOOL_NAME),fe=resolveParentLineage(M,le),pe=O?.get(ParentTraceContextKey),me=O?.get(SessionTraceSeedKey),he,P=createInstrumentationHandleEvent({agentName:t.runtimeIdentity?.agentName,channelAudience:A,channelKind:k?.kind,getAttemptScope:()=>he,handleEvent:n,hooks:j,parentLineage:fe,parentTraceContext:pe,rootSessionId:M?.rootSessionId,sessionId:E.sessionId,turnId:activeTurnId(D)}),failModelSelection=async(n,r)=>{if(throwIfTurnAborted(t.abortSignal),w&&recordErrorOnSpan(w,n),!P)throw n;let a=createErrorId(),o=toErrorMessage(n);return log.error(`model selection failed terminally`,{error:n,errorId:a,sessionId:E.sessionId,turnId:r.turnId}),await emitFailedStep(P,r,{code:`MODEL_SELECTION_FAILED`,details:{errorId:a},message:o,sessionId:E.sessionId}),{next:t.mode===`task`||de?{done:!0,isError:!0,output:o}:{done:!0,output:``},session:E}},preparePreambleTrace=async()=>{let e=w?.spanContext(),n=e!==void 0&&isValidSpanContext(e)?{spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId}:void 0;return await prepareTurnTraceContext({agentName:t.runtimeIdentity?.agentName,channelAudience:A,channelType:k?.channelType,instrumentation:t.instrumentation,parentLineage:fe,parentTraceContext:pe,rootSessionId:M?.rootSessionId??E.rootSessionId??E.sessionId,sequence:D.sequence,sessionId:E.sessionId,sessionStarted:D.sessionStarted,traceContext:n,traceSeed:me,turnId:`turn_${D.sequence}`})};if(t.clearOnly===!0)return E={...E,compaction:{recentWindowSize:E.compaction.recentWindowSize,threshold:E.compaction.threshold,thresholdPercent:E.compaction.thresholdPercent},history:[],state:clearMemorySessionState(E.state)},await P?.(createContextClearedEvent({sequence:D.sequence,sessionId:E.sessionId,turnId:activeTurnId(D)})),await P?.(createSessionWaitingEvent()),{next:null,session:E};if(t.compactOnly===!0){if(E.history.length>0)try{let e=contextStorage.getStore(),n=await resolveActiveRuntimeModel({config:t,ctx:e,session:E});E=n.session;let r=await maybeCompact({abortSignal:t.abortSignal,auth:e?.get(AuthKey)??null,emit:P,emissionState:{...D,turnId:activeTurnId(D)},force:!0,historyProjector:t.historyProjector,messages:[...E.history],model:n.model,onCompaction:t.onCompaction,resolveModel:t.resolveModel,runtimeIdentity:t.runtimeIdentity,session:E,telemetry:enrichTelemetry(b,A,C)??void 0});E={...r.session,compaction:{recentWindowSize:r.session.compaction.recentWindowSize,threshold:r.session.compaction.threshold,thresholdPercent:r.session.compaction.thresholdPercent},history:r.messages}}catch(e){logError(log,`manual session compaction failed`,e,{sessionId:E.sessionId})}return await P?.(createSessionWaitingEvent()),{next:null,session:E}}let F=consumeDeferredStepInput({input:S,preferCurrentInput:t.mode!==`conversation`&&S!==void 0&&hasPendingApprovalBatch(E),session:E});E=F.session;let I=await resolvePendingRuntimeActions({emit:P,session:E,stepInput:F.input});if(I.outcome===`unresolved`)return{next:null,session:I.session};E=I.session;let ge=getPendingInputRequestIds(E.state),L=convertStaleResponsesToUserMessage({history:I.messages,pendingRequestIds:ge,stepInput:dropStaleSessionLimitContinuationResponses({pendingRequestIds:ge,stepInput:F.input})}),R=L.stepInput,_e=L.kind===`converted`?{...R,message:L.displayMessage}:R,z=contextStorage.getStore();z!==void 0&&t.resolveStepDynamicTools!==void 0&&shouldPrepareApprovalPolicyTools({session:E,stepInput:R})&&await t.resolveStepDynamicTools({ctx:z,event:createStepStartedEvent({modelId:E.agent.modelReference?.id??`dynamic`,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId}),messages:projectHistory(I.messages,E.state)});let B=await coordinateApprovalDelivery({session:E,stepInput:R,tools:buildResponseAuthorizationTools({authoredTools:t.tools,context:z})});if(E=B.session,P){for(let e of B.feedback)await P(createMessageCompletedEvent({message:e,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId}));let e=getApprovalAuditState(E.state);for(let t of e.activeCandidates.filter(e=>e.pendingEventEmitted!==!0))await P(createApprovalCandidateEvent({candidateId:t.candidateId,outcome:`pending`,requestId:t.requestId,responderPrincipalId:t.responder.principalId,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalCandidatePendingEventEmitted({candidateId:t.candidateId,state:E.state})};for(let t of e.candidateHistory.filter(e=>e.eventEmitted!==!0&&e.status!==`allowed`))await P(createApprovalCandidateEvent({candidateId:t.candidateId,outcome:t.status,requestId:t.requestId,responderPrincipalId:t.responder.principalId,reason:t.reason,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalCandidateHistoryEventEmitted({candidateId:t.candidateId,state:E.state})};for(let t of e.settlements.filter(e=>e.eventEmitted!==!0))await P(createApprovalSettledEvent({outcome:t.outcome===`allowed`?`approved`:`cancelled`,requestId:t.requestId,responderPrincipalId:t.actor.principalId,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalSettlementEventEmitted({requestId:t.requestId,state:E.state})}}if(B.kind===`park`)return{next:null,session:E};if(B.kind===`continue-coordination`)return{next:runStep,session:B.stepInput===void 0?E:queueDeferredStepInput(E,B.stepInput)};if(B.challenges.length>0){if(P)for(let e of B.challenges)await P(createAuthorizationRequiredEvent({authorization:e.challenge,candidateId:e.candidateId,description:e.challenge.instructions??`Authorization required for ${e.name}`,name:e.name,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId,webhookUrl:e.hookUrl}));let e=B.stepInput===void 0?E:queueDeferredStepInput(E,B.stepInput);return{next:null,session:{...e,state:setPendingAuthorization(e.state,{challenges:B.challenges})}}}let V=resolvePendingInput({deferMessagesWhileApprovalsPending:t.mode!==`conversation`,history:I.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:E,stepInput:B.stepInput});if(V.outcome===`unresolved`){let e=I.outcome===`resolved`?{...V.session,history:[...I.messages]}:V.session;if(P&&t.mode===`conversation`&&V.deferredMessage===!0&&hasStepInput(S)){O!==void 0&&prepareDynamicInstructionPreamble(O,projectHistory(e.history,e.state));let n=[];try{let e=await preparePreambleTrace();D=await emitTurnPreamble(P,_e??{},D,t.runtimeIdentity,e)}catch(t){if(n=O===void 0?[]:drainDynamicInstructionUserMessages(O),e={...e,history:[...e.history,...n]},E=e,!isDynamicModelSelectionError(t))throw t;return failModelSelection(t,{sessionStarted:!0,sequence:D.sequence,stepIndex:0,turnId:`turn_${D.sequence}`})}return n=O===void 0?[]:drainDynamicInstructionUserMessages(O),e={...e,history:[...e.history,...n]},D=await emitTurnEpilogue(P,D,t.mode),{next:null,session:setHarnessEmissionState(e,D)}}return I.outcome===`resolved`?(P&&t.mode===`conversation`&&(D=await emitTurnEpilogue(P,D,t.mode),e=setHarnessEmissionState(e,D)),{next:null,session:e}):{next:null,session:V.session}}if(V.resolvedInputs!==void 0)for(let e of V.resolvedInputs)j!==void 0&&await publishInputResolutions({batch:e,hooks:j,sessionId:E.sessionId}),P&&await P(createInputResolvedEvent({resolutions:e.inputs.map(e=>{let t={kind:e.request.kind,outcome:e.outcome,requestId:e.request.requestId};return e.response===void 0?t:{...t,response:e.response}}),sequence:e.event.sequence,stepIndex:e.event.stepIndex,turnId:e.event.turnId}));if(P&&V.rejectedActions)for(let e of V.rejectedActions)for(let t of e.results)await P(createActionResultEvent({rejected:!0,result:t,sequence:e.event.sequence,stepIndex:e.event.stepIndex,turnId:e.event.turnId}));let H=[];if(R?.context!==void 0&&V.deferredContext!==!0)for(let e of R.context)H.push({content:e,role:`user`});let ve=normalizeUserContent(R?.message),ye=ve!==void 0&&!V.deferredMessage&&!V.consumedMessage?await stageAttachmentsToSandbox(ve):void 0;ye!==void 0&&H.push({content:ye,role:`user`});let U=[],W;if(P&&hasStepInput(S)){O!==void 0&&(prepareDynamicInstructionPreamble(O,projectHistory(V.session.history,V.session.state)),prepareMemoryPreamble(O,{history:V.messages,input:H,state:V.session.state}));try{let e=await preparePreambleTrace();D=await emitTurnPreamble(P,_e??{},D,t.runtimeIdentity,e)}catch(e){if(U=O===void 0?[]:drainDynamicInstructionUserMessages(O),W=O===void 0?void 0:drainMemoryCommit(O),E={...V.session,history:[...W?.history??V.session.history,...U],state:W?.state??V.session.state},!isDynamicModelSelectionError(e))throw e;return failModelSelection(e,{sessionStarted:!0,sequence:D.sequence,stepIndex:0,turnId:`turn_${D.sequence}`})}U=O===void 0?[]:drainDynamicInstructionUserMessages(O),W=O===void 0?void 0:drainMemoryCommit(O),w&&w.setAttribute(`eve.turn.id`,D.turnId)}let be=W?.history??V.session.history,xe=V.session.history.length;E=setHarnessEmissionState({...V.session,history:[...be,...U],state:W?.state??V.session.state},D);let G=[...W?.history??V.messages.slice(0,xe),...U,...W===void 0?V.messages.slice(xe):[]],Se=await applySessionLimitContinuation({config:t,emit:P,emissionState:D,limitContinuation:V.limitContinuation,session:E});if(Se.result!==null)return Se.result;E=Se.session;let Ce=getAgentHandleStore(E.state);if(Ce!==void 0&&!hasUnansweredToolCall(G)&&Ce.handles.some(e=>e.phase===`addressed`)!==!0){let e=resolveAgentsAnnouncement({messages:projectHistory(G,E.state),store:Ce});e!==void 0&&G.push({content:e,role:`user`})}G=[...G,...H];let K=projectHistory(G,E.state),q=O,we;try{q!==void 0&&t.dispatchDynamicModelEvent!==void 0&&await t.dispatchDynamicModelEvent({ctx:q,event:{data:{sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId},type:`step.started`},messages:K}),we=await resolveActiveRuntimeModel({config:t,ctx:q,session:E})}catch(e){return failModelSelection(e,D)}E=we.session;let J=we.model,Te=detectPromptCachePath(J),Y=Te.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,Ee=buildGatewayAttributionHeaders(J,t.runtimeIdentity),De=await maybeCompact({abortSignal:t.abortSignal,auth:q?.get(AuthKey)??null,emit:P,emissionState:D,historyProjector:t.historyProjector,messages:[...G],model:J,onCompaction:t.onCompaction,resolveModel:t.resolveModel,runtimeIdentity:t.runtimeIdentity,session:E,telemetry:enrichTelemetry(b,A,C)??void 0});E=De.session,De.compacted&&(G=De.messages),K=normalizeModelMessages(projectHistory(G,E.state)),P&&await emitStepStarted(P,D,requireSessionModelReference(E).id,K);let Oe=getApprovedTools(E),X=q?.get(TurnTaskDeliveryKey),ke=E.outputSchema!==void 0||q===void 0||q.get(ParentSessionKey)!==void 0?void 0:X===`pending`?TASK_DELIVERY_PENDING_INSTRUCTION:X===`settled`?TASK_DELIVERY_SETTLED_INSTRUCTION:isScheduleAppAuth(q.get(AuthKey))?CONDITIONAL_DELIVERY_INSTRUCTION:X===`initiating`?TASK_DELIVERY_INITIATING_INSTRUCTION:void 0,Ae=ke!==void 0&&X!==`initiating`,je=await hydrateSandboxAttachments(K),Z=[],Me=[];for(let e of je)e.role===`system`?Z.push(e):Me.push(e);if(q!==void 0){Z.push(...buildDynamicInstructionMessages(q));let e=q.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&Z.push({role:`system`,content:e});let t=q.get(TurnTaskStateKey);t!==void 0&&Z.push({role:`system`,content:t})}ke!==void 0&&Z.push({role:`system`,content:ke});let Ne=Me,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=E.agent.system?[{role:`system`,content:E.agent.system}]:[],r=Z.length>0||t.length>0?[...t,...n,...Z]:void 0,i=r!==void 0&&Y?applySystemCacheBreakpoint(r,Y):r,a=i===void 0?E.agent.system??void 0:mergeSystemInstructions(i);return{instructions:a,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:te,emissionState:D,environment,modelInput:{instructions:a,messages:Ne},providerResolvers:ne,session:E})}},Pe=t.tools,runSingleModelCall=async e=>{let{instructions:n,telemetryRuntimeContext:i={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(i[`eve.retry.reason`]=e.retryReason);let a=e.trailingUserNote?[...Ne,{role:`user`,content:e.trailingUserNote}]:Ne,o=buildHarnessToolsWithDynamicSubagents(t.tools,q),c=createBackgroundToolCallBatch(),l=getAdvertisedTools({delegatedCaller:N,session:E,tools:o});Pe=l;let u=await buildToolSetWithProviderTools({approvedTools:Oe,backgroundBatch:c,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:requireSessionModelReference(E),tools:l,webSearchProvider:t.webSearchProvider});if(q!==void 0){let n=getAdvertisedTools({delegatedCaller:N,session:E,tools:buildDynamicTools(q)}),r=buildToolSetFromDefinitions({approvedTools:Oe,backgroundBatch:c,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r)){if(l.get(e)?.runtimeAction!==void 0)throw Error(`Dynamic tool "${e}" collides with a runtime-visible subagent.`);u[e]=t}}E.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(E.outputSchema));let d=P===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:P,emissionState:D,tools:e}),f=t.workflow===!0?{lifecycle:d,maxSubagents:t.workflowMaxSubagents}:void 0,p=await getAdvertisedTools({delegatedCaller:N,modelTools:u,session:E,tools:l,workflow:f});E=p.session;let m=p.modelTools,h=Y?applyLastToolCacheBreakpoint(m,Y):m,g=activeTurnId(D),_=j===void 0?void 0:{attemptId:`${E.sessionId}:${g}:${D.stepIndex}:${e.attemptIndex}`,attemptIndex:e.attemptIndex,channelAudience:A,functionId:b?.functionId??C,rootSessionId:M?.rootSessionId??E.sessionId,sessionId:E.sessionId,stepIndex:D.stepIndex,turnId:g};he=_;let v=_===void 0||j===void 0?void 0:createAiSdkHookBridge(_,j,t.instrumentation?.runInContext,i),y=buildStepHooks({auth:q?.get(AuthKey)??null,cachePath:Te,emit:P,emissionState:D,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:Y,session:E}),ee=new ToolLoopAgent({headers:Ee,instructions:n,model:J,onLanguageModelCallEnd(e){for(let t of e.content)t.type!==`tool-call`||t.providerExecuted===!0||isInvalidToolCall(t)||c.register({callId:t.toolCallId,input:t.input,toolName:t.toolName})},onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownError(e.error)?.tags.includes(`config`)!==!0&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:y.onStepFinish,prepareStep:y.prepareStep,reasoning:E.agent.reasoning,runtimeContext:i,stopWhen:isStepCount(1),telemetry:enrichTelemetry(b,A,C,i,v),toolApproval:buildToolApproval(m),tools:h}),executeModelCall=async()=>{if(P){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&l.get(e)===void 0).map(([e])=>e),n=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),r=await ee.stream({abortSignal:t.abortSignal,messages:a}),{emittedActionCallIds:i,handledInlineToolResultCallIds:o,invalidInputToolCallIds:s,inlineAuthorizationResults:c,trailingInlineToolResultParts:u}=await emitStreamContent(P,D,r.fullStream,{excludedActionToolNames:n,tools:l});throwIfTurnAborted(t.abortSignal);let[d,f]=await Promise.all([y.stepResult,r.responseMessages]);if(isEmptyModelResponse(d)&&extractToolResultCallIds(f).size===0&&c.length===0&&u.length===0)throw new EmptyModelResponseError;await emitStepActions(P,D,d,{emittedActionCallIds:i,excludedActionCallIds:s,excludedActionToolNames:n,handledInlineToolResultCallIds:o,tools:l});let p=d.toolResults,m=new Map(p.map(e=>[e.toolCallId,e]));for(let e of c)m.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:s,responseMessages:appendMissingToolResultMessages({append:u,responseMessages:f}),stepResult:d,toolResults:[...m.values()]})}let e=await ee.generate({abortSignal:t.abortSignal,messages:a});throwIfTurnAborted(t.abortSignal);let n=await y.stepResult;if(isEmptyModelResponse(n)&&extractToolResultCallIds(e.responseMessages).size===0)throw new EmptyModelResponseError;return withAccumulatedResponseMessages({responseMessages:e.responseMessages,stepResult:n})};try{let e=await executeModelCall();return _!==void 0&&await j?.publish({idempotencyKey:attemptIdempotencyKey(_),scope:_,type:`step.attempt.completed`}),e}catch(e){return _!==void 0&&await j?.publish({error:e,idempotencyKey:attemptIdempotencyKey(_),scope:_,type:`step.attempt.failed`}),rethrowNoOutputAsEmptyResponse(e)}},Fe=0,runOneModelCall=async e=>runModelCallWithRetries(t=>runSingleModelCall({...e,attemptIndex:Fe++,preparedInput:t===1?e.preparedInput:void 0,suppressStepStartedEmission:t!==1||e.suppressStepStartedEmission}),{sessionId:E.sessionId,turnId:D.turnId},t.abortSignal),Ie=prepareModelCallInput(),Le=await continuePendingWorkflowInterrupt({childResults:R?.runtimeActionResults,config:t,emit:P,emissionState:D,runStep,session:E,tools:buildHarnessToolsWithDynamicSubagents(t.tools,q)});if(Le!==null)return Le;let Re=await enforceSessionTokenLimit({config:t,emit:P,emissionState:D,messages:K,session:E});if(Re!==null)return Re;let Q;try{Q=await runOneModelCall({preparedInput:Ie,suppressStepStartedEmission:!0})}catch(n){throwIfTurnAborted(t.abortSignal);let r=await runModelCallRecoveryPipeline({error:n,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:E.sessionId,turnId:D.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:Ae,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:E.sessionId,turnId:D.turnId})]});if(throwIfTurnAborted(t.abortSignal),r.outcome===`recovered`)Q=r.result;else{let n=r.error;if(w&&recordErrorOnSpan(w,n),!P)throw n;let a=extractWorkflowStreamWriteErrorDetails(n);if(a!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...a,errorId:t,error:n,sessionId:E.sessionId,turnId:D.turnId}),D=await emitRecoverableFailedTurn(P,D,{code:`WORKFLOW_STREAM_WRITE_FAILED`,continuationToken:E.continuationToken,details:{...a,errorId:t},message:toErrorMessage(n)}),{next:null,session:setHarnessEmissionState(E,D)}}let o=classifyModelCallError(n),s=createErrorId(),c=summarizeKnownError(n),l=c===null?extractUpstreamRejectionMessage(n):null,u=c?.message??l?.message??toErrorMessage(n),d=c?.hint===void 0?u:`${u} ${c.hint}`,f=extractModelCallErrorDetails(n),p=buildModelCallFailureDetails({catalogSummary:c,error:n,errorId:s,modelCallDetails:f,upstreamRejection:l}),m=buildModelCallFailureLogFields({error:n,errorId:s,modelCallDetails:f,recognized:c!==null||l!==null,sessionId:E.sessionId,turnId:D.turnId});if(o===`terminal`)return c===null?log.error(l?.message??`model call failed terminally`,m):log.error(`${c.name}: ${c.message}`,{errorId:s,hint:c.hint,sessionId:E.sessionId,turnId:D.turnId}),await emitFailedStep(P,D,{code:`MODEL_CALL_FAILED`,details:p,message:u,sessionId:E.sessionId}),{next:t.mode===`task`||de?{done:!0,isError:!0,output:d}:{done:!0,output:``},session:E};if(t.mode===`task`){if(o===`recoverable`&&!(n instanceof EmptyModelResponseError))throw log.warn(l?.message??`model call failed recoverably in task mode — rethrowing for durable step retry`,m),n;return log.error(l?.message??`model call failed; failing the task run`,m),await emitFailedStep(P,D,{code:`MODEL_CALL_FAILED`,details:p,message:u,sessionId:E.sessionId}),{next:{done:!0,isError:!0,output:d},session:E}}log.error(l?.message??`model call failed — parking session for retry by the user`,m),D=await emitRecoverableFailedTurn(P,D,{code:`MODEL_CALL_FAILED`,continuationToken:E.continuationToken,details:p,message:u});let h={isError:!0,output:d};return E={...E,outputSchema:void 0},{next:null,session:setHarnessEmissionState(E,D),settledTurn:h}}}let $=accumulateTurnUsage({previous:getTurnUsageState(E.state),turnId:D.turnId,usage:extractTokenUsageDelta({costUsd:extractGatewayCostUsd(Q.providerMetadata),usage:Q.usage})});E=setTurnUsageState(E,$);let ze;try{ze=formatLanguageModelGatewayId(J)}catch{ze=void 0}return await setEveAttributes({"$eve.model":ze,"$eve.input_tokens":$.inputTokens,"$eve.output_tokens":$.outputTokens,"$eve.cache_read_tokens":$.cacheReadTokens,"$eve.cache_write_tokens":$.cacheWriteTokens,"$eve.cost_usd":$.sawCost?$.costUsd:void 0,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:P,emissionState:D,delegatedCaller:N,modelPromptMessageCount:K.length,promptMessages:G,result:Q,runStep,session:E,runtimeActionTools:Pe})}return runStep}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}function extractTokenUsageDelta(e){let t=e.usage;if(!(t===void 0&&e.costUsd===void 0))return{cacheReadTokens:t?.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:t?.inputTokenDetails?.cacheWriteTokens,costUsd:e.costUsd,inputTokens:t?.inputTokens,outputTokens:t?.outputTokens}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function buildModelCallFailureDetails(e){let{catalogSummary:t,error:r,errorId:i,modelCallDetails:a,upstreamRejection:o}=e;if(t!==null){let e={errorId:i,message:t.message,name:t.name,semanticErrorId:t.id,...a};return t.hint!==void 0&&(e.hint=t.hint),e}return o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.recognized?{...t,details:e.modelCallDetails}:{...t,error:e.error}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}function withAccumulatedResponseMessages(e){let{stepResult:t}=e;return{content:t.content,finishReason:t.finishReason,...e.invalidInputToolCallIds===void 0?{}:{invalidInputToolCallIds:e.invalidInputToolCallIds},providerMetadata:t.providerMetadata,response:{...t.response,messages:[...e.responseMessages]},text:t.text,toolCalls:t.toolCalls,toolResults:e.toolResults===void 0?t.toolResults:[...e.toolResults],usage:t.usage}}function appendMissingToolResultMessages(e){let t=extractToolResultCallIds(e.responseMessages),n=e.append.filter(e=>!t.has(e.toolCallId));return[...e.responseMessages,...n.length>0?[{role:`tool`,content:[...n]}]:[]]}function getInvalidToolCallInputErrors(e){let t=[];for(let n of e.toolCalls){if(n.toolName===FINAL_OUTPUT_TOOL_NAME)continue;let e=getInvalidToolCallInputError({toolCall:n});e!==void 0&&t.push(e)}return t}function extractToolResultCallIds(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let e of n.content)typeof e==`object`&&e&&e.type===`tool-result`&&t.add(e.toolCallId);return t}function hasUnansweredToolCall(e){let t=new Set,n=new Set;for(let r of e)if(Array.isArray(r.content))for(let e of r.content)typeof e!=`object`||!e||(e.type===`tool-call`&&t.add(e.toolCallId),e.type===`tool-result`&&n.add(e.toolCallId));for(let e of t)if(!n.has(e))return!0;return!1}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=getInvalidToolCallInputErrors({toolCalls:i.toolCalls}),d=new Set([...i.invalidInputToolCallIds??[],...i.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId),...u.map(e=>e.toolCallId)]),f=l?[]:appendMissingToolResultMessages({append:u.map(e=>createToolResultMessagePartFromToolError(e)),responseMessages:i.response.messages}),p=l?null:c,m=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&m.add(e.toolCallId);let h=normalizeProviderToolHistory({messages:f,providerExecutedOutcomeIds:m}),g=h.messages,_={...s,compaction:createNextCompactionConfig(s.compaction,e.modelPromptMessageCount,i)},v=t.workflow===!0?readWorkflowContinuationSecurity(_):void 0;if(v!==void 0){let e=await getWorkflowSandboxInterrupt(i,v);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:_,emissionState:o,interrupt:e,promptMessages:r,responseMessages:g})}}let y=extractToolApprovalInputRequests({content:i.content??[],excludedCallIds:d}),te=new Set(y.map(e=>e.action.callId)),ne=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:new Set([...d,...te])}),x=[...y,...ne],re=renderPendingApprovalsSnippet(y),ie=[...r,...re===void 0?[]:[{content:re,role:`user`}]],C=getAdvertisedTools({delegatedCaller:e.delegatedCaller,session:_,tools:e.runtimeActionTools}),ae=(i.toolCalls??[]).filter(e=>!d.has(e.toolCallId)).filter(t=>e.runtimeActionTools.get(t.toolName)?.runtimeAction!==void 0).filter(e=>C.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:_.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:C}));if(ae.length>0){if(x.length===0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:ae,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:[...r]}}),advanceStep(o))};let e=setPendingRuntimeActionBatch({actions:ae,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:ie}});return e=appendPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:x,responseMessages:[],session:e}),n&&await n(createInputRequestedEvent({requests:x,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{next:null,session:setHarnessEmissionState(e,advanceStep(o))}}if(x.length>0){let e=buildResponseAuthorizationTools({authoredTools:t.tools,context:contextStorage.getStore()}),r=appendPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:x,responseAuthRequiredRequestIds:y.filter(t=>{let n=e.get(t.action.toolName)?.approval;return n!==void 0&&typeof n!=`function`&&n.response!==void 0}).map(e=>e.requestId),responseMessages:g,session:{..._,history:ie}});return n&&(await n(createInputRequestedEvent({requests:x,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),r=setHarnessEmissionState(r,o))),{next:hasDeferredStepInput(r)?a:null,session:r}}let oe=findAuthorizationSignalFromToolResults(i.toolResults);if(oe){let{challenges:e}=oe;if(n){for(let t of getSupersededAuthorizationChallenges(_.state,e))await n(createAuthorizationCompletedEvent({attemptId:t.attemptId,authorization:t.challenge,name:t.name,outcome:`failed`,reason:`Superseded by a newer authorization attempt.`,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));for(let t of e)await n(createAuthorizationRequiredEvent({attemptId:t.attemptId,authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode))}return{next:null,session:setHarnessEmissionState({..._,history:[...r],state:setPendingAuthorization(_.state,{challenges:e})},o)}}let se=g,w=[...r,...se],T={..._,history:w};return!(T.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(se.at(-1)?.role===`tool`||h.outcomeEndsResponse||hasDeferredStepInput(T))?(n&&(o=advanceStep(o),T=setHarnessEmissionState(T,o)),{next:a,session:T}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T,stepOutput:p}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:T.outputSchema,session:T,stepOutput:p})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME&&!isInvalidToolCall(e))?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r,i){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r,i)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`,s.history),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(s={...s,outputSchema:void 0},t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`,s.history),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`conversation`,s.history),s=setHarnessEmissionState(s,o)),{next:null,session:s,settledTurn:{output:a??``}};let c=extractFinalOutput(r);if(c===void 0){s={...s,outputSchema:void 0},t&&(o=await emitRecoverableFailedTurn(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,continuationToken:s.continuationToken}),s=setHarnessEmissionState(s,o));let e={isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message};return{next:null,session:s,settledTurn:e}}return s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`conversation`,s.history),s=setHarnessEmissionState(s,o)),{next:null,session:s,settledTurn:{output:c}}}async function continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({bridgeRequestLimit:resolveWorkflowSandboxBridgeRequestLimit(e.config.workflowMaxSubagents),continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let n=await unwrapWorkflowSandboxResult(o,a);if(n.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(n.interrupt)||c+1>=r.length)break;let l=getWorkflowRuntimeActionInterrupts(n.interrupt)[0];if(l===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=l}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold,thresholdPercent:e.thresholdPercent};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session,a=e.historyProjector?.({messages:r,state:i.state})??r,o=e.force===!0||shouldCompact(a,i.compaction),s=shouldCanonicalizeMemory(r);if(!o&&!s)return{compacted:!1,messages:r,session:i};let c=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:requireSessionModelReference(i),resolveModel:e.resolveModel}),l=mergeProviderSafetyIdentifier(i.agent.compactionModelReference??requireSessionModelReference(i),c.providerOptions,e.auth);if(t){let e=contextStorage.getStore();e!==void 0&&prepareMemoryCompaction(e,{history:r,state:i.state}),await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(c.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(a,i.compaction)}),a)}let u=canonicalizeMemoryRecords(r),d=e.historyProjector?.({messages:u.ordinary,state:i.state})??u.ordinary,f=o?await compactMessages([...d],c.model,i.compaction,l,e.telemetry,buildGatewayAttributionHeaders(c.model,e.runtimeIdentity),e.abortSignal,e.force===!0):[...d];if(r=[...u.memory,...f],e.onCompaction)for(let t of e.onCompaction())r.push(t);if(t){let a=contextStorage.getStore();if(a!==void 0&&prepareMemoryCompaction(a,{history:r,state:i.state}),await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(c.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId}),e.historyProjector?.({messages:r,state:i.state})??r),a!==void 0){let e=drainMemoryCommit(a);e!==void 0&&(r=[...e.history],i={...i,state:e.state})}}return{compacted:!0,messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t,n){for(let r=1;;r++){throwIfTurnAborted(n);try{return await e(r)}catch(e){if(throwIfTurnAborted(n),r===3||classifyModelCallError(e)!==`retry`)throw e;let i=500*2**(r-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:r,delayMs:i,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,i))}}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{appendMissingToolResultMessages,createToolLoopHarness};
|
|
3
|
+
`)};return t!==void 0&&(n.providerOptions=t),n}function buildGatewayAttributionHeaders(e,t){let n=resolveProviderHeaders(e);if(n===void 0)return;let r=t?.agentName??t?.agentId,i=process.env.VERCEL_PROJECT_PRODUCTION_URL||process.env.VERCEL_URL,a=i?`https://${i}`:void 0,o={...n};return r&&(o[`x-title`]=r),a&&(o[`http-referer`]=a),o}async function resolveActiveRuntimeModel(e){if(e.ctx===void 0){let t=e.session.agent.modelReference;if(t===void 0)throw Error(`Dynamic model selection is unavailable outside an eve runtime context.`);return{model:await e.config.resolveModel(t),session:e.session}}let t=getActiveDynamicModelSelection(e.ctx);if(t===null){let t=e.session.agent.modelReference;if(e.session.agent.dynamicModel===!0||t===void 0)throw Error(`Dynamic model selection is required before model-dependent work begins. Add a matching resolver handler that returns a concrete model.`);return{model:await e.config.resolveModel(t),session:e.session}}return{model:t.model===void 0?await e.config.resolveModel(t.reference):t.model,session:updateSessionModelReference(e.session,t.reference)}}function updateSessionModelReference(e,t){return{...e,agent:{...e.agent,modelReference:t},compaction:updateCompactionThresholdForModelReference({compaction:e.compaction,modelReference:t})}}function updateCompactionThresholdForModelReference(e){return e.modelReference.contextWindowTokens===void 0?e.compaction:{...e.compaction,threshold:Math.max(1,Math.floor(e.modelReference.contextWindowTokens*(e.compaction.thresholdPercent??.9)))}}const TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`;function getTurnTraceState(e){return e.state?.[TURN_TRACE_STATE_KEY]}function setTurnTraceState(e,t){let n={traceId:t.traceId,spanId:t.spanId,traceFlags:t.traceFlags};return{...e,state:{...e.state,[TURN_TRACE_STATE_KEY]:n}}}function resolveStepOtelContext(e,t,n){if(t)return trace.setSpan(context.active(),t);if(e){let e=getTurnTraceState(n);if(e){let t=trace.wrapSpanContext({isRemote:!0,traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags});return trace.setSpan(context.active(),t)}}}function buildHarnessToolsWithDynamicSubagents(e,t){let n=new Map(e);if(t===void 0)return n;for(let e of buildDynamicSubagentTools(t)){if(n.has(e.name))throw Error(`Dynamic subagent "${e.name}" collides with another runtime-visible tool name.`);n.set(e.name,e)}return n}function createToolLoopHarness(t){let n=t.handleEvent,h=getInstrumentationRuntime(),y=h?.otelSettings,ne=getInstrumentationConfig(),re=h?.runtimeContextResolvers;y!==void 0&&ensureOtelIntegration();let x=y===void 0?void 0:trace.getTracer(`eve`),S=t.runtimeIdentity?.agentName;async function runStep(e,t){let n=shouldEnableAiSdkTelemetry(y,S),r;if(x&&hasStepInput(t)){let t=y?.functionId??S,n={"eve.version":eveVersion,"eve.environment":environment,"eve.session.id":e.sessionId};t&&(n[`ai.telemetry.functionId`]=t),r=x.startSpan(`ai.eve.turn`,{attributes:n})}let i=resolveStepOtelContext(x,r,e),executeStep=()=>executeStepBody(e,t,r,n);try{return i?await context.with(i,executeStep):await executeStep()}finally{r?.end()}}async function executeStepBody(h,x,C,T=!0){let E=h,le=createHistoryViewPreparer({previous:t.historyView,projector:t.historyProjector});le(E.history,E.state);let projectHistory=(e,t)=>le(e,t).messages;C&&(E=setTurnTraceState(E,C.spanContext()));let D=getHarnessEmissionState(E.state),O=contextStorage.getStore(),ue=O?.get(ChannelInstrumentationKey),k=normalizeChannelAudience(ue?.metadata.audience),A=instrumentationHooksForAudience(t.instrumentation?.hooks,k),j=O?.get(ParentSessionKey),de=O?.get(ChannelKey),fe=O?.get(SessionCallbackKey),pe=j!==void 0||fe!==void 0,M=(fe?.taskId!==void 0||readTaskIdFromInboxToken(String(de?.state?.parentContinuationToken??``))!==void 0)&&t.tools.has(TASK_UPDATE_TOOL_NAME),me=resolveParentLineage(j,de),he=O?.get(ParentTraceContextKey),ge=O?.get(SessionTraceSeedKey),_e,N=createInstrumentationHandleEvent({agentName:t.runtimeIdentity?.agentName,channelAudience:k,channelKind:ue?.kind,getAttemptScope:()=>_e,handleEvent:n,hooks:A,parentLineage:me,parentTraceContext:he,rootSessionId:j?.rootSessionId,sessionId:E.sessionId,turnId:activeTurnId(D)}),failModelSelection=async(n,r)=>{if(throwIfTurnAborted(t.abortSignal),C&&recordErrorOnSpan(C,n),!N)throw n;let a=createErrorId(),o=toErrorMessage(n);return log.error(`model selection failed terminally`,{error:n,errorId:a,sessionId:E.sessionId,turnId:r.turnId}),await emitFailedStep(N,r,{code:`MODEL_SELECTION_FAILED`,details:{errorId:a},message:o,sessionId:E.sessionId}),{next:t.mode===`task`||pe?{done:!0,isError:!0,output:o}:{done:!0,output:``},session:E}},preparePreambleTrace=async()=>{let e=C?.spanContext(),n=e!==void 0&&isValidSpanContext(e)?{spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId}:void 0;return await prepareTurnTraceContext({agentName:t.runtimeIdentity?.agentName,channelAudience:k,channelType:ue?.channelType,instrumentation:t.instrumentation,parentLineage:me,parentTraceContext:he,rootSessionId:j?.rootSessionId??E.rootSessionId??E.sessionId,sequence:D.sequence,sessionId:E.sessionId,sessionStarted:D.sessionStarted,traceContext:n,traceSeed:ge,turnId:`turn_${D.sequence}`})};if(t.clearOnly===!0)return E={...E,compaction:{recentWindowSize:E.compaction.recentWindowSize,threshold:E.compaction.threshold,thresholdPercent:E.compaction.thresholdPercent},history:[],state:clearMemorySessionState(E.state)},await N?.(createContextClearedEvent({sequence:D.sequence,sessionId:E.sessionId,turnId:activeTurnId(D)})),await N?.(createSessionWaitingEvent()),{next:null,session:E};if(t.compactOnly===!0){if(E.history.length>0)try{let e=contextStorage.getStore(),n=await resolveActiveRuntimeModel({config:t,ctx:e,session:E});E=n.session;let r=await maybeCompact({abortSignal:t.abortSignal,auth:e?.get(AuthKey)??null,emit:N,emissionState:{...D,turnId:activeTurnId(D)},force:!0,historyProjector:t.historyProjector,messages:[...E.history],model:n.model,onCompaction:t.onCompaction,resolveModel:t.resolveModel,runtimeIdentity:t.runtimeIdentity,session:E,telemetry:enrichTelemetry(T,y,k,S)??void 0});E={...r.session,compaction:{recentWindowSize:r.session.compaction.recentWindowSize,threshold:r.session.compaction.threshold,thresholdPercent:r.session.compaction.thresholdPercent},history:r.messages}}catch(e){logError(log,`manual session compaction failed`,e,{sessionId:E.sessionId})}return await N?.(createSessionWaitingEvent()),{next:null,session:E}}let P=consumeDeferredStepInput({input:x,preferCurrentInput:t.mode!==`conversation`&&x!==void 0&&hasPendingApprovalBatch(E),session:E});E=P.session;let F=await resolvePendingRuntimeActions({emit:N,session:E,stepInput:P.input});if(F.outcome===`unresolved`)return{next:null,session:F.session};E=F.session;let ve=getPendingInputRequestIds(E.state),I=convertStaleResponsesToUserMessage({history:F.messages,pendingRequestIds:ve,stepInput:dropStaleSessionLimitContinuationResponses({pendingRequestIds:ve,stepInput:P.input})}),L=I.stepInput,ye=I.kind===`converted`?{...L,message:I.displayMessage}:L,R=contextStorage.getStore();R!==void 0&&t.resolveStepDynamicTools!==void 0&&shouldPrepareApprovalPolicyTools({session:E,stepInput:L})&&await t.resolveStepDynamicTools({ctx:R,event:createStepStartedEvent({modelId:E.agent.modelReference?.id??`dynamic`,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId}),messages:projectHistory(F.messages,E.state)});let z=await coordinateApprovalDelivery({session:E,stepInput:L,tools:buildResponseAuthorizationTools({authoredTools:t.tools,context:R})});if(E=z.session,N){for(let e of z.feedback)await N(createMessageCompletedEvent({message:e,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId}));let e=getApprovalAuditState(E.state);for(let t of e.activeCandidates.filter(e=>e.pendingEventEmitted!==!0))await N(createApprovalCandidateEvent({candidateId:t.candidateId,outcome:`pending`,requestId:t.requestId,responderPrincipalId:t.responder.principalId,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalCandidatePendingEventEmitted({candidateId:t.candidateId,state:E.state})};for(let t of e.candidateHistory.filter(e=>e.eventEmitted!==!0&&e.status!==`allowed`))await N(createApprovalCandidateEvent({candidateId:t.candidateId,outcome:t.status,requestId:t.requestId,responderPrincipalId:t.responder.principalId,reason:t.reason,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalCandidateHistoryEventEmitted({candidateId:t.candidateId,state:E.state})};for(let t of e.settlements.filter(e=>e.eventEmitted!==!0))await N(createApprovalSettledEvent({outcome:t.outcome===`allowed`?`approved`:`cancelled`,requestId:t.requestId,responderPrincipalId:t.actor.principalId,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId})),E={...E,state:markApprovalSettlementEventEmitted({requestId:t.requestId,state:E.state})}}if(z.kind===`park`)return{next:null,session:E};if(z.kind===`continue-coordination`)return{next:runStep,session:z.stepInput===void 0?E:queueDeferredStepInput(E,z.stepInput)};if(z.challenges.length>0){if(N)for(let e of z.challenges)await N(createAuthorizationRequiredEvent({authorization:e.challenge,candidateId:e.candidateId,description:e.challenge.instructions??`Authorization required for ${e.name}`,name:e.name,sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId,webhookUrl:e.hookUrl}));let e=z.stepInput===void 0?E:queueDeferredStepInput(E,z.stepInput);return{next:null,session:{...e,state:setPendingAuthorization(e.state,{challenges:z.challenges})}}}let B=resolvePendingInput({deferMessagesWhileApprovalsPending:t.mode!==`conversation`,history:F.messages,resolveApprovalKey:resolveApprovalKeyFromTools(t.tools),session:E,stepInput:z.stepInput});if(B.outcome===`unresolved`){let e=F.outcome===`resolved`?{...B.session,history:[...F.messages]}:B.session;if(N&&t.mode===`conversation`&&B.deferredMessage===!0&&hasStepInput(x)){O!==void 0&&prepareDynamicInstructionPreamble(O,projectHistory(e.history,e.state));let n=[];try{let e=await preparePreambleTrace();D=await emitTurnPreamble(N,ye??{},D,t.runtimeIdentity,e)}catch(t){if(n=O===void 0?[]:drainDynamicInstructionUserMessages(O),e={...e,history:[...e.history,...n]},E=e,!isDynamicModelSelectionError(t))throw t;return failModelSelection(t,{sessionStarted:!0,sequence:D.sequence,stepIndex:0,turnId:`turn_${D.sequence}`})}return n=O===void 0?[]:drainDynamicInstructionUserMessages(O),e={...e,history:[...e.history,...n]},D=await emitTurnEpilogue(N,D,t.mode),{next:null,session:setHarnessEmissionState(e,D)}}return F.outcome===`resolved`?(N&&t.mode===`conversation`&&(D=await emitTurnEpilogue(N,D,t.mode),e=setHarnessEmissionState(e,D)),{next:null,session:e}):{next:null,session:B.session}}if(B.resolvedInputs!==void 0)for(let e of B.resolvedInputs)A!==void 0&&await publishInputResolutions({batch:e,hooks:A,sessionId:E.sessionId}),N&&await N(createInputResolvedEvent({resolutions:e.inputs.map(e=>{let t={kind:e.request.kind,outcome:e.outcome,requestId:e.request.requestId};return e.response===void 0?t:{...t,response:e.response}}),sequence:e.event.sequence,stepIndex:e.event.stepIndex,turnId:e.event.turnId}));if(N&&B.rejectedActions)for(let e of B.rejectedActions)for(let t of e.results)await N(createActionResultEvent({rejected:!0,result:t,sequence:e.event.sequence,stepIndex:e.event.stepIndex,turnId:e.event.turnId}));let V=[];if(L?.context!==void 0&&B.deferredContext!==!0)for(let e of L.context)V.push({content:e,role:`user`});let be=normalizeUserContent(L?.message),xe=be!==void 0&&!B.deferredMessage&&!B.consumedMessage?await stageAttachmentsToSandbox(be):void 0;xe!==void 0&&V.push({content:xe,role:`user`});let H=[],U;if(N&&hasStepInput(x)){O!==void 0&&(prepareDynamicInstructionPreamble(O,projectHistory(B.session.history,B.session.state)),prepareMemoryPreamble(O,{history:B.messages,input:V,state:B.session.state}));try{let e=await preparePreambleTrace();D=await emitTurnPreamble(N,ye??{},D,t.runtimeIdentity,e)}catch(e){if(H=O===void 0?[]:drainDynamicInstructionUserMessages(O),U=O===void 0?void 0:drainMemoryCommit(O),E={...B.session,history:[...U?.history??B.session.history,...H],state:U?.state??B.session.state},!isDynamicModelSelectionError(e))throw e;return failModelSelection(e,{sessionStarted:!0,sequence:D.sequence,stepIndex:0,turnId:`turn_${D.sequence}`})}H=O===void 0?[]:drainDynamicInstructionUserMessages(O),U=O===void 0?void 0:drainMemoryCommit(O),C&&C.setAttribute(`eve.turn.id`,D.turnId)}let Se=U?.history??B.session.history,Ce=B.session.history.length;E=setHarnessEmissionState({...B.session,history:[...Se,...H],state:U?.state??B.session.state},D);let W=[...U?.history??B.messages.slice(0,Ce),...H,...U===void 0?B.messages.slice(Ce):[]],we=await applySessionLimitContinuation({config:t,emit:N,emissionState:D,limitContinuation:B.limitContinuation,session:E});if(we.result!==null)return we.result;E=we.session;let Te=getAgentHandleStore(E.state);if(Te!==void 0&&!hasUnansweredToolCall(W)&&Te.handles.some(e=>e.phase===`addressed`)!==!0){let e=resolveAgentsAnnouncement({messages:projectHistory(W,E.state),store:Te});e!==void 0&&W.push({content:e,role:`user`})}W=[...W,...V];let G=projectHistory(W,E.state),K=O,Ee;try{K!==void 0&&t.dispatchDynamicModelEvent!==void 0&&await t.dispatchDynamicModelEvent({ctx:K,event:{data:{sequence:D.sequence,stepIndex:D.stepIndex,turnId:D.turnId},type:`step.started`},messages:G}),Ee=await resolveActiveRuntimeModel({config:t,ctx:K,session:E})}catch(e){return failModelSelection(e,D)}E=Ee.session;let q=Ee.model,De=detectPromptCachePath(q),J=De.kind===`anthropic-direct`?getAnthropicCacheMarker():void 0,Oe=buildGatewayAttributionHeaders(q,t.runtimeIdentity),ke=await maybeCompact({abortSignal:t.abortSignal,auth:K?.get(AuthKey)??null,emit:N,emissionState:D,historyProjector:t.historyProjector,messages:[...W],model:q,onCompaction:t.onCompaction,resolveModel:t.resolveModel,runtimeIdentity:t.runtimeIdentity,session:E,telemetry:enrichTelemetry(T,y,k,S)??void 0});E=ke.session,ke.compacted&&(W=ke.messages),G=normalizeModelMessages(projectHistory(W,E.state)),N&&await emitStepStarted(N,D,requireSessionModelReference(E).id,G);let Ae=getApprovedTools(E),Y=K?.get(TurnTaskDeliveryKey),je=E.outputSchema!==void 0||K===void 0||K.get(ParentSessionKey)!==void 0?void 0:Y===`pending`?TASK_DELIVERY_PENDING_INSTRUCTION:Y===`settled`?TASK_DELIVERY_SETTLED_INSTRUCTION:isScheduleAppAuth(K.get(AuthKey))?CONDITIONAL_DELIVERY_INSTRUCTION:Y===`initiating`?TASK_DELIVERY_INITIATING_INSTRUCTION:void 0,Me=je!==void 0&&Y!==`initiating`,Ne=await hydrateSandboxAttachments(G),X=[],Pe=[];for(let e of Ne)e.role===`system`?X.push(e):Pe.push(e);if(K!==void 0){X.push(...buildDynamicInstructionMessages(K));let e=K.get(PendingSkillAnnouncementKey);e!==void 0&&e.length>0&&X.push({role:`system`,content:e});let t=K.get(TurnTaskStateKey);t!==void 0&&X.push({role:`system`,content:t})}je!==void 0&&X.push({role:`system`,content:je});let Fe=renderPendingApprovalsInstruction(getPendingInputBatches(E.state).flatMap(e=>e.requests));Fe!==void 0&&X.push({role:`system`,content:Fe});let Ie=Pe,prepareModelCallInput=e=>{let t=e?[{role:`system`,content:e}]:[],n=E.agent.system?[{role:`system`,content:E.agent.system}]:[],r=X.length>0||t.length>0?[...t,...n,...X]:void 0,i=r!==void 0&&J?applySystemCacheBreakpoint(r,J):r,a=i===void 0?E.agent.system??void 0:mergeSystemInstructions(i);return{instructions:a,telemetryRuntimeContext:buildTelemetryRuntimeContext({eveVersion,authored:ne,emissionState:D,environment,modelInput:{instructions:a,messages:Ie},providerResolvers:re,session:E})}},Le=t.tools,runSingleModelCall=async e=>{let{instructions:n,telemetryRuntimeContext:i={}}=e.preparedInput??prepareModelCallInput(e.extraSystemNote);e.retryReason&&(i[`eve.retry.reason`]=e.retryReason);let a=e.trailingUserNote?[...Ie,{role:`user`,content:e.trailingUserNote}]:Ie,o=buildHarnessToolsWithDynamicSubagents(t.tools,K),c=createBackgroundToolCallBatch(),l=getAdvertisedTools({delegatedCaller:M,session:E,tools:o});Le=l;let u=await buildToolSetWithProviderTools({approvedTools:Ae,backgroundBatch:c,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,modelReference:requireSessionModelReference(E),tools:l,webSearchProvider:t.webSearchProvider});if(K!==void 0){let n=getAdvertisedTools({delegatedCaller:M,session:E,tools:buildDynamicTools(K)}),r=buildToolSetFromDefinitions({approvedTools:Ae,backgroundBatch:c,capabilities:t.capabilities,disabledProviderTools:e.disabledProviderTools,tools:n});for(let[e,t]of Object.entries(r)){if(l.get(e)?.runtimeAction!==void 0)throw Error(`Dynamic tool "${e}" collides with a runtime-visible subagent.`);u[e]=t}}E.outputSchema!==void 0&&(u[FINAL_OUTPUT_TOOL_NAME]=buildFinalOutputTool(E.outputSchema));let d=N===void 0?void 0:({tools:e})=>createWorkflowLifecycle({emit:N,emissionState:D,tools:e}),f=t.workflow===!0?{lifecycle:d,maxSubagents:t.workflowMaxSubagents}:void 0,p=await getAdvertisedTools({delegatedCaller:M,modelTools:u,session:E,tools:l,workflow:f});E=p.session;let m=p.modelTools,h=J?applyLastToolCacheBreakpoint(m,J):m,g=activeTurnId(D),_=A===void 0?void 0:{attemptId:`${E.sessionId}:${g}:${D.stepIndex}:${e.attemptIndex}`,attemptIndex:e.attemptIndex,channelAudience:k,functionId:y?.functionId??S,rootSessionId:j?.rootSessionId??E.sessionId,sessionId:E.sessionId,stepIndex:D.stepIndex,turnId:g};_e=_;let ee=!T||_===void 0||A===void 0?void 0:createAiSdkHookBridge(_,A,t.instrumentation?.runInContext,i),v=buildStepHooks({auth:K?.get(AuthKey)??null,cachePath:De,emit:N,emissionState:D,emitStepStarted:e.suppressStepStartedEmission!==!0,marker:J,session:E}),te=new ToolLoopAgent({headers:Oe,instructions:n,model:q,onLanguageModelCallEnd(e){for(let t of e.content)t.type!==`tool-call`||t.providerExecuted===!0||isInvalidToolCall(t)||c.register({callId:t.toolCallId,input:t.input,toolName:t.toolName})},onToolExecutionEnd:logToolExecutionError,onError(e){summarizeKnownError(e.error)?.tags.includes(`config`)!==!0&&logError(log,`tool-loop stream error`,e.error)},onStepFinish:v.onStepFinish,prepareStep:v.prepareStep,reasoning:E.agent.reasoning,runtimeContext:i,stopWhen:isStepCount(1),telemetry:enrichTelemetry(T,y,k,S,i,ee),toolApproval:buildToolApproval(m),tools:h}),executeModelCall=async()=>{if(N){let e=[...t.tools].filter(([e,t])=>t.runtimeAction!==void 0&&l.get(e)===void 0).map(([e])=>e),n=new Set([ASK_QUESTION_TOOL_NAME,FINAL_OUTPUT_TOOL_NAME,...e]),r=await te.stream({abortSignal:t.abortSignal,messages:a}),{emittedActionCallIds:i,handledInlineToolResultCallIds:o,invalidInputToolCallIds:s,inlineAuthorizationResults:c,trailingInlineToolResultParts:u}=await emitStreamContent(N,D,r.fullStream,{excludedActionToolNames:n,tools:l});throwIfTurnAborted(t.abortSignal);let[d,f]=await Promise.all([v.stepResult,r.responseMessages]);if(isEmptyModelResponse(d)&&extractToolResultCallIds(f).size===0&&c.length===0&&u.length===0)throw new EmptyModelResponseError;await emitStepActions(N,D,d,{emittedActionCallIds:i,excludedActionCallIds:s,excludedActionToolNames:n,handledInlineToolResultCallIds:o,tools:l});let p=d.toolResults,m=new Map(p.map(e=>[e.toolCallId,e]));for(let e of c)m.set(e.toolCallId,e);return withAccumulatedResponseMessages({invalidInputToolCallIds:s,responseMessages:appendMissingToolResultMessages({append:u,responseMessages:f}),stepResult:d,toolResults:[...m.values()]})}let e=await te.generate({abortSignal:t.abortSignal,messages:a});throwIfTurnAborted(t.abortSignal);let n=await v.stepResult;if(isEmptyModelResponse(n)&&extractToolResultCallIds(e.responseMessages).size===0)throw new EmptyModelResponseError;return withAccumulatedResponseMessages({responseMessages:e.responseMessages,stepResult:n})};try{let e=await executeModelCall();return _!==void 0&&await A?.publish({idempotencyKey:attemptIdempotencyKey(_),scope:_,type:`step.attempt.completed`}),e}catch(e){return _!==void 0&&await A?.publish({error:e,idempotencyKey:attemptIdempotencyKey(_),scope:_,type:`step.attempt.failed`}),rethrowNoOutputAsEmptyResponse(e)}},Re=0,runOneModelCall=async e=>runModelCallWithRetries(t=>runSingleModelCall({...e,attemptIndex:Re++,preparedInput:t===1?e.preparedInput:void 0,suppressStepStartedEmission:t!==1||e.suppressStepStartedEmission}),{sessionId:E.sessionId,turnId:D.turnId},t.abortSignal),ze=prepareModelCallInput(),Be=await continuePendingWorkflowInterrupt({childResults:L?.runtimeActionResults,config:t,emit:N,emissionState:D,runStep,session:E,tools:buildHarnessToolsWithDynamicSubagents(t.tools,K)});if(Be!==null)return Be;let Ve=await enforceSessionTokenLimit({config:t,emit:N,emissionState:D,messages:G,session:E});if(Ve!==null)return Ve;let Z;try{Z=await runOneModelCall({preparedInput:ze,suppressStepStartedEmission:!0})}catch(n){throwIfTurnAborted(t.abortSignal);let r=await runModelCallRecoveryPipeline({error:n,stages:[e=>attemptUnsupportedProviderToolRecovery({error:e.error,runOneModelCall,sessionId:E.sessionId,turnId:D.turnId}),e=>attemptEmptyResponseRecovery({emptyDeliveryEnabled:Me,error:e.error,retryCallOptions:e.retryCallOptions,runOneModelCall,sessionId:E.sessionId,turnId:D.turnId})]});if(throwIfTurnAborted(t.abortSignal),r.outcome===`recovered`)Z=r.result;else{let n=r.error;if(C&&recordErrorOnSpan(C,n),!N)throw n;let a=extractWorkflowStreamWriteErrorDetails(n);if(a!==null){let t=createErrorId();return log.error(`workflow stream write failed — parking session for retry by the user`,{...a,errorId:t,error:n,sessionId:E.sessionId,turnId:D.turnId}),D=await emitRecoverableFailedTurn(N,D,{code:`WORKFLOW_STREAM_WRITE_FAILED`,continuationToken:E.continuationToken,details:{...a,errorId:t},message:toErrorMessage(n)}),{next:null,session:setHarnessEmissionState(E,D)}}let o=classifyModelCallError(n),s=createErrorId(),c=summarizeKnownError(n),l=c===null?extractUpstreamRejectionMessage(n):null,u=c?.message??l?.message??toErrorMessage(n),d=c?.hint===void 0?u:`${u} ${c.hint}`,f=extractModelCallErrorDetails(n),p=buildModelCallFailureDetails({catalogSummary:c,error:n,errorId:s,modelCallDetails:f,upstreamRejection:l}),m=buildModelCallFailureLogFields({error:n,errorId:s,modelCallDetails:f,recognized:c!==null||l!==null,sessionId:E.sessionId,turnId:D.turnId});if(o===`terminal`)return c===null?log.error(l?.message??`model call failed terminally`,m):log.error(`${c.name}: ${c.message}`,{errorId:s,hint:c.hint,sessionId:E.sessionId,turnId:D.turnId}),await emitFailedStep(N,D,{code:`MODEL_CALL_FAILED`,details:p,message:u,sessionId:E.sessionId}),{next:t.mode===`task`||pe?{done:!0,isError:!0,output:d}:{done:!0,output:``},session:E};if(t.mode===`task`){if(o===`recoverable`&&!(n instanceof EmptyModelResponseError))throw log.warn(l?.message??`model call failed recoverably in task mode — rethrowing for durable step retry`,m),n;return log.error(l?.message??`model call failed; failing the task run`,m),await emitFailedStep(N,D,{code:`MODEL_CALL_FAILED`,details:p,message:u,sessionId:E.sessionId}),{next:{done:!0,isError:!0,output:d},session:E}}log.error(l?.message??`model call failed — parking session for retry by the user`,m),D=await emitRecoverableFailedTurn(N,D,{code:`MODEL_CALL_FAILED`,continuationToken:E.continuationToken,details:p,message:u});let h={isError:!0,output:d};return E={...E,outputSchema:void 0},{next:null,session:setHarnessEmissionState(E,D),settledTurn:h}}}let Q=accumulateTurnUsage({previous:getTurnUsageState(E.state),turnId:D.turnId,usage:extractTokenUsageDelta({costUsd:extractGatewayCostUsd(Z.providerMetadata),usage:Z.usage})});E=setTurnUsageState(E,Q);let $;try{$=formatLanguageModelGatewayId(q)}catch{$=void 0}return await setEveAttributes({"$eve.model":$,"$eve.input_tokens":Q.inputTokens,"$eve.output_tokens":Q.outputTokens,"$eve.cache_read_tokens":Q.cacheReadTokens,"$eve.cache_write_tokens":Q.cacheWriteTokens,"$eve.cost_usd":Q.sawCost?Q.costUsd:void 0,"$eve.tool_count":t.tools.size}),handleStepResult({config:t,emit:N,emissionState:D,delegatedCaller:M,modelPromptMessageCount:G.length,promptMessages:W,result:Z,runStep,session:E,runtimeActionTools:Le})}return runStep}function shouldEnableAiSdkTelemetry(e,t){if(e===void 0)return!0;let n=contextStorage.getStore(),r=n?.get(SessionTraceSeedKey);if(r!==void 0)return isSampledTrace(r);let i=n?.get(ChannelInstrumentationKey);return evaluateTracePolicy(e.tracePolicy,{agentName:t,audience:normalizeChannelAudience(i?.metadata.audience),channelType:i?.channelType})}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}function extractTokenUsageDelta(e){let t=e.usage;if(!(t===void 0&&e.costUsd===void 0))return{cacheReadTokens:t?.inputTokenDetails?.cacheReadTokens,cacheWriteTokens:t?.inputTokenDetails?.cacheWriteTokens,costUsd:e.costUsd,inputTokens:t?.inputTokens,outputTokens:t?.outputTokens}}function extractGatewayCostUsd(e){let t=readGatewayMetadata(e)?.cost;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Number(t);return Number.isFinite(e)?e:void 0}}function readGatewayMetadata(e){let t=e?.gateway;return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}function buildModelCallFailureDetails(e){let{catalogSummary:t,error:r,errorId:i,modelCallDetails:a,upstreamRejection:o}=e;if(t!==null){let e={errorId:i,message:t.message,name:t.name,semanticErrorId:t.id,...a};return t.hint!==void 0&&(e.hint=t.hint),e}return o===null?{...formatError(r,i),...a}:{errorId:i,message:toErrorMessage(r),name:o.name,...a}}function buildModelCallFailureLogFields(e){let t={errorId:e.errorId,sessionId:e.sessionId,turnId:e.turnId};return e.recognized?{...t,details:e.modelCallDetails}:{...t,error:e.error}}async function runModelCallRecoveryPipeline(e){let t=e.error,n;for(let r of e.stages){let e=await r({error:t,retryCallOptions:n});if(e.outcome===`recovered`)return e;e.outcome===`failed`&&(t=e.error,n=e.retryCallOptions)}return{outcome:`failed`,error:t}}function withAccumulatedResponseMessages(e){let{stepResult:t}=e;return{content:t.content,finishReason:t.finishReason,...e.invalidInputToolCallIds===void 0?{}:{invalidInputToolCallIds:e.invalidInputToolCallIds},providerMetadata:t.providerMetadata,response:{...t.response,messages:[...e.responseMessages]},text:t.text,toolCalls:t.toolCalls,toolResults:e.toolResults===void 0?t.toolResults:[...e.toolResults],usage:t.usage}}function appendMissingToolResultMessages(e){let t=extractToolResultCallIds(e.responseMessages),n=e.append.filter(e=>!t.has(e.toolCallId));return[...e.responseMessages,...n.length>0?[{role:`tool`,content:[...n]}]:[]]}function getInvalidToolCallInputErrors(e){let t=[];for(let n of e.toolCalls){if(n.toolName===FINAL_OUTPUT_TOOL_NAME)continue;let e=getInvalidToolCallInputError({toolCall:n});e!==void 0&&t.push(e)}return t}function extractToolResultCallIds(e){let t=new Set;for(let n of e)if(Array.isArray(n.content))for(let e of n.content)typeof e==`object`&&e&&e.type===`tool-result`&&t.add(e.toolCallId);return t}function hasUnansweredToolCall(e){let t=new Set,n=new Set;for(let r of e)if(Array.isArray(r.content))for(let e of r.content)typeof e!=`object`||!e||(e.type===`tool-call`&&t.add(e.toolCallId),e.type===`tool-result`&&n.add(e.toolCallId));for(let e of t)if(!n.has(e))return!0;return!1}async function attemptUnsupportedProviderToolRecovery(e){let t=extractUnsupportedProviderToolTypes(e.error);if(t.length===0)return{outcome:`skipped`};let n=[];for(let e of t){let t=resolveFrameworkToolFromUpstreamType(e);t!==null&&!n.includes(t)&&n.push(t)}if(n.length===0)return{outcome:`skipped`};log.warn(`disabling unsupported provider tool(s); retrying step once`,{disabled:n,sessionId:e.sessionId,turnId:e.turnId,upstreamTypes:t});let r={disabledProviderTools:new Set(n),extraSystemNote:buildDisabledToolNote(n)};try{return{outcome:`recovered`,result:await e.runOneModelCall({...r,suppressStepStartedEmission:!0})}}catch(e){return{outcome:`failed`,error:e,retryCallOptions:r}}}function buildDisabledToolNote(e){let t=e.join(`, `);return`The following ${e.length===1?`tool is`:`tools are`} not available with the current model and has been removed: ${t}. Proceed using the remaining tools or your training knowledge.`}function isEmptyModelResponse(e){return e.toolCalls.length===0&&e.toolResults.length===0&&resolveAssistantStepText(e.response.messages,e.text)===null}function rethrowNoOutputAsEmptyResponse(e){throw isNoOutputGeneratedError(e)?new EmptyModelResponseError({cause:e}):e}const EMPTY_RESPONSE_NUDGE=`Your previous reply was empty and was not delivered. Answer now from the tool results above; do not re-run tools or mention this notice.`;function buildEmptyResponseNudge(e){return e?`${EMPTY_RESPONSE_NUDGE} If the current task explicitly requires conditional delivery and there is nothing to report, reply with exactly ${EMPTY_DELIVERY_SENTINEL}.`:EMPTY_RESPONSE_NUDGE}async function attemptEmptyResponseRecovery(e){if(!(e.error instanceof EmptyModelResponseError))return{outcome:`skipped`};log.warn(`empty model response; reissuing the model call once`,{sessionId:e.sessionId,turnId:e.turnId});try{return{outcome:`recovered`,result:await e.runOneModelCall({...e.retryCallOptions,retryReason:`empty-response`,suppressStepStartedEmission:!0,trailingUserNote:buildEmptyResponseNudge(e.emptyDeliveryEnabled)})}}catch(t){return{outcome:`failed`,error:t,retryCallOptions:e.retryCallOptions}}}async function handleStepResult(e){let{config:t,emit:n,promptMessages:r,result:i,runStep:a}=e,{emissionState:o,session:s}=e,c=resolveAssistantStepText(i.response.messages,i.text),l=i.finishReason!==`tool-calls`&&i.toolCalls.length===0&&hasEmptyDeliverySentinel(c),u=getInvalidToolCallInputErrors({toolCalls:i.toolCalls}),d=new Set([...i.invalidInputToolCallIds??[],...i.toolCalls.filter(isInvalidToolCall).map(e=>e.toolCallId),...u.map(e=>e.toolCallId)]),f=l?[]:appendMissingToolResultMessages({append:u.map(e=>createToolResultMessagePartFromToolError(e)),responseMessages:i.response.messages}),p=l?null:c,m=new Set;for(let e of[...i.content??[],...i.toolResults??[]])(e.type===`tool-result`||e.type===`tool-error`)&&e.providerExecuted===!0&&m.add(e.toolCallId);let h=normalizeProviderToolHistory({messages:f,providerExecutedOutcomeIds:m}),g=h.messages,_={...s,compaction:createNextCompactionConfig(s.compaction,e.modelPromptMessageCount,i)},ee=t.workflow===!0?readWorkflowContinuationSecurity(_):void 0;if(ee!==void 0){let e=await getWorkflowSandboxInterrupt(i,ee);if(e!==void 0){if(!isWorkflowRuntimeActionInterrupt(e))throw Error(`Unsupported Workflow interrupt kind "${e.payload.kind}".`);return parkOnWorkflowInterrupt({baseSession:_,emissionState:o,interrupt:e,promptMessages:r,responseMessages:g})}}let v=extractToolApprovalInputRequests({content:i.content??[],excludedCallIds:d}),ne=new Set(v.map(e=>e.action.callId)),re=extractQuestionInputRequests({toolCalls:i.toolCalls,excludedCallIds:new Set([...d,...ne])}),b=[...v,...re],ie=renderPendingApprovalsSnippet(v),ae=[...r,...ie===void 0?[]:[{content:ie,role:`user`}]],S=getAdvertisedTools({delegatedCaller:e.delegatedCaller,session:_,tools:e.runtimeActionTools}),oe=(i.toolCalls??[]).filter(e=>!d.has(e.toolCallId)).filter(t=>e.runtimeActionTools.get(t.toolName)?.runtimeAction!==void 0).filter(e=>S.get(e.toolName)?.runtimeAction===void 0?(log.warn(`runtime action tool call blocked because tool is not advertised`,{callId:e.toolCallId,sessionId:_.sessionId,toolName:e.toolName}),!1):!0).map(e=>createRuntimeActionRequestFromToolCall({toolCall:e,tools:S}));if(oe.length>0){if(b.length===0)return{next:null,session:setHarnessEmissionState(setPendingRuntimeActionBatch({actions:oe,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:[...r]}}),advanceStep(o))};let e=setPendingRuntimeActionBatch({actions:oe,event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},responseMessages:g,session:{..._,history:ae}});return e=appendPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:b,responseMessages:[],session:e}),n&&await n(createInputRequestedEvent({requests:b,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),{next:null,session:setHarnessEmissionState(e,advanceStep(o))}}if(b.length>0){let e=buildResponseAuthorizationTools({authoredTools:t.tools,context:contextStorage.getStore()}),r=appendPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:b,responseAuthRequiredRequestIds:v.filter(t=>{let n=e.get(t.action.toolName)?.approval;return n!==void 0&&typeof n!=`function`&&n.response!==void 0}).map(e=>e.requestId),responseMessages:g,session:{..._,history:ae}});return n&&(await n(createInputRequestedEvent({requests:b,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode),r=setHarnessEmissionState(r,o))),{next:hasDeferredStepInput(r)?a:null,session:r}}let se=findAuthorizationSignalFromToolResults(i.toolResults);if(se){let{challenges:e}=se;if(n){for(let t of getSupersededAuthorizationChallenges(_.state,e))await n(createAuthorizationCompletedEvent({attemptId:t.attemptId,authorization:t.challenge,name:t.name,outcome:`failed`,reason:`Superseded by a newer authorization attempt.`,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));for(let t of e)await n(createAuthorizationRequiredEvent({attemptId:t.attemptId,authorization:t.challenge,name:t.name,description:t.challenge.instructions??`Authorization required for ${t.name}`,webhookUrl:t.hookUrl,sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId}));t.mode===`conversation`&&(o=await emitTurnEpilogue(n,o,t.mode))}return{next:null,session:setHarnessEmissionState({..._,history:[...r],state:setPendingAuthorization(_.state,{challenges:e})},o)}}let ce=g,C=[...r,...ce],w={..._,history:C};return!(w.outputSchema!==void 0&&extractFinalOutput(i)!==void 0)&&(ce.at(-1)?.role===`tool`||h.outcomeEndsResponse||hasDeferredStepInput(w))?(n&&(o=advanceStep(o),w=setHarnessEmissionState(w,o)),{next:a,session:w}):t.mode===`task`?finishTaskTurn({emissionState:o,emit:n,history:r,result:i,schema:w.outputSchema,session:w,stepOutput:p}):finishConversationTurn({emissionState:o,emit:n,history:r,result:i,schema:w.outputSchema,session:w,stepOutput:p})}const OUTPUT_SCHEMA_NOT_FULFILLED={code:`OUTPUT_SCHEMA_NOT_FULFILLED`,message:`The agent could not produce a result matching the requested schema.`};function extractFinalOutput(e){return(e.toolCalls??[]).find(e=>e.toolName===FINAL_OUTPUT_TOOL_NAME&&!isInvalidToolCall(e))?.input}function persistStructuredAssistantTurn(e,t,n){return{...e,history:[...t,{content:JSON.stringify(n),role:`assistant`}],outputSchema:void 0}}async function emitStructuredResult(e,t,n,r,i){return await e(createResultCompletedEvent({result:n,sequence:t.sequence,stepIndex:t.stepIndex,turnId:t.turnId})),emitTurnEpilogue(e,t,r,i)}async function finishTaskTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`task`,s.history),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:a??``},session:s};let c=extractFinalOutput(r);return c===void 0?(s={...s,outputSchema:void 0},t&&await emitFailedStep(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,sessionId:s.sessionId}),{next:{done:!0,isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message},session:s}):(s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`task`,s.history),s=setHarnessEmissionState(s,o)),{next:{done:!0,output:c},session:s})}async function finishConversationTurn(e){let{emit:t,history:n,result:r,schema:i,stepOutput:a}=e,{emissionState:o,session:s}=e;if(i===void 0)return t&&(o=await emitTurnEpilogue(t,o,`conversation`,s.history),s=setHarnessEmissionState(s,o)),{next:null,session:s,settledTurn:{output:a??``}};let c=extractFinalOutput(r);if(c===void 0){s={...s,outputSchema:void 0},t&&(o=await emitRecoverableFailedTurn(t,o,{...OUTPUT_SCHEMA_NOT_FULFILLED,continuationToken:s.continuationToken}),s=setHarnessEmissionState(s,o));let e={isError:!0,output:OUTPUT_SCHEMA_NOT_FULFILLED.message};return{next:null,session:s,settledTurn:e}}return s=persistStructuredAssistantTurn(s,n,c),t&&(o=await emitStructuredResult(t,o,c,`conversation`,s.history),s=setHarnessEmissionState(s,o)),{next:null,session:s,settledTurn:{output:c}}}async function continuePendingWorkflowInterrupt(e){let t=getPendingWorkflowInterrupt(e.session.state);if(t===void 0)return null;let n=t.interrupt;if(!isWorkflowRuntimeActionInterrupt(n))throw Error(`Unsupported Workflow interrupt kind "${n.payload.kind}".`);let i=e.emit===void 0?void 0:createWorkflowLifecycle({emit:e.emit,emissionState:e.emissionState,skipReplayed:!0,tools:e.tools}),a=getWorkflowContinuationSecurity(e.session),o;try{let t=buildWorkflowHostTools({tools:e.tools}),r=e.childResults??[],s=n,c=0;for(;;){o=await continueWorkflowSandboxInterrupt({bridgeRequestLimit:resolveWorkflowSandboxBridgeRequestLimit(e.config.workflowMaxSubagents),continuationSecurity:a,interrupt:s,lifecycle:i,resolution:r[c]?.output,tools:t});let n=await unwrapWorkflowSandboxResult(o,a);if(n.status!==`interrupted`||!isWorkflowRuntimeActionInterrupt(n.interrupt)||c+1>=r.length)break;let l=getWorkflowRuntimeActionInterrupts(n.interrupt)[0];if(l===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);c++,s=l}}catch(e){logError(log,`Workflow interrupt continuation failed`,e),o={error:`workflow_continuation_failed`,message:toErrorMessage(e),retryable:!1}}let s=await unwrapWorkflowSandboxResult(o,a),c=s.status===`interrupted`?s.interrupt:s.output,l=replaceWorkflowToolResult([...e.session.history,...t.responseMessages],n.outerToolCallId,c),u=clearPendingWorkflowInterrupt({...e.session,history:l});if(s.status===`interrupted`){if(!isWorkflowRuntimeActionInterrupt(s.interrupt))throw Error(`Unsupported Workflow interrupt kind "${s.interrupt.payload.kind}".`);let t=e.session.history.length,n=l.slice(0,t),r=l.slice(t);return u={...u,history:n},parkOnWorkflowInterrupt({baseSession:u,emissionState:e.emissionState,interrupt:s.interrupt,promptMessages:n,responseMessages:r})}return{next:e.runStep,session:u}}function replaceWorkflowToolResult(e,t,n){if(t===void 0)return[...e];let r=typeof n==`string`?{type:`text`,value:n}:{type:`json`,value:n};return e.map(e=>{if(e.role!==`tool`)return e;let n=e.content.map(e=>e.type!==`tool-result`||e.toolCallId!==t?e:{...e,output:r});return{...e,content:n}})}function parkOnWorkflowInterrupt(e){let t=getWorkflowRuntimeActionInterrupts(e.interrupt)[0];if(t===void 0)throw Error(`Workflow continuation contains no pending runtime-action interrupt.`);let n={...e.baseSession,history:[...e.promptMessages]};return{next:null,session:setHarnessEmissionState(setPendingWorkflowInterrupt({interrupt:t,responseMessages:e.responseMessages,session:n}),e.emissionState)}}function createNextCompactionConfig(e,t,n){let r={recentWindowSize:e.recentWindowSize,threshold:e.threshold,thresholdPercent:e.thresholdPercent};return n.usage?.inputTokens!==void 0&&(r.lastKnownInputTokens=n.usage.inputTokens,r.lastKnownPromptMessageCount=t),r}async function maybeCompact(e){let{emit:t,emissionState:n}=e,r=e.messages,i=e.session,a=e.historyProjector?.({messages:r,state:i.state})??r,o=e.force===!0||shouldCompact(a,i.compaction),s=shouldCanonicalizeMemory(r);if(!o&&!s)return{compacted:!1,messages:r,session:i};let c=await resolveCompactionModel({compactionModelReference:i.agent.compactionModelReference,model:e.model,modelReference:requireSessionModelReference(i),resolveModel:e.resolveModel}),l=mergeProviderSafetyIdentifier(i.agent.compactionModelReference??requireSessionModelReference(i),c.providerOptions,e.auth);if(t){let e=contextStorage.getStore();e!==void 0&&prepareMemoryCompaction(e,{history:r,state:i.state}),await t(createCompactionRequestedEvent({modelId:formatLanguageModelGatewayId(c.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId,usageInputTokens:getInputTokenCount(a,i.compaction)}),a)}let u=canonicalizeMemoryRecords(r),d=e.historyProjector?.({messages:u.ordinary,state:i.state})??u.ordinary,f=o?await compactMessages([...d],c.model,i.compaction,l,e.telemetry,buildGatewayAttributionHeaders(c.model,e.runtimeIdentity),e.abortSignal,e.force===!0):[...d];if(r=[...u.memory,...f],e.onCompaction)for(let t of e.onCompaction())r.push(t);if(t){let a=contextStorage.getStore();if(a!==void 0&&prepareMemoryCompaction(a,{history:r,state:i.state}),await t(createCompactionCompletedEvent({modelId:formatLanguageModelGatewayId(c.model),sequence:n.sequence,sessionId:i.sessionId,turnId:n.turnId}),e.historyProjector?.({messages:r,state:i.state})??r),a!==void 0){let e=drainMemoryCommit(a);e!==void 0&&(r=[...e.history],i={...i,state:e.state})}}return{compacted:!0,messages:r,session:i}}function resolveApprovalKeyFromTools(e){return t=>{let n=e.get(t.action.toolName);if(n?.approvalKey!==void 0)return n.approvalKey(t.action.input)}}async function runModelCallWithRetries(e,t,n){for(let r=1;;r++){throwIfTurnAborted(n);try{return await e(r)}catch(e){if(throwIfTurnAborted(n),r===3||classifyModelCallError(e)!==`retry`)throw e;let i=500*2**(r-1)+Math.floor(Math.random()*250);log.warn(`model call failed transiently — retrying`,{attempt:r,delayMs:i,sessionId:t.sessionId,turnId:t.turnId,error:e}),await new Promise(e=>setTimeout(e,i))}}}function findAuthorizationSignalFromToolResults(e){let t=contextStorage.getStore();if(t!==void 0)for(let n of e??[]){let e=readToolInterrupt(t,n.toolCallId);if(e!==void 0&&isAuthorizationSignal(e))return e}for(let t of e??[])if(isAuthorizationSignal(t.output))return t.output}export{appendMissingToolResultMessages,createToolLoopHarness};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import{copyFile,mkdir,writeFile}from"node:fs/promises";import{join}from"node:path";import{resolvePackageCompiledFilePath,resolvePackageSourceFilePath}from"#internal/application/package.js";import{createCompiledModuleMapSource}from"#compiler/module-map.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{buildPackageUserAgent}from"#internal/user-agent.js";import{usesParentDevelopmentWorkflowWorld}from"#internal/workflow/development-world-protocol.js";import{readMaterializedAuthoredModuleIndex}from"#internal/materialized-authored-modules.js";import{resolveInstrumentationLayout}from"#internal/instrumentation-layout.js";import{resolveWorkflowWorldImport}from"#internal/workflow/world-target.js";async function writeCompiledArtifactsFiles(e){let i=join(e.outDir,`compiled-artifacts-bootstrap.mjs`),o=join(e.outDir,`compiled-artifacts-instrumentation.mjs`),s=join(e.outDir,`compiled-artifacts-workflow-world.mjs`),c=e.compileResult.manifest.config.experimental?.instrumentationProviders??!1?resolveInstrumentationLayout({agentRoot:e.compileResult.manifest.agentRoot,providersEnabled:!0}):void 0;await mkdir(e.outDir,{recursive:!0}),await writeFile(i,await createCompiledArtifactsBootstrapSource({compileResult:e.compileResult,installModulePath:resolvePackageSourceFilePath(`src/runtime/loaders/bundled-artifacts.ts`),moduleMapPath:i,metadata:e.compileResult.metadata})),await writeFile(s,createWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:i,configuredWorld:e.compileResult.manifest.config.experimental?.workflow?.world,defaultWorld:e.defaultWorkflowWorld}));let l={bootstrapPath:i,workflowWorldPluginPath:s};if(e.compileResult.manifest.instrumentation!==void 0){let t=e.compileResult.manifest.instrumentation.sourceId;await writeFile(o,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:{kind:`module-map`,moduleMapPath:i,sourceId:t}})),l.instrumentationPluginPath=o,l.instrumentationLayout={kind:`file`};let r=e.compileResult.manifest.bindings[t];r?.backing.kind===`filesystem`&&(l.instrumentationSourcePaths=[r.backing.sourcePath])}else c!==void 0&&(await writeFile(o,createInstrumentationPluginSource({agentName:e.compileResult.manifest.config.name,layout:c})),l.instrumentationPluginPath=o,l.instrumentationLayout=generatedInstrumentationLayout(c),l.instrumentationSourcePaths=instrumentationSourcePathsOf(c));return l}function instrumentationSourcePathsOf(e){return e.kind===`file`?[e.modulePath]:Object.values(e.modulePathsBySlot)}async function writeDevelopmentCompiledArtifactsFiles(i){let a=join(i.outDir,`compiled-artifacts-bootstrap.mjs`),o=join(i.outDir,`compiled-artifacts-instrumentation.mjs`),s=join(i.outDir,`compiled-artifacts-workflow-world.mjs`),c=await readMaterializedAuthoredModuleIndex(i.runtimeAppRoot);if(c===void 0)throw Error(`Development generation at "${i.runtimeAppRoot}" is not materialized.`);await mkdir(i.outDir,{recursive:!0}),await writeFile(a,createDevelopmentCompiledArtifactsBootstrapSource(i.compileResult.manifest.config.name)),await writeFile(s,createDevelopmentWorkflowWorldPluginSource({compiledArtifactsBootstrapPath:a,configuredWorld:i.compileResult.manifest.config.experimental?.workflow?.world}));let l={bootstrapPath:a,workflowWorldPluginPath:s};if(i.compileResult.manifest.instrumentation!==void 0){let t=join(i.runtimeAppRoot,`.eve`,`compile`),a=join(i.outDir,`compiled-artifacts-instrumentation-source.mjs`);await copyFile(join(t,c.moduleMap),a),await writeFile(o,createInstrumentationPluginSource({agentName:i.compileResult.manifest.config.name,layout:{kind:`module-map`,moduleMapPath:a,sourceId:i.compileResult.manifest.instrumentation.sourceId}})),l.instrumentationPluginPath=o,l.instrumentationLayout={kind:`file`},l.instrumentationSourcePaths=[a]}else if(c.instrumentation!==void 0){let e=await copyMaterializedInstrumentation({instrumentation:c.instrumentation,outDir:i.outDir,runtimeAppRoot:i.runtimeAppRoot});await writeFile(o,createInstrumentationPluginSource({agentName:i.compileResult.manifest.config.name,layout:e})),l.instrumentationPluginPath=o,l.instrumentationLayout=generatedInstrumentationLayout(e),l.instrumentationSourcePaths=instrumentationSourcePathsOf(e)}return l}function generatedInstrumentationLayout(e){return e.kind===`file`?{kind:`file`}:{kind:`directory`,slots:Object.keys(e.modulePathsBySlot)}}async function copyMaterializedInstrumentation(t){let n=join(t.runtimeAppRoot,`.eve`,`compile`),copyOne=async(i,a)=>{let o=join(t.outDir,`compiled-artifacts-instrumentation-${i}.mjs`);return await copyFile(join(n,a),o),o};if(t.instrumentation.kind===`file`)return{kind:`file`,modulePath:await copyOne(`source`,t.instrumentation.modulePath)};let i={};for(let[e,n]of Object.entries(t.instrumentation.modulePathsBySlot))i[e]=await copyOne(e,n);return{kind:`directory`,modulePathsBySlot:i}}function createDevelopmentCompiledArtifactsBootstrapSource(e){return[`// Generated by eve. Do not edit by hand.`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(e)});`,``,`export default function installDevelopmentCompiledArtifactsPlugin() {}`,``].join(`
|
|
2
2
|
`)}function stripCompiledModuleMapDefaultExport(e){return e.replace(/\nexport default moduleMap;\n?$/,`
|
|
3
3
|
`)}async function createCompiledArtifactsBootstrapSource(e){let t=e.compileResult.manifest.config.name,n=stripCompiledModuleMapDefaultExport(createCompiledModuleMapSource({importSpecifierStyle:`absolute`,manifest:e.compileResult.manifest,moduleMapPath:e.moduleMapPath,programmaticLoaderImportSpecifier:resolvePackageSourceFilePath(`src/internal/programmatic-source-loader.ts`)})).trim();return[`// Generated by eve. Do not edit by hand.`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(e.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/queue-namespace.ts`))};`,``,`installEveWorkflowQueueNamespace(${JSON.stringify(t)});`,``,n,``,`const metadata = ${JSON.stringify(e.metadata,null,2)};`,``,`const manifest = ${JSON.stringify(e.compileResult.manifest,null,2)};`,``,`export function installCompiledArtifactsBootstrap() {`,` installBundledCompiledArtifacts({`,` manifest,`,` metadata,`,` moduleMap,`,` });`,`}`,``,`installCompiledArtifactsBootstrap();`,``,`// Default export satisfies the Nitro plugin contract so this file`,`// can be used directly as a Nitro plugin without a separate wrapper.`,`export default function installCompiledArtifactsPlugin() {`,` // Already installed on import above.`,`}`,``].join(`
|
|
4
|
-
`)}function resolveWorkflowWorldWiring(e){if(e===`@workflow/world-local`){let t=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`));return{moduleImportSpecifier:resolvePackageCompiledFilePath(`src/compiled/${e}/index.js`),extraImportLines:`
|
|
4
|
+
`)}function resolveWorkflowWorldWiring(e){if(e===`@workflow/world-local`){let t=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-data-directory.ts`)),n=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/workflow/local-world-delivery-timeouts.ts`));return{moduleImportSpecifier:resolvePackageCompiledFilePath(`src/compiled/${e}/index.js`),extraImportLines:`
|
|
5
|
+
import { applyLocalWorkflowWorldDeliveryTimeoutDefaults } from ${n};
|
|
5
6
|
import { resolveLocalWorkflowWorldDataDirectory } from ${t};`.trimStart().split(`
|
|
6
|
-
`),runtimeImports:`getWorld, setWorld`,createWorldSource:`
|
|
7
|
+
`),runtimeImports:`getWorld, setWorld`,createWorldSource:`applyLocalWorkflowWorldDeliveryTimeoutDefaults();
|
|
8
|
+
const workflowWorld = await workflowWorldModule.createWorld({
|
|
7
9
|
dataDir: resolveLocalWorkflowWorldDataDirectory(process.cwd()),
|
|
8
10
|
});`}}return e===`@workflow/world-vercel`?{moduleImportSpecifier:resolvePackageCompiledFilePath(`src/compiled/${e}/index.js`),extraImportLines:[],runtimeImports:`getWorld, setWorld`,createWorldSource:`
|
|
9
11
|
const workflowWorld = await workflowWorldModule.createWorld({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.45.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.45.2`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let i=dirname(t);if(i===t)return;t=i}}function tryResolveDirectBuildLocation(e){let i=dirname(e);for(;;){if(basename(i)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(i),`package.json`));if(e!==void 0)return{packageBuildRoot:i,packageRoot:e}}let e=dirname(i);if(e===i)return;i=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let r=realpathSync.native(e),i=tryResolveDirectBuildLocation(r);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(r));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(r)),n=e===void 0?void 0:tryCreatePackageLocation(e);if(n!==void 0)return n}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,join}from"node:path";import{existsSync}from"node:fs";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory}from"#internal/workflow/local-world-data-directory.js";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldValue,encodeDevelopmentWorldValue,serializeDevelopmentWorldError}from"#internal/workflow/development-world-codec.js";import{createWorld}from"#compiled/@workflow/world-local/index.js";function createParentDevelopmentWorkflowWorld(e){return new LocalParentDevelopmentWorkflowWorld(e)}var LocalParentDevelopmentWorkflowWorld=class{#e;#t;#n;#r;#i;#a=!1;#o=!1;constructor(e){if(e.transportSecret.length<16)throw Error(`Development Workflow transport secret is too short to be trusted.`);this.#e=e.agentName,this.#t=e.appRoot,this.#n=e.resolveActiveGenerationId,this.#r=e.transportSecret,this.#i=createWorld({dataDir:resolveLocalWorkflowWorldDataDirectory(e.appRoot),recoverActiveRuns:!1})}async start(){if(this.#o)return;let e=await this.#s(),t=new Set;for(let n of e)this.#p(n)||t.add(n);t.size>0&&console.error(`[eve:dev] ${String(t.size)} active local Workflow run(s) reference development generations that no longer exist (${[...t].join(`, `)}). Their deliveries are quarantined; remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`),await this.#i.start?.(),this.#o=!0,await reenqueueActiveDevelopmentRuns({enqueue:this.#u.bind(this),prefix:deriveEveWorkflowQueuePrefix(this.#e),quarantinedGenerationIds:t,world:this.#i})}async close(){this.#a||(this.#a=!0,this.#o=!1,await this.#i.close?.())}async handleRequest(e){let t=new URL(e.url);if(t.pathname===DEVELOPMENT_WORKFLOW_WORLD_ROUTE)return await this.#c(e);if(t.pathname===DEVELOPMENT_WORKFLOW_STREAM_ROUTE)return await this.#l(e,t)}async#s(){let e=new Set;for(let t of[`pending`,`running`]){let n;do{let i;try{i=await this.#i.runs.list({pagination:{cursor:n,limit:1e3},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)t.workflowName===turnWorkflowReference.workflowId&&e.add(t.deploymentId);n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}return e}async#c(e){if(!this.#f(e)||e.method!==`POST`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});try{let t=decodeDevelopmentWorldValue(await e.text()),n=await this.#d(t);return new Response(encodeDevelopmentWorldValue(n))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#l(e,t){if(!this.#f(e)||e.method!==`GET`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});let n=t.searchParams.get(`runId`),r=t.searchParams.get(`name`),i=t.searchParams.get(`startIndex`);if(n===null||r===null)return Response.json({error:`Workflow stream request is malformed.`},{status:400});let a=i===null||i===``?void 0:Number(i);if(i===``||a!==void 0&&!Number.isInteger(a))return Response.json({error:`Workflow stream start index is invalid.`},{status:400});try{return new Response(await this.#i.streams.get(n,r,a))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#u(...e){let[t,n,r]=e;return await this.#i.queue(t,n,{...r,headers:{...r?.headers,[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]:this.#r}})}async#d(e){if(!isDevelopmentWorldCall(e))throw Error(`Development Workflow World call is malformed.`);let t=[...e.arguments];if(e.operation===`getDeploymentId`||e.operation===`resolveLatestDeploymentId`)return this.#n();if(e.operation===`queue`)return await this.#u(...t);if(e.operation===`streams.writeMulti`&&this.#i.streams.writeMulti===void 0){for(let e of t[2])await this.#i.streams.write(t[0],t[1],e);return}let n=e.operation.indexOf(`.`),r=this.#i[e.operation.slice(0,n)],i=typeof r==`object`&&r?r[e.operation.slice(n+1)]:void 0;if(typeof i==`function`)return await Reflect.apply(i,r,t)}#f(e){let t=e.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);return t!==null&&timingSafeEqualStrings(t,this.#r)}#p(e){return isValidGenerationId(e)?existsSync(join(this.#t,`.eve`,`dev-runtime`,`snapshots`,e,`generation.json`)):!1}};function isValidGenerationId(t){return t.length>0&&t!==`.`&&t!==`..`&&basename(t)===t}const DEVELOPMENT_WORLD_OPERATION_SET=new Set(DEVELOPMENT_WORLD_OPERATIONS);function isDevelopmentWorldCall(e){return isObject(e)&&typeof e.operation==`string`&&DEVELOPMENT_WORLD_OPERATION_SET.has(e.operation)&&Array.isArray(e.arguments)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function reenqueueActiveDevelopmentRuns(e){for(let t of[`pending`,`running`]){let n;do{let i;try{i=await e.world.runs.list({pagination:{cursor:n},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)e.quarantinedGenerationIds.has(t.deploymentId)||await e.enqueue(`${e.prefix}${t.workflowName}`,{runId:t.runId});n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}}export{createParentDevelopmentWorkflowWorld};
|
|
1
|
+
import{basename,join}from"node:path";import{existsSync}from"node:fs";import{LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH,resolveLocalWorkflowWorldDataDirectory}from"#internal/workflow/local-world-data-directory.js";import{turnWorkflowReference}from"#execution/workflow-runtime.js";import{DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,DEVELOPMENT_WORKFLOW_STREAM_ROUTE,DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,DEVELOPMENT_WORKFLOW_WORLD_ROUTE,DEVELOPMENT_WORLD_OPERATIONS}from"#internal/workflow/development-world-protocol.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{timingSafeEqualStrings}from"#internal/nitro/dev-client-address.js";import{decodeDevelopmentWorldValue,encodeDevelopmentWorldValue,serializeDevelopmentWorldError}from"#internal/workflow/development-world-codec.js";import{createWorld}from"#compiled/@workflow/world-local/index.js";import{applyLocalWorkflowWorldDeliveryTimeoutDefaults}from"#internal/workflow/local-world-delivery-timeouts.js";function createParentDevelopmentWorkflowWorld(e){return new LocalParentDevelopmentWorkflowWorld(e)}var LocalParentDevelopmentWorkflowWorld=class{#e;#t;#n;#r;#i;#a=!1;#o=!1;constructor(e){if(e.transportSecret.length<16)throw Error(`Development Workflow transport secret is too short to be trusted.`);this.#e=e.agentName,this.#t=e.appRoot,this.#n=e.resolveActiveGenerationId,this.#r=e.transportSecret,applyLocalWorkflowWorldDeliveryTimeoutDefaults(),this.#i=createWorld({dataDir:resolveLocalWorkflowWorldDataDirectory(e.appRoot),recoverActiveRuns:!1})}async start(){if(this.#o)return;let e=await this.#s(),t=new Set;for(let n of e)this.#p(n)||t.add(n);t.size>0&&console.error(`[eve:dev] ${String(t.size)} active local Workflow run(s) reference development generations that no longer exist (${[...t].join(`, `)}). Their deliveries are quarantined; remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard the app's active local Workflow runs.`),await this.#i.start?.(),this.#o=!0,await reenqueueActiveDevelopmentRuns({enqueue:this.#u.bind(this),prefix:deriveEveWorkflowQueuePrefix(this.#e),quarantinedGenerationIds:t,world:this.#i})}async close(){this.#a||(this.#a=!0,this.#o=!1,await this.#i.close?.())}async handleRequest(e){let t=new URL(e.url);if(t.pathname===DEVELOPMENT_WORKFLOW_WORLD_ROUTE)return await this.#c(e);if(t.pathname===DEVELOPMENT_WORKFLOW_STREAM_ROUTE)return await this.#l(e,t)}async#s(){let e=new Set;for(let t of[`pending`,`running`]){let n;do{let i;try{i=await this.#i.runs.list({pagination:{cursor:n,limit:1e3},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)t.workflowName===turnWorkflowReference.workflowId&&e.add(t.deploymentId);n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}return e}async#c(e){if(!this.#f(e)||e.method!==`POST`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});try{let t=decodeDevelopmentWorldValue(await e.text()),n=await this.#d(t);return new Response(encodeDevelopmentWorldValue(n))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#l(e,t){if(!this.#f(e)||e.method!==`GET`)return Response.json({error:`Workflow World request is not trusted.`},{status:401});let n=t.searchParams.get(`runId`),r=t.searchParams.get(`name`),i=t.searchParams.get(`startIndex`);if(n===null||r===null)return Response.json({error:`Workflow stream request is malformed.`},{status:400});let a=i===null||i===``?void 0:Number(i);if(i===``||a!==void 0&&!Number.isInteger(a))return Response.json({error:`Workflow stream start index is invalid.`},{status:400});try{return new Response(await this.#i.streams.get(n,r,a))}catch(e){return new Response(encodeDevelopmentWorldValue(serializeDevelopmentWorldError(e)),{status:500})}}async#u(...e){let[t,n,r]=e;return await this.#i.queue(t,n,{...r,headers:{...r?.headers,[DEVELOPMENT_WORKFLOW_DELIVERY_HEADER]:this.#r}})}async#d(e){if(!isDevelopmentWorldCall(e))throw Error(`Development Workflow World call is malformed.`);let t=[...e.arguments];if(e.operation===`getDeploymentId`||e.operation===`resolveLatestDeploymentId`)return this.#n();if(e.operation===`queue`)return await this.#u(...t);if(e.operation===`streams.writeMulti`&&this.#i.streams.writeMulti===void 0){for(let e of t[2])await this.#i.streams.write(t[0],t[1],e);return}let n=e.operation.indexOf(`.`),r=this.#i[e.operation.slice(0,n)],i=typeof r==`object`&&r?r[e.operation.slice(n+1)]:void 0;if(typeof i==`function`)return await Reflect.apply(i,r,t)}#f(e){let t=e.headers.get(DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER);return t!==null&&timingSafeEqualStrings(t,this.#r)}#p(e){return isValidGenerationId(e)?existsSync(join(this.#t,`.eve`,`dev-runtime`,`snapshots`,e,`generation.json`)):!1}};function isValidGenerationId(t){return t.length>0&&t!==`.`&&t!==`..`&&basename(t)===t}const DEVELOPMENT_WORLD_OPERATION_SET=new Set(DEVELOPMENT_WORLD_OPERATIONS);function isDevelopmentWorldCall(e){return isObject(e)&&typeof e.operation==`string`&&DEVELOPMENT_WORLD_OPERATION_SET.has(e.operation)&&Array.isArray(e.arguments)}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function reenqueueActiveDevelopmentRuns(e){for(let t of[`pending`,`running`]){let n;do{let i;try{i=await e.world.runs.list({pagination:{cursor:n},resolveData:`none`,status:t})}catch(e){throw Error(`Failed to read the app's active local Workflow runs. Remove "${LOCAL_WORKFLOW_WORLD_DATA_DIRECTORY_RELATIVE_PATH}" to discard them.`,{cause:e})}for(let t of i.data)e.quarantinedGenerationIds.has(t.deploymentId)||await e.enqueue(`${e.prefix}${t.workflowName}`,{runId:t.runId});n=i.hasMore?i.cursor??void 0:void 0}while(n!==void 0)}}export{createParentDevelopmentWorkflowWorld};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Disables world-local's delivery deadlines unless the operator supplied an
|
|
3
|
+
* override. world-local snapshots these values when `createWorld()` constructs
|
|
4
|
+
* its queue and supports `0` as an unbounded timeout. Without this default, a
|
|
5
|
+
* long inline turn can be retried while its original provider call is active.
|
|
6
|
+
*/
|
|
7
|
+
export declare function applyLocalWorkflowWorldDeliveryTimeoutDefaults(env?: Record<string, string | undefined>): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const LOCAL_WORKFLOW_DELIVERY_TIMEOUT_ENV_NAMES=[`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`,`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`];function applyLocalWorkflowWorldDeliveryTimeoutDefaults(e=process.env){for(let t of LOCAL_WORKFLOW_DELIVERY_TIMEOUT_ENV_NAMES)(e[t]===void 0||e[t]===``)&&(e[t]=`0`)}export{applyLocalWorkflowWorldDeliveryTimeoutDefaults};
|