@orgsdk/executor 0.1.0 → 0.2.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.
@@ -0,0 +1,57 @@
1
+ // src/mcp/contract.ts
2
+ import { z } from "zod";
3
+ var jsonObject = z.record(z.string(), z.json());
4
+ var endpointSchema = z.string().url().max(2e3).refine((value) => {
5
+ const url = new URL(value);
6
+ return ["https:", "http:"].includes(url.protocol) && !url.username && !url.password && !url.hash;
7
+ }, "Use an HTTP(S) URL without embedded credentials or a fragment");
8
+ var transportSchema = z.enum(["auto", "streamable-http", "sse"]);
9
+ var remoteToolSchema = z.object({
10
+ name: z.string().min(1).max(256),
11
+ description: z.string().max(1e4).optional(),
12
+ inputSchema: jsonObject,
13
+ outputSchema: jsonObject.optional(),
14
+ annotations: jsonObject.optional()
15
+ }).strip();
16
+ var approvedToolSchema = remoteToolSchema.extend({
17
+ alias: z.string().regex(/^[a-z][a-zA-Z0-9]*$/).max(100)
18
+ });
19
+ var connectionSchema = z.object({
20
+ id: z.string().uuid(),
21
+ endpoint: endpointSchema,
22
+ transport: transportSchema,
23
+ revision: z.number().int().nonnegative(),
24
+ tools: z.array(approvedToolSchema).max(1e3)
25
+ });
26
+ var discoverySchema = z.object({
27
+ tools: z.array(remoteToolSchema).max(1e3),
28
+ transport: z.enum(["streamable-http", "sse"]),
29
+ authRequired: z.boolean().default(false),
30
+ resourceMetadata: jsonObject.optional()
31
+ });
32
+ var headerSchema = z.record(
33
+ z.string().regex(/^[!#$%&'*+.^_`|~0-9a-z-]+$/i),
34
+ z.string().max(8e3).refine((value) => !/[\r\n]/.test(value))
35
+ ).refine(
36
+ (headers) => Object.keys(headers).length <= 20 && Object.keys(headers).every(
37
+ (name) => ![
38
+ "host",
39
+ "connection",
40
+ "content-length",
41
+ "content-type",
42
+ "accept",
43
+ "mcp-session-id",
44
+ "mcp-protocol-version"
45
+ ].includes(name.toLowerCase())
46
+ ),
47
+ "Unsupported authentication header"
48
+ );
49
+ export {
50
+ approvedToolSchema,
51
+ connectionSchema,
52
+ discoverySchema,
53
+ endpointSchema,
54
+ headerSchema,
55
+ remoteToolSchema,
56
+ transportSchema
57
+ };
@@ -0,0 +1,40 @@
1
+ // src/mcp/functions.ts
2
+ import { z } from "zod";
3
+ import { McpRuntime } from "./client.js";
4
+ import { connectionSchema, headerSchema } from "./contract.js";
5
+ var executionSecretSchema = z.object({
6
+ headers: z.unknown(),
7
+ expires_at: z.number().optional()
8
+ });
9
+ function mcpPlugin(plugin, client, signal) {
10
+ const connection = connectionSchema.parse(plugin.mcp);
11
+ let cached;
12
+ const runtime = new McpRuntime(
13
+ connection,
14
+ async () => {
15
+ if (!plugin.credential_id) return {};
16
+ if (cached && cached.expiresAt > Date.now() + 6e4)
17
+ return cached.headers;
18
+ const secret = executionSecretSchema.parse(
19
+ await client.secret(plugin.credential_id)
20
+ );
21
+ cached = {
22
+ headers: headerSchema.parse(secret.headers),
23
+ expiresAt: secret.expires_at ?? Number.POSITIVE_INFINITY
24
+ };
25
+ return cached.headers;
26
+ },
27
+ signal
28
+ );
29
+ const functions = connection.tools.map((tool) => ({
30
+ name: tool.alias,
31
+ category: plugin.slug,
32
+ calling: "named",
33
+ description: tool.description ?? "",
34
+ handler: (args) => runtime.call(tool.alias, args)
35
+ }));
36
+ return { runtime, functions };
37
+ }
38
+ export {
39
+ mcpPlugin
40
+ };
@@ -0,0 +1,61 @@
1
+ // src/mcp/network.ts
2
+ import { endpointSchema } from "./contract.js";
3
+ function endpointFetch(endpoint, signal, headers = {}, limit = 1e6) {
4
+ const origin = new URL(endpointSchema.parse(endpoint)).origin;
5
+ return async (input, init) => {
6
+ const request = new Request(input, init);
7
+ const url = new URL(request.url);
8
+ if (url.origin !== origin)
9
+ throw new Error(
10
+ "MCP request changed origin; configure the destination explicitly"
11
+ );
12
+ const authenticated = new Headers(request.headers);
13
+ for (const [name, value] of Object.entries(headers))
14
+ authenticated.set(name, value);
15
+ const response = await fetch(request, {
16
+ headers: authenticated,
17
+ redirect: "error",
18
+ signal: AbortSignal.any([signal, request.signal])
19
+ });
20
+ if (!response.body) return response;
21
+ let bytes = 0;
22
+ const body = response.body.pipeThrough(
23
+ new TransformStream({
24
+ transform(chunk, controller) {
25
+ bytes += chunk.byteLength;
26
+ if (bytes > limit)
27
+ throw new Error("MCP response exceeds the supported size");
28
+ controller.enqueue(chunk);
29
+ }
30
+ })
31
+ );
32
+ return new Response(body, {
33
+ status: response.status,
34
+ statusText: response.statusText,
35
+ headers: response.headers
36
+ });
37
+ };
38
+ }
39
+ function redactMcp(value, headers) {
40
+ const secrets = Object.values(headers).flatMap((header) => [header, header.replace(/^Bearer /i, "")]).filter(Boolean);
41
+ const text = (input) => secrets.reduce(
42
+ (result, secret) => result.split(secret).join("[REDACTED]"),
43
+ input
44
+ );
45
+ const visit = (input) => {
46
+ if (typeof input === "string") return text(input);
47
+ if (typeof input === "number" && secrets.includes(String(input)))
48
+ return "[REDACTED]";
49
+ if (Array.isArray(input)) return input.map(visit);
50
+ if (input !== null && typeof input === "object")
51
+ return Object.fromEntries(
52
+ Object.entries(input).map(([key, item]) => [text(key), visit(item)])
53
+ );
54
+ return input;
55
+ };
56
+ return visit(value);
57
+ }
58
+ export {
59
+ endpointFetch,
60
+ redactMcp
61
+ };
@@ -0,0 +1,35 @@
1
+ // src/mcp/schema-types.ts
2
+ function schemaType(value, depth = 0) {
3
+ if (depth > 8 || !value || typeof value !== "object" || Array.isArray(value))
4
+ return "unknown";
5
+ const schema = value;
6
+ if (schema.$ref || schema.allOf || schema.not || schema.if) return "unknown";
7
+ if (Array.isArray(schema.enum) && schema.enum.length <= 50)
8
+ return schema.enum.map(
9
+ (item) => typeof item === "string" || typeof item === "boolean" || typeof item === "number" || item === null ? JSON.stringify(item) : "unknown"
10
+ ).join(" | ") || "never";
11
+ const variants = schema.anyOf ?? schema.oneOf;
12
+ if (Array.isArray(variants))
13
+ return variants.length > 30 ? "unknown" : variants.map((item) => schemaType(item, depth + 1)).join(" | ") || "unknown";
14
+ if (Array.isArray(schema.type))
15
+ return schema.type.map((type) => schemaType({ ...schema, type }, depth + 1)).join(" | ");
16
+ if (["string", "boolean", "number", "null"].includes(String(schema.type)))
17
+ return String(schema.type);
18
+ if (schema.type === "integer") return "number";
19
+ if (schema.type === "array")
20
+ return `Array<${schemaType(schema.items, depth + 1)}>`;
21
+ if (schema.type === "object" || schema.properties) {
22
+ if (!schema.properties || typeof schema.properties !== "object" || Array.isArray(schema.properties))
23
+ return "Record<string, unknown>";
24
+ const required = new Set(
25
+ Array.isArray(schema.required) ? schema.required : []
26
+ );
27
+ const properties = Object.entries(schema.properties);
28
+ if (properties.length > 100) return "Record<string, unknown>";
29
+ return `{${properties.map(([key, child]) => `${JSON.stringify(key)}${required.has(key) ? "" : "?"}: ${schemaType(child, depth + 1)}`).join("; ")}${schema.additionalProperties === false ? "" : "; [key: string]: unknown"}}`;
30
+ }
31
+ return "unknown";
32
+ }
33
+ export {
34
+ schemaType
35
+ };
@@ -0,0 +1,18 @@
1
+ // src/mcp/transport.ts
2
+ import {
3
+ StreamableHTTPClientTransport,
4
+ SSEClientTransport
5
+ } from "@modelcontextprotocol/client";
6
+ var httpTransport = (endpoint, kind, fetcher) => kind === "sse" ? new SSEClientTransport(new URL(endpoint), { fetch: fetcher }) : new StreamableHTTPClientTransport(new URL(endpoint), {
7
+ fetch: fetcher,
8
+ reconnectionOptions: {
9
+ maxRetries: 0,
10
+ initialReconnectionDelay: 1e3,
11
+ maxReconnectionDelay: 1e3,
12
+ reconnectionDelayGrowFactor: 1
13
+ },
14
+ onInsufficientScope: "throw"
15
+ });
16
+ export {
17
+ httpTransport
18
+ };
@@ -28,7 +28,7 @@ function validJsonText(value) {
28
28
  function projectDataFunctions(client, signal) {
29
29
  const call = (operation, params) => {
30
30
  signal.throwIfAborted();
31
- return client.product("project-data/", "POST", { operation, ...params });
31
+ return client.projectData(operation, params);
32
32
  };
33
33
  const page = (start, count) => ({
34
34
  offset: offset.parse(start),
@@ -0,0 +1,23 @@
1
+ // src/register-executor.ts
2
+ var capabilities = ["action", "code", "validate", "test", "mcp_discover"];
3
+ var unsupported = 'API 400: {"detail":"Unsupported executor protocol or capability."}';
4
+ async function registerExecutor(client, agentId) {
5
+ const registration = {
6
+ protocol_version: 4,
7
+ agent_id: agentId
8
+ };
9
+ try {
10
+ return await client.register({
11
+ ...registration,
12
+ capabilities: [...capabilities, "session"]
13
+ });
14
+ } catch (error) {
15
+ if (!(error instanceof Error) || error.message !== unsupported) {
16
+ throw error;
17
+ }
18
+ return client.register({ ...registration, capabilities });
19
+ }
20
+ }
21
+ export {
22
+ registerExecutor
23
+ };
package/dist/runner.js CHANGED
@@ -7,6 +7,7 @@ import { projectFileFunctions } from "./project-files.js";
7
7
  import { z } from "zod";
8
8
  import { SandboxExecutor } from "./engine/sandbox/executor.js";
9
9
  import { loadPlugins } from "./plugins.js";
10
+ import { mcpPlugin } from "./mcp/functions.js";
10
11
  import {
11
12
  TRACE_LIMIT,
12
13
  TRACE_QUEUE_BYTES,
@@ -30,18 +31,18 @@ var Runner = class {
30
31
  events = Promise.resolve();
31
32
  async event(kind, data) {
32
33
  const pending = this.events.then(
33
- () => this.client.request(
34
- `/internal/execution/v1/runs/${this.job.run_id}/events/`,
35
- "POST",
36
- { sequence: ++this.sequence, kind, data }
37
- )
34
+ () => this.client.publishEvent(this.job.run_id, {
35
+ sequence: ++this.sequence,
36
+ kind,
37
+ data
38
+ })
38
39
  ).then(() => void 0);
39
40
  this.events = pending.catch(() => void 0);
40
41
  return pending;
41
42
  }
42
43
  async approval(prompt) {
43
44
  let approval = approvalSchema.parse(
44
- await this.client.product("approvals/", "POST", {
45
+ await this.client.createApproval({
45
46
  run: this.job.run_id,
46
47
  prompt
47
48
  })
@@ -53,15 +54,13 @@ var Runner = class {
53
54
  while (approval.status === "pending") {
54
55
  this.signal.throwIfAborted();
55
56
  await sleep(1e3);
56
- approval = approvalSchema.parse(
57
- await this.client.product(`approvals/${approval.id}/`)
58
- );
57
+ approval = approvalSchema.parse(await this.client.approval(approval.id));
59
58
  }
60
59
  if (approval.status !== "approved")
61
60
  throw new Error("Approval denied or interrupted");
62
61
  return true;
63
62
  }
64
- builtins(agent) {
63
+ builtins() {
65
64
  let fileFunctions;
66
65
  const files = ["readFile", "writeFile", "listFiles", "removeFile"].map(
67
66
  (name) => ({
@@ -91,23 +90,12 @@ var Runner = class {
91
90
  {
92
91
  name: "saveArtifact",
93
92
  calling: "positional",
94
- handler: (name, content) => this.client.product("artifacts/", "POST", {
93
+ handler: (name, content) => this.client.saveArtifact({
95
94
  run: this.job.run_id,
96
95
  name: z.string().parse(name),
97
96
  content: z.string().parse(content)
98
97
  })
99
98
  },
100
- ...agent.resources === void 0 && this.job.operation !== "code" ? [
101
- {
102
- name: "saveMemory",
103
- calling: "positional",
104
- handler: (title, content) => this.client.product("documents/", "POST", {
105
- kind: "memory",
106
- title: z.string().parse(title),
107
- content: z.string().parse(content)
108
- })
109
- }
110
- ] : [],
111
99
  {
112
100
  name: "delegate",
113
101
  calling: "positional",
@@ -134,10 +122,16 @@ var Runner = class {
134
122
  );
135
123
  }
136
124
  const executor = new SandboxExecutor();
137
- executor.registerBuiltins(this.builtins(agent));
125
+ executor.registerBuiltins(this.builtins());
126
+ const remote = agent.plugins.filter((plugin) => plugin.distribution === "mcp").map((plugin) => mcpPlugin(plugin, this.client, this.signal));
138
127
  executor.registerMultiple(
139
- await loadPlugins(agent.plugins, this.client, agent.id)
128
+ await loadPlugins(
129
+ agent.plugins.filter((plugin) => plugin.distribution !== "mcp"),
130
+ this.client,
131
+ agent.id
132
+ )
140
133
  );
134
+ executor.registerMultiple(remote.flatMap((entry) => entry.functions));
141
135
  let pending = Promise.resolve();
142
136
  let eventCount = 0;
143
137
  let eventBytes = 0;
@@ -192,6 +186,7 @@ var Runner = class {
192
186
  const output = result.result ?? null;
193
187
  return output;
194
188
  } finally {
189
+ await Promise.all(remote.map((entry) => entry.runtime.close()));
195
190
  let timer;
196
191
  let onAbort;
197
192
  try {
@@ -221,6 +216,17 @@ var Runner = class {
221
216
  "Unsupported operation: built-in chat has been retired; use external-client code or actions"
222
217
  );
223
218
  const agent = this.agent(this.job.snapshot.root_agent_id);
219
+ if (this.job.operation === "mcp_discover") {
220
+ const plugin = agent.plugins[0];
221
+ if (this.job.protocol_version !== 4 || !plugin || agent.plugins.length !== 1 || plugin.distribution !== "mcp" || !this.job.snapshot.mcp_discovery)
222
+ throw new Error("Invalid MCP discovery job");
223
+ const remote = mcpPlugin(plugin, this.client, this.signal);
224
+ try {
225
+ return await remote.runtime.discover();
226
+ } finally {
227
+ await remote.runtime.close();
228
+ }
229
+ }
224
230
  return this.action(
225
231
  agent,
226
232
  z.string().parse(this.job.snapshot.source),
@@ -1,5 +1,6 @@
1
1
  // src/sdk-declarations.ts
2
2
  import ts from "typescript";
3
+ import { schemaType } from "./mcp/schema-types.js";
3
4
  import {
4
5
  RESERVED_NAMESPACE_IDENTIFIERS,
5
6
  RESERVED_FUNCTION_KEYS
@@ -129,7 +130,7 @@ function pluginDeclaration(plugin) {
129
130
  if (plugin.available !== true || !safeIdentifier(namespace) || RESERVED_NAMESPACE_IDENTIFIERS.has(namespace) || builtinNames.has(namespace))
130
131
  return;
131
132
  const fallback = `const ${namespace}: Readonly<Record<string, (...args: unknown[]) => Promise<unknown>>>;`;
132
- if (plugin.metadata_complete !== true || !Array.isArray(plugin.tools) || plugin.tools.length > 100)
133
+ if (plugin.metadata_complete !== true || !Array.isArray(plugin.tools) || plugin.tools.length > 1e3)
133
134
  return fallback;
134
135
  const names = /* @__PURE__ */ new Set();
135
136
  const methods = [];
@@ -138,6 +139,12 @@ function pluginDeclaration(plugin) {
138
139
  if (!tool || !safeIdentifier(tool.name) || names.has(tool.name) || !Array.isArray(tool.parameters) || tool.parameters.length > 30)
139
140
  return fallback;
140
141
  names.add(tool.name);
142
+ if (plugin.kind === "mcp" && tool.inputSchema) {
143
+ methods.push(
144
+ `${tool.name}(args: ${schemaType(tool.inputSchema)}): Promise<{content?: Array<unknown>; structuredContent?: ${schemaType(tool.outputSchema)}; [key: string]: unknown}>`
145
+ );
146
+ continue;
147
+ }
141
148
  const isNamed = tool.calling === "named";
142
149
  const parameters = [];
143
150
  const parameterNames = /* @__PURE__ */ new Set();
@@ -0,0 +1,29 @@
1
+ // src/session-job-contract.ts
2
+ import { z } from "zod";
3
+ var sessionScopeSchema = z.object({
4
+ workspaceId: z.string().min(1).max(256),
5
+ projectId: z.uuid(),
6
+ ownerId: z.string().min(1).max(256)
7
+ });
8
+ var sessionCommandSchema = z.discriminatedUnion("operation", [
9
+ z.strictObject({ operation: z.literal("open") }),
10
+ z.strictObject({
11
+ operation: z.literal("execute"),
12
+ id: z.uuid(),
13
+ cellId: z.uuid(),
14
+ generation: z.number().int().positive(),
15
+ expectedSequence: z.number().int().nonnegative(),
16
+ after: z.number().int().nonnegative().optional()
17
+ }),
18
+ z.strictObject({ operation: z.literal("close"), id: z.uuid() }),
19
+ z.strictObject({
20
+ operation: z.literal("read"),
21
+ id: z.uuid(),
22
+ after: z.number().int().nonnegative().optional(),
23
+ limit: z.number().int().positive().max(10).optional()
24
+ })
25
+ ]);
26
+ export {
27
+ sessionCommandSchema,
28
+ sessionScopeSchema
29
+ };
@@ -0,0 +1,256 @@
1
+ // src/session-job.ts
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { Client } from "./client.js";
5
+ import { withRetry } from "./engine/retry.js";
6
+ import { SessionManager } from "./sessions/index.js";
7
+ import { MAX_VALUE_BYTES } from "./sessions/values.js";
8
+ import { spawnJob } from "./spawn-job.js";
9
+ var sdkPluginSchema = z.object({
10
+ slug: z.string(),
11
+ available: z.literal(true),
12
+ namespace: z.string(),
13
+ tools: z.array(z.object({ name: z.string(), calling: z.literal("named") }))
14
+ });
15
+ var sdkSchema = z.object({ plugins: z.array(z.unknown()) });
16
+ var heartbeatSchema = z.object({
17
+ cancel_requested: z.boolean(),
18
+ status: z.string()
19
+ });
20
+ var toolOutputSchema = z.object({ result: z.json() });
21
+ var agentVolume = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/);
22
+ var SessionJobs = class {
23
+ constructor(options) {
24
+ this.options = options;
25
+ const { agentId, directory, mode } = options;
26
+ const volume = mode === "docker" && process.env.EXECUTOR_DATA_BIND !== "1" ? {
27
+ name: agentVolume.parse(process.env.EXECUTOR_DATA_VOLUME),
28
+ subpath: `agents/${agentId}/workspace`
29
+ } : void 0;
30
+ this.manager = new SessionManager({
31
+ mode,
32
+ historyDirectory: join(directory, "..", "..", "session-history", agentId),
33
+ image: process.env.EXECUTOR_IMAGE,
34
+ sourceDirectory: process.env.EXECUTOR_SOURCE_DIR,
35
+ workspaceVolume: volume
36
+ });
37
+ }
38
+ options;
39
+ manager;
40
+ authority;
41
+ activePluginCalls = 0;
42
+ functions(job) {
43
+ const plugins = job.snapshot.agents.find((entry) => entry.id === this.options.agentId)?.plugins ?? [];
44
+ const sdk = sdkSchema.parse(job.snapshot.sdk);
45
+ return sdk.plugins.flatMap((entry) => {
46
+ const parsed = sdkPluginSchema.safeParse(entry);
47
+ if (!parsed.success) return [];
48
+ const metadata = parsed.data;
49
+ const plugin = plugins.find((item) => item.slug === metadata.slug);
50
+ if (plugin?.distribution !== "mcp" && plugin?.distribution !== "external") {
51
+ return [];
52
+ }
53
+ return metadata.tools.map((tool) => ({
54
+ name: `${metadata.namespace}.${tool.name}`,
55
+ handler: (args, context) => {
56
+ if (!context.capability)
57
+ throw new Error("Missing active cell authority");
58
+ return this.pluginCall(
59
+ plugin,
60
+ tool.name,
61
+ args,
62
+ context.capability,
63
+ context.signal
64
+ );
65
+ }
66
+ }));
67
+ });
68
+ }
69
+ async pluginCall(plugin, name, args, capability, signal) {
70
+ const authority = this.authority;
71
+ if (authority?.job.capability !== capability) {
72
+ throw new Error("Missing active cell authority");
73
+ }
74
+ if (this.activePluginCalls >= 4) {
75
+ throw new Error(
76
+ "At most four plugin calls may run concurrently in a cell"
77
+ );
78
+ }
79
+ this.activePluginCalls++;
80
+ try {
81
+ await authority.check();
82
+ signal.throwIfAborted();
83
+ return await this.invokePlugin(plugin, name, args, capability, signal);
84
+ } finally {
85
+ this.activePluginCalls--;
86
+ }
87
+ }
88
+ async invokePlugin(plugin, name, args, capability, signal) {
89
+ if (args.length > 1) {
90
+ throw new Error(
91
+ "Plugin functions accept a single named arguments object"
92
+ );
93
+ }
94
+ const input = z.record(z.string(), z.json()).parse(args.length ? args[0] : {});
95
+ const { child, kill } = spawnJob(
96
+ { ...this.options, name: `orgsdk-session-tool-${crypto.randomUUID()}` },
97
+ "pipe"
98
+ );
99
+ signal.addEventListener("abort", kill, { once: true });
100
+ const exited = child.exited.catch(() => 1);
101
+ try {
102
+ child.stdin.end(
103
+ JSON.stringify({
104
+ type: "session_plugin_call",
105
+ agentId: this.options.agentId,
106
+ capability,
107
+ plugin,
108
+ name,
109
+ args: input
110
+ })
111
+ );
112
+ const chunks = [];
113
+ let bytes = 0;
114
+ for await (const chunk of child.stdout) {
115
+ const buffer = Buffer.from(chunk);
116
+ bytes += buffer.length;
117
+ if (bytes > MAX_VALUE_BYTES + 1024) {
118
+ throw new Error("Plugin function output exceeds session limit");
119
+ }
120
+ chunks.push(buffer);
121
+ }
122
+ const code = await exited;
123
+ signal.throwIfAborted();
124
+ if (code !== 0)
125
+ throw new Error(`Plugin function ${plugin.slug}.${name} failed`);
126
+ const output = Buffer.concat(chunks).toString("utf8").trim();
127
+ return toolOutputSchema.parse(JSON.parse(output.split("\n").at(-1) ?? "")).result;
128
+ } finally {
129
+ signal.removeEventListener("abort", kill);
130
+ kill();
131
+ await exited;
132
+ }
133
+ }
134
+ summary(history) {
135
+ return {
136
+ id: history.id,
137
+ generation: history.generation,
138
+ status: history.status,
139
+ cursor: history.cursor,
140
+ sequence: history.cells.length,
141
+ worker: history.worker
142
+ };
143
+ }
144
+ async execute(job, signal) {
145
+ const { session: command, session_scope: scope } = job.snapshot;
146
+ if (!command || !scope) throw new Error("Invalid session command");
147
+ const workspaceDirectory = join(this.options.directory, "workspace");
148
+ const revision = z.string().min(1).parse(job.snapshot.configuration_revision);
149
+ signal.throwIfAborted();
150
+ switch (command.operation) {
151
+ case "open": {
152
+ const history = await this.manager.open({
153
+ ...scope,
154
+ workspaceDirectory,
155
+ configurationRevision: revision,
156
+ functions: this.functions(job)
157
+ });
158
+ if (signal.aborted) {
159
+ await this.manager.close(history.id, scope);
160
+ signal.throwIfAborted();
161
+ }
162
+ return this.summary(history);
163
+ }
164
+ case "execute": {
165
+ const reply = await this.manager.execute(command.id, scope, {
166
+ id: command.cellId,
167
+ generation: command.generation,
168
+ expectedSequence: command.expectedSequence,
169
+ after: command.after,
170
+ source: z.string().parse(job.snapshot.source),
171
+ inputs: job.inputs,
172
+ capability: job.capability,
173
+ configurationRevision: revision,
174
+ signal,
175
+ limit: 10,
176
+ timeoutMs: Math.max(
177
+ 1,
178
+ Math.min(3e5, Date.parse(job.deadline) - Date.now())
179
+ )
180
+ });
181
+ const { cell, ...page } = reply;
182
+ const { source: _source, inputs: _inputs, ...result } = cell;
183
+ return { ...page, cell: result };
184
+ }
185
+ case "read": {
186
+ const history = await this.manager.inspect(command.id, scope);
187
+ const page = await this.manager.readEvents(command.id, scope, {
188
+ after: command.after,
189
+ limit: command.limit ?? 10
190
+ });
191
+ return { ...this.summary(history), ...page };
192
+ }
193
+ case "close":
194
+ return this.summary(await this.manager.close(command.id, scope));
195
+ }
196
+ }
197
+ async run(job, parentSignal) {
198
+ const controller = new AbortController();
199
+ const signal = AbortSignal.any([parentSignal, controller.signal]);
200
+ const client = new Client(this.options.base, job.capability, parentSignal);
201
+ const check = async () => {
202
+ try {
203
+ const state = heartbeatSchema.parse(await client.heartbeat(job.run_id));
204
+ if (state.cancel_requested || state.status !== "running")
205
+ controller.abort();
206
+ } catch {
207
+ controller.abort();
208
+ }
209
+ };
210
+ const timer = setInterval(() => void check(), 5e3);
211
+ const deadline = setTimeout(
212
+ () => controller.abort(),
213
+ Math.max(0, Date.parse(job.deadline) - Date.now())
214
+ );
215
+ this.authority = { job, check };
216
+ try {
217
+ let completion;
218
+ try {
219
+ await check();
220
+ const output = await this.execute(job, signal);
221
+ signal.throwIfAborted();
222
+ completion = { status: "succeeded", output: { result: output } };
223
+ } catch (error) {
224
+ completion = {
225
+ status: signal.aborted ? "cancelled" : "failed",
226
+ error: error instanceof Error ? error.message : "Session operation failed"
227
+ };
228
+ }
229
+ await withRetry(
230
+ () => client.complete(job.run_id, completion),
231
+ {
232
+ maxRetries: 2,
233
+ initialDelayMs: 200,
234
+ shouldRetry: (error) => !parentSignal.aborted && !/^API 4(?!29)\d\d:/.test(error.message)
235
+ }
236
+ );
237
+ } catch (error) {
238
+ if (!parentSignal.aborted) {
239
+ console.error(
240
+ `Session run ${job.run_id} completion was not acknowledged:`,
241
+ error instanceof Error ? error.message : "Unknown transport error"
242
+ );
243
+ }
244
+ } finally {
245
+ this.authority = void 0;
246
+ clearTimeout(deadline);
247
+ clearInterval(timer);
248
+ }
249
+ }
250
+ dispose() {
251
+ return this.manager.dispose();
252
+ }
253
+ };
254
+ export {
255
+ SessionJobs
256
+ };