@saturn-universe/tools 0.0.0-stage → 0.1.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.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/container-sandbox.d.ts +168 -0
  3. package/dist/container-sandbox.js +1241 -0
  4. package/dist/counter.d.ts +5 -0
  5. package/dist/counter.js +82 -0
  6. package/dist/data-review.d.ts +4 -0
  7. package/dist/data-review.js +146 -0
  8. package/dist/execution-backend.d.ts +55 -0
  9. package/dist/execution-backend.js +339 -0
  10. package/dist/executor.d.ts +25 -0
  11. package/dist/executor.js +978 -0
  12. package/dist/file-window.d.ts +3 -0
  13. package/dist/file-window.js +12 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +17 -0
  16. package/dist/mcp-headers.d.ts +3 -0
  17. package/dist/mcp-headers.js +51 -0
  18. package/dist/mcp-http.d.ts +3 -0
  19. package/dist/mcp-http.js +253 -0
  20. package/dist/mcp-stdio.d.ts +2 -0
  21. package/dist/mcp-stdio.js +147 -0
  22. package/dist/mcp-wire.d.ts +33 -0
  23. package/dist/mcp-wire.js +85 -0
  24. package/dist/mcp.d.ts +19 -0
  25. package/dist/mcp.js +325 -0
  26. package/dist/path-containment.d.ts +3 -0
  27. package/dist/path-containment.js +11 -0
  28. package/dist/planner.d.ts +3 -0
  29. package/dist/planner.js +162 -0
  30. package/dist/process-manager.d.ts +67 -0
  31. package/dist/process-manager.js +423 -0
  32. package/dist/process-output.d.ts +34 -0
  33. package/dist/process-output.js +162 -0
  34. package/dist/process-worker.d.ts +1 -0
  35. package/dist/process-worker.js +202 -0
  36. package/dist/registry.d.ts +33 -0
  37. package/dist/registry.js +227 -0
  38. package/dist/search.d.ts +9 -0
  39. package/dist/search.js +96 -0
  40. package/dist/team.d.ts +36 -0
  41. package/dist/team.js +284 -0
  42. package/dist/text-patch.d.ts +15 -0
  43. package/dist/text-patch.js +81 -0
  44. package/dist/todo.d.ts +3 -0
  45. package/dist/todo.js +105 -0
  46. package/dist/workspace-discovery.d.ts +42 -0
  47. package/dist/workspace-discovery.js +404 -0
  48. package/dist/workspace-snapshot.d.ts +28 -0
  49. package/dist/workspace-snapshot.js +371 -0
  50. package/dist/workspace.d.ts +22 -0
  51. package/dist/workspace.js +1819 -0
  52. package/package.json +16 -3
  53. package/README.md +0 -3
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { ToolBinding } from '@saturn-universe/core';
2
+ export type McpServerConfig = ({
3
+ transport: 'stdio';
4
+ command: string;
5
+ args?: readonly string[];
6
+ env?: Readonly<Record<string, string>>;
7
+ } | {
8
+ transport: 'http';
9
+ url: string;
10
+ headers?: Readonly<Record<string, string>>;
11
+ }) & {
12
+ tools?: readonly string[];
13
+ readOnlyTools?: readonly string[];
14
+ timeoutMs?: number;
15
+ };
16
+ export declare function openMcpServer(serverId: string, config: McpServerConfig, workspaceRoot: string, signal?: AbortSignal): Promise<{
17
+ bindings: ToolBinding[];
18
+ close(): Promise<void>;
19
+ }>;
package/dist/mcp.js ADDED
@@ -0,0 +1,325 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalJson, RuntimeError } from '@saturn-universe/core';
3
+ import { httpTransport } from './mcp-http.js';
4
+ import { parameterHeaders } from './mcp-headers.js';
5
+ import { stdioTransport } from './mcp-stdio.js';
6
+ import { clientInfo, McpError, modernVersion, object } from './mcp-wire.js';
7
+ const legacyVersions = ['2025-11-25', '2025-06-18', '2025-03-26'];
8
+ const maxTools = 256;
9
+ const maxErrorMessageLength = 1000;
10
+ const explicitHttpRejections = new Set([400, 401, 403, 404, 409, 422, 429]);
11
+ const digest = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
12
+ function wireName(serverId, name) {
13
+ const simple = /^[a-z0-9-]+$/i;
14
+ const readable = 'mcp_' + serverId + '_' + name;
15
+ if (simple.test(serverId) && simple.test(name) && readable.length <= 64)
16
+ return readable;
17
+ return ('mcp_' + readable.slice(4, 39).replace(/[^a-z0-9-]/gi, '_') + '__' + digest([serverId, name]).slice(0, 22));
18
+ }
19
+ async function identify(transport, kind, signal, timeoutMs) {
20
+ let discovery;
21
+ const probe = AbortSignal.timeout(Math.max(1, Math.min(1500, Math.floor(timeoutMs / 2))));
22
+ try {
23
+ discovery = await transport.request('server/discover', {}, kind === 'stdio' ? AbortSignal.any([signal, probe]) : signal);
24
+ }
25
+ catch (error) {
26
+ signal.throwIfAborted();
27
+ if (error instanceof McpError && (error.kind === 'auth_required' || error.kind === 'forbidden'))
28
+ throw error;
29
+ const legacyError = error instanceof McpError &&
30
+ ![-32022, -32020].includes(error.rpcCode ?? 0) &&
31
+ (kind === 'stdio'
32
+ ? error.rpcCode !== undefined
33
+ : [400, 404, 405].includes(error.httpStatus ?? 0) ||
34
+ error.rpcCode === -32601 ||
35
+ error.rpcCode === -32002);
36
+ if (!legacyError && !(kind === 'stdio' && probe.aborted))
37
+ throw error;
38
+ }
39
+ let info;
40
+ if (discovery) {
41
+ if (!Array.isArray(discovery.supportedVersions) || !discovery.supportedVersions.includes(modernVersion))
42
+ throw new McpError('MCP protocol version unavailable');
43
+ info = object(discovery._meta) ? discovery._meta['io.modelcontextprotocol/serverInfo'] : undefined;
44
+ }
45
+ else {
46
+ transport.version = legacyVersions[0];
47
+ discovery = await transport.request('initialize', {
48
+ protocolVersion: transport.version,
49
+ capabilities: {},
50
+ clientInfo,
51
+ }, signal);
52
+ if (typeof discovery.protocolVersion !== 'string' || !legacyVersions.includes(discovery.protocolVersion))
53
+ throw new McpError('MCP protocol version unavailable');
54
+ transport.version = discovery.protocolVersion;
55
+ info = discovery.serverInfo;
56
+ if (!object(info) || typeof info.name !== 'string' || typeof info.version !== 'string')
57
+ throw new McpError('Invalid MCP server identity');
58
+ await transport.notify('notifications/initialized', {}, signal);
59
+ }
60
+ if (!object(discovery.capabilities) || !object(discovery.capabilities.tools))
61
+ throw new McpError('MCP server has no tools capability');
62
+ return info ?? null;
63
+ }
64
+ function sanitizeMessage(message) {
65
+ return message
66
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
67
+ .replace(/\s+/g, ' ')
68
+ .trim()
69
+ .slice(0, maxErrorMessageLength);
70
+ }
71
+ function safeJson(value) {
72
+ try {
73
+ const serialized = JSON.stringify(value);
74
+ return typeof serialized === 'string' ? serialized : undefined;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ function failure(code, effect, message) {
81
+ return {
82
+ effect,
83
+ outcome: {
84
+ status: 'error',
85
+ error: { code, message: message ?? code.replaceAll('_', ' '), retryable: false },
86
+ },
87
+ };
88
+ }
89
+ function toolErrorMessage(reply) {
90
+ const text = Array.isArray(reply.content)
91
+ ? reply.content
92
+ .filter((part) => object(part) && part.type === 'text' && typeof part.text === 'string')
93
+ .map((part) => part.text)
94
+ .join(' ')
95
+ : '';
96
+ const message = sanitizeMessage(text);
97
+ if (message)
98
+ return message;
99
+ const structured = reply.structuredContent === undefined ? undefined : safeJson(reply.structuredContent);
100
+ return sanitizeMessage(structured ?? '') || 'MCP TOOL ERROR';
101
+ }
102
+ function isExplicitRejection(error) {
103
+ return ((error.httpStatus !== undefined && explicitHttpRejections.has(error.httpStatus)) ||
104
+ (error.rpcCode !== undefined &&
105
+ ([-32600, -32601, -32602].includes(error.rpcCode) || error.rpcCode <= -32000)));
106
+ }
107
+ function observation(reply, read) {
108
+ if ((reply.resultType !== undefined && reply.resultType !== 'complete') ||
109
+ !Array.isArray(reply.content) ||
110
+ (reply.isError !== undefined && typeof reply.isError !== 'boolean'))
111
+ return failure('MCP_INVALID_RESULT', read ? 'none' : 'unknown');
112
+ if (reply.isError)
113
+ return failure('MCP_TOOL_ERROR', 'none', toolErrorMessage(reply));
114
+ const effect = read ? 'none' : 'applied';
115
+ const content = [];
116
+ for (const part of reply.content) {
117
+ if (!object(part) || part.type !== 'text' || typeof part.text !== 'string')
118
+ return failure('MCP_UNSUPPORTED_CONTENT', effect);
119
+ content.push({ type: 'text', text: part.text });
120
+ }
121
+ if (!content.length && reply.structuredContent !== undefined)
122
+ content.push({ type: 'text', text: JSON.stringify(reply.structuredContent) });
123
+ return {
124
+ effect,
125
+ outcome: {
126
+ status: 'success',
127
+ content,
128
+ ...(reply.structuredContent !== undefined ? { data: reply.structuredContent } : {}),
129
+ },
130
+ };
131
+ }
132
+ async function discover(serverId, config, workspaceRoot, signal) {
133
+ const discoveryTimeoutMs = config.timeoutMs ?? 10000;
134
+ const callTimeoutMs = config.timeoutMs ?? 60000;
135
+ if (!Number.isSafeInteger(discoveryTimeoutMs) ||
136
+ discoveryTimeoutMs < 1 ||
137
+ discoveryTimeoutMs > 600000 ||
138
+ !/^[a-z0-9_.-]{1,128}$/i.test(serverId))
139
+ throw new RuntimeError('INVALID_CONFIG', 'Invalid MCP server configuration');
140
+ const startup = AbortSignal.any([AbortSignal.timeout(discoveryTimeoutMs), ...(signal ? [signal] : [])]);
141
+ startup.throwIfAborted();
142
+ const transport = config.transport === 'stdio'
143
+ ? stdioTransport(config.command, config.args ?? [], workspaceRoot, config.env)
144
+ : httpTransport(config.url, config.headers);
145
+ try {
146
+ const serverInfo = await identify(transport, config.transport, startup, discoveryTimeoutMs);
147
+ const identity = digest({
148
+ serverId,
149
+ config,
150
+ workspaceRoot,
151
+ serverInfo,
152
+ protocolVersion: transport.version,
153
+ });
154
+ const bindings = [];
155
+ const seen = new Set();
156
+ const cursors = new Set();
157
+ let cursor;
158
+ do {
159
+ const page = await transport.request('tools/list', cursor ? { cursor } : {}, startup);
160
+ if (!Array.isArray(page.tools) || seen.size + page.tools.length > maxTools)
161
+ throw new McpError('Invalid or oversized MCP tool list');
162
+ for (const tool of page.tools) {
163
+ if (!object(tool) ||
164
+ typeof tool.name !== 'string' ||
165
+ !tool.name ||
166
+ tool.name.length > 128 ||
167
+ seen.has(tool.name))
168
+ throw new McpError('Invalid or duplicate MCP tool name');
169
+ const name = tool.name;
170
+ seen.add(name);
171
+ if (config.tools && !config.tools.includes(name))
172
+ continue;
173
+ if (!object(tool.inputSchema) ||
174
+ tool.inputSchema.type !== 'object' ||
175
+ (tool.outputSchema !== undefined && !object(tool.outputSchema)) ||
176
+ (tool.description !== undefined && typeof tool.description !== 'string') ||
177
+ Buffer.byteLength(JSON.stringify(tool)) > 32 * 1024)
178
+ throw new McpError('Invalid MCP tool definition');
179
+ const annotations = object(tool.annotations) ? tool.annotations : undefined;
180
+ const read = config.readOnlyTools?.includes(name) === true ||
181
+ (annotations?.readOnlyHint === true && annotations.destructiveHint !== true);
182
+ let headers;
183
+ if (transport.version === modernVersion && config.transport === 'http') {
184
+ try {
185
+ headers = parameterHeaders(tool.inputSchema);
186
+ }
187
+ catch {
188
+ if (config.tools?.includes(name))
189
+ throw new McpError('Configured MCP tool has invalid parameter headers');
190
+ continue;
191
+ }
192
+ }
193
+ const callHeaders = headers;
194
+ const version = digest({ identity, tool });
195
+ bindings.push({
196
+ definition: {
197
+ name: wireName(serverId, name),
198
+ version,
199
+ description: tool.description ?? name,
200
+ source: { kind: 'mcp', serverId, remoteName: name },
201
+ inputSchema: tool.inputSchema,
202
+ ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
203
+ effects: read ? 'read' : 'non_idempotent_write',
204
+ supportsIdempotencyKey: false,
205
+ supportsReconcile: false,
206
+ concurrency: read ? 'parallel' : 'serial_per_run',
207
+ timeoutMs: callTimeoutMs,
208
+ },
209
+ handler: {
210
+ async resolveResources() {
211
+ return [serverId, name, version];
212
+ },
213
+ async invoke(args, context) {
214
+ if (context.signal.aborted || transport.changed)
215
+ return failure('MCP_TOOL_UNAVAILABLE', 'none');
216
+ let extra;
217
+ try {
218
+ extra = callHeaders?.(args);
219
+ }
220
+ catch {
221
+ return failure('MCP_INVALID_ARGUMENTS', 'none');
222
+ }
223
+ try {
224
+ const result = await transport.request('tools/call', { name, arguments: args }, AbortSignal.any([context.signal, AbortSignal.timeout(callTimeoutMs)]), extra);
225
+ return observation(result, read);
226
+ }
227
+ catch (error) {
228
+ if (error instanceof McpError && isExplicitRejection(error))
229
+ return failure('MCP_REQUEST_REJECTED', 'none', sanitizeMessage(error.message) || 'MCP REQUEST REJECTED');
230
+ // A remote write may have happened even if its response or connection is lost.
231
+ return failure('MCP_CALL_UNCONFIRMED', read ? 'none' : 'unknown');
232
+ }
233
+ },
234
+ },
235
+ });
236
+ }
237
+ if (page.nextCursor === undefined)
238
+ break;
239
+ if (typeof page.nextCursor !== 'string' ||
240
+ !page.nextCursor ||
241
+ cursors.has(page.nextCursor) ||
242
+ cursors.size >= 32)
243
+ throw new McpError('Invalid MCP pagination');
244
+ cursor = page.nextCursor;
245
+ cursors.add(cursor);
246
+ } while (cursor);
247
+ if (config.tools?.some((name) => !seen.has(name)) ||
248
+ config.readOnlyTools?.some((name) => !seen.has(name)))
249
+ throw new McpError('Configured MCP tool missing from discovery');
250
+ if (transport.changed)
251
+ throw new McpError('MCP tool list changed during discovery');
252
+ return { bindings, transport, users: 0 };
253
+ }
254
+ catch (error) {
255
+ await transport.close();
256
+ throw error;
257
+ }
258
+ }
259
+ export async function openMcpServer(serverId, config, workspaceRoot, signal) {
260
+ const lifetime = new AbortController();
261
+ const initial = await discover(serverId, config, workspaceRoot, signal);
262
+ let live = initial;
263
+ const connections = new Set([initial]);
264
+ let refresh;
265
+ let closing;
266
+ async function retire(idle) {
267
+ if (idle !== live && !idle.users) {
268
+ await idle.transport.close();
269
+ connections.delete(idle);
270
+ }
271
+ }
272
+ async function reconnect() {
273
+ const prior = live;
274
+ const next = await discover(serverId, config, workspaceRoot, lifetime.signal);
275
+ if (lifetime.signal.aborted) {
276
+ await next.transport.close();
277
+ return;
278
+ }
279
+ connections.add(next);
280
+ live = next;
281
+ await retire(prior);
282
+ }
283
+ return {
284
+ bindings: initial.bindings.map(({ definition, handler }) => ({
285
+ definition,
286
+ handler: {
287
+ ...handler,
288
+ async invoke(args, context) {
289
+ if (lifetime.signal.aborted || context.signal.aborted)
290
+ return failure('MCP_TOOL_UNAVAILABLE', 'none');
291
+ if (live.transport.changed) {
292
+ try {
293
+ await (refresh ??= reconnect().finally(() => {
294
+ refresh = undefined;
295
+ }));
296
+ }
297
+ catch {
298
+ return failure('MCP_TOOL_UNAVAILABLE', 'none');
299
+ }
300
+ }
301
+ const active = live;
302
+ const binding = active.bindings.find(({ definition: current }) => current.name === definition.name && current.version === definition.version);
303
+ if (!binding || lifetime.signal.aborted || context.signal.aborted)
304
+ return failure('MCP_TOOL_UNAVAILABLE', 'none');
305
+ active.users++;
306
+ try {
307
+ return await binding.handler.invoke(args, context);
308
+ }
309
+ finally {
310
+ active.users--;
311
+ await retire(active);
312
+ }
313
+ },
314
+ },
315
+ })),
316
+ close() {
317
+ return (closing ??= (async () => {
318
+ lifetime.abort();
319
+ await Promise.allSettled([...connections].map(({ transport }) => transport.close()));
320
+ await refresh?.catch(() => { });
321
+ connections.clear();
322
+ })());
323
+ },
324
+ };
325
+ }
@@ -0,0 +1,3 @@
1
+ /** Returns the relative path, including an empty string for the root itself. */
2
+ export declare function relativePathWithin(root: string, target: string): string | undefined;
3
+ export declare function isContainedPath(root: string, target: string): boolean;
@@ -0,0 +1,11 @@
1
+ import path from 'node:path';
2
+ /** Returns the relative path, including an empty string for the root itself. */
3
+ export function relativePathWithin(root, target) {
4
+ const relative = path.relative(root, target);
5
+ if (path.isAbsolute(relative) || relative === '..' || relative.startsWith(`..${path.sep}`))
6
+ return undefined;
7
+ return relative;
8
+ }
9
+ export function isContainedPath(root, target) {
10
+ return relativePathWithin(root, target) !== undefined;
11
+ }
@@ -0,0 +1,3 @@
1
+ import type { ToolBinding } from '@saturn-universe/core';
2
+ export declare const plannerToolName = "submit_plan";
3
+ export declare function createPlannerTool(): ToolBinding;
@@ -0,0 +1,162 @@
1
+ import { RuntimeError, validateTeamConfig } from '@saturn-universe/core';
2
+ export const plannerToolName = 'submit_plan';
3
+ export function createPlannerTool() {
4
+ return {
5
+ definition: {
6
+ name: plannerToolName,
7
+ version: '1',
8
+ description: 'Record the execution plan deciding between single-agent execution or a multi-agent team. Inspect relevant workspace files first when workspace tools are available, and include structured evidence (observed files/symbols/findings), execution_steps, and verification_criteria.',
9
+ inputSchema: {
10
+ type: 'object',
11
+ properties: {
12
+ decision: { type: 'string', enum: ['single', 'team'] },
13
+ reason: { type: 'string', minLength: 1, maxLength: 1000 },
14
+ plan_summary: { type: 'string', maxLength: 4000 },
15
+ evidence: {
16
+ type: 'array',
17
+ maxItems: 20,
18
+ items: { type: 'string', minLength: 1, maxLength: 1000 },
19
+ },
20
+ execution_steps: {
21
+ type: 'array',
22
+ maxItems: 20,
23
+ items: { type: 'string', minLength: 1, maxLength: 1000 },
24
+ },
25
+ verification_criteria: {
26
+ type: 'array',
27
+ maxItems: 10,
28
+ items: { type: 'string', minLength: 1, maxLength: 1000 },
29
+ },
30
+ concurrency: { type: 'integer', minimum: 1, maximum: 16 },
31
+ members: {
32
+ type: 'array',
33
+ maxItems: 15,
34
+ items: {
35
+ type: 'object',
36
+ properties: {
37
+ id: { type: 'string', minLength: 1, maxLength: 64 },
38
+ parent: { type: 'string', minLength: 1, maxLength: 64 },
39
+ task: { type: 'string', minLength: 1, maxLength: 4000 },
40
+ },
41
+ required: ['id', 'parent', 'task'],
42
+ additionalProperties: false,
43
+ },
44
+ },
45
+ },
46
+ required: ['decision', 'reason'],
47
+ additionalProperties: false,
48
+ },
49
+ source: { kind: 'builtin' },
50
+ effects: 'read',
51
+ supportsIdempotencyKey: false,
52
+ supportsReconcile: false,
53
+ concurrency: 'parallel',
54
+ timeoutMs: 10000,
55
+ },
56
+ handler: {
57
+ async invoke(input) {
58
+ const parsed = input;
59
+ const reason = parsed.reason.trim();
60
+ if (!reason)
61
+ return invalidPlan('reason must not be empty');
62
+ const summary = parsed.plan_summary?.trim();
63
+ const evidence = parsePlanList(parsed.evidence, 'evidence', 20);
64
+ if (!Array.isArray(evidence))
65
+ return evidence;
66
+ const executionSteps = parsePlanList(parsed.execution_steps, 'execution_steps', 20);
67
+ if (!Array.isArray(executionSteps))
68
+ return executionSteps;
69
+ const verificationCriteria = parsePlanList(parsed.verification_criteria, 'verification_criteria', 10);
70
+ if (!Array.isArray(verificationCriteria))
71
+ return verificationCriteria;
72
+ const structuredData = {
73
+ ...(summary ? { summary } : {}),
74
+ ...(evidence.length ? { evidence } : {}),
75
+ ...(executionSteps.length ? { executionSteps } : {}),
76
+ ...(verificationCriteria.length ? { verificationCriteria } : {}),
77
+ };
78
+ if (parsed.decision === 'single') {
79
+ if (parsed.members && parsed.members.length > 0)
80
+ return invalidPlan('single decision must not include team members');
81
+ return {
82
+ effect: 'none',
83
+ outcome: {
84
+ status: 'success',
85
+ content: [{ type: 'text', text: 'Plan recorded: single agent.' }],
86
+ data: {
87
+ decision: 'single',
88
+ reason,
89
+ ...structuredData,
90
+ },
91
+ },
92
+ };
93
+ }
94
+ if (!parsed.members?.length)
95
+ return invalidPlan('team decision requires at least one worker member');
96
+ const members = parsed.members.map((member) => ({
97
+ id: member.id,
98
+ parent: member.parent,
99
+ task: member.task,
100
+ }));
101
+ const team = {
102
+ members,
103
+ ...(parsed.concurrency !== undefined ? { concurrency: parsed.concurrency } : {}),
104
+ };
105
+ try {
106
+ validateTeamConfig(team);
107
+ }
108
+ catch (err) {
109
+ if (err instanceof RuntimeError) {
110
+ return {
111
+ effect: 'none',
112
+ outcome: {
113
+ status: 'error',
114
+ error: { code: err.code, message: err.message, retryable: false },
115
+ },
116
+ };
117
+ }
118
+ throw err;
119
+ }
120
+ const teamData = {
121
+ members: members.map((member) => ({ ...member })),
122
+ ...(parsed.concurrency !== undefined ? { concurrency: parsed.concurrency } : {}),
123
+ };
124
+ return {
125
+ effect: 'none',
126
+ outcome: {
127
+ status: 'success',
128
+ content: [{ type: 'text', text: `Plan recorded: team with ${team.members.length} worker(s).` }],
129
+ data: {
130
+ decision: 'team',
131
+ reason,
132
+ ...structuredData,
133
+ team: teamData,
134
+ },
135
+ },
136
+ };
137
+ },
138
+ },
139
+ };
140
+ }
141
+ function parsePlanList(value, field, maxItems) {
142
+ if (value === undefined)
143
+ return [];
144
+ if (!Array.isArray(value) || value.length > maxItems)
145
+ return invalidPlan(`${field} must be an array of at most ${maxItems} items`);
146
+ const normalized = [];
147
+ for (const item of value) {
148
+ if (typeof item !== 'string' || !item.trim())
149
+ return invalidPlan(`${field} entries must be non-empty strings`);
150
+ normalized.push(item.trim());
151
+ }
152
+ return normalized;
153
+ }
154
+ function invalidPlan(message) {
155
+ return {
156
+ effect: 'none',
157
+ outcome: {
158
+ status: 'error',
159
+ error: { code: 'INVALID_TEAM_CONFIG', message, retryable: false },
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,67 @@
1
+ export interface ProcessScope {
2
+ readonly workspaceId: string;
3
+ readonly runId: string;
4
+ readonly agentId: string;
5
+ }
6
+ export interface ProcessStopCommand {
7
+ readonly program: string;
8
+ readonly args: readonly string[];
9
+ readonly cwd?: string;
10
+ readonly env?: NodeJS.ProcessEnv;
11
+ readonly timeoutMs?: number;
12
+ }
13
+ export interface ProcessStartInput {
14
+ readonly program: string;
15
+ readonly args: readonly string[];
16
+ readonly cwd: string;
17
+ readonly timeoutMs?: number;
18
+ readonly env?: NodeJS.ProcessEnv;
19
+ readonly stopCommand?: ProcessStopCommand;
20
+ }
21
+ export interface ProcessReadOptions {
22
+ readonly stdoutOffset?: number;
23
+ readonly stderrOffset?: number;
24
+ readonly maxBytes?: number;
25
+ readonly waitMs?: number;
26
+ }
27
+ export interface ProcessSnapshot {
28
+ readonly processId: string;
29
+ readonly scope: ProcessScope;
30
+ readonly status: 'starting' | 'running' | 'exited' | 'unknown';
31
+ readonly pid?: number;
32
+ readonly exitCode: number | null;
33
+ readonly signal: string | null;
34
+ readonly terminationConfirmed: boolean;
35
+ readonly stdout: string;
36
+ readonly stderr: string;
37
+ readonly stdoutOffset: number;
38
+ readonly stderrOffset: number;
39
+ readonly nextStdoutOffset: number;
40
+ readonly nextStderrOffset: number;
41
+ readonly truncated: boolean;
42
+ readonly deadlineAt: number;
43
+ readonly stopReason?: string;
44
+ readonly startError?: string;
45
+ }
46
+ export interface ProcessManagerOptions {
47
+ readonly directory: string;
48
+ readonly getRunDeadline?: (runId: string) => number | undefined | Promise<number | undefined>;
49
+ readonly onRecordError?: (processId: string, message: string) => void;
50
+ }
51
+ export interface ProcessManager {
52
+ start(input: ProcessStartInput, scope: ProcessScope, executionKey: string, signal?: AbortSignal): Promise<ProcessSnapshot>;
53
+ read(processId: string, scope: ProcessScope, options?: ProcessReadOptions, signal?: AbortSignal): Promise<ProcessSnapshot>;
54
+ write(processId: string, scope: ProcessScope, input: {
55
+ readonly input?: string;
56
+ readonly eof?: boolean;
57
+ }, executionKey: string): Promise<ProcessSnapshot>;
58
+ stop(processId: string, scope: ProcessScope): Promise<ProcessSnapshot>;
59
+ reconcile(executionKey: string, scope: ProcessScope): Promise<ProcessSnapshot | undefined>;
60
+ recover(scope?: Partial<ProcessScope>): Promise<ProcessSnapshot[]>;
61
+ stopRun(runId: string): Promise<ProcessSnapshot[]>;
62
+ stopWorkspace(workingDirectory: string, includeDescendants?: boolean): Promise<ProcessSnapshot[]>;
63
+ close(): Promise<void>;
64
+ }
65
+ export declare function processEnvironment(): NodeJS.ProcessEnv;
66
+ /** Persisted supervisor instances, rather than PIDs, are the unit of ownership. */
67
+ export declare function createProcessManager(options: ProcessManagerOptions): ProcessManager;