@kitman-sh/cli 0.14.9 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/{chunk-cwdrhsvk.js → chunk-0ws25xvg.js} +2 -2
  2. package/dist/{chunk-czmbgsqr.js → chunk-2vxb3q01.js} +656 -39
  3. package/dist/{chunk-mgjer6c7.js → chunk-39ykbhq8.js} +3 -3
  4. package/dist/{chunk-vt8aqeby.js → chunk-3ns4sbfb.js} +1 -1
  5. package/dist/{chunk-c80dvhxf.js → chunk-5hkdgzh4.js} +1 -6
  6. package/dist/{chunk-0x5r7h2g.js → chunk-60fhzjx3.js} +1127 -109
  7. package/dist/{chunk-enmtmq63.js → chunk-69xka6ew.js} +1 -1
  8. package/dist/{chunk-vjt0d9zj.js → chunk-6h70kent.js} +7 -7
  9. package/dist/{chunk-qb9jft1r.js → chunk-8wpg3rph.js} +2 -2
  10. package/dist/{chunk-ftre6ndb.js → chunk-91tmbf95.js} +6 -6
  11. package/dist/chunk-csxxwscf.js +39 -0
  12. package/dist/chunk-d40233pm.js +3080 -0
  13. package/dist/{chunk-jsb61dsk.js → chunk-dv4v0tbn.js} +1815 -117
  14. package/dist/{chunk-wttgq85b.js → chunk-dx792s4w.js} +1396 -41
  15. package/dist/{chunk-dd7wknyk.js → chunk-f36s9s1g.js} +1512 -125
  16. package/dist/{chunk-y9x0yv20.js → chunk-fggwdr03.js} +461 -224
  17. package/dist/{chunk-93xj74qp.js → chunk-fzaecdgv.js} +3 -3
  18. package/dist/{chunk-2r4jy82z.js → chunk-k2wd9r6t.js} +4 -4
  19. package/dist/{chunk-h7qv6nzc.js → chunk-kskb0hkb.js} +7 -7
  20. package/dist/{chunk-6qygqj10.js → chunk-tgt9a3yz.js} +6 -6
  21. package/dist/{chunk-bmwf2ea5.js → chunk-vg78dz3w.js} +85 -26
  22. package/dist/{chunk-axr8avvs.js → chunk-wh4bpc4w.js} +4 -4
  23. package/dist/chunk-xrjt25ns.js +4345 -0
  24. package/dist/{chunk-e3c15bgw.js → chunk-xx711t5r.js} +4 -4
  25. package/dist/{chunk-b2yy07ag.js → chunk-ygx2pda7.js} +7 -7
  26. package/dist/{chunk-cpss81fx.js → chunk-zy4sv70r.js} +13 -5
  27. package/dist/index.js +4 -4
  28. package/package.json +2 -1
  29. package/dist/chunk-3hdjd2c3.js +0 -1192
  30. package/dist/chunk-qvyqfm54.js +0 -526
@@ -0,0 +1,3080 @@
1
+ // @bun
2
+ import {
3
+ dual,
4
+ isString,
5
+ isFunction,
6
+ hasProperty,
7
+ isTagged,
8
+ Prototype,
9
+ isNone,
10
+ getOrElse,
11
+ Service2,
12
+ empty3,
13
+ add,
14
+ getOrUndefined2,
15
+ get4,
16
+ merge3,
17
+ Reference,
18
+ fromInputUnsafe,
19
+ toMillis,
20
+ TaggedClass,
21
+ TaggedError,
22
+ encode,
23
+ succeed3,
24
+ isSuccess2,
25
+ isFailure2,
26
+ map8,
27
+ addFinalizerExit,
28
+ succeed5,
29
+ effectDiscard,
30
+ isDieReason,
31
+ hasInterruptsOnly,
32
+ combine2,
33
+ squash,
34
+ hasInterrupts2,
35
+ min2,
36
+ exponential,
37
+ spaced,
38
+ while_,
39
+ setInputType,
40
+ forEach,
41
+ promise,
42
+ tryPromise,
43
+ succeed6,
44
+ suspend3,
45
+ sync2,
46
+ void_3,
47
+ callback3,
48
+ gen,
49
+ fail7,
50
+ failCause3,
51
+ die3,
52
+ try_2,
53
+ yieldNow,
54
+ flatMap3,
55
+ andThen2,
56
+ tap2,
57
+ exit,
58
+ map9,
59
+ as,
60
+ asVoid,
61
+ catch_,
62
+ catchTag,
63
+ catchTags,
64
+ mapError2,
65
+ orDie,
66
+ tapError2,
67
+ retry,
68
+ sandbox,
69
+ orElseSucceed,
70
+ matchEffect2,
71
+ context,
72
+ contextWith,
73
+ provide3,
74
+ provideContext2,
75
+ service,
76
+ serviceOption,
77
+ provideService,
78
+ scoped,
79
+ acquireUseRelease,
80
+ onExit,
81
+ interruptible,
82
+ uninterruptibleMask2,
83
+ annotateCurrentSpan,
84
+ withSpan,
85
+ runSync,
86
+ fnUntraced,
87
+ encode3,
88
+ makeFormatterStandardSchemaV1,
89
+ transform,
90
+ encodeBase64Url,
91
+ decodeBase64UrlString,
92
+ transform2,
93
+ declare,
94
+ is,
95
+ decodeUnknownEffect2,
96
+ decodeEffect,
97
+ decodeSync,
98
+ encodeUnknownEffect,
99
+ encodeEffect,
100
+ encodeSync,
101
+ isSchema,
102
+ optionalKey,
103
+ optional,
104
+ Literal,
105
+ Never,
106
+ Unknown,
107
+ Null,
108
+ String4,
109
+ Boolean2,
110
+ Void,
111
+ Struct,
112
+ Record,
113
+ Tuple2,
114
+ ArraySchema,
115
+ NonEmptyArray,
116
+ Union,
117
+ Literals,
118
+ NullOr,
119
+ decodeTo2,
120
+ tag,
121
+ TaggedStruct,
122
+ link,
123
+ makeFilter,
124
+ isPattern,
125
+ Finite,
126
+ isGreaterThanOrEqualTo,
127
+ isLessThanOrEqualTo,
128
+ Int,
129
+ isMinLength,
130
+ isMaxLength,
131
+ Defect,
132
+ fromJsonString,
133
+ Cause,
134
+ Exit,
135
+ Class2,
136
+ TaggedClass2,
137
+ TaggedError2,
138
+ toJsonSchemaDocument,
139
+ toCodecJson,
140
+ Json
141
+ } from "./chunk-dx792s4w.js";
142
+ import {
143
+ currentTimeMillis,
144
+ WebCrypto,
145
+ makeUnsafe,
146
+ formatIso,
147
+ RepoBindingProvider,
148
+ releaseVersion,
149
+ ReleaseScope,
150
+ recommendedDefault,
151
+ DeliveryMode,
152
+ ProgramWorkUnit,
153
+ MeasureEvidence,
154
+ TagVersions,
155
+ CatchUp,
156
+ DeployTargetName,
157
+ DeployRef,
158
+ DeployStatus,
159
+ runsDeployedTag,
160
+ DeployTargetRunning,
161
+ RunFileRefused,
162
+ runFileContentType,
163
+ ClaimResult,
164
+ mergeTurnResource,
165
+ sha256Hasher,
166
+ put,
167
+ setHeaders,
168
+ bodyUint8Array,
169
+ filterStatusOk,
170
+ HttpClient,
171
+ runTicketsPayload,
172
+ runTicketResult,
173
+ LoopCapabilities,
174
+ LoopManifest,
175
+ CallableLoop,
176
+ StepManifest,
177
+ KitSetup,
178
+ RunnerRpcError
179
+ } from "./chunk-f36s9s1g.js";
180
+ import {
181
+ getCurrent,
182
+ runForEach,
183
+ FileSystem
184
+ } from "./chunk-vg78dz3w.js";
185
+ import {
186
+ splitQuestionOptions,
187
+ recommendationProblem,
188
+ questionAdvice
189
+ } from "./chunk-csxxwscf.js";
190
+ import {
191
+ guard,
192
+ Id,
193
+ Timestamp,
194
+ ActorType
195
+ } from "./chunk-5hkdgzh4.js";
196
+ var __defProp = Object.defineProperty;
197
+ var __returnValue = (v) => v;
198
+ function __exportSetter(name, newValue) {
199
+ this[name] = __returnValue.bind(null, newValue);
200
+ }
201
+ var __export = (target, all) => {
202
+ for (var name in all)
203
+ __defProp(target, name, {
204
+ get: all[name],
205
+ enumerable: true,
206
+ configurable: true,
207
+ set: __exportSetter.bind(all, name)
208
+ });
209
+ };
210
+
211
+ // packages/sdk/src/loop/activities.ts
212
+ var exports_activities = {};
213
+ __export(exports_activities, {
214
+ AlertTaskRequest: () => AlertTaskRequest,
215
+ AlertTaskResult: () => AlertTaskResult,
216
+ AlertTaskStep: () => AlertTaskStep,
217
+ ApproveChangeRequestRequest: () => ApproveChangeRequestRequest,
218
+ ApproveChangeRequestResult: () => ApproveChangeRequestResult,
219
+ ApproveChangeRequestStep: () => ApproveChangeRequestStep,
220
+ ArtifactRequest: () => ArtifactRequest,
221
+ ArtifactResult: () => ArtifactResult,
222
+ ArtifactStep: () => ArtifactStep,
223
+ Branch: () => Branch,
224
+ BranchChangeRequest: () => BranchChangeRequest,
225
+ BranchChangeRequestRequest: () => BranchChangeRequestRequest,
226
+ BranchRequest: () => BranchRequest,
227
+ BranchStep: () => BranchStep,
228
+ CallableLoops: () => CallableLoops,
229
+ CallableLoopsRequest: () => CallableLoopsRequest,
230
+ CallableLoopsStep: () => CallableLoopsStep,
231
+ ChangeRequestBetweenStep: () => ChangeRequestBetweenStep,
232
+ ChangeRequestReadRequest: () => ChangeRequestReadRequest,
233
+ ChangeRequestRequest: () => ChangeRequestRequest,
234
+ ChangeRequestResult: () => ChangeRequestResult,
235
+ ChangeRequestStep: () => ChangeRequestStep,
236
+ CloseChangeRequestRequest: () => CloseChangeRequestRequest,
237
+ CloseChangeRequestResult: () => CloseChangeRequestResult,
238
+ CloseChangeRequestStep: () => CloseChangeRequestStep,
239
+ CommentRequest: () => CommentRequest,
240
+ CommentStep: () => CommentStep,
241
+ CreateTasksRequest: () => CreateTasksRequest,
242
+ CreateTasksResult: () => CreateTasksResult,
243
+ CreateTasksStep: () => CreateTasksStep,
244
+ DeliveryBaseStep: () => DeliveryBaseStep,
245
+ DeployTargetRequest: () => DeployTargetRequest,
246
+ DeployTargetResult: () => DeployTargetResult,
247
+ DeployTargetStep: () => DeployTargetStep,
248
+ DraftUpdateRequest: () => DraftUpdateRequest,
249
+ DraftUpdateResult: () => DraftUpdateResult,
250
+ DraftUpdateStep: () => DraftUpdateStep,
251
+ FileRequest: () => FileRequest,
252
+ FileStep: () => FileStep,
253
+ IntegrationBranch: () => IntegrationBranch,
254
+ IntegrationBranchRequest: () => IntegrationBranchRequest,
255
+ IntegrationBranchStep: () => IntegrationBranchStep,
256
+ LiveBranch: () => LiveBranch,
257
+ LiveBranchSource: () => LiveBranchSource,
258
+ LiveBranches: () => LiveBranches,
259
+ LiveBranchesRequest: () => LiveBranchesRequest,
260
+ LiveBranchesStep: () => LiveBranchesStep,
261
+ MergeChangeRequestRequest: () => MergeChangeRequestRequest,
262
+ MergeChangeRequestStep: () => MergeChangeRequestStep,
263
+ MergeResult: () => MergeResult,
264
+ MergedChangeRequest: () => MergedChangeRequest,
265
+ MergedChangeRequestRequest: () => MergedChangeRequestRequest,
266
+ MergedChangeRequestStep: () => MergedChangeRequestStep,
267
+ NoteRequest: () => NoteRequest,
268
+ NoteStep: () => NoteStep,
269
+ OpenChangeRequest: () => OpenChangeRequest,
270
+ OpenChangeRequests: () => OpenChangeRequests,
271
+ OpenChangeRequestsRequest: () => OpenChangeRequestsRequest,
272
+ OpenChangeRequestsStep: () => OpenChangeRequestsStep,
273
+ OwnChangeRequest: () => OwnChangeRequest,
274
+ OwnChangeRequests: () => OwnChangeRequests,
275
+ OwnChangeRequestsStep: () => OwnChangeRequestsStep,
276
+ PipelineJob: () => PipelineJob,
277
+ PipelineStatus: () => PipelineStatus,
278
+ PipelineStatusRequest: () => PipelineStatusRequest,
279
+ PipelineStatusStep: () => PipelineStatusStep,
280
+ ProjectActivityRequest: () => ProjectActivityRequest,
281
+ ProjectActivityResult: () => ProjectActivityResult,
282
+ ProjectActivityStep: () => ProjectActivityStep,
283
+ ProposeRequest: () => ProposeRequest,
284
+ ProposeResult: () => ProposeResult,
285
+ ProposeStep: () => ProposeStep,
286
+ RecordDeployRequest: () => RecordDeployRequest,
287
+ RecordDeployResult: () => RecordDeployResult,
288
+ RecordDeployStep: () => RecordDeployStep,
289
+ RecordRevertRequest: () => RecordRevertRequest,
290
+ RecordRevertStep: () => RecordRevertStep,
291
+ RecordedRevert: () => RecordedRevert,
292
+ ReleaseRequest: () => ReleaseRequest,
293
+ ReleaseResult: () => ReleaseResult,
294
+ ReleaseStep: () => ReleaseStep,
295
+ ReportPipelineRequest: () => ReportPipelineRequest,
296
+ ReportPipelineResult: () => ReportPipelineResult,
297
+ ReportPipelineStep: () => ReportPipelineStep,
298
+ RerunPipelineRequest: () => RerunPipelineRequest,
299
+ RerunPipelineResult: () => RerunPipelineResult,
300
+ RerunPipelineStep: () => RerunPipelineStep,
301
+ ReviewThread: () => ReviewThread,
302
+ ReviewThreads: () => ReviewThreads,
303
+ ReviewThreadsStep: () => ReviewThreadsStep,
304
+ RunFile: () => RunFile,
305
+ TranscriptPoint: () => TranscriptPoint,
306
+ TranscriptsRequest: () => TranscriptsRequest,
307
+ TranscriptsResult: () => TranscriptsResult,
308
+ TranscriptsStep: () => TranscriptsStep,
309
+ WriteBackMilestones: () => WriteBackMilestones,
310
+ WriteBackRequest: () => WriteBackRequest,
311
+ WriteBackStep: () => WriteBackStep,
312
+ alertTask: () => alertTask,
313
+ approveChangeRequest: () => approveChangeRequest,
314
+ artifact: () => artifact,
315
+ branch: () => branch,
316
+ callableLoops: () => callableLoops,
317
+ changeRequest: () => changeRequest,
318
+ closeChangeRequest: () => closeChangeRequest,
319
+ comment: () => comment,
320
+ createTasks: () => createTasks,
321
+ deliveryBase: () => deliveryBase,
322
+ deployTarget: () => deployTarget,
323
+ draftUpdate: () => draftUpdate,
324
+ file: () => file,
325
+ hostSteps: () => hostSteps,
326
+ integrationBranch: () => integrationBranch,
327
+ liveBranches: () => liveBranches,
328
+ mergeChangeRequest: () => mergeChangeRequest,
329
+ mergedChangeRequest: () => mergedChangeRequest,
330
+ note: () => note,
331
+ openChangeRequests: () => openChangeRequests,
332
+ ownChangeRequests: () => ownChangeRequests,
333
+ pipelineMoved: () => pipelineMoved,
334
+ pipelineStatus: () => pipelineStatus,
335
+ projectActivity: () => projectActivity,
336
+ propose: () => propose,
337
+ recordDeploy: () => recordDeploy,
338
+ recordRevert: () => recordRevert,
339
+ release: () => release,
340
+ reportPipeline: () => reportPipeline,
341
+ rerunPipeline: () => rerunPipeline,
342
+ reviewThreads: () => reviewThreads,
343
+ transcripts: () => transcripts,
344
+ writeBack: () => writeBack
345
+ });
346
+
347
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/crypto/internal/webCrypto.js
348
+ var subtleUnavailable = () => new Error("crypto.subtle is unavailable; browsers expose it only in secure contexts");
349
+
350
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/crypto/internal/digest.js
351
+ var webCryptoDigest = (crypto, algorithm, data) => {
352
+ const implementation = algorithm.implementation;
353
+ if (implementation !== undefined) {
354
+ return sync2(() => implementation(data));
355
+ }
356
+ return suspend3(() => {
357
+ const subtle = crypto?.subtle;
358
+ if (subtle === undefined)
359
+ return die3(subtleUnavailable());
360
+ return promise(async () => new Uint8Array(await subtle.digest(algorithm.name, data)));
361
+ });
362
+ };
363
+
364
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/crypto/Digest.js
365
+ var sha256 = {
366
+ name: "SHA-256",
367
+ outputLength: 32,
368
+ implementation: undefined
369
+ };
370
+
371
+ // packages/core/src/provider-safe-text.ts
372
+ var UnsafeProviderContentPattern = [
373
+ "```",
374
+ "[dD][iI][fF][fF]\\s*--\\s*[gG][iI][tT]",
375
+ "@@",
376
+ "[tT][eE][rR][mM][iI][nN][aA][lL][\\s_-]*[lL][oO][gG]",
377
+ "[rR][aA][wW][\\s_-]*[lL][oO][gG]",
378
+ "[pP][rR][oO][vV][iI][dD][eE][rR][\\s_-]*[pP][aA][yY][lL][oO][aA][dD]",
379
+ "[pP][rR][oO][vV][iI][dD][eE][rR][\\s_-]*[cC][oO][mM][mM][eE][nN][tT]",
380
+ "[rR][aA][wW][\\s_-]*[pP][rR][oO][vV][iI][dD][eE][rR]",
381
+ "\\b[sS][kK]-",
382
+ "[gG][hH][pP]_",
383
+ "[gG][lL][pP][aA][tT]-",
384
+ "[bB][eE][aA][rR][eE][rR]\\s",
385
+ "\\b[eE][yY][jJ]"
386
+ ].join("|");
387
+ var CredentialWordPattern = [
388
+ "[tT][oO][kK][eE][nN]",
389
+ "[sS][eE][cC][rR][eE][tT]",
390
+ "[pP][aA][sS][sS][wW][oO][rR][dD]",
391
+ "[pP][rR][iI][vV][aA][tT][eE][\\s_-]*[kK][eE][yY]",
392
+ "[aA][pP][iI][\\s_-]*[kK][eE][yY]"
393
+ ].join("|");
394
+ var SafeProviderMetadataPattern = `^(?!.*(?:${UnsafeProviderContentPattern}|${CredentialWordPattern}))[A-Za-z0-9][A-Za-z0-9 ._:/()+-]{0,119}$`;
395
+
396
+ // packages/core/src/change-request.ts
397
+ var ChangeRequestStatuses = ["draft", "open", "closed", "merged"];
398
+ var ChangeRequestStatus = Literals(ChangeRequestStatuses);
399
+ var ChangeRequestProviderRef = Struct({
400
+ provider: RepoBindingProvider,
401
+ host: String4.check(isMinLength(1)),
402
+ owner: String4.check(isMinLength(1)),
403
+ repositoryName: String4.check(isMinLength(1)),
404
+ providerRepositoryId: String4.check(isMinLength(1)),
405
+ url: String4.check(isMinLength(1)),
406
+ externalId: String4.check(isMinLength(1))
407
+ });
408
+ var ChangeRequestProviderMetadata = Struct({
409
+ headCommitSha: optionalKey(String4.check(isMinLength(7), isMaxLength(64), isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
410
+ baseCommitSha: optionalKey(String4.check(isMinLength(7), isMaxLength(64), isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
411
+ bodyDigest: optionalKey(String4.check(isPattern(new RegExp("^[a-f0-9]{64}$", "u")))),
412
+ labels: optionalKey(ArraySchema(String4.check(isMinLength(1), isMaxLength(120), isPattern(new RegExp(SafeProviderMetadataPattern, "u")))).check(isMaxLength(100))),
413
+ mergeable: optionalKey(Boolean2),
414
+ conflicts: optionalKey(Boolean2),
415
+ forked: optionalKey(Boolean2),
416
+ mergeState: optionalKey(String4.check(isMinLength(1), isMaxLength(120), isPattern(new RegExp(SafeProviderMetadataPattern, "u")))),
417
+ checkState: optionalKey(String4.check(isMinLength(1), isMaxLength(120), isPattern(new RegExp(SafeProviderMetadataPattern, "u")))),
418
+ reviewState: optionalKey(String4.check(isMinLength(1), isMaxLength(120), isPattern(new RegExp(SafeProviderMetadataPattern, "u")))),
419
+ reviewHeadCommitSha: optionalKey(String4.check(isMinLength(7), isMaxLength(64), isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
420
+ checkHeadCommitSha: optionalKey(String4.check(isMinLength(7), isMaxLength(64), isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
421
+ snapshotObservedAt: optionalKey(Timestamp),
422
+ reviewObservedAt: optionalKey(Timestamp),
423
+ checkObservedAt: optionalKey(Timestamp),
424
+ reconciliationState: optionalKey(Literals(["current", "required"]))
425
+ });
426
+ var ChangeRequest = Struct({
427
+ id: Id,
428
+ workspaceId: Id,
429
+ teamId: optionalKey(Id),
430
+ taskIds: ArraySchema(Id),
431
+ stepAttemptId: optionalKey(Id),
432
+ repoBindingId: Id,
433
+ provider: RepoBindingProvider,
434
+ host: String4.check(isMinLength(1)),
435
+ owner: String4.check(isMinLength(1)),
436
+ repositoryName: String4.check(isMinLength(1)),
437
+ providerRepositoryId: String4.check(isMinLength(1)),
438
+ url: String4.check(isMinLength(1)),
439
+ externalId: String4.check(isMinLength(1)),
440
+ title: String4.check(isMinLength(1)),
441
+ sourceBranch: String4.check(isMinLength(1)),
442
+ targetBranch: String4.check(isMinLength(1)),
443
+ status: ChangeRequestStatus,
444
+ draft: Boolean2,
445
+ providerMetadata: optionalKey(ChangeRequestProviderMetadata),
446
+ mergeRevision: optionalKey(String4.check(isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
447
+ lastObservedAt: Timestamp,
448
+ createdByActorType: ActorType,
449
+ createdByActorId: Id,
450
+ createdAt: Timestamp,
451
+ updatedAt: Timestamp
452
+ });
453
+ var ChangeRequestList = Struct({
454
+ items: ArraySchema(ChangeRequest),
455
+ nextCursor: optionalKey(String4.check(isMinLength(1)))
456
+ });
457
+ var ChangeRequestDetail = Struct({
458
+ changeRequest: ChangeRequest
459
+ });
460
+ var ChangeRequestChangedFile = Struct({
461
+ path: String4,
462
+ previousPath: optionalKey(String4),
463
+ status: Literals(["added", "modified", "removed", "renamed", "copied", "changed"]),
464
+ additions: optionalKey(Int),
465
+ deletions: optionalKey(Int),
466
+ patch: optionalKey(String4),
467
+ patchState: Literals(["shown", "omitted", "truncated", "binary"])
468
+ });
469
+ var ChangeRequestFiles = Struct({
470
+ forge: String4,
471
+ url: String4,
472
+ files: optionalKey(ArraySchema(ChangeRequestChangedFile)),
473
+ more: optionalKey(Boolean2),
474
+ headSha: optionalKey(String4.check(isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u"))))
475
+ });
476
+ var ChangeRequestTaskLink = Struct({ taskId: Id });
477
+ var ChangeRequestReadinessGate = Struct({
478
+ ready: Boolean2,
479
+ reason: optionalKey(String4.check(isMinLength(1), isMaxLength(240)))
480
+ });
481
+ var ChangeRequestReadiness = Struct({
482
+ state: Literals(["ready", "blocked", "stale"]),
483
+ headCommitSha: optionalKey(String4.check(isMinLength(7), isMaxLength(64), isPattern(new RegExp("^[a-fA-F0-9]{7,64}$", "u")))),
484
+ observedAt: Timestamp,
485
+ refreshDueAt: Timestamp,
486
+ freshness: Literals(["current", "stale"]),
487
+ permissionState: Literals(["ready", "missing"]),
488
+ providerUrl: String4.check(isMinLength(1)),
489
+ gates: Struct({
490
+ providerProtection: ChangeRequestReadinessGate,
491
+ providerChecks: ChangeRequestReadinessGate,
492
+ providerReview: ChangeRequestReadinessGate,
493
+ taskAcceptance: ChangeRequestReadinessGate,
494
+ verification: ChangeRequestReadinessGate,
495
+ independence: ChangeRequestReadinessGate,
496
+ authority: ChangeRequestReadinessGate,
497
+ capability: ChangeRequestReadinessGate
498
+ }),
499
+ reasons: ArraySchema(String4.check(isMinLength(1), isMaxLength(240))).check(isMaxLength(8)),
500
+ delivery: DeliveryMode,
501
+ approval: optionalKey(Struct({
502
+ allowed: Boolean2,
503
+ reason: optionalKey(String4.check(isMinLength(1))),
504
+ opened: optionalKey(Literal(true))
505
+ }))
506
+ });
507
+
508
+ // packages/core/src/revert.ts
509
+ var NamedChangeRequest = Struct({
510
+ id: String4,
511
+ reference: String4,
512
+ title: String4,
513
+ url: String4,
514
+ mergeRevision: optionalKey(String4)
515
+ });
516
+ var ContainingRelease = Struct({
517
+ tag: String4,
518
+ version: String4,
519
+ prerelease: Boolean2,
520
+ url: optionalKey(String4)
521
+ });
522
+ var MergedChangeRequest = Struct({
523
+ ...NamedChangeRequest.fields,
524
+ status: ChangeRequestStatus,
525
+ targetBranch: String4,
526
+ mergedAt: optionalKey(String4),
527
+ reverted: optionalKey(Struct({ at: String4, revision: optionalKey(String4) })),
528
+ tasks: ArraySchema(Struct({ id: String4, key: String4, title: String4 })),
529
+ releases: ArraySchema(ContainingRelease),
530
+ later: ArraySchema(NamedChangeRequest)
531
+ });
532
+ var RecordedRevert = Struct({
533
+ revertedAt: String4,
534
+ revision: optionalKey(String4),
535
+ tasks: ArraySchema(Struct({ id: String4, key: String4, state: optionalKey(String4) }))
536
+ });
537
+
538
+ // packages/core/src/plan-waves.ts
539
+ var byRepoBinding = (left, right) => (left.repoBindingId ?? "").localeCompare(right.repoBindingId ?? "");
540
+ var ticketWaves = (tickets) => {
541
+ const placed = new Set;
542
+ const waves = [];
543
+ let left = tickets;
544
+ while (left.length > 0) {
545
+ const ready = left.filter((ticket) => ticket.blockedBy.every((blocker) => placed.has(blocker)));
546
+ if (ready.length === 0)
547
+ break;
548
+ for (const ticket of ready)
549
+ placed.add(ticket.key);
550
+ waves.push(ready.toSorted(byRepoBinding));
551
+ left = left.filter((ticket) => !placed.has(ticket.key));
552
+ }
553
+ return { waves, blocked: left.map((ticket) => ticket.key) };
554
+ };
555
+
556
+ // packages/core/src/run-journal.ts
557
+ var journalEntryMaxBytes = 256 * 1024;
558
+ var JournalExit = toCodecJson(Exit(Json, Json, Defect()));
559
+ var encodeJournalExit = (exit) => encodeUnknownEffect(JournalExit)(map8(exit, (value) => value ?? null));
560
+ var decodeJournalExit = decodeUnknownEffect2(JournalExit);
561
+ var journalSuccess = (value) => runSync(encodeJournalExit(succeed3(value)));
562
+ var JournalStepFailed = TaggedStruct("StepFailed", { step: String4, reason: String4 });
563
+ var JournalOutputInvalid = TaggedStruct("OutputInvalid", {
564
+ step: String4,
565
+ message: String4
566
+ });
567
+ var JournalChildFailed = TaggedStruct("ChildFailed", {
568
+ step: String4,
569
+ loop: String4,
570
+ reason: String4
571
+ });
572
+ var JournalWaitTimedOut = TaggedStruct("WaitTimedOut", { step: String4, event: String4 });
573
+ var journalEntryBytes = (entry) => new TextEncoder().encode(JSON.stringify(entry)).byteLength;
574
+
575
+ // packages/sdk/src/loop/review.ts
576
+ var Severity = Literals(["blocker", "major", "minor"]);
577
+ var Finding = Struct({
578
+ severity: Severity,
579
+ file: String4,
580
+ line: Int,
581
+ detail: String4
582
+ });
583
+ var MergedFinding = Struct({
584
+ id: String4,
585
+ ...Finding.fields,
586
+ seats: ArraySchema(String4),
587
+ blockingSeats: optionalKey(ArraySchema(String4))
588
+ });
589
+ var Rebuttal = Struct({ findingId: String4, reason: String4 });
590
+ var RebuttalVerdict = Struct({ findingId: String4, accepted: Boolean2 });
591
+ var ScopeJudgement = Struct({ met: Boolean2, unmet: ArraySchema(String4) });
592
+
593
+ // packages/sdk/src/loop/role.ts
594
+ var ReviewRoleFinding = Struct({ id: String4, severity: Severity });
595
+ var ReviewRoleInput = Struct({
596
+ changeRequestId: optional(String4),
597
+ base: optional(String4),
598
+ head: optional(String4),
599
+ files: optional(ArraySchema(String4)),
600
+ since: optional(String4),
601
+ approved: optional(String4),
602
+ failing: optional(ArraySchema(String4)),
603
+ notRun: optional(ArraySchema(String4)),
604
+ reviewed: optional(String4),
605
+ earlier: optional(ArraySchema(ReviewRoleFinding))
606
+ });
607
+ var ReviewRoleOutput = Struct({
608
+ findings: ArraySchema(ReviewRoleFinding),
609
+ blocking: Boolean2,
610
+ scope: optional(Struct({ met: Boolean2 })),
611
+ failing: optional(ArraySchema(String4))
612
+ });
613
+ var ReleaseRoleInput = Struct({
614
+ releaseScope: optional(ReleaseScope),
615
+ continues: optional(Struct({
616
+ runId: String4,
617
+ tag: String4,
618
+ revision: String4,
619
+ previousTag: optionalKey(String4),
620
+ url: optionalKey(String4)
621
+ })),
622
+ candidate: optional(Boolean2)
623
+ });
624
+ var ReleaseRoleStatus = Literals([
625
+ "drafted",
626
+ "gate_failed",
627
+ "not_mergeable",
628
+ "rejected",
629
+ "deployed",
630
+ "published",
631
+ "rolled_back",
632
+ "deploy_failed",
633
+ "rollback_failed",
634
+ "timed_out",
635
+ "not_deployed",
636
+ "not_due",
637
+ "nothing_to_release",
638
+ "version_taken"
639
+ ]);
640
+ var ReleaseRoleOutput = Struct({ status: ReleaseRoleStatus });
641
+
642
+ // packages/sdk/src/loop/define.ts
643
+ var LoopOutcome = Literals([
644
+ "feature",
645
+ "bug",
646
+ "refactor",
647
+ "investigation",
648
+ "docs",
649
+ "migration",
650
+ "performance"
651
+ ]);
652
+ class ManifestInvalid extends TaggedError2()("ManifestInvalid", {
653
+ loop: String4,
654
+ message: String4
655
+ }) {
656
+ }
657
+ var jsonSchemaOf = (loop, schema) => try_2({
658
+ try: () => toJsonSchemaDocument(schema),
659
+ catch: (error) => new ManifestInvalid({ loop, message: `Schema has no JSON Schema: ${String(error)}` })
660
+ }).pipe(flatMap3((document) => decodeUnknownEffect2(JsonObjectSchema)({ ...document.schema, $defs: document.definitions }).pipe(mapError2((error) => new ManifestInvalid({ loop, message: error.message })))));
661
+ var JsonObjectSchema = Record(String4, Json);
662
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/workflow/internal/crypto.js
663
+ var encoder = /* @__PURE__ */ new TextEncoder;
664
+ var makeHashDigest = (original) => WebCrypto.use((crypto) => map9(webCryptoDigest(crypto, sha256, encoder.encode(original)), (bytes) => encode(bytes).slice(0, 32)));
665
+
666
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/workflow/Workflow.js
667
+ var TypeId = "~effect/workflow/Workflow";
668
+ var EngineTag = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine");
669
+ var InstanceTag = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine/WorkflowInstance");
670
+ var makeExecutionIdFromPayload = (self, payload) => makeHashDigest(`${self._tag.length}:${self._tag}:${self.idempotencyKey(payload)}`);
671
+ var Proto = {
672
+ [TypeId]: TypeId,
673
+ annotate(tag, value) {
674
+ return makeProto({
675
+ _tag: this._tag,
676
+ payloadSchema: this.payloadSchema,
677
+ successSchema: this.successSchema,
678
+ errorSchema: this.errorSchema,
679
+ annotations: add(this.annotations, tag, value),
680
+ idempotencyKey: this.idempotencyKey,
681
+ suspendedRetrySchedule: this.suspendedRetrySchedule
682
+ });
683
+ },
684
+ annotateMerge(context) {
685
+ return makeProto({
686
+ _tag: this._tag,
687
+ payloadSchema: this.payloadSchema,
688
+ successSchema: this.successSchema,
689
+ errorSchema: this.errorSchema,
690
+ annotations: merge3(this.annotations, context),
691
+ idempotencyKey: this.idempotencyKey,
692
+ suspendedRetrySchedule: this.suspendedRetrySchedule
693
+ });
694
+ },
695
+ execute(fields, opts) {
696
+ return suspend3(() => {
697
+ const payload = this.payloadSchema.make(fields);
698
+ const run = flatMap3(EngineTag, (engine) => flatMap3(makeExecutionIdFromPayload(this, payload), (executionId) => andThen2(annotateCurrentSpan({
699
+ executionId
700
+ }), engine.execute(this, {
701
+ executionId,
702
+ payload,
703
+ discard: opts?.discard,
704
+ detached: opts?.detached,
705
+ suspendedRetrySchedule: this.suspendedRetrySchedule
706
+ }))));
707
+ return opts?.discard ? run : withPendingActivity(run);
708
+ }).pipe(withSpan(`${this._tag}.execute`, {}, {
709
+ captureStackTrace: false
710
+ }));
711
+ },
712
+ poll(executionId) {
713
+ return flatMap3(EngineTag, (engine) => engine.poll(this, executionId)).pipe(withSpan(`${this._tag}.poll`, {
714
+ attributes: {
715
+ executionId
716
+ }
717
+ }, {
718
+ captureStackTrace: false
719
+ }));
720
+ },
721
+ interrupt(executionId) {
722
+ return flatMap3(EngineTag, (engine) => engine.interrupt(this, executionId)).pipe(withSpan(`${this._tag}.interrupt`, {
723
+ attributes: {
724
+ executionId
725
+ }
726
+ }, {
727
+ captureStackTrace: false
728
+ }));
729
+ },
730
+ resume(executionId) {
731
+ return flatMap3(EngineTag, (engine) => engine.resume(this, executionId)).pipe(withSpan(`${this._tag}.resume`, {
732
+ attributes: {
733
+ executionId
734
+ }
735
+ }, {
736
+ captureStackTrace: false
737
+ }));
738
+ },
739
+ toLayer(execute) {
740
+ return effectDiscard(flatMap3(EngineTag, (engine) => engine.register(this, execute)));
741
+ },
742
+ executionId(payload) {
743
+ return flatMap3(orDie(this.payloadSchema.makeEffect(payload)), (payload) => makeExecutionIdFromPayload(this, payload));
744
+ },
745
+ withCompensation: (...args) => withCompensation(...args)
746
+ };
747
+ var makeProto = (options) => {
748
+ function Workflow() {}
749
+ Object.setPrototypeOf(Workflow, Proto);
750
+ Object.assign(Workflow, options);
751
+ return Workflow;
752
+ };
753
+ var make = (tag, options) => makeProto({
754
+ _tag: tag,
755
+ payloadSchema: isSchema(options.payload) ? options.payload : Struct(options.payload),
756
+ successSchema: options.success ?? Void,
757
+ errorSchema: options.error ?? Never,
758
+ annotations: options.annotations ?? empty3(),
759
+ idempotencyKey: options.idempotencyKey,
760
+ suspendedRetrySchedule: options.suspendedRetrySchedule
761
+ });
762
+ var ResultTypeId = "~effect/workflow/Workflow/Result";
763
+ var isResult = (u) => hasProperty(u, ResultTypeId);
764
+ class Suspended extends (/* @__PURE__ */ Class2("effect/workflow/Workflow/Suspended")({
765
+ _tag: /* @__PURE__ */ tag("Suspended"),
766
+ cause: /* @__PURE__ */ optional(/* @__PURE__ */ Cause(Never, /* @__PURE__ */ Defect())),
767
+ failed: /* @__PURE__ */ optional(Boolean2)
768
+ })) {
769
+ [ResultTypeId] = ResultTypeId;
770
+ }
771
+ var wrapActivityResult = (effect, isSuspend) => contextWith((context) => {
772
+ const instance = get4(context, InstanceTag);
773
+ return acquireUseRelease(sync2(() => adoptActivityUnsafe(context, instance) ?? registerActivityUnsafe(instance)), () => effect, (registration, exit) => {
774
+ releaseActivityUnsafe(registration);
775
+ const isSuspended = isSuccess2(exit) && isSuspend(exit.value);
776
+ if (isSuccess2(exit) && isResult(exit.value) && exit.value._tag === "Suspended" && exit.value.cause) {
777
+ instance.cause = instance.cause ? combine2(instance.cause, exit.value.cause) : exit.value.cause;
778
+ }
779
+ return isSuspended && instance.activityState.count > 0 ? waitForZero(instance) : void_3;
780
+ });
781
+ });
782
+ var PendingActivityRegistration = /* @__PURE__ */ Service2("effect/workflow/Workflow/PendingActivityRegistration");
783
+ var registerActivityUnsafe = (instance) => {
784
+ const state = instance.activityState;
785
+ if (state.count === 0)
786
+ state.latch.closeUnsafe();
787
+ state.count++;
788
+ return {
789
+ instance,
790
+ state: "pending"
791
+ };
792
+ };
793
+ var adoptActivityUnsafe = (context, instance) => {
794
+ const pending = getOrUndefined2(context, PendingActivityRegistration);
795
+ if (!pending || pending.instance !== instance) {
796
+ return;
797
+ }
798
+ if (pending.state !== "pending") {
799
+ throw new Error("Workflow.wrapActivityResult: pending child registration has already been consumed");
800
+ }
801
+ pending.state = "adopted";
802
+ return pending;
803
+ };
804
+ var releaseActivityUnsafe = (registration) => {
805
+ if (registration.state === "released")
806
+ return;
807
+ registration.state = "released";
808
+ const state = registration.instance.activityState;
809
+ state.count--;
810
+ if (state.count === 0)
811
+ state.latch.openUnsafe();
812
+ };
813
+ var withPendingActivity = (effect) => contextWith((context) => {
814
+ const instance = getOrUndefined2(context, InstanceTag);
815
+ if (!instance)
816
+ return effect;
817
+ return acquireUseRelease(sync2(() => registerActivityUnsafe(instance)), (registration) => provideService(effect, PendingActivityRegistration, registration), (registration) => sync2(() => releaseActivityUnsafe(registration)));
818
+ });
819
+ var waitForZero = /* @__PURE__ */ fnUntraced(function* (instance) {
820
+ const state = instance.activityState;
821
+ while (true) {
822
+ if (state.count > 0) {
823
+ yield* state.latch.await;
824
+ yield* yieldNow;
825
+ continue;
826
+ }
827
+ yield* yieldNow;
828
+ if (state.count === 0)
829
+ return;
830
+ }
831
+ });
832
+ var addFinalizer = /* @__PURE__ */ fnUntraced(function* (f) {
833
+ const instance = yield* InstanceTag;
834
+ const services = yield* context();
835
+ yield* addFinalizerExit(instance.scope, (exit) => instance.abandoned ? void_3 : provideContext2(f(exit), services));
836
+ });
837
+ var withCompensation = /* @__PURE__ */ dual(2, (effect, compensation) => uninterruptibleMask2((restore) => tap2(restore(effect), (value) => addFinalizer((exit) => isSuccess2(exit) ? void_3 : compensation(value, exit.cause)))));
838
+ var suspend = (instance) => interruptible(callback3(() => {
839
+ instance.suspended = true;
840
+ const fiber = getCurrent();
841
+ fiber.interruptUnsafe(fiber.id);
842
+ }));
843
+
844
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/workflow/DurableDeferred.js
845
+ var TypeId2 = "~effect/workflow/DurableDeferred";
846
+ var make2 = (name, options) => {
847
+ const successSchema = options?.success ?? Void;
848
+ const errorSchema = options?.error ?? Never;
849
+ return {
850
+ [TypeId2]: TypeId2,
851
+ name,
852
+ successSchema,
853
+ errorSchema,
854
+ exitSchema: Exit(toCodecJson(successSchema), toCodecJson(errorSchema), toCodecJson(Defect())),
855
+ withActivityAttempt: gen(function* () {
856
+ const attempt = yield* CurrentAttempt;
857
+ return make2(`${name}/${attempt}`, {
858
+ success: successSchema,
859
+ error: errorSchema
860
+ });
861
+ })
862
+ };
863
+ };
864
+ var EngineTag2 = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine");
865
+ var InstanceTag2 = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine/WorkflowInstance");
866
+ var CurrentAttempt = /* @__PURE__ */ Reference("effect/workflow/Activity/CurrentAttempt", {
867
+ defaultValue: () => 1
868
+ });
869
+ var awaitOwners = /* @__PURE__ */ new WeakMap;
870
+ var registerAwait = (instance, name) => {
871
+ instance.awaitedDeferreds.set(name, (instance.awaitedDeferreds.get(name) ?? 0) + 1);
872
+ awaitOwners.get(instance)?.push(name);
873
+ };
874
+ var await_ = /* @__PURE__ */ fnUntraced(function* (self) {
875
+ const engine = yield* EngineTag2;
876
+ const instance = yield* InstanceTag2;
877
+ registerAwait(instance, self.name);
878
+ const exit = yield* wrapActivityResult(engine.deferredResult(self), isNone);
879
+ if (isNone(exit)) {
880
+ return yield* suspend(instance);
881
+ }
882
+ return yield* exit.value;
883
+ });
884
+ class TokenParsed extends (/* @__PURE__ */ Class2("effect/workflow/DurableDeferred/TokenParsed")({
885
+ workflowName: String4,
886
+ executionId: String4,
887
+ deferredName: String4
888
+ })) {
889
+ get asToken() {
890
+ return encode3(JSON.stringify([this.workflowName, this.executionId, this.deferredName]));
891
+ }
892
+ static FromString = /* @__PURE__ */ String4.pipe(/* @__PURE__ */ decodeTo2(/* @__PURE__ */ fromJsonString(/* @__PURE__ */ Tuple2([String4, String4, String4])), {
893
+ decode: /* @__PURE__ */ decodeBase64UrlString(),
894
+ encode: /* @__PURE__ */ encodeBase64Url()
895
+ }), /* @__PURE__ */ decodeTo2(TokenParsed, {
896
+ decode: /* @__PURE__ */ transform(([workflowName, executionId, deferredName]) => new TokenParsed({
897
+ workflowName,
898
+ executionId,
899
+ deferredName
900
+ })),
901
+ encode: /* @__PURE__ */ transform((parsed) => [parsed.workflowName, parsed.executionId, parsed.deferredName])
902
+ }));
903
+ static fromString = /* @__PURE__ */ decodeSync(TokenParsed.FromString);
904
+ static encode = /* @__PURE__ */ encodeSync(TokenParsed.FromString);
905
+ }
906
+ var token = /* @__PURE__ */ fnUntraced(function* (self) {
907
+ const instance = yield* InstanceTag2;
908
+ return tokenFromExecutionId(self, instance);
909
+ });
910
+ var tokenFromExecutionId = /* @__PURE__ */ dual(2, (self, options) => new TokenParsed({
911
+ workflowName: options.workflow._tag,
912
+ executionId: options.executionId,
913
+ deferredName: self.name
914
+ }).asToken);
915
+
916
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/workflow/Activity.js
917
+ var TypeId3 = "~effect/workflow/Activity";
918
+ var make3 = (options) => {
919
+ const successSchema = options.success ?? Void;
920
+ const errorSchema = options.error ?? Never;
921
+ const successSchemaJson = toCodecJson(successSchema);
922
+ const errorSchemaJson = toCodecJson(errorSchema);
923
+ let execute;
924
+ const executeWithoutInterrupt = retryOnInterrupt(options.name, options.interruptRetryPolicy)(options.execute);
925
+ const self = {
926
+ ...Prototype({
927
+ label: "Activity",
928
+ evaluate(_) {
929
+ return execute;
930
+ }
931
+ }),
932
+ [TypeId3]: TypeId3,
933
+ name: options.name,
934
+ successSchema,
935
+ errorSchema,
936
+ exitSchema: Exit(successSchemaJson, errorSchemaJson, Defect()),
937
+ exitSchemaPartial: Exit(successSchemaJson, errorSchemaJson, Unknown),
938
+ annotations: options.annotations ?? empty3(),
939
+ annotate(tag, value) {
940
+ return make3({
941
+ ...options,
942
+ annotations: add(self.annotations, tag, value)
943
+ });
944
+ },
945
+ annotateMerge(context) {
946
+ return make3({
947
+ ...options,
948
+ annotations: merge3(self.annotations, context)
949
+ });
950
+ },
951
+ execute: executeWithoutInterrupt,
952
+ executeEncoded: matchEffect2(executeWithoutInterrupt, {
953
+ onFailure: (error) => flatMap3(orDie(encodeEffect(errorSchemaJson)(error)), fail7),
954
+ onSuccess: (value) => orDie(encodeEffect(successSchemaJson)(value))
955
+ })
956
+ };
957
+ execute = makeExecute(self);
958
+ return self;
959
+ };
960
+ var interruptRetryPolicy = /* @__PURE__ */ min2([exponential(400, 1.5), spaced("10 seconds")]).pipe(/* @__PURE__ */ setInputType(), /* @__PURE__ */ while_((meta) => meta.attempt <= 10 && hasInterrupts2(meta.input)));
961
+ var retryOnInterrupt = (name, policy = interruptRetryPolicy) => (effect) => flatMap3(InstanceTag3, (instance) => effect.pipe(sandbox, retry({
962
+ schedule: policy,
963
+ while: () => !instance.suspended
964
+ }), catch_((cause) => hasInterrupts2(cause) && !instance.suspended ? die3(`Activity "${name}" interrupted and retry attempts exhausted`) : failCause3(cause))));
965
+ var CurrentAttempt2 = /* @__PURE__ */ Reference("effect/workflow/Activity/CurrentAttempt", {
966
+ defaultValue: () => 1
967
+ });
968
+ var EngineTag3 = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine");
969
+ var InstanceTag3 = /* @__PURE__ */ Service2("effect/workflow/WorkflowEngine/WorkflowInstance");
970
+ var makeExecute = /* @__PURE__ */ fnUntraced(function* (activity) {
971
+ const engine = yield* EngineTag3;
972
+ const instance = yield* InstanceTag3;
973
+ const attempt = yield* CurrentAttempt2;
974
+ yield* annotateCurrentSpan({
975
+ executionId: instance.executionId
976
+ });
977
+ const result = yield* wrapActivityResult(engine.activityExecute(activity, attempt), (_) => _._tag === "Suspended");
978
+ if (result._tag === "Suspended") {
979
+ if (result.failed)
980
+ instance.failed = true;
981
+ return yield* suspend(instance);
982
+ }
983
+ return yield* result.exit;
984
+ }, (effect, activity) => withSpan(effect, activity.name, {
985
+ captureStackTrace: false
986
+ }));
987
+ // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/workflow/WorkflowEngine.js
988
+ class WorkflowEngine extends (/* @__PURE__ */ Service2()("effect/workflow/WorkflowEngine")) {
989
+ }
990
+ // packages/core/src/agent-round.ts
991
+ var prefix = "agent_work";
992
+ var named = new RegExp(`^${prefix}(?:#(\\d+))?/(.*)$`, "s");
993
+
994
+ // packages/sdk/src/loop/evidence.ts
995
+ var EvidenceCheck = Struct({
996
+ name: String4,
997
+ command: String4,
998
+ status: Literals(["passed", "failed"]),
999
+ preExisting: Boolean2,
1000
+ durationMs: Finite,
1001
+ evidenceId: String4,
1002
+ outputTail: optionalKey(String4),
1003
+ failedTests: optionalKey(ArraySchema(String4)),
1004
+ suggested: optionalKey(Boolean2),
1005
+ skippedSinceBaseline: optionalKey(ArraySchema(String4)),
1006
+ newNotRun: optionalKey(ArraySchema(String4)),
1007
+ environmentFailure: optionalKey(Struct({
1008
+ failedTests: optionalKey(ArraySchema(String4)),
1009
+ exitCode: optionalKey(Int),
1010
+ outputTail: optionalKey(String4),
1011
+ retryFailedTests: optionalKey(ArraySchema(String4))
1012
+ }))
1013
+ });
1014
+ var VerifyResult = Struct({
1015
+ revision: String4,
1016
+ tree: String4,
1017
+ passed: Boolean2,
1018
+ unchanged: optionalKey(Boolean2),
1019
+ checks: ArraySchema(EvidenceCheck)
1020
+ });
1021
+
1022
+ // packages/sdk/src/loop/steps.ts
1023
+ class StepFailed extends TaggedError2()("StepFailed", {
1024
+ step: String4,
1025
+ reason: String4,
1026
+ code: optional(String4)
1027
+ }) {
1028
+ get message() {
1029
+ return `Step "${this.step}" failed: ${this.reason}`;
1030
+ }
1031
+ }
1032
+ class OutputInvalid extends TaggedError2()("OutputInvalid", {
1033
+ step: String4,
1034
+ message: String4
1035
+ }) {
1036
+ }
1037
+
1038
+ class QuestionRefused extends TaggedError2()("QuestionRefused", {
1039
+ step: String4,
1040
+ answer: String4,
1041
+ options: ArraySchema(String4)
1042
+ }) {
1043
+ }
1044
+
1045
+ class WaitTimedOut extends TaggedError2()("WaitTimedOut", {
1046
+ step: String4,
1047
+ event: String4
1048
+ }) {
1049
+ }
1050
+
1051
+ class ChangeRequestClosed extends TaggedError2()("ChangeRequestClosed", {
1052
+ step: String4,
1053
+ merged: Boolean2
1054
+ }) {
1055
+ }
1056
+
1057
+ class ChildFailed extends TaggedError2()("ChildFailed", {
1058
+ step: String4,
1059
+ loop: String4,
1060
+ reason: String4
1061
+ }) {
1062
+ get message() {
1063
+ return `Child Run of "${this.loop}" for Step "${this.step}" failed: ${this.reason}`;
1064
+ }
1065
+ }
1066
+
1067
+ class CapabilityDenied extends TaggedError2()("CapabilityDenied", {
1068
+ step: String4,
1069
+ capability: Literals(LoopCapabilities),
1070
+ secret: optionalKey(String4)
1071
+ }) {
1072
+ get message() {
1073
+ return this.secret === undefined ? `Step "${this.step}" needs the "${this.capability}" capability, which this Run was not granted` : `Step "${this.step}" names the Secret "${this.secret}", which its Loop does not declare`;
1074
+ }
1075
+ }
1076
+
1077
+ class DuplicateStep extends TaggedError2()("DuplicateStep", {
1078
+ step: String4
1079
+ }) {
1080
+ }
1081
+
1082
+ class InputInvalid extends TaggedError2()("InputInvalid", {
1083
+ loop: String4,
1084
+ message: String4
1085
+ }) {
1086
+ }
1087
+ var LoopEvent = Struct({ type: String4, payload: Record(String4, Json) });
1088
+
1089
+ class LoopRun extends Service2()("@kitman-sh/sdk/loop/LoopRun") {
1090
+ }
1091
+ var ScriptedToLose = Reference("@kitman-sh/sdk/loop/ScriptedToLose", {
1092
+ defaultValue: () => false
1093
+ });
1094
+
1095
+ class LoopHost extends Service2()("@kitman-sh/sdk/loop/LoopHost") {
1096
+ }
1097
+ var TakenClaim = Struct({ step: String4, resource: String4 });
1098
+ var FirstBranches = Reference("@kitman-sh/sdk/loop/FirstBranches", {
1099
+ defaultValue: () => []
1100
+ });
1101
+ var FirstEntry = Reference("@kitman-sh/sdk/loop/FirstEntry", { defaultValue: () => "" });
1102
+ var noteInBranches = (take) => map9(FirstBranches, (branches) => branches.forEach(take));
1103
+ var agentDeferredNamed = (deferredName) => make2(deferredName, { success: Json, error: StepFailed });
1104
+ var syncDeferred = (step) => agentDeferredNamed(`sync/${step}`);
1105
+ var answerDeferred = (step) => make2(`ask/${step}`, { success: String4, error: StepFailed });
1106
+ var eventDeferred = (step) => make2(`wait_for/${step}`, { success: LoopEvent, error: WaitTimedOut });
1107
+ var verifyDeferred = (step) => make2(`verify/${step}`, { success: VerifyResult, error: StepFailed });
1108
+ var recordStep = (name, kind, exit) => {
1109
+ if (isSuccess2(exit))
1110
+ return { name, kind, status: "succeeded", result: exit.value };
1111
+ if (hasInterruptsOnly(exit.cause))
1112
+ return;
1113
+ return { name, kind, status: "failed", error: squash(exit.cause) };
1114
+ };
1115
+ var StepScope = Reference("@kitman-sh/sdk/loop/StepScope", { defaultValue: () => "" });
1116
+ var scopedName = (scope, name) => scope === "" ? name : `${scope}/${name}`;
1117
+ var stepName = (name) => gen(function* () {
1118
+ const run = yield* LoopRun;
1119
+ const scope = yield* StepScope;
1120
+ for (let visit = scope;visit !== ""; visit = visit.slice(0, Math.max(visit.lastIndexOf("/"), 0))) {
1121
+ if (run.names.has(scopedName(visit, name)))
1122
+ return scopedName(visit, name);
1123
+ }
1124
+ return run.names.has(name) ? name : scopedName(scope, name);
1125
+ });
1126
+ var ActivityNamed = Reference("@kitman-sh/sdk/loop/ActivityNamed", {
1127
+ defaultValue: () => false
1128
+ });
1129
+ var namedActivity = (activity) => activity.annotate(ActivityNamed, true);
1130
+ var takeStep = (name, kind, capability, body, taken = false) => gen(function* () {
1131
+ const run = yield* LoopRun;
1132
+ const step = scopedName(yield* StepScope, name);
1133
+ if (!taken && run.names.has(step))
1134
+ return yield* new DuplicateStep({ step });
1135
+ if (capability !== undefined && !run.granted.has(capability))
1136
+ return yield* new CapabilityDenied({ step, capability });
1137
+ if (!taken) {
1138
+ run.names.add(step);
1139
+ yield* noteInBranches((branch) => branch.names.push(step));
1140
+ }
1141
+ return yield* body(step).pipe(onExit((exit) => sync2(() => {
1142
+ const record = recordStep(step, kind, exit);
1143
+ if (record !== undefined)
1144
+ run.steps.push(record);
1145
+ })), withSpan(step, { attributes: { "kitman.loop": run.loop, "kitman.step": step, "kitman.kind": kind } }));
1146
+ });
1147
+ var launch = (deferred, start, step = deferred.name.slice(deferred.name.indexOf("/") + 1)) => gen(function* () {
1148
+ const branches = yield* FirstBranches;
1149
+ const noted = { step, deferredName: deferred.name };
1150
+ for (const branch of branches)
1151
+ branch.launches.push(noted);
1152
+ return yield* namedActivity(make3({
1153
+ name: deferred.name,
1154
+ error: StepFailed,
1155
+ execute: gen(function* () {
1156
+ return yield* start(yield* LoopHost, yield* token(deferred));
1157
+ })
1158
+ }));
1159
+ });
1160
+ var submittedBy = (step, deferred, options) => gen(function* () {
1161
+ const run = yield* LoopRun;
1162
+ const agentId = Object.hasOwn(run.agents, options.agent) ? run.agents[options.agent] : undefined;
1163
+ const undeclared = options.secrets?.find((secret) => !run.secrets.has(secret));
1164
+ if (undeclared !== undefined)
1165
+ return yield* new CapabilityDenied({ step, capability: "agent_work", secret: undeclared });
1166
+ if (agentId === undefined)
1167
+ return yield* new StepFailed({ step, reason: `The Loop declares no agent "${options.agent}" in its agents` });
1168
+ const output = yield* jsonSchemaOf(run.loop, options.answer ?? options.output).pipe(mapError2((error) => new StepFailed({ step, reason: error.message })));
1169
+ yield* launch(deferred, (host, token2) => host.startAgentWork({
1170
+ step,
1171
+ deferredName: deferred.name,
1172
+ role: options.agent,
1173
+ agent: agentId,
1174
+ prompt: options.prompt,
1175
+ ...options.skill === undefined ? undefined : { skill: options.skill },
1176
+ output,
1177
+ ...options.secrets === undefined ? undefined : { secrets: options.secrets },
1178
+ ...options.timeout === undefined ? undefined : { timeoutMillis: toMillis(fromInputUnsafe(options.timeout)) },
1179
+ ...options.mergeTarget === undefined ? undefined : { mergeTarget: options.mergeTarget },
1180
+ ...options.applyChange === undefined ? undefined : { applyChange: options.applyChange },
1181
+ token: token2
1182
+ }), step);
1183
+ return yield* await_(deferred);
1184
+ });
1185
+ var decodeOutput = (step, schema, submitted) => decodeEffect(toCodecJson(schema))(submitted).pipe(mapError2((error) => new OutputInvalid({ step, message: error.message })));
1186
+ var agentWorkAs = (deferredOf, name, options) => takeStep(name, "agent_work", "agent_work", (step) => flatMap3(submittedBy(step, deferredOf(step), options), (submitted) => decodeOutput(step, options.output, submitted)));
1187
+ var ask = (name, question) => takeStep(name, "ask", "ask", (name) => gen(function* () {
1188
+ const deferred = answerDeferred(name);
1189
+ const offered = "options" in question ? splitQuestionOptions(question.options) : undefined;
1190
+ const options = offered?.options;
1191
+ const recommended = "recommended" in question ? question.recommended : undefined;
1192
+ const informationOnly = "informationOnly" in question ? question.informationOnly : undefined;
1193
+ const advice = questionAdvice({
1194
+ ...offered,
1195
+ ...recommended === undefined ? undefined : { recommended },
1196
+ recommendationReason: question.recommendationReason,
1197
+ ...informationOnly === undefined ? undefined : { informationOnly }
1198
+ });
1199
+ const refused = recommendationProblem({ ...advice, ...options === undefined ? undefined : { options } });
1200
+ if (refused !== undefined)
1201
+ return yield* new StepFailed({ step: name, reason: refused });
1202
+ const fallback = question.default === undefined ? recommendedDefault(recommended) : question.default ?? undefined;
1203
+ if (fallback !== undefined && options !== undefined && !options.includes(fallback))
1204
+ return yield* new QuestionRefused({ step: name, answer: fallback, options });
1205
+ if (question.auto !== undefined && options !== undefined && !options.includes(question.auto))
1206
+ return yield* new QuestionRefused({ step: name, answer: question.auto, options });
1207
+ if (question.unattendedAuto !== undefined && options !== undefined && !options.includes(question.unattendedAuto))
1208
+ return yield* new QuestionRefused({ step: name, answer: question.unattendedAuto, options });
1209
+ yield* launch(deferred, (host, token2) => host.putQuestion({
1210
+ step: name,
1211
+ prompt: question.prompt,
1212
+ ...options === undefined ? undefined : { options },
1213
+ ...advice,
1214
+ ...fallback === undefined ? undefined : { default: fallback },
1215
+ ...question.auto === undefined ? undefined : { auto: question.auto },
1216
+ ...question.unattendedAuto === undefined ? undefined : { unattendedAuto: question.unattendedAuto },
1217
+ ...question.evidence === undefined ? undefined : { evidence: question.evidence },
1218
+ ...question.timeout === undefined ? undefined : { timeoutMillis: toMillis(fromInputUnsafe(question.timeout)) },
1219
+ token: token2
1220
+ }));
1221
+ const answer = yield* await_(deferred);
1222
+ if (options === undefined) {
1223
+ return answer;
1224
+ }
1225
+ const offeredAnswer = options.find((option) => option === answer);
1226
+ if (offeredAnswer === undefined)
1227
+ return yield* new QuestionRefused({ step: name, answer, options });
1228
+ return offeredAnswer;
1229
+ }));
1230
+ var waitFor = (name, wait) => takeStep(name, "wait_for", undefined, (name) => gen(function* () {
1231
+ const deferred = eventDeferred(name);
1232
+ const timeoutMillis = toMillis(fromInputUnsafe(wait.timeout));
1233
+ yield* launch(deferred, (host, token2) => host.awaitEvent({
1234
+ step: name,
1235
+ event: wait.event,
1236
+ ...wait.filter === undefined ? undefined : { filter: wait.filter },
1237
+ ...wait.since === undefined ? undefined : { since: wait.since },
1238
+ ...wait.or === undefined ? undefined : { or: wait.or },
1239
+ timeoutMillis,
1240
+ token: token2
1241
+ }));
1242
+ const event = yield* await_(deferred);
1243
+ if (event.type === "change_request.closed" && wait.event !== event.type && wait.or?.some((other) => other.event === event.type) !== true)
1244
+ return yield* new ChangeRequestClosed({
1245
+ step: name,
1246
+ merged: event.payload.merged === true
1247
+ });
1248
+ return event;
1249
+ }));
1250
+ var verify = (name, request) => takeStep(name, "verify", "verify", (name) => gen(function* () {
1251
+ const deferred = verifyDeferred(name);
1252
+ yield* launch(deferred, (host, token2) => host.startVerification({
1253
+ step: name,
1254
+ ...request.revision === undefined ? undefined : { revision: request.revision },
1255
+ ...request.checks === undefined ? undefined : { checks: request.checks },
1256
+ ...request.suggested === undefined || request.suggested.length === 0 ? undefined : { suggested: request.suggested },
1257
+ ...request.extra === undefined || request.extra.length === 0 ? undefined : { extra: request.extra },
1258
+ ...request.rerunFailed === true ? { rerunFailed: true } : undefined,
1259
+ token: token2
1260
+ }));
1261
+ return yield* await_(deferred);
1262
+ }));
1263
+ // packages/sdk/src/loop/unfinished.ts
1264
+ class JournalWriteFailed extends TaggedError("JournalWriteFailed") {
1265
+ get message() {
1266
+ return `Journal write failed: ${this.cause.message}`;
1267
+ }
1268
+ }
1269
+ var journalLoss = (cause) => cause.reasons.flatMap((reason) => isDieReason(reason) && reason.defect instanceof JournalWriteFailed ? [reason.defect] : [])[0];
1270
+ var ParkSinks = Reference("@kitman-sh/sdk/loop/ParkSinks", {
1271
+ defaultValue: () => []
1272
+ });
1273
+ var isUnfinished = (exit, parked = false) => isFailure2(exit) && (journalLoss(exit.cause) !== undefined || hasInterruptsOnly(exit.cause) || parked && hasInterrupts2(exit.cause));
1274
+
1275
+ // packages/sdk/src/loop/claims.ts
1276
+ var claimDeferred = (step) => make2(`claim/${step}`, { success: ClaimResult, error: StepFailed });
1277
+ var claimEndDeferred = (claim) => make2(`claim_end/${claim}`, { success: Null, error: StepFailed });
1278
+ var CurrentVisit = Reference("@kitman-sh/sdk/loop/CurrentVisit", {
1279
+ defaultValue: () => {
1280
+ return;
1281
+ }
1282
+ });
1283
+ var holdingByRun = new WeakMap;
1284
+ var holdingOf = (run) => {
1285
+ const known = holdingByRun.get(run);
1286
+ if (known !== undefined)
1287
+ return known;
1288
+ const holding = { open: new Map, ended: new Set, grants: new WeakMap };
1289
+ holdingByRun.set(run, holding);
1290
+ return holding;
1291
+ };
1292
+ var ending = (holding, claims) => forEach(claims, ({ step, resource }) => suspend3(() => {
1293
+ if (holding.ended.has(step))
1294
+ return void_3;
1295
+ return launch(claimEndDeferred(step), (host, token) => host.claimResource({ ...endOf(step, resource), token }), step).pipe(tap2(() => sync2(() => {
1296
+ holding.ended.add(step);
1297
+ holding.open.delete(step);
1298
+ })));
1299
+ }), { discard: true });
1300
+ var endOf = (step, resource) => ({
1301
+ step,
1302
+ resource,
1303
+ action: "let_go",
1304
+ deferredName: claimEndDeferred(step).name,
1305
+ claims: [step]
1306
+ });
1307
+ var endsWith = (visit, of) => of === visit || of?.state === "unfinished" && endsWith(visit, of.calledIn);
1308
+ var visiting = (effect) => gen(function* () {
1309
+ const holding = holdingOf(yield* LoopRun);
1310
+ const visit = { calledIn: yield* CurrentVisit, state: "running", parked: false };
1311
+ const sinks = yield* ParkSinks;
1312
+ return yield* exit(effect.pipe(provideService(CurrentVisit, visit), provideService(ParkSinks, [...sinks, visit]))).pipe(flatMap3((exit) => {
1313
+ const unfinished = isUnfinished(exit, visit.parked);
1314
+ const ended = { exit, unfinished };
1315
+ if (unfinished) {
1316
+ visit.state = "unfinished";
1317
+ return succeed6(ended);
1318
+ }
1319
+ return orDie(ending(holding, [...holding.open.values()].filter((open) => endsWith(visit, open.visit)))).pipe(andThen2(sync2(() => visit.state = "ended")), as(ended));
1320
+ }), onExit(() => sync2(() => {
1321
+ if (visit.state === "running")
1322
+ visit.state = "unfinished";
1323
+ })));
1324
+ });
1325
+ var claimOnce = (name, request, action) => takeStep(name, "claim", "claim", (step) => gen(function* () {
1326
+ const holding = holdingOf(yield* LoopRun);
1327
+ const deferred = claimDeferred(step);
1328
+ const { resource, changeRequestId } = request;
1329
+ const current = request.keep === "run" ? undefined : yield* CurrentVisit;
1330
+ const visit = request.keep === "caller" ? current?.calledIn : current;
1331
+ const open = { step, resource, visit: visit?.state === "running" ? visit : undefined };
1332
+ holding.open.set(step, open);
1333
+ for (const branch of yield* FirstBranches)
1334
+ branch.claims.push({ step, resource });
1335
+ const result = yield* launch(deferred, (host, token) => host.claimResource({
1336
+ step,
1337
+ resource,
1338
+ action,
1339
+ token,
1340
+ ...changeRequestId === undefined ? undefined : { changeRequestId }
1341
+ })).pipe(andThen2(await_(deferred)), tapError2(() => sync2(() => holding.open.delete(step))));
1342
+ if (result.status === "granted")
1343
+ holding.grants.set(result, step);
1344
+ else
1345
+ holding.open.delete(step);
1346
+ return result;
1347
+ }));
1348
+ var takeOver = "Take it over";
1349
+ var holderName = (holder) => holder.private === true ? "a Run of a private Team you are not in" : `Run ${holder.runId} of ${holder.loopId}`;
1350
+ var claim = (name, request) => gen(function* () {
1351
+ const first = yield* claimOnce(name, request, "claim");
1352
+ if (first.status === "granted")
1353
+ return first;
1354
+ const { holder } = first;
1355
+ const fallback = holder.sameLoop ? takeOver : "Leave it";
1356
+ const askFirst = !(holder.sameLoop && request.takeOverOwnLoop === true);
1357
+ const answer = askFirst && (yield* LoopRun).granted.has("ask") ? yield* ask(`${name}-offer`, {
1358
+ prompt: `${request.resource} is still held by ${holderName(holder)}${holder.status === undefined ? "" : `, which ${holder.status}`}${holder.reason === undefined ? "" : `: ${holder.reason}`}. Take it over?`,
1359
+ options: [takeOver, "Leave it"],
1360
+ recommended: fallback,
1361
+ recommendationReason: holder.sameLoop ? "The holder is this Loop on the same repository and its program died without ending, so nothing else is using it." : "Another Loop holds it and may still need it; waiting is safer than taking it from under that Run.",
1362
+ timeout: request.timeout ?? "10 minutes"
1363
+ }) : fallback;
1364
+ if (answer !== takeOver)
1365
+ return yield* new StepFailed({ step: name, reason: `${request.resource} was left to ${holderName(holder)}` });
1366
+ const taken = yield* claimOnce(`${name}-take-over`, request, "take_over");
1367
+ if (taken.status === "granted")
1368
+ return taken;
1369
+ return yield* new StepFailed({ step: name, reason: `${request.resource} is kept by ${holderName(taken.holder)}` });
1370
+ });
1371
+
1372
+ // packages/sdk/src/loop/step.ts
1373
+ var StepError = Union([
1374
+ StepFailed,
1375
+ DuplicateStep,
1376
+ CapabilityDenied,
1377
+ OutputInvalid,
1378
+ QuestionRefused,
1379
+ WaitTimedOut,
1380
+ ChangeRequestClosed,
1381
+ ChildFailed
1382
+ ]);
1383
+ var serviceFree = (effect) => provide3(effect, empty3());
1384
+ var declared = [];
1385
+ var stackSite = /\(?((?:[a-z]+:\/\/)?[^\s()]+):(\d+):(\d+)\)?$/u;
1386
+ var callSite = (above) => {
1387
+ const trace = new Error("defined here");
1388
+ Error.captureStackTrace(trace, above);
1389
+ const frame = trace.stack?.split(`
1390
+ `).find((line) => line.trimStart().startsWith("at "));
1391
+ const site = frame === undefined ? undefined : stackSite.exec(frame.trim());
1392
+ return site === null || site === undefined ? undefined : `${site[1]}:${site[2]}:${site[3]}`;
1393
+ };
1394
+ var ActivitiesScoped = Reference("@kitman-sh/sdk/loop/ActivitiesScoped", {
1395
+ defaultValue: () => false
1396
+ });
1397
+ var authorDeferredPrefixes = ["DurableClock/", "Activity/"];
1398
+ var scopedDeferredName = (scope, name) => {
1399
+ const prefix = authorDeferredPrefixes.find((candidate) => name.startsWith(candidate));
1400
+ if (prefix === undefined || scope === "" || name.startsWith(`${prefix}${scope}/`))
1401
+ return name;
1402
+ return `${prefix}${scopedName(scope, name.slice(prefix.length))}`;
1403
+ };
1404
+ var renamed = (value, name, more = {}) => name === value.name ? value : Object.create(value, { name: { value: name }, ...more });
1405
+ var outsideVisits = (effect) => effect.pipe(provideService(StepScope, ""), provideService(ActivitiesScoped, false));
1406
+ var scopingActivities = (engine) => ({
1407
+ ...engine,
1408
+ deferredResult: (deferred) => flatMap3(StepScope, (scope) => engine.deferredResult(renamed(deferred, scopedDeferredName(scope, deferred.name)))),
1409
+ deferredDone: (deferred, options) => flatMap3(StepScope, (scope) => {
1410
+ const deferredName = scopedDeferredName(scope, options.deferredName);
1411
+ return outsideVisits(engine.deferredDone(renamed(deferred, scopedDeferredName(scope, deferred.name)), { ...options, deferredName }));
1412
+ }),
1413
+ scheduleClock: (workflow, options) => flatMap3(StepScope, (scope) => {
1414
+ const deferred = renamed(options.clock.deferred, scopedDeferredName(scope, options.clock.deferred.name));
1415
+ const name = deferred.name.slice("DurableClock/".length);
1416
+ return outsideVisits(engine.scheduleClock(workflow, {
1417
+ ...options,
1418
+ clock: renamed(options.clock, name, { deferred: { value: deferred } })
1419
+ }));
1420
+ }),
1421
+ activityExecute: (activity, attempt) => gen(function* () {
1422
+ const scope = yield* StepScope;
1423
+ if (scope === "" || get4(activity.annotations, ActivityNamed))
1424
+ return yield* engine.activityExecute(activity, attempt);
1425
+ return yield* engine.activityExecute(renamed(activity, scopedName(scope, activity.name)), attempt);
1426
+ })
1427
+ });
1428
+ var tagOf = (value, otherwise) => hasProperty(value, "_tag") && isString(value._tag) ? value._tag : otherwise;
1429
+ var scopeActivities = (effect) => gen(function* () {
1430
+ if (yield* ActivitiesScoped)
1431
+ return yield* effect;
1432
+ const engine = yield* serviceOption(WorkflowEngine);
1433
+ if (isNone(engine))
1434
+ return yield* effect;
1435
+ return yield* effect.pipe(provideService(WorkflowEngine, scopingActivities(engine.value)), provideService(ActivitiesScoped, true));
1436
+ });
1437
+ var VisitEntry = Struct({
1438
+ payload: Json,
1439
+ outcome: String4,
1440
+ result: optionalKey(Json),
1441
+ error: optionalKey(Json)
1442
+ });
1443
+ var visitParts = ["payload", "outcome", "result", "error"];
1444
+ var fitsJournal = (entry) => journalEntryBytes(journalSuccess(entry)) <= journalEntryMaxBytes;
1445
+ var fittingJournal = (visit, entry) => {
1446
+ if (fitsJournal(entry))
1447
+ return { entry, ticketsParts: [] };
1448
+ const largestFirst = visitParts.flatMap((part) => {
1449
+ const value = entry[part];
1450
+ return value === undefined ? [] : [{ part, value, bytes: journalEntryBytes(value) }];
1451
+ }).toSorted((left, right) => right.bytes - left.bytes);
1452
+ const drawn = runTicketsPayload(visit, entry.payload);
1453
+ const fitting = { ...entry };
1454
+ let ticketsParts = [];
1455
+ for (const { part, value, bytes } of largestFirst) {
1456
+ if (fitsJournal(fitting))
1457
+ break;
1458
+ const leftOut = `Left out: its ${bytes} bytes do not fit this entry, which holds ${journalEntryMaxBytes}`;
1459
+ if (part === "outcome" || part === "error") {
1460
+ fitting[part] = leftOut;
1461
+ continue;
1462
+ }
1463
+ const kept = part === "payload" ? drawn.kept : runTicketResult(value);
1464
+ fitting[part] = Object.keys(kept).length === 0 ? leftOut : { leftOut, ...kept };
1465
+ if (part === "payload")
1466
+ ticketsParts = drawn.parts;
1467
+ }
1468
+ return { entry: fitting, ticketsParts };
1469
+ };
1470
+ var step = (name, options) => {
1471
+ const payloadSchema = isSchema(options.payload) ? options.payload : Struct(options.payload);
1472
+ const successSchema = options.success ?? Void;
1473
+ const errorSchema = options.error ?? Never;
1474
+ const failure = Union([errorSchema, StepError]);
1475
+ const reference = Reference(`@kitman-sh/sdk/loop/step/${name}/${declared.length}`, {
1476
+ defaultValue: () => options.run
1477
+ });
1478
+ const encode = (visit, schema, value) => serviceFree(encodeUnknownEffect(toCodecJson(schema))(value)).pipe(flatMap3(decodeUnknownEffect2(Json)), mapError2((error) => new StepFailed({ step: visit, reason: error.message })));
1479
+ const decode = (visit, schema, value) => serviceFree(decodeEffect(toCodecJson(schema))(value)).pipe(mapError2((error) => new StepFailed({ step: visit, reason: `scripted outcome: ${error.message}` })));
1480
+ const scriptedExit = (visit, scripted) => ("success" in scripted) ? decode(visit, successSchema, scripted.success) : flatMap3(decode(visit, failure, scripted.error), fail7);
1481
+ const ended = (visit, payload, exit) => gen(function* () {
1482
+ if (isSuccess2(exit)) {
1483
+ const result = yield* encode(visit, successSchema, exit.value);
1484
+ return { payload, outcome: tagOf(exit.value, "succeeded"), result };
1485
+ }
1486
+ const error = squash(exit.cause);
1487
+ const encoded = yield* serviceFree(encodeUnknownEffect(toCodecJson(failure))(error)).pipe(flatMap3(decodeUnknownEffect2(Json)), orElseSucceed(() => ({ message: error instanceof Error ? error.message : String(error) })));
1488
+ return { payload, outcome: tagOf(error, "failed"), error: encoded };
1489
+ });
1490
+ const visitOf = (payload) => gen(function* () {
1491
+ const run = yield* LoopRun;
1492
+ const called = scopedName(yield* StepScope, options.key === undefined ? name : `${name}[${options.key(payload)}]`);
1493
+ const count = (run.visitCounts.get(called) ?? 0) + 1;
1494
+ run.visitCounts.set(called, count);
1495
+ const visit = count === 1 ? called : `${called}#${count}`;
1496
+ if (run.names.has(visit))
1497
+ return yield* new DuplicateStep({ step: visit });
1498
+ run.names.add(visit);
1499
+ yield* noteInBranches((branch) => {
1500
+ branch.names.push(visit);
1501
+ branch.visits.push(called);
1502
+ });
1503
+ return { run, visit };
1504
+ });
1505
+ const call = (payload) => gen(function* () {
1506
+ const { run, visit } = yield* visitOf(payload);
1507
+ const encodedPayload = yield* encode(visit, payloadSchema, payload);
1508
+ const scripted = run.scriptedVisit?.(visit, name);
1509
+ return yield* gen(function* () {
1510
+ const body = scripted === undefined ? flatMap3(service(reference), (take) => take(payload)).pipe(provideService(StepScope, visit), scopeActivities) : (yield* ScriptedToLose) ? await_(make2(`first/held/${visit}`, { success: Never, error: Never })) : scriptedExit(visit, scripted);
1511
+ const { exit: exit2, unfinished } = scripted === undefined ? yield* visiting(body) : yield* map9(exit(body), (exit2) => ({ exit: exit2, unfinished: isUnfinished(exit2) }));
1512
+ if (unfinished)
1513
+ return yield* exit2;
1514
+ const entry = yield* ended(visit, encodedPayload, exit2);
1515
+ yield* annotateCurrentSpan("kitman.outcome", entry.outcome);
1516
+ const journaled = fittingJournal(visit, entry);
1517
+ for (const { name: part, text } of journaled.ticketsParts)
1518
+ yield* namedActivity(make3({ name: part, success: String4, execute: succeed6(text) }));
1519
+ yield* namedActivity(make3({ name: `step/${visit}`, success: VisitEntry, execute: succeed6(journaled.entry) }));
1520
+ run.visits.push(visitRecord(visit, name, entry, scripted !== undefined));
1521
+ return yield* exit2;
1522
+ }).pipe(withSpan(name, { attributes: { "kitman.loop": run.loop, "kitman.step": name, "kitman.visit": visit } }));
1523
+ });
1524
+ const definedAt = callSite(step);
1525
+ const defined = Object.assign(call, {
1526
+ payloadSchema,
1527
+ successSchema,
1528
+ errorSchema,
1529
+ definedAt,
1530
+ run: reference,
1531
+ layer: (replacement) => succeed5(reference, replacement),
1532
+ succeeded: (result) => ({
1533
+ success: runSync(encode(name, successSchema, result))
1534
+ }),
1535
+ failed: (error) => ({
1536
+ error: runSync(encode(name, failure, error))
1537
+ })
1538
+ });
1539
+ Object.defineProperty(defined, "name", { value: name });
1540
+ declared.push(defined);
1541
+ return defined;
1542
+ };
1543
+ var visitRecord = (visit, step, entry, scripted) => ({
1544
+ name: visit,
1545
+ step,
1546
+ payload: entry.payload,
1547
+ outcome: entry.outcome,
1548
+ ...scripted ? { scripted: true } : undefined,
1549
+ ...entry.error === undefined ? { status: "succeeded", result: entry.result ?? null } : { status: "failed", error: entry.error }
1550
+ });
1551
+
1552
+ class StepDefinedTwice extends TaggedError2()("StepDefinedTwice", {
1553
+ step: String4,
1554
+ first: String4,
1555
+ second: String4
1556
+ }) {
1557
+ get message() {
1558
+ return `Two Steps are defined with the name "${this.step}", at ${this.first} and at ${this.second}; give each a name of its own`;
1559
+ }
1560
+ }
1561
+ var stepDefinedTwice = (steps) => {
1562
+ const seen = new Map;
1563
+ for (const declaration of steps) {
1564
+ const first = seen.get(declaration.name);
1565
+ if (first !== undefined && first !== declaration)
1566
+ return new StepDefinedTwice({
1567
+ step: declaration.name,
1568
+ first: first.definedAt ?? "an unknown place",
1569
+ second: declaration.definedAt ?? "an unknown place"
1570
+ });
1571
+ seen.set(declaration.name, declaration);
1572
+ }
1573
+ return;
1574
+ };
1575
+ // packages/sdk/src/loop/first.ts
1576
+ var Taken = Struct({
1577
+ entry: String4,
1578
+ names: ArraySchema(String4),
1579
+ visits: ArraySchema(String4),
1580
+ launches: ArraySchema(Struct({ step: String4, deferredName: String4 })),
1581
+ claims: optional(ArraySchema(TakenClaim))
1582
+ });
1583
+ var FirstRecord = Struct({ winner: String4, stopped: ArraySchema(Taken), kept: ArraySchema(Taken) });
1584
+ // packages/sdk/src/loop/plan.ts
1585
+ var PlanTicket = Struct({
1586
+ key: String4,
1587
+ title: String4,
1588
+ body: String4,
1589
+ acceptanceCriteria: ArraySchema(String4),
1590
+ promise: optional(String4),
1591
+ outOfScope: optional(ArraySchema(String4)),
1592
+ repoBindingId: optional(String4),
1593
+ blockedBy: ArraySchema(String4),
1594
+ outcome: optional(LoopOutcome)
1595
+ });
1596
+ var cycleMessage = (keys) => `These tickets block each other in a cycle, so none can start: ${keys.join(", ")}`;
1597
+ var ticketsProblem = (tickets) => {
1598
+ const keys = new Set;
1599
+ for (const ticket of tickets) {
1600
+ if (keys.has(ticket.key))
1601
+ return `Two tickets have the key "${ticket.key}"`;
1602
+ keys.add(ticket.key);
1603
+ }
1604
+ for (const ticket of tickets)
1605
+ for (const blocker of ticket.blockedBy)
1606
+ if (!keys.has(blocker))
1607
+ return `Ticket "${ticket.key}" is blocked by "${blocker}", which is not a ticket`;
1608
+ const { blocked } = ticketWaves(tickets);
1609
+ return blocked.length === 0 ? undefined : cycleMessage(blocked);
1610
+ };
1611
+ var planTicketsOf = (ticket) => ArraySchema(ticket).check(makeFilter((tickets) => ticketsProblem(tickets) ?? true));
1612
+ var PlanTickets = planTicketsOf(PlanTicket);
1613
+
1614
+ class BlockingCycle extends TaggedError2()("BlockingCycle", {
1615
+ tickets: ArraySchema(String4)
1616
+ }) {
1617
+ get message() {
1618
+ return cycleMessage(this.tickets);
1619
+ }
1620
+ }
1621
+
1622
+ // packages/sdk/src/loop/deploy-target-order.ts
1623
+ var deployTargetOrder = () => [];
1624
+
1625
+ // packages/sdk/src/loop/host-step.ts
1626
+ var defineStep = (definition) => {
1627
+ const { id, kind, capability, request, result } = definition;
1628
+ const service = Service2(`@kitman-sh/sdk/loop/HostStep/${id}`);
1629
+ const journalName = (name) => `${kind}/${name}`;
1630
+ const gatedBy = (gate) => (name, stepRequest) => takeStep(name, kind, gate, (step) => namedActivity(make3({
1631
+ name: journalName(step),
1632
+ success: result,
1633
+ error: StepFailed,
1634
+ execute: gen(function* () {
1635
+ return yield* (yield* service).run(stepRequest, step);
1636
+ })
1637
+ })));
1638
+ return {
1639
+ id,
1640
+ kind,
1641
+ capability,
1642
+ request,
1643
+ result,
1644
+ double: "doubleEachRun" in definition ? definition.doubleEachRun : () => definition.double,
1645
+ service,
1646
+ journalName,
1647
+ step: gatedBy(capability),
1648
+ stepForKitman: gatedBy(undefined)
1649
+ };
1650
+ };
1651
+
1652
+ // packages/sdk/src/loop/activities.ts
1653
+ var ChangeRequestRequest = Struct({
1654
+ title: String4,
1655
+ body: String4,
1656
+ integration: optional(String4)
1657
+ });
1658
+ var ChangeRequestResult = Struct({ id: String4, number: String4, url: String4 });
1659
+ var BranchChangeRequestRequest = Struct({
1660
+ title: String4,
1661
+ body: String4,
1662
+ source: String4,
1663
+ target: optional(String4),
1664
+ repoBindingId: optional(String4)
1665
+ });
1666
+ var BranchChangeRequest = Union([
1667
+ Struct({
1668
+ status: Literal("open"),
1669
+ ...ChangeRequestResult.fields,
1670
+ opened: Boolean2
1671
+ }),
1672
+ Struct({ status: Literal("nothing") }),
1673
+ Struct({ status: Literal("elsewhere"), team: String4 })
1674
+ ]);
1675
+ var WriteBackMilestones = ["started", "change_request_opened", "merged", "failed", "blocked"];
1676
+ var WriteBackRequest = Struct({
1677
+ milestone: optional(Literals(WriteBackMilestones)),
1678
+ changeRequestUrl: optional(String4)
1679
+ });
1680
+ var RunFile = Struct({ runFile: String4 }).pipe(decodeTo2(Struct({ id: String4 }), transform2({
1681
+ decode: ({ runFile }) => ({ id: runFile }),
1682
+ encode: ({ id }) => ({ runFile: id })
1683
+ })));
1684
+ var FileRequest = Struct({ path: String4, caption: optional(String4) });
1685
+ var ArtifactRequest = Struct({
1686
+ kind: String4,
1687
+ title: String4,
1688
+ text: String4,
1689
+ data: optional(Json),
1690
+ files: optional(ArraySchema(RunFile))
1691
+ });
1692
+ var ArtifactResult = Struct({ artifactId: String4 });
1693
+ var NoteRequest = Struct({
1694
+ text: String4,
1695
+ artifactId: optional(String4),
1696
+ kind: optional(Literals(["note", "blocker"]))
1697
+ });
1698
+ var CreateTasksRequest = Struct({
1699
+ tickets: ArraySchema(PlanTicket),
1700
+ projectId: optionalKey(String4),
1701
+ builds: optionalKey(Boolean2),
1702
+ releases: optionalKey(Boolean2),
1703
+ planReviewed: optionalKey(Boolean2)
1704
+ });
1705
+ var CreateTasksResult = Struct({
1706
+ tasks: ArraySchema(Struct({ key: String4, taskId: String4 }))
1707
+ });
1708
+ var AlertTaskRequest = Struct({
1709
+ fingerprint: String4.check(isMinLength(1), isMaxLength(400)),
1710
+ title: String4,
1711
+ windowHours: Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo(720)),
1712
+ resolved: optionalKey(Boolean2),
1713
+ priority: optionalKey(Literals(["urgent", "high", "medium", "low"]))
1714
+ });
1715
+ var AlertTaskResult = Struct({
1716
+ taskId: optionalKey(String4),
1717
+ created: Boolean2,
1718
+ resolved: optionalKey(Boolean2),
1719
+ joined: optionalKey(Struct({ kind: Literals(["run", "recent"]), runId: String4 }))
1720
+ });
1721
+ var BranchRequest = Struct({
1722
+ branch: String4,
1723
+ from: optional(String4),
1724
+ repoBindingId: optional(String4)
1725
+ });
1726
+ var Branch = Struct({
1727
+ repoBindingId: String4,
1728
+ branch: String4,
1729
+ revision: String4,
1730
+ created: Boolean2
1731
+ });
1732
+ var IntegrationBranchRequest = Struct({
1733
+ repoBindingId: optional(String4),
1734
+ base: optional(Boolean2)
1735
+ });
1736
+ var IntegrationBranch = Struct({ ...Branch.fields, created: optional(Boolean2) });
1737
+ var MergeChangeRequestRequest = Struct({
1738
+ changeRequestId: String4,
1739
+ head: optionalKey(String4),
1740
+ rebase: optionalKey(Boolean2)
1741
+ });
1742
+ var MergeResult = Union([
1743
+ Struct({ status: Literal("merged"), revision: String4 }),
1744
+ Struct({
1745
+ status: Literal("conflict"),
1746
+ reason: optionalKey(Literals(["conflicts", "behind", "not_ready"]))
1747
+ }),
1748
+ Struct({ status: Literal("moved"), head: String4 })
1749
+ ]);
1750
+ var ApproveChangeRequestRequest = Struct({
1751
+ changeRequestId: String4,
1752
+ head: String4,
1753
+ summary: String4,
1754
+ review: optionalKey(String4),
1755
+ carries: optionalKey(String4),
1756
+ reuses: optionalKey(String4)
1757
+ });
1758
+ var ApproveChangeRequestResult = Union([
1759
+ Struct({ approved: Literal(true), reviewId: String4 }),
1760
+ Struct({ approved: Literal(false), reason: String4 })
1761
+ ]);
1762
+ var CloseChangeRequestRequest = Struct({
1763
+ number: String4,
1764
+ head: String4,
1765
+ note: String4
1766
+ });
1767
+ var CloseChangeRequestResult = Struct({
1768
+ closed: Boolean2,
1769
+ head: optionalKey(String4)
1770
+ });
1771
+ var RerunPipelineRequest = Union([
1772
+ Struct({ changeRequestId: String4 }),
1773
+ Struct({ ref: String4, all: optionalKey(Boolean2) })
1774
+ ]);
1775
+ var RerunPipelineResult = Struct({ head: String4, pipelines: Int });
1776
+ var ReportPipelineRequest = Struct({ changeRequestId: String4, verification: String4 });
1777
+ var ReportPipelineResult = Struct({
1778
+ head: String4,
1779
+ status: Literals(["success", "failed"])
1780
+ });
1781
+ var CommentRequest = Struct({
1782
+ changeRequestId: String4,
1783
+ body: String4,
1784
+ threadId: optionalKey(String4),
1785
+ summary: optionalKey(String4),
1786
+ anchors: optionalKey(ArraySchema(Struct({
1787
+ file: String4,
1788
+ line: Int.check(isGreaterThanOrEqualTo(1)),
1789
+ body: String4.check(isMinLength(1))
1790
+ })))
1791
+ });
1792
+ var ReleaseRequest = Struct({
1793
+ tag: String4,
1794
+ revision: optional(String4),
1795
+ title: String4,
1796
+ notes: String4,
1797
+ prerelease: optional(Boolean2),
1798
+ previousTag: optional(NullOr(String4)),
1799
+ branch: optional(String4),
1800
+ squashed: optional(Boolean2)
1801
+ });
1802
+ var ReleaseResult = Struct({ tag: String4, revision: String4, url: String4 });
1803
+ var ChangeRequestReadRequest = Struct({ changeRequestId: String4 });
1804
+ var PipelineStatusRequest = Struct({
1805
+ changeRequestId: String4,
1806
+ behind: optionalKey(Literal(true))
1807
+ });
1808
+ var PipelineJob = Struct({
1809
+ name: String4,
1810
+ status: Literals(["running", "success", "failed", "skipped"]),
1811
+ url: optional(String4),
1812
+ logTail: optional(String4)
1813
+ });
1814
+ var PipelineStatus = Struct({
1815
+ head: String4,
1816
+ status: Literals(["none", "running", "success", "failed", "canceled"]),
1817
+ source: Literals(["forge", "reported"]),
1818
+ jobs: ArraySchema(PipelineJob),
1819
+ readAt: optionalKey(String4),
1820
+ runnerChecks: optionalKey(ArraySchema(String4)),
1821
+ targetChecks: optionalKey(ArraySchema(String4)),
1822
+ approved: optionalKey(String4),
1823
+ reviewed: optionalKey(Struct({ review: String4, notRun: optionalKey(ArraySchema(String4)) })),
1824
+ repository: optionalKey(String4),
1825
+ sourceBranch: optionalKey(String4),
1826
+ targetBranch: optionalKey(String4),
1827
+ conflicts: optionalKey(Boolean2),
1828
+ needsRebase: optionalKey(Boolean2),
1829
+ behind: optionalKey(Boolean2),
1830
+ target: optionalKey(Struct({ branch: String4, head: String4, jobs: ArraySchema(PipelineJob) }))
1831
+ });
1832
+ var ReviewThread = Struct({
1833
+ id: String4,
1834
+ path: optional(String4),
1835
+ line: optional(Int),
1836
+ outdated: optional(Boolean2),
1837
+ comments: ArraySchema(Struct({ author: optional(String4), body: String4 }))
1838
+ });
1839
+ var ReviewThreads = Struct({ threads: ArraySchema(ReviewThread) });
1840
+ var OpenChangeRequestsRequest = Struct({ authors: NonEmptyArray(String4) });
1841
+ var OpenChangeRequest = Struct({
1842
+ number: String4,
1843
+ title: String4,
1844
+ body: String4,
1845
+ url: String4,
1846
+ author: String4,
1847
+ sourceBranch: String4,
1848
+ head: String4
1849
+ });
1850
+ var OpenChangeRequests = Struct({ changeRequests: ArraySchema(OpenChangeRequest) });
1851
+ var OwnChangeRequest = Struct({
1852
+ id: String4,
1853
+ number: String4,
1854
+ url: String4,
1855
+ title: String4,
1856
+ sourceBranch: String4,
1857
+ body: String4
1858
+ });
1859
+ var OwnChangeRequests = Struct({ changeRequests: ArraySchema(OwnChangeRequest) });
1860
+ var TranscriptPoint = Struct({
1861
+ runId: String4,
1862
+ stepAttemptId: String4,
1863
+ sequence: Int
1864
+ });
1865
+ var TranscriptsRequest = Struct({
1866
+ days: Int.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(31)),
1867
+ teamId: optionalKey(String4),
1868
+ projectId: optionalKey(String4),
1869
+ fileIntoProjectId: optionalKey(String4)
1870
+ });
1871
+ var TranscriptsResult = Struct({
1872
+ runs: ArraySchema(Struct({
1873
+ runId: String4,
1874
+ loopId: String4,
1875
+ rootRunId: optional(String4),
1876
+ status: optional(Literals(["completed", "failed", "canceled", "expired"])),
1877
+ teamId: optional(String4),
1878
+ failure: optional(String4),
1879
+ retried: optional(Boolean2),
1880
+ entries: ArraySchema(Struct({ stepAttemptId: String4, sequence: Int, kind: String4, text: String4 })),
1881
+ omitted: optional(Int)
1882
+ })),
1883
+ artifactId: optional(String4),
1884
+ findings: optional(ArraySchema(Struct({
1885
+ key: String4,
1886
+ title: String4,
1887
+ taskId: optional(String4),
1888
+ taskKey: optional(String4)
1889
+ })))
1890
+ });
1891
+ var Citations = NonEmptyArray(TranscriptPoint);
1892
+ var ProposeRequest = Union([
1893
+ Struct({
1894
+ kind: Literal("memory"),
1895
+ teamId: String4,
1896
+ content: String4,
1897
+ citations: Citations
1898
+ }),
1899
+ Struct({
1900
+ kind: Literal("task"),
1901
+ title: String4,
1902
+ description: String4,
1903
+ teamId: optional(String4),
1904
+ projectId: optionalKey(String4),
1905
+ key: optionalKey(String4.check(isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/), isMaxLength(80))),
1906
+ citations: Citations
1907
+ })
1908
+ ]);
1909
+ var ProposeResult = Struct({
1910
+ kind: Literals(["memory", "task"]),
1911
+ id: String4,
1912
+ matched: optionalKey(Boolean2),
1913
+ task: optionalKey(Struct({ id: String4, active: Boolean2 }))
1914
+ });
1915
+ var Health = Literals(["on_track", "at_risk", "off_track"]);
1916
+ var ProjectActivityRequest = Struct({ projectId: String4 });
1917
+ var ProjectActivityResult = Struct({
1918
+ project: Struct({ id: String4, name: String4 }),
1919
+ health: optional(Health),
1920
+ since: optional(String4),
1921
+ runs: ArraySchema(Struct({
1922
+ runId: String4,
1923
+ loopId: String4,
1924
+ status: String4,
1925
+ taskKey: optional(String4),
1926
+ taskTitle: optional(String4),
1927
+ summary: optional(String4),
1928
+ entries: ArraySchema(Struct({ stepAttemptId: String4, sequence: Int, kind: String4, text: String4 }))
1929
+ })),
1930
+ taskChanges: ArraySchema(Struct({ taskKey: String4, title: String4, change: String4, at: String4 }))
1931
+ });
1932
+ var DraftUpdateRequest = Struct({
1933
+ projectId: String4,
1934
+ health: Health,
1935
+ note: String4,
1936
+ writtenFrom: Struct({
1937
+ runs: Int,
1938
+ taskChanges: Int,
1939
+ since: optional(String4)
1940
+ })
1941
+ });
1942
+ var DraftUpdateResult = Struct({ id: String4 });
1943
+ var CallableLoops = Struct({ loops: ArraySchema(CallableLoop) });
1944
+ var CallableLoopsRequest = Struct({
1945
+ taskId: optional(String4)
1946
+ });
1947
+ var RecordDeployRequest = Struct({
1948
+ target: DeployTargetName,
1949
+ tag: DeployRef,
1950
+ revision: optional(DeployRef),
1951
+ status: DeployStatus,
1952
+ detail: optional(String4)
1953
+ });
1954
+ var RecordDeployResult = Struct({
1955
+ id: String4,
1956
+ target: String4,
1957
+ tag: String4,
1958
+ revision: optionalKey(String4),
1959
+ status: DeployStatus,
1960
+ deployedAt: String4
1961
+ });
1962
+ var DeployTargetRequest = Struct({ target: DeployTargetName });
1963
+ var DeployTargetResult = Struct({
1964
+ target: String4,
1965
+ running: optionalKey(DeployTargetRunning),
1966
+ order: optionalKey(ArraySchema(String4))
1967
+ });
1968
+ var MergedChangeRequestRequest = Struct({ changeRequestId: String4 });
1969
+ var RecordRevertRequest = Struct({
1970
+ changeRequestId: String4,
1971
+ revertedBy: String4,
1972
+ reason: optional(String4)
1973
+ });
1974
+ var LiveBranchesRequest = Struct({
1975
+ changeRequestId: String4
1976
+ });
1977
+ var LiveBranchSource = Literals(["project", "milestone", "release"]);
1978
+ var LiveBranch = Struct({
1979
+ branch: String4,
1980
+ source: LiveBranchSource,
1981
+ name: optionalKey(String4)
1982
+ });
1983
+ var LiveBranches = Struct({ branches: ArraySchema(LiveBranch) });
1984
+ var ChangeRequestStep = defineStep({
1985
+ id: "changeRequest",
1986
+ kind: "change_request",
1987
+ capability: "change_request",
1988
+ request: ChangeRequestRequest,
1989
+ result: ChangeRequestResult,
1990
+ double: () => succeed6({ id: "change-request-1", number: "1", url: "test://change-requests/1" })
1991
+ });
1992
+ var ChangeRequestBetweenStep = defineStep({
1993
+ id: "changeRequestBetween",
1994
+ kind: "change_request",
1995
+ capability: "change_request",
1996
+ request: BranchChangeRequestRequest,
1997
+ result: BranchChangeRequest,
1998
+ doubleEachRun: () => {
1999
+ const numbers = new Map;
2000
+ return (request) => sync2(() => {
2001
+ const key = `${request.repoBindingId ?? "repo"}:${request.source}:${request.target ?? "main"}`;
2002
+ const opened = !numbers.has(key);
2003
+ if (opened)
2004
+ numbers.set(key, numbers.size + 2);
2005
+ const number = String(numbers.get(key));
2006
+ return {
2007
+ status: "open",
2008
+ id: `change-request-${number}`,
2009
+ number,
2010
+ url: `test://change-requests/${number}`,
2011
+ opened
2012
+ };
2013
+ });
2014
+ }
2015
+ });
2016
+ var madeBranches = () => {
2017
+ const branches = new Set;
2018
+ return (repoBindingId, branch2) => {
2019
+ const created = !branches.has(`${repoBindingId}:${branch2}`);
2020
+ branches.add(`${repoBindingId}:${branch2}`);
2021
+ return created;
2022
+ };
2023
+ };
2024
+ var BranchStep = defineStep({
2025
+ id: "branch",
2026
+ kind: "branch",
2027
+ capability: "create_branch",
2028
+ request: BranchRequest,
2029
+ result: Branch,
2030
+ doubleEachRun: (shared) => {
2031
+ const made = shared(madeBranches);
2032
+ return (request) => sync2(() => {
2033
+ const repoBindingId = request.repoBindingId ?? "repo";
2034
+ return {
2035
+ repoBindingId,
2036
+ branch: request.branch,
2037
+ revision: `${request.branch}-head`,
2038
+ created: made(repoBindingId, request.branch)
2039
+ };
2040
+ });
2041
+ }
2042
+ });
2043
+ var WriteBackStep = defineStep({
2044
+ id: "writeBack",
2045
+ kind: "write_back",
2046
+ capability: "write_back",
2047
+ request: WriteBackRequest,
2048
+ result: Void,
2049
+ double: () => void_3
2050
+ });
2051
+ var ArtifactStep = defineStep({
2052
+ id: "artifact",
2053
+ kind: "artifact",
2054
+ capability: undefined,
2055
+ request: ArtifactRequest,
2056
+ result: ArtifactResult,
2057
+ double: (request) => succeed6({ artifactId: request.title })
2058
+ });
2059
+ var FileStep = defineStep({
2060
+ id: "file",
2061
+ kind: "file",
2062
+ capability: undefined,
2063
+ request: FileRequest,
2064
+ result: RunFile,
2065
+ double: (_request, step) => succeed6({ id: `file-${step}` })
2066
+ });
2067
+ var NoteStep = defineStep({
2068
+ id: "note",
2069
+ kind: "note",
2070
+ capability: undefined,
2071
+ request: NoteRequest,
2072
+ result: Void,
2073
+ double: () => void_3
2074
+ });
2075
+ var CommentStep = defineStep({
2076
+ id: "comment",
2077
+ kind: "comment",
2078
+ capability: "post_comment",
2079
+ request: CommentRequest,
2080
+ result: Void,
2081
+ double: () => void_3
2082
+ });
2083
+ var CreateTasksStep = defineStep({
2084
+ id: "createTasks",
2085
+ kind: "create_tasks",
2086
+ capability: "create_tasks",
2087
+ request: CreateTasksRequest,
2088
+ result: CreateTasksResult,
2089
+ double: (request) => succeed6({ tasks: request.tickets.map((ticket) => ({ key: ticket.key, taskId: `task-${ticket.key}` })) })
2090
+ });
2091
+ var AlertTaskStep = defineStep({
2092
+ id: "alertTask",
2093
+ kind: "create_tasks",
2094
+ capability: "create_tasks",
2095
+ request: AlertTaskRequest,
2096
+ result: AlertTaskResult,
2097
+ double: () => succeed6({ taskId: "task-alert", created: true })
2098
+ });
2099
+ var IntegrationBranchStep = defineStep({
2100
+ id: "integrationBranch",
2101
+ kind: "branch",
2102
+ capability: "create_branch",
2103
+ request: IntegrationBranchRequest,
2104
+ result: IntegrationBranch,
2105
+ doubleEachRun: (shared) => {
2106
+ const made = shared(madeBranches);
2107
+ return (request) => sync2(() => {
2108
+ const repoBindingId = request.repoBindingId ?? "repo";
2109
+ const branch2 = request.base === true ? "base" : "kitman/run/integration";
2110
+ return { repoBindingId, branch: branch2, revision: "integration-head", created: made(repoBindingId, branch2) };
2111
+ });
2112
+ }
2113
+ });
2114
+ var DeliveryBaseStep = defineStep({
2115
+ id: "deliveryBase",
2116
+ kind: "integration_branch",
2117
+ capability: "change_request",
2118
+ request: Struct({}),
2119
+ result: IntegrationBranch,
2120
+ doubleEachRun: (shared) => {
2121
+ const made = shared(madeBranches);
2122
+ return () => sync2(() => ({
2123
+ repoBindingId: "repo",
2124
+ branch: "base",
2125
+ revision: "integration-head",
2126
+ created: made("repo", "base")
2127
+ }));
2128
+ }
2129
+ });
2130
+ var MergeChangeRequestStep = defineStep({
2131
+ id: "mergeChangeRequest",
2132
+ kind: "merge_change_request",
2133
+ capability: "merge_change_request",
2134
+ request: MergeChangeRequestRequest,
2135
+ result: MergeResult,
2136
+ double: (request) => succeed6({ status: "merged", revision: `merged-${request.changeRequestId}` })
2137
+ });
2138
+ var ApproveChangeRequestStep = defineStep({
2139
+ id: "approveChangeRequest",
2140
+ kind: "approve_change_request",
2141
+ capability: "approve_change_request",
2142
+ request: ApproveChangeRequestRequest,
2143
+ result: ApproveChangeRequestResult,
2144
+ double: (request) => succeed6({ approved: true, reviewId: `review-${request.changeRequestId}` })
2145
+ });
2146
+ var CloseChangeRequestStep = defineStep({
2147
+ id: "closeChangeRequest",
2148
+ kind: "close_change_request",
2149
+ capability: "merge_change_request",
2150
+ request: CloseChangeRequestRequest,
2151
+ result: CloseChangeRequestResult,
2152
+ double: () => succeed6({ closed: true })
2153
+ });
2154
+ var RerunPipelineStep = defineStep({
2155
+ id: "rerunPipeline",
2156
+ kind: "rerun_pipeline",
2157
+ capability: "merge_change_request",
2158
+ request: RerunPipelineRequest,
2159
+ result: RerunPipelineResult,
2160
+ double: () => succeed6({ head: "head", pipelines: 1 })
2161
+ });
2162
+ var ReportPipelineStep = defineStep({
2163
+ id: "reportPipeline",
2164
+ kind: "report_pipeline",
2165
+ capability: "verify",
2166
+ request: ReportPipelineRequest,
2167
+ result: ReportPipelineResult,
2168
+ double: () => succeed6({ head: "head", status: "success" })
2169
+ });
2170
+ var ReleaseStep = defineStep({
2171
+ id: "release",
2172
+ kind: "release",
2173
+ capability: "publish_release",
2174
+ request: ReleaseRequest,
2175
+ result: ReleaseResult,
2176
+ double: (request) => succeed6({
2177
+ tag: request.tag,
2178
+ revision: request.revision ?? "base-head",
2179
+ url: `test://releases/${request.tag}`
2180
+ })
2181
+ });
2182
+ var TranscriptsStep = defineStep({
2183
+ id: "transcripts",
2184
+ kind: "transcripts",
2185
+ capability: "read_transcripts",
2186
+ request: TranscriptsRequest,
2187
+ result: TranscriptsResult,
2188
+ double: () => succeed6({ runs: [] })
2189
+ });
2190
+ var ProposeStep = defineStep({
2191
+ id: "propose",
2192
+ kind: "propose",
2193
+ capability: "propose",
2194
+ request: ProposeRequest,
2195
+ result: ProposeResult,
2196
+ double: (request, step) => succeed6({ kind: request.kind, id: `${request.kind}-${step}` })
2197
+ });
2198
+ var ProjectActivityStep = defineStep({
2199
+ id: "projectActivity",
2200
+ kind: "project_activity",
2201
+ capability: "read_project",
2202
+ request: ProjectActivityRequest,
2203
+ result: ProjectActivityResult,
2204
+ double: (request) => succeed6({ project: { id: request.projectId, name: request.projectId }, runs: [], taskChanges: [] })
2205
+ });
2206
+ var PipelineStatusStep = defineStep({
2207
+ id: "pipelineStatus",
2208
+ kind: "pipeline_status",
2209
+ capability: "read_change_request",
2210
+ request: PipelineStatusRequest,
2211
+ result: PipelineStatus,
2212
+ double: () => succeed6({
2213
+ head: "head",
2214
+ status: "success",
2215
+ source: "forge",
2216
+ jobs: [],
2217
+ sourceBranch: "change",
2218
+ targetBranch: "main"
2219
+ })
2220
+ });
2221
+ var ReviewThreadsStep = defineStep({
2222
+ id: "reviewThreads",
2223
+ kind: "review_threads",
2224
+ capability: "read_change_request",
2225
+ request: ChangeRequestReadRequest,
2226
+ result: ReviewThreads,
2227
+ double: () => succeed6({ threads: [] })
2228
+ });
2229
+ var OpenChangeRequestsStep = defineStep({
2230
+ id: "openChangeRequests",
2231
+ kind: "open_change_requests",
2232
+ capability: "read_change_request",
2233
+ request: OpenChangeRequestsRequest,
2234
+ result: OpenChangeRequests,
2235
+ double: () => succeed6({ changeRequests: [] })
2236
+ });
2237
+ var OwnChangeRequestsStep = defineStep({
2238
+ id: "ownChangeRequests",
2239
+ kind: "own_change_requests",
2240
+ capability: "read_change_request",
2241
+ request: Struct({}),
2242
+ result: OwnChangeRequests,
2243
+ double: () => succeed6({ changeRequests: [] })
2244
+ });
2245
+ var DraftUpdateStep = defineStep({
2246
+ id: "draftUpdate",
2247
+ kind: "draft_update",
2248
+ capability: "draft_update",
2249
+ request: DraftUpdateRequest,
2250
+ result: DraftUpdateResult,
2251
+ double: (_request, step) => succeed6({ id: `draft-${step}` })
2252
+ });
2253
+ var CallableLoopsStep = defineStep({
2254
+ id: "callableLoops",
2255
+ kind: "callable_loops",
2256
+ capability: "call",
2257
+ request: CallableLoopsRequest,
2258
+ result: CallableLoops,
2259
+ double: () => succeed6({ loops: [] })
2260
+ });
2261
+ var deployedTargets = () => new Map;
2262
+ var RecordDeployStep = defineStep({
2263
+ id: "recordDeploy",
2264
+ kind: "record_deploy",
2265
+ capability: "publish_release",
2266
+ request: RecordDeployRequest,
2267
+ result: RecordDeployResult,
2268
+ doubleEachRun: (shared) => {
2269
+ const running = shared(deployedTargets);
2270
+ let deploys = 0;
2271
+ return (request) => sync2(() => {
2272
+ deploys += 1;
2273
+ const deployedAt = formatIso(makeUnsafe(Date.UTC(2026, 0, 1, 0, deploys)));
2274
+ const revision = request.revision === undefined ? undefined : { revision: request.revision };
2275
+ if (runsDeployedTag(request.status))
2276
+ running.set(request.target, { tag: request.tag, ...revision, since: deployedAt });
2277
+ return {
2278
+ id: `deploy-${deploys}`,
2279
+ target: request.target,
2280
+ tag: request.tag,
2281
+ ...revision,
2282
+ status: request.status,
2283
+ deployedAt
2284
+ };
2285
+ });
2286
+ }
2287
+ });
2288
+ var DeployTargetStep = defineStep({
2289
+ id: "deployTarget",
2290
+ kind: "deploy_target",
2291
+ capability: undefined,
2292
+ request: DeployTargetRequest,
2293
+ result: DeployTargetResult,
2294
+ doubleEachRun: (shared) => {
2295
+ const running = shared(deployedTargets);
2296
+ const order = shared(deployTargetOrder);
2297
+ return (request) => sync2(() => {
2298
+ const runs = running.get(request.target);
2299
+ return {
2300
+ target: request.target,
2301
+ ...runs === undefined ? undefined : { running: runs },
2302
+ ...order.length === 0 ? undefined : { order: [...order] }
2303
+ };
2304
+ });
2305
+ }
2306
+ });
2307
+ var MergedChangeRequestStep = defineStep({
2308
+ id: "mergedChangeRequest",
2309
+ kind: "merged_change_request",
2310
+ capability: "read_change_request",
2311
+ request: MergedChangeRequestRequest,
2312
+ result: MergedChangeRequest,
2313
+ double: (request) => succeed6({
2314
+ id: request.changeRequestId,
2315
+ reference: "!1",
2316
+ title: "Change",
2317
+ url: "test://change-requests/1",
2318
+ mergeRevision: `merged-${request.changeRequestId}`,
2319
+ status: "merged",
2320
+ targetBranch: "main",
2321
+ tasks: [],
2322
+ releases: [],
2323
+ later: []
2324
+ })
2325
+ });
2326
+ var RecordRevertStep = defineStep({
2327
+ id: "recordRevert",
2328
+ kind: "record_revert",
2329
+ capability: "write_back",
2330
+ request: RecordRevertRequest,
2331
+ result: RecordedRevert,
2332
+ double: (request) => succeed6({ revertedAt: "2026-01-01T00:00:00.000Z", revision: `merged-${request.revertedBy}`, tasks: [] })
2333
+ });
2334
+ var LiveBranchesStep = defineStep({
2335
+ id: "liveBranches",
2336
+ kind: "live_branches",
2337
+ capability: "read_change_request",
2338
+ request: LiveBranchesRequest,
2339
+ result: LiveBranches,
2340
+ double: () => succeed6({ branches: [] })
2341
+ });
2342
+ var hostSteps = [
2343
+ ChangeRequestStep,
2344
+ ChangeRequestBetweenStep,
2345
+ BranchStep,
2346
+ WriteBackStep,
2347
+ ArtifactStep,
2348
+ FileStep,
2349
+ NoteStep,
2350
+ CommentStep,
2351
+ CreateTasksStep,
2352
+ AlertTaskStep,
2353
+ IntegrationBranchStep,
2354
+ DeliveryBaseStep,
2355
+ MergeChangeRequestStep,
2356
+ ApproveChangeRequestStep,
2357
+ CloseChangeRequestStep,
2358
+ RerunPipelineStep,
2359
+ ReportPipelineStep,
2360
+ ReleaseStep,
2361
+ TranscriptsStep,
2362
+ ProposeStep,
2363
+ ProjectActivityStep,
2364
+ PipelineStatusStep,
2365
+ ReviewThreadsStep,
2366
+ OpenChangeRequestsStep,
2367
+ OwnChangeRequestsStep,
2368
+ DraftUpdateStep,
2369
+ CallableLoopsStep,
2370
+ RecordDeployStep,
2371
+ DeployTargetStep,
2372
+ MergedChangeRequestStep,
2373
+ LiveBranchesStep,
2374
+ RecordRevertStep
2375
+ ];
2376
+ function changeRequest(name, request) {
2377
+ return "source" in request ? ChangeRequestBetweenStep.step(name, request) : ChangeRequestStep.step(name, request);
2378
+ }
2379
+ var branch = BranchStep.step;
2380
+ var writeBack = WriteBackStep.step;
2381
+ var artifact = ArtifactStep.step;
2382
+ var file = FileStep.step;
2383
+ var note = NoteStep.step;
2384
+ var comment = CommentStep.step;
2385
+ var createTasks = CreateTasksStep.step;
2386
+ var alertTask = AlertTaskStep.step;
2387
+ var integrationBranch = IntegrationBranchStep.step;
2388
+ var deliveryBase = (name) => DeliveryBaseStep.step(name, {});
2389
+ var mergeChangeRequest = MergeChangeRequestStep.step;
2390
+ var approveChangeRequest = (name, request) => gen(function* () {
2391
+ const referred = {
2392
+ ...request,
2393
+ ...request.review === undefined ? undefined : { review: yield* stepName(request.review) },
2394
+ ...request.carries === undefined ? undefined : { carries: yield* stepName(request.carries) }
2395
+ };
2396
+ return yield* ApproveChangeRequestStep.step(name, referred);
2397
+ });
2398
+ var closeChangeRequest = CloseChangeRequestStep.step;
2399
+ var pipelineMoved = (name, changeRequestId, read, timeout = "6 hours") => waitFor(name, {
2400
+ event: "change_request.pipeline",
2401
+ filter: read.readAt === undefined ? { changeRequestId, head: read.head } : { changeRequestId },
2402
+ timeout,
2403
+ ...read.readAt === undefined ? undefined : { since: read.readAt }
2404
+ });
2405
+ var rerunPipeline = RerunPipelineStep.step;
2406
+ var reportPipeline = (name, request) => flatMap3(stepName(request.verification), (verification) => ReportPipelineStep.step(name, { ...request, verification }));
2407
+ var release = ReleaseStep.step;
2408
+ var transcripts = TranscriptsStep.step;
2409
+ var propose = ProposeStep.step;
2410
+ var projectActivity = ProjectActivityStep.step;
2411
+ var pipelineStatus = PipelineStatusStep.step;
2412
+ var reviewThreads = ReviewThreadsStep.step;
2413
+ var openChangeRequests = OpenChangeRequestsStep.step;
2414
+ var ownChangeRequests = (name) => OwnChangeRequestsStep.step(name, {});
2415
+ var draftUpdate = DraftUpdateStep.step;
2416
+ var callableLoops = (name, request = {}) => CallableLoopsStep.step(name, request);
2417
+ var recordDeploy = RecordDeployStep.step;
2418
+ var deployTarget = DeployTargetStep.step;
2419
+ var mergedChangeRequest = MergedChangeRequestStep.step;
2420
+ var recordRevert = RecordRevertStep.step;
2421
+ var liveBranches = LiveBranchesStep.step;
2422
+
2423
+ // packages/sdk/src/loop/green.ts
2424
+ class Green extends TaggedClass2()("Green", {
2425
+ head: String4,
2426
+ jobs: ArraySchema(PipelineJob),
2427
+ pipeline: PipelineStatus
2428
+ }) {
2429
+ }
2430
+
2431
+ class Pending extends TaggedClass2()("Pending", {
2432
+ head: String4,
2433
+ pipeline: PipelineStatus
2434
+ }) {
2435
+ }
2436
+
2437
+ class PipelineFailed extends TaggedError2()("PipelineFailed", {
2438
+ head: String4,
2439
+ jobs: ArraySchema(PipelineJob),
2440
+ target: PipelineStatus.fields.target,
2441
+ pipeline: PipelineStatus
2442
+ }) {
2443
+ }
2444
+
2445
+ class PipelineCanceled extends TaggedError2()("PipelineCanceled", {
2446
+ head: String4,
2447
+ pipeline: PipelineStatus
2448
+ }) {
2449
+ }
2450
+
2451
+ class PipelineNotRun extends TaggedError2()("PipelineNotRun", {
2452
+ head: String4,
2453
+ reason: String4
2454
+ }) {
2455
+ }
2456
+ var green = step("green", {
2457
+ payload: {
2458
+ changeRequestId: String4.annotate({ description: "The ChangeRequest whose pipeline it waits for" }),
2459
+ read: optionalKey(PipelineStatus).annotate({
2460
+ description: "A `pipelineStatus` read the caller already made, which it starts from instead of reading again"
2461
+ }),
2462
+ behind: optionalKey(Literal(true)).annotate({
2463
+ description: "Reads `behind` too, as `pipelineStatus` does when asked"
2464
+ }),
2465
+ looks: optionalKey(Int.check(isGreaterThanOrEqualTo(1))).annotate({
2466
+ description: "Runner runs or waits it takes before it ends Pending; it waits on until the pipeline ends when left out"
2467
+ })
2468
+ },
2469
+ success: Union([Green, Pending]),
2470
+ error: Union([PipelineFailed, PipelineCanceled, PipelineNotRun]),
2471
+ run: ({ changeRequestId, read, behind, looks }) => gen(function* () {
2472
+ const request = { changeRequestId, ...behind === undefined ? undefined : { behind } };
2473
+ let pipeline = read ?? (yield* pipelineStatus("pipeline", request));
2474
+ const ranAt = new Set;
2475
+ for (let look = 1;; look++) {
2476
+ const { head, jobs } = pipeline;
2477
+ if (pipeline.status === "success")
2478
+ return new Green({ head, jobs, pipeline });
2479
+ if (pipeline.status === "failed")
2480
+ return yield* new PipelineFailed({
2481
+ head,
2482
+ jobs,
2483
+ ...pipeline.target === undefined ? undefined : { target: pipeline.target },
2484
+ pipeline
2485
+ });
2486
+ if (pipeline.status === "canceled")
2487
+ return yield* new PipelineCanceled({ head, pipeline });
2488
+ if (looks !== undefined && look > looks)
2489
+ return new Pending({ head, pipeline });
2490
+ const checks = pipeline.runnerChecks;
2491
+ if (pipeline.status === "none" && checks !== undefined && ranAt.has(head))
2492
+ return yield* new PipelineNotRun({ head, reason: "no result was recorded after it ran" });
2493
+ if (pipeline.status === "none" && checks !== undefined) {
2494
+ ranAt.add(head);
2495
+ const verification = `runner:${look}`;
2496
+ yield* verify(verification, { revision: head, checks }).pipe(catchTag("StepFailed", (error) => fail7(new PipelineNotRun({ head, reason: error.reason }))));
2497
+ yield* reportPipeline(`report:${look}`, { changeRequestId, verification });
2498
+ } else
2499
+ yield* pipelineMoved(`moved:${look}`, changeRequestId, pipeline);
2500
+ pipeline = yield* pipelineStatus(`pipeline:${look}`, request);
2501
+ }
2502
+ })
2503
+ });
2504
+ // packages/sdk/src/loop/capabilities.ts
2505
+ var lentCapabilities = [
2506
+ "agent_work",
2507
+ "ask",
2508
+ "call",
2509
+ "verify",
2510
+ "run_command",
2511
+ "measure",
2512
+ "claim"
2513
+ ];
2514
+ var LoopCapabilities2 = [
2515
+ ...new Set([
2516
+ ...lentCapabilities,
2517
+ ...hostSteps.flatMap((step) => step.capability === undefined ? [] : [step.capability])
2518
+ ])
2519
+ ];
2520
+ // packages/sdk/src/loop/run-context.ts
2521
+ class LoopRunContext extends Service2()("@kitman-sh/sdk/loop/RunContext") {
2522
+ }
2523
+
2524
+ // packages/sdk/src/loop/measure.ts
2525
+ var MetricStats = Struct({
2526
+ samples: Finite,
2527
+ median: Finite,
2528
+ mean: Finite,
2529
+ min: Finite,
2530
+ max: Finite,
2531
+ stdev: Finite
2532
+ });
2533
+ var MeasureVerdict = Literals(["gain", "no_gain", "guardrail_regressed", "too_noisy"]);
2534
+ var Measurement = Struct({
2535
+ verdict: MeasureVerdict,
2536
+ reason: String4,
2537
+ metrics: ArraySchema(Struct({
2538
+ name: String4,
2539
+ role: Literals(["primary", "guardrail"]),
2540
+ direction: Literals(["lower", "higher"]),
2541
+ base: MetricStats,
2542
+ head: MetricStats,
2543
+ change: Finite,
2544
+ noise: Finite
2545
+ })),
2546
+ suggestion: optional(String4),
2547
+ evidence: MeasureEvidence
2548
+ });
2549
+ var floors = new WeakMap;
2550
+
2551
+ // packages/sdk/src/loop/versions.ts
2552
+ var versionsDeferred = (step) => make2(`versions/${step}`, { success: TagVersions, error: StepFailed });
2553
+ var versions = (name, request = {}) => takeStep(name, "verify", "verify", (name) => gen(function* () {
2554
+ const deferred = versionsDeferred(name);
2555
+ yield* launch(deferred, (host, token) => host.startVerification({ step: name, versions: request, token }));
2556
+ return yield* await_(deferred);
2557
+ }));
2558
+
2559
+ // packages/sdk/src/loop/test-loop.ts
2560
+ var LoopJournal = Struct({
2561
+ activities: Record(String4, Json),
2562
+ deferreds: Record(String4, Json)
2563
+ });
2564
+
2565
+ class ScriptedFailure extends TaggedClass("ScriptedFailure") {
2566
+ }
2567
+ var targetBranchStep = "kitman:target-branch";
2568
+ var targetBranch = DeliveryBaseStep.stepForKitman(targetBranchStep, {}).pipe(catchTags({ DuplicateStep: die3, CapabilityDenied: die3 }));
2569
+ // packages/sdk/src/loop/check.ts
2570
+ class CheckFailed extends TaggedError2()("CheckFailed", {
2571
+ loop: String4,
2572
+ check: String4,
2573
+ reason: String4
2574
+ }) {
2575
+ get detail() {
2576
+ return `Check "${this.check}": ${this.reason}`;
2577
+ }
2578
+ get message() {
2579
+ return `Loop "${this.loop}": ${this.detail}`;
2580
+ }
2581
+ }
2582
+
2583
+ class StepNamedTwice extends TaggedError2()("StepNamedTwice", {
2584
+ loop: String4,
2585
+ check: String4,
2586
+ step: String4
2587
+ }) {
2588
+ get detail() {
2589
+ return `Check "${this.check}": Step "${this.step}" is named twice`;
2590
+ }
2591
+ get message() {
2592
+ return `Loop "${this.loop}": ${this.detail}`;
2593
+ }
2594
+ }
2595
+
2596
+ class ReplayDiverged extends TaggedError2()("ReplayDiverged", {
2597
+ loop: String4,
2598
+ check: String4,
2599
+ first: ArraySchema(String4),
2600
+ replay: ArraySchema(String4),
2601
+ rerun: ArraySchema(String4)
2602
+ }) {
2603
+ get detail() {
2604
+ const steps = (names) => names.join(", ") || "no Steps";
2605
+ return `Check "${this.check}": its replay from the journal diverged; it took ${steps(this.first)} and then ${steps(this.replay)}${this.rerun.length > 0 ? `, running ${this.rerun.join(", ")} again` : ""}. Keep effects and randomness inside Activities.`;
2606
+ }
2607
+ get message() {
2608
+ return `Loop "${this.loop}": ${this.detail}`;
2609
+ }
2610
+ }
2611
+ var LoopCheckError = Union([CheckFailed, StepNamedTwice, ReplayDiverged]);
2612
+ // packages/sdk/src/loop/sync.ts
2613
+ var UpToDate = Struct({ status: Literal("up_to_date") });
2614
+ var Conflict = Struct({
2615
+ status: Literal("conflict"),
2616
+ files: NonEmptyArray(String4),
2617
+ reason: String4
2618
+ });
2619
+ var merged = {
2620
+ status: Literal("merged"),
2621
+ settled: ArraySchema(String4)
2622
+ };
2623
+ var SyncAnswer = Union([UpToDate, Struct(merged), Conflict]);
2624
+ var reported = { base: optionalKey(String4) };
2625
+ var BaseSync = Union([
2626
+ Struct({ ...UpToDate.fields, ...reported }),
2627
+ Struct({ ...merged, catchUp: optionalKey(CatchUp), ...reported }),
2628
+ Struct({ ...Conflict.fields, ...reported })
2629
+ ]);
2630
+ var afterMerge = "One thing comes before any answer of merged, a clean merge included, and stopping above means stopping after it: before you answer merged, run the `after-merge` command the note names, if it names one, and otherwise what the repository's agent instructions (`AGENTS.md` or `CLAUDE.md`, already in your context) name for after merging the target branch, and read the section that line links when it names no command. Regenerate this branch's database migrations on top of the target's when it adds one, and regenerate each generated file whose source the merge changed, such as API contracts, with the command those instructions name. Do not search the repository for these steps: when the instructions name none, there are none. Leave what that changes in the workspace: Kitman commits it.";
2631
+ var prompt = (target) => [
2632
+ `Kitman merged \`origin/${target}\` into this branch before you started, outside your sandbox, and says what came of it in a note after this brief. Do not fetch, as this workspace has no credential for the forge, and do not run git commands that write, such as \`git add\`, \`git commit\` or \`git merge --abort\`: Kitman finishes the merge itself from your answer.`,
2633
+ "Kitman starts you only when the merge conflicts, or when it merged cleanly and the repository's approved `after-merge` command, which Kitman runs after a clean merge, failed. If it was already up to date, change nothing and answer up_to_date. If it merged cleanly, do what the note says the command could not, answer merged with no settled files and stop: do not review or test anything else.",
2634
+ "If it conflicts, settle each file the note names so both sides' intent survives: leave no conflict marker, and for a file one side deleted or git could not mark, leave it as the version you want or delete it. Run the tests of the files you touched, and answer merged with those files under settled. Kitman then commits the files as you left them.",
2635
+ "If you cannot settle a file, answer conflict with the files and why: Kitman then aborts the whole merge.",
2636
+ "Never rebase, reset or force-push: this branch's history only grows."
2637
+ ].concat(afterMerge).join(`
2638
+
2639
+ `);
2640
+ var syncBase = (name, options) => agentWorkAs(syncDeferred, name, {
2641
+ agent: options.agent,
2642
+ prompt: prompt(options.target ?? "HEAD"),
2643
+ output: BaseSync,
2644
+ answer: SyncAnswer,
2645
+ mergeTarget: options.target ?? "HEAD"
2646
+ });
2647
+ // packages/sdk/src/loop/apply.ts
2648
+ var Conflict2 = Struct({
2649
+ status: Literal("conflict"),
2650
+ files: NonEmptyArray(String4),
2651
+ reason: String4
2652
+ });
2653
+ var settled = {
2654
+ settled: ArraySchema(String4)
2655
+ };
2656
+ var ApplyAnswer = Union([Struct({ status: Literal("applied"), ...settled }), Conflict2]);
2657
+ var AppliedChange = Union([
2658
+ Struct({ status: Literal("applied"), revision: String4, ...settled }),
2659
+ Struct({ status: Literal("already") }),
2660
+ Conflict2
2661
+ ]);
2662
+ // packages/sdk/src/loop/level.ts
2663
+ class Level extends TaggedClass2()("Level", {
2664
+ head: String4
2665
+ }) {
2666
+ }
2667
+
2668
+ class CaughtUp extends TaggedClass2()("CaughtUp", {
2669
+ head: optionalKey(String4),
2670
+ from: optionalKey(String4),
2671
+ carried: Boolean2,
2672
+ unreviewed: ArraySchema(String4),
2673
+ why: optionalKey(String4),
2674
+ sync: String4
2675
+ }) {
2676
+ }
2677
+
2678
+ class Conflict3 extends TaggedError2()("Conflict", {
2679
+ files: NonEmptyArray(String4),
2680
+ reason: String4
2681
+ }) {
2682
+ }
2683
+ var verdictOf = (catchUp) => {
2684
+ if (catchUp.truncated)
2685
+ return { kind: "changed", why: "it changed more files than the Runner compares" };
2686
+ const files = [...new Set([...catchUp.conflicted, ...catchUp.rewritten])];
2687
+ const elsewhere = catchUp.changed.filter((file) => !files.includes(file));
2688
+ if (elsewhere.length > 0)
2689
+ return { kind: "changed", why: `the branch's own diff changed in ${elsewhere.join(", ")}` };
2690
+ return files.length === 0 ? { kind: "carry" } : { kind: "review", files };
2691
+ };
2692
+ var level = step("level", {
2693
+ payload: {
2694
+ changeRequestId: String4.annotate({
2695
+ description: "The ChangeRequest to bring level; the Run works its branch."
2696
+ }),
2697
+ head: String4.annotate({ description: "The ChangeRequest's head as last read." }),
2698
+ agent: String4.annotate({ description: "The agent role that settles conflicts." }),
2699
+ target: optional(String4).annotate({
2700
+ description: "The branch to merge in; the default branch when left out."
2701
+ }),
2702
+ unreviewed: optional(ArraySchema(String4)).annotate({
2703
+ description: "Files an earlier catch-up left to review: the head they are in was never approved, so no approval is carried."
2704
+ })
2705
+ },
2706
+ success: Union([Level, CaughtUp]),
2707
+ error: Conflict3,
2708
+ run: ({ changeRequestId, head, agent, target = "HEAD", unreviewed = [] }) => gen(function* () {
2709
+ const sync = scopedName(yield* StepScope, "sync");
2710
+ const synced = yield* syncBase("sync", { agent, target });
2711
+ if (synced.status === "conflict")
2712
+ return yield* new Conflict3({ files: synced.files, reason: synced.reason });
2713
+ if (synced.status === "up_to_date")
2714
+ return new Level({ head });
2715
+ const caught = synced.catchUp;
2716
+ if (caught === undefined)
2717
+ return new CaughtUp({
2718
+ carried: false,
2719
+ unreviewed: [],
2720
+ why: `merging ${target} in changed it: its Runner did not report what it did to the branch`,
2721
+ sync
2722
+ });
2723
+ const verdict = verdictOf(caught);
2724
+ const pushed = { head: caught.head, from: caught.from, sync };
2725
+ if (verdict.kind === "changed")
2726
+ return new CaughtUp({
2727
+ ...pushed,
2728
+ carried: false,
2729
+ unreviewed: [],
2730
+ why: `merging ${target} in changed it: ${verdict.why}`
2731
+ });
2732
+ const files = [...new Set([...unreviewed, ...verdict.kind === "review" ? verdict.files : []])];
2733
+ if (files.length > 0)
2734
+ return new CaughtUp({ ...pushed, carried: false, unreviewed: files });
2735
+ const carried = yield* approveChangeRequest("carry", {
2736
+ changeRequestId,
2737
+ head: caught.head,
2738
+ summary: `Merging ${target} in left the branch's own diff as it was approved.`,
2739
+ carries: "sync"
2740
+ }).pipe(catchTag("StepFailed", (error) => succeed6({ approved: false, reason: error.reason })));
2741
+ return carried.approved ? new CaughtUp({ ...pushed, carried: true, unreviewed: [] }) : new CaughtUp({
2742
+ ...pushed,
2743
+ carried: false,
2744
+ unreviewed: [],
2745
+ why: `the approval was not carried: ${carried.reason}`
2746
+ });
2747
+ })
2748
+ });
2749
+ // packages/sdk/src/loop/landed.ts
2750
+ class Merged extends TaggedClass2()("Merged", {
2751
+ revision: String4,
2752
+ head: String4
2753
+ }) {
2754
+ }
2755
+
2756
+ class Unapproved extends TaggedError2()("Unapproved", {
2757
+ head: String4,
2758
+ why: String4
2759
+ }) {
2760
+ }
2761
+
2762
+ class MergeRefused extends TaggedError2()("MergeRefused", {
2763
+ reason: String4,
2764
+ cause: Literals(["turn", "pending", "not_ready", "moved", "behind", "up_to_date", "not_shown"])
2765
+ }) {
2766
+ }
2767
+ var LandedApproval = Struct({
2768
+ changeRequestId: String4,
2769
+ head: String4,
2770
+ target: String4,
2771
+ approved: optionalKey(String4),
2772
+ unreviewed: optionalKey(Struct({ files: ArraySchema(String4), caughtUp: String4, sync: String4 })),
2773
+ caughtUp: optionalKey(CaughtUp)
2774
+ });
2775
+ var Approve = declare((value) => isFunction(value), {
2776
+ toCodecJson: () => link()(Null.annotate({
2777
+ format: "function",
2778
+ description: "Gets a head approved, as the Kit's `approved` Step does; it fails when the head is not approved."
2779
+ }), transform2({ decode: () => () => void_3, encode: () => null }))
2780
+ });
2781
+ var isStepError = is(StepError);
2782
+ var whyOf = (error) => {
2783
+ if (isString(error.why))
2784
+ return error.why;
2785
+ return isString(error.reason) ? error.reason : error._tag;
2786
+ };
2787
+ var staleReads = 5;
2788
+ var landed = step("landed", {
2789
+ payload: {
2790
+ changeRequestId: String4.annotate({ description: "The ChangeRequest to merge; the Run works its branch." }),
2791
+ agent: String4.annotate({ description: "The agent role that settles conflicts merging the target in." }),
2792
+ approve: Approve,
2793
+ target: optional(String4).annotate({
2794
+ description: "The branch it merges into, which must be the read's target branch; the read's when left out."
2795
+ }),
2796
+ repository: optional(String4).annotate({
2797
+ description: "The ChangeRequest's RepoBinding, for the turn, which must be the read's; the read's when left out."
2798
+ }),
2799
+ read: optional(PipelineStatus).annotate({
2800
+ description: "A `pipelineStatus` read the caller already made, which it starts from instead of reading again."
2801
+ }),
2802
+ catchUp: optional(Boolean2).annotate({
2803
+ description: "False to fail `MergeRefused` as `behind` when the merge is refused as behind, merging nothing in."
2804
+ })
2805
+ },
2806
+ success: Merged,
2807
+ error: Union([PipelineFailed, PipelineCanceled, PipelineNotRun, Unapproved, Conflict3, MergeRefused]),
2808
+ run: ({ changeRequestId, agent, approve, target: named, repository: boundTo, read, catchUp = true }) => gen(function* () {
2809
+ const approving = (request) => approve(request).pipe(asVoid, mapError2((error) => isStepError(error) ? error : new Unapproved({ head: request.head, why: whyOf(error) })));
2810
+ const greenRead = (from) => flatMap3(green({ changeRequestId, read: from }), (result) => isTagged(result, "Green") ? succeed6(result.pipeline) : fail7(new MergeRefused({ reason: `The pipeline at ${result.head} has no result yet`, cause: "pending" })));
2811
+ const first = read ?? (yield* pipelineStatus("pipeline", { changeRequestId }));
2812
+ const { target, repository } = yield* destinationOf(changeRequestId, first, named, boundTo);
2813
+ const checked = yield* greenRead(first);
2814
+ let head = checked.head;
2815
+ yield* approving({
2816
+ changeRequestId,
2817
+ head,
2818
+ target,
2819
+ ...checked.approved === undefined ? undefined : { approved: checked.approved }
2820
+ });
2821
+ yield* claim("turn", { resource: mergeTurnResource(repository, target), changeRequestId }).pipe(catchTag("StepFailed", (error) => fail7(new MergeRefused({ reason: error.reason, cause: "turn" }))));
2822
+ for (let round = 1;; round++) {
2823
+ const merged = yield* mergeChangeRequest(round === 1 ? "merge" : `merge:${round}`, { changeRequestId, head });
2824
+ if (merged.status === "merged")
2825
+ return new Merged({ revision: merged.revision, head });
2826
+ if (merged.status === "moved")
2827
+ return yield* new MergeRefused({
2828
+ reason: `The head moved to ${merged.head} from ${head}, which it checked`,
2829
+ cause: "moved"
2830
+ });
2831
+ if (merged.reason === "not_ready")
2832
+ return yield* new MergeRefused({ reason: "The forge holds the merge back", cause: "not_ready" });
2833
+ if (!catchUp)
2834
+ return yield* new MergeRefused({
2835
+ reason: `The forge refused the merge of ${head} as behind ${target} or conflicting`,
2836
+ cause: "behind"
2837
+ });
2838
+ const synced = yield* level({ changeRequestId, head, agent, target });
2839
+ if (isTagged(synced, "Level"))
2840
+ return yield* new MergeRefused({
2841
+ reason: `The forge refused the merge, but ${target} had nothing to merge in`,
2842
+ cause: "up_to_date"
2843
+ });
2844
+ const showed = yield* showing(round, changeRequestId, { from: head, head: synced.head });
2845
+ if ("stale" in showed)
2846
+ return yield* new MergeRefused({
2847
+ reason: synced.head === undefined ? `The forge still shows ${showed.stale}, the head from before the catch-up` : `The forge still shows ${showed.stale}, not ${synced.head} that the catch-up pushed`,
2848
+ cause: "not_shown"
2849
+ });
2850
+ const shown = showed.read;
2851
+ head = shown.head;
2852
+ yield* approving({
2853
+ changeRequestId,
2854
+ head,
2855
+ target,
2856
+ ...shown.approved === undefined ? undefined : { approved: shown.approved },
2857
+ ...synced.unreviewed.length === 0 || synced.head === undefined ? undefined : { unreviewed: { files: synced.unreviewed, caughtUp: synced.head, sync: synced.sync } },
2858
+ caughtUp: synced
2859
+ });
2860
+ const passed = yield* greenRead(shown);
2861
+ if (passed.head !== head)
2862
+ return yield* new MergeRefused({
2863
+ reason: `The head moved to ${passed.head} from ${head}, which it checked`,
2864
+ cause: "moved"
2865
+ });
2866
+ }
2867
+ })
2868
+ });
2869
+ var destinationOf = (changeRequestId, read, target, repository) => {
2870
+ const disagree = (what, named, actual) => named !== undefined && actual !== undefined && named !== actual ? `ChangeRequest ${changeRequestId} merges into ${what} ${actual}, not ${named}` : undefined;
2871
+ const disagreement = disagree("branch", target, read.targetBranch) ?? disagree("RepoBinding", repository, read.repository);
2872
+ if (disagreement !== undefined)
2873
+ return fail7(new MergeRefused({ reason: disagreement, cause: "turn" }));
2874
+ const bound = read.repository ?? repository;
2875
+ return succeed6({
2876
+ target: read.targetBranch ?? target ?? "HEAD",
2877
+ ...bound === undefined ? undefined : { repository: bound }
2878
+ });
2879
+ };
2880
+ var showing = (round, changeRequestId, pushed) => gen(function* () {
2881
+ const suffix = round === 1 ? "" : `:${round}`;
2882
+ const { head } = pushed;
2883
+ const shows = (read) => head === undefined ? read.head !== pushed.from : read.head === head;
2884
+ const filter = head === undefined ? { changeRequestId } : { changeRequestId, head };
2885
+ if (head !== undefined)
2886
+ yield* waitFor(`pushed${suffix}`, { event: "change_request.mergeable", filter, timeout: "5 minutes" }).pipe(catchTag("WaitTimedOut", () => void_3));
2887
+ let shown = yield* pipelineStatus(`shown${suffix}:1`, { changeRequestId });
2888
+ for (let look = 1;!shows(shown); look++) {
2889
+ if (look > staleReads)
2890
+ return { stale: shown.head };
2891
+ yield* waitFor(`pushed-again${suffix}:${look}`, {
2892
+ event: "change_request.mergeable",
2893
+ filter,
2894
+ timeout: "1 minute",
2895
+ ...shown.readAt === undefined ? undefined : { since: shown.readAt }
2896
+ }).pipe(catchTag("WaitTimedOut", () => void_3));
2897
+ shown = yield* pipelineStatus(`shown${suffix}:${look + 1}`, { changeRequestId });
2898
+ }
2899
+ return { read: shown };
2900
+ });
2901
+ // packages/sdk/src/loop/integrated.ts
2902
+ var integrated = step("integrated", {
2903
+ payload: {
2904
+ repoBindingId: optional(String4).annotate({
2905
+ description: "The Team's default RepoBinding when left out."
2906
+ })
2907
+ },
2908
+ success: IntegrationBranch,
2909
+ key: ({ repoBindingId }) => repoBindingId ?? "default",
2910
+ run: ({ repoBindingId }) => integrationBranch("head", repoBindingId === undefined ? {} : { repoBindingId })
2911
+ });
2912
+ // packages/sdk/src/loop/left-for-pickup.ts
2913
+ var leftForPickup = step("leftForPickup", {
2914
+ payload: {
2915
+ tickets: ArraySchema(PlanTicket),
2916
+ projectId: optional(String4).annotate({ description: "The Project the Tasks are in." })
2917
+ },
2918
+ run: ({ tickets, projectId }) => asVoid(createTasks("release-tasks", {
2919
+ tickets,
2920
+ releases: true,
2921
+ ...projectId === undefined ? undefined : { projectId }
2922
+ }))
2923
+ });
2924
+ // packages/sdk/src/loop/version-scheme.ts
2925
+ var Bump = Literals(["major", "minor", "patch"]);
2926
+ class VersionScheme extends Service2()("@kitman-sh/sdk/loop/VersionScheme") {
2927
+ }
2928
+ var sameForEveryBump = (tag) => ({ major: tag, minor: tag, patch: tag });
2929
+ var semverTags = {
2930
+ name: "semver-tags",
2931
+ versions: (request) => map9(versions(request.step, {
2932
+ revision: request.revision,
2933
+ ...request.prerelease === undefined ? undefined : { prerelease: request.prerelease },
2934
+ ...request.prefix === undefined ? undefined : { prefix: request.prefix }
2935
+ }), ({ series: _series, ...read }) => read)
2936
+ };
2937
+ var prefixOf = (previous) => previous === undefined ? "" : previous.tag.slice(0, previous.tag.length - previous.version.length);
2938
+ var projectName = {
2939
+ name: "project-name",
2940
+ versions: (request) => gen(function* () {
2941
+ const project = request.project;
2942
+ const named = project?.name === undefined ? undefined : releaseVersion(project.name);
2943
+ if (project === undefined || named === undefined)
2944
+ return;
2945
+ const ownPrefix = request.prefix === undefined && named.startsWith("v");
2946
+ const nameVersion = ownPrefix ? named : named.replace(/^v/u, "");
2947
+ const stemsOf = (stem) => request.prefix === undefined && !ownPrefix ? [stem, `v${stem}`] : [stem];
2948
+ const candidateStem = (version) => `${version}-${request.prerelease ?? "rc"}.`;
2949
+ const readSeries = (step, series) => versions(step, {
2950
+ revision: request.revision,
2951
+ ...request.prefix === undefined ? undefined : { prefix: request.prefix },
2952
+ ...series.length === 0 ? undefined : { series }
2953
+ });
2954
+ const highestOf = (read, stems) => Math.max(-1, ...(read.series ?? []).filter((counted) => stems.includes(counted.series)).map((counted) => counted.highest ?? -1));
2955
+ const parts = /^(v?\d+\.\d+\.)(\d+)$/u.exec(nameVersion);
2956
+ const minorLine = parts?.[1] ?? nameVersion;
2957
+ const read = yield* readSeries(request.step, [
2958
+ ...project.candidate ? stemsOf(candidateStem(nameVersion)) : [],
2959
+ ...project.reopened === true ? stemsOf(minorLine) : []
2960
+ ]);
2961
+ const tagged = project.reopened === true ? highestOf(read, stemsOf(minorLine)) : -1;
2962
+ const version = tagged >= Number(parts?.[2] ?? 0) ? `${minorLine}${tagged + 1}` : nameVersion;
2963
+ const candidates = !project.candidate || version === nameVersion ? read : yield* readSeries(`${request.step}:after-${nameVersion}`, stemsOf(candidateStem(version)));
2964
+ const prefix = request.prefix ?? (ownPrefix ? "" : prefixOf(read.previous));
2965
+ const highest = Math.max(0, highestOf(candidates, stemsOf(candidateStem(version))));
2966
+ return {
2967
+ revision: read.revision,
2968
+ ...read.previous === undefined ? undefined : { previous: read.previous },
2969
+ ...read.containedIn === undefined ? undefined : { containedIn: read.containedIn },
2970
+ next: sameForEveryBump(project.candidate ? `${prefix}${candidateStem(version)}${highest + 1}` : `${prefix}${version}`)
2971
+ };
2972
+ })
2973
+ };
2974
+ var calverTokenNames = new Set(["YYYY", "YY", "0Y", "MM", "0M", "DD", "0D", "MICRO"]);
2975
+ var chain = (...schemes) => ({
2976
+ name: `chain(${schemes.map((scheme) => scheme.name).join(", ")})`,
2977
+ versions: (request) => gen(function* () {
2978
+ for (const scheme of schemes) {
2979
+ const read = yield* scheme.versions(request);
2980
+ if (read !== undefined)
2981
+ return read;
2982
+ }
2983
+ return;
2984
+ })
2985
+ });
2986
+ var auto = { ...chain(projectName, semverTags), name: "auto" };
2987
+ var VersionSchemeName = Literals(["auto", "semver-tags", "project-name", "calver"]);
2988
+ class BumpPolicy extends Service2()("@kitman-sh/sdk/loop/BumpPolicy") {
2989
+ }
2990
+ var BumpPolicyName = Literals(["outcome", "conventional-commits", "labels", "fixed"]);
2991
+ // packages/sdk/src/program/engine.ts
2992
+ var JournalEntries = Record(String4, Json);
2993
+ var isSuspended = is(Suspended);
2994
+ var emptyWorkflow = make("kitman-loop/none", { payload: {}, idempotencyKey: () => "none" });
2995
+ var replayStatuses = new Set([401, 403, 409, 429]);
2996
+ var isRunnerRpcError = is(RunnerRpcError);
2997
+ var isRunFileRefused = is(RunFileRefused);
2998
+ var issues = makeFormatterStandardSchemaV1();
2999
+ var put2 = (target, contentType, body) => gen(function* () {
3000
+ const response = yield* (yield* HttpClient).execute(put(target.url).pipe(bodyUint8Array(body, contentType), setHeaders(target.headers ?? {})));
3001
+ return (yield* filterStatusOk(response)).headers.etag ?? "";
3002
+ });
3003
+ var readRange = (path, offset, size) => scoped(gen(function* () {
3004
+ const file = yield* (yield* FileSystem).open(path);
3005
+ return getOrElse(yield* file.readAlloc(size, { position: BigInt(offset) }), () => new Uint8Array);
3006
+ }));
3007
+ var partUrlMarginMillis = 60000;
3008
+ var uploadParts = (files, path, contentType, fileId, upload) => forEach(upload.parts, (part) => gen(function* () {
3009
+ const now = yield* currentTimeMillis;
3010
+ const fresh = Date.parse(part.expiresAt) - now > partUrlMarginMillis ? part : (yield* files.runFileParts({ fileId, partNumbers: [part.partNumber] }))[0] ?? part;
3011
+ const body = yield* readRange(path, (part.partNumber - 1) * upload.partSize, upload.partSize);
3012
+ return { partNumber: part.partNumber, etag: yield* put2(fresh, contentType, body) };
3013
+ }));
3014
+ var uploadRunFile = (files, file) => gen(function* () {
3015
+ const fs = yield* FileSystem;
3016
+ const contentType = runFileContentType(file.name);
3017
+ const byteSize = Number((yield* fs.stat(file.path)).size);
3018
+ const hash = sha256Hasher();
3019
+ yield* runForEach(fs.stream(file.path), (chunk) => sync2(() => hash.update(chunk)));
3020
+ const { file: slotted, upload } = yield* files.createRunFile({
3021
+ step: file.step,
3022
+ name: file.name,
3023
+ ...file.caption === undefined ? undefined : { caption: file.caption },
3024
+ contentType,
3025
+ byteSize,
3026
+ sha256: hash.digest("hex")
3027
+ });
3028
+ if (upload === undefined)
3029
+ return slotted;
3030
+ return yield* upload.kind === "single" ? readRange(file.path, 0, byteSize).pipe(flatMap3((body) => put2(upload, contentType, body)), andThen2(files.completeRunFile({ fileId: slotted.id }))) : flatMap3(uploadParts(files, file.path, contentType, slotted.id, upload), (parts) => files.completeRunFile({ fileId: slotted.id, parts }));
3031
+ });
3032
+ var programLease = (work) => ({
3033
+ workUnitId: work.id,
3034
+ leaseOwnerId: work.lease.leaseOwnerId,
3035
+ runnerReplicaId: work.lease.runnerReplicaId,
3036
+ leaseId: work.lease.leaseId,
3037
+ attempt: work.lease.attempt,
3038
+ fencingToken: work.lease.fencingToken,
3039
+ capacitySlot: work.lease.capacitySlot
3040
+ });
3041
+ var rpcRunFiles = (rpc, lease) => ({
3042
+ createRunFile: (file) => rpc.createRunFile({ lease, ...file }),
3043
+ runFileParts: (request) => map9(rpc.runFileParts({ lease, ...request, partNumbers: [...request.partNumbers] }), ({ parts }) => parts),
3044
+ completeRunFile: ({ parts, ...request }) => rpc.completeRunFile({ lease, ...request, ...parts === undefined ? undefined : { parts: [...parts] } })
3045
+ });
3046
+
3047
+ // packages/sdk/src/program/host.ts
3048
+ var describeFlag = "--kitman-describe";
3049
+ var DescribedKit = Struct({
3050
+ name: String4,
3051
+ version: String4,
3052
+ loops: ArraySchema(LoopManifest),
3053
+ agents: Record(String4, Json),
3054
+ schedules: optionalKey(Record(String4, Json)),
3055
+ setup: optionalKey(KitSetup),
3056
+ extends: optionalKey(ArraySchema(Struct({ name: String4, version: String4 })))
3057
+ });
3058
+ var Described = Union([
3059
+ TaggedStruct("Described", {
3060
+ kits: ArraySchema(DescribedKit),
3061
+ steps: optionalKey(ArraySchema(Struct({ ...StepManifest.fields, definedAt: optionalKey(String4) })))
3062
+ }),
3063
+ TaggedStruct("Refused", { error: Union([ManifestInvalid, LoopCheckError]) })
3064
+ ]);
3065
+ var encodeDescribed = encodeEffect(fromJsonString(toCodecJson(Described)));
3066
+
3067
+ class ProgramRefused extends TaggedError2()("ProgramRefused", { reason: String4 }) {
3068
+ get message() {
3069
+ return this.reason;
3070
+ }
3071
+ }
3072
+ var programHostsEnv = "KITMAN_PROGRAM_HOSTS";
3073
+ var undeclaredHostsEnv = "KITMAN_UNDECLARED_HOSTS";
3074
+ var redirectStatuses = new Set([301, 302, 303, 307, 308]);
3075
+ var runningBundle = tryPromise(() => Bun.file(Bun.main).text()).pipe(map9((text) => ({ path: Bun.main, lines: text.split(`
3076
+ `) })), orElseSucceed(() => ({ path: Bun.main, lines: [] })));
3077
+ var readStdin = tryPromise(() => Bun.stdin.text());
3078
+ var isWorkUnit = guard(ProgramWorkUnit);
3079
+
3080
+ export { stepDefinedTwice, hostSteps, exports_activities, uploadRunFile, programLease, rpcRunFiles, describeFlag, Described, programHostsEnv, undeclaredHostsEnv };