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,1215 @@
1
+ import { WORK_RECORD_ARTIFACT_KIND } from './chunk-B3EVEGNZ.js';
2
+ import { terminalOutputText, terminalTaskResult } from './chunk-ES42FTPC.js';
3
+ import { randomUUID, createHash } from 'crypto';
4
+
5
+ var DEFAULT_POLL_INTERVAL_MS = 1e3;
6
+ var DEFAULT_LEASE_DURATION_MS = 5 * 6e4;
7
+ var DEFAULT_RETRY_BASE_MS = 1e3;
8
+ var DEFAULT_MAX_ATTEMPTS = 5;
9
+ var MAX_PRIOR_TASKS_PER_PLAN = 5;
10
+ var MAX_SESSION_HISTORY_TASKS = 5;
11
+ var MAX_PRIOR_INTENT_CHARACTERS = 2e3;
12
+ var MAX_PRIOR_RESPONSE_CHARACTERS = 4e3;
13
+ var HARNESS_CHECKPOINT_ARTIFACT_KIND = "supertag.harness-checkpoint.v1";
14
+ var HARNESS_CHECKPOINT_METADATA_VERSION = 1;
15
+ var Gateway = class {
16
+ #store;
17
+ #credentialVault;
18
+ #onInboundEvent;
19
+ #worker;
20
+ #reply;
21
+ #instanceId;
22
+ #pollIntervalMs;
23
+ #leaseDurationMs;
24
+ #retryBaseMs;
25
+ #maxAttempts;
26
+ #onDispatchError;
27
+ #accepting = false;
28
+ #running = false;
29
+ #stopping = false;
30
+ #taskControllerDrained = false;
31
+ #taskControllerLoop;
32
+ #deliveryControllerLoop;
33
+ #wakeTaskController;
34
+ #wakeDeliveryController;
35
+ #activeAdmissions = 0;
36
+ #admissionsDrained;
37
+ constructor(dependencies) {
38
+ if (dependencies.worker === void 0 !== (dependencies.reply === void 0)) {
39
+ throw new Error("Gateway worker and reply handler must be configured together");
40
+ }
41
+ this.#store = dependencies.store;
42
+ this.#credentialVault = dependencies.credentialVault;
43
+ this.#onInboundEvent = dependencies.onInboundEvent;
44
+ this.#worker = dependencies.worker;
45
+ this.#reply = dependencies.reply;
46
+ this.#instanceId = dependencies.dispatch?.instanceId ?? randomUUID();
47
+ this.#pollIntervalMs = positiveDuration(
48
+ dependencies.dispatch?.pollIntervalMs,
49
+ DEFAULT_POLL_INTERVAL_MS,
50
+ "pollIntervalMs"
51
+ );
52
+ this.#leaseDurationMs = positiveDuration(
53
+ dependencies.dispatch?.leaseDurationMs,
54
+ DEFAULT_LEASE_DURATION_MS,
55
+ "leaseDurationMs"
56
+ );
57
+ this.#retryBaseMs = positiveDuration(
58
+ dependencies.dispatch?.retryBaseMs,
59
+ DEFAULT_RETRY_BASE_MS,
60
+ "retryBaseMs"
61
+ );
62
+ this.#maxAttempts = positiveInteger(
63
+ dependencies.dispatch?.maxAttempts,
64
+ DEFAULT_MAX_ATTEMPTS,
65
+ "maxAttempts"
66
+ );
67
+ this.#onDispatchError = dependencies.dispatch?.onDispatchError;
68
+ }
69
+ get isAccepting() {
70
+ return this.#accepting;
71
+ }
72
+ get isRunning() {
73
+ return this.#running;
74
+ }
75
+ get controllerStatuses() {
76
+ const phase = this.#worker === void 0 ? "disabled" : this.#stopping ? "draining" : this.#running ? "running" : "stopped";
77
+ return [
78
+ { name: "task-dispatch", phase },
79
+ { name: "reply-delivery", phase }
80
+ ];
81
+ }
82
+ async start() {
83
+ if (this.#running) {
84
+ return;
85
+ }
86
+ await this.#store.connect();
87
+ this.#stopping = false;
88
+ this.#taskControllerDrained = false;
89
+ this.#running = true;
90
+ this.#accepting = true;
91
+ if (this.#worker !== void 0) {
92
+ this.#taskControllerLoop = this.#runTaskController();
93
+ this.#deliveryControllerLoop = this.#runDeliveryController();
94
+ }
95
+ }
96
+ async stop() {
97
+ if (!this.#running) {
98
+ return;
99
+ }
100
+ this.#accepting = false;
101
+ await this.#waitForAdmissions();
102
+ this.#stopping = true;
103
+ this.#wakeTaskController?.();
104
+ this.#wakeDeliveryController?.();
105
+ await Promise.all([this.#taskControllerLoop, this.#deliveryControllerLoop]);
106
+ this.#running = false;
107
+ this.#taskControllerLoop = void 0;
108
+ this.#deliveryControllerLoop = void 0;
109
+ await this.#store.disconnect();
110
+ }
111
+ async setupConnectorAccount(verified) {
112
+ const credentialId = `connector/${verified.provider}/${verified.externalAccountId}`;
113
+ const priorCredential = await this.#credentialVault.resolve(credentialId);
114
+ await this.#credentialVault.store(credentialId, verified.secrets);
115
+ try {
116
+ return await this.#store.saveConnectorAccount({
117
+ provider: verified.provider,
118
+ externalAccountId: verified.externalAccountId,
119
+ displayName: verified.displayName,
120
+ authMethod: verified.authMethod,
121
+ credentialId,
122
+ status: "connected",
123
+ configuration: verified.configuration,
124
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
125
+ });
126
+ } catch (error) {
127
+ if (priorCredential === void 0) {
128
+ await this.#credentialVault.delete(credentialId);
129
+ } else {
130
+ await this.#credentialVault.store(credentialId, priorCredential);
131
+ }
132
+ throw error;
133
+ }
134
+ }
135
+ async ingestConnectorEvent(event) {
136
+ if (!this.#accepting) {
137
+ throw new Error("Gateway is stopped or draining and is not accepting inbound events");
138
+ }
139
+ this.#activeAdmissions += 1;
140
+ try {
141
+ const identity = await this.#resolveInvocationIdentity(event);
142
+ if (identity.status === "unconfigured") {
143
+ return {
144
+ status: "unconfigured",
145
+ connectorAccountId: identity.account.id,
146
+ eventId: event.eventId
147
+ };
148
+ }
149
+ const { account, presence, tag } = identity;
150
+ if ((event.provider === "slack" || event.provider === "lark") && event.kind === "message" && await this.#store.findSessionByTagAndKey(tag.id, event.sessionKey) === void 0) {
151
+ return {
152
+ status: "ignored",
153
+ connectorAccountId: account.id,
154
+ eventId: event.eventId,
155
+ tagPresenceId: presence.id,
156
+ tagId: tag.id
157
+ };
158
+ }
159
+ const capturedAt = (/* @__PURE__ */ new Date()).toISOString();
160
+ const [authorization, contextPlan] = await Promise.all([
161
+ this.#captureAuthorization(event, account, presence, tag, capturedAt),
162
+ this.#captureContextPlan(event, account, presence, capturedAt)
163
+ ]);
164
+ const admission = await this.#store.admitInboundEvent({
165
+ connectorAccountId: account.id,
166
+ tagPresenceId: presence.id,
167
+ tagId: tag.id,
168
+ authorization,
169
+ contextPlan,
170
+ event,
171
+ maxAttempts: this.#maxAttempts
172
+ });
173
+ const task = await this.#openTask(admission.work);
174
+ if (admission.status === "duplicate") {
175
+ return {
176
+ status: "duplicate",
177
+ connectorAccountId: account.id,
178
+ eventId: event.eventId,
179
+ inboundEventId: admission.work.id,
180
+ taskId: task.id,
181
+ tagPresenceId: presence.id,
182
+ tagId: tag.id
183
+ };
184
+ }
185
+ await this.#appendTaskEvent(task.id, "task.admitted", {
186
+ tagPresenceId: presence.id,
187
+ scope: event.scope,
188
+ contextSetIds: contextPlan.sets.map((set) => set.id)
189
+ });
190
+ await this.#enqueuePresentation(admission.work, {
191
+ workerId: "gateway",
192
+ presentation: "acknowledgement",
193
+ deliveryKey: "acknowledgement",
194
+ text: acknowledgementText(task)
195
+ });
196
+ this.#wakeTaskController?.();
197
+ this.#wakeDeliveryController?.();
198
+ return {
199
+ status: "accepted",
200
+ connectorAccountId: account.id,
201
+ eventId: event.eventId,
202
+ inboundEventId: admission.work.id,
203
+ taskId: task.id,
204
+ tagPresenceId: presence.id,
205
+ tagId: tag.id
206
+ };
207
+ } finally {
208
+ this.#activeAdmissions -= 1;
209
+ if (this.#activeAdmissions === 0) {
210
+ this.#admissionsDrained?.();
211
+ this.#admissionsDrained = void 0;
212
+ }
213
+ }
214
+ }
215
+ async #resolveInvocationIdentity(event) {
216
+ const account = await this.#store.findConnectorAccount(event.provider, event.externalAccountId);
217
+ if (account === void 0) {
218
+ throw new Error(`No connected ${event.provider} account matches ${event.externalAccountId}`);
219
+ }
220
+ const presence = await this.#store.resolveTagPresence(account.id, event.scope);
221
+ if (presence === void 0) return { status: "unconfigured", account };
222
+ if (presence.connectorAccountId !== account.id || presence.scope !== event.scope) {
223
+ throw new Error("Resolved Tag presence does not match the authenticated invocation surface");
224
+ }
225
+ const tag = await this.#store.findTagById(presence.tagId);
226
+ if (tag === void 0) {
227
+ throw new Error(`Tag ${presence.tagId} for presence ${presence.id} no longer exists`);
228
+ }
229
+ return { status: "resolved", account, presence, tag };
230
+ }
231
+ async #runTaskController() {
232
+ try {
233
+ while (this.#running) {
234
+ try {
235
+ if (!await this.#reconcileNextTask() && this.#running) {
236
+ if (this.#stopping) break;
237
+ await this.#waitForDispatch("inbound");
238
+ }
239
+ } catch (error) {
240
+ this.#reportDispatchError(error);
241
+ if (this.#stopping) break;
242
+ if (this.#running) await this.#waitForDispatch("inbound");
243
+ }
244
+ }
245
+ } finally {
246
+ this.#taskControllerDrained = true;
247
+ this.#wakeDeliveryController?.();
248
+ }
249
+ }
250
+ async #runDeliveryController() {
251
+ while (this.#running) {
252
+ try {
253
+ if (!await this.#reconcileNextDelivery() && this.#running) {
254
+ if (this.#stopping && this.#taskControllerDrained) break;
255
+ await this.#waitForDispatch("outbound");
256
+ }
257
+ } catch (error) {
258
+ this.#reportDispatchError(error);
259
+ if (this.#stopping && this.#taskControllerDrained) break;
260
+ if (this.#running) await this.#waitForDispatch("outbound");
261
+ }
262
+ }
263
+ }
264
+ async #reconcileNextTask() {
265
+ if (this.#worker === void 0) {
266
+ return false;
267
+ }
268
+ try {
269
+ await this.#worker.describe();
270
+ } catch {
271
+ return false;
272
+ }
273
+ const work = await this.#store.claimNextInboundEvent(this.#claimInput());
274
+ if (work === void 0) {
275
+ return false;
276
+ }
277
+ let task;
278
+ let attempt;
279
+ try {
280
+ const account = await this.#store.findConnectorAccountById(work.connectorAccountId);
281
+ if (account === void 0) {
282
+ throw new Error(`Connector account ${work.connectorAccountId} no longer exists`);
283
+ }
284
+ await this.#onInboundEvent?.(work.event, account, {
285
+ tagPresenceId: work.tagPresenceId,
286
+ tagId: work.tagId
287
+ });
288
+ task = await this.#openTask(work);
289
+ attempt = await this.#openTaskAttempt(work, task);
290
+ const workerEvents = [];
291
+ for await (const event of this.#worker.execute(
292
+ await this.#taskAttemptSpec(work, task, attempt)
293
+ )) {
294
+ workerEvents.push(event);
295
+ await this.#recordWorkerEvent(task.id, attempt.id, event);
296
+ if (event.type === "materialization.completed" && event.manifest.harness.id !== "static") {
297
+ await this.#enqueuePresentation(work, {
298
+ workerId: this.#worker.id,
299
+ presentation: "status",
300
+ deliveryKey: `attempt:${attempt.id}:materialized`,
301
+ text: materializationStatusText(task, event.manifest)
302
+ });
303
+ this.#wakeDeliveryController?.();
304
+ }
305
+ }
306
+ const responseText = terminalOutputText(workerEvents);
307
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
308
+ const workRecord = await this.#persistWorkRecord(
309
+ work,
310
+ task,
311
+ responseText,
312
+ workerEvents,
313
+ completedAt
314
+ );
315
+ await this.#store.completeInboundEvent({
316
+ inboundEventId: work.id,
317
+ leaseOwner: this.#instanceId,
318
+ workerId: this.#worker.id,
319
+ responseText: finalResultText(responseText, workRecord),
320
+ completedAt
321
+ });
322
+ await this.#closeTaskAttempt(attempt, "completed", {
323
+ responseLength: responseText.length
324
+ });
325
+ await this.#closeTask(task, "completed", { responseLength: responseText.length });
326
+ await this.#persistHarnessCheckpoint(work, task, workerEvents, completedAt).catch(
327
+ (error) => this.#reportDispatchError(error)
328
+ );
329
+ this.#wakeDeliveryController?.();
330
+ } catch (error) {
331
+ if (attempt !== void 0) {
332
+ await this.#closeTaskAttempt(attempt, "failed", { error: errorMessage(error) });
333
+ }
334
+ const retryStatus = await this.#retryInbound(work, error);
335
+ if (task !== void 0 && retryStatus === "failed") {
336
+ await this.#closeTask(task, "failed", { error: errorMessage(error) });
337
+ await this.#enqueuePresentation(work, {
338
+ workerId: this.#worker?.id ?? "gateway",
339
+ presentation: "error",
340
+ deliveryKey: "final",
341
+ text: failureText(task, error)
342
+ });
343
+ this.#wakeDeliveryController?.();
344
+ }
345
+ this.#reportDispatchError(error);
346
+ }
347
+ return true;
348
+ }
349
+ async #taskAttemptSpec(work, task, attempt) {
350
+ const text = work.event.text?.trim();
351
+ const checkpoint = await this.#compatibleHarnessCheckpoint(work, task);
352
+ return {
353
+ version: 1,
354
+ taskId: task.id,
355
+ attemptId: attempt.id,
356
+ tag: { id: work.authorization.tag.id, name: work.authorization.tag.name },
357
+ input: {
358
+ origin: {
359
+ surface: work.event.provider,
360
+ accountId: work.connectorAccountId,
361
+ scope: work.event.scope,
362
+ sessionKey: work.event.sessionKey,
363
+ occurredAt: work.event.occurredAt,
364
+ source: work.event.source,
365
+ metadata: work.event.metadata
366
+ },
367
+ messages: text === void 0 || text.length === 0 ? [] : [
368
+ {
369
+ id: work.event.eventId,
370
+ role: "requester",
371
+ text,
372
+ actor: work.event.actor
373
+ }
374
+ ]
375
+ },
376
+ authorization: work.authorization,
377
+ contextPlan: work.contextPlan,
378
+ workspacePlan: task.workspacePlan,
379
+ workerProfile: work.authorization.tag.workerProfile,
380
+ session: {
381
+ id: task.sessionId,
382
+ ...checkpoint === void 0 ? {} : { checkpoint },
383
+ ...task.sessionHistory.length === 0 ? {} : { history: task.sessionHistory }
384
+ }
385
+ };
386
+ }
387
+ async #compatibleHarnessCheckpoint(work, task) {
388
+ const expectedCompatibility = harnessCheckpointCompatibility(work, task);
389
+ const artifacts = await this.#store.listArtifacts({
390
+ sessionId: task.sessionId,
391
+ tagId: task.tagId,
392
+ kind: HARNESS_CHECKPOINT_ARTIFACT_KIND,
393
+ limit: 20
394
+ });
395
+ for (const artifact of artifacts) {
396
+ const sourceTask = await this.#store.findTaskById(artifact.taskId);
397
+ if (sourceTask?.status !== "completed") continue;
398
+ const checkpoint = checkpointFromArtifactMetadata(artifact.metadata, expectedCompatibility);
399
+ if (checkpoint !== void 0) return checkpoint;
400
+ }
401
+ return void 0;
402
+ }
403
+ async #persistHarnessCheckpoint(work, task, events, createdAt) {
404
+ const checkpoint = events.findLast(
405
+ (event) => event.type === "checkpoint.created"
406
+ )?.checkpoint;
407
+ if (checkpoint === void 0) return;
408
+ const compatibility = harnessCheckpointCompatibility(work, task);
409
+ const serialized = JSON.stringify({ checkpoint, compatibility });
410
+ await this.#store.createArtifact({
411
+ taskId: task.id,
412
+ kind: HARNESS_CHECKPOINT_ARTIFACT_KIND,
413
+ location: checkpoint.uri,
414
+ contentHash: checkpoint.digest ?? `sha256:${createHash("sha256").update(serialized).digest("hex")}`,
415
+ metadata: {
416
+ version: HARNESS_CHECKPOINT_METADATA_VERSION,
417
+ checkpoint,
418
+ compatibility
419
+ },
420
+ createdAt
421
+ });
422
+ }
423
+ async #recordWorkerEvent(taskId, attemptId, event) {
424
+ const { taskId: _workerTaskId, attemptId: _workerAttemptId, type, at, ...data } = event;
425
+ const eventType = type.startsWith("execution.") ? type : `execution.${type}`;
426
+ await this.#appendTaskEvent(taskId, eventType, { at, ...data }, attemptId);
427
+ }
428
+ async #persistWorkRecord(work, task, response, workerEvents, completedAt) {
429
+ const intent = work.event.text?.trim();
430
+ const workerResult = terminalTaskResult(workerEvents);
431
+ const producedArtifacts = workerEvents.flatMap(
432
+ (event) => event.type === "artifact.created" ? [
433
+ {
434
+ uri: event.artifact.uri,
435
+ ...event.artifact.mediaType === void 0 ? {} : { mediaType: event.artifact.mediaType },
436
+ ...event.artifact.digest === void 0 ? {} : { digest: event.artifact.digest }
437
+ }
438
+ ] : []
439
+ );
440
+ const result = {
441
+ ...workerResult,
442
+ summary: workerResult.summary.trim().length === 0 ? response : workerResult.summary,
443
+ artifacts: uniqueArtifacts([...workerResult.artifacts, ...producedArtifacts])
444
+ };
445
+ const references = uniqueWorkReferences([
446
+ ...workReferencesFromOrigin(work.event, work.connectorAccountId),
447
+ ...workReferencesFromMaterialization(workerEvents),
448
+ ...result.references,
449
+ ...result.artifacts.map(
450
+ (artifact) => ({
451
+ provider: work.event.provider,
452
+ connectorAccountId: work.connectorAccountId,
453
+ resourceType: "artifact",
454
+ reference: artifact.uri,
455
+ relationship: "produced"
456
+ })
457
+ )
458
+ ]);
459
+ const record = {
460
+ version: 1,
461
+ taskId: task.id,
462
+ sessionId: task.sessionId,
463
+ tagId: task.tagId,
464
+ ...intent === void 0 || intent.length === 0 ? {} : { intent },
465
+ result: { ...result, references },
466
+ origin: {
467
+ tagPresenceId: work.tagPresenceId,
468
+ provider: work.event.provider,
469
+ connectorAccountId: work.connectorAccountId,
470
+ scope: work.event.scope,
471
+ sessionKey: work.event.sessionKey,
472
+ source: work.event.source
473
+ },
474
+ requester: work.event.actor,
475
+ resources: work.authorization.resources.map((resource) => ({
476
+ provider: resource.provider,
477
+ connectorAccountId: resource.connectorAccountId,
478
+ scope: resource.scope,
479
+ ...resource.reference === void 0 ? {} : { reference: resource.reference },
480
+ actions: resource.actions
481
+ })),
482
+ references,
483
+ citation: taskCitation(work.event, task.id),
484
+ completedAt
485
+ };
486
+ const serialized = JSON.stringify(record);
487
+ await this.#store.createArtifact({
488
+ taskId: task.id,
489
+ kind: WORK_RECORD_ARTIFACT_KIND,
490
+ location: `supertag://tasks/${task.id}/work-record`,
491
+ contentHash: `sha256:${createHash("sha256").update(serialized).digest("hex")}`,
492
+ sourceReferences: record.resources,
493
+ metadata: { record },
494
+ references,
495
+ createdAt: completedAt
496
+ });
497
+ return record;
498
+ }
499
+ /** Opens the durable Task for one accepted unit of user intent. */
500
+ async #openTask(work) {
501
+ const now = (/* @__PURE__ */ new Date()).toISOString();
502
+ const session = await this.#store.openSession({
503
+ tagId: work.tagId,
504
+ workerProfile: work.authorization.tag.workerProfile,
505
+ sessionKey: work.event.sessionKey,
506
+ origin: {
507
+ provider: work.event.provider,
508
+ connectorAccountId: work.connectorAccountId,
509
+ scope: work.event.scope,
510
+ threadKey: work.event.callback.threadKey
511
+ },
512
+ at: now
513
+ });
514
+ const sessionHistory = (await this.#store.listArtifacts({
515
+ sessionId: session.id,
516
+ tagId: work.tagId,
517
+ kind: WORK_RECORD_ARTIFACT_KIND,
518
+ limit: MAX_SESSION_HISTORY_TASKS
519
+ })).map((artifact) => workRecordFromArtifactMetadata(artifact.metadata, session.id)).toReversed().map(boundedWorkRecord);
520
+ const task = await this.#store.openTask({
521
+ inboundEventId: work.id,
522
+ tagId: work.tagId,
523
+ sessionId: session.id,
524
+ workerProfile: work.authorization.tag.workerProfile,
525
+ actor: work.event.actor,
526
+ trigger: {
527
+ kind: work.event.kind,
528
+ inboundEventId: work.id,
529
+ logicalEventId: work.event.logicalEventId,
530
+ occurredAt: work.event.occurredAt
531
+ },
532
+ workspacePlan: captureWorkspacePlan(work.event, work.authorization),
533
+ sessionHistory,
534
+ authorizationSnapshot: work.authorization,
535
+ contextPlan: work.contextPlan,
536
+ createdAt: work.createdAt
537
+ });
538
+ return task;
539
+ }
540
+ async #openTaskAttempt(work, task) {
541
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
542
+ await this.#store.startTask({ taskId: task.id, startedAt });
543
+ if (work.attemptCount === 1) {
544
+ await this.#appendTaskEvent(task.id, "task.started", {
545
+ tagPresenceId: work.tagPresenceId,
546
+ scope: work.event.scope
547
+ });
548
+ }
549
+ const attempt = await this.#store.createTaskAttempt({
550
+ taskId: task.id,
551
+ attemptNumber: work.attemptCount,
552
+ workerSnapshot: {
553
+ workerHostId: this.#worker?.id ?? "unknown",
554
+ workerProfile: work.authorization.tag.workerProfile
555
+ },
556
+ startedAt
557
+ });
558
+ await this.#appendTaskEvent(
559
+ task.id,
560
+ "attempt.started",
561
+ { attemptNumber: attempt.attemptNumber },
562
+ attempt.id
563
+ );
564
+ return attempt;
565
+ }
566
+ async #closeTask(task, status, outcome) {
567
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
568
+ await this.#appendTaskEvent(task.id, `task.${status}`, outcome);
569
+ try {
570
+ await this.#store.closeTask({ taskId: task.id, status, outcome, endedAt });
571
+ } catch (error) {
572
+ this.#reportDispatchError(error);
573
+ }
574
+ }
575
+ async #closeTaskAttempt(attempt, status, outcome) {
576
+ const endedAt = (/* @__PURE__ */ new Date()).toISOString();
577
+ await this.#appendTaskEvent(attempt.taskId, `attempt.${status}`, outcome, attempt.id);
578
+ try {
579
+ await this.#store.closeTaskAttempt({
580
+ attemptId: attempt.id,
581
+ status,
582
+ outcome,
583
+ endedAt
584
+ });
585
+ } catch (error) {
586
+ this.#reportDispatchError(error);
587
+ }
588
+ }
589
+ /** Task history is observability; it must never fail the dispatch it records. */
590
+ async #appendTaskEvent(taskId, type, payload, attemptId) {
591
+ try {
592
+ await this.#store.appendTaskEvent({
593
+ taskId,
594
+ type,
595
+ payload,
596
+ ...attemptId ? { attemptId } : {}
597
+ });
598
+ } catch (error) {
599
+ this.#reportDispatchError(error);
600
+ }
601
+ }
602
+ async #reconcileNextDelivery() {
603
+ if (this.#reply === void 0) {
604
+ return false;
605
+ }
606
+ const outbound = await this.#store.claimNextOutboundReply(this.#claimInput());
607
+ if (outbound === void 0) {
608
+ return false;
609
+ }
610
+ try {
611
+ const account = await this.#store.findConnectorAccountById(outbound.connectorAccountId);
612
+ if (account === void 0) {
613
+ throw new Error(`Connector account ${outbound.connectorAccountId} no longer exists`);
614
+ }
615
+ await this.#reply(
616
+ outbound.event,
617
+ { kind: outbound.presentation, markdown: outbound.text },
618
+ account
619
+ );
620
+ await this.#store.completeOutboundReply({
621
+ outboundReplyId: outbound.id,
622
+ leaseOwner: this.#instanceId,
623
+ deliveredAt: (/* @__PURE__ */ new Date()).toISOString()
624
+ });
625
+ } catch (error) {
626
+ await this.#retryOutbound(outbound, error);
627
+ this.#reportDispatchError(error);
628
+ }
629
+ return true;
630
+ }
631
+ #claimInput() {
632
+ const now = /* @__PURE__ */ new Date();
633
+ return {
634
+ leaseOwner: this.#instanceId,
635
+ now: now.toISOString(),
636
+ leaseExpiresAt: new Date(now.getTime() + this.#leaseDurationMs).toISOString()
637
+ };
638
+ }
639
+ async #captureAuthorization(event, originAccount, presence, tag, capturedAt) {
640
+ const activations = await this.#store.listTagPermissionActivations({
641
+ tagPresenceId: presence.id
642
+ });
643
+ const permissionSets = (await Promise.all(
644
+ activations.map(
645
+ (activation) => this.#store.findTagPermissionSetById(activation.permissionSetId)
646
+ )
647
+ )).filter((set) => set !== void 0 && set.tagId === presence.tagId).sort(
648
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
649
+ );
650
+ const permissions = (await Promise.all(
651
+ permissionSets.map((set) => this.#store.listTagPermissions({ permissionSetId: set.id }))
652
+ )).flat();
653
+ const accountIds = [...new Set(permissions.map((permission) => permission.connectorAccountId))];
654
+ const permissionAccounts = await Promise.all(
655
+ accountIds.map(async (id) => {
656
+ const account = await this.#store.findConnectorAccountById(id);
657
+ if (account === void 0) {
658
+ throw new Error(`Connector account ${id} for Tag ${tag.name} no longer exists`);
659
+ }
660
+ return account;
661
+ })
662
+ );
663
+ const accountsById = new Map(permissionAccounts.map((account) => [account.id, account]));
664
+ accountsById.set(originAccount.id, originAccount);
665
+ const resources = /* @__PURE__ */ new Map();
666
+ const origin = authorizationResource(
667
+ originAccount,
668
+ presence.scope,
669
+ ["event:receive", "thread:read", "thread:reply"],
670
+ "origin",
671
+ sourceReference(event, originAccount.provider)
672
+ );
673
+ resources.set(resourceKey(origin.connectorAccountId, origin.scope), origin);
674
+ for (const permission of permissions) {
675
+ const account = accountsById.get(permission.connectorAccountId);
676
+ if (account === void 0) {
677
+ throw new Error(`Connector account ${permission.connectorAccountId} is unavailable`);
678
+ }
679
+ const key = resourceKey(permission.connectorAccountId, permission.scope);
680
+ const existing = resources.get(key);
681
+ if (existing === void 0) {
682
+ resources.set(
683
+ key,
684
+ authorizationResource(
685
+ account,
686
+ permission.scope,
687
+ [permission.action],
688
+ "permission-set",
689
+ permission.reference
690
+ )
691
+ );
692
+ } else {
693
+ existing.actions.add(permission.action);
694
+ existing.sources.add("permission-set");
695
+ if (existing.reference === void 0 && permission.reference !== void 0) {
696
+ existing.reference = permission.reference;
697
+ }
698
+ }
699
+ }
700
+ return {
701
+ version: 2,
702
+ capturedAt,
703
+ tag: { id: tag.id, name: tag.name, workerProfile: tag.workerProfile },
704
+ origin: {
705
+ tagPresenceId: presence.id,
706
+ connectorAccountId: originAccount.id,
707
+ provider: originAccount.provider,
708
+ scope: presence.scope
709
+ },
710
+ requester: event.actor,
711
+ permissionSets: permissionSets.map((set) => ({ id: set.id, name: set.name })),
712
+ resources: [...resources.values()].map(freezeAuthorizationResource)
713
+ };
714
+ }
715
+ async #captureContextPlan(event, account, presence, capturedAt) {
716
+ const requestReferences = workReferencesFromOrigin(event, account.id);
717
+ const activations = await this.#store.listTagContextActivations({
718
+ tagPresenceId: presence.id
719
+ });
720
+ const sets = (await Promise.all(
721
+ activations.map((activation) => this.#store.findTagContextSetById(activation.contextSetId))
722
+ )).filter((set) => set !== void 0 && set.tagId === presence.tagId).sort(
723
+ (left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id)
724
+ );
725
+ const itemsBySet = await Promise.all(
726
+ sets.map((set) => this.#store.listTagContextItems({ contextSetId: set.id }))
727
+ );
728
+ const planSets = await Promise.all(
729
+ sets.map(async (set, index) => ({
730
+ id: set.id,
731
+ name: set.name,
732
+ items: await Promise.all(
733
+ (itemsBySet[index] ?? []).map(async (item) => {
734
+ if (item.kind === "work") {
735
+ const sourcePresence = await this.#store.findTagPresenceById(item.sourcePresenceId);
736
+ if (sourcePresence === void 0 || sourcePresence.tagId !== presence.tagId) {
737
+ throw new Error(
738
+ `Work selection ${item.itemKey} references an unavailable source presence`
739
+ );
740
+ }
741
+ const sourceAccount = await this.#store.findConnectorAccountById(
742
+ sourcePresence.connectorAccountId
743
+ );
744
+ if (sourceAccount === void 0) {
745
+ throw new Error(
746
+ `Work selection ${item.itemKey} references a disconnected source account`
747
+ );
748
+ }
749
+ const workRecords = await this.#resolveSharedWork(
750
+ item,
751
+ sourcePresence,
752
+ sourceAccount,
753
+ presence.tagId,
754
+ requestReferences,
755
+ event.sessionKey,
756
+ capturedAt
757
+ );
758
+ return {
759
+ id: item.id,
760
+ kind: "work",
761
+ itemKey: item.itemKey,
762
+ source: {
763
+ tagPresenceId: sourcePresence.id,
764
+ connectorAccountId: sourceAccount.id,
765
+ provider: sourceAccount.provider,
766
+ scope: sourcePresence.scope
767
+ },
768
+ selection: item.selection,
769
+ workRecords
770
+ };
771
+ }
772
+ return {
773
+ id: item.id,
774
+ kind: item.kind,
775
+ itemKey: item.itemKey,
776
+ reference: item.reference,
777
+ ...item.configuration === void 0 ? {} : { configuration: item.configuration }
778
+ };
779
+ })
780
+ )
781
+ }))
782
+ );
783
+ const priorTaskCount = planSets.flatMap((set) => set.items).reduce((count, item) => count + (item.kind === "work" ? item.workRecords.length : 0), 0);
784
+ if (priorTaskCount > MAX_PRIOR_TASKS_PER_PLAN) {
785
+ throw new Error(
786
+ `Context Plan selects ${priorTaskCount} prior Tasks; narrow it to ${MAX_PRIOR_TASKS_PER_PLAN}`
787
+ );
788
+ }
789
+ return {
790
+ version: 4,
791
+ capturedAt,
792
+ sets: planSets
793
+ };
794
+ }
795
+ async #resolveSharedWork(item, sourcePresence, sourceAccount, tagId, requestReferences, currentSessionKey, capturedAt) {
796
+ const matchable = requestReferences.filter(
797
+ (reference) => reference.resourceType === "channel" || reference.resourceType === "repository" || reference.resourceType === "issue" || reference.resourceType === "pull-request" || reference.resourceType === "file" || reference.resourceType === "project"
798
+ );
799
+ if (matchable.length === 0) return [];
800
+ const createdAfter = new Date(
801
+ Date.parse(capturedAt) - item.selection.maxAgeDays * 24 * 60 * 60 * 1e3
802
+ ).toISOString();
803
+ const artifacts = await this.#store.listArtifacts({
804
+ tagId,
805
+ kind: WORK_RECORD_ARTIFACT_KIND,
806
+ relatedTo: matchable,
807
+ originSurfaces: [
808
+ {
809
+ provider: sourceAccount.provider,
810
+ connectorAccountId: sourceAccount.id,
811
+ scope: sourcePresence.scope
812
+ }
813
+ ],
814
+ createdAfter,
815
+ limit: 100
816
+ });
817
+ return artifacts.map((artifact) => workRecordFromArtifactMetadata(artifact.metadata, item.itemKey)).filter((record) => record.origin.sessionKey !== currentSessionKey).slice(0, item.selection.limit).toReversed().map(boundedWorkRecord);
818
+ }
819
+ async #enqueuePresentation(work, presentation) {
820
+ await this.#store.enqueueOutboundReply({
821
+ inboundEventId: work.id,
822
+ ...presentation,
823
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
824
+ });
825
+ }
826
+ async #retryInbound(work, error) {
827
+ const now = /* @__PURE__ */ new Date();
828
+ return this.#store.retryInboundEvent({
829
+ inboundEventId: work.id,
830
+ leaseOwner: this.#instanceId,
831
+ error: errorMessage(error),
832
+ retryAt: new Date(now.getTime() + this.#retryDelay(work.attemptCount)).toISOString(),
833
+ failedAt: now.toISOString()
834
+ });
835
+ }
836
+ async #retryOutbound(outbound, error) {
837
+ const now = /* @__PURE__ */ new Date();
838
+ await this.#store.retryOutboundReply({
839
+ outboundReplyId: outbound.id,
840
+ leaseOwner: this.#instanceId,
841
+ error: errorMessage(error),
842
+ retryAt: new Date(now.getTime() + this.#retryDelay(outbound.attemptCount)).toISOString(),
843
+ failedAt: now.toISOString()
844
+ });
845
+ }
846
+ #retryDelay(attemptCount) {
847
+ return this.#retryBaseMs * 2 ** Math.max(0, attemptCount - 1);
848
+ }
849
+ async #waitForDispatch(kind) {
850
+ await new Promise((resolve) => {
851
+ const timeout = setTimeout(() => {
852
+ if (kind === "inbound") this.#wakeTaskController = void 0;
853
+ else this.#wakeDeliveryController = void 0;
854
+ resolve();
855
+ }, this.#pollIntervalMs);
856
+ const wake = () => {
857
+ clearTimeout(timeout);
858
+ if (kind === "inbound") this.#wakeTaskController = void 0;
859
+ else this.#wakeDeliveryController = void 0;
860
+ resolve();
861
+ };
862
+ if (kind === "inbound") this.#wakeTaskController = wake;
863
+ else this.#wakeDeliveryController = wake;
864
+ });
865
+ }
866
+ async #waitForAdmissions() {
867
+ if (this.#activeAdmissions === 0) {
868
+ return;
869
+ }
870
+ await new Promise((resolve) => {
871
+ this.#admissionsDrained = resolve;
872
+ });
873
+ }
874
+ #reportDispatchError(error) {
875
+ try {
876
+ this.#onDispatchError?.(error);
877
+ } catch {
878
+ }
879
+ }
880
+ };
881
+ function positiveDuration(value, fallback, name) {
882
+ const selected = value ?? fallback;
883
+ if (!Number.isFinite(selected) || selected <= 0) {
884
+ throw new Error(`Gateway dispatch ${name} must be greater than zero`);
885
+ }
886
+ return selected;
887
+ }
888
+ function captureWorkspacePlan(event, authorization) {
889
+ const choices = authorization.resources.filter(
890
+ (resource) => resource.provider === "github" && resource.scope.startsWith("repository:") && resource.actions.includes("contents:read")
891
+ ).map((resource) => ({
892
+ provider: resource.provider,
893
+ connectorAccountId: resource.connectorAccountId,
894
+ scope: resource.scope,
895
+ ...resource.reference === void 0 ? {} : { reference: resource.reference },
896
+ actions: resource.actions
897
+ })).sort(
898
+ (left, right) => (left.reference ?? left.scope).localeCompare(right.reference ?? right.scope)
899
+ );
900
+ const requested = repositoryReferences(event.text ?? "");
901
+ if (choices.length === 0) {
902
+ return requested.length === 0 ? { version: 1, status: "none" } : { version: 1, status: "unavailable", requested };
903
+ }
904
+ if (event.provider === "github") {
905
+ const origin = choices.find(
906
+ (choice) => choice.connectorAccountId === authorization.origin.connectorAccountId && choice.scope === authorization.origin.scope
907
+ );
908
+ if (origin !== void 0) {
909
+ return { version: 1, status: "selected", selectedBy: "origin", target: origin };
910
+ }
911
+ }
912
+ if (requested.length > 0) {
913
+ const selected = choices.find(
914
+ (choice) => choice.reference !== void 0 && requested.some((reference) => reference === choice.reference?.toLowerCase())
915
+ );
916
+ if (selected !== void 0) {
917
+ return { version: 1, status: "selected", selectedBy: "request", target: selected };
918
+ }
919
+ return { version: 1, status: "selection-required", choices };
920
+ }
921
+ const onlyChoice = choices[0];
922
+ if (choices.length === 1 && onlyChoice !== void 0) {
923
+ return { version: 1, status: "selected", selectedBy: "default", target: onlyChoice };
924
+ }
925
+ return { version: 1, status: "selection-required", choices };
926
+ }
927
+ function repositoryReferences(text) {
928
+ return [...text.matchAll(/(?:^|[\s(`])([a-z0-9_.-]+\/[a-z0-9_.-]+)(?=$|[\s),.:;!?])/gi)].flatMap(
929
+ (match) => match[1] === void 0 ? [] : [match[1].toLowerCase()]
930
+ );
931
+ }
932
+ function acknowledgementText(task) {
933
+ const workspace = taskWorkspaceLabel(task.workspacePlan);
934
+ return `Task ${shortTaskId(task.id)} accepted${workspace === void 0 ? "" : ` for ${workspace}`}. I\u2019ll keep progress and the final result in this thread.`;
935
+ }
936
+ function materializationStatusText(task, manifest) {
937
+ const workspace = taskWorkspaceLabel(task.workspacePlan);
938
+ const location = workspace === void 0 ? "the selected execution environment" : workspace;
939
+ return `Task ${shortTaskId(task.id)} is running in ${location} with ${manifest.harness.id}.`;
940
+ }
941
+ function finalResultText(response, record) {
942
+ return `${response.trim()}
943
+
944
+ Task ${shortTaskId(record.taskId)} completed \xB7 Work Record: supertag://tasks/${record.taskId}/work-record`;
945
+ }
946
+ function failureText(task, error) {
947
+ const message = errorMessage(error).replace(/\s+/g, " ").slice(0, 500);
948
+ return `Task ${shortTaskId(task.id)} failed: ${message}`;
949
+ }
950
+ function taskWorkspaceLabel(plan) {
951
+ if (plan.status === "selected") return plan.target.reference ?? plan.target.scope;
952
+ if (plan.status === "selection-required") return "a repository awaiting selection";
953
+ if (plan.status === "unavailable") return plan.requested.join(", ");
954
+ return void 0;
955
+ }
956
+ function shortTaskId(taskId) {
957
+ return taskId.slice(0, 8);
958
+ }
959
+ function authorizationResource(account, scope, actions, source, reference) {
960
+ return {
961
+ connectorAccountId: account.id,
962
+ provider: account.provider,
963
+ scope,
964
+ ...reference === void 0 ? {} : { reference },
965
+ actions: new Set(actions),
966
+ sources: /* @__PURE__ */ new Set([source])
967
+ };
968
+ }
969
+ function freezeAuthorizationResource(resource) {
970
+ return {
971
+ connectorAccountId: resource.connectorAccountId,
972
+ provider: resource.provider,
973
+ scope: resource.scope,
974
+ ...resource.reference === void 0 ? {} : { reference: resource.reference },
975
+ actions: [...resource.actions].sort(),
976
+ sources: [...resource.sources].sort()
977
+ };
978
+ }
979
+ function sourceReference(event, provider) {
980
+ if (provider !== "github") return void 0;
981
+ const candidate = event.source["repository"];
982
+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : void 0;
983
+ }
984
+ function resourceKey(connectorAccountId, scope) {
985
+ return `${connectorAccountId}\0${scope}`;
986
+ }
987
+ function positiveInteger(value, fallback, name) {
988
+ const selected = value ?? fallback;
989
+ if (!Number.isInteger(selected) || selected <= 0) {
990
+ throw new Error(`Gateway dispatch ${name} must be a positive integer`);
991
+ }
992
+ return selected;
993
+ }
994
+ function errorMessage(error) {
995
+ return error instanceof Error ? error.message : String(error);
996
+ }
997
+ function workRecordFromArtifactMetadata(metadata, itemKey) {
998
+ const document = metadata?.["record"];
999
+ if (!isRecord(document) || document["version"] !== 1 || typeof document["taskId"] !== "string" || typeof document["sessionId"] !== "string" || typeof document["tagId"] !== "string" || !isRecord(document["result"]) || typeof document["result"]["summary"] !== "string" || !isRecord(document["origin"]) || typeof document["origin"]["tagPresenceId"] !== "string" || !isRecord(document["origin"]["source"]) || !isRecord(document["requester"]) || !Array.isArray(document["resources"]) || !Array.isArray(document["references"]) || !isRecord(document["citation"]) || typeof document["citation"]["label"] !== "string" || typeof document["citation"]["uri"] !== "string" || typeof document["completedAt"] !== "string") {
1000
+ throw new Error(`Context source ${itemKey} references an invalid Work Record artifact`);
1001
+ }
1002
+ return document;
1003
+ }
1004
+ function isRecord(value) {
1005
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1006
+ }
1007
+ function boundedWorkRecord(document) {
1008
+ return {
1009
+ ...document,
1010
+ ...document.intent === void 0 ? {} : { intent: truncate(document.intent, MAX_PRIOR_INTENT_CHARACTERS) },
1011
+ result: {
1012
+ ...document.result,
1013
+ summary: truncate(document.result.summary, MAX_PRIOR_RESPONSE_CHARACTERS),
1014
+ decisions: document.result.decisions.slice(0, 10).map((decision) => ({
1015
+ ...decision,
1016
+ text: truncate(decision.text, 1e3)
1017
+ })),
1018
+ changes: document.result.changes.slice(0, 10).map((change) => ({
1019
+ ...change,
1020
+ summary: truncate(change.summary, 1e3)
1021
+ })),
1022
+ unresolved: document.result.unresolved.slice(0, 10).map((item) => truncate(item, 1e3)),
1023
+ references: document.result.references.slice(0, 25),
1024
+ artifacts: document.result.artifacts.slice(0, 25)
1025
+ }
1026
+ };
1027
+ }
1028
+ function truncate(value, limit) {
1029
+ if (value.length <= limit) return value;
1030
+ return `${value.slice(0, limit)}
1031
+ [truncated]`;
1032
+ }
1033
+ function workReferencesFromOrigin(event, connectorAccountId) {
1034
+ if (event.provider === "github") {
1035
+ const repositoryId = textValue(event.source["repositoryId"]) ?? scopeId(event.scope);
1036
+ const repository = textValue(event.source["repository"]) ?? (repositoryId === void 0 ? void 0 : `github:repository:${repositoryId}`);
1037
+ if (repository === void 0) return [];
1038
+ const references = [
1039
+ {
1040
+ provider: "github",
1041
+ connectorAccountId,
1042
+ resourceType: "repository",
1043
+ ...repositoryId === void 0 ? {} : { resourceId: repositoryId },
1044
+ reference: repository,
1045
+ relationship: "originated-in"
1046
+ }
1047
+ ];
1048
+ const number = textValue(event.source["number"]);
1049
+ if (number !== void 0) {
1050
+ references.push({
1051
+ provider: "github",
1052
+ connectorAccountId,
1053
+ resourceType: event.metadata["isPullRequest"] === true ? "pull-request" : "issue",
1054
+ resourceId: number,
1055
+ reference: `${repository}#${number}`,
1056
+ relationship: "originated-in"
1057
+ });
1058
+ }
1059
+ return references;
1060
+ }
1061
+ if (event.provider === "linear") {
1062
+ const issueId = textValue(event.source["issueId"]);
1063
+ if (issueId === void 0) return [];
1064
+ const teamId = textValue(event.source["teamId"]) ?? scopeId(event.scope);
1065
+ return [
1066
+ ...teamId === void 0 ? [] : [
1067
+ {
1068
+ provider: "linear",
1069
+ connectorAccountId,
1070
+ resourceType: "project",
1071
+ resourceId: teamId,
1072
+ reference: `linear:${event.externalAccountId}:team:${teamId}`,
1073
+ relationship: "originated-in"
1074
+ }
1075
+ ],
1076
+ {
1077
+ provider: "linear",
1078
+ connectorAccountId,
1079
+ resourceType: "issue",
1080
+ resourceId: issueId,
1081
+ reference: textValue(event.source["issueIdentifier"]) ?? issueId,
1082
+ relationship: "originated-in"
1083
+ }
1084
+ ];
1085
+ }
1086
+ const channelId = textValue(event.source["channelId"]) ?? scopeId(event.scope);
1087
+ if (channelId === void 0) return [];
1088
+ return [
1089
+ {
1090
+ provider: event.provider,
1091
+ connectorAccountId,
1092
+ resourceType: "channel",
1093
+ resourceId: channelId,
1094
+ reference: `${event.provider}:${event.externalAccountId}:${channelId}`,
1095
+ relationship: "originated-in"
1096
+ }
1097
+ ];
1098
+ }
1099
+ function workReferencesFromMaterialization(events) {
1100
+ return events.flatMap((event) => {
1101
+ if (event.type !== "materialization.completed") return [];
1102
+ return event.manifest.contributions.flatMap((contribution) => {
1103
+ const provenance = contribution.resource?.provenance;
1104
+ if (provenance?.["provider"] !== "github") return [];
1105
+ const repositoryId = textValue(provenance["repositoryId"]);
1106
+ const repository = textValue(provenance["repository"]);
1107
+ const connectorAccountId = textValue(provenance["connectorAccountId"]);
1108
+ if (repository === void 0) return [];
1109
+ return [
1110
+ {
1111
+ provider: "github",
1112
+ ...connectorAccountId === void 0 ? {} : { connectorAccountId },
1113
+ resourceType: "repository",
1114
+ ...repositoryId === void 0 ? {} : { resourceId: repositoryId },
1115
+ reference: repository,
1116
+ relationship: "inspected"
1117
+ }
1118
+ ];
1119
+ });
1120
+ });
1121
+ }
1122
+ function uniqueWorkReferences(references) {
1123
+ return [
1124
+ ...new Map(
1125
+ references.map((reference) => [
1126
+ `${reference.provider}\0${reference.resourceType}\0${reference.reference}\0${reference.relationship}`,
1127
+ reference
1128
+ ])
1129
+ ).values()
1130
+ ];
1131
+ }
1132
+ function uniqueArtifacts(artifacts) {
1133
+ return [...new Map(artifacts.map((artifact) => [artifact.uri, artifact])).values()];
1134
+ }
1135
+ function taskCitation(event, taskId) {
1136
+ return {
1137
+ label: `${event.provider}:${event.scope}`,
1138
+ uri: textValue(event.source["url"]) ?? `supertag://tasks/${taskId}`
1139
+ };
1140
+ }
1141
+ function harnessCheckpointCompatibility(work, task) {
1142
+ const authorization = work.authorization;
1143
+ const canonical = stableJson({
1144
+ version: 1,
1145
+ tagId: task.tagId,
1146
+ sessionId: task.sessionId,
1147
+ workerProfile: task.workerProfile,
1148
+ audience: {
1149
+ provider: work.event.provider,
1150
+ connectorAccountId: work.connectorAccountId,
1151
+ scope: work.event.scope,
1152
+ sessionKey: work.event.sessionKey,
1153
+ callbackTarget: work.event.callback.target
1154
+ },
1155
+ authorization: {
1156
+ origin: authorization.origin,
1157
+ permissionSets: authorization.permissionSets,
1158
+ resources: authorization.resources
1159
+ },
1160
+ contextSets: work.contextPlan.sets
1161
+ });
1162
+ return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
1163
+ }
1164
+ function checkpointFromArtifactMetadata(metadata, expectedCompatibility) {
1165
+ if (metadata?.["version"] !== HARNESS_CHECKPOINT_METADATA_VERSION || metadata["compatibility"] !== expectedCompatibility) {
1166
+ return void 0;
1167
+ }
1168
+ const value = metadata["checkpoint"];
1169
+ if (!isJsonObject(value)) return void 0;
1170
+ const id = textValue(value["id"]);
1171
+ const format = textValue(value["format"]);
1172
+ const uri = textValue(value["uri"]);
1173
+ if (id === void 0 || format === void 0 || uri === void 0) return void 0;
1174
+ try {
1175
+ new URL(uri);
1176
+ } catch {
1177
+ return void 0;
1178
+ }
1179
+ const mediaType = textValue(value["mediaType"]);
1180
+ const digest = textValue(value["digest"]);
1181
+ const provenance = value["provenance"];
1182
+ if (provenance !== void 0 && !isJsonObject(provenance)) return void 0;
1183
+ return {
1184
+ id,
1185
+ format,
1186
+ uri,
1187
+ ...mediaType === void 0 ? {} : { mediaType },
1188
+ ...digest === void 0 ? {} : { digest },
1189
+ ...provenance === void 0 ? {} : { provenance }
1190
+ };
1191
+ }
1192
+ function stableJson(value) {
1193
+ return JSON.stringify(canonicalJsonValue(value));
1194
+ }
1195
+ function canonicalJsonValue(value) {
1196
+ if (Array.isArray(value)) return value.map(canonicalJsonValue);
1197
+ if (!isJsonObject(value)) return value;
1198
+ return Object.fromEntries(
1199
+ Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, canonicalJsonValue(entry)])
1200
+ );
1201
+ }
1202
+ function isJsonObject(value) {
1203
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1204
+ }
1205
+ function textValue(value) {
1206
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1207
+ }
1208
+ function scopeId(scope) {
1209
+ const separator = scope.indexOf(":");
1210
+ return separator < 0 ? void 0 : textValue(scope.slice(separator + 1));
1211
+ }
1212
+
1213
+ export { Gateway };
1214
+ //# sourceMappingURL=gateway.js.map
1215
+ //# sourceMappingURL=gateway.js.map