@b3os/sdk 0.1.0 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -42
- package/dist/cjs/core/bytes.d.ts +30 -0
- package/dist/cjs/core/bytes.js +115 -0
- package/dist/cjs/core/bytes.js.map +1 -0
- package/dist/cjs/core/client.d.ts +61 -3
- package/dist/cjs/core/client.js +211 -33
- package/dist/cjs/core/client.js.map +1 -1
- package/dist/cjs/core/errors.d.ts +16 -4
- package/dist/cjs/core/errors.js +9 -6
- package/dist/cjs/core/errors.js.map +1 -1
- package/dist/cjs/core/handle.d.ts +31 -0
- package/dist/cjs/core/handle.js +86 -0
- package/dist/cjs/core/handle.js.map +1 -0
- package/dist/cjs/core/index.d.ts +6 -4
- package/dist/cjs/core/index.js +8 -1
- package/dist/cjs/core/index.js.map +1 -1
- package/dist/cjs/core/login.d.ts +24 -0
- package/dist/cjs/core/login.js +93 -0
- package/dist/cjs/core/login.js.map +1 -0
- package/dist/cjs/core/namespace.d.ts +1 -1
- package/dist/cjs/core/namespace.js +1 -1
- package/dist/cjs/core/op.d.ts +11 -1
- package/dist/cjs/core/timing.d.ts +1 -1
- package/dist/cjs/core/timing.js +8 -1
- package/dist/cjs/core/timing.js.map +1 -1
- package/dist/cjs/core/transport.js +1 -1
- package/dist/cjs/core/transport.js.map +1 -1
- package/dist/cjs/core/util.d.ts +15 -3
- package/dist/cjs/core/util.js +54 -2
- package/dist/cjs/core/util.js.map +1 -1
- package/dist/cjs/core/ws.d.ts +4 -0
- package/dist/cjs/core/ws.js +7 -4
- package/dist/cjs/core/ws.js.map +1 -1
- package/dist/cjs/generated/client.d.ts +2 -2
- package/dist/cjs/generated/client.js +2 -2
- package/dist/cjs/generated/errors.d.ts +1 -1
- package/dist/cjs/generated/errors.js +30 -0
- package/dist/cjs/generated/errors.js.map +1 -1
- package/dist/cjs/generated/jobs.js +1 -1
- package/dist/cjs/generated/ns/actions.d.ts +48 -6
- package/dist/cjs/generated/ns/actions.js +59 -6
- package/dist/cjs/generated/ns/actions.js.map +1 -1
- package/dist/cjs/generated/ns/infer.d.ts +185 -54
- package/dist/cjs/generated/ns/infer.js +28 -74
- package/dist/cjs/generated/ns/infer.js.map +1 -1
- package/dist/cjs/generated/ns/keys.d.ts +12 -0
- package/dist/cjs/generated/ns/keys.js +22 -0
- package/dist/cjs/generated/ns/keys.js.map +1 -1
- package/dist/cjs/generated/ns/render.d.ts +95 -6
- package/dist/cjs/generated/ns/render.js +124 -7
- package/dist/cjs/generated/ns/render.js.map +1 -1
- package/dist/cjs/generated/ns/requests.d.ts +3 -1
- package/dist/cjs/generated/ns/requests.js +3 -1
- package/dist/cjs/generated/ns/requests.js.map +1 -1
- package/dist/cjs/generated/ns/routines.d.ts +131 -9
- package/dist/cjs/generated/ns/routines.js +186 -9
- package/dist/cjs/generated/ns/routines.js.map +1 -1
- package/dist/cjs/generated/ns/sandboxes.d.ts +298 -31
- package/dist/cjs/generated/ns/sandboxes.js +368 -29
- package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
- package/dist/cjs/generated/ns/vision.d.ts +133 -14
- package/dist/cjs/generated/ns/vision.js +158 -12
- package/dist/cjs/generated/ns/vision.js.map +1 -1
- package/dist/cjs/generated/ns/webhooks.d.ts +8 -5
- package/dist/cjs/generated/ns/webhooks.js +8 -5
- package/dist/cjs/generated/ns/webhooks.js.map +1 -1
- package/dist/cjs/generated/types.d.ts +1956 -301
- package/dist/cjs/helpers/agents.d.ts +95 -0
- package/dist/cjs/helpers/agents.js +205 -0
- package/dist/cjs/helpers/agents.js.map +1 -0
- package/dist/cjs/helpers/render.d.ts +15 -0
- package/dist/cjs/helpers/render.js +74 -0
- package/dist/cjs/helpers/render.js.map +1 -0
- package/dist/cjs/helpers/routines.d.ts +61 -0
- package/dist/cjs/helpers/routines.js +234 -0
- package/dist/cjs/helpers/routines.js.map +1 -0
- package/dist/cjs/helpers/sandboxes.d.ts +237 -0
- package/dist/cjs/helpers/sandboxes.js +608 -0
- package/dist/cjs/helpers/sandboxes.js.map +1 -0
- package/dist/cjs/index.d.ts +4 -1
- package/dist/cjs/index.js +8 -5
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/routines.d.ts +1 -0
- package/dist/cjs/routines.js +21 -0
- package/dist/cjs/routines.js.map +1 -0
- package/dist/cjs/webhooks.js.map +1 -1
- package/dist/esm/core/bytes.d.ts +30 -0
- package/dist/esm/core/bytes.js +111 -0
- package/dist/esm/core/bytes.js.map +1 -0
- package/dist/esm/core/client.d.ts +61 -3
- package/dist/esm/core/client.js +208 -31
- package/dist/esm/core/client.js.map +1 -1
- package/dist/esm/core/errors.d.ts +16 -4
- package/dist/esm/core/errors.js +9 -6
- package/dist/esm/core/errors.js.map +1 -1
- package/dist/esm/core/handle.d.ts +31 -0
- package/dist/esm/core/handle.js +82 -0
- package/dist/esm/core/handle.js.map +1 -0
- package/dist/esm/core/index.d.ts +6 -4
- package/dist/esm/core/index.js +4 -2
- package/dist/esm/core/index.js.map +1 -1
- package/dist/esm/core/login.d.ts +24 -0
- package/dist/esm/core/login.js +85 -0
- package/dist/esm/core/login.js.map +1 -0
- package/dist/esm/core/namespace.d.ts +1 -1
- package/dist/esm/core/namespace.js +1 -1
- package/dist/esm/core/op.d.ts +11 -1
- package/dist/esm/core/timing.d.ts +1 -1
- package/dist/esm/core/timing.js +8 -1
- package/dist/esm/core/timing.js.map +1 -1
- package/dist/esm/core/transport.js +1 -1
- package/dist/esm/core/transport.js.map +1 -1
- package/dist/esm/core/util.d.ts +15 -3
- package/dist/esm/core/util.js +48 -1
- package/dist/esm/core/util.js.map +1 -1
- package/dist/esm/core/ws.d.ts +4 -0
- package/dist/esm/core/ws.js +7 -4
- package/dist/esm/core/ws.js.map +1 -1
- package/dist/esm/generated/client.d.ts +2 -2
- package/dist/esm/generated/client.js +2 -2
- package/dist/esm/generated/errors.d.ts +1 -1
- package/dist/esm/generated/errors.js +30 -0
- package/dist/esm/generated/errors.js.map +1 -1
- package/dist/esm/generated/jobs.js +1 -1
- package/dist/esm/generated/ns/actions.d.ts +48 -6
- package/dist/esm/generated/ns/actions.js +59 -6
- package/dist/esm/generated/ns/actions.js.map +1 -1
- package/dist/esm/generated/ns/infer.d.ts +185 -54
- package/dist/esm/generated/ns/infer.js +28 -74
- package/dist/esm/generated/ns/infer.js.map +1 -1
- package/dist/esm/generated/ns/keys.d.ts +12 -0
- package/dist/esm/generated/ns/keys.js +22 -0
- package/dist/esm/generated/ns/keys.js.map +1 -1
- package/dist/esm/generated/ns/render.d.ts +95 -6
- package/dist/esm/generated/ns/render.js +124 -7
- package/dist/esm/generated/ns/render.js.map +1 -1
- package/dist/esm/generated/ns/requests.d.ts +3 -1
- package/dist/esm/generated/ns/requests.js +3 -1
- package/dist/esm/generated/ns/requests.js.map +1 -1
- package/dist/esm/generated/ns/routines.d.ts +131 -9
- package/dist/esm/generated/ns/routines.js +186 -9
- package/dist/esm/generated/ns/routines.js.map +1 -1
- package/dist/esm/generated/ns/sandboxes.d.ts +298 -31
- package/dist/esm/generated/ns/sandboxes.js +368 -29
- package/dist/esm/generated/ns/sandboxes.js.map +1 -1
- package/dist/esm/generated/ns/vision.d.ts +133 -14
- package/dist/esm/generated/ns/vision.js +158 -12
- package/dist/esm/generated/ns/vision.js.map +1 -1
- package/dist/esm/generated/ns/webhooks.d.ts +8 -5
- package/dist/esm/generated/ns/webhooks.js +8 -5
- package/dist/esm/generated/ns/webhooks.js.map +1 -1
- package/dist/esm/generated/types.d.ts +1956 -301
- package/dist/esm/helpers/agents.d.ts +95 -0
- package/dist/esm/helpers/agents.js +199 -0
- package/dist/esm/helpers/agents.js.map +1 -0
- package/dist/esm/helpers/render.d.ts +15 -0
- package/dist/esm/helpers/render.js +70 -0
- package/dist/esm/helpers/render.js.map +1 -0
- package/dist/esm/helpers/routines.d.ts +61 -0
- package/dist/esm/helpers/routines.js +226 -0
- package/dist/esm/helpers/routines.js.map +1 -0
- package/dist/esm/helpers/sandboxes.d.ts +237 -0
- package/dist/esm/helpers/sandboxes.js +600 -0
- package/dist/esm/helpers/sandboxes.js.map +1 -0
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.js +6 -5
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/routines.d.ts +1 -0
- package/dist/esm/routines.js +5 -0
- package/dist/esm/routines.js.map +1 -0
- package/dist/esm/webhooks.js.map +1 -1
- package/package.json +14 -3
- package/src/core/bytes.ts +112 -0
- package/src/core/client.ts +253 -33
- package/src/core/errors.ts +27 -10
- package/src/core/handle.ts +97 -0
- package/src/core/index.ts +7 -2
- package/src/core/login.ts +98 -0
- package/src/core/namespace.ts +1 -1
- package/src/core/op.ts +11 -1
- package/src/core/timing.ts +7 -2
- package/src/core/transport.ts +1 -1
- package/src/core/util.ts +53 -3
- package/src/core/ws.ts +11 -4
- package/src/generated/client.ts +2 -2
- package/src/generated/errors.ts +60 -0
- package/src/generated/jobs.ts +1 -1
- package/src/generated/ns/actions.ts +69 -6
- package/src/generated/ns/infer.ts +229 -61
- package/src/generated/ns/keys.ts +23 -0
- package/src/generated/ns/render.ts +152 -7
- package/src/generated/ns/requests.ts +3 -1
- package/src/generated/ns/routines.ts +205 -9
- package/src/generated/ns/sandboxes.ts +434 -34
- package/src/generated/ns/vision.ts +168 -14
- package/src/generated/ns/webhooks.ts +8 -5
- package/src/generated/types.ts +2211 -422
- package/src/helpers/agents.ts +300 -0
- package/src/helpers/render.ts +91 -0
- package/src/helpers/routines.ts +278 -0
- package/src/helpers/sandboxes.ts +788 -0
- package/src/index.ts +29 -5
- package/src/routines.ts +5 -0
- package/src/webhooks.ts +5 -1
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// Hosted agent harnesses running their tools in B3OS sandboxes (research A15): the model and the agent loop stay
|
|
2
|
+
// with the provider, the tool calls run in a microVM on the node, and the sandbox talks to the provider over
|
|
3
|
+
// outbound connections only (no inbound port). The commands are the providers' own workers, which the sandbox
|
|
4
|
+
// template must carry (the sandboxes workstream's `agent` template; `command` overrides the binary):
|
|
5
|
+
//
|
|
6
|
+
// - Claude Managed Agents, self-hosted environments: `ant beta:worker poll --workdir /workspace` (always on, every
|
|
7
|
+
// session in one sandbox) or `ant beta:worker run` (one sandbox per claimed session), authenticated with the
|
|
8
|
+
// environment key (platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes-workers, read 2026-10-27).
|
|
9
|
+
// - OpenAI Codex remote environments: `codex exec-server --remote <url> --environment-id <id>` registers the
|
|
10
|
+
// exec-server over one outbound connection (`codex exec-server --help`, codex-cli 0.164.0).
|
|
11
|
+
//
|
|
12
|
+
// In a sandbox this helper creates, credentials go in as sandbox `secrets`: environment variables that are never
|
|
13
|
+
// returned or logged by B3OS but that code inside the VM can read (ARCHITECTURE §5.3), and egress is an allow list
|
|
14
|
+
// of the provider's API host (and of `baseUrl`'s / `remoteUrl`'s host). An existing sandbox (`sandboxId`) keeps
|
|
15
|
+
// the secrets and egress it was created with, which cannot change afterwards: the helper uses the secrets it holds
|
|
16
|
+
// (by `secret_names`), refuses one it lacks unless `execEnvCredentials` says to pass the value on the worker's
|
|
17
|
+
// exec request (outside the `secrets` guarantee), and refuses a sandbox whose egress cannot reach the provider.
|
|
18
|
+
|
|
19
|
+
import type { RequestOptions } from "../core/client.ts";
|
|
20
|
+
import { B3OSError } from "../core/errors.ts";
|
|
21
|
+
import type { SandboxesAPI } from "../generated/ns/sandboxes.ts";
|
|
22
|
+
import type * as T from "../generated/types.ts";
|
|
23
|
+
import { type SandboxCreateBody, type Service, startService } from "./sandboxes.ts";
|
|
24
|
+
|
|
25
|
+
/** Where a harness sandbox comes from and what it may reach. */
|
|
26
|
+
export interface HarnessSandboxOptions extends RequestOptions {
|
|
27
|
+
/**
|
|
28
|
+
* An existing sandbox; otherwise one is created from `snapshot` or `template` (default `agent`). It keeps its own
|
|
29
|
+
* secrets and egress: create it with the credentials as `secrets` (e.g. `ANTHROPIC_ENVIRONMENT_KEY`) and an
|
|
30
|
+
* egress policy that reaches the provider.
|
|
31
|
+
*/
|
|
32
|
+
sandboxId?: string;
|
|
33
|
+
/**
|
|
34
|
+
* With `sandboxId`: pass a credential the sandbox does not hold as a secret in the worker's exec `env` instead
|
|
35
|
+
* of refusing. Exec `env` is not covered by the `secrets` guarantee (never returned or logged).
|
|
36
|
+
*/
|
|
37
|
+
execEnvCredentials?: boolean;
|
|
38
|
+
template?: string;
|
|
39
|
+
/** Restore this snapshot (a prepared harness image boots per session from it). */
|
|
40
|
+
snapshot?: string;
|
|
41
|
+
vcpu?: number;
|
|
42
|
+
memory_mib?: number;
|
|
43
|
+
timeout_s?: number;
|
|
44
|
+
/** `pause` keeps a session's sandbox frozen between turns instead of stopping it at `timeout_s`. */
|
|
45
|
+
on_timeout?: "stop" | "pause";
|
|
46
|
+
/** @deprecated The old name of `on_timeout`; it does the same. */
|
|
47
|
+
on_idle?: "stop" | "pause";
|
|
48
|
+
/** Hosts a new sandbox may reach; default the provider's API host only. Not with `sandboxId`. */
|
|
49
|
+
egressAllow?: string[];
|
|
50
|
+
metadata?: Record<string, string>;
|
|
51
|
+
/** The worker binary, when it is not on the template's PATH. */
|
|
52
|
+
command?: string;
|
|
53
|
+
workdir?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface Harness extends Service {
|
|
57
|
+
sandbox: T.Sandbox;
|
|
58
|
+
/** True when this helper created the sandbox (`stop()` then also deletes it unless `keepSandbox`). */
|
|
59
|
+
created: boolean;
|
|
60
|
+
/** Stops the worker and, for a sandbox this helper created, deletes the sandbox. */
|
|
61
|
+
close(options?: { keepSandbox?: boolean }): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const ANTHROPIC_HOSTS = ["api.anthropic.com"];
|
|
65
|
+
const OPENAI_HOSTS = ["api.openai.com", "chatgpt.com"];
|
|
66
|
+
|
|
67
|
+
const invalid = (detail: string) => new B3OSError({ code: "invalid_request", status: null, detail });
|
|
68
|
+
|
|
69
|
+
function hostOf(url: string, what: string): string {
|
|
70
|
+
try {
|
|
71
|
+
const h = new URL(url).hostname;
|
|
72
|
+
if (h) return h;
|
|
73
|
+
} catch {
|
|
74
|
+
// reported below
|
|
75
|
+
}
|
|
76
|
+
throw invalid(`${what} is not a URL: ${url}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Whether an egress allow list (exact hosts, `*.` wildcards) admits `host`. */
|
|
80
|
+
export function egressAllows(egress: { mode: string; allow?: string[] }, host: string): boolean {
|
|
81
|
+
if (egress.mode === "public") return true;
|
|
82
|
+
if (egress.mode !== "allowlist") return false;
|
|
83
|
+
const h = host.toLowerCase();
|
|
84
|
+
return (egress.allow ?? []).some((a) => {
|
|
85
|
+
const x = a.toLowerCase();
|
|
86
|
+
return x === h || (x.startsWith("*.") && h.endsWith(x.slice(1)));
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The worker's exec `env` in an existing sandbox: its variables, plus only those credentials the sandbox does not
|
|
92
|
+
* hold as secrets, and only when the caller allowed that. Refuses what would not work or would weaken the secret.
|
|
93
|
+
*/
|
|
94
|
+
function existingSandboxEnv(
|
|
95
|
+
sandbox: T.Sandbox,
|
|
96
|
+
o: HarnessSandboxOptions,
|
|
97
|
+
spec: { env: Record<string, string>; secrets: Record<string, string>; hosts: string[]; name: string },
|
|
98
|
+
): Record<string, string> {
|
|
99
|
+
if (o.egressAllow !== undefined) {
|
|
100
|
+
throw invalid(
|
|
101
|
+
`egressAllow applies to a sandbox the helper creates; ${sandbox.id} keeps the egress it was created with`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
const need = spec.hosts[0] as string;
|
|
105
|
+
const egress = sandbox.egress ?? { mode: "public", allow: [] };
|
|
106
|
+
if (!egressAllows(egress, need)) {
|
|
107
|
+
const allow = egress.mode === "allowlist" ? `: ${egress.allow?.join(", ") || "nothing"}` : "";
|
|
108
|
+
throw invalid(
|
|
109
|
+
`${sandbox.id}'s egress (${egress.mode}${allow}) does not reach ${need}, which the ${spec.name} worker needs; ` +
|
|
110
|
+
"egress is fixed when a sandbox is created",
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
const held = new Set(sandbox.secret_names ?? []);
|
|
114
|
+
const missing = Object.keys(spec.secrets).filter((k) => !held.has(k));
|
|
115
|
+
if (missing.length && !o.execEnvCredentials) {
|
|
116
|
+
throw invalid(
|
|
117
|
+
`${sandbox.id} holds no secret ${missing.join(", ")}: create the sandbox with it in \`secrets\`, or set ` +
|
|
118
|
+
"execEnvCredentials to pass it in the worker's exec env (not covered by the secrets guarantee)",
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return { ...spec.env, ...Object.fromEntries(missing.map((k) => [k, spec.secrets[k] as string])) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function harness(
|
|
125
|
+
api: SandboxesAPI,
|
|
126
|
+
o: HarnessSandboxOptions,
|
|
127
|
+
spec: { env: Record<string, string>; secrets: Record<string, string>; cmd: string[]; hosts: string[]; name: string },
|
|
128
|
+
): Promise<Harness> {
|
|
129
|
+
const req: RequestOptions = {
|
|
130
|
+
...(o.signal ? { signal: o.signal } : {}),
|
|
131
|
+
...(o.headers ? { headers: o.headers } : {}),
|
|
132
|
+
};
|
|
133
|
+
let sandbox: T.Sandbox;
|
|
134
|
+
let created = false;
|
|
135
|
+
let env: Record<string, string> | undefined;
|
|
136
|
+
if (o.sandboxId) {
|
|
137
|
+
sandbox = await api.getSandbox(o.sandboxId, req);
|
|
138
|
+
env = existingSandboxEnv(sandbox, o, spec);
|
|
139
|
+
} else {
|
|
140
|
+
const onTimeout = o.on_timeout ?? o.on_idle;
|
|
141
|
+
const body: SandboxCreateBody = {
|
|
142
|
+
...(o.snapshot ? { snapshot: o.snapshot } : { template: o.template ?? "agent" }),
|
|
143
|
+
env: spec.env,
|
|
144
|
+
secrets: spec.secrets,
|
|
145
|
+
egress: { mode: "allowlist", allow: o.egressAllow ?? spec.hosts },
|
|
146
|
+
metadata: { "b3os.harness": spec.name, ...(o.metadata ?? {}) },
|
|
147
|
+
...(o.vcpu !== undefined ? { vcpu: o.vcpu } : {}),
|
|
148
|
+
...(o.memory_mib !== undefined ? { memory_mib: o.memory_mib } : {}),
|
|
149
|
+
...(o.timeout_s !== undefined ? { timeout_s: o.timeout_s } : {}),
|
|
150
|
+
...(onTimeout ? { on_timeout: onTimeout } : {}),
|
|
151
|
+
} as SandboxCreateBody;
|
|
152
|
+
sandbox = await api.createSandbox(body, req);
|
|
153
|
+
created = true;
|
|
154
|
+
}
|
|
155
|
+
let svc: Service;
|
|
156
|
+
try {
|
|
157
|
+
// A new sandbox already has the variables as env and secrets; an existing one gets them on the process.
|
|
158
|
+
svc = await startService(api, sandbox.id, {
|
|
159
|
+
cmd: spec.cmd,
|
|
160
|
+
...(o.workdir ? { cwd: o.workdir } : {}),
|
|
161
|
+
...(env && Object.keys(env).length ? { env } : {}),
|
|
162
|
+
...req,
|
|
163
|
+
});
|
|
164
|
+
// The workers print no documented "ready" line; one that dies at once (bad key, missing binary) is reported.
|
|
165
|
+
await new Promise((r) => setTimeout(r, 750));
|
|
166
|
+
const list = await api.listProcesses(sandbox.id, req);
|
|
167
|
+
const p = list.data.find((x) => x.pid === svc.pid);
|
|
168
|
+
if (!p || p.status === "exited") {
|
|
169
|
+
throw new B3OSError({
|
|
170
|
+
code: "process_exited",
|
|
171
|
+
status: null,
|
|
172
|
+
detail:
|
|
173
|
+
`${spec.name} worker ${spec.cmd[0]} ${p ? `exited ${p.exit_code ?? p.signal ?? ""}` : "is gone"} right after ` +
|
|
174
|
+
`starting in ${sandbox.id}; read its output with sandboxes.streamLogs(id, { pid: ${svc.pid} })`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
} catch (e) {
|
|
178
|
+
if (created) await api.deleteSandbox(sandbox.id, req).catch(() => undefined);
|
|
179
|
+
throw e;
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
...svc,
|
|
183
|
+
sandbox,
|
|
184
|
+
created,
|
|
185
|
+
async close(c = {}) {
|
|
186
|
+
await svc.stop().catch(() => undefined);
|
|
187
|
+
if (created && !c.keepSandbox) await api.deleteSandbox(sandbox.id, req).catch(() => undefined);
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface ManagedAgentsWorkerOptions extends HarnessSandboxOptions {
|
|
193
|
+
/** The self-hosted environment's ID (`ANTHROPIC_ENVIRONMENT_ID`). */
|
|
194
|
+
environmentId: string;
|
|
195
|
+
/** The environment key (not an API key); it becomes the sandbox secret `ANTHROPIC_ENVIRONMENT_KEY`. */
|
|
196
|
+
environmentKey: string;
|
|
197
|
+
/** Anthropic API base URL, when not the default (`ANTHROPIC_BASE_URL`); its host joins the default egress. */
|
|
198
|
+
baseUrl?: string;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const anthropicHosts = (baseUrl: string | undefined) =>
|
|
202
|
+
baseUrl ? [...new Set([hostOf(baseUrl, "baseUrl"), ...ANTHROPIC_HOSTS])] : ANTHROPIC_HOSTS;
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* An always-on Claude Managed Agents worker in a sandbox: `ant beta:worker poll` claims every session of the
|
|
206
|
+
* environment and runs its tool calls in this one sandbox (outbound HTTPS only).
|
|
207
|
+
*/
|
|
208
|
+
export async function startManagedAgentsWorker(api: SandboxesAPI, o: ManagedAgentsWorkerOptions): Promise<Harness> {
|
|
209
|
+
const workdir = o.workdir ?? "/workspace";
|
|
210
|
+
return harness(
|
|
211
|
+
api,
|
|
212
|
+
{ ...o, workdir },
|
|
213
|
+
{
|
|
214
|
+
name: "claude-managed-agents",
|
|
215
|
+
env: { ANTHROPIC_ENVIRONMENT_ID: o.environmentId, ...(o.baseUrl ? { ANTHROPIC_BASE_URL: o.baseUrl } : {}) },
|
|
216
|
+
secrets: { ANTHROPIC_ENVIRONMENT_KEY: o.environmentKey },
|
|
217
|
+
cmd: [o.command ?? "ant", "beta:worker", "poll", "--workdir", workdir],
|
|
218
|
+
hosts: anthropicHosts(o.baseUrl),
|
|
219
|
+
},
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A work item claimed from the environment's queue (the Anthropic SDK's WorkPoller yields these). */
|
|
224
|
+
export interface ManagedAgentsWork {
|
|
225
|
+
id: string;
|
|
226
|
+
data: { id: string };
|
|
227
|
+
secret?: string | null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export interface ManagedAgentsSessionOptions extends ManagedAgentsWorkerOptions {
|
|
231
|
+
work: ManagedAgentsWork;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* One sandbox per claimed Claude Managed Agents session (`ant beta:worker run`): pass each work item your
|
|
236
|
+
* WorkPoller claims (with `autoStop: false`); restoring from a prepared `snapshot` boots the harness per session,
|
|
237
|
+
* and `on_timeout: "pause"` keeps it frozen between turns. The work item's secret becomes `ANTHROPIC_WORK_SECRET`.
|
|
238
|
+
*/
|
|
239
|
+
export async function launchManagedAgentsSession(api: SandboxesAPI, o: ManagedAgentsSessionOptions): Promise<Harness> {
|
|
240
|
+
const workdir = o.workdir ?? "/workspace";
|
|
241
|
+
return harness(
|
|
242
|
+
api,
|
|
243
|
+
{ ...o, workdir, metadata: { "anthropic.session": o.work.data.id, ...(o.metadata ?? {}) } },
|
|
244
|
+
{
|
|
245
|
+
name: "claude-managed-agents-session",
|
|
246
|
+
env: {
|
|
247
|
+
ANTHROPIC_ENVIRONMENT_ID: o.environmentId,
|
|
248
|
+
ANTHROPIC_SESSION_ID: o.work.data.id,
|
|
249
|
+
ANTHROPIC_WORK_ID: o.work.id,
|
|
250
|
+
...(o.baseUrl ? { ANTHROPIC_BASE_URL: o.baseUrl } : {}),
|
|
251
|
+
},
|
|
252
|
+
secrets: {
|
|
253
|
+
ANTHROPIC_ENVIRONMENT_KEY: o.environmentKey,
|
|
254
|
+
...(o.work.secret ? { ANTHROPIC_WORK_SECRET: o.work.secret } : {}),
|
|
255
|
+
},
|
|
256
|
+
cmd: [o.command ?? "ant", "beta:worker", "run"],
|
|
257
|
+
hosts: anthropicHosts(o.baseUrl),
|
|
258
|
+
},
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface CodexExecServerOptions extends HarnessSandboxOptions {
|
|
263
|
+
/** The remote environment service's base URL (`codex exec-server --remote`). */
|
|
264
|
+
remoteUrl: string;
|
|
265
|
+
environmentId: string;
|
|
266
|
+
/** Human-readable environment name (`--name`). */
|
|
267
|
+
name?: string;
|
|
268
|
+
/** `CODEX_ACCESS_TOKEN` for `--use-agent-identity-auth`; it becomes a sandbox secret. */
|
|
269
|
+
accessToken?: string;
|
|
270
|
+
/** `--remote-transport` (codex default: noise). */
|
|
271
|
+
remoteTransport?: "noise" | "direct";
|
|
272
|
+
extraArgs?: string[];
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* A Codex exec-server registered as a remote environment from inside a sandbox: one outbound connection, no
|
|
277
|
+
* inbound port; the provider's agent runs its commands here.
|
|
278
|
+
*/
|
|
279
|
+
export async function startCodexExecServer(api: SandboxesAPI, o: CodexExecServerOptions): Promise<Harness> {
|
|
280
|
+
const cmd = [
|
|
281
|
+
o.command ?? "codex",
|
|
282
|
+
"exec-server",
|
|
283
|
+
"--remote",
|
|
284
|
+
o.remoteUrl,
|
|
285
|
+
"--environment-id",
|
|
286
|
+
o.environmentId,
|
|
287
|
+
...(o.name ? ["--name", o.name] : []),
|
|
288
|
+
...(o.remoteTransport ? ["--remote-transport", o.remoteTransport] : []),
|
|
289
|
+
...(o.accessToken ? ["--use-agent-identity-auth"] : []),
|
|
290
|
+
...(o.extraArgs ?? []),
|
|
291
|
+
];
|
|
292
|
+
const host = hostOf(o.remoteUrl, "remoteUrl");
|
|
293
|
+
return harness(api, o, {
|
|
294
|
+
name: "codex-exec-server",
|
|
295
|
+
env: {},
|
|
296
|
+
secrets: o.accessToken ? { CODEX_ACCESS_TOKEN: o.accessToken } : {},
|
|
297
|
+
cmd,
|
|
298
|
+
hosts: [...new Set([host, ...OPENAI_HOSTS])],
|
|
299
|
+
});
|
|
300
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// render.fetchArtifact: an artifact's bytes. Artifact URLs point at usercontent.b3os.org
|
|
2
|
+
// (`/a/<art-…>/<name>?node=…&exp=…&sig=…`), which serves them from storage or, until the upload lands, streams them
|
|
3
|
+
// from the node through the tunnel. A client that reaches the node itself (its Unix socket, or a node URL inside a
|
|
4
|
+
// sandbox) reads the same bytes from the node's public route `GET /v1/render/artifacts/{art_…}/content/{name}`
|
|
5
|
+
// with the same signed query (the signature covers that route's path), so a same-host agent never sends them out
|
|
6
|
+
// over the node's uplink and back. Any other client fetches the URL as given.
|
|
7
|
+
|
|
8
|
+
import type { B3OSCore, RequestOptions } from "../core/client.ts";
|
|
9
|
+
import { B3OSError } from "../core/errors.ts";
|
|
10
|
+
import type { Op } from "../core/op.ts";
|
|
11
|
+
import type * as T from "../generated/types.ts";
|
|
12
|
+
|
|
13
|
+
const artifactContentOp: Op = {
|
|
14
|
+
id: "renderGetArtifactContent",
|
|
15
|
+
method: "GET",
|
|
16
|
+
path: "/v1/render/artifacts/{artifact_id}/content/{name}",
|
|
17
|
+
params: ["artifact_id", "name"],
|
|
18
|
+
timeoutMs: 65000,
|
|
19
|
+
scope: "render:read",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export interface ArtifactBytes {
|
|
23
|
+
bytes: Uint8Array;
|
|
24
|
+
contentType: string | null;
|
|
25
|
+
/** `node`: read from the node's own route; `url`: fetched from the artifact URL. */
|
|
26
|
+
via: "node" | "url";
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The node route for a usercontent artifact URL, or undefined when the URL has another shape. */
|
|
30
|
+
export function nodeArtifactRoute(
|
|
31
|
+
url: string,
|
|
32
|
+
): { artifactId: string; name: string; query: Record<string, string> } | undefined {
|
|
33
|
+
let u: URL;
|
|
34
|
+
try {
|
|
35
|
+
u = new URL(url);
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const m = u.pathname.match(/^\/a\/art-([0-9a-hjkmnp-tv-z]{26})\/([^/]+)$/);
|
|
40
|
+
if (!m) return undefined;
|
|
41
|
+
const query: Record<string, string> = {};
|
|
42
|
+
for (const k of ["node", "exp", "sig"]) {
|
|
43
|
+
const v = u.searchParams.get(k);
|
|
44
|
+
if (v === null) return undefined;
|
|
45
|
+
query[k] = v;
|
|
46
|
+
}
|
|
47
|
+
let name: string;
|
|
48
|
+
try {
|
|
49
|
+
name = decodeURIComponent(m[2] as string);
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
return { artifactId: `art_${m[1]}`, name, query };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function fetchArtifact(
|
|
57
|
+
client: B3OSCore,
|
|
58
|
+
artifact: Pick<T.Artifact, "url" | "content_type"> | string,
|
|
59
|
+
options: RequestOptions = {},
|
|
60
|
+
): Promise<ArtifactBytes> {
|
|
61
|
+
const url = typeof artifact === "string" ? artifact : artifact.url;
|
|
62
|
+
if (!url) {
|
|
63
|
+
throw new B3OSError({
|
|
64
|
+
code: "invalid_response",
|
|
65
|
+
status: null,
|
|
66
|
+
detail: "The artifact has no url (expired or not ready)",
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const route = client.routes.nodeKind === "edge" ? undefined : nodeArtifactRoute(url);
|
|
70
|
+
if (route) {
|
|
71
|
+
const { data, response } = await client
|
|
72
|
+
._call<Uint8Array>(
|
|
73
|
+
artifactContentOp,
|
|
74
|
+
{ path: [route.artifactId, route.name], query: route.query },
|
|
75
|
+
options,
|
|
76
|
+
typeof artifact === "string" ? "*/*" : (artifact.content_type ?? "*/*"),
|
|
77
|
+
"bytes",
|
|
78
|
+
)
|
|
79
|
+
.withResponse();
|
|
80
|
+
return { bytes: data, contentType: response.headers.get("content-type"), via: "node" };
|
|
81
|
+
}
|
|
82
|
+
const res = await fetch(url, options.signal ? { signal: options.signal } : {});
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
throw new B3OSError({
|
|
85
|
+
code: res.status === 403 ? "signed_url_invalid" : res.status === 404 ? "artifact_not_found" : "internal",
|
|
86
|
+
status: res.status,
|
|
87
|
+
detail: `GET ${new URL(url).host}${new URL(url).pathname}: ${res.status}`,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return { bytes: new Uint8Array(await res.arrayBuffer()), contentType: res.headers.get("content-type"), via: "url" };
|
|
91
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// @b3os/sdk/routines: build routine definitions (packages/spec/schemas/routine.schema.json) in TypeScript, with the
|
|
2
|
+
// product steps' `with` typed as their API request bodies, then publish them with `b3os.routines.publishRoutine`.
|
|
3
|
+
//
|
|
4
|
+
// import { defineRoutine, expr, step } from "@b3os/sdk/routines";
|
|
5
|
+
// const digest = defineRoutine({
|
|
6
|
+
// name: "hn-digest",
|
|
7
|
+
// inputs: { type: "object", properties: { url: { type: "string" } }, required: ["url"] },
|
|
8
|
+
// triggers: [{ type: "cron", cron: "0 0 8 * * *", tz: "America/Los_Angeles" }],
|
|
9
|
+
// steps: [
|
|
10
|
+
// step.vision.scrape("page", { url: expr("inputs.url"), formats: ["markdown"] }),
|
|
11
|
+
// step.infer.chat("summary", { model: "b3os/qwen3.5-9b", messages: [{ role: "user", content: expr("steps.page.outputs.markdown") }] }, { needs: ["page"] }),
|
|
12
|
+
// ],
|
|
13
|
+
// output: expr("steps.summary.outputs.choices[0].message.content"),
|
|
14
|
+
// });
|
|
15
|
+
// await b3os.routines.publishRoutine(digest.name, digest);
|
|
16
|
+
//
|
|
17
|
+
// `defineRoutine` checks what can be checked without the node: step ids unique per scope, `needs` naming steps of
|
|
18
|
+
// the same scope, `uses` in the callable grammar, and every `${{` closed (scanned as the node scans it). The node
|
|
19
|
+
// validates the rest at publish (CEL names, schemas).
|
|
20
|
+
|
|
21
|
+
import type {
|
|
22
|
+
ChatCompletionRequest,
|
|
23
|
+
ExecRequest,
|
|
24
|
+
RoutineDefinition,
|
|
25
|
+
RoutineDefinitionCoreHttpWith,
|
|
26
|
+
RoutineDefinitionCoreLogWith,
|
|
27
|
+
RoutineDefinitionStep,
|
|
28
|
+
ScrapeRequest,
|
|
29
|
+
ScreenshotCreateRequest,
|
|
30
|
+
} from "../generated/types.ts";
|
|
31
|
+
|
|
32
|
+
/** A value or a `${{ }}` expression standing for one (recursively for objects and arrays). */
|
|
33
|
+
export type Templated<T> = T extends string
|
|
34
|
+
? string
|
|
35
|
+
: T extends readonly (infer U)[]
|
|
36
|
+
? Templated<U>[] | string
|
|
37
|
+
: T extends object
|
|
38
|
+
? { [K in keyof T]: Templated<T[K]> } | string
|
|
39
|
+
: T | string;
|
|
40
|
+
|
|
41
|
+
/** `${{ <cel> }}`: a CEL expression, evaluated when the step runs. */
|
|
42
|
+
export function expr(cel: string): string {
|
|
43
|
+
return `\${{ ${cel} }}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `${{ steps.<id>.outputs.<path> }}`. */
|
|
47
|
+
export function output(stepId: string, path = ""): string {
|
|
48
|
+
return expr(`steps.${stepId}.outputs${path ? (path.startsWith("[") ? path : `.${path}`) : ""}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
type StepOptions = Omit<RoutineDefinitionStep, "id" | "uses" | "with">;
|
|
52
|
+
|
|
53
|
+
function callStep(uses: string) {
|
|
54
|
+
return <W>(id: string, w: Templated<W>, options: StepOptions = {}): RoutineDefinitionStep => ({
|
|
55
|
+
id,
|
|
56
|
+
uses,
|
|
57
|
+
with: w as Record<string, unknown>,
|
|
58
|
+
...options,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Steps for B3OS's first-party callables and marketplace actions. */
|
|
63
|
+
export const step = {
|
|
64
|
+
vision: {
|
|
65
|
+
scrape: callStep("vision/scrape@1") as (
|
|
66
|
+
id: string,
|
|
67
|
+
w: Templated<ScrapeRequest>,
|
|
68
|
+
o?: StepOptions,
|
|
69
|
+
) => RoutineDefinitionStep,
|
|
70
|
+
},
|
|
71
|
+
render: {
|
|
72
|
+
screenshot: callStep("render/screenshot@1") as (
|
|
73
|
+
id: string,
|
|
74
|
+
w: Templated<ScreenshotCreateRequest>,
|
|
75
|
+
o?: StepOptions,
|
|
76
|
+
) => RoutineDefinitionStep,
|
|
77
|
+
},
|
|
78
|
+
sandboxes: {
|
|
79
|
+
/** `sandboxes/exec@1`: `with` is the exec body plus the sandbox (`sandbox_id`). */
|
|
80
|
+
exec: callStep("sandboxes/exec@1") as (
|
|
81
|
+
id: string,
|
|
82
|
+
w: Templated<ExecRequest & { sandbox_id: string }>,
|
|
83
|
+
o?: StepOptions,
|
|
84
|
+
) => RoutineDefinitionStep,
|
|
85
|
+
},
|
|
86
|
+
infer: {
|
|
87
|
+
chat: callStep("infer/chat@1") as (
|
|
88
|
+
id: string,
|
|
89
|
+
w: Templated<ChatCompletionRequest>,
|
|
90
|
+
o?: StepOptions,
|
|
91
|
+
) => RoutineDefinitionStep,
|
|
92
|
+
},
|
|
93
|
+
core: {
|
|
94
|
+
http: callStep("core/http@1") as (
|
|
95
|
+
id: string,
|
|
96
|
+
w: Templated<RoutineDefinitionCoreHttpWith>,
|
|
97
|
+
o?: StepOptions,
|
|
98
|
+
) => RoutineDefinitionStep,
|
|
99
|
+
transform: (id: string, value: unknown, o: StepOptions = {}): RoutineDefinitionStep => ({
|
|
100
|
+
id,
|
|
101
|
+
uses: "core/transform@1",
|
|
102
|
+
with: { value },
|
|
103
|
+
...o,
|
|
104
|
+
}),
|
|
105
|
+
log: callStep("core/log@1") as (
|
|
106
|
+
id: string,
|
|
107
|
+
w: Templated<RoutineDefinitionCoreLogWith>,
|
|
108
|
+
o?: StepOptions,
|
|
109
|
+
) => RoutineDefinitionStep,
|
|
110
|
+
/** Waits for a signal (`routine signal`), until a time, or for a duration. */
|
|
111
|
+
wait: (
|
|
112
|
+
id: string,
|
|
113
|
+
wait: NonNullable<RoutineDefinitionStep["wait"]>,
|
|
114
|
+
o: StepOptions = {},
|
|
115
|
+
): RoutineDefinitionStep => ({
|
|
116
|
+
id,
|
|
117
|
+
wait,
|
|
118
|
+
...o,
|
|
119
|
+
}),
|
|
120
|
+
sleep: (id: string, ms: number | string, o: StepOptions = {}): RoutineDefinitionStep => ({
|
|
121
|
+
id,
|
|
122
|
+
sleep_ms: ms,
|
|
123
|
+
...o,
|
|
124
|
+
}),
|
|
125
|
+
},
|
|
126
|
+
/** A marketplace action: `io.b3os/github/create-issue@1.2.0` with its input. */
|
|
127
|
+
action: (id: string, ref: string, input: Record<string, unknown>, o: StepOptions = {}): RoutineDefinitionStep => ({
|
|
128
|
+
id,
|
|
129
|
+
uses: ref,
|
|
130
|
+
with: input,
|
|
131
|
+
...o,
|
|
132
|
+
}),
|
|
133
|
+
/** Another routine (`routine/<id>@<version>`). */
|
|
134
|
+
routine: (id: string, ref: string, input: Record<string, unknown>, o: StepOptions = {}): RoutineDefinitionStep => ({
|
|
135
|
+
id,
|
|
136
|
+
uses: ref.startsWith("routine/") ? ref : `routine/${ref}`,
|
|
137
|
+
with: input,
|
|
138
|
+
...o,
|
|
139
|
+
}),
|
|
140
|
+
/** Runs `steps` once per item of `over` (a CEL list), `concurrency` at a time. */
|
|
141
|
+
map: (
|
|
142
|
+
id: string,
|
|
143
|
+
over: string,
|
|
144
|
+
steps: RoutineDefinitionStep[],
|
|
145
|
+
o: StepOptions & { concurrency?: number } = {},
|
|
146
|
+
): RoutineDefinitionStep => {
|
|
147
|
+
const { concurrency, ...rest } = o;
|
|
148
|
+
return { id, map: { over, steps, ...(concurrency !== undefined ? { concurrency } : {}) }, ...rest };
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/** A definition that does not pass the client-side checks; `problems` lists each as `<pointer>: <detail>`. */
|
|
153
|
+
export class RoutineDefinitionError extends Error {
|
|
154
|
+
readonly problems: string[];
|
|
155
|
+
constructor(problems: string[]) {
|
|
156
|
+
super(`invalid routine definition: ${problems.join("; ")}`);
|
|
157
|
+
this.name = "RoutineDefinitionError";
|
|
158
|
+
this.problems = problems;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// routine.schema.json's `name`, `$defs.ident` and `$defs.callable` (a test keeps these equal to the schema).
|
|
163
|
+
export const NAME_PATTERN = "^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$";
|
|
164
|
+
export const IDENT_PATTERN = "^[a-z_][a-z0-9_]{0,63}$";
|
|
165
|
+
const RESERVED = new Set(
|
|
166
|
+
"true false null in as break const continue else for function if import let loop package namespace return var void while".split(
|
|
167
|
+
" ",
|
|
168
|
+
),
|
|
169
|
+
);
|
|
170
|
+
export const CALLABLE_PATTERNS = [
|
|
171
|
+
"^(vision|render|sandboxes|infer)/[a-z][a-z0-9_-]{0,63}@[1-9][0-9]{0,3}$",
|
|
172
|
+
"^core/[a-z][a-z0-9_-]{0,63}@[1-9][0-9]{0,3}$",
|
|
173
|
+
"^routine/rtn_[0-9a-hjkmnp-tv-z]{26}@ver_[0-9a-hjkmnp-tv-z]{26}$",
|
|
174
|
+
"^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+/[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?/[a-z][a-z0-9]*(-[a-z0-9]+)*@((0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?|[1-9][0-9]*)$",
|
|
175
|
+
];
|
|
176
|
+
const IDENT = new RegExp(IDENT_PATTERN);
|
|
177
|
+
const CALLABLES = CALLABLE_PATTERNS.map((p) => new RegExp(p));
|
|
178
|
+
const isCallable = (s: string) => CALLABLES.some((r) => r.test(s)) && !/^core\/(map|wait|sleep)@/.test(s);
|
|
179
|
+
|
|
180
|
+
function strings(v: unknown, at: string, out: Array<[string, string]>): void {
|
|
181
|
+
if (typeof v === "string") out.push([at, v]);
|
|
182
|
+
else if (Array.isArray(v)) v.forEach((x, i) => strings(x, `${at}/${i}`, out));
|
|
183
|
+
else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) strings(x, `${at}/${k}`, out);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function checkSteps(steps: RoutineDefinitionStep[], at: string, problems: string[]): void {
|
|
187
|
+
const ids = new Set<string>();
|
|
188
|
+
steps.forEach((s, i) => {
|
|
189
|
+
const p = `${at}/${i}`;
|
|
190
|
+
if (!IDENT.test(s.id) || RESERVED.has(s.id))
|
|
191
|
+
problems.push(`${p}/id: ${JSON.stringify(s.id)} is not a step id (a CEL identifier: [a-z_][a-z0-9_]*)`);
|
|
192
|
+
if (ids.has(s.id)) problems.push(`${p}/id: duplicate step id ${s.id}`);
|
|
193
|
+
ids.add(s.id);
|
|
194
|
+
const kinds = [s.uses !== undefined, s.map !== undefined, s.wait !== undefined, s.sleep_ms !== undefined].filter(
|
|
195
|
+
Boolean,
|
|
196
|
+
);
|
|
197
|
+
if (kinds.length !== 1) problems.push(`${p}: a step has exactly one of uses, map, wait, sleep_ms`);
|
|
198
|
+
if (s.uses !== undefined && !isCallable(s.uses)) problems.push(`${p}/uses: ${s.uses} is not <ref>@<version>`);
|
|
199
|
+
if (s.map) checkSteps(s.map.steps, `${p}/map/steps`, problems);
|
|
200
|
+
});
|
|
201
|
+
steps.forEach((s, i) => {
|
|
202
|
+
for (const n of s.needs ?? []) {
|
|
203
|
+
if (!ids.has(n)) problems.push(`${at}/${i}/needs: no step ${n} in this scope`);
|
|
204
|
+
if (n === s.id) problems.push(`${at}/${i}/needs: a step cannot need itself`);
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The offset of the first `${{` that is never closed, or -1. Scans as the node does (crates/b3os-routines
|
|
211
|
+
* src/cel/template.rs): an expression runs to the first `}}` at brace depth 0 outside a CEL string literal (quoted
|
|
212
|
+
* with ', ", three ' or three ", with backslash escapes); a `}}` outside any `${{` is literal text.
|
|
213
|
+
*/
|
|
214
|
+
export function unterminatedTemplate(s: string): number {
|
|
215
|
+
let i = 0;
|
|
216
|
+
while (i < s.length) {
|
|
217
|
+
if (s.startsWith("${{", i)) {
|
|
218
|
+
const end = expressionEnd(s, i + 3);
|
|
219
|
+
if (end < 0) return i;
|
|
220
|
+
i = end + 2;
|
|
221
|
+
} else i += 1;
|
|
222
|
+
}
|
|
223
|
+
return -1;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function expressionEnd(s: string, from: number): number {
|
|
227
|
+
let j = from;
|
|
228
|
+
let depth = 0;
|
|
229
|
+
let quote: string | undefined;
|
|
230
|
+
while (j < s.length) {
|
|
231
|
+
if (quote !== undefined) {
|
|
232
|
+
if (s[j] === "\\") j += 2;
|
|
233
|
+
else if (s.startsWith(quote, j)) {
|
|
234
|
+
j += quote.length;
|
|
235
|
+
quote = undefined;
|
|
236
|
+
} else j += 1;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (s.startsWith("'''", j) || s.startsWith('"""', j)) {
|
|
240
|
+
quote = s.slice(j, j + 3);
|
|
241
|
+
j += 3;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
const c = s[j];
|
|
245
|
+
if (c === "'" || c === '"') {
|
|
246
|
+
quote = c;
|
|
247
|
+
j += 1;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (c === "{") depth += 1;
|
|
251
|
+
else if (c === "}") {
|
|
252
|
+
if (depth === 0 && s[j + 1] === "}") return j;
|
|
253
|
+
depth -= 1;
|
|
254
|
+
}
|
|
255
|
+
j += 1;
|
|
256
|
+
}
|
|
257
|
+
return -1;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Checks a routine definition client-side and returns it unchanged (typed for publishRoutine). */
|
|
261
|
+
export function defineRoutine(def: RoutineDefinition): RoutineDefinition {
|
|
262
|
+
const problems: string[] = [];
|
|
263
|
+
if (!new RegExp(NAME_PATTERN).test(def.name))
|
|
264
|
+
problems.push(`/name: ${JSON.stringify(def.name)} is not a routine name`);
|
|
265
|
+
if (!def.steps?.length) problems.push("/steps: a routine needs at least one step");
|
|
266
|
+
else checkSteps(def.steps, "/steps", problems);
|
|
267
|
+
const texts: Array<[string, string]> = [];
|
|
268
|
+
strings(def, "", texts);
|
|
269
|
+
for (const [at, t] of texts) {
|
|
270
|
+
const open = unterminatedTemplate(t);
|
|
271
|
+
if (open >= 0)
|
|
272
|
+
problems.push(
|
|
273
|
+
`${at}: unbalanced \${{ }}: the \${{ at offset ${open} is never closed in ${JSON.stringify(t.slice(0, 60))}`,
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
if (problems.length) throw new RoutineDefinitionError(problems);
|
|
277
|
+
return def;
|
|
278
|
+
}
|