@toren-run/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/apiKeys.d.ts +28 -0
- package/dist/apiKeys.js +40 -0
- package/dist/approvals.d.ts +30 -0
- package/dist/approvals.js +54 -0
- package/dist/blobs.d.ts +12 -0
- package/dist/blobs.js +17 -0
- package/dist/builtins.d.ts +10 -0
- package/dist/builtins.js +244 -0
- package/dist/conversations.d.ts +38 -0
- package/dist/conversations.js +87 -0
- package/dist/db.d.ts +3 -0
- package/dist/db.js +20 -0
- package/dist/digest.d.ts +1 -0
- package/dist/digest.js +13 -0
- package/dist/events.d.ts +20 -0
- package/dist/events.js +4 -0
- package/dist/files.d.ts +28 -0
- package/dist/files.js +27 -0
- package/dist/fold.d.ts +3 -0
- package/dist/fold.js +6 -0
- package/dist/guardians.d.ts +9 -0
- package/dist/guardians.js +14 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +27 -0
- package/dist/leases.d.ts +16 -0
- package/dist/leases.js +30 -0
- package/dist/loop.d.ts +69 -0
- package/dist/loop.js +413 -0
- package/dist/migrate.d.ts +4 -0
- package/dist/migrate.js +167 -0
- package/dist/model.d.ts +42 -0
- package/dist/model.js +1 -0
- package/dist/orchestrator.d.ts +35 -0
- package/dist/orchestrator.js +146 -0
- package/dist/providers/echo.d.ts +9 -0
- package/dist/providers/echo.js +17 -0
- package/dist/providers/mock.d.ts +12 -0
- package/dist/providers/mock.js +15 -0
- package/dist/queue.d.ts +68 -0
- package/dist/queue.js +54 -0
- package/dist/schedules.d.ts +61 -0
- package/dist/schedules.js +128 -0
- package/dist/spawn.d.ts +14 -0
- package/dist/spawn.js +113 -0
- package/dist/store.d.ts +50 -0
- package/dist/store.js +65 -0
- package/dist/tools.d.ts +98 -0
- package/dist/tools.js +14 -0
- package/dist/tracing.d.ts +6 -0
- package/dist/tracing.js +21 -0
- package/dist/worker.d.ts +34 -0
- package/dist/worker.js +176 -0
- package/dist/workflow.d.ts +91 -0
- package/dist/workflow.js +210 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type pg from "pg";
|
|
2
|
+
/**
|
|
3
|
+
* Deployment API keys. Secrets are shown once at
|
|
4
|
+
* creation and stored only as SHA-256 hashes; verification is a hash lookup,
|
|
5
|
+
* so the raw secret never touches a comparison the caller can time.
|
|
6
|
+
*/
|
|
7
|
+
export interface ApiKeyRecord {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
/** First characters of the secret, for display ("trn_ab12cd34…"). */
|
|
11
|
+
prefix: string;
|
|
12
|
+
createdAt: Date;
|
|
13
|
+
revokedAt: Date | null;
|
|
14
|
+
lastUsedAt: Date | null;
|
|
15
|
+
}
|
|
16
|
+
export interface CreatedApiKey extends ApiKeyRecord {
|
|
17
|
+
/** The full secret — returned exactly once, never stored. */
|
|
18
|
+
secret: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function createApiKey(pool: pg.Pool, name: string): Promise<CreatedApiKey>;
|
|
21
|
+
/** Returns the key's identity if the secret matches an unrevoked key, else null. */
|
|
22
|
+
export declare function verifyApiKey(pool: pg.Pool, secret: string): Promise<{
|
|
23
|
+
id: string;
|
|
24
|
+
name: string;
|
|
25
|
+
} | null>;
|
|
26
|
+
/** Revokes a key. Returns false if the key doesn't exist or was already revoked. */
|
|
27
|
+
export declare function revokeApiKey(pool: pg.Pool, id: string): Promise<boolean>;
|
|
28
|
+
export declare function listApiKeys(pool: pg.Pool): Promise<ApiKeyRecord[]>;
|
package/dist/apiKeys.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
const hash = (secret) => createHash("sha256").update(secret).digest("hex");
|
|
3
|
+
const rowToRecord = (r) => ({
|
|
4
|
+
id: String(r.id),
|
|
5
|
+
name: String(r.name),
|
|
6
|
+
prefix: String(r.prefix),
|
|
7
|
+
createdAt: r.created_at,
|
|
8
|
+
revokedAt: r.revoked_at ?? null,
|
|
9
|
+
lastUsedAt: r.last_used_at ?? null,
|
|
10
|
+
});
|
|
11
|
+
export async function createApiKey(pool, name) {
|
|
12
|
+
if (!name.trim())
|
|
13
|
+
throw new Error("api key name must be non-empty");
|
|
14
|
+
const secret = `trn_${randomBytes(20).toString("hex")}`;
|
|
15
|
+
const prefix = secret.slice(0, 12);
|
|
16
|
+
const id = randomUUID();
|
|
17
|
+
const res = await pool.query(`INSERT INTO toren_control.api_keys (id, name, key_hash, prefix) VALUES ($1, $2, $3, $4)
|
|
18
|
+
RETURNING id, name, prefix, created_at, revoked_at, last_used_at`, [id, name.trim(), hash(secret), prefix]);
|
|
19
|
+
return { ...rowToRecord(res.rows[0]), secret };
|
|
20
|
+
}
|
|
21
|
+
/** Returns the key's identity if the secret matches an unrevoked key, else null. */
|
|
22
|
+
export async function verifyApiKey(pool, secret) {
|
|
23
|
+
if (!secret)
|
|
24
|
+
return null;
|
|
25
|
+
const res = await pool.query(`UPDATE toren_control.api_keys SET last_used_at = now()
|
|
26
|
+
WHERE key_hash = $1 AND revoked_at IS NULL
|
|
27
|
+
RETURNING id, name`, [hash(secret)]);
|
|
28
|
+
const row = res.rows[0];
|
|
29
|
+
return row ? { id: String(row.id), name: String(row.name) } : null;
|
|
30
|
+
}
|
|
31
|
+
/** Revokes a key. Returns false if the key doesn't exist or was already revoked. */
|
|
32
|
+
export async function revokeApiKey(pool, id) {
|
|
33
|
+
const res = await pool.query(`UPDATE toren_control.api_keys SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL`, [id]);
|
|
34
|
+
return (res.rowCount ?? 0) > 0;
|
|
35
|
+
}
|
|
36
|
+
export async function listApiKeys(pool) {
|
|
37
|
+
const res = await pool.query(`SELECT id, name, prefix, created_at, revoked_at, last_used_at
|
|
38
|
+
FROM toren_control.api_keys ORDER BY created_at DESC`);
|
|
39
|
+
return res.rows.map(rowToRecord);
|
|
40
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { PgStateStore } from "./store.js";
|
|
2
|
+
import type { QueueAdapter } from "./queue.js";
|
|
3
|
+
import type { PgLeases } from "./leases.js";
|
|
4
|
+
export interface PendingApproval {
|
|
5
|
+
runId: string;
|
|
6
|
+
taskId: string;
|
|
7
|
+
stepId: string;
|
|
8
|
+
tool: string;
|
|
9
|
+
args: unknown;
|
|
10
|
+
}
|
|
11
|
+
/** Unresolved ApprovalRequested events across non-terminal runs (or one run). */
|
|
12
|
+
export declare function listPendingApprovals(store: PgStateStore, runId?: string): Promise<PendingApproval[]>;
|
|
13
|
+
export interface ResolveApprovalDeps {
|
|
14
|
+
store: PgStateStore;
|
|
15
|
+
leases: PgLeases;
|
|
16
|
+
queue: QueueAdapter;
|
|
17
|
+
}
|
|
18
|
+
export interface ResolveApprovalReq {
|
|
19
|
+
runId: string;
|
|
20
|
+
taskId: string;
|
|
21
|
+
stepId: string;
|
|
22
|
+
granted: boolean;
|
|
23
|
+
by: string;
|
|
24
|
+
comment?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Append ApprovalResolved to the parked task's stream (taking its lease
|
|
28
|
+
* briefly) and nudge the orchestrator so the run resumes.
|
|
29
|
+
*/
|
|
30
|
+
export declare function resolveApproval(deps: ResolveApprovalDeps, req: ResolveApprovalReq): Promise<void>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { effectiveEvents } from "./fold.js";
|
|
2
|
+
/** Unresolved ApprovalRequested events across non-terminal runs (or one run). */
|
|
3
|
+
export async function listPendingApprovals(store, runId) {
|
|
4
|
+
const runIds = runId ? [runId] : await store.listNonTerminalRuns();
|
|
5
|
+
const pending = [];
|
|
6
|
+
for (const rid of runIds) {
|
|
7
|
+
const runEff = effectiveEvents(await store.read(rid, "run"));
|
|
8
|
+
const taskIds = runEff
|
|
9
|
+
.filter((e) => e.type === "WavePlanned")
|
|
10
|
+
.flatMap((e) => e.payload.tasks.map((t) => t.taskId));
|
|
11
|
+
for (const taskId of taskIds) {
|
|
12
|
+
const eff = effectiveEvents(await store.read(rid, `task:${taskId}`));
|
|
13
|
+
const resolved = new Set(eff.filter((e) => e.type === "ApprovalResolved").map((e) => String(e.payload.stepId)));
|
|
14
|
+
for (const e of eff) {
|
|
15
|
+
if (e.type === "ApprovalRequested" && !resolved.has(String(e.payload.stepId))) {
|
|
16
|
+
pending.push({
|
|
17
|
+
runId: rid, taskId,
|
|
18
|
+
stepId: String(e.payload.stepId),
|
|
19
|
+
tool: String(e.payload.tool),
|
|
20
|
+
args: e.payload.args,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return pending;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Append ApprovalResolved to the parked task's stream (taking its lease
|
|
30
|
+
* briefly) and nudge the orchestrator so the run resumes.
|
|
31
|
+
*/
|
|
32
|
+
export async function resolveApproval(deps, req) {
|
|
33
|
+
const streamId = `task:${req.taskId}`;
|
|
34
|
+
const lease = await deps.leases.acquire(req.runId, streamId, `approvals-${req.by}`, 30);
|
|
35
|
+
if (!lease)
|
|
36
|
+
throw new Error(`task ${req.taskId} is currently leased — is a worker still running it?`);
|
|
37
|
+
try {
|
|
38
|
+
const raw = await deps.store.read(req.runId, streamId);
|
|
39
|
+
const head = raw.at(-1)?.seq ?? 0;
|
|
40
|
+
const r = await deps.store.append(req.runId, streamId, head, [
|
|
41
|
+
{
|
|
42
|
+
type: "ApprovalResolved",
|
|
43
|
+
payload: { v: 1, stepId: req.stepId, granted: req.granted, by: req.by, comment: req.comment },
|
|
44
|
+
},
|
|
45
|
+
]);
|
|
46
|
+
if (!r.ok)
|
|
47
|
+
throw new Error("task stream advanced concurrently; retry the approval");
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
await deps.leases.release(lease);
|
|
51
|
+
}
|
|
52
|
+
// Wake the task, then the orchestrator will absorb the outcome.
|
|
53
|
+
await deps.queue.send("tasks-short", { kind: "task", runId: req.runId, taskId: req.taskId, dedupeKey: `approve-${req.taskId}-${req.stepId}` });
|
|
54
|
+
}
|
package/dist/blobs.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type pg from "pg";
|
|
2
|
+
export interface BlobRef {
|
|
3
|
+
runId: string;
|
|
4
|
+
key: string;
|
|
5
|
+
}
|
|
6
|
+
export declare class PgBlobs {
|
|
7
|
+
private pool;
|
|
8
|
+
private schema;
|
|
9
|
+
constructor(pool: pg.Pool, schema: string);
|
|
10
|
+
put(runId: string, key: string, data: Buffer): Promise<BlobRef>;
|
|
11
|
+
get(ref: BlobRef): Promise<Buffer | null>;
|
|
12
|
+
}
|
package/dist/blobs.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export class PgBlobs {
|
|
2
|
+
pool;
|
|
3
|
+
schema;
|
|
4
|
+
constructor(pool, schema) {
|
|
5
|
+
this.pool = pool;
|
|
6
|
+
this.schema = schema;
|
|
7
|
+
}
|
|
8
|
+
async put(runId, key, data) {
|
|
9
|
+
await this.pool.query(`INSERT INTO ${this.schema}.blobs (run_id, key, data) VALUES ($1, $2, $3)
|
|
10
|
+
ON CONFLICT (run_id, key) DO UPDATE SET data = EXCLUDED.data`, [runId, key, data]);
|
|
11
|
+
return { runId, key };
|
|
12
|
+
}
|
|
13
|
+
async get(ref) {
|
|
14
|
+
const r = await this.pool.query(`SELECT data FROM ${this.schema}.blobs WHERE run_id = $1 AND key = $2`, [ref.runId, ref.key]);
|
|
15
|
+
return r.rows[0]?.data ?? null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type ToolDefAny } from "./tools.js";
|
|
2
|
+
export declare const BUILTIN_TOOLS: Record<string, ToolDefAny>;
|
|
3
|
+
/** Env each builtin needs — folded into the agent's required env by the loader. */
|
|
4
|
+
export declare const BUILTIN_TOOL_ENV: Record<string, string[]>;
|
|
5
|
+
/**
|
|
6
|
+
* The toolkit `sandbox: true` grants: a computer for the agent. bash gates on
|
|
7
|
+
* approval by default; workspace file operations are free (their blast radius
|
|
8
|
+
* is the workspace itself).
|
|
9
|
+
*/
|
|
10
|
+
export declare const SANDBOX_TOOLKIT: ToolDefAny[];
|
package/dist/builtins.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { defineTool } from "./tools.js";
|
|
4
|
+
/**
|
|
5
|
+
* Built-in tools: declared by name in agent.yaml (`builtin_tools: [web_search]`),
|
|
6
|
+
* no handler to write. Each carries the env it needs; the loader folds that into
|
|
7
|
+
* the agent's required env so a missing key fails fast at startup, not mid-run.
|
|
8
|
+
*/
|
|
9
|
+
const webSearch = defineTool({
|
|
10
|
+
name: "web_search",
|
|
11
|
+
description: "Search the live web. Returns JSON with a short answer (when available) and the top results as {title, url, snippet}.",
|
|
12
|
+
input: z.object({
|
|
13
|
+
query: z.string().describe("what to search for"),
|
|
14
|
+
max_results: z.number().int().min(1).max(10).default(5),
|
|
15
|
+
}),
|
|
16
|
+
effects: "none",
|
|
17
|
+
idempotency: "keyed",
|
|
18
|
+
approval: "never",
|
|
19
|
+
handler: async ({ query, max_results }, ctx) => {
|
|
20
|
+
const res = await fetch("https://api.tavily.com/search", {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: {
|
|
23
|
+
"content-type": "application/json",
|
|
24
|
+
authorization: `Bearer ${ctx.env.TAVILY_API_KEY}`,
|
|
25
|
+
},
|
|
26
|
+
body: JSON.stringify({ query, max_results, include_answer: "basic" }),
|
|
27
|
+
});
|
|
28
|
+
if (!res.ok) {
|
|
29
|
+
const detail = (await res.text().catch(() => "")).slice(0, 200);
|
|
30
|
+
throw new Error(`web_search: tavily returned HTTP ${res.status}${detail ? ` (${detail})` : ""}`);
|
|
31
|
+
}
|
|
32
|
+
const body = (await res.json());
|
|
33
|
+
return JSON.stringify({
|
|
34
|
+
answer: body.answer,
|
|
35
|
+
results: (body.results ?? []).map((r) => ({ title: r.title, url: r.url, snippet: r.content })),
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const readAttachment = defineTool({
|
|
40
|
+
name: "read_attachment",
|
|
41
|
+
description: "Read one page of an attached file. Attachments are listed in the conversation with their file_id and page count; call again with the next page number to keep reading.",
|
|
42
|
+
input: z.object({
|
|
43
|
+
file_id: z.string().describe("from the attachment list"),
|
|
44
|
+
page: z.number().int().min(1).default(1),
|
|
45
|
+
}),
|
|
46
|
+
effects: "none",
|
|
47
|
+
idempotency: "keyed",
|
|
48
|
+
approval: "never",
|
|
49
|
+
handler: async ({ file_id, page }, ctx) => {
|
|
50
|
+
if (!ctx.files)
|
|
51
|
+
throw new Error("read_file: this deployment has no file store configured");
|
|
52
|
+
const f = await ctx.files.get(file_id);
|
|
53
|
+
if (!f)
|
|
54
|
+
return JSON.stringify({ error: `no file with id ${file_id}; check the attachment list` });
|
|
55
|
+
const text = f.pages[page - 1];
|
|
56
|
+
if (text === undefined) {
|
|
57
|
+
return JSON.stringify({ error: `page ${page} is out of range`, name: f.name, pages: f.pages.length });
|
|
58
|
+
}
|
|
59
|
+
return JSON.stringify({ name: f.name, page, of: f.pages.length, text });
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
const BASH_OUTPUT_CAP = 8_000; // chars kept from each of head and tail per stream
|
|
63
|
+
function capOutput(s) {
|
|
64
|
+
if (s.length <= BASH_OUTPUT_CAP * 2)
|
|
65
|
+
return s;
|
|
66
|
+
return `${s.slice(0, BASH_OUTPUT_CAP)}\n[... ${s.length - BASH_OUTPUT_CAP * 2} chars elided ...]\n${s.slice(-BASH_OUTPUT_CAP)}`;
|
|
67
|
+
}
|
|
68
|
+
function needSandbox(ctx) {
|
|
69
|
+
if (!ctx.sandbox)
|
|
70
|
+
throw new Error("this deployment has no sandbox backend configured (is docker available?)");
|
|
71
|
+
return ctx.sandbox;
|
|
72
|
+
}
|
|
73
|
+
/** Workspace file tools, pi-style: models edit reliably with exact strings, not sed. */
|
|
74
|
+
const wsReadFile = defineTool({
|
|
75
|
+
name: "read_file",
|
|
76
|
+
description: "Read a file from the workspace. Returns the content with 1-indexed line numbers.",
|
|
77
|
+
input: z.object({
|
|
78
|
+
path: z.string().describe("workspace-relative path"),
|
|
79
|
+
offset: z.number().int().min(1).default(1).describe("first line to read"),
|
|
80
|
+
limit: z.number().int().min(1).max(2000).default(500),
|
|
81
|
+
}),
|
|
82
|
+
effects: "sandbox",
|
|
83
|
+
idempotency: "keyed",
|
|
84
|
+
approval: "never",
|
|
85
|
+
handler: async ({ path, offset, limit }, ctx) => {
|
|
86
|
+
const content = await needSandbox(ctx).readFile(path);
|
|
87
|
+
const lines = content.split("\n");
|
|
88
|
+
const slice = lines.slice(offset - 1, offset - 1 + limit);
|
|
89
|
+
const numbered = slice.map((l, i) => `${offset + i}\t${l}`).join("\n");
|
|
90
|
+
return JSON.stringify({ path, lines: lines.length, from: offset, text: capOutput(numbered) });
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
const wsWriteFile = defineTool({
|
|
94
|
+
name: "write_file",
|
|
95
|
+
description: "Create or overwrite a file in the workspace.",
|
|
96
|
+
input: z.object({ path: z.string(), content: z.string() }),
|
|
97
|
+
effects: "sandbox",
|
|
98
|
+
idempotency: "keyed",
|
|
99
|
+
approval: "never",
|
|
100
|
+
handler: async ({ path, content }, ctx) => {
|
|
101
|
+
await needSandbox(ctx).writeFile(path, content);
|
|
102
|
+
return JSON.stringify({ path, bytes: Buffer.byteLength(content) });
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
const wsEditFile = defineTool({
|
|
106
|
+
name: "edit_file",
|
|
107
|
+
description: "Replace an exact string in a workspace file. old_string must appear exactly once unless replace_all is set; include enough surrounding context to make it unique.",
|
|
108
|
+
input: z.object({
|
|
109
|
+
path: z.string(),
|
|
110
|
+
old_string: z.string(),
|
|
111
|
+
new_string: z.string(),
|
|
112
|
+
replace_all: z.boolean().default(false),
|
|
113
|
+
}),
|
|
114
|
+
effects: "sandbox",
|
|
115
|
+
idempotency: "keyed",
|
|
116
|
+
approval: "never",
|
|
117
|
+
handler: async ({ path, old_string, new_string, replace_all }, ctx) => {
|
|
118
|
+
const sandbox = needSandbox(ctx);
|
|
119
|
+
const content = await sandbox.readFile(path);
|
|
120
|
+
const count = content.split(old_string).length - 1;
|
|
121
|
+
if (count === 0)
|
|
122
|
+
return JSON.stringify({ error: "old_string not found", path });
|
|
123
|
+
if (count > 1 && !replace_all)
|
|
124
|
+
return JSON.stringify({ error: `old_string appears ${count} times; add context or set replace_all`, path });
|
|
125
|
+
const next = replace_all ? content.split(old_string).join(new_string) : content.replace(old_string, new_string);
|
|
126
|
+
await sandbox.writeFile(path, next);
|
|
127
|
+
return JSON.stringify({ path, replacements: replace_all ? count : 1 });
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
const bash = defineTool({
|
|
131
|
+
name: "bash",
|
|
132
|
+
description: "Run a shell command in this run's persistent workspace. The workspace survives crashes and restarts; " +
|
|
133
|
+
"files you create stay for later commands. Commands run in a sandbox container with no credentials.",
|
|
134
|
+
input: z.object({
|
|
135
|
+
command: z.string().describe("the shell command"),
|
|
136
|
+
timeout_seconds: z.number().int().min(1).max(600).default(120),
|
|
137
|
+
}),
|
|
138
|
+
effects: "sandbox",
|
|
139
|
+
idempotency: "keyed",
|
|
140
|
+
approval: "always",
|
|
141
|
+
handler: async ({ command, timeout_seconds }, ctx) => {
|
|
142
|
+
if (!ctx.sandbox)
|
|
143
|
+
throw new Error("bash: this deployment has no sandbox backend configured (is docker available?)");
|
|
144
|
+
const r = await ctx.sandbox.exec(command, { timeoutMs: timeout_seconds * 1000 });
|
|
145
|
+
return JSON.stringify({ exit_code: r.exitCode, stdout: capOutput(r.stdout), stderr: capOutput(r.stderr) });
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
// ---- sql_query: read-only database access as a tool.
|
|
149
|
+
// Defense in depth on top of the STRONGLY RECOMMENDED read-only DB role:
|
|
150
|
+
// only a single SELECT/WITH runs, forbidden keywords are rejected, stacked
|
|
151
|
+
// statements are blocked, the result is row-capped, and a statement timeout
|
|
152
|
+
// bounds a heavy query. Pools are cached per connection string.
|
|
153
|
+
const sqlPools = new Map();
|
|
154
|
+
function sqlPool(url) {
|
|
155
|
+
let p = sqlPools.get(url);
|
|
156
|
+
if (!p) {
|
|
157
|
+
p = new pg.Pool({ connectionString: url, max: 2, statement_timeout: 10_000, query_timeout: 12_000 });
|
|
158
|
+
sqlPools.set(url, p);
|
|
159
|
+
}
|
|
160
|
+
return p;
|
|
161
|
+
}
|
|
162
|
+
const SELECT_ONLY = /^\s*(with[\s\S]+\bselect\b|select)\b/i;
|
|
163
|
+
const FORBIDDEN = /\b(insert|update|delete|drop|alter|create|truncate|grant|revoke|copy|call|merge|vacuum|reindex|comment|do|set|begin|commit)\b/i;
|
|
164
|
+
const sqlQuery = defineTool({
|
|
165
|
+
name: "sql_query",
|
|
166
|
+
description: "Run a READ-ONLY SQL query (a single SELECT) against the configured database and get the rows back as JSON. Use standard SQL; results are capped.",
|
|
167
|
+
input: z.object({
|
|
168
|
+
query: z.string().describe("a single read-only SELECT statement"),
|
|
169
|
+
limit: z.number().int().min(1).max(500).default(100),
|
|
170
|
+
}),
|
|
171
|
+
effects: "none",
|
|
172
|
+
idempotency: "keyed",
|
|
173
|
+
approval: "never",
|
|
174
|
+
handler: async ({ query, limit }, ctx) => {
|
|
175
|
+
const url = ctx.env.SQL_DATABASE_URL;
|
|
176
|
+
if (!url)
|
|
177
|
+
throw new Error("sql_query: SQL_DATABASE_URL is not configured for this agent");
|
|
178
|
+
const q = query.trim().replace(/;\s*$/, "");
|
|
179
|
+
if (q.includes(";"))
|
|
180
|
+
return JSON.stringify({ error: "only one statement is allowed (no ';')" });
|
|
181
|
+
if (!SELECT_ONLY.test(q))
|
|
182
|
+
return JSON.stringify({ error: "only a read-only SELECT (or WITH ... SELECT) is allowed" });
|
|
183
|
+
if (FORBIDDEN.test(q))
|
|
184
|
+
return JSON.stringify({ error: "the query contains a forbidden (write/DDL) keyword; this tool is read-only" });
|
|
185
|
+
try {
|
|
186
|
+
// Wrap so a missing LIMIT can never return an unbounded result set.
|
|
187
|
+
const res = await sqlPool(url).query(`SELECT * FROM (${q}) AS _toren_q LIMIT ${limit}`);
|
|
188
|
+
const out = JSON.stringify({ rowCount: res.rowCount, truncated: (res.rowCount ?? 0) >= limit, rows: res.rows });
|
|
189
|
+
return out.length > 24_000 ? JSON.stringify({ rowCount: res.rowCount, note: "result too large; add columns/filters or a smaller limit", rows: res.rows.slice(0, 10) }) : out;
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
return JSON.stringify({ error: `query failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
// ---- run_process / check_run: the spawn arc. A conversation triggers a named
|
|
197
|
+
// process as a durable background run; a watcher wakes the session when it
|
|
198
|
+
// settles, so the agent messages the user in-channel without polling. The
|
|
199
|
+
// child runId derives from the tool-use id, so a crash-window re-run finds the
|
|
200
|
+
// run already exists — spawning is effectively-once.
|
|
201
|
+
const runProcess = defineTool({
|
|
202
|
+
name: "run_process",
|
|
203
|
+
description: "Start one of this agent's named processes as a background run. It executes durably on the workers while this conversation continues; a message lands in this conversation when it settles, and check_run polls it on demand.",
|
|
204
|
+
input: z.object({
|
|
205
|
+
process: z.string().describe("the process name to run"),
|
|
206
|
+
input: z.string().describe("the input handed to the process run"),
|
|
207
|
+
}),
|
|
208
|
+
effects: "none",
|
|
209
|
+
idempotency: "keyed",
|
|
210
|
+
approval: "never",
|
|
211
|
+
handler: async ({ process, input }, ctx) => {
|
|
212
|
+
if (!ctx.processes)
|
|
213
|
+
throw new Error("run_process: background processes are not wired in this deployment");
|
|
214
|
+
const r = await ctx.processes.start({ process, input, parentRunId: ctx.runId, parentTaskId: ctx.taskId, toolUseId: ctx.toolUseId });
|
|
215
|
+
return JSON.stringify({ run_id: r.runId, process, status: r.started ? "started" : "already_running" });
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
const checkRun = defineTool({
|
|
219
|
+
name: "check_run",
|
|
220
|
+
description: "Check a background run started with run_process: status, per-wave progress from its event log, and the output once it finishes.",
|
|
221
|
+
input: z.object({
|
|
222
|
+
run_id: z.string().describe("from run_process"),
|
|
223
|
+
}),
|
|
224
|
+
effects: "none",
|
|
225
|
+
idempotency: "keyed",
|
|
226
|
+
approval: "never",
|
|
227
|
+
handler: async ({ run_id }, ctx) => {
|
|
228
|
+
if (!ctx.processes)
|
|
229
|
+
throw new Error("check_run: background processes are not wired in this deployment");
|
|
230
|
+
const s = await ctx.processes.status(run_id);
|
|
231
|
+
if (!s)
|
|
232
|
+
return JSON.stringify({ error: `no run ${run_id}` });
|
|
233
|
+
return JSON.stringify({ run_id: s.runId, process: s.process, status: s.status, waves: s.waves, ...(s.output !== undefined ? { output: s.output } : {}), ...(s.error !== undefined ? { error: s.error } : {}) });
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
export const BUILTIN_TOOLS = { web_search: webSearch, read_attachment: readAttachment, sql_query: sqlQuery, bash, run_process: runProcess, check_run: checkRun };
|
|
237
|
+
/** Env each builtin needs — folded into the agent's required env by the loader. */
|
|
238
|
+
export const BUILTIN_TOOL_ENV = { web_search: ["TAVILY_API_KEY"], read_attachment: [], sql_query: ["SQL_DATABASE_URL"], bash: [], run_process: [], check_run: [] };
|
|
239
|
+
/**
|
|
240
|
+
* The toolkit `sandbox: true` grants: a computer for the agent. bash gates on
|
|
241
|
+
* approval by default; workspace file operations are free (their blast radius
|
|
242
|
+
* is the workspace itself).
|
|
243
|
+
*/
|
|
244
|
+
export const SANDBOX_TOOLKIT = [bash, wsReadFile, wsWriteFile, wsEditFile];
|