supertag-ai 0.1.0

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -0
  3. package/dist/chunk-B3EVEGNZ.js +13 -0
  4. package/dist/chunk-B3EVEGNZ.js.map +1 -0
  5. package/dist/chunk-ES42FTPC.js +1068 -0
  6. package/dist/chunk-ES42FTPC.js.map +1 -0
  7. package/dist/chunk-L7S2TKUG.js +656 -0
  8. package/dist/chunk-L7S2TKUG.js.map +1 -0
  9. package/dist/connectors.d.ts +45 -0
  10. package/dist/connectors.js +39 -0
  11. package/dist/connectors.js.map +1 -0
  12. package/dist/core.d.ts +721 -0
  13. package/dist/core.js +3 -0
  14. package/dist/core.js.map +1 -0
  15. package/dist/environments/e2b.d.ts +69 -0
  16. package/dist/environments/e2b.js +268 -0
  17. package/dist/environments/e2b.js.map +1 -0
  18. package/dist/gateway.d.ts +59 -0
  19. package/dist/gateway.js +1215 -0
  20. package/dist/gateway.js.map +1 -0
  21. package/dist/harnesses/claude-code.d.ts +67 -0
  22. package/dist/harnesses/claude-code.js +565 -0
  23. package/dist/harnesses/claude-code.js.map +1 -0
  24. package/dist/harnesses/codex.d.ts +68 -0
  25. package/dist/harnesses/codex.js +690 -0
  26. package/dist/harnesses/codex.js.map +1 -0
  27. package/dist/index.d.ts +100 -0
  28. package/dist/index.js +4 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/resources/github.d.ts +80 -0
  31. package/dist/resources/github.js +374 -0
  32. package/dist/resources/github.js.map +1 -0
  33. package/dist/resources/linear.d.ts +25 -0
  34. package/dist/resources/linear.js +92 -0
  35. package/dist/resources/linear.js.map +1 -0
  36. package/dist/resources/slack.d.ts +25 -0
  37. package/dist/resources/slack.js +98 -0
  38. package/dist/resources/slack.js.map +1 -0
  39. package/dist/resources/teams.d.ts +27 -0
  40. package/dist/resources/teams.js +101 -0
  41. package/dist/resources/teams.js.map +1 -0
  42. package/dist/transport.d.ts +5 -0
  43. package/dist/transport.js +3 -0
  44. package/dist/transport.js.map +1 -0
  45. package/dist/worker.d.ts +634 -0
  46. package/dist/worker.js +3 -0
  47. package/dist/worker.js.map +1 -0
  48. package/package.json +127 -0
@@ -0,0 +1,1068 @@
1
+ import { spawn } from 'child_process';
2
+ import { createHash } from 'crypto';
3
+ import { readFile, mkdir, writeFile, rename, rm, mkdtemp, lstat, cp, readdir, chmod } from 'fs/promises';
4
+ import { tmpdir } from 'os';
5
+ import { resolve, isAbsolute, dirname, join, relative } from 'path';
6
+ import { pathToFileURL, fileURLToPath } from 'url';
7
+
8
+ // ../runtime/sdk/src/index.ts
9
+ var TASK_ATTEMPT_EVENT_STREAM_CAPABILITY = {
10
+ id: "supertag.task-attempt.events",
11
+ version: 1
12
+ };
13
+ var TASK_ATTEMPT_CANCELLATION_CAPABILITY = {
14
+ id: "supertag.task-attempt.cancellation",
15
+ version: 1
16
+ };
17
+ var LOCAL_PROCESS_CAPABILITY = {
18
+ id: "supertag.execution.local-process",
19
+ version: 1
20
+ };
21
+ async function resolveSkillPackages(contributions) {
22
+ const resolvedPackages = [];
23
+ for (const contribution of contributions) {
24
+ const sourcePath = localPackagePath(contribution.source.uri, contribution.kind);
25
+ await requireSkillPackage(sourcePath, contribution.id);
26
+ resolvedPackages.push({
27
+ contributionId: contribution.id,
28
+ name: contribution.id,
29
+ source: contribution.source
30
+ });
31
+ }
32
+ return resolvedPackages;
33
+ }
34
+ var ContextMaterializerRegistry = class {
35
+ #materializers;
36
+ constructor(materializers) {
37
+ this.#materializers = materializers;
38
+ }
39
+ async materialize(context) {
40
+ const contributions = [];
41
+ for (const item of context.task.contextPlan.sets.flatMap((set) => set.items)) {
42
+ const materializer = this.#materializers.find((candidate) => candidate.supports(item));
43
+ if (materializer === void 0) {
44
+ throw new Error(
45
+ `No Context Item materializer is installed for ${item.kind}:${item.itemKey}`
46
+ );
47
+ }
48
+ const resolved = await materializer.materialize(item, context);
49
+ if (resolved === void 0) continue;
50
+ const itemContributions = Array.isArray(resolved) ? resolved : [resolved];
51
+ if (itemContributions.length === 0) continue;
52
+ for (const contribution of itemContributions) {
53
+ contributions.push({
54
+ ...contribution,
55
+ sourceItemKey: item.itemKey
56
+ });
57
+ }
58
+ }
59
+ return contributions;
60
+ }
61
+ };
62
+ var WorkRecordMaterializer = class {
63
+ supports(item) {
64
+ return item.kind === "work";
65
+ }
66
+ async materialize(item) {
67
+ if (item.workRecords.length === 0) return void 0;
68
+ return workRecordContribution({
69
+ id: `shared-work:${item.id}`,
70
+ records: item.workRecords,
71
+ source: {
72
+ uri: `supertag://context-items/${encodeURIComponent(item.id)}/work`,
73
+ mediaType: "application/vnd.supertag.work-record+json;version=1",
74
+ provenance: {
75
+ itemKey: item.itemKey,
76
+ sourcePresenceId: item.source.tagPresenceId,
77
+ sourceProvider: item.source.provider,
78
+ sourceScope: item.source.scope
79
+ }
80
+ },
81
+ sourceItemKey: item.itemKey
82
+ });
83
+ }
84
+ };
85
+ function workRecordContribution(input) {
86
+ const records = input.records.map((record) => ({
87
+ taskId: record.taskId,
88
+ sessionId: record.sessionId,
89
+ completedAt: record.completedAt,
90
+ origin: {
91
+ provider: record.origin.provider,
92
+ scope: record.origin.scope
93
+ },
94
+ requester: record.requester,
95
+ ...record.intent === void 0 ? {} : { intent: boundedText(record.intent, 4e3) },
96
+ result: {
97
+ ...record.result,
98
+ summary: boundedText(record.result.summary, 8e3)
99
+ },
100
+ resources: record.resources.map((resource) => ({
101
+ provider: resource.provider,
102
+ scope: resource.scope,
103
+ ...resource.reference === void 0 ? {} : { reference: resource.reference }
104
+ })),
105
+ references: record.references,
106
+ citation: record.citation
107
+ }));
108
+ return {
109
+ id: input.id,
110
+ kind: "work-context",
111
+ required: true,
112
+ trust: "untrusted-history",
113
+ content: JSON.stringify(records),
114
+ source: input.source,
115
+ ...input.sourceItemKey === void 0 ? {} : { sourceItemKey: input.sourceItemKey }
116
+ };
117
+ }
118
+ var FileSkillMaterializer = class _FileSkillMaterializer {
119
+ #entries;
120
+ #maxFiles;
121
+ #maxBytes;
122
+ constructor(entries, options) {
123
+ this.#entries = entries;
124
+ this.#maxFiles = positiveInteger(options.maxFiles ?? 2048, "maxFiles");
125
+ this.#maxBytes = positiveInteger(options.maxBytes ?? 64 * 1024 * 1024, "maxBytes");
126
+ }
127
+ static async load(options) {
128
+ const catalogPath = resolve(nonEmptyText(options.catalogPath, "catalogPath"));
129
+ const catalog = parseSkillCatalog(JSON.parse(await readFile(catalogPath, "utf8")));
130
+ const entries = /* @__PURE__ */ new Map();
131
+ for (const entry of catalog.skills) {
132
+ if (entries.has(entry.id)) {
133
+ throw new Error(`Skill catalog contains duplicate Skill ${entry.id}`);
134
+ }
135
+ entries.set(entry.id, {
136
+ ...entry,
137
+ path: isAbsolute(entry.path) ? entry.path : resolve(dirname(catalogPath), entry.path)
138
+ });
139
+ }
140
+ return new _FileSkillMaterializer(entries, options);
141
+ }
142
+ supports(item) {
143
+ return item.kind === "skill";
144
+ }
145
+ async materialize(item) {
146
+ const entry = this.#entries.get(item.reference);
147
+ if (entry === void 0) {
148
+ throw new Error(`Worker does not allow Skill ${JSON.stringify(item.reference)}`);
149
+ }
150
+ const requestedVersion = item.configuration?.version;
151
+ if (requestedVersion !== void 0 && requestedVersion !== entry.version) {
152
+ throw new Error(
153
+ `Skill ${item.reference} requires version ${requestedVersion}, but the Worker provides ${entry.version ?? "an unversioned Skill"}`
154
+ );
155
+ }
156
+ const digest = await digestContextPackage(entry.path, {
157
+ maxFiles: this.#maxFiles,
158
+ maxBytes: this.#maxBytes
159
+ });
160
+ const requestedDigest = item.configuration?.digest;
161
+ if (requestedDigest !== void 0 && normalizeSha256Digest(requestedDigest) !== digest) {
162
+ throw new Error(`Skill ${item.reference} does not match required digest ${requestedDigest}`);
163
+ }
164
+ const provenance = {
165
+ packageId: entry.id,
166
+ ...entry.version === void 0 ? {} : { version: entry.version }
167
+ };
168
+ return {
169
+ id: `skill:${entry.id}`,
170
+ kind: "skill",
171
+ required: true,
172
+ source: {
173
+ uri: pathToFileURL(entry.path).href,
174
+ digest,
175
+ provenance
176
+ }
177
+ };
178
+ }
179
+ };
180
+ var WorkspaceMaterializerRegistry = class {
181
+ #materializers;
182
+ constructor(materializers) {
183
+ this.#materializers = materializers;
184
+ }
185
+ async materialize(context) {
186
+ const contributions = [];
187
+ for (const materializer of this.#materializers) {
188
+ const resolved = await materializer.materialize(context);
189
+ if (resolved === void 0) continue;
190
+ contributions.push(...Array.isArray(resolved) ? resolved : [resolved]);
191
+ }
192
+ return contributions;
193
+ }
194
+ };
195
+ var ToolProvisionerRegistry = class {
196
+ #provisioners;
197
+ constructor(provisioners) {
198
+ const providers = provisioners.map((provisioner) => provisioner.provider);
199
+ if (new Set(providers).size !== providers.length) {
200
+ throw new Error("Only one Tool Provisioner may be installed for each provider");
201
+ }
202
+ this.#provisioners = provisioners;
203
+ }
204
+ async provision(context) {
205
+ const contributions = [];
206
+ for (const provisioner of this.#provisioners) {
207
+ const bundle = await provisioner.provision(context);
208
+ if (bundle === void 0) continue;
209
+ if (bundle.provider !== provisioner.provider) {
210
+ throw new Error(
211
+ `Tool Provisioner ${provisioner.provider} returned bundle for ${bundle.provider}`
212
+ );
213
+ }
214
+ contributions.push(...bundle.contributions);
215
+ }
216
+ return contributions;
217
+ }
218
+ };
219
+ function readMcpToolConfiguration(contribution) {
220
+ const configuration = contribution.configuration;
221
+ const serverName = nonEmptyConfigurationText(configuration["serverName"], "serverName");
222
+ const toolNames = configurationTextArray(configuration["toolNames"], "toolNames");
223
+ if (toolNames.length === 0) {
224
+ throw new Error(`Tool contribution ${contribution.id} must expose at least one tool`);
225
+ }
226
+ if (contribution.transport === "mcp-http") {
227
+ const url = nonEmptyConfigurationText(configuration["url"], "url");
228
+ const parsed = new URL(url);
229
+ if (parsed.protocol !== "https:") {
230
+ throw new Error(`Tool contribution ${contribution.id} MCP URL must use HTTPS`);
231
+ }
232
+ return { transport: "mcp-http", serverName, url: parsed.href, toolNames };
233
+ }
234
+ if (contribution.transport === "mcp-stdio") {
235
+ const command = nonEmptyConfigurationText(configuration["command"], "command");
236
+ const args = configurationTextArray(configuration["args"], "args");
237
+ return { transport: "mcp-stdio", serverName, command, args, toolNames };
238
+ }
239
+ throw new Error(`Tool contribution ${contribution.id} does not use an MCP transport`);
240
+ }
241
+ var InMemoryCheckpointStore = class {
242
+ #checkpoints = /* @__PURE__ */ new Map();
243
+ async load(ref) {
244
+ const checkpoint = this.#checkpoints.get(ref.id);
245
+ if (checkpoint === void 0 || checkpoint.ref.uri !== ref.uri || checkpoint.ref.format !== ref.format) {
246
+ return void 0;
247
+ }
248
+ return checkpoint;
249
+ }
250
+ async save(checkpoint) {
251
+ this.#checkpoints.set(checkpoint.ref.id, checkpoint);
252
+ }
253
+ async delete(ref) {
254
+ this.#checkpoints.delete(ref.id);
255
+ }
256
+ };
257
+ var FileCheckpointStore = class {
258
+ #directory;
259
+ constructor(directory) {
260
+ this.#directory = resolve(directory);
261
+ }
262
+ async load(ref) {
263
+ try {
264
+ const value = JSON.parse(await readFile(this.#path(ref), "utf8"));
265
+ if (!isPlainObject(value) || !isPlainObject(value["ref"]) || !isPlainObject(value["data"])) {
266
+ throw new Error(`Stored checkpoint ${ref.id} is invalid`);
267
+ }
268
+ const checkpoint = value;
269
+ if (checkpoint.ref.id !== ref.id || checkpoint.ref.uri !== ref.uri || checkpoint.ref.format !== ref.format) {
270
+ return void 0;
271
+ }
272
+ return checkpoint;
273
+ } catch (error) {
274
+ if (error.code === "ENOENT") return void 0;
275
+ throw error;
276
+ }
277
+ }
278
+ async save(checkpoint) {
279
+ await mkdir(this.#directory, { recursive: true, mode: 448 });
280
+ const path = this.#path(checkpoint.ref);
281
+ const temporary = `${path}.tmp`;
282
+ await writeFile(temporary, `${JSON.stringify(checkpoint)}
283
+ `, { mode: 384 });
284
+ await rename(temporary, path);
285
+ }
286
+ async delete(ref) {
287
+ await rm(this.#path(ref), { force: true });
288
+ }
289
+ #path(ref) {
290
+ const name = createHash("sha256").update(ref.id).digest("hex");
291
+ return join(this.#directory, `${name}.json`);
292
+ }
293
+ };
294
+ function executionContributions(context) {
295
+ return [
296
+ ...context.context.instructions,
297
+ ...context.context.skills,
298
+ ...context.context.priorWork,
299
+ ...context.context.resources,
300
+ ...context.workspace === void 0 ? [] : [context.workspace],
301
+ ...context.tools,
302
+ ...context.secrets,
303
+ ...context.checkpoints,
304
+ ...context.extensions
305
+ ];
306
+ }
307
+ function resolveHarnessContinuity(continuity, acceptsCheckpoint) {
308
+ if (continuity?.priorCheckpoint !== void 0 && acceptsCheckpoint(continuity.priorCheckpoint)) {
309
+ return {
310
+ mode: "resume",
311
+ sessionId: continuity.sessionId,
312
+ checkpoint: continuity.priorCheckpoint,
313
+ ...continuity.replayContribution === void 0 ? {} : { replayContribution: continuity.replayContribution }
314
+ };
315
+ }
316
+ if (continuity?.replayContribution !== void 0) {
317
+ return {
318
+ mode: "replay",
319
+ sessionId: continuity.sessionId,
320
+ replayContribution: continuity.replayContribution
321
+ };
322
+ }
323
+ return {
324
+ mode: "fresh",
325
+ ...continuity === void 0 ? {} : { sessionId: continuity.sessionId }
326
+ };
327
+ }
328
+ var WorkerRuntime = class {
329
+ #options;
330
+ #checkpointStore;
331
+ constructor(options) {
332
+ this.#options = options;
333
+ this.#checkpointStore = options.checkpointStore ?? new InMemoryCheckpointStore();
334
+ }
335
+ async describe() {
336
+ const harnessCapabilities = await Promise.all(
337
+ this.#options.harnesses.map((harness) => harness.describe())
338
+ );
339
+ const capabilities = [TASK_ATTEMPT_EVENT_STREAM_CAPABILITY];
340
+ if (harnessCapabilities.length > 0 && harnessCapabilities.every((capability) => capability.cancellation)) {
341
+ capabilities.push(TASK_ATTEMPT_CANCELLATION_CAPABILITY);
342
+ }
343
+ for (const provider of this.#options.environments) {
344
+ capabilities.push(...provider.capabilities);
345
+ }
346
+ return {
347
+ id: this.#options.id,
348
+ type: "runtime",
349
+ capabilities: uniqueCapabilities(capabilities),
350
+ profiles: this.#options.profiles.map((profile) => profile.ref),
351
+ ...this.#options.maxConcurrency === void 0 ? {} : { maxConcurrency: this.#options.maxConcurrency }
352
+ };
353
+ }
354
+ async *execute(spec, signal) {
355
+ const at = () => (/* @__PURE__ */ new Date()).toISOString();
356
+ const identity = { taskId: spec.taskId, attemptId: spec.attemptId };
357
+ yield { type: "execution.started", ...identity, at: at(), workerId: this.#options.id };
358
+ let environment;
359
+ let execution;
360
+ let reason = "failed";
361
+ try {
362
+ throwIfAborted(signal);
363
+ const profile = this.#profile(spec.workerProfile);
364
+ const harness = this.#harness(profile.harness.provider);
365
+ const provider = this.#environment(profile.execution.provider);
366
+ const harnessCapabilities = await harness.describe();
367
+ const materialized = this.#options.contextMaterializers === void 0 ? await requireEmptyContextPlan(spec) : await this.#options.contextMaterializers.materialize({ task: spec, profile });
368
+ const workspaceMaterialized = this.#options.workspaceMaterializers === void 0 ? [] : await this.#options.workspaceMaterializers.materialize({ task: spec, profile });
369
+ const provisionedTools = this.#options.toolProvisioners === void 0 ? [] : await this.#options.toolProvisioners.provision({ task: spec, profile });
370
+ const replayContribution = spec.session?.history === void 0 || spec.session.history.length === 0 ? void 0 : workRecordContribution({
371
+ id: `session-continuity:${spec.session.id}`,
372
+ records: spec.session.history,
373
+ source: {
374
+ uri: `supertag://sessions/${encodeURIComponent(spec.session.id)}/continuity`,
375
+ mediaType: "application/vnd.supertag.work-record+json;version=1",
376
+ provenance: { sessionId: spec.session.id, automatic: true }
377
+ }
378
+ });
379
+ const contributions = [
380
+ ...profile.instructions ?? [],
381
+ ...replayContribution === void 0 ? [] : [replayContribution],
382
+ ...materialized,
383
+ ...workspaceMaterialized,
384
+ ...provisionedTools
385
+ ];
386
+ const { accepted, omitted } = selectSupportedContributions(
387
+ contributions,
388
+ harness,
389
+ harnessCapabilities
390
+ );
391
+ const executionContext = executionContextFromContributions({
392
+ attempt: spec,
393
+ profile,
394
+ contributions: accepted,
395
+ checkpointStore: this.#checkpointStore,
396
+ ...spec.session === void 0 ? {} : {
397
+ continuity: {
398
+ sessionId: spec.session.id,
399
+ ...spec.session.checkpoint === void 0 ? {} : { priorCheckpoint: spec.session.checkpoint },
400
+ ...replayContribution === void 0 ? {} : { replayContribution }
401
+ }
402
+ }
403
+ });
404
+ const plan = await harness.plan(executionContext);
405
+ environment = await provider.provision({ task: spec, profile, plan }, signal);
406
+ if (harnessCapabilities.executionPlacements !== void 0 && !harnessCapabilities.executionPlacements.includes(environment.placement)) {
407
+ throw new Error(
408
+ `Harness ${harness.id} cannot run in a ${environment.placement} execution environment`
409
+ );
410
+ }
411
+ await environment.prepare(plan);
412
+ execution = await harness.start(plan, environment, executionContext);
413
+ const manifest = {
414
+ workerProfile: profile.ref,
415
+ harness: { id: harness.id, version: harnessCapabilities.version },
416
+ environment: { provider: provider.id, placement: environment.placement },
417
+ contributions: accepted.map(contributionManifest),
418
+ omitted
419
+ };
420
+ yield { type: "materialization.completed", ...identity, at: at(), manifest };
421
+ let finalOutput;
422
+ let resultSeen = false;
423
+ for await (const event of execution.run(signal)) {
424
+ throwIfAborted(signal);
425
+ if (event.type === "output.message") finalOutput = event.text;
426
+ if (event.type === "result") resultSeen = true;
427
+ yield harnessEventToTaskAttemptEvent(identity, at(), event);
428
+ }
429
+ if (!resultSeen && finalOutput !== void 0) {
430
+ yield {
431
+ type: "result",
432
+ ...identity,
433
+ at: at(),
434
+ result: defaultTaskResult(finalOutput)
435
+ };
436
+ }
437
+ const checkpoint = await execution.checkpoint?.();
438
+ if (checkpoint !== void 0) {
439
+ yield { type: "checkpoint.created", ...identity, at: at(), checkpoint };
440
+ }
441
+ reason = signal?.aborted === true ? "cancelled" : "completed";
442
+ await execution.close();
443
+ execution = void 0;
444
+ await environment.dispose(reason);
445
+ environment = void 0;
446
+ if (reason === "cancelled") {
447
+ throw abortError(signal);
448
+ }
449
+ yield { type: "execution.completed", ...identity, at: at() };
450
+ } catch (error) {
451
+ reason = signal?.aborted === true ? "cancelled" : "failed";
452
+ yield { type: "execution.failed", ...identity, at: at(), error: serializeError(error) };
453
+ } finally {
454
+ await execution?.close().catch(() => void 0);
455
+ await environment?.dispose(reason).catch(() => void 0);
456
+ }
457
+ }
458
+ #profile(ref) {
459
+ const profile = this.#options.profiles.find(
460
+ (candidate) => candidate.ref.id === ref.id && candidate.ref.revision === ref.revision
461
+ );
462
+ if (profile === void 0) {
463
+ throw new Error(`Worker Profile ${ref.id}@${ref.revision} is not available`);
464
+ }
465
+ return profile;
466
+ }
467
+ #harness(type) {
468
+ const harness = this.#options.harnesses.find((candidate) => candidate.id === type);
469
+ if (harness === void 0) {
470
+ throw new Error(`Harness ${type} is not installed`);
471
+ }
472
+ return harness;
473
+ }
474
+ #environment(type) {
475
+ const environment = this.#options.environments.find((candidate) => candidate.id === type);
476
+ if (environment === void 0) {
477
+ throw new Error(`Execution Environment Provider ${type} is not installed`);
478
+ }
479
+ return environment;
480
+ }
481
+ };
482
+ var LocalWorkerHost = class {
483
+ id;
484
+ #workers;
485
+ constructor(id, workers) {
486
+ this.id = id;
487
+ this.#workers = workers;
488
+ }
489
+ async describe() {
490
+ return {
491
+ id: this.id,
492
+ protocolVersion: 1,
493
+ workers: await Promise.all(this.#workers.map((w) => w.describe()))
494
+ };
495
+ }
496
+ async *execute(spec, signal) {
497
+ const descriptors = await Promise.all(
498
+ this.#workers.map(async (worker) => ({ worker, descriptor: await worker.describe() }))
499
+ );
500
+ const match = descriptors.find(
501
+ ({ descriptor }) => descriptor.profiles.some(
502
+ (profile) => profile.id === spec.workerProfile.id && profile.revision === spec.workerProfile.revision
503
+ )
504
+ );
505
+ if (match === void 0) {
506
+ yield {
507
+ type: "execution.failed",
508
+ taskId: spec.taskId,
509
+ attemptId: spec.attemptId,
510
+ at: (/* @__PURE__ */ new Date()).toISOString(),
511
+ error: {
512
+ name: "WorkerProfileUnavailableError",
513
+ message: `No Worker on host ${this.id} provides ${spec.workerProfile.id}@${spec.workerProfile.revision}`
514
+ }
515
+ };
516
+ return;
517
+ }
518
+ yield* match.worker.execute(spec, signal);
519
+ }
520
+ };
521
+ var StaticWorker = class {
522
+ #id;
523
+ #profile;
524
+ #text;
525
+ constructor(options = {}) {
526
+ this.#id = options.id ?? "static";
527
+ this.#profile = options.profile ?? { id: "static", revision: "1" };
528
+ this.#text = options.text ?? "SuperTag received your request. Gateway and connector smoke test succeeded.";
529
+ }
530
+ async describe() {
531
+ return {
532
+ id: this.#id,
533
+ type: "static",
534
+ capabilities: [TASK_ATTEMPT_EVENT_STREAM_CAPABILITY],
535
+ profiles: [this.#profile]
536
+ };
537
+ }
538
+ async *execute(spec) {
539
+ const at = (/* @__PURE__ */ new Date()).toISOString();
540
+ const identity = { taskId: spec.taskId, attemptId: spec.attemptId };
541
+ yield { type: "execution.started", ...identity, at, workerId: this.#id };
542
+ if (spec.workerProfile.id !== this.#profile.id || spec.workerProfile.revision !== this.#profile.revision) {
543
+ yield {
544
+ type: "execution.failed",
545
+ ...identity,
546
+ at,
547
+ error: {
548
+ name: "WorkerProfileUnavailableError",
549
+ message: `Worker Profile ${spec.workerProfile.id}@${spec.workerProfile.revision} is not available`
550
+ }
551
+ };
552
+ return;
553
+ }
554
+ yield {
555
+ type: "output.message",
556
+ ...identity,
557
+ at,
558
+ message: { role: "teammate", text: this.#text }
559
+ };
560
+ yield { type: "result", ...identity, at, result: defaultTaskResult(this.#text) };
561
+ yield { type: "execution.completed", ...identity, at };
562
+ }
563
+ };
564
+ var LocalProcessEnvironmentProvider = class {
565
+ id = "local-process";
566
+ capabilities = [LOCAL_PROCESS_CAPABILITY];
567
+ #options;
568
+ constructor(options = {}) {
569
+ this.#options = options;
570
+ }
571
+ async provision(spec) {
572
+ if (spec.profile.execution.lifetime.scope !== "attempt") {
573
+ throw new Error(
574
+ "The local-process provider currently supports only attempt-scoped environments"
575
+ );
576
+ }
577
+ const root = await mkdtemp(
578
+ join(this.#options.temporaryDirectory ?? tmpdir(), "supertag-attempt-")
579
+ );
580
+ return new LocalProcessEnvironment(root, this.#options);
581
+ }
582
+ };
583
+ var LocalProcessEnvironment = class {
584
+ id;
585
+ placement = "local";
586
+ rootDirectory;
587
+ #options;
588
+ #disposed = false;
589
+ constructor(root, options) {
590
+ this.id = `local:${root}`;
591
+ this.rootDirectory = root;
592
+ this.#options = options;
593
+ }
594
+ async prepare(plan) {
595
+ this.#assertOpen();
596
+ const readOnlyMounts = [];
597
+ for (const file of plan.files) {
598
+ const destination = this.resolvePath(file.path);
599
+ await mkdir(dirname(destination), { recursive: true });
600
+ await writeFile(
601
+ destination,
602
+ file.content,
603
+ file.mode === void 0 ? {} : { mode: file.mode }
604
+ );
605
+ }
606
+ for (const mount of plan.mounts) {
607
+ const source = localFileResourcePath(mount.source);
608
+ await assertSafeLocalResource(source);
609
+ const destination = this.resolvePath(mount.destination);
610
+ await mkdir(dirname(destination), { recursive: true });
611
+ const status = await lstat(source);
612
+ await cp(source, destination, {
613
+ recursive: status.isDirectory(),
614
+ errorOnExist: true,
615
+ force: false
616
+ });
617
+ if (mount.readOnly) readOnlyMounts.push(destination);
618
+ }
619
+ for (const destination of readOnlyMounts.toReversed()) await makeTreeReadOnly(destination);
620
+ if (plan.secretBindings.length > 0) {
621
+ throw new Error(
622
+ "The local-process provider requires a Secret Resolver before secret bindings can be used"
623
+ );
624
+ }
625
+ }
626
+ resolvePath(path) {
627
+ this.#assertOpen();
628
+ const destination = resolve(this.rootDirectory, path);
629
+ const traversal = relative(this.rootDirectory, destination);
630
+ if (traversal.startsWith("..") || isAbsolute(traversal)) {
631
+ throw new Error(`Environment path escapes its root: ${path}`);
632
+ }
633
+ return destination;
634
+ }
635
+ async read(path) {
636
+ return await readFile(this.resolvePath(path), "utf8");
637
+ }
638
+ async spawn(process2, signal) {
639
+ this.#assertOpen();
640
+ throwIfAborted(signal);
641
+ const inherited = this.#options.inheritedEnvironment ?? processEnvironment();
642
+ const child = spawn(process2.command, [...process2.args ?? []], {
643
+ cwd: process2.cwd ?? this.rootDirectory,
644
+ env: { ...inherited, ...process2.environment ?? {} },
645
+ stdio: ["pipe", "pipe", "pipe"]
646
+ });
647
+ const maxOutput = this.#options.maxOutputCharacters ?? 32e3;
648
+ let stdout = "";
649
+ let stderr = "";
650
+ child.stdout.setEncoding("utf8");
651
+ child.stderr.setEncoding("utf8");
652
+ child.stdout.on("data", (chunk) => {
653
+ stdout = appendBounded(stdout, chunk, maxOutput);
654
+ });
655
+ child.stderr.on("data", (chunk) => {
656
+ stderr = appendBounded(stderr, chunk, maxOutput);
657
+ });
658
+ child.stdin.end(process2.stdin);
659
+ let timedOut = false;
660
+ const timeout = process2.timeoutMs === void 0 ? void 0 : setTimeout(() => {
661
+ timedOut = true;
662
+ child.kill("SIGTERM");
663
+ }, process2.timeoutMs);
664
+ timeout?.unref();
665
+ const abort = () => child.kill("SIGTERM");
666
+ signal?.addEventListener("abort", abort, { once: true });
667
+ const wait = new Promise((resolveProcess, rejectProcess) => {
668
+ child.once("error", rejectProcess);
669
+ child.once("close", (exitCode, processSignal) => {
670
+ if (timeout !== void 0) clearTimeout(timeout);
671
+ signal?.removeEventListener("abort", abort);
672
+ if (timedOut) {
673
+ rejectProcess(new Error(`Process exceeded its ${process2.timeoutMs}ms execution limit`));
674
+ return;
675
+ }
676
+ if (signal?.aborted === true) {
677
+ rejectProcess(abortError(signal));
678
+ return;
679
+ }
680
+ resolveProcess({
681
+ exitCode,
682
+ ...processSignal === null ? {} : { signal: processSignal },
683
+ stdout,
684
+ stderr
685
+ });
686
+ });
687
+ });
688
+ return {
689
+ ...child.pid === void 0 ? {} : { pid: child.pid },
690
+ wait: async () => await wait,
691
+ kill: (requestedSignal = "SIGTERM") => child.kill(requestedSignal)
692
+ };
693
+ }
694
+ async dispose() {
695
+ if (this.#disposed) return;
696
+ this.#disposed = true;
697
+ await makeTreeWritable(this.rootDirectory).catch(() => void 0);
698
+ await rm(this.rootDirectory, { recursive: true, force: true });
699
+ }
700
+ #assertOpen() {
701
+ if (this.#disposed) throw new Error(`Execution Environment ${this.id} has been disposed`);
702
+ }
703
+ };
704
+ async function collectTaskAttemptEvents(events) {
705
+ const collected = [];
706
+ for await (const event of events) collected.push(event);
707
+ return collected;
708
+ }
709
+ function terminalOutputText(events) {
710
+ const failure = events.findLast((event) => event.type === "execution.failed");
711
+ if (failure?.type === "execution.failed") {
712
+ throw new Error(failure.error.message);
713
+ }
714
+ if (!events.some((event) => event.type === "execution.completed")) {
715
+ throw new Error("Task Attempt event stream ended without a terminal event");
716
+ }
717
+ const message = events.findLast((event) => event.type === "output.message");
718
+ if (message?.type !== "output.message") {
719
+ throw new Error("Task Attempt completed without a teammate output message");
720
+ }
721
+ return message.message.text;
722
+ }
723
+ function terminalTaskResult(events) {
724
+ const failure = events.findLast((event) => event.type === "execution.failed");
725
+ if (failure?.type === "execution.failed") throw new Error(failure.error.message);
726
+ const result = events.findLast((event) => event.type === "result");
727
+ if (result?.type === "result") return result.result;
728
+ return defaultTaskResult(terminalOutputText(events));
729
+ }
730
+ function defaultTaskResult(summary) {
731
+ return {
732
+ summary,
733
+ decisions: [],
734
+ changes: [],
735
+ unresolved: [],
736
+ references: [],
737
+ artifacts: []
738
+ };
739
+ }
740
+ async function executeToTerminalOutput(worker, spec, signal) {
741
+ return terminalOutputText(await collectTaskAttemptEvents(worker.execute(spec, signal)));
742
+ }
743
+ function isTagActionAllowed(task, input) {
744
+ return task.authorization.resources.some(
745
+ (resource) => resource.connectorAccountId === input.connectorAccountId && resource.scope === input.scope && resource.actions.includes(input.action)
746
+ );
747
+ }
748
+ function assertTagActionAllowed(task, input) {
749
+ if (!isTagActionAllowed(task, input)) {
750
+ throw new Error(`Tag ${task.tag.name} is not allowed to ${input.action} on ${input.scope}`);
751
+ }
752
+ }
753
+ function isTagContextItemEligible(task, itemKey) {
754
+ return task.contextPlan.sets.some((set) => set.items.some((item) => item.itemKey === itemKey));
755
+ }
756
+ function assertTagContextItemEligible(task, itemKey) {
757
+ if (!isTagContextItemEligible(task, itemKey)) {
758
+ throw new Error(`Tag ${task.tag.name} cannot incorporate Context Item ${itemKey}`);
759
+ }
760
+ }
761
+ function executionContextFromContributions(input) {
762
+ const workspaces = input.contributions.filter(
763
+ (contribution) => contribution.kind === "workspace"
764
+ );
765
+ if (workspaces.length > 1) {
766
+ throw new Error("A Task Attempt may materialize at most one operational workspace");
767
+ }
768
+ return {
769
+ attempt: input.attempt,
770
+ profile: input.profile,
771
+ context: {
772
+ instructions: input.contributions.filter(
773
+ (contribution) => contribution.kind === "instruction"
774
+ ),
775
+ skills: input.contributions.filter(
776
+ (contribution) => contribution.kind === "skill"
777
+ ),
778
+ priorWork: input.contributions.filter(
779
+ (contribution) => contribution.kind === "work-context"
780
+ ),
781
+ resources: input.contributions.filter(
782
+ (contribution) => contribution.kind === "resource"
783
+ )
784
+ },
785
+ ...workspaces[0] === void 0 ? {} : { workspace: workspaces[0] },
786
+ tools: input.contributions.filter(
787
+ (contribution) => contribution.kind === "tool"
788
+ ),
789
+ ...input.continuity === void 0 ? {} : { continuity: input.continuity },
790
+ secrets: input.contributions.filter(
791
+ (contribution) => contribution.kind === "secret"
792
+ ),
793
+ checkpoints: input.contributions.filter(
794
+ (contribution) => contribution.kind === "checkpoint"
795
+ ),
796
+ extensions: input.contributions.filter(
797
+ (contribution) => contribution.kind === "harness-specific"
798
+ ),
799
+ checkpointStore: input.checkpointStore
800
+ };
801
+ }
802
+ function selectSupportedContributions(contributions, harness, capabilities) {
803
+ const accepted = [];
804
+ const omitted = [];
805
+ for (const contribution of contributions) {
806
+ const supported = capabilities.contributionKinds.includes(contribution.kind) && (contribution.kind !== "harness-specific" || contribution.harness === harness.id);
807
+ if (supported) {
808
+ accepted.push(contribution);
809
+ continue;
810
+ }
811
+ const reason = `Harness ${harness.id} does not support ${contribution.kind} contributions`;
812
+ if (contribution.required)
813
+ throw new Error(`${reason}; required contribution ${contribution.id} cannot be omitted`);
814
+ omitted.push({ ...contributionManifest(contribution), reason });
815
+ }
816
+ return { accepted, omitted };
817
+ }
818
+ function contributionManifest(contribution) {
819
+ const source = "source" in contribution ? contribution.source : void 0;
820
+ const hasResourceMetadata = source !== void 0 && (source.mediaType !== void 0 || source.digest !== void 0 || source.provenance !== void 0);
821
+ return {
822
+ id: contribution.id,
823
+ kind: contribution.kind,
824
+ ...contribution.sourceItemKey === void 0 ? {} : { sourceItemKey: contribution.sourceItemKey },
825
+ ...hasResourceMetadata ? {
826
+ resource: {
827
+ ...source.mediaType === void 0 ? {} : { mediaType: source.mediaType },
828
+ ...source.digest === void 0 ? {} : { digest: source.digest },
829
+ ...source.provenance === void 0 ? {} : { provenance: source.provenance }
830
+ }
831
+ } : {}
832
+ };
833
+ }
834
+ function parseSkillCatalog(value) {
835
+ if (!isPlainObject(value) || value["version"] !== 1 || !Array.isArray(value["skills"])) {
836
+ throw new Error("Skill catalog must have version 1 and a skills array");
837
+ }
838
+ return {
839
+ version: 1,
840
+ skills: value["skills"].map((entry, index) => parseSkillCatalogEntry(entry, index))
841
+ };
842
+ }
843
+ function parseSkillCatalogEntry(value, index) {
844
+ if (!isPlainObject(value)) {
845
+ throw new Error(`Skill catalog entry ${index} must be an object`);
846
+ }
847
+ const id = packageIdentifier(value["id"], `skills[${index}].id`);
848
+ const path = nonEmptyUnknownText(value["path"], `skills[${index}].path`);
849
+ const version = optionalUnknownText(value["version"], `skills[${index}].version`);
850
+ const allowed = /* @__PURE__ */ new Set(["id", "path", "version"]);
851
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
852
+ if (unknown.length > 0) {
853
+ throw new Error(`Skill catalog entry ${index} has unknown fields: ${unknown.join(", ")}`);
854
+ }
855
+ return {
856
+ id,
857
+ path,
858
+ ...version === void 0 ? {} : { version }
859
+ };
860
+ }
861
+ async function digestContextPackage(root, limits) {
862
+ const rootStatus = await lstat(root).catch((error) => {
863
+ throw new Error(`Context package path is unavailable: ${root}`, { cause: error });
864
+ });
865
+ if (!rootStatus.isDirectory() || rootStatus.isSymbolicLink()) {
866
+ throw new Error(`Context package path must be a non-symbolic directory: ${root}`);
867
+ }
868
+ const hash = createHash("sha256");
869
+ let files = 0;
870
+ let bytes = 0;
871
+ const visit = async (path, packagePath) => {
872
+ const status = await lstat(path).catch((error) => {
873
+ throw new Error(`Context package path is unavailable: ${root}`, { cause: error });
874
+ });
875
+ if (status.isSymbolicLink()) {
876
+ throw new Error(`Context package cannot contain symbolic links: ${packagePath || "."}`);
877
+ }
878
+ if (status.isDirectory()) {
879
+ hash.update(`directory\0${packagePath}\0`);
880
+ for (const entry of (await readdir(path)).toSorted()) {
881
+ await visit(join(path, entry), packagePath === "" ? entry : `${packagePath}/${entry}`);
882
+ }
883
+ return;
884
+ }
885
+ if (!status.isFile()) {
886
+ throw new Error(`Context package contains unsupported entry: ${packagePath}`);
887
+ }
888
+ files += 1;
889
+ bytes += status.size;
890
+ if (files > limits.maxFiles || bytes > limits.maxBytes) {
891
+ throw new Error(
892
+ `Context package exceeds Worker limits (${limits.maxFiles} files, ${limits.maxBytes} bytes)`
893
+ );
894
+ }
895
+ hash.update(`file\0${packagePath}\0${status.mode & 511}\0${status.size}\0`);
896
+ hash.update(await readFile(path));
897
+ hash.update("\0");
898
+ };
899
+ await visit(root, "");
900
+ return `sha256:${hash.digest("hex")}`;
901
+ }
902
+ function normalizeSha256Digest(value) {
903
+ const digest = value.trim().toLowerCase();
904
+ if (!/^sha256:[a-f0-9]{64}$/.test(digest)) {
905
+ throw new Error("Context package digest must use sha256:<64 lowercase hexadecimal characters>");
906
+ }
907
+ return digest;
908
+ }
909
+ function packageIdentifier(value, label) {
910
+ const result = nonEmptyUnknownText(value, label);
911
+ if (!/^[a-z0-9][a-z0-9._:@/-]{0,127}$/i.test(result) || result.includes("..")) {
912
+ throw new Error(`${label} contains unsupported characters`);
913
+ }
914
+ return result;
915
+ }
916
+ function nonEmptyUnknownText(value, label) {
917
+ if (typeof value !== "string") throw new Error(`${label} must be a string`);
918
+ return nonEmptyText(value, label);
919
+ }
920
+ function optionalUnknownText(value, label) {
921
+ return value === void 0 ? void 0 : nonEmptyUnknownText(value, label);
922
+ }
923
+ function nonEmptyConfigurationText(value, field) {
924
+ return nonEmptyUnknownText(value, `MCP configuration ${field}`);
925
+ }
926
+ function configurationTextArray(value, field) {
927
+ if (!Array.isArray(value)) throw new Error(`MCP configuration ${field} must be an array`);
928
+ return value.map(
929
+ (entry, index) => nonEmptyUnknownText(entry, `MCP configuration ${field}[${index}]`)
930
+ );
931
+ }
932
+ function nonEmptyText(value, label) {
933
+ const result = value.trim();
934
+ if (result.length === 0) throw new Error(`${label} must not be empty`);
935
+ return result;
936
+ }
937
+ function positiveInteger(value, label) {
938
+ if (!Number.isSafeInteger(value) || value < 1)
939
+ throw new Error(`${label} must be a positive integer`);
940
+ return value;
941
+ }
942
+ function isPlainObject(value) {
943
+ return typeof value === "object" && value !== null && !Array.isArray(value);
944
+ }
945
+ function boundedText(value, limit) {
946
+ if (value.length <= limit) return value;
947
+ return `${value.slice(0, limit)}
948
+ [truncated]`;
949
+ }
950
+ function localFileResourcePath(resource) {
951
+ let url;
952
+ try {
953
+ url = new URL(resource.uri);
954
+ } catch {
955
+ throw new Error(`Resource ${resource.uri} is not a valid URI`);
956
+ }
957
+ if (url.protocol !== "file:") {
958
+ throw new Error(
959
+ `Local process environments can only stage file: resources, received ${url.protocol}`
960
+ );
961
+ }
962
+ return fileURLToPath(url);
963
+ }
964
+ async function assertSafeLocalResource(path) {
965
+ const status = await lstat(path);
966
+ if (status.isSymbolicLink()) throw new Error(`Workspace resource contains symbolic link ${path}`);
967
+ if (status.isDirectory()) {
968
+ for (const entry of await readdir(path)) await assertSafeLocalResource(join(path, entry));
969
+ } else if (!status.isFile()) {
970
+ throw new Error(`Workspace resource contains unsupported entry ${path}`);
971
+ }
972
+ }
973
+ async function makeTreeReadOnly(path) {
974
+ const status = await lstat(path);
975
+ if (status.isDirectory()) {
976
+ for (const entry of await readdir(path)) await makeTreeReadOnly(join(path, entry));
977
+ await chmod(path, 365);
978
+ } else {
979
+ await chmod(path, status.mode & 73 ? 365 : 292);
980
+ }
981
+ }
982
+ async function makeTreeWritable(path) {
983
+ const status = await lstat(path);
984
+ if (status.isDirectory()) {
985
+ await chmod(path, status.mode | 448);
986
+ for (const entry of await readdir(path)) await makeTreeWritable(join(path, entry));
987
+ } else {
988
+ await chmod(path, status.mode | 384);
989
+ }
990
+ }
991
+ async function requireEmptyContextPlan(spec) {
992
+ const firstItem = spec.contextPlan.sets.flatMap((set) => set.items)[0];
993
+ if (firstItem !== void 0) {
994
+ throw new Error(
995
+ `No Context Materializer Registry is configured for ${firstItem.kind}:${firstItem.itemKey}`
996
+ );
997
+ }
998
+ return [];
999
+ }
1000
+ function harnessEventToTaskAttemptEvent(identity, at, event) {
1001
+ switch (event.type) {
1002
+ case "output.delta":
1003
+ return { type: event.type, ...identity, at, text: event.text };
1004
+ case "output.message":
1005
+ return { type: event.type, ...identity, at, message: { role: "teammate", text: event.text } };
1006
+ case "result":
1007
+ return { type: event.type, ...identity, at, result: event.result };
1008
+ case "artifact.created":
1009
+ return { type: event.type, ...identity, at, artifact: event.artifact };
1010
+ case "checkpoint.created":
1011
+ return { type: event.type, ...identity, at, checkpoint: event.checkpoint };
1012
+ case "approval.requested":
1013
+ return { type: event.type, ...identity, at, request: event.request };
1014
+ }
1015
+ }
1016
+ function uniqueCapabilities(capabilities) {
1017
+ return [
1018
+ ...new Map(
1019
+ capabilities.map((capability) => [`${capability.id}@${capability.version}`, capability])
1020
+ ).values()
1021
+ ];
1022
+ }
1023
+ function serializeError(error) {
1024
+ return error instanceof Error ? { name: error.name, message: error.message } : { name: "Error", message: String(error) };
1025
+ }
1026
+ function localPackagePath(uri, kind) {
1027
+ let url;
1028
+ try {
1029
+ url = new URL(uri);
1030
+ } catch (error) {
1031
+ throw new Error(`${kind} package source is not a valid URI`, { cause: error });
1032
+ }
1033
+ if (url.protocol !== "file:") {
1034
+ throw new Error(`Harnesses currently require Worker-local file: ${kind} packages`);
1035
+ }
1036
+ return fileURLToPath(url);
1037
+ }
1038
+ async function requireSkillPackage(path, id) {
1039
+ await requirePackageDirectory(path, `Skill ${id}`);
1040
+ const status = await lstat(join(path, "SKILL.md")).catch(() => void 0);
1041
+ if (status?.isFile() !== true) throw new Error(`Skill ${id} is missing SKILL.md`);
1042
+ }
1043
+ async function requirePackageDirectory(path, label) {
1044
+ const metadata = await lstat(path).catch(() => void 0);
1045
+ if (metadata?.isDirectory() !== true) throw new Error(`${label} is not a directory: ${path}`);
1046
+ }
1047
+ function throwIfAborted(signal) {
1048
+ if (signal?.aborted === true) throw abortError(signal);
1049
+ }
1050
+ function abortError(signal) {
1051
+ const reason = signal?.reason;
1052
+ return reason instanceof Error ? reason : new Error(reason === void 0 ? "Task Attempt cancelled" : String(reason));
1053
+ }
1054
+ function processEnvironment() {
1055
+ return Object.fromEntries(
1056
+ Object.entries(process.env).filter(
1057
+ (entry) => entry[1] !== void 0
1058
+ )
1059
+ );
1060
+ }
1061
+ function appendBounded(current, chunk, limit) {
1062
+ const combined = current + chunk;
1063
+ return combined.length <= limit ? combined : combined.slice(combined.length - limit);
1064
+ }
1065
+
1066
+ export { ContextMaterializerRegistry, FileCheckpointStore, FileSkillMaterializer, InMemoryCheckpointStore, LOCAL_PROCESS_CAPABILITY, LocalProcessEnvironmentProvider, LocalWorkerHost, StaticWorker, TASK_ATTEMPT_CANCELLATION_CAPABILITY, TASK_ATTEMPT_EVENT_STREAM_CAPABILITY, ToolProvisionerRegistry, WorkRecordMaterializer, WorkerRuntime, WorkspaceMaterializerRegistry, assertTagActionAllowed, assertTagContextItemEligible, collectTaskAttemptEvents, defaultTaskResult, executeToTerminalOutput, executionContributions, isTagActionAllowed, isTagContextItemEligible, readMcpToolConfiguration, resolveHarnessContinuity, resolveSkillPackages, terminalOutputText, terminalTaskResult };
1067
+ //# sourceMappingURL=chunk-ES42FTPC.js.map
1068
+ //# sourceMappingURL=chunk-ES42FTPC.js.map