@ai-sdk/harness 0.0.0-6b196531-20260710185421

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 (77) hide show
  1. package/CHANGELOG.md +414 -0
  2. package/LICENSE +13 -0
  3. package/README.md +176 -0
  4. package/agent/index.ts +56 -0
  5. package/bridge/index.ts +10 -0
  6. package/dist/agent/index.d.ts +1631 -0
  7. package/dist/agent/index.js +3491 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/bridge/index.d.ts +129 -0
  10. package/dist/bridge/index.js +482 -0
  11. package/dist/bridge/index.js.map +1 -0
  12. package/dist/index.d.ts +1587 -0
  13. package/dist/index.js +517 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/utils/index.d.ts +329 -0
  16. package/dist/utils/index.js +1241 -0
  17. package/dist/utils/index.js.map +1 -0
  18. package/package.json +100 -0
  19. package/src/agent/harness-agent-session.ts +518 -0
  20. package/src/agent/harness-agent-settings.ts +187 -0
  21. package/src/agent/harness-agent-tool-approval-continuation.ts +94 -0
  22. package/src/agent/harness-agent-tool-types.ts +15 -0
  23. package/src/agent/harness-agent-types.ts +50 -0
  24. package/src/agent/harness-agent.ts +865 -0
  25. package/src/agent/internal/bootstrap-recipe.ts +124 -0
  26. package/src/agent/internal/bridge-port-registry.ts +52 -0
  27. package/src/agent/internal/harness-stream-text-result.ts +731 -0
  28. package/src/agent/internal/lifecycle-state-validation.ts +95 -0
  29. package/src/agent/internal/permission-mode.ts +50 -0
  30. package/src/agent/internal/resolve-observability.ts +128 -0
  31. package/src/agent/internal/run-prompt.ts +901 -0
  32. package/src/agent/internal/sandbox-bootstrap.ts +266 -0
  33. package/src/agent/internal/strip-work-dir.ts +68 -0
  34. package/src/agent/internal/to-harness-stream.ts +75 -0
  35. package/src/agent/internal/tool-filtering.ts +114 -0
  36. package/src/agent/internal/translate-stream-part.ts +221 -0
  37. package/src/agent/internal/turn-telemetry.ts +361 -0
  38. package/src/agent/observability/file-reporter.ts +206 -0
  39. package/src/agent/observability/index.ts +15 -0
  40. package/src/agent/observability/trace-tree-reporter.ts +122 -0
  41. package/src/agent/observability/types.ts +86 -0
  42. package/src/agent/prepare-harness-sandbox-template.ts +68 -0
  43. package/src/agent/prepare-sandbox-for-harness.ts +165 -0
  44. package/src/bridge/index.ts +797 -0
  45. package/src/errors/harness-capability-unsupported-error.ts +41 -0
  46. package/src/errors/harness-error.ts +22 -0
  47. package/src/index.ts +3 -0
  48. package/src/utils/ai-gateway-auth.ts +15 -0
  49. package/src/utils/bridge-diagnostics.ts +213 -0
  50. package/src/utils/bridge-ready.ts +277 -0
  51. package/src/utils/classify-disk-log.ts +43 -0
  52. package/src/utils/index.ts +31 -0
  53. package/src/utils/sandbox-channel.ts +525 -0
  54. package/src/utils/sandbox-home-dir.ts +22 -0
  55. package/src/utils/shell-quote.ts +3 -0
  56. package/src/utils/write-skills.ts +141 -0
  57. package/src/v1/harness-v1-bootstrap.ts +46 -0
  58. package/src/v1/harness-v1-bridge-protocol.ts +342 -0
  59. package/src/v1/harness-v1-builtin-tool.ts +138 -0
  60. package/src/v1/harness-v1-call-warning.ts +22 -0
  61. package/src/v1/harness-v1-diagnostic.ts +66 -0
  62. package/src/v1/harness-v1-lifecycle-state.ts +65 -0
  63. package/src/v1/harness-v1-metadata.ts +13 -0
  64. package/src/v1/harness-v1-network-sandbox-session.ts +123 -0
  65. package/src/v1/harness-v1-observability.ts +20 -0
  66. package/src/v1/harness-v1-permission-mode.ts +11 -0
  67. package/src/v1/harness-v1-prompt-control.ts +41 -0
  68. package/src/v1/harness-v1-prompt.ts +11 -0
  69. package/src/v1/harness-v1-sandbox-provider.ts +76 -0
  70. package/src/v1/harness-v1-session.ts +280 -0
  71. package/src/v1/harness-v1-skill.ts +36 -0
  72. package/src/v1/harness-v1-stream-part.ts +363 -0
  73. package/src/v1/harness-v1-tool-filtering.ts +25 -0
  74. package/src/v1/harness-v1-tool-spec.ts +31 -0
  75. package/src/v1/harness-v1.ts +94 -0
  76. package/src/v1/index.ts +99 -0
  77. package/utils/index.ts +1 -0
@@ -0,0 +1,525 @@
1
+ import {
2
+ safeParseJSON,
3
+ safeValidateTypes,
4
+ type FlexibleSchema,
5
+ } from '@ai-sdk/provider-utils';
6
+ import type { WebSocket } from 'ws';
7
+
8
+ /**
9
+ * Diagnostic event surfaced by {@link SandboxChannel} during its connection
10
+ * lifecycle. Silent unless a consumer wires `onDebug`. Reconnects are otherwise
11
+ * invisible — the channel reconnects transparently and the in-flight turn keeps
12
+ * streaming.
13
+ */
14
+ export type SandboxChannelDebugEvent =
15
+ | { event: 'reconnect-attempt'; attempt: number; lastSeenEventId: number }
16
+ | { event: 'reconnected'; attempt: number; lastSeenEventId: number }
17
+ | {
18
+ event: 'reconnect-failed';
19
+ attempts: number;
20
+ lastSeenEventId: number;
21
+ cause: unknown;
22
+ };
23
+
24
+ export interface SandboxChannelReconnectOptions {
25
+ /** Give up reconnecting after this many milliseconds. Default 30_000. */
26
+ readonly maxElapsedMs?: number;
27
+ /** First backoff delay. Default 50. */
28
+ readonly initialDelayMs?: number;
29
+ /** Backoff ceiling. Default 2_000. */
30
+ readonly maxDelayMs?: number;
31
+ }
32
+
33
+ export interface SandboxChannelOptions<TOut> {
34
+ /**
35
+ * Open a fresh WebSocket to the bridge and resolve once it is ready to carry
36
+ * frames (i.e. after any adapter-specific handshake such as Claude Code's
37
+ * `bridge-hello`). Called once by {@link SandboxChannel.open} and again on
38
+ * every transient reconnect. Must reject if the connection cannot be
39
+ * established.
40
+ */
41
+ connect: () => Promise<WebSocket>;
42
+
43
+ /** Schema validating inbound (bridge → host) frames. */
44
+ outboundSchema: FlexibleSchema<TOut>;
45
+
46
+ reconnect?: SandboxChannelReconnectOptions;
47
+
48
+ onDebug?: (event: SandboxChannelDebugEvent) => void;
49
+
50
+ /**
51
+ * Sink for forwarded bridge diagnostics — `sandbox-log` (captured
52
+ * console lines) and `debug-event` (structured) frames. When set, these
53
+ * frame types are routed here instead of the per-type listener dispatch, so
54
+ * they never reach the consumer's stream. Typed to the diagnostic members of
55
+ * `TOut`, so it is a no-op union for channels whose protocol has none.
56
+ */
57
+ onDiagnostic?: (
58
+ event: Extract<TOut, { type: 'sandbox-log' | 'debug-event' }>,
59
+ ) => void;
60
+
61
+ onBridgeError?: (event: Extract<TOut, { type: 'error' }>) => void;
62
+
63
+ /**
64
+ * Seed the host-side cursor before the first connect. Pass the
65
+ * `lastSeenEventId` persisted from a prior process so the bridge replays only
66
+ * events past it when this channel opens with `{ resume: true }` — the
67
+ * cross-process attach handshake. Defaults to `0` (fresh session).
68
+ */
69
+ initialLastSeenEventId?: number;
70
+ }
71
+
72
+ type EventTypeOf<TOut extends { type: string }> = TOut['type'];
73
+
74
+ type Listener<TOut extends { type: string }, T extends EventTypeOf<TOut>> = (
75
+ event: Extract<TOut, { type: T }>,
76
+ ) => void;
77
+
78
+ const sleep = (ms: number): Promise<void> =>
79
+ new Promise(resolve => {
80
+ const t = setTimeout(resolve, ms);
81
+ (t as { unref?: () => void }).unref?.();
82
+ });
83
+
84
+ /**
85
+ * Host-side typed wrapper around the bridge WebSocket connection.
86
+ *
87
+ * Buffers inbound messages until a listener for their type is registered, so
88
+ * callers that subscribe asynchronously do not miss early frames. Inbound
89
+ * dispatch is serialised through a promise chain so a `close` event that
90
+ * arrives on the same microtask as the final `finish` message does not fire
91
+ * close handlers until the message has been dispatched.
92
+ *
93
+ * Survives transient disconnects. The bridge keeps running and
94
+ * accumulates events in an in-memory log keyed by a monotonic `seq`; on an
95
+ * unexpected socket drop this channel re-invokes `connect`, re-wires the new
96
+ * socket, and asks the bridge to replay everything past `lastSeenEventId`. The
97
+ * in-flight turn never observes the blip — `onClose` fires only after a
98
+ * host-initiated close or once the reconnect budget is exhausted.
99
+ */
100
+ export class SandboxChannel<
101
+ TOut extends { type: string },
102
+ TIn extends { type: string } = { type: string },
103
+ > {
104
+ private readonly listeners = new Map<
105
+ EventTypeOf<TOut>,
106
+ Set<Listener<TOut, EventTypeOf<TOut>>>
107
+ >();
108
+ private readonly buffered = new Map<EventTypeOf<TOut>, TOut[]>();
109
+ private readonly onCloseHandlers = new Set<
110
+ (code: number, reason: string) => void
111
+ >();
112
+
113
+ private readonly connectThunk: () => Promise<WebSocket>;
114
+ private readonly outboundSchema: FlexibleSchema<TOut>;
115
+ private readonly onDebug:
116
+ | ((event: SandboxChannelDebugEvent) => void)
117
+ | undefined;
118
+ private readonly onDiagnostic:
119
+ | ((event: Extract<TOut, { type: 'sandbox-log' | 'debug-event' }>) => void)
120
+ | undefined;
121
+ private readonly onBridgeError:
122
+ | ((event: Extract<TOut, { type: 'error' }>) => void)
123
+ | undefined;
124
+ private readonly maxElapsedMs: number;
125
+ private readonly initialDelayMs: number;
126
+ private readonly maxDelayMs: number;
127
+
128
+ private ws: WebSocket | undefined;
129
+ private connected = false;
130
+ /** Host has begun teardown; suppresses reconnect so a bridge-side close finalises. */
131
+ private closing = false;
132
+ /**
133
+ * Host has gracefully suspended (slice boundary). Inbound frames are ignored
134
+ * from this point so the cursor stops advancing exactly at the last delivered
135
+ * event — the bridge keeps the turn running and the not-yet-delivered tail is
136
+ * replayed to the next process on `resume`.
137
+ */
138
+ private suspended = false;
139
+ /** Channel is fully torn down; `send` throws and `onClose` has fired. */
140
+ private terminal = false;
141
+ private _lastSeenEventId = 0;
142
+ private readonly pendingSends: string[] = [];
143
+ private dispatchChain: Promise<void> = Promise.resolve();
144
+
145
+ constructor(options: SandboxChannelOptions<TOut>) {
146
+ this.connectThunk = options.connect;
147
+ this.outboundSchema = options.outboundSchema;
148
+ this.onDebug = options.onDebug;
149
+ this.onDiagnostic = options.onDiagnostic;
150
+ this.onBridgeError = options.onBridgeError;
151
+ this.maxElapsedMs = options.reconnect?.maxElapsedMs ?? 30_000;
152
+ this.initialDelayMs = options.reconnect?.initialDelayMs ?? 50;
153
+ this.maxDelayMs = options.reconnect?.maxDelayMs ?? 2_000;
154
+ this._lastSeenEventId = options.initialLastSeenEventId ?? 0;
155
+ }
156
+
157
+ /**
158
+ * Highest bridge event `seq` this channel has observed. Persist it (e.g. via
159
+ * the adapter's resume handle) so a future process can seed
160
+ * {@link SandboxChannelOptions.initialLastSeenEventId} and attach.
161
+ */
162
+ get lastSeenEventId(): number {
163
+ return this._lastSeenEventId;
164
+ }
165
+
166
+ /**
167
+ * Establish the initial connection. A single attempt — startup failures
168
+ * reject so the caller can fail `doStart` cleanly. Reconnect retries apply
169
+ * only to drops after a successful open.
170
+ *
171
+ * Pass `{ resume: true }` to attach to a bridge that is already mid-session:
172
+ * after the socket opens, the channel sends `{ type: 'resume', lastSeenEventId }`
173
+ * so the bridge replays everything past the seeded cursor. This is the
174
+ * cross-process attach handshake — identical to what a transient reconnect
175
+ * does, but triggered by the initial open from a new process.
176
+ */
177
+ async open(opts?: { resume?: boolean }): Promise<void> {
178
+ if (this.terminal) {
179
+ throw new Error('SandboxChannel: cannot open a closed channel.');
180
+ }
181
+ const ws = await this.connectThunk();
182
+ this.wire(ws);
183
+ this.ws = ws;
184
+ this.connected = true;
185
+ if (opts?.resume) {
186
+ this.rawSend(
187
+ JSON.stringify({
188
+ type: 'resume',
189
+ lastSeenEventId: this._lastSeenEventId,
190
+ }),
191
+ );
192
+ }
193
+ }
194
+
195
+ on<T extends EventTypeOf<TOut>>(
196
+ type: T,
197
+ listener: Listener<TOut, T>,
198
+ ): () => void {
199
+ let set = this.listeners.get(type);
200
+ if (!set) {
201
+ set = new Set();
202
+ this.listeners.set(type, set);
203
+ }
204
+ set.add(listener as unknown as Listener<TOut, EventTypeOf<TOut>>);
205
+
206
+ const buffered = this.buffered.get(type);
207
+ if (buffered) {
208
+ this.buffered.delete(type);
209
+ for (const event of buffered) {
210
+ listener(event as Extract<TOut, { type: T }>);
211
+ }
212
+ }
213
+
214
+ return () => {
215
+ set!.delete(listener as unknown as Listener<TOut, EventTypeOf<TOut>>);
216
+ };
217
+ }
218
+
219
+ onClose(handler: (code: number, reason: string) => void): void {
220
+ this.onCloseHandlers.add(handler);
221
+ }
222
+
223
+ send(message: TIn): void {
224
+ if (this.terminal) {
225
+ throw new Error(
226
+ `SandboxChannel: cannot send ${message.type} — channel is closed.`,
227
+ );
228
+ }
229
+ this.rawSend(JSON.stringify(message));
230
+ }
231
+
232
+ /**
233
+ * Mark that the host is tearing the session down. The next socket close is
234
+ * then treated as terminal rather than triggering a reconnect. Call before
235
+ * sending a `shutdown` / `detach` message whose ack the bridge follows with a
236
+ * socket close.
237
+ */
238
+ beginClose(): void {
239
+ this.closing = true;
240
+ }
241
+
242
+ close(): void {
243
+ if (this.terminal) return;
244
+ this.closing = true;
245
+ try {
246
+ this.ws?.close();
247
+ } catch {
248
+ // best-effort
249
+ }
250
+ this.enqueue(() => this.finalizeClose(1000, 'closed'));
251
+ }
252
+
253
+ interrupt(options?: { timeoutMs?: number }): Promise<void> {
254
+ const timeoutMs = options?.timeoutMs ?? 5000;
255
+ return new Promise<void>((resolve, reject) => {
256
+ let settled = false;
257
+ let unsub = (): void => {};
258
+ const timer = setTimeout(() => {
259
+ complete(
260
+ new Error(
261
+ `SandboxChannel: interrupt was not acknowledged within ${timeoutMs}ms.`,
262
+ ),
263
+ );
264
+ }, timeoutMs);
265
+ timer.unref?.();
266
+
267
+ const complete = (error?: unknown): void => {
268
+ if (settled) return;
269
+ settled = true;
270
+ clearTimeout(timer);
271
+ unsub();
272
+ if (error) {
273
+ reject(error);
274
+ } else {
275
+ resolve();
276
+ }
277
+ };
278
+
279
+ unsub = this.on('bridge-interrupted' as EventTypeOf<TOut>, event => {
280
+ const response = event as unknown as {
281
+ type: 'bridge-interrupted';
282
+ ok: boolean;
283
+ error?: unknown;
284
+ };
285
+ if (response.ok) {
286
+ complete();
287
+ return;
288
+ }
289
+ complete(
290
+ new Error(
291
+ `SandboxChannel: interrupt failed: ${formatControlError(
292
+ response.error,
293
+ )}`,
294
+ ),
295
+ );
296
+ });
297
+
298
+ try {
299
+ this.send({ type: 'interrupt' } as TIn);
300
+ } catch (err) {
301
+ complete(err);
302
+ }
303
+ });
304
+ }
305
+
306
+ /**
307
+ * Gracefully suspend at a slice boundary: stop processing inbound frames
308
+ * (so the cursor freezes at the last delivered event), drain any frames
309
+ * already queued for dispatch, then close the socket and finalise with the
310
+ * close reason `'suspended'`. Resolves with the final `lastSeenEventId`.
311
+ *
312
+ * The bridge keeps the in-flight turn running (a host socket close never
313
+ * aborts it) and accumulates events past the cursor for the next process to
314
+ * `resume`. Unlike {@link close}, the consumer's active turn is wound down
315
+ * cleanly — adapters distinguish a suspend from an unexpected drop via the
316
+ * `'suspended'` close reason and resolve `done` successfully.
317
+ */
318
+ suspend(): Promise<number> {
319
+ return new Promise<number>(resolve => {
320
+ if (this.terminal) {
321
+ resolve(this._lastSeenEventId);
322
+ return;
323
+ }
324
+ // Stop counting/dispatching further inbound frames immediately, and
325
+ // suppress reconnect so the socket close finalises.
326
+ this.suspended = true;
327
+ this.closing = true;
328
+ this.onClose(() => resolve(this._lastSeenEventId));
329
+ // Queue the close behind any already-dispatched frames so everything
330
+ // delivered to the consumer is reflected in the final cursor.
331
+ this.enqueue(() => {
332
+ try {
333
+ this.ws?.close();
334
+ } catch {
335
+ // best-effort
336
+ }
337
+ this.finalizeClose(1000, 'suspended');
338
+ });
339
+ });
340
+ }
341
+
342
+ isClosed(): boolean {
343
+ return this.terminal;
344
+ }
345
+
346
+ // ─── internals ──────────────────────────────────────────────────────
347
+
348
+ private wire(ws: WebSocket): void {
349
+ let dropped = false;
350
+ const onDrop = (code: number, reason: string) => {
351
+ if (dropped) return;
352
+ dropped = true;
353
+ if (ws !== this.ws) return;
354
+ this.connected = false;
355
+ if (this.closing) {
356
+ this.enqueue(() => this.finalizeClose(code, reason));
357
+ } else {
358
+ this.enqueue(() => this.reconnectLoop());
359
+ }
360
+ };
361
+
362
+ ws.on('message', (raw: ArrayBufferLike | string) => {
363
+ // Once suspended, ignore further frames so the cursor freezes exactly at
364
+ // the last delivered event (the bridge replays the rest to the next slice).
365
+ if (this.suspended) return;
366
+ const text =
367
+ typeof raw === 'string' ? raw : Buffer.from(raw).toString('utf8');
368
+ this.enqueue(() => this.handleIncoming(text));
369
+ });
370
+ ws.on('close', (code: number, reason: Buffer) =>
371
+ onDrop(code, reason?.toString?.('utf8') ?? ''),
372
+ );
373
+ ws.on('error', () => onDrop(1006, 'socket error'));
374
+ }
375
+
376
+ private async reconnectLoop(): Promise<void> {
377
+ if (this.terminal || this.closing) return;
378
+ const start = Date.now();
379
+ let attempt = 0;
380
+ let delay = this.initialDelayMs;
381
+ while (!this.terminal && !this.closing) {
382
+ attempt++;
383
+ this.onDebug?.({
384
+ event: 'reconnect-attempt',
385
+ attempt,
386
+ lastSeenEventId: this._lastSeenEventId,
387
+ });
388
+ try {
389
+ const ws = await this.connectThunk();
390
+ if (this.terminal || this.closing) {
391
+ try {
392
+ ws.close();
393
+ } catch {
394
+ // best-effort
395
+ }
396
+ return;
397
+ }
398
+ this.wire(ws);
399
+ this.ws = ws;
400
+ this.connected = true;
401
+ // Ask the bridge to replay everything we have not seen, then flush any
402
+ // host → bridge frames produced while we were disconnected.
403
+ this.rawSend(
404
+ JSON.stringify({
405
+ type: 'resume',
406
+ lastSeenEventId: this._lastSeenEventId,
407
+ }),
408
+ );
409
+ this.flushPending();
410
+ this.onDebug?.({
411
+ event: 'reconnected',
412
+ attempt,
413
+ lastSeenEventId: this._lastSeenEventId,
414
+ });
415
+ return;
416
+ } catch (cause) {
417
+ if (Date.now() - start >= this.maxElapsedMs) {
418
+ this.finalizeClose(1006, 'reconnect failed');
419
+ this.onDebug?.({
420
+ event: 'reconnect-failed',
421
+ attempts: attempt,
422
+ lastSeenEventId: this._lastSeenEventId,
423
+ cause,
424
+ });
425
+ return;
426
+ }
427
+ await sleep(delay);
428
+ delay = Math.min(delay * 1.5, this.maxDelayMs);
429
+ }
430
+ }
431
+ }
432
+
433
+ private rawSend(text: string): void {
434
+ if (this.connected && this.ws) {
435
+ this.ws.send(text);
436
+ } else {
437
+ this.pendingSends.push(text);
438
+ }
439
+ }
440
+
441
+ private flushPending(): void {
442
+ if (!this.connected || !this.ws) return;
443
+ const queued = this.pendingSends.splice(0);
444
+ for (const text of queued) this.ws.send(text);
445
+ }
446
+
447
+ private enqueue(work: () => void | Promise<void>): void {
448
+ this.dispatchChain = this.dispatchChain.then(work);
449
+ }
450
+
451
+ private async handleIncoming(text: string): Promise<void> {
452
+ const raw = await safeParseJSON({ text });
453
+ let seq: number | undefined;
454
+ if (
455
+ raw.success &&
456
+ raw.value != null &&
457
+ typeof raw.value === 'object' &&
458
+ typeof (raw.value as { seq?: unknown }).seq === 'number'
459
+ ) {
460
+ seq = (raw.value as { seq: number }).seq;
461
+ }
462
+
463
+ const validated = await safeValidateTypes({
464
+ value: raw.success ? raw.value : undefined,
465
+ schema: this.outboundSchema,
466
+ });
467
+ if (validated.success) {
468
+ this.dispatch(validated.value);
469
+ } else {
470
+ this.dispatch({
471
+ type: 'error',
472
+ error: validated.error,
473
+ } as unknown as TOut);
474
+ }
475
+
476
+ if (seq !== undefined && seq > this._lastSeenEventId) {
477
+ this._lastSeenEventId = seq;
478
+ }
479
+ }
480
+
481
+ private dispatch(message: TOut): void {
482
+ // Diagnostics are routed to their own sink and never enter the
483
+ // per-type listener/buffer path, so they stay off the consumer stream.
484
+ if (message.type === 'sandbox-log' || message.type === 'debug-event') {
485
+ this.onDiagnostic?.(
486
+ message as Extract<TOut, { type: 'sandbox-log' | 'debug-event' }>,
487
+ );
488
+ return;
489
+ }
490
+ if (message.type === 'error') {
491
+ this.onBridgeError?.(message as Extract<TOut, { type: 'error' }>);
492
+ }
493
+ const type = message.type as EventTypeOf<TOut>;
494
+ const set = this.listeners.get(type);
495
+ if (!set || set.size === 0) {
496
+ let bucket = this.buffered.get(type);
497
+ if (!bucket) {
498
+ bucket = [];
499
+ this.buffered.set(type, bucket);
500
+ }
501
+ bucket.push(message);
502
+ return;
503
+ }
504
+ for (const listener of set) {
505
+ listener(message as Extract<TOut, { type: EventTypeOf<TOut> }>);
506
+ }
507
+ }
508
+
509
+ private finalizeClose(code: number, reason: string): void {
510
+ if (this.terminal) return;
511
+ this.terminal = true;
512
+ this.connected = false;
513
+ for (const h of this.onCloseHandlers) h(code, reason);
514
+ }
515
+ }
516
+
517
+ function formatControlError(error: unknown): string {
518
+ if (error instanceof Error) return error.message;
519
+ if (error && typeof error === 'object') {
520
+ const message = (error as { message?: unknown }).message;
521
+ if (typeof message === 'string' && message.length > 0) return message;
522
+ }
523
+ if (typeof error === 'string' && error.length > 0) return error;
524
+ return 'unknown error';
525
+ }
@@ -0,0 +1,22 @@
1
+ import path from 'node:path';
2
+ import type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';
3
+
4
+ export async function resolveSandboxHomeDir({
5
+ sandbox,
6
+ abortSignal,
7
+ }: {
8
+ sandbox: Experimental_SandboxSession;
9
+ abortSignal?: AbortSignal;
10
+ }): Promise<string> {
11
+ const result = await sandbox.run({
12
+ command: 'printf "%s" "$HOME"',
13
+ abortSignal,
14
+ });
15
+ const homeDir = result.stdout.trim();
16
+ if (result.exitCode !== 0 || !homeDir || !path.posix.isAbsolute(homeDir)) {
17
+ throw new Error(
18
+ `Unable to resolve sandbox HOME directory: ${result.stderr || result.stdout}`,
19
+ );
20
+ }
21
+ return homeDir;
22
+ }
@@ -0,0 +1,3 @@
1
+ export function shellQuote(value: string): string {
2
+ return `'${value.replace(/'/g, `'\\''`)}'`;
3
+ }
@@ -0,0 +1,141 @@
1
+ import path from 'node:path';
2
+ import type { Experimental_SandboxSession } from '@ai-sdk/provider-utils';
3
+ import type { HarnessV1Skill } from '../v1';
4
+ import { shellQuote } from './shell-quote';
5
+
6
+ export type SkillFilePathMode = 'relative' | 'strip-leading-slashes';
7
+
8
+ export type WriteSkillsOptions = {
9
+ sandbox: Experimental_SandboxSession;
10
+ rootDir: string;
11
+ skills: ReadonlyArray<HarnessV1Skill>;
12
+ abortSignal?: AbortSignal;
13
+ skillNamePattern?: RegExp;
14
+ invalidSkillNameMessage?: (input: { name: string }) => string;
15
+ filePathMode?: SkillFilePathMode;
16
+ invalidSkillFilePathMessage?: (input: {
17
+ skillName: string;
18
+ filePath: string;
19
+ }) => string;
20
+ trailingNewline?: boolean;
21
+ };
22
+
23
+ export async function writeSkills({
24
+ sandbox,
25
+ rootDir,
26
+ skills,
27
+ abortSignal,
28
+ skillNamePattern = /^[A-Za-z0-9._-]+$/,
29
+ invalidSkillNameMessage = ({ name }) => `Invalid skill name: ${name}`,
30
+ filePathMode = 'relative',
31
+ invalidSkillFilePathMessage = ({ skillName, filePath }) =>
32
+ `Invalid skill file path for ${skillName}: ${filePath}`,
33
+ trailingNewline = false,
34
+ }: WriteSkillsOptions): Promise<void> {
35
+ for (const skill of skills) {
36
+ validateSkillName({
37
+ name: skill.name,
38
+ pattern: skillNamePattern,
39
+ message: invalidSkillNameMessage,
40
+ });
41
+ for (const file of skill.files ?? []) {
42
+ normalizeSkillFilePath({
43
+ skillName: skill.name,
44
+ filePath: file.path,
45
+ mode: filePathMode,
46
+ message: invalidSkillFilePathMessage,
47
+ });
48
+ }
49
+ }
50
+
51
+ await sandbox.run({
52
+ command: `mkdir -p ${shellQuote(rootDir)}`,
53
+ abortSignal,
54
+ });
55
+
56
+ for (const skill of skills) {
57
+ const name = validateSkillName({
58
+ name: skill.name,
59
+ pattern: skillNamePattern,
60
+ message: invalidSkillNameMessage,
61
+ });
62
+ const skillDir = path.posix.join(rootDir, name);
63
+ await sandbox.writeTextFile({
64
+ path: path.posix.join(skillDir, 'SKILL.md'),
65
+ content: renderSkillFile({ skill, trailingNewline }),
66
+ abortSignal,
67
+ });
68
+
69
+ for (const file of skill.files ?? []) {
70
+ const filePath = normalizeSkillFilePath({
71
+ skillName: skill.name,
72
+ filePath: file.path,
73
+ mode: filePathMode,
74
+ message: invalidSkillFilePathMessage,
75
+ });
76
+ await sandbox.writeTextFile({
77
+ path: path.posix.join(skillDir, filePath),
78
+ content: file.content,
79
+ abortSignal,
80
+ });
81
+ }
82
+ }
83
+ }
84
+
85
+ function validateSkillName({
86
+ name,
87
+ pattern,
88
+ message,
89
+ }: {
90
+ name: string;
91
+ pattern: RegExp;
92
+ message?: (input: { name: string }) => string;
93
+ }): string {
94
+ if (!pattern.test(name) || name === '.' || name === '..') {
95
+ throw new Error(message?.({ name }) ?? `Invalid skill name: ${name}`);
96
+ }
97
+ return name;
98
+ }
99
+
100
+ function normalizeSkillFilePath({
101
+ skillName,
102
+ filePath,
103
+ mode,
104
+ message,
105
+ }: {
106
+ skillName?: string;
107
+ filePath: string;
108
+ mode: SkillFilePathMode;
109
+ message?: (input: { skillName: string; filePath: string }) => string;
110
+ }): string {
111
+ const normalized =
112
+ mode === 'strip-leading-slashes'
113
+ ? filePath.replace(/^\/+/, '')
114
+ : path.posix.normalize(filePath);
115
+ const invalid =
116
+ normalized === '' ||
117
+ (mode === 'relative' && normalized === '.') ||
118
+ normalized.startsWith('../') ||
119
+ normalized.includes('/../') ||
120
+ normalized.endsWith('/..') ||
121
+ (mode === 'relative' && path.posix.isAbsolute(normalized));
122
+
123
+ if (invalid) {
124
+ throw new Error(
125
+ message?.({ skillName: skillName ?? '', filePath }) ??
126
+ `Invalid skill file path for ${skillName}: ${filePath}`,
127
+ );
128
+ }
129
+ return normalized;
130
+ }
131
+
132
+ function renderSkillFile({
133
+ skill,
134
+ trailingNewline,
135
+ }: {
136
+ skill: HarnessV1Skill;
137
+ trailingNewline: boolean;
138
+ }): string {
139
+ const content = `---\nname: ${skill.name}\ndescription: ${skill.description}\n---\n\n${skill.content}`;
140
+ return trailingNewline ? `${content}\n` : content;
141
+ }