@withgateway/sdk 0.4.0 → 0.9.1
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/dist/agents/index.d.mts +573 -0
- package/dist/agents/index.d.ts +573 -0
- package/dist/agents/index.js +1443 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/agents/index.mjs +1394 -0
- package/dist/agents/index.mjs.map +1 -0
- package/dist/apiError-DHpfbmdx.d.mts +17 -0
- package/dist/apiError-DHpfbmdx.d.ts +17 -0
- package/dist/cli.js +5655 -1890
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +5769 -2005
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.d.mts +3 -1
- package/dist/files/index.d.ts +3 -1
- package/dist/files/index.js +418 -120
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +418 -120
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.js +346 -136
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +346 -136
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-DUHmS74p.d.ts → index-DIN14Lhg.d.ts} +27 -4
- package/dist/{index-mJhG3vZU.d.mts → index-DuB-eQ0Z.d.mts} +27 -4
- package/dist/index.d.mts +7 -4
- package/dist/index.d.ts +7 -4
- package/dist/index.js +2862 -438
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2820 -431
- package/dist/index.mjs.map +1 -1
- package/dist/media-CQUC7TkS.d.mts +39 -0
- package/dist/media-DQnBloaX.d.ts +39 -0
- package/dist/replay/index.d.mts +1 -1
- package/dist/replay/index.d.ts +1 -1
- package/dist/replay/index.js.map +1 -1
- package/dist/replay/index.mjs.map +1 -1
- package/dist/traces/index.d.mts +3 -1
- package/dist/traces/index.d.ts +3 -1
- package/dist/traces/index.js +418 -120
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +418 -120
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +3 -2
- package/dist/tracing/index.d.ts +3 -2
- package/dist/tracing/index.js +257 -16
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +257 -16
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/transport-CpRe7zgd.d.mts +123 -0
- package/dist/transport-CpRe7zgd.d.ts +123 -0
- package/dist/worlds/index.d.mts +2086 -1749
- package/dist/worlds/index.d.ts +2086 -1749
- package/dist/worlds/index.js +1471 -269
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +1466 -265
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +6 -1
- package/runtime/gatewaysdk/environment/_bundle.py +4 -6
- package/runtime/gatewaysdk/environment/_world.py +24 -1
- package/runtime/gatewaysdk/environment/bundle_manifest.py +243 -0
- package/runtime/gatewaysdk/environment/runtime.py +45 -2
- package/runtime/gatewaysdk/environment/schema/__main__.py +2 -2
- package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +8 -23
- package/runtime/gatewaysdk/environment/schema/api.py +27 -7
- package/runtime/gatewaysdk/environment/schema/assertions.py +7 -1
- package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +2 -0
- package/runtime/gatewaysdk/environment/schema/call_capture.py +13 -1
- package/runtime/gatewaysdk/environment/schema/call_log.py +66 -0
- package/runtime/gatewaysdk/environment/schema/call_redaction.py +6 -0
- package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
- package/runtime/gatewaysdk/environment/schema/conform.py +32 -8
- package/runtime/gatewaysdk/environment/schema/connector.py +5 -0
- package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
- package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
- package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +9 -19
- package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
- package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
- package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
- package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
- package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
- package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
- package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
- package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
- package/runtime/gatewaysdk/environment/schema/database/base.py +2 -2
- package/runtime/gatewaysdk/environment/schema/database/guard.py +2 -1
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +27 -1
- package/runtime/gatewaysdk/environment/schema/host.py +74 -11
- package/runtime/gatewaysdk/environment/schema/host_browser.py +48 -0
- package/runtime/gatewaysdk/environment/schema/host_control.py +33 -2
- package/runtime/gatewaysdk/environment/schema/host_handoff.py +4 -1
- package/runtime/gatewaysdk/environment/schema/host_requests.py +14 -0
- package/runtime/gatewaysdk/environment/schema/host_session.py +13 -2
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +6 -0
- package/runtime/gatewaysdk/environment/schema/host_versions.py +96 -19
- package/runtime/gatewaysdk/environment/schema/journal.py +10 -4
- package/runtime/gatewaysdk/environment/schema/local.py +33 -7
- package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
- package/runtime/gatewaysdk/environment/schema/page_checks.py +123 -0
- package/runtime/gatewaysdk/environment/schema/platform.py +33 -480
- package/runtime/gatewaysdk/environment/schema/platform_templates.py +332 -0
- package/runtime/gatewaysdk/environment/schema/request_ledger.py +4 -1
- package/runtime/gatewaysdk/environment/schema/run_parameters.py +25 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +49 -4
- package/runtime/gatewaysdk/environment/schema/scaffold.py +369 -218
- package/runtime/gatewaysdk/environment/schema/session_files.py +13 -2
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +20 -24
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +11 -11
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +9 -9
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +40 -9
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +17 -2
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +3 -2
- package/runtime/gatewaysdk/environment/schema/slack.py +55 -10
- package/runtime/gatewaysdk/environment/schema/snapshot.py +30 -4
- package/runtime/gatewaysdk/environment/schema/tasks.py +25 -2
- package/runtime/gatewaysdk/environment/schema/template_record.py +131 -0
- package/runtime/gatewaysdk/environment/schema/tools_world.py +26 -5
- package/runtime/gatewaysdk/environment/schema/ui.py +54 -33
- package/runtime/gatewaysdk/environment/schema/ui_interactions.py +419 -0
- package/runtime/gatewaysdk/environment/schema/ui_recorder.js +895 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay.py +366 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay_record.LICENSE +25 -0
- package/runtime/gatewaysdk/environment/schema/ui_replay_record.js +109 -0
- package/runtime/gatewaysdk/environment/schema/validation.py +10 -1
- package/runtime/gatewaysdk/environment/schema/verbs.py +6 -0
- package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
- package/runtime/gatewaysdk/environment/schema/worker.py +5 -1
- package/runtime/gatewaysdk/environment/schema/workers.py +8 -1
- package/runtime/gatewaysdk/environment/schema/world_host.py +64 -18
- package/runtime/gatewaysdk/environment/schema/world_tests.py +74 -0
- package/runtime/gatewaysdk/environment/secret_values.py +1 -1
- package/runtime/gatewaysdk/environment/world.py +34 -43
- package/runtime/gatewaysdk/environment/world_session_contract.py +7 -34
- package/skills/benchmarks-getting-started/SKILL.md +1 -1
- package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
- package/skills/connector-schema-authoring/SKILL.md +20 -24
- package/skills/connector-schema-authoring/connector-worlds.md +155 -13
- package/skills/connector-schema-authoring/world-schema.md +36 -29
- package/skills/world-data-ingestion/SKILL.md +11 -11
- package/skills/worlds-getting-started/SKILL.md +9 -9
- package/skills/worlds-getting-started/references/cli-mcp-map.md +45 -12
- package/skills/worlds-getting-started/references/gotchas.md +40 -9
- package/skills/worlds-getting-started/references/journal-checks.md +17 -2
- package/skills/worlds-getting-started/references/new-world-sandbox.md +1 -1
- package/skills/worlds-getting-started/references/ui-map.md +3 -2
- package/dist/media-BIApiPzS.d.mts +0 -102
- package/dist/media-BIApiPzS.d.ts +0 -102
|
@@ -0,0 +1,1394 @@
|
|
|
1
|
+
import { createRequire as __gatewayCreateRequire } from "module";
|
|
2
|
+
const require = __gatewayCreateRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/worlds/apiError.ts
|
|
5
|
+
var ApiError = class extends Error {
|
|
6
|
+
constructor(status, method, path, text) {
|
|
7
|
+
const parsed = parseErrorBody(text, status);
|
|
8
|
+
super(`${method} ${path} -> ${status}: ${parsed.detail}`);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.text = text;
|
|
11
|
+
this.name = "ApiError";
|
|
12
|
+
this.code = parsed.code;
|
|
13
|
+
}
|
|
14
|
+
status;
|
|
15
|
+
text;
|
|
16
|
+
code;
|
|
17
|
+
};
|
|
18
|
+
var DETAIL_LIMIT = 600;
|
|
19
|
+
var EDGE_ANSWERS = {
|
|
20
|
+
502: "Bad Gateway from the load balancer in front of the platform, not the platform's answer: the web server dropped the connection or restarted mid-request. Retry; if it repeats, the platform is restarting or overloaded.",
|
|
21
|
+
503: "Service Unavailable from the load balancer in front of the platform, not the platform's answer: no web server was ready to take the request (a deploy or a restart). Retry in a minute.",
|
|
22
|
+
504: "Gateway Time-out from the load balancer in front of the platform, not the platform's answer: the request sent nothing back within the load balancer's idle timeout (60 s unless the deployment raises it: Helm ingress.idleTimeoutSeconds) and was cut there, though the platform may still be running it. Check what it changed before you retry."
|
|
23
|
+
};
|
|
24
|
+
var EDGE_FAILURE = "The platform failed without its JSON error body: a proxy in front of it answered, or the server stopped before its error handler ran. Retry; if it repeats, report the request and the time.";
|
|
25
|
+
var EDGE_PAGE = "An HTML page answered instead of the platform's JSON: a proxy in front of the platform, or the configured host is not the platform.";
|
|
26
|
+
function edgeAnswer(text, status) {
|
|
27
|
+
if (status !== void 0 && status >= 500) return EDGE_ANSWERS[status] ?? EDGE_FAILURE;
|
|
28
|
+
return /^\s*</.test(text) ? EDGE_PAGE : null;
|
|
29
|
+
}
|
|
30
|
+
function parseErrorBody(text, status) {
|
|
31
|
+
const raw = { detail: text.slice(0, DETAIL_LIMIT), code: null };
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(text);
|
|
35
|
+
} catch {
|
|
36
|
+
return { detail: (edgeAnswer(text, status) ?? text).slice(0, DETAIL_LIMIT), code: null };
|
|
37
|
+
}
|
|
38
|
+
if (parsed === null || typeof parsed !== "object") return raw;
|
|
39
|
+
const { message, code, error } = parsed;
|
|
40
|
+
const stableCode = typeof code === "string" ? code : null;
|
|
41
|
+
if (typeof message !== "string") return { ...raw, code: stableCode };
|
|
42
|
+
const fields = invalidFields(error);
|
|
43
|
+
const said = fields ? `${message}: ${fields}` : message;
|
|
44
|
+
if (stableCode === null) return { detail: said.slice(0, DETAIL_LIMIT), code: null };
|
|
45
|
+
return {
|
|
46
|
+
detail: `${said} (${stableCode})`.slice(0, DETAIL_LIMIT),
|
|
47
|
+
code: stableCode
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function invalidFields(error) {
|
|
51
|
+
const issues = Array.isArray(error) ? error : [];
|
|
52
|
+
return issues.filter(
|
|
53
|
+
(issue) => issue !== null && typeof issue === "object" && typeof issue.message === "string"
|
|
54
|
+
).map((issue) => {
|
|
55
|
+
const path = Array.isArray(issue.path) ? issue.path.map(String).join(".") : "";
|
|
56
|
+
return path ? `${path}: ${issue.message}` : issue.message;
|
|
57
|
+
}).join("; ");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/agents/patch.ts
|
|
61
|
+
var list = (value) => Array.isArray(value) ? value : [value];
|
|
62
|
+
function grantOf(input) {
|
|
63
|
+
if (typeof input === "string") return { server: input };
|
|
64
|
+
return input.only ? { server: input.server, only: [...input.only].sort() } : { server: input.server };
|
|
65
|
+
}
|
|
66
|
+
var AgentPatch = class _AgentPatch {
|
|
67
|
+
constructor(json) {
|
|
68
|
+
this.json = json;
|
|
69
|
+
}
|
|
70
|
+
json;
|
|
71
|
+
static update(fields) {
|
|
72
|
+
const set = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
|
|
73
|
+
return new _AgentPatch({ set });
|
|
74
|
+
}
|
|
75
|
+
static attach(grants) {
|
|
76
|
+
return new _AgentPatch({ attach: list(grants).map(grantOf) });
|
|
77
|
+
}
|
|
78
|
+
static detach(servers) {
|
|
79
|
+
return new _AgentPatch({ detach: [...list(servers)] });
|
|
80
|
+
}
|
|
81
|
+
toJSON() {
|
|
82
|
+
return structuredClone(this.json);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// src/agents/agent.ts
|
|
87
|
+
var AgentVersionConflictError = class extends ApiError {
|
|
88
|
+
currentVersionId;
|
|
89
|
+
constructor(status, method, path, text) {
|
|
90
|
+
super(status, method, path, text);
|
|
91
|
+
this.name = "AgentVersionConflictError";
|
|
92
|
+
this.currentVersionId = currentVersionOf(text);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
function currentVersionOf(text) {
|
|
96
|
+
try {
|
|
97
|
+
const id = JSON.parse(text).currentVersionId;
|
|
98
|
+
return typeof id === "string" ? id : null;
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
var AgentTools = class {
|
|
104
|
+
constructor(agent) {
|
|
105
|
+
this.agent = agent;
|
|
106
|
+
}
|
|
107
|
+
agent;
|
|
108
|
+
/** Grant servers: one already attached keeps its place and takes the new grant. */
|
|
109
|
+
attach(grants, options = {}) {
|
|
110
|
+
return this.agent.edit(AgentPatch.attach(grants), options);
|
|
111
|
+
}
|
|
112
|
+
/** Remove servers; one that is not attached changes nothing. */
|
|
113
|
+
detach(servers, options = {}) {
|
|
114
|
+
return this.agent.edit(AgentPatch.detach(servers), options);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
var AgentThreads = class {
|
|
118
|
+
constructor(threads, name) {
|
|
119
|
+
this.threads = threads;
|
|
120
|
+
this.name = name;
|
|
121
|
+
}
|
|
122
|
+
threads;
|
|
123
|
+
name;
|
|
124
|
+
create(options = {}) {
|
|
125
|
+
return this.threads.create({ ...options, agent: this.name });
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
var Agent = class {
|
|
129
|
+
#agents;
|
|
130
|
+
#record;
|
|
131
|
+
tools;
|
|
132
|
+
threads;
|
|
133
|
+
constructor(agents, record, threads) {
|
|
134
|
+
this.#agents = agents;
|
|
135
|
+
this.#record = liveOf(record);
|
|
136
|
+
this.tools = new AgentTools(this);
|
|
137
|
+
this.threads = new AgentThreads(threads, record.name);
|
|
138
|
+
}
|
|
139
|
+
get name() {
|
|
140
|
+
return this.#record.name;
|
|
141
|
+
}
|
|
142
|
+
/** The version edits apply to: the one `production` runs (else, never deployed, the newest). */
|
|
143
|
+
get versionId() {
|
|
144
|
+
return this.#record.versionId;
|
|
145
|
+
}
|
|
146
|
+
get version() {
|
|
147
|
+
return this.#record.version;
|
|
148
|
+
}
|
|
149
|
+
get buildHash() {
|
|
150
|
+
return this.#record.buildHash;
|
|
151
|
+
}
|
|
152
|
+
get deployed() {
|
|
153
|
+
return this.#record.deployed;
|
|
154
|
+
}
|
|
155
|
+
get definition() {
|
|
156
|
+
return structuredClone(this.#record.definition);
|
|
157
|
+
}
|
|
158
|
+
/** Change fields: a new version, live unless `deploy: false`; a change to the values it already has writes nothing. */
|
|
159
|
+
update(fields, options = {}) {
|
|
160
|
+
return this.edit(AgentPatch.update(fields), options);
|
|
161
|
+
}
|
|
162
|
+
/** Apply one patch made of `AgentPatch.update`, `.attach` or `.detach`. */
|
|
163
|
+
async edit(patch, options = {}) {
|
|
164
|
+
const result = await this.#agents.edit(this.name, patch, { ...options, from: this.versionId });
|
|
165
|
+
if (result.deployed || !this.deployed) this.#record = liveOf(result);
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
/** Move `production` to one of this agent's versions (an earlier one, or one staged with `deploy: false`); `force` crosses a breaking tool change. */
|
|
169
|
+
async rollback(versionId, options = {}) {
|
|
170
|
+
this.#record = liveOf(await this.#agents.rollback(this.name, versionId, { ...options, from: this.versionId }));
|
|
171
|
+
return this.toJSON();
|
|
172
|
+
}
|
|
173
|
+
/** Every version, newest first, with whether it is live and its changes against the version before it. */
|
|
174
|
+
versions() {
|
|
175
|
+
return this.#agents.history(this.name);
|
|
176
|
+
}
|
|
177
|
+
/** Read the live version again, after a conflict or someone else's change. */
|
|
178
|
+
async refresh() {
|
|
179
|
+
this.#record = liveOf(await this.#agents.live(this.name));
|
|
180
|
+
return this;
|
|
181
|
+
}
|
|
182
|
+
/** Start a thread with this agent and send it `input`: the run uses the version `production` runs now (or `version`). */
|
|
183
|
+
async run(input, options = {}) {
|
|
184
|
+
const { version, ...thread } = options;
|
|
185
|
+
return (await this.threads.create(thread)).send(input, { version });
|
|
186
|
+
}
|
|
187
|
+
toJSON() {
|
|
188
|
+
return { ...this.#record, definition: this.definition };
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
function liveOf(record) {
|
|
192
|
+
const { name, versionId, version, buildHash, deployed, definition } = record;
|
|
193
|
+
return { name, versionId, version, buildHash, deployed, definition };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/agents/definition.ts
|
|
197
|
+
var NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
198
|
+
var DEFAULT_MODEL = "claude-opus-5";
|
|
199
|
+
var DEFAULT_MAX_TURNS = 50;
|
|
200
|
+
var INSTRUCTIONS = { min: 1, max: 65536 };
|
|
201
|
+
var MAX_TURNS = { min: 1, max: 200 };
|
|
202
|
+
var DEFINITION_FIELDS = /* @__PURE__ */ new Set([
|
|
203
|
+
"name",
|
|
204
|
+
"instructions",
|
|
205
|
+
"model",
|
|
206
|
+
"effort",
|
|
207
|
+
"maxTurns",
|
|
208
|
+
"tools"
|
|
209
|
+
]);
|
|
210
|
+
var GRANT_FIELDS = /* @__PURE__ */ new Set(["server", "only"]);
|
|
211
|
+
var AgentDefinitionError = class extends Error {
|
|
212
|
+
constructor(issues) {
|
|
213
|
+
super(`Invalid agent definition: ${issues.map((issue) => `${pathText(issue.path)}: ${issue.message}`).join("; ")}`);
|
|
214
|
+
this.issues = issues;
|
|
215
|
+
this.name = "AgentDefinitionError";
|
|
216
|
+
}
|
|
217
|
+
issues;
|
|
218
|
+
};
|
|
219
|
+
var AgentDefinition = class _AgentDefinition {
|
|
220
|
+
name;
|
|
221
|
+
instructions;
|
|
222
|
+
model;
|
|
223
|
+
effort;
|
|
224
|
+
maxTurns;
|
|
225
|
+
tools;
|
|
226
|
+
constructor(spec) {
|
|
227
|
+
this.name = spec.name;
|
|
228
|
+
this.instructions = spec.instructions;
|
|
229
|
+
this.model = spec.model;
|
|
230
|
+
this.effort = spec.effort;
|
|
231
|
+
this.maxTurns = spec.maxTurns;
|
|
232
|
+
this.tools = Object.freeze(spec.tools.map(freezeGrant));
|
|
233
|
+
Object.freeze(this);
|
|
234
|
+
}
|
|
235
|
+
/** Validate and normalize any value (a parsed JSON file included); throws `AgentDefinitionError` listing every broken rule. */
|
|
236
|
+
static from(input) {
|
|
237
|
+
return new _AgentDefinition(DefinitionReader.read(input));
|
|
238
|
+
}
|
|
239
|
+
/** The normalized definition: defaults filled, tool shorthands expanded, `only` sorted, `effort` present only when set. */
|
|
240
|
+
toJSON() {
|
|
241
|
+
return {
|
|
242
|
+
name: this.name,
|
|
243
|
+
instructions: this.instructions,
|
|
244
|
+
model: this.model,
|
|
245
|
+
...this.effort === void 0 ? {} : { effort: this.effort },
|
|
246
|
+
maxTurns: this.maxTurns,
|
|
247
|
+
tools: this.tools.map(
|
|
248
|
+
(grant2) => grant2.only ? { server: grant2.server, only: [...grant2.only] } : { server: grant2.server }
|
|
249
|
+
)
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
function defineAgent(input) {
|
|
254
|
+
return AgentDefinition.from(input);
|
|
255
|
+
}
|
|
256
|
+
function freezeGrant(grant2) {
|
|
257
|
+
const only = grant2.only ? { only: Object.freeze([...grant2.only]) } : {};
|
|
258
|
+
return Object.freeze({ server: grant2.server, ...only });
|
|
259
|
+
}
|
|
260
|
+
function pathText(path) {
|
|
261
|
+
return path.length === 0 ? "definition" : path.join(".");
|
|
262
|
+
}
|
|
263
|
+
function isRecord(value) {
|
|
264
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
265
|
+
}
|
|
266
|
+
function isString(value) {
|
|
267
|
+
return value !== null;
|
|
268
|
+
}
|
|
269
|
+
var DefinitionReader = class _DefinitionReader {
|
|
270
|
+
#issues = [];
|
|
271
|
+
static read(input) {
|
|
272
|
+
const reader = new _DefinitionReader();
|
|
273
|
+
const spec = reader.spec(input);
|
|
274
|
+
if (!spec || reader.#issues.length > 0) throw new AgentDefinitionError(reader.#issues);
|
|
275
|
+
return spec;
|
|
276
|
+
}
|
|
277
|
+
spec(input) {
|
|
278
|
+
if (!isRecord(input)) return this.refuse([], "invalid_type", "a definition is an object", null);
|
|
279
|
+
this.unknownFields(input, DEFINITION_FIELDS, []);
|
|
280
|
+
const effort = this.optionalString(input.effort, ["effort"]);
|
|
281
|
+
return {
|
|
282
|
+
name: this.name(input.name),
|
|
283
|
+
instructions: this.instructions(input.instructions),
|
|
284
|
+
model: this.optionalString(input.model, ["model"]) ?? DEFAULT_MODEL,
|
|
285
|
+
...effort === void 0 ? {} : { effort },
|
|
286
|
+
maxTurns: this.maxTurns(input.maxTurns),
|
|
287
|
+
tools: this.tools(input.tools)
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
name(value) {
|
|
291
|
+
const name = this.string(value, ["name"]);
|
|
292
|
+
if (name !== null && !NAME_PATTERN.test(name))
|
|
293
|
+
this.issue(["name"], "invalid_name", "lowercase letters, digits and dashes, 1-63 long, not starting with a dash");
|
|
294
|
+
return name ?? "";
|
|
295
|
+
}
|
|
296
|
+
instructions(value) {
|
|
297
|
+
const instructions = this.string(value, ["instructions"]);
|
|
298
|
+
if (instructions !== null) this.bounded(instructions.length, INSTRUCTIONS, ["instructions"], "characters");
|
|
299
|
+
return instructions ?? "";
|
|
300
|
+
}
|
|
301
|
+
maxTurns(value) {
|
|
302
|
+
if (value === void 0) return DEFAULT_MAX_TURNS;
|
|
303
|
+
if (typeof value !== "number" || !Number.isInteger(value))
|
|
304
|
+
return this.refuse(["maxTurns"], "invalid_type", "a whole number", DEFAULT_MAX_TURNS);
|
|
305
|
+
this.bounded(value, MAX_TURNS, ["maxTurns"], "turns");
|
|
306
|
+
return value;
|
|
307
|
+
}
|
|
308
|
+
tools(value) {
|
|
309
|
+
if (value === void 0) return [];
|
|
310
|
+
if (!Array.isArray(value)) return this.refuse(["tools"], "invalid_type", "a list of tools", []);
|
|
311
|
+
const grants = value.map((entry, index) => this.grant(entry, ["tools", index]));
|
|
312
|
+
this.noRepeats(
|
|
313
|
+
grants.map((grant2) => grant2?.server ?? null),
|
|
314
|
+
(index) => ["tools", index, "server"],
|
|
315
|
+
"duplicate_tool_server",
|
|
316
|
+
"this server is already granted"
|
|
317
|
+
);
|
|
318
|
+
return grants.filter((grant2) => grant2 !== null);
|
|
319
|
+
}
|
|
320
|
+
grant(entry, path) {
|
|
321
|
+
if (typeof entry === "string") return { server: entry };
|
|
322
|
+
if (!isRecord(entry)) return this.refuse(path, "invalid_type", "a server name or { server, only }", null);
|
|
323
|
+
this.unknownFields(entry, GRANT_FIELDS, path);
|
|
324
|
+
const server = this.string(entry.server, [...path, "server"]);
|
|
325
|
+
if (server === null) return null;
|
|
326
|
+
return entry.only === void 0 ? { server } : { server, only: this.only(entry.only, [...path, "only"]) };
|
|
327
|
+
}
|
|
328
|
+
only(value, path) {
|
|
329
|
+
if (!Array.isArray(value)) return this.refuse(path, "invalid_type", "a list of tool names", []);
|
|
330
|
+
if (value.length === 0)
|
|
331
|
+
this.issue(path, "too_small", "names at least one tool; leave `only` out to grant the whole server");
|
|
332
|
+
const names = value.map((name, index) => this.string(name, [...path, index]));
|
|
333
|
+
this.noRepeats(names, (index) => [...path, index], "duplicate_tool", "this tool is already named");
|
|
334
|
+
return names.filter(isString).sort();
|
|
335
|
+
}
|
|
336
|
+
string(value, path) {
|
|
337
|
+
if (typeof value === "string") return value;
|
|
338
|
+
return this.refuse(path, "invalid_type", "a string", null);
|
|
339
|
+
}
|
|
340
|
+
optionalString(value, path) {
|
|
341
|
+
if (value === void 0) return void 0;
|
|
342
|
+
return this.string(value, path) ?? void 0;
|
|
343
|
+
}
|
|
344
|
+
bounded(value, bounds, path, unit) {
|
|
345
|
+
if (value < bounds.min) this.issue(path, "too_small", `at least ${bounds.min} ${unit}`);
|
|
346
|
+
if (value > bounds.max) this.issue(path, "too_large", `at most ${bounds.max} ${unit}`);
|
|
347
|
+
}
|
|
348
|
+
unknownFields(record, known, path) {
|
|
349
|
+
for (const [key, value] of Object.entries(record)) {
|
|
350
|
+
if (value !== void 0 && !known.has(key))
|
|
351
|
+
this.issue([...path, key], "unknown_field", "not a field of an agent definition");
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
noRepeats(values, pathOf, code, message) {
|
|
355
|
+
const seen = /* @__PURE__ */ new Set();
|
|
356
|
+
values.forEach((value, index) => {
|
|
357
|
+
if (value === null) return;
|
|
358
|
+
if (seen.has(value)) this.issue(pathOf(index), code, message);
|
|
359
|
+
seen.add(value);
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
issue(path, code, message) {
|
|
363
|
+
this.#issues.push({ path, code, message });
|
|
364
|
+
}
|
|
365
|
+
refuse(path, code, message, fallback) {
|
|
366
|
+
this.issue(path, code, message);
|
|
367
|
+
return fallback;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
// src/worlds/personalToken.ts
|
|
372
|
+
var TOKEN_NOT_PERSONAL = "GATEWAY_TOKEN takes a personal access token: pat_ followed by letters and digits only.";
|
|
373
|
+
var TOKEN_NEEDS_PROJECT = "GATEWAY_TOKEN acts in the project GATEWAY_PROJECT_ID names: set it to the official project's id (letters, digits, - and _).";
|
|
374
|
+
var TOKEN_NEEDS_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names: set GATEWAY_HOST.";
|
|
375
|
+
var TOKEN_OTHER_HOST = "GATEWAY_TOKEN goes only to the host GATEWAY_HOST names, and this call names another host: point the call at GATEWAY_HOST or unset GATEWAY_TOKEN.";
|
|
376
|
+
var TOKEN_BESIDE_KEYS = "GATEWAY_TOKEN is set beside a project key (GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY, GATEWAY_API_KEY or a key passed in): unset one of them. Neither replaces the other.";
|
|
377
|
+
var PERSONAL = /^pat_[A-Za-z0-9]+$/;
|
|
378
|
+
var PROJECT = /^[A-Za-z0-9_-]+$/;
|
|
379
|
+
var ENV_KEYS = ["GATEWAY_PUBLIC_KEY", "GATEWAY_SECRET_KEY", "GATEWAY_API_KEY"];
|
|
380
|
+
var PersonalTokenRefused = class extends Error {
|
|
381
|
+
};
|
|
382
|
+
var bare = (host) => host.replace(/\/+$/, "");
|
|
383
|
+
var PersonalToken = class _PersonalToken {
|
|
384
|
+
constructor(value, project, host) {
|
|
385
|
+
this.value = value;
|
|
386
|
+
this.project = project;
|
|
387
|
+
this.host = host;
|
|
388
|
+
}
|
|
389
|
+
value;
|
|
390
|
+
project;
|
|
391
|
+
host;
|
|
392
|
+
static fromEnv(env, request = {}) {
|
|
393
|
+
const value = env.GATEWAY_TOKEN;
|
|
394
|
+
if (!value) return null;
|
|
395
|
+
if (request.keys || ENV_KEYS.some((name) => env[name])) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
|
|
396
|
+
const host = bare(env.GATEWAY_HOST ?? "");
|
|
397
|
+
if (!host) throw new PersonalTokenRefused(TOKEN_NEEDS_HOST);
|
|
398
|
+
if (request.host && bare(request.host) !== host) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
|
|
399
|
+
if (!PERSONAL.test(value)) throw new PersonalTokenRefused(TOKEN_NOT_PERSONAL);
|
|
400
|
+
const project = env.GATEWAY_PROJECT_ID ?? "";
|
|
401
|
+
if (!PROJECT.test(project)) throw new PersonalTokenRefused(TOKEN_NEEDS_PROJECT);
|
|
402
|
+
return new _PersonalToken(value, project, host);
|
|
403
|
+
}
|
|
404
|
+
toJSON() {
|
|
405
|
+
return { project: this.project, host: this.host };
|
|
406
|
+
}
|
|
407
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
408
|
+
return `PersonalToken { project: ${this.project}, host: ${this.host} }`;
|
|
409
|
+
}
|
|
410
|
+
static scrubbed(env) {
|
|
411
|
+
return Object.fromEntries(Object.entries(env).filter(([key]) => key !== "GATEWAY_TOKEN"));
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
// src/worlds/transport.ts
|
|
416
|
+
var PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
|
|
417
|
+
var PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
|
|
418
|
+
function platformTimeoutMs(env = process.env) {
|
|
419
|
+
const raw = env[PLATFORM_TIMEOUT_ENV];
|
|
420
|
+
if (raw === void 0 || raw === "") return PLATFORM_TIMEOUT_DEFAULT_MS;
|
|
421
|
+
const value = Number(raw);
|
|
422
|
+
if (Number.isInteger(value) && value > 0) return value;
|
|
423
|
+
throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
|
|
424
|
+
}
|
|
425
|
+
var CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
|
|
426
|
+
var RETRY = "Retry; if it repeats, check the network between here and the platform.";
|
|
427
|
+
var FETCH_LIMIT = {
|
|
428
|
+
reason: "Node's fetch stopped waiting after 300 s",
|
|
429
|
+
next: "The platform may still be running it: check what it changed before you retry."
|
|
430
|
+
};
|
|
431
|
+
var CAUSES = {
|
|
432
|
+
UND_ERR_HEADERS_TIMEOUT: FETCH_LIMIT,
|
|
433
|
+
UND_ERR_BODY_TIMEOUT: FETCH_LIMIT,
|
|
434
|
+
ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
|
|
435
|
+
ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
|
|
436
|
+
EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
|
|
437
|
+
ETIMEDOUT: { reason: "connect timed out", next: CHECK_HOST },
|
|
438
|
+
UND_ERR_CONNECT_TIMEOUT: { reason: "connect timed out", next: CHECK_HOST },
|
|
439
|
+
EHOSTUNREACH: { reason: "host unreachable", next: CHECK_HOST },
|
|
440
|
+
ENETUNREACH: { reason: "network unreachable", next: RETRY },
|
|
441
|
+
ECONNRESET: { reason: "connection dropped", next: RETRY },
|
|
442
|
+
UND_ERR_SOCKET: { reason: "connection dropped", next: RETRY },
|
|
443
|
+
EPIPE: { reason: "connection dropped", next: RETRY }
|
|
444
|
+
};
|
|
445
|
+
var UNKNOWN_CAUSE = { reason: "network error", next: CHECK_HOST };
|
|
446
|
+
var TransportCause = class _TransportCause {
|
|
447
|
+
constructor(reason, detail, next) {
|
|
448
|
+
this.reason = reason;
|
|
449
|
+
this.detail = detail;
|
|
450
|
+
this.next = next;
|
|
451
|
+
}
|
|
452
|
+
reason;
|
|
453
|
+
detail;
|
|
454
|
+
next;
|
|
455
|
+
static timeout(timeoutMs) {
|
|
456
|
+
return new _TransportCause(
|
|
457
|
+
`timed out after ${timeoutMs / 1e3}s`,
|
|
458
|
+
null,
|
|
459
|
+
`Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
static idle(idleMs) {
|
|
463
|
+
return new _TransportCause(
|
|
464
|
+
`no data for ${idleMs / 1e3}s`,
|
|
465
|
+
null,
|
|
466
|
+
"The stream resumes from its last event; if it repeats, check the network between here and the platform."
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
static of(error) {
|
|
470
|
+
const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
|
|
471
|
+
const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
|
|
472
|
+
const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
|
|
473
|
+
const known = code && CAUSES[code] || UNKNOWN_CAUSE;
|
|
474
|
+
return new _TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);
|
|
475
|
+
}
|
|
476
|
+
describe() {
|
|
477
|
+
return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
var UnreachableError = class extends Error {
|
|
481
|
+
constructor(host, method, route, failure) {
|
|
482
|
+
super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
|
|
483
|
+
this.host = host;
|
|
484
|
+
this.method = method;
|
|
485
|
+
this.route = route;
|
|
486
|
+
this.failure = failure;
|
|
487
|
+
this.name = "UnreachableError";
|
|
488
|
+
}
|
|
489
|
+
host;
|
|
490
|
+
method;
|
|
491
|
+
route;
|
|
492
|
+
failure;
|
|
493
|
+
};
|
|
494
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
495
|
+
var RetryPolicy = class _RetryPolicy {
|
|
496
|
+
constructor(delaysMs, wait = sleep, budgetMs = Number.POSITIVE_INFINITY, now = Date.now) {
|
|
497
|
+
this.delaysMs = delaysMs;
|
|
498
|
+
this.wait = wait;
|
|
499
|
+
this.budgetMs = budgetMs;
|
|
500
|
+
this.now = now;
|
|
501
|
+
}
|
|
502
|
+
delaysMs;
|
|
503
|
+
wait;
|
|
504
|
+
budgetMs;
|
|
505
|
+
now;
|
|
506
|
+
static NONE = new _RetryPolicy([]);
|
|
507
|
+
/** A platform restart or a short edge outage: no wait starts that would end past five minutes, so a step ends
|
|
508
|
+
* within the budget plus one request timeout. */
|
|
509
|
+
static FILING = new _RetryPolicy([250, 500, 1e3, 2e3, 4e3, 8e3, 16e3, 3e4], sleep, 3e5);
|
|
510
|
+
static TRANSIENT_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
|
|
511
|
+
async run(attempt) {
|
|
512
|
+
const started = this.now();
|
|
513
|
+
for (let tries = 0; ; tries += 1) {
|
|
514
|
+
const outcome = await Attempt.of(attempt);
|
|
515
|
+
const delayMs = this.delaysMs[tries];
|
|
516
|
+
const spent = delayMs === void 0 || this.now() - started + delayMs >= this.budgetMs;
|
|
517
|
+
if (!outcome.transient || spent) return outcome.settle();
|
|
518
|
+
await this.wait(delayMs);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
var Attempt = class _Attempt {
|
|
523
|
+
constructor(reply, error, transient) {
|
|
524
|
+
this.reply = reply;
|
|
525
|
+
this.error = error;
|
|
526
|
+
this.transient = transient;
|
|
527
|
+
}
|
|
528
|
+
reply;
|
|
529
|
+
error;
|
|
530
|
+
transient;
|
|
531
|
+
static async of(attempt) {
|
|
532
|
+
try {
|
|
533
|
+
const reply = await attempt();
|
|
534
|
+
return new _Attempt(reply, null, RetryPolicy.TRANSIENT_STATUSES.has(reply.status));
|
|
535
|
+
} catch (error) {
|
|
536
|
+
return new _Attempt(null, error, error instanceof UnreachableError);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
settle() {
|
|
540
|
+
if (this.reply) return this.reply;
|
|
541
|
+
throw this.error;
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
var PLATFORM_STREAM_IDLE_MS = 6e4;
|
|
545
|
+
var REFUSAL_TEXT_LIMIT = 64 * 1024;
|
|
546
|
+
var KEYED_REDIRECTS = "manual";
|
|
547
|
+
function platformAuthorization(endpoint, url) {
|
|
548
|
+
const { token } = endpoint;
|
|
549
|
+
if (!token)
|
|
550
|
+
return { authorization: "Basic " + Buffer.from(`${endpoint.publicKey}:${endpoint.secretKey}`).toString("base64") };
|
|
551
|
+
if (endpoint.publicKey || endpoint.secretKey) throw new PersonalTokenRefused(TOKEN_BESIDE_KEYS);
|
|
552
|
+
if (!url.startsWith(`${token.host}/`)) throw new PersonalTokenRefused(TOKEN_OTHER_HOST);
|
|
553
|
+
return { authorization: `Bearer ${token.value}`, "x-gateway-project": token.project };
|
|
554
|
+
}
|
|
555
|
+
var PlatformTransport = class {
|
|
556
|
+
#endpoint;
|
|
557
|
+
#timeoutMs;
|
|
558
|
+
constructor(endpoint, timeoutMs = platformTimeoutMs()) {
|
|
559
|
+
this.#endpoint = endpoint;
|
|
560
|
+
this.#timeoutMs = timeoutMs;
|
|
561
|
+
}
|
|
562
|
+
/** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
|
|
563
|
+
budget(ownMs) {
|
|
564
|
+
return Math.max(ownMs ?? 0, this.#timeoutMs);
|
|
565
|
+
}
|
|
566
|
+
/** One request; the caller's `signal` aborts it in flight and throws the signal's reason, never an `UnreachableError`. */
|
|
567
|
+
async send(method, route, body, opts = {}) {
|
|
568
|
+
const timeoutMs = this.budget(opts.timeoutMs);
|
|
569
|
+
return (opts.retry ?? RetryPolicy.NONE).run(() => this.once(method, route, body, timeoutMs, opts.signal));
|
|
570
|
+
}
|
|
571
|
+
/** `send`, then the 2xx body as JSON; any other answer throws `ApiError` with its status and stable `code`. */
|
|
572
|
+
async json(method, route, body, opts = {}) {
|
|
573
|
+
const reply = await this.send(method, route, body, opts);
|
|
574
|
+
if (!reply.ok) throw new ApiError(reply.status, method, route, reply.text);
|
|
575
|
+
return JSON.parse(reply.text);
|
|
576
|
+
}
|
|
577
|
+
/** The streaming twin of `send` for a `GET` event stream: nothing is buffered, `after` travels as `Last-Event-ID`, and each wait for the platform (the headers, every chunk) may last `idleMs` (default 60 s) instead of the request budget. */
|
|
578
|
+
async stream(route, opts = {}) {
|
|
579
|
+
const watch = new StreamWatch(opts.signal, opts.idleMs ?? PLATFORM_STREAM_IDLE_MS, this.#endpoint.host, route);
|
|
580
|
+
const headers = this.headers(route, "text/event-stream", opts.after ? { "last-event-id": opts.after } : {});
|
|
581
|
+
try {
|
|
582
|
+
const response = await watch.within(
|
|
583
|
+
() => fetch(this.url(route), { method: "GET", headers, signal: watch.signal, redirect: KEYED_REDIRECTS })
|
|
584
|
+
);
|
|
585
|
+
return new PlatformStream(response, watch);
|
|
586
|
+
} catch (error) {
|
|
587
|
+
watch.close();
|
|
588
|
+
throw error;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
url(route) {
|
|
592
|
+
return `${this.#endpoint.host}${route}`;
|
|
593
|
+
}
|
|
594
|
+
headers(route, accept, extra = {}) {
|
|
595
|
+
return {
|
|
596
|
+
"content-type": "application/json",
|
|
597
|
+
accept,
|
|
598
|
+
...platformAuthorization(this.#endpoint, this.url(route)),
|
|
599
|
+
...extra
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
async once(method, route, body, timeoutMs, caller) {
|
|
603
|
+
if (caller?.aborted) throw caller.reason;
|
|
604
|
+
const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
|
|
605
|
+
const headers = this.headers(route, "application/json");
|
|
606
|
+
const controller = new AbortController();
|
|
607
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
608
|
+
const relay = () => controller.abort(caller?.reason);
|
|
609
|
+
caller?.addEventListener("abort", relay, { once: true });
|
|
610
|
+
try {
|
|
611
|
+
const res = await fetch(this.url(route), {
|
|
612
|
+
method,
|
|
613
|
+
headers,
|
|
614
|
+
...payload,
|
|
615
|
+
signal: controller.signal,
|
|
616
|
+
redirect: KEYED_REDIRECTS
|
|
617
|
+
});
|
|
618
|
+
return { status: res.status, ok: res.ok, text: await res.text() };
|
|
619
|
+
} catch (error) {
|
|
620
|
+
if (caller?.aborted) throw caller.reason;
|
|
621
|
+
const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
|
|
622
|
+
throw new UnreachableError(this.#endpoint.host, method, route, cause);
|
|
623
|
+
} finally {
|
|
624
|
+
clearTimeout(timer);
|
|
625
|
+
caller?.removeEventListener("abort", relay);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
var StreamWatch = class {
|
|
630
|
+
constructor(caller, idleMs, host, route) {
|
|
631
|
+
this.idleMs = idleMs;
|
|
632
|
+
this.host = host;
|
|
633
|
+
this.route = route;
|
|
634
|
+
this.#caller = caller;
|
|
635
|
+
caller?.addEventListener("abort", this.#relay, { once: true });
|
|
636
|
+
if (caller?.aborted) this.#relay();
|
|
637
|
+
}
|
|
638
|
+
idleMs;
|
|
639
|
+
host;
|
|
640
|
+
route;
|
|
641
|
+
#controller = new AbortController();
|
|
642
|
+
#caller;
|
|
643
|
+
#relay = () => this.#controller.abort(this.#caller?.reason);
|
|
644
|
+
#idled = false;
|
|
645
|
+
get signal() {
|
|
646
|
+
return this.#controller.signal;
|
|
647
|
+
}
|
|
648
|
+
async within(wait) {
|
|
649
|
+
const timer = setTimeout(() => this.idle(), this.idleMs);
|
|
650
|
+
try {
|
|
651
|
+
return await wait();
|
|
652
|
+
} catch (error) {
|
|
653
|
+
throw this.failure(error);
|
|
654
|
+
} finally {
|
|
655
|
+
clearTimeout(timer);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
close() {
|
|
659
|
+
this.#caller?.removeEventListener("abort", this.#relay);
|
|
660
|
+
this.#controller.abort();
|
|
661
|
+
}
|
|
662
|
+
idle() {
|
|
663
|
+
this.#idled = true;
|
|
664
|
+
this.#controller.abort();
|
|
665
|
+
}
|
|
666
|
+
failure(error) {
|
|
667
|
+
if (this.#caller?.aborted) return this.#caller.reason;
|
|
668
|
+
const cause = this.#idled ? TransportCause.idle(this.idleMs) : TransportCause.of(error);
|
|
669
|
+
return new UnreachableError(this.host, "GET", this.route, cause);
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
var PlatformStream = class {
|
|
673
|
+
#response;
|
|
674
|
+
#watch;
|
|
675
|
+
constructor(response, watch) {
|
|
676
|
+
this.#response = response;
|
|
677
|
+
this.#watch = watch;
|
|
678
|
+
}
|
|
679
|
+
get status() {
|
|
680
|
+
return this.#response.status;
|
|
681
|
+
}
|
|
682
|
+
get ok() {
|
|
683
|
+
return this.#response.ok;
|
|
684
|
+
}
|
|
685
|
+
/** The body as text, for a refusal: at most the first 64 KiB of characters; closes the stream. */
|
|
686
|
+
async text() {
|
|
687
|
+
const decoder = new TextDecoder();
|
|
688
|
+
let text = "";
|
|
689
|
+
for await (const chunk of this.chunks()) {
|
|
690
|
+
text += decoder.decode(chunk, { stream: true });
|
|
691
|
+
if (text.length >= REFUSAL_TEXT_LIMIT) return text.slice(0, REFUSAL_TEXT_LIMIT);
|
|
692
|
+
}
|
|
693
|
+
return text + decoder.decode();
|
|
694
|
+
}
|
|
695
|
+
/** The body's bytes as they arrive; the idle budget runs only while waiting for the platform, never while the caller holds a chunk. */
|
|
696
|
+
async *chunks() {
|
|
697
|
+
const reader = this.#response.body?.getReader();
|
|
698
|
+
try {
|
|
699
|
+
for (; ; ) {
|
|
700
|
+
const next = reader ? await this.#watch.within(() => reader.read()) : { done: true };
|
|
701
|
+
if (next.done) return;
|
|
702
|
+
yield next.value;
|
|
703
|
+
}
|
|
704
|
+
} finally {
|
|
705
|
+
this.close();
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
close() {
|
|
709
|
+
this.#watch.close();
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
// src/agents/segment.ts
|
|
714
|
+
function segment(id) {
|
|
715
|
+
if (id === "" || id === "." || id === "..") throw new TypeError(`not an id: "${id}"`);
|
|
716
|
+
return encodeURIComponent(id);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// src/agents/agents.ts
|
|
720
|
+
var PRODUCTION = "production";
|
|
721
|
+
var PAGE_SIZE = 100;
|
|
722
|
+
var buildRoute = (buildId) => `/api/public/agent-builds/${segment(buildId)}`;
|
|
723
|
+
var AgentVersionNotFoundError = class extends Error {
|
|
724
|
+
constructor(agent, versionId) {
|
|
725
|
+
super(`${versionId} is not a version of ${agent}; nothing was deployed.`);
|
|
726
|
+
this.agent = agent;
|
|
727
|
+
this.versionId = versionId;
|
|
728
|
+
this.name = "AgentVersionNotFoundError";
|
|
729
|
+
}
|
|
730
|
+
agent;
|
|
731
|
+
versionId;
|
|
732
|
+
code = "version_not_found";
|
|
733
|
+
};
|
|
734
|
+
var Agents = class {
|
|
735
|
+
#transport;
|
|
736
|
+
#threads;
|
|
737
|
+
constructor(transport, threads) {
|
|
738
|
+
this.#transport = transport;
|
|
739
|
+
this.#threads = threads;
|
|
740
|
+
}
|
|
741
|
+
/** Create an agent, live in one call: version 1, deployed. A definition `defineAgent` would refuse throws `AgentDefinitionError` before anything is sent; a name the project already holds is 409 `agent_exists`. */
|
|
742
|
+
async create(input) {
|
|
743
|
+
const { name, ...definition } = AgentDefinition.from(input).toJSON();
|
|
744
|
+
const record = await this.#transport.json(
|
|
745
|
+
"POST",
|
|
746
|
+
`/api/public/agent-builds/definitions/${segment(name)}`,
|
|
747
|
+
definition
|
|
748
|
+
);
|
|
749
|
+
return new Agent(this, record, this.#threads);
|
|
750
|
+
}
|
|
751
|
+
/** The live agent named `name`, to edit or run; 404 `agent_not_found` when the project has none. */
|
|
752
|
+
async get(name) {
|
|
753
|
+
return new Agent(this, await this.live(name), this.#threads);
|
|
754
|
+
}
|
|
755
|
+
/** The version of `name` that edits apply to: the one `production` runs, else the newest. */
|
|
756
|
+
live(name) {
|
|
757
|
+
return this.#transport.json("GET", `/api/public/agent-builds/definitions/${segment(name)}`);
|
|
758
|
+
}
|
|
759
|
+
/** Apply one patch to `name` as a new version, live unless `deploy: false`. With `from`, a version that is no longer the live one is refused (`AgentVersionConflictError`) and nothing is written. */
|
|
760
|
+
edit(name, patch, options = {}) {
|
|
761
|
+
const body = { patch: patch.toJSON(), from: options.from, deploy: options.deploy ?? true };
|
|
762
|
+
return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/versions`, body);
|
|
763
|
+
}
|
|
764
|
+
/** Move `production` of `name` to one of its versions, with the audit row; `force` crosses a breaking tool change. */
|
|
765
|
+
rollback(name, versionId, options = {}) {
|
|
766
|
+
const body = { versionId, from: options.from, force: options.force ?? false };
|
|
767
|
+
return this.conflictAware("POST", `/api/public/agent-builds/definitions/${segment(name)}/rollback`, body);
|
|
768
|
+
}
|
|
769
|
+
/** Every version of the live agent `name`, newest first, each with `isDeployed` and its changes against the one before; a version written while the pages are read never repeats one. */
|
|
770
|
+
async history(name) {
|
|
771
|
+
const versions = /* @__PURE__ */ new Map();
|
|
772
|
+
for (let page = 1, pages = 1; page <= pages; page += 1) {
|
|
773
|
+
const query = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
|
|
774
|
+
const reply = await this.#transport.json(
|
|
775
|
+
"GET",
|
|
776
|
+
`/api/public/agent-builds/definitions/${segment(name)}/versions?${query}`
|
|
777
|
+
);
|
|
778
|
+
for (const version of reply.data) if (!versions.has(version.id)) versions.set(version.id, version);
|
|
779
|
+
pages = reply.meta.totalPages;
|
|
780
|
+
}
|
|
781
|
+
return [...versions.values()];
|
|
782
|
+
}
|
|
783
|
+
/** Push a definition: a new version, or the identical one already pushed (`created: false`); the platform derives its `buildHash`. With `deploy`, `production` moves to it; when that move is refused the version still exists, and pushing again returns it. */
|
|
784
|
+
async push(definition, options = {}) {
|
|
785
|
+
const body = { definition: definition.toJSON(), attribution: options.attribution };
|
|
786
|
+
const version = await this.#transport.json("POST", "/api/public/agent-builds/definitions", body);
|
|
787
|
+
if (!options.deploy) return version;
|
|
788
|
+
await this.move(version.id, false);
|
|
789
|
+
return { ...version, deployed: true, labels: [.../* @__PURE__ */ new Set([...version.labels, PRODUCTION])] };
|
|
790
|
+
}
|
|
791
|
+
/** Move `production` to `versionId`, after checking it is a defined version of `name` (an observed build of that name is not one). Rolling back is deploying an older version; `force` crosses a breaking tool change. */
|
|
792
|
+
async deploy(name, versionId, options = {}) {
|
|
793
|
+
const versions = await this.versions(name);
|
|
794
|
+
if (!versions.some((version) => version.id === versionId && version.kind === "defined"))
|
|
795
|
+
throw new AgentVersionNotFoundError(name, versionId);
|
|
796
|
+
return this.move(versionId, options.force ?? false);
|
|
797
|
+
}
|
|
798
|
+
/** Every version of `name`, newest first. */
|
|
799
|
+
async versions(name) {
|
|
800
|
+
const builds = [];
|
|
801
|
+
for (let page = 1, pages = 1; page <= pages; page += 1) {
|
|
802
|
+
const query = new URLSearchParams({ agentId: name, page: String(page), limit: String(PAGE_SIZE) });
|
|
803
|
+
const reply = await this.#transport.json("GET", `/api/public/agent-builds?${query}`);
|
|
804
|
+
builds.push(...reply.data);
|
|
805
|
+
pages = reply.meta.totalPages;
|
|
806
|
+
}
|
|
807
|
+
return builds;
|
|
808
|
+
}
|
|
809
|
+
async conflictAware(method, path, body) {
|
|
810
|
+
try {
|
|
811
|
+
return await this.#transport.json(method, path, body);
|
|
812
|
+
} catch (error) {
|
|
813
|
+
if (error instanceof ApiError && error.code === "agent_version_conflict")
|
|
814
|
+
throw new AgentVersionConflictError(error.status, method, path, error.text);
|
|
815
|
+
throw error;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
async move(versionId, force) {
|
|
819
|
+
const body = { label: PRODUCTION, source: "api", force };
|
|
820
|
+
const moved = await this.#transport.json("POST", `${buildRoute(versionId)}/labels`, body);
|
|
821
|
+
return {
|
|
822
|
+
agentId: moved.agentId,
|
|
823
|
+
label: moved.label,
|
|
824
|
+
versionId,
|
|
825
|
+
fromBuildHash: moved.fromBuild,
|
|
826
|
+
toBuildHash: moved.toBuild
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
// src/worlds/platformEndpoint.ts
|
|
832
|
+
var DEFAULT_HOST = "https://withgateway.ai";
|
|
833
|
+
var GATEWAY_KEYS_MISSING = "Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).";
|
|
834
|
+
function platformEndpoint(options) {
|
|
835
|
+
if (options.token)
|
|
836
|
+
return {
|
|
837
|
+
host: (options.host ?? options.token.host).replace(/\/+$/, ""),
|
|
838
|
+
publicKey: options.publicKey ?? "",
|
|
839
|
+
secretKey: options.secretKey ?? "",
|
|
840
|
+
token: options.token
|
|
841
|
+
};
|
|
842
|
+
const token = PersonalToken.fromEnv(process.env, {
|
|
843
|
+
host: options.host,
|
|
844
|
+
keys: Boolean(options.publicKey || options.secretKey)
|
|
845
|
+
});
|
|
846
|
+
if (token) return { host: token.host, publicKey: "", secretKey: "", token };
|
|
847
|
+
const host = (options.host ?? process.env.GATEWAY_HOST ?? DEFAULT_HOST).replace(/\/+$/, "");
|
|
848
|
+
const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
|
|
849
|
+
const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;
|
|
850
|
+
if (!publicKey || !secretKey) return null;
|
|
851
|
+
return { host, publicKey, secretKey };
|
|
852
|
+
}
|
|
853
|
+
function requirePlatformEndpoint(options) {
|
|
854
|
+
const endpoint = platformEndpoint(options);
|
|
855
|
+
if (!endpoint) throw new Error(GATEWAY_KEYS_MISSING);
|
|
856
|
+
return endpoint;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// src/agents/sse.ts
|
|
860
|
+
var EventStreamError = class extends Error {
|
|
861
|
+
constructor(code, message) {
|
|
862
|
+
super(message);
|
|
863
|
+
this.code = code;
|
|
864
|
+
this.name = "EventStreamError";
|
|
865
|
+
}
|
|
866
|
+
code;
|
|
867
|
+
};
|
|
868
|
+
var SseLimits = class _SseLimits {
|
|
869
|
+
constructor(maxLineLength, maxEventLength) {
|
|
870
|
+
this.maxLineLength = maxLineLength;
|
|
871
|
+
this.maxEventLength = maxEventLength;
|
|
872
|
+
}
|
|
873
|
+
maxLineLength;
|
|
874
|
+
maxEventLength;
|
|
875
|
+
static DEFAULT = new _SseLimits(4 * 1024 * 1024, 4 * 1024 * 1024);
|
|
876
|
+
};
|
|
877
|
+
var EventBlock = class {
|
|
878
|
+
constructor(id, limits) {
|
|
879
|
+
this.id = id;
|
|
880
|
+
this.limits = limits;
|
|
881
|
+
}
|
|
882
|
+
id;
|
|
883
|
+
limits;
|
|
884
|
+
#data = [];
|
|
885
|
+
#length = 0;
|
|
886
|
+
#type = "";
|
|
887
|
+
addData(value) {
|
|
888
|
+
this.#length += value.length + 1;
|
|
889
|
+
if (this.#length > this.limits.maxEventLength)
|
|
890
|
+
throw new EventStreamError("event_too_large", `an event passed ${this.limits.maxEventLength} characters`);
|
|
891
|
+
this.#data.push(value);
|
|
892
|
+
}
|
|
893
|
+
setType(value) {
|
|
894
|
+
this.#type = value;
|
|
895
|
+
}
|
|
896
|
+
setId(value) {
|
|
897
|
+
if (!value.includes("\0")) this.id = value;
|
|
898
|
+
}
|
|
899
|
+
message() {
|
|
900
|
+
if (this.#data.length === 0) return null;
|
|
901
|
+
return { event: this.#type || "message", data: this.#data.join("\n"), lastEventId: this.id || null };
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
var FIELDS = /* @__PURE__ */ new Map([
|
|
905
|
+
["data", (block, value) => block.addData(value)],
|
|
906
|
+
["event", (block, value) => block.setType(value)],
|
|
907
|
+
["id", (block, value) => block.setId(value)]
|
|
908
|
+
]);
|
|
909
|
+
var SseParser = class {
|
|
910
|
+
#decoder = new TextDecoder();
|
|
911
|
+
#lineEnd = /[\r\n]/g;
|
|
912
|
+
#limits;
|
|
913
|
+
#pending = "";
|
|
914
|
+
#afterCarriageReturn = false;
|
|
915
|
+
#lastEventId;
|
|
916
|
+
#block;
|
|
917
|
+
constructor(lastEventId = null, limits = SseLimits.DEFAULT) {
|
|
918
|
+
this.#limits = limits;
|
|
919
|
+
this.#lastEventId = lastEventId ?? "";
|
|
920
|
+
this.#block = new EventBlock(this.#lastEventId, limits);
|
|
921
|
+
}
|
|
922
|
+
/** The id a reconnect sends as `Last-Event-ID`: the last one set before a dispatched event, or null. */
|
|
923
|
+
get lastEventId() {
|
|
924
|
+
return this.#lastEventId || null;
|
|
925
|
+
}
|
|
926
|
+
/** Feed the next bytes; returns the events they completed, in order. */
|
|
927
|
+
push(chunk) {
|
|
928
|
+
const messages = [];
|
|
929
|
+
for (const line of this.lines(this.#decoder.decode(chunk, { stream: true }))) {
|
|
930
|
+
const message = this.line(line);
|
|
931
|
+
if (message) messages.push(message);
|
|
932
|
+
}
|
|
933
|
+
return messages;
|
|
934
|
+
}
|
|
935
|
+
lines(text) {
|
|
936
|
+
const scanFrom = this.#pending.length;
|
|
937
|
+
this.#pending += this.skipLineFeed(text);
|
|
938
|
+
const lines = [];
|
|
939
|
+
let start = 0;
|
|
940
|
+
this.#lineEnd.lastIndex = scanFrom;
|
|
941
|
+
for (let end = this.#lineEnd.exec(this.#pending); end; end = this.#lineEnd.exec(this.#pending)) {
|
|
942
|
+
lines.push(this.capped(this.#pending.slice(start, end.index)));
|
|
943
|
+
start = this.lineEnd(end.index);
|
|
944
|
+
this.#lineEnd.lastIndex = start;
|
|
945
|
+
}
|
|
946
|
+
this.#pending = this.capped(this.#pending.slice(start));
|
|
947
|
+
return lines;
|
|
948
|
+
}
|
|
949
|
+
lineEnd(index) {
|
|
950
|
+
const crlf = this.#pending.startsWith("\r\n", index);
|
|
951
|
+
this.#afterCarriageReturn = this.#pending[index] === "\r" && index + 1 === this.#pending.length;
|
|
952
|
+
return index + (crlf ? 2 : 1);
|
|
953
|
+
}
|
|
954
|
+
skipLineFeed(text) {
|
|
955
|
+
if (!this.#afterCarriageReturn || text === "") return text;
|
|
956
|
+
this.#afterCarriageReturn = false;
|
|
957
|
+
return text.startsWith("\n") ? text.slice(1) : text;
|
|
958
|
+
}
|
|
959
|
+
capped(line) {
|
|
960
|
+
if (line.length > this.#limits.maxLineLength)
|
|
961
|
+
throw new EventStreamError("line_too_large", `a line passed ${this.#limits.maxLineLength} characters`);
|
|
962
|
+
return line;
|
|
963
|
+
}
|
|
964
|
+
line(line) {
|
|
965
|
+
if (line === "") return this.dispatch();
|
|
966
|
+
if (line.startsWith(":")) return null;
|
|
967
|
+
const colon = line.indexOf(":");
|
|
968
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
969
|
+
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
970
|
+
FIELDS.get(field)?.(this.#block, value);
|
|
971
|
+
return null;
|
|
972
|
+
}
|
|
973
|
+
dispatch() {
|
|
974
|
+
const message = this.#block.message();
|
|
975
|
+
this.#lastEventId = this.#block.id;
|
|
976
|
+
this.#block = new EventBlock(this.#lastEventId, this.#limits);
|
|
977
|
+
return message;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
|
|
981
|
+
// src/agents/run.ts
|
|
982
|
+
var SYSTEM_CLOCK = Object.freeze({
|
|
983
|
+
now: () => Date.now(),
|
|
984
|
+
sleep: (ms, signal) => new Promise((resolve, reject) => {
|
|
985
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
986
|
+
const abort = () => {
|
|
987
|
+
clearTimeout(timer);
|
|
988
|
+
reject(signal?.reason);
|
|
989
|
+
};
|
|
990
|
+
const timer = setTimeout(() => {
|
|
991
|
+
signal?.removeEventListener("abort", abort);
|
|
992
|
+
resolve();
|
|
993
|
+
}, ms);
|
|
994
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
995
|
+
})
|
|
996
|
+
});
|
|
997
|
+
var ReconnectPolicy = class _ReconnectPolicy {
|
|
998
|
+
constructor(delaysMs, idleMs) {
|
|
999
|
+
this.delaysMs = delaysMs;
|
|
1000
|
+
this.idleMs = idleMs;
|
|
1001
|
+
}
|
|
1002
|
+
delaysMs;
|
|
1003
|
+
idleMs;
|
|
1004
|
+
static DEFAULT = new _ReconnectPolicy([250, 500, 1e3, 2e3, 4e3], PLATFORM_STREAM_IDLE_MS);
|
|
1005
|
+
};
|
|
1006
|
+
var STOPS = {
|
|
1007
|
+
"run.started": "continues",
|
|
1008
|
+
"step.attempt": "continues",
|
|
1009
|
+
"message.delta": "continues",
|
|
1010
|
+
"step.completed": "continues",
|
|
1011
|
+
"tool.started": "continues",
|
|
1012
|
+
"tool.completed": "continues",
|
|
1013
|
+
"run.error": "continues",
|
|
1014
|
+
"action.required": "waits",
|
|
1015
|
+
"run.completed": "ends",
|
|
1016
|
+
"run.failed": "ends",
|
|
1017
|
+
"run.cancelled": "ends"
|
|
1018
|
+
};
|
|
1019
|
+
var FINISHED = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
|
|
1020
|
+
var REFRESH_RETRIES = 3;
|
|
1021
|
+
var STREAM_REFUSALS_RETRIED = /* @__PURE__ */ new Set(["too_many_streams"]);
|
|
1022
|
+
var runRoute = (threadId, runId) => `/api/public/threads/${segment(threadId)}/runs/${segment(runId)}`;
|
|
1023
|
+
function readEvent(message) {
|
|
1024
|
+
if (!Object.hasOwn(STOPS, message.event)) return null;
|
|
1025
|
+
const data = parseJson(message.data);
|
|
1026
|
+
if (typeof data !== "object" || data === null || data.type !== message.event)
|
|
1027
|
+
throw new EventStreamError("malformed_event", `a ${message.event} event whose data is not that event's JSON`);
|
|
1028
|
+
return data;
|
|
1029
|
+
}
|
|
1030
|
+
function retried(refusal) {
|
|
1031
|
+
return RetryPolicy.TRANSIENT_STATUSES.has(refusal.status) || STREAM_REFUSALS_RETRIED.has(refusal.code ?? "");
|
|
1032
|
+
}
|
|
1033
|
+
function parseJson(text) {
|
|
1034
|
+
try {
|
|
1035
|
+
return JSON.parse(text);
|
|
1036
|
+
} catch {
|
|
1037
|
+
return void 0;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
var Connection = class {
|
|
1041
|
+
constructor(openedAt) {
|
|
1042
|
+
this.openedAt = openedAt;
|
|
1043
|
+
}
|
|
1044
|
+
openedAt;
|
|
1045
|
+
#delivered = false;
|
|
1046
|
+
#closedCleanly = false;
|
|
1047
|
+
#stop = "continues";
|
|
1048
|
+
#why = "the stream closed before the run ended";
|
|
1049
|
+
get ended() {
|
|
1050
|
+
return this.#stop === "ends";
|
|
1051
|
+
}
|
|
1052
|
+
// The door closes after action.required only while the run waits; when more events follow, that wait was answered.
|
|
1053
|
+
get stopped() {
|
|
1054
|
+
return this.#stop !== "continues";
|
|
1055
|
+
}
|
|
1056
|
+
get why() {
|
|
1057
|
+
return this.#why;
|
|
1058
|
+
}
|
|
1059
|
+
delivered() {
|
|
1060
|
+
this.#delivered = true;
|
|
1061
|
+
}
|
|
1062
|
+
at(stop) {
|
|
1063
|
+
this.#stop = stop;
|
|
1064
|
+
}
|
|
1065
|
+
closedCleanly() {
|
|
1066
|
+
this.#closedCleanly = true;
|
|
1067
|
+
}
|
|
1068
|
+
refused(status) {
|
|
1069
|
+
this.#why = `the platform answered ${status}`;
|
|
1070
|
+
}
|
|
1071
|
+
dropped(error) {
|
|
1072
|
+
if (!(error instanceof UnreachableError)) throw error;
|
|
1073
|
+
this.#why = error.message;
|
|
1074
|
+
}
|
|
1075
|
+
// A silence cut, a drop or a refused status never counts as working, however long it took: only an event, or the
|
|
1076
|
+
// platform's own clean close of a stream that lived the idle budget (its lifetime close), starts the count again.
|
|
1077
|
+
working(now, idleMs) {
|
|
1078
|
+
return this.#delivered || this.#closedCleanly && now - this.openedAt >= idleMs;
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
var Reconnects = class {
|
|
1082
|
+
constructor(policy, clock, route) {
|
|
1083
|
+
this.policy = policy;
|
|
1084
|
+
this.clock = clock;
|
|
1085
|
+
this.route = route;
|
|
1086
|
+
}
|
|
1087
|
+
policy;
|
|
1088
|
+
clock;
|
|
1089
|
+
route;
|
|
1090
|
+
#inARow = 0;
|
|
1091
|
+
async after(connection, signal) {
|
|
1092
|
+
this.#inARow = connection.working(this.clock.now(), this.policy.idleMs) ? 1 : this.#inARow + 1;
|
|
1093
|
+
const delayMs = this.policy.delaysMs[this.#inARow - 1];
|
|
1094
|
+
if (delayMs === void 0)
|
|
1095
|
+
throw new EventStreamError(
|
|
1096
|
+
"reconnects_exhausted",
|
|
1097
|
+
`GET ${this.route}: no working stream after ${this.policy.delaysMs.length} reconnects in a row; last: ${connection.why}`
|
|
1098
|
+
);
|
|
1099
|
+
await this.clock.sleep(delayMs, signal);
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
var AgentRun = class {
|
|
1103
|
+
#transport;
|
|
1104
|
+
#clock;
|
|
1105
|
+
#reconnect;
|
|
1106
|
+
#snapshot;
|
|
1107
|
+
#cursor = null;
|
|
1108
|
+
#ending = null;
|
|
1109
|
+
constructor(transport, run, options = {}) {
|
|
1110
|
+
this.#transport = transport;
|
|
1111
|
+
this.#snapshot = run;
|
|
1112
|
+
this.#clock = options.clock ?? SYSTEM_CLOCK;
|
|
1113
|
+
this.#reconnect = options.reconnect ?? ReconnectPolicy.DEFAULT;
|
|
1114
|
+
}
|
|
1115
|
+
get id() {
|
|
1116
|
+
return this.#snapshot.id;
|
|
1117
|
+
}
|
|
1118
|
+
get threadId() {
|
|
1119
|
+
return this.#snapshot.threadId;
|
|
1120
|
+
}
|
|
1121
|
+
/** The run as last read from the platform. */
|
|
1122
|
+
get snapshot() {
|
|
1123
|
+
return this.#snapshot;
|
|
1124
|
+
}
|
|
1125
|
+
/** The id of the last event delivered by any reader; pass it as `after` to resume this run's events elsewhere. */
|
|
1126
|
+
get cursor() {
|
|
1127
|
+
return this.#cursor;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* The run's events from `after` (default: where the last `events()` stopped, else the start). A dropped connection, a
|
|
1131
|
+
* silence past the idle budget (60 s), a 502/503/504, a 429 `too_many_streams` or the platform closing the stream
|
|
1132
|
+
* reconnects with `Last-Event-ID`,
|
|
1133
|
+
* so each event arrives once; after 5 reconnects in a row with no event delivered (a clean close after at least the idle
|
|
1134
|
+
* budget also counts as working) it throws `EventStreamError`. Ends after `run.completed`, `run.failed` (`not_found` when
|
|
1135
|
+
* the run no longer exists) or `run.cancelled`, and at an `action.required` the platform ends the stream on (the run waits
|
|
1136
|
+
* for a person); an `action.required` followed by more events was a wait already answered, and the events go on. A key
|
|
1137
|
+
* holds at most 64 open streams: past that the platform answers 429 `too_many_streams`, which counts against the same
|
|
1138
|
+
* five reconnects.
|
|
1139
|
+
*/
|
|
1140
|
+
async *events(options = {}) {
|
|
1141
|
+
const position = { cursor: options.after === void 0 ? this.#cursor : options.after };
|
|
1142
|
+
this.#ending = null;
|
|
1143
|
+
const reconnects = new Reconnects(this.#reconnect, this.#clock, `${runRoute(this.threadId, this.id)}/events`);
|
|
1144
|
+
for (; ; ) {
|
|
1145
|
+
const connection = new Connection(this.#clock.now());
|
|
1146
|
+
yield* this.connect(position, connection, options.signal);
|
|
1147
|
+
if (connection.stopped) return;
|
|
1148
|
+
await reconnects.after(connection, options.signal);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/** The run once it has finished, or once it waits for a person (`status: "requires_action"` with its `action`). Throws `EventStreamError` `run_not_finished` when the stream ended the run and the platform still reads it as active after the reconnect delays, and the platform's 404 `ApiError` (`not_found`) for a run that no longer exists. */
|
|
1152
|
+
async wait(options = {}) {
|
|
1153
|
+
const polls = this.#reconnect.delaysMs[Symbol.iterator]();
|
|
1154
|
+
let run = this.#ending === null ? this.#snapshot : await this.refresh(options);
|
|
1155
|
+
while (!this.settled(run)) {
|
|
1156
|
+
await this.advance(polls, options.signal);
|
|
1157
|
+
run = await this.refresh(options);
|
|
1158
|
+
}
|
|
1159
|
+
return run;
|
|
1160
|
+
}
|
|
1161
|
+
/** The run as the platform reads it now; a gateway 5xx or a dropped connection is retried with the first reconnect delays. `signal` aborts the request and its retry waits. */
|
|
1162
|
+
async refresh(options = {}) {
|
|
1163
|
+
const { signal } = options;
|
|
1164
|
+
const retry = new RetryPolicy(
|
|
1165
|
+
this.#reconnect.delaysMs.slice(0, REFRESH_RETRIES),
|
|
1166
|
+
(ms) => this.#clock.sleep(ms, signal)
|
|
1167
|
+
);
|
|
1168
|
+
return this.take(
|
|
1169
|
+
await this.#transport.json("GET", `${runRoute(this.threadId, this.id)}`, void 0, { retry, signal })
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
/** Stop the run; a run already finished answers with its status. */
|
|
1173
|
+
async cancel(options = {}) {
|
|
1174
|
+
const { signal } = options;
|
|
1175
|
+
return this.take(
|
|
1176
|
+
await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/cancel`, {}, { signal })
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
/** Answer the question the run waits on; the run is queued again and `events()` continues from where it stopped. */
|
|
1180
|
+
async resolve(answer, options = {}) {
|
|
1181
|
+
const body = { actionId: answer.actionId, answer: answer.answer };
|
|
1182
|
+
const { signal } = options;
|
|
1183
|
+
const run = await this.#transport.json("POST", `${runRoute(this.threadId, this.id)}/resolve`, body, {
|
|
1184
|
+
signal
|
|
1185
|
+
});
|
|
1186
|
+
this.#ending = null;
|
|
1187
|
+
return this.take(run);
|
|
1188
|
+
}
|
|
1189
|
+
settled(run) {
|
|
1190
|
+
return FINISHED.has(run.status) || this.#ending === "action.required" && run.status === "requires_action";
|
|
1191
|
+
}
|
|
1192
|
+
async advance(polls, signal) {
|
|
1193
|
+
if (this.#ending !== null && this.#ending !== "action.required") return this.pause(polls, signal);
|
|
1194
|
+
const before = this.#cursor;
|
|
1195
|
+
for await (const event of this.events({ signal })) void event;
|
|
1196
|
+
if (this.#ending === "action.required" && this.#cursor === before) await this.pause(polls, signal);
|
|
1197
|
+
}
|
|
1198
|
+
async pause(polls, signal) {
|
|
1199
|
+
const delay = polls.next();
|
|
1200
|
+
if (delay.done)
|
|
1201
|
+
throw new EventStreamError(
|
|
1202
|
+
"run_not_finished",
|
|
1203
|
+
`${runRoute(this.threadId, this.id)}: the stream ended the run with ${this.#ending}, and the platform still reads it as ${this.#snapshot.status}`
|
|
1204
|
+
);
|
|
1205
|
+
await this.#clock.sleep(delay.value, signal);
|
|
1206
|
+
}
|
|
1207
|
+
take(run) {
|
|
1208
|
+
this.#snapshot = run;
|
|
1209
|
+
return run;
|
|
1210
|
+
}
|
|
1211
|
+
async *connect(position, connection, signal) {
|
|
1212
|
+
const stream = await this.open(position, connection, signal);
|
|
1213
|
+
if (!stream) return;
|
|
1214
|
+
try {
|
|
1215
|
+
yield* this.read(stream, position, connection);
|
|
1216
|
+
connection.closedCleanly();
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
connection.dropped(error);
|
|
1219
|
+
} finally {
|
|
1220
|
+
stream.close();
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
async open(position, connection, signal) {
|
|
1224
|
+
const route = `${runRoute(this.threadId, this.id)}/events`;
|
|
1225
|
+
try {
|
|
1226
|
+
const stream = await this.#transport.stream(route, {
|
|
1227
|
+
after: position.cursor,
|
|
1228
|
+
signal,
|
|
1229
|
+
idleMs: this.#reconnect.idleMs
|
|
1230
|
+
});
|
|
1231
|
+
return await this.accepted(stream, route, connection);
|
|
1232
|
+
} catch (error) {
|
|
1233
|
+
connection.dropped(error);
|
|
1234
|
+
return null;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
async accepted(stream, route, connection) {
|
|
1238
|
+
if (stream.ok) return stream;
|
|
1239
|
+
const refusal = new ApiError(stream.status, "GET", route, await stream.text());
|
|
1240
|
+
if (!retried(refusal)) throw refusal;
|
|
1241
|
+
connection.refused(stream.status);
|
|
1242
|
+
return null;
|
|
1243
|
+
}
|
|
1244
|
+
async *read(stream, position, connection) {
|
|
1245
|
+
const parser = new SseParser(position.cursor);
|
|
1246
|
+
for await (const chunk of stream.chunks()) {
|
|
1247
|
+
for (const message of parser.push(chunk)) {
|
|
1248
|
+
const event = readEvent(message);
|
|
1249
|
+
this.moveTo(position, message.lastEventId);
|
|
1250
|
+
if (!event) continue;
|
|
1251
|
+
connection.delivered();
|
|
1252
|
+
this.note(event, connection);
|
|
1253
|
+
yield event;
|
|
1254
|
+
if (connection.ended) return;
|
|
1255
|
+
}
|
|
1256
|
+
this.moveTo(position, parser.lastEventId);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
// Each events() call resumes from its own position, so two readers of one run never skip or repeat each other's events.
|
|
1260
|
+
moveTo(position, cursor) {
|
|
1261
|
+
position.cursor = cursor;
|
|
1262
|
+
this.#cursor = cursor;
|
|
1263
|
+
}
|
|
1264
|
+
note(event, connection) {
|
|
1265
|
+
const stop = STOPS[event.type];
|
|
1266
|
+
this.#ending = stop === "continues" ? null : event.type;
|
|
1267
|
+
connection.at(stop);
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
|
|
1271
|
+
// src/agents/threads.ts
|
|
1272
|
+
var threadRoute = (threadId) => `/api/public/threads/${segment(threadId)}`;
|
|
1273
|
+
var Thread = class {
|
|
1274
|
+
#transport;
|
|
1275
|
+
#runs;
|
|
1276
|
+
id;
|
|
1277
|
+
agent;
|
|
1278
|
+
title;
|
|
1279
|
+
autonomy;
|
|
1280
|
+
activeRun;
|
|
1281
|
+
createdAt;
|
|
1282
|
+
/** Granted tools this key cannot activate; only on the thread `create` returns. */
|
|
1283
|
+
warnings;
|
|
1284
|
+
constructor(transport, record, runs = {}) {
|
|
1285
|
+
this.#transport = transport;
|
|
1286
|
+
this.#runs = runs;
|
|
1287
|
+
this.id = record.id;
|
|
1288
|
+
this.agent = record.agent;
|
|
1289
|
+
this.title = record.title;
|
|
1290
|
+
this.autonomy = Object.freeze({ ...record.autonomy });
|
|
1291
|
+
this.activeRun = record.activeRun ? Object.freeze({ ...record.activeRun }) : null;
|
|
1292
|
+
this.createdAt = record.createdAt;
|
|
1293
|
+
this.warnings = Object.freeze([...record.warnings ?? []]);
|
|
1294
|
+
}
|
|
1295
|
+
/** Start a run on the agent's deployed version (or `version`); refused with 409 `thread_busy` while another run is active. */
|
|
1296
|
+
async send(input, options = {}) {
|
|
1297
|
+
const body = { input, version: options.version, multitask: options.multitask };
|
|
1298
|
+
const run = await this.#transport.json("POST", `${threadRoute(this.id)}/runs`, body);
|
|
1299
|
+
return new AgentRun(this.#transport, run, this.#runs);
|
|
1300
|
+
}
|
|
1301
|
+
/** A run of this thread by id, as it is now. */
|
|
1302
|
+
async run(runId) {
|
|
1303
|
+
const run = await this.#transport.json("GET", `${threadRoute(this.id)}/runs/${segment(runId)}`);
|
|
1304
|
+
return new AgentRun(this.#transport, run, this.#runs);
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
var Threads = class {
|
|
1308
|
+
#transport;
|
|
1309
|
+
#runs;
|
|
1310
|
+
constructor(transport, runs = {}) {
|
|
1311
|
+
this.#transport = transport;
|
|
1312
|
+
this.#runs = runs;
|
|
1313
|
+
}
|
|
1314
|
+
/** A thread for a deployed agent; `allowSelfSchedule` or `allowSubagents` set to `true` is refused (400 `autonomy_unsupported`). */
|
|
1315
|
+
async create(options) {
|
|
1316
|
+
const agent = typeof options.agent === "string" ? options.agent : options.agent.name;
|
|
1317
|
+
const body = { agent, title: options.title, autonomy: options.autonomy };
|
|
1318
|
+
const record = await this.#transport.json("POST", "/api/public/threads", body);
|
|
1319
|
+
return new Thread(this.#transport, record, this.#runs);
|
|
1320
|
+
}
|
|
1321
|
+
async get(threadId) {
|
|
1322
|
+
const record = await this.#transport.json("GET", `${threadRoute(threadId)}`);
|
|
1323
|
+
return new Thread(this.#transport, record, this.#runs);
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
|
|
1327
|
+
// src/agents/gateway.ts
|
|
1328
|
+
var Gateway = class {
|
|
1329
|
+
agents;
|
|
1330
|
+
threads;
|
|
1331
|
+
constructor(options = {}) {
|
|
1332
|
+
const transport = options.transport ?? new PlatformTransport(requirePlatformEndpoint(options));
|
|
1333
|
+
this.threads = new Threads(transport, { clock: options.clock, reconnect: options.reconnect });
|
|
1334
|
+
this.agents = new Agents(transport, this.threads);
|
|
1335
|
+
Object.freeze(this);
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
|
|
1339
|
+
// src/agents/tools.ts
|
|
1340
|
+
var AGENT_MODELS = ["claude-opus-5", "claude-sonnet-5"];
|
|
1341
|
+
var AGENT_EFFORTS = ["low", "medium", "high", "xhigh"];
|
|
1342
|
+
var TOOL_SERVERS = {
|
|
1343
|
+
docs: ["search_docs"],
|
|
1344
|
+
drive: ["get_drive_file", "list_drive_files", "save_drive_file"],
|
|
1345
|
+
sandbox: [
|
|
1346
|
+
"copy_file",
|
|
1347
|
+
"execute_python",
|
|
1348
|
+
"grep_files",
|
|
1349
|
+
"ingest_sessions_to_sandbox",
|
|
1350
|
+
"list_files",
|
|
1351
|
+
"query_json",
|
|
1352
|
+
"read_file",
|
|
1353
|
+
"run_bash",
|
|
1354
|
+
"run_gateway_cli",
|
|
1355
|
+
"write_file"
|
|
1356
|
+
],
|
|
1357
|
+
web: ["download_url_to_drive", "fetch_url"]
|
|
1358
|
+
};
|
|
1359
|
+
var grant = (server) => (options = {}) => options.only ? { server, only: [...options.only] } : { server };
|
|
1360
|
+
var tools = Object.freeze({
|
|
1361
|
+
sandbox: grant("sandbox"),
|
|
1362
|
+
drive: grant("drive"),
|
|
1363
|
+
web: grant("web"),
|
|
1364
|
+
docs: grant("docs")
|
|
1365
|
+
});
|
|
1366
|
+
export {
|
|
1367
|
+
AGENT_EFFORTS,
|
|
1368
|
+
AGENT_MODELS,
|
|
1369
|
+
Agent,
|
|
1370
|
+
AgentDefinition,
|
|
1371
|
+
AgentDefinitionError,
|
|
1372
|
+
AgentPatch,
|
|
1373
|
+
AgentRun,
|
|
1374
|
+
AgentThreads,
|
|
1375
|
+
AgentTools,
|
|
1376
|
+
AgentVersionConflictError,
|
|
1377
|
+
AgentVersionNotFoundError,
|
|
1378
|
+
Agents,
|
|
1379
|
+
ApiError,
|
|
1380
|
+
EventStreamError,
|
|
1381
|
+
Gateway,
|
|
1382
|
+
PlatformTransport,
|
|
1383
|
+
ReconnectPolicy,
|
|
1384
|
+
SYSTEM_CLOCK,
|
|
1385
|
+
SseLimits,
|
|
1386
|
+
SseParser,
|
|
1387
|
+
TOOL_SERVERS,
|
|
1388
|
+
Thread,
|
|
1389
|
+
Threads,
|
|
1390
|
+
UnreachableError,
|
|
1391
|
+
defineAgent,
|
|
1392
|
+
tools
|
|
1393
|
+
};
|
|
1394
|
+
//# sourceMappingURL=index.mjs.map
|