@kitman-sh/cli 0.9.0 → 0.10.53

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 (37) hide show
  1. package/dist/chunk-11p4wf6n.js +3551 -0
  2. package/dist/chunk-1mc9vgcr.js +39 -0
  3. package/dist/chunk-30397r95.js +30 -0
  4. package/dist/chunk-3bj7sc3v.js +389 -0
  5. package/dist/chunk-6vns3ej0.js +23 -0
  6. package/dist/chunk-7thnf14y.js +936 -0
  7. package/dist/chunk-arvwar2c.js +141 -0
  8. package/dist/chunk-b6thzgc9.js +32 -0
  9. package/dist/{chunk-8bvf4fh4.js → chunk-ctasxxz5.js} +26 -11
  10. package/dist/{chunk-5gjpv3ax.js → chunk-dzh9e6n2.js} +824 -651
  11. package/dist/{chunk-snn0e1qb.js → chunk-eg8f5ncv.js} +7 -3
  12. package/dist/chunk-g5bs3f6z.js +173 -0
  13. package/dist/chunk-jafetf7z.js +109 -0
  14. package/dist/chunk-jagzz148.js +527 -0
  15. package/dist/{chunk-1d4316hp.js → chunk-jfvq7s24.js} +38 -25
  16. package/dist/chunk-mbctzx7e.js +11436 -0
  17. package/dist/chunk-mej2bx5n.js +100 -0
  18. package/dist/chunk-p6spvbwq.js +6305 -0
  19. package/dist/chunk-pp1p3g6e.js +133 -0
  20. package/dist/chunk-r8p3nxcp.js +231 -0
  21. package/dist/chunk-txwt6r25.js +1731 -0
  22. package/dist/chunk-v290mf51.js +5242 -0
  23. package/dist/chunk-vjmz23rs.js +13 -0
  24. package/dist/chunk-vyv0p5eq.js +3183 -0
  25. package/dist/chunk-wh1pa2aa.js +15322 -0
  26. package/dist/chunk-x0b92bjb.js +222 -0
  27. package/dist/{chunk-8z5b6fpd.js → chunk-x9dhxfts.js} +216 -152
  28. package/dist/chunk-z821b2gp.js +164 -0
  29. package/dist/index.js +13 -5738
  30. package/dist/opencode-reader.main.ts +4 -0
  31. package/package.json +6 -5
  32. package/dist/chunk-3gxahgnq.js +0 -28495
  33. package/dist/chunk-ehzbtavj.js +0 -247
  34. package/dist/chunk-f5z8tgss.js +0 -1214
  35. package/dist/chunk-kdb1cbnx.js +0 -1273
  36. package/dist/chunk-ke1w0hx7.js +0 -5771
  37. package/dist/chunk-z6hc4ew9.js +0 -13
@@ -1,1273 +0,0 @@
1
- // @bun
2
- import {
3
- dual,
4
- hasProperty,
5
- Prototype,
6
- isNone,
7
- Service,
8
- empty,
9
- add,
10
- getOrUndefined2,
11
- get,
12
- merge,
13
- Reference,
14
- fromInputUnsafe,
15
- toMillis,
16
- TaggedClass,
17
- hasInterruptsOnly,
18
- combine,
19
- squash,
20
- hasInterrupts,
21
- isSuccess2,
22
- addFinalizerExit,
23
- effectDiscard,
24
- min,
25
- exponential,
26
- spaced,
27
- while_,
28
- setInputType,
29
- promise,
30
- succeed5,
31
- suspend,
32
- sync,
33
- void_2,
34
- callback,
35
- gen,
36
- fail4,
37
- failCause2,
38
- die3,
39
- try_,
40
- yieldNow,
41
- flatMap2,
42
- andThen,
43
- tap,
44
- map3,
45
- catch_,
46
- mapError,
47
- orDie,
48
- retry,
49
- sandbox,
50
- matchEffect,
51
- context,
52
- contextWith,
53
- provideContext,
54
- provideService,
55
- acquireUseRelease,
56
- onExit,
57
- interruptible,
58
- uninterruptibleMask,
59
- annotateCurrentSpan,
60
- withSpan,
61
- fnUntraced,
62
- getCurrent,
63
- encode2,
64
- transform,
65
- encodeBase64Url,
66
- decodeBase64UrlString,
67
- transform2,
68
- declare,
69
- decodeUnknownEffect,
70
- decodeEffect,
71
- decodeSync,
72
- encodeUnknownEffect,
73
- encodeEffect,
74
- encodeSync,
75
- isSchema,
76
- optionalKey,
77
- optional,
78
- Literal,
79
- Never,
80
- Unknown,
81
- Null,
82
- String2,
83
- Boolean2,
84
- Void,
85
- Struct,
86
- Record,
87
- Tuple,
88
- ArraySchema,
89
- NonEmptyArray,
90
- Union,
91
- Literals,
92
- decodeTo,
93
- tag,
94
- makeFilter,
95
- isPattern,
96
- Finite,
97
- isGreaterThanOrEqualTo,
98
- isLessThanOrEqualTo2,
99
- Int,
100
- isMinLength,
101
- isMaxLength,
102
- Defect,
103
- fromJsonString,
104
- Cause,
105
- Exit,
106
- Class,
107
- TaggedError2,
108
- toEquivalence,
109
- toJsonSchemaDocument,
110
- toCodecJson,
111
- Json,
112
- guard,
113
- SafeJson,
114
- relativePathPattern,
115
- skillNamePattern,
116
- AgentSandboxNetwork,
117
- AgentEfforts,
118
- LoopDataSchemaRef,
119
- ProgramLoop,
120
- KitKinds
121
- } from "./chunk-3gxahgnq.js";
122
-
123
- // packages/core/src/schedule.ts
124
- var ScheduleFrequency = ["daily", "weekly"];
125
- var ScheduleMisfirePolicies = ["skip", "fire_once", "catch_up"];
126
- var ScheduleOverlapPolicies = ["allow", "skip", "coalesce"];
127
- var ScheduleVersionStatuses = ["draft", "published", "disabled", "archived"];
128
- var ScheduleCalendarRule = Struct({
129
- frequency: Literals(ScheduleFrequency),
130
- hour: Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(23)),
131
- minute: Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(59)),
132
- second: optionalKey(Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(59))),
133
- daysOfWeek: optionalKey(ArraySchema(Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(6))).check(isMinLength(1), isMaxLength(7)))
134
- });
135
- var ScheduleCronRule = Struct({
136
- cron: String2.check(isMinLength(9), isMaxLength(200), isPattern(new RegExp("^[0-9*,/-]+( [0-9*,/-]+){4}$", "u")))
137
- });
138
- var ScheduleRule = Union([ScheduleCalendarRule, ScheduleCronRule]);
139
- var cronBounds = [
140
- [0, 59],
141
- [0, 23],
142
- [1, 31],
143
- [1, 12],
144
- [0, 7]
145
- ];
146
- function cronField(field, [min, max]) {
147
- const values = new Set;
148
- for (const part of field.split(",")) {
149
- const match = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
150
- if (match === null)
151
- return;
152
- const from = match[1] === "*" ? min : Number(match[2]);
153
- const to = match[1] === "*" ? max : match[3] === undefined ? match[4] === undefined ? from : max : Number(match[3]);
154
- const step = match[4] === undefined ? 1 : Number(match[4]);
155
- if (from < min || to > max || from > to || step < 1)
156
- return;
157
- for (let value = from;value <= to; value += step)
158
- values.add(value);
159
- }
160
- return values;
161
- }
162
- function parseCron(cron) {
163
- const fields = cron.split(" ");
164
- const [minutes, hours, days, months, weekdays] = fields.map((field, index) => cronField(field, cronBounds[index] ?? [0, 0]));
165
- if (fields.length !== 5 || !minutes || !hours || !days || !months || !weekdays)
166
- return;
167
- return {
168
- minutes,
169
- hours,
170
- days,
171
- months,
172
- weekdays: new Set([...weekdays].map((value) => value % 7)),
173
- dayRestricted: !(fields[2] ?? "").startsWith("*"),
174
- weekdayRestricted: !(fields[4] ?? "").startsWith("*")
175
- };
176
- }
177
- function isScheduleRule(value) {
178
- return guard(ScheduleRule)(value) && (!("cron" in value) || parseCron(value.cron) !== undefined);
179
- }
180
- var ScheduleVersion = Struct({
181
- contractVersion: Literal("schedule.v1"),
182
- id: String2.check(isMinLength(1)),
183
- scheduleId: String2.check(isMinLength(1)),
184
- workspaceId: String2.check(isMinLength(1)),
185
- teamId: optionalKey(String2.check(isMinLength(1))),
186
- loopId: optionalKey(String2.check(isMinLength(1))),
187
- name: optionalKey(String2.check(isMinLength(1), isMaxLength(200))),
188
- version: Int.check(isGreaterThanOrEqualTo(1)),
189
- status: Literals(ScheduleVersionStatuses),
190
- timezone: String2.check(isMinLength(1), isMaxLength(80)),
191
- rule: ScheduleRule,
192
- misfirePolicy: Literals(ScheduleMisfirePolicies),
193
- overlapPolicy: Literals(ScheduleOverlapPolicies),
194
- maxCatchUp: Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(200)),
195
- misfireGraceSeconds: optionalKey(Int.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo2(604800))),
196
- inputSchemaRef: optionalKey(LoopDataSchemaRef),
197
- input: optionalKey(SafeJson),
198
- createdAt: String2.check(isMinLength(1))
199
- });
200
- var zones = new Map;
201
- var resolvedLocalDateTimes = new Map;
202
-
203
- // packages/core/src/package-declarations.ts
204
- var LoopCapabilities = [
205
- "agent_work",
206
- "ask",
207
- "call",
208
- "verify",
209
- "change_request",
210
- "write_back",
211
- "post_comment",
212
- "create_tasks",
213
- "merge_change_request",
214
- "publish_release",
215
- "read_transcripts",
216
- "propose",
217
- "read_project",
218
- "draft_update"
219
- ];
220
- var JsonObject = Record(String2, Json);
221
- var recordKeyedBy = (pattern, value) => Record(String2, value).check(makeFilter((record) => {
222
- const bad = Object.keys(record).find((key) => !new RegExp(pattern).test(key));
223
- return bad === undefined ? true : `${JSON.stringify(bad)} is not a valid name or relative path`;
224
- }));
225
- var SecretName = String2.check(isPattern(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/));
226
- var EventFilterValue = Union([String2, Finite, Boolean2, Null]);
227
- var LoopManifest = Struct({
228
- id: String2,
229
- title: String2,
230
- input: JsonObject,
231
- output: JsonObject,
232
- outcome: optionalKey(Literals(["feature", "bug", "refactor", "investigation", "docs", "migration"])),
233
- agents: Record(String2, String2),
234
- checkout: Literals(["none", "read", "write"]),
235
- when: ArraySchema(Struct({
236
- event: String2,
237
- filter: optionalKey(Record(String2, Union([EventFilterValue, ArraySchema(EventFilterValue)]))),
238
- input: Record(String2, String2)
239
- })),
240
- offers: ArraySchema(Struct({ id: String2, title: String2, loop: String2 })),
241
- capabilities: ArraySchema(Literals(LoopCapabilities)),
242
- secrets: optionalKey(ArraySchema(SecretName)),
243
- network: optionalKey(AgentSandboxNetwork),
244
- schedule: optionalKey(Struct({ rule: ScheduleRule, timezone: String2 }))
245
- });
246
- var LoopDetail = Struct({
247
- id: String2,
248
- resolved: optionalKey(Struct({
249
- ...ProgramLoop.fields,
250
- agents: LoopManifest.fields.agents,
251
- when: LoopManifest.fields.when,
252
- schedule: optionalKey(Struct({
253
- rule: ScheduleRule,
254
- timezone: String2,
255
- on: Boolean2,
256
- nextRunAt: optionalKey(String2)
257
- }))
258
- }))
259
- });
260
- var AgentDeclaration = Struct({
261
- extends: optionalKey(String2),
262
- instructions: optionalKey(String2),
263
- harness: optionalKey(String2),
264
- model: optionalKey(String2),
265
- effort: optionalKey(Literals(AgentEfforts)),
266
- kits: optionalKey(ArraySchema(String2)),
267
- network: optionalKey(Union([Struct({ hosts: ArraySchema(String2) }), Literal("open")])),
268
- sandbox: optionalKey(Literal("docker"))
269
- });
270
- var scheduleFields = {
271
- name: String2.check(isMinLength(1)),
272
- loop: String2,
273
- team: optionalKey(String2),
274
- input: optionalKey(JsonObject),
275
- timezone: String2,
276
- misfire: optionalKey(Literals(ScheduleMisfirePolicies)),
277
- overlap: optionalKey(Literals(ScheduleOverlapPolicies))
278
- };
279
- var ScheduleDeclaration = Union([
280
- Struct({
281
- ...scheduleFields,
282
- cron: String2.check(makeFilter((cron) => isScheduleRule({ cron }) || "five cron fields, each within its range"))
283
- }),
284
- Struct({
285
- ...scheduleFields,
286
- rule: declare((value) => isScheduleRule(value), {
287
- expected: "a Schedule rule: frequency daily or weekly, hour, minute, and optionally second and daysOfWeek"
288
- })
289
- })
290
- ]);
291
- var AuthoredKitDeclaration = Struct({
292
- name: String2.check(isMinLength(1)),
293
- kind: optionalKey(Literals(KitKinds)),
294
- description: optionalKey(String2),
295
- context: String2,
296
- skills: optionalKey(recordKeyedBy(skillNamePattern, recordKeyedBy(relativePathPattern, String2)))
297
- });
298
- var KitInstallationDeclaration = Struct({
299
- source: String2.check(isMinLength(1)),
300
- version: optionalKey(String2)
301
- });
302
- var KitAssignmentDeclaration = Struct({
303
- kit: String2.check(isMinLength(1)),
304
- workspace: optionalKey(Literals(["default", "mandatory"])),
305
- teams: optionalKey(ArraySchema(String2))
306
- });
307
- var KitDeclaration = Union([
308
- KitInstallationDeclaration,
309
- KitAssignmentDeclaration,
310
- AuthoredKitDeclaration
311
- ]);
312
- var PackageDeclarations = Struct({
313
- loops: ArraySchema(LoopManifest),
314
- agents: Record(String2, AgentDeclaration),
315
- schedules: optionalKey(Record(String2, ScheduleDeclaration)),
316
- kits: optionalKey(Record(String2, KitDeclaration))
317
- });
318
- var sameLoop = toEquivalence(LoopManifest);
319
- var sameAgent = toEquivalence(AgentDeclaration);
320
-
321
- // packages/sdk/src/loop/define.ts
322
- var LoopOutcome = Literals(["feature", "bug", "refactor", "investigation", "docs", "migration"]);
323
- var defineLoop = (definition) => definition;
324
-
325
- class ManifestInvalid extends TaggedError2()("ManifestInvalid", {
326
- loop: String2,
327
- message: String2
328
- }) {
329
- }
330
- var jsonSchemaOf = (loop, schema) => try_({
331
- try: () => toJsonSchemaDocument(schema),
332
- catch: (error) => new ManifestInvalid({ loop, message: `Schema has no JSON Schema: ${String(error)}` })
333
- }).pipe(flatMap2((document) => decodeUnknownEffect(JsonObjectSchema)({ ...document.schema, $defs: document.definitions }).pipe(mapError((error) => new ManifestInvalid({ loop, message: error.message })))));
334
- var JsonObjectSchema = Record(String2, Json);
335
- // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workflow/internal/crypto.js
336
- var makeHashDigest = (original) => map3(promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(original))), (buffer) => {
337
- const data = new Uint8Array(buffer);
338
- let hexString = "";
339
- for (let i = 0;i < 16; i++) {
340
- hexString += data[i].toString(16).padStart(2, "0");
341
- }
342
- return hexString;
343
- });
344
-
345
- // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workflow/Workflow.js
346
- var TypeId = "~effect/workflow/Workflow";
347
- var EngineTag = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine");
348
- var InstanceTag = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine/WorkflowInstance");
349
- var makeExecutionIdFromPayload = (self, payload) => makeHashDigest(`${self._tag.length}:${self._tag}:${self.idempotencyKey(payload)}`);
350
- var Proto = {
351
- [TypeId]: TypeId,
352
- annotate(tag, value) {
353
- return makeProto({
354
- _tag: this._tag,
355
- payloadSchema: this.payloadSchema,
356
- successSchema: this.successSchema,
357
- errorSchema: this.errorSchema,
358
- annotations: add(this.annotations, tag, value),
359
- idempotencyKey: this.idempotencyKey,
360
- suspendedRetrySchedule: this.suspendedRetrySchedule
361
- });
362
- },
363
- annotateMerge(context) {
364
- return makeProto({
365
- _tag: this._tag,
366
- payloadSchema: this.payloadSchema,
367
- successSchema: this.successSchema,
368
- errorSchema: this.errorSchema,
369
- annotations: merge(this.annotations, context),
370
- idempotencyKey: this.idempotencyKey,
371
- suspendedRetrySchedule: this.suspendedRetrySchedule
372
- });
373
- },
374
- execute(fields, opts) {
375
- return suspend(() => {
376
- const payload = this.payloadSchema.make(fields);
377
- const run = flatMap2(EngineTag, (engine) => flatMap2(makeExecutionIdFromPayload(this, payload), (executionId) => andThen(annotateCurrentSpan({
378
- executionId
379
- }), engine.execute(this, {
380
- executionId,
381
- payload,
382
- discard: opts?.discard,
383
- suspendedRetrySchedule: this.suspendedRetrySchedule
384
- }))));
385
- return opts?.discard ? run : withPendingActivity(run);
386
- }).pipe(withSpan(`${this._tag}.execute`, {}, {
387
- captureStackTrace: false
388
- }));
389
- },
390
- poll(executionId) {
391
- return flatMap2(EngineTag, (engine) => engine.poll(this, executionId)).pipe(withSpan(`${this._tag}.poll`, {
392
- attributes: {
393
- executionId
394
- }
395
- }, {
396
- captureStackTrace: false
397
- }));
398
- },
399
- interrupt(executionId) {
400
- return flatMap2(EngineTag, (engine) => engine.interrupt(this, executionId)).pipe(withSpan(`${this._tag}.interrupt`, {
401
- attributes: {
402
- executionId
403
- }
404
- }, {
405
- captureStackTrace: false
406
- }));
407
- },
408
- resume(executionId) {
409
- return flatMap2(EngineTag, (engine) => engine.resume(this, executionId)).pipe(withSpan(`${this._tag}.resume`, {
410
- attributes: {
411
- executionId
412
- }
413
- }, {
414
- captureStackTrace: false
415
- }));
416
- },
417
- toLayer(execute) {
418
- return effectDiscard(flatMap2(EngineTag, (engine) => engine.register(this, execute)));
419
- },
420
- executionId(payload) {
421
- return flatMap2(orDie(this.payloadSchema.makeEffect(payload)), (payload) => makeExecutionIdFromPayload(this, payload));
422
- },
423
- withCompensation: (...args) => withCompensation(...args)
424
- };
425
- var makeProto = (options) => {
426
- function Workflow() {}
427
- Object.setPrototypeOf(Workflow, Proto);
428
- Object.assign(Workflow, options);
429
- return Workflow;
430
- };
431
- var make = (tag, options) => makeProto({
432
- _tag: tag,
433
- payloadSchema: isSchema(options.payload) ? options.payload : Struct(options.payload),
434
- successSchema: options.success ?? Void,
435
- errorSchema: options.error ?? Never,
436
- annotations: options.annotations ?? empty(),
437
- idempotencyKey: options.idempotencyKey,
438
- suspendedRetrySchedule: options.suspendedRetrySchedule
439
- });
440
- var ResultTypeId = "~effect/workflow/Workflow/Result";
441
- var isResult = (u) => hasProperty(u, ResultTypeId);
442
- class Suspended extends (/* @__PURE__ */ Class("effect/workflow/Workflow/Suspended")({
443
- _tag: /* @__PURE__ */ tag("Suspended"),
444
- cause: /* @__PURE__ */ optional(/* @__PURE__ */ Cause(Never, /* @__PURE__ */ Defect()))
445
- })) {
446
- [ResultTypeId] = ResultTypeId;
447
- }
448
- var wrapActivityResult = (effect, isSuspend) => contextWith((context) => {
449
- const instance = get(context, InstanceTag);
450
- return acquireUseRelease(sync(() => adoptActivityUnsafe(context, instance) ?? registerActivityUnsafe(instance)), () => effect, (registration, exit) => {
451
- releaseActivityUnsafe(registration);
452
- const isSuspended = isSuccess2(exit) && isSuspend(exit.value);
453
- if (isSuccess2(exit) && isResult(exit.value) && exit.value._tag === "Suspended" && exit.value.cause) {
454
- instance.cause = instance.cause ? combine(instance.cause, exit.value.cause) : exit.value.cause;
455
- }
456
- return isSuspended && instance.activityState.count > 0 ? waitForZero(instance) : void_2;
457
- });
458
- });
459
- var PendingActivityRegistration = /* @__PURE__ */ Service("effect/workflow/Workflow/PendingActivityRegistration");
460
- var registerActivityUnsafe = (instance) => {
461
- const state = instance.activityState;
462
- if (state.count === 0)
463
- state.latch.closeUnsafe();
464
- state.count++;
465
- return {
466
- instance,
467
- state: "pending"
468
- };
469
- };
470
- var adoptActivityUnsafe = (context, instance) => {
471
- const pending = getOrUndefined2(context, PendingActivityRegistration);
472
- if (!pending || pending.instance !== instance) {
473
- return;
474
- }
475
- if (pending.state !== "pending") {
476
- throw new Error("Workflow.wrapActivityResult: pending child registration has already been consumed");
477
- }
478
- pending.state = "adopted";
479
- return pending;
480
- };
481
- var releaseActivityUnsafe = (registration) => {
482
- if (registration.state === "released")
483
- return;
484
- registration.state = "released";
485
- const state = registration.instance.activityState;
486
- state.count--;
487
- if (state.count === 0)
488
- state.latch.openUnsafe();
489
- };
490
- var withPendingActivity = (effect) => contextWith((context) => {
491
- const instance = getOrUndefined2(context, InstanceTag);
492
- if (!instance)
493
- return effect;
494
- return acquireUseRelease(sync(() => registerActivityUnsafe(instance)), (registration) => provideService(effect, PendingActivityRegistration, registration), (registration) => sync(() => releaseActivityUnsafe(registration)));
495
- });
496
- var waitForZero = /* @__PURE__ */ fnUntraced(function* (instance) {
497
- const state = instance.activityState;
498
- while (true) {
499
- if (state.count > 0) {
500
- yield* state.latch.await;
501
- yield* yieldNow;
502
- continue;
503
- }
504
- yield* yieldNow;
505
- if (state.count === 0)
506
- return;
507
- }
508
- });
509
- var addFinalizer = /* @__PURE__ */ fnUntraced(function* (f) {
510
- const instance = yield* InstanceTag;
511
- const services = yield* context();
512
- yield* addFinalizerExit(instance.scope, (exit) => instance.abandoned ? void_2 : provideContext(f(exit), services));
513
- });
514
- var withCompensation = /* @__PURE__ */ dual(2, (effect, compensation) => uninterruptibleMask((restore) => tap(restore(effect), (value) => addFinalizer((exit) => isSuccess2(exit) ? void_2 : compensation(value, exit.cause)))));
515
- var suspend2 = (instance) => interruptible(callback(() => {
516
- instance.suspended = true;
517
- const fiber = getCurrent();
518
- fiber.interruptUnsafe(fiber.id);
519
- }));
520
-
521
- // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workflow/DurableDeferred.js
522
- var TypeId2 = "~effect/workflow/DurableDeferred";
523
- var make2 = (name, options) => {
524
- const successSchema = options?.success ?? Void;
525
- const errorSchema = options?.error ?? Never;
526
- return {
527
- [TypeId2]: TypeId2,
528
- name,
529
- successSchema,
530
- errorSchema,
531
- exitSchema: Exit(toCodecJson(successSchema), toCodecJson(errorSchema), toCodecJson(Defect())),
532
- withActivityAttempt: gen(function* () {
533
- const attempt = yield* CurrentAttempt;
534
- return make2(`${name}/${attempt}`, {
535
- success: successSchema,
536
- error: errorSchema
537
- });
538
- })
539
- };
540
- };
541
- var EngineTag2 = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine");
542
- var InstanceTag2 = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine/WorkflowInstance");
543
- var CurrentAttempt = /* @__PURE__ */ Reference("effect/workflow/Activity/CurrentAttempt", {
544
- defaultValue: () => 1
545
- });
546
- var awaitOwners = /* @__PURE__ */ new WeakMap;
547
- var registerAwait = (instance, name) => {
548
- instance.awaitedDeferreds.set(name, (instance.awaitedDeferreds.get(name) ?? 0) + 1);
549
- awaitOwners.get(instance)?.push(name);
550
- };
551
- var await_ = /* @__PURE__ */ fnUntraced(function* (self) {
552
- const engine = yield* EngineTag2;
553
- const instance = yield* InstanceTag2;
554
- registerAwait(instance, self.name);
555
- const exit = yield* wrapActivityResult(engine.deferredResult(self), isNone);
556
- if (isNone(exit)) {
557
- return yield* suspend2(instance);
558
- }
559
- return yield* exit.value;
560
- });
561
- class TokenParsed extends (/* @__PURE__ */ Class("effect/workflow/DurableDeferred/TokenParsed")({
562
- workflowName: String2,
563
- executionId: String2,
564
- deferredName: String2
565
- })) {
566
- get asToken() {
567
- return encode2(JSON.stringify([this.workflowName, this.executionId, this.deferredName]));
568
- }
569
- static FromString = /* @__PURE__ */ String2.pipe(/* @__PURE__ */ decodeTo(/* @__PURE__ */ fromJsonString(/* @__PURE__ */ Tuple([String2, String2, String2])), {
570
- decode: /* @__PURE__ */ decodeBase64UrlString(),
571
- encode: /* @__PURE__ */ encodeBase64Url()
572
- }), /* @__PURE__ */ decodeTo(TokenParsed, {
573
- decode: /* @__PURE__ */ transform(([workflowName, executionId, deferredName]) => new TokenParsed({
574
- workflowName,
575
- executionId,
576
- deferredName
577
- })),
578
- encode: /* @__PURE__ */ transform((parsed) => [parsed.workflowName, parsed.executionId, parsed.deferredName])
579
- }));
580
- static fromString = /* @__PURE__ */ decodeSync(TokenParsed.FromString);
581
- static encode = /* @__PURE__ */ encodeSync(TokenParsed.FromString);
582
- }
583
- var token = /* @__PURE__ */ fnUntraced(function* (self) {
584
- const instance = yield* InstanceTag2;
585
- return tokenFromExecutionId(self, instance);
586
- });
587
- var tokenFromExecutionId = /* @__PURE__ */ dual(2, (self, options) => new TokenParsed({
588
- workflowName: options.workflow._tag,
589
- executionId: options.executionId,
590
- deferredName: self.name
591
- }).asToken);
592
-
593
- // node_modules/.bun/effect@4.0.4/node_modules/effect/dist/workflow/Activity.js
594
- var TypeId3 = "~effect/workflow/Activity";
595
- var make3 = (options) => {
596
- const successSchema = options.success ?? Void;
597
- const errorSchema = options.error ?? Never;
598
- const successSchemaJson = toCodecJson(successSchema);
599
- const errorSchemaJson = toCodecJson(errorSchema);
600
- let execute;
601
- const executeWithoutInterrupt = retryOnInterrupt(options.name, options.interruptRetryPolicy)(options.execute);
602
- const self = {
603
- ...Prototype({
604
- label: "Activity",
605
- evaluate(_) {
606
- return execute;
607
- }
608
- }),
609
- [TypeId3]: TypeId3,
610
- name: options.name,
611
- successSchema,
612
- errorSchema,
613
- exitSchema: Exit(successSchemaJson, errorSchemaJson, Defect()),
614
- exitSchemaPartial: Exit(successSchemaJson, errorSchemaJson, Unknown),
615
- annotations: options.annotations ?? empty(),
616
- annotate(tag, value) {
617
- return make3({
618
- ...options,
619
- annotations: add(self.annotations, tag, value)
620
- });
621
- },
622
- annotateMerge(context) {
623
- return make3({
624
- ...options,
625
- annotations: merge(self.annotations, context)
626
- });
627
- },
628
- execute: executeWithoutInterrupt,
629
- executeEncoded: matchEffect(executeWithoutInterrupt, {
630
- onFailure: (error) => flatMap2(orDie(encodeEffect(errorSchemaJson)(error)), fail4),
631
- onSuccess: (value) => orDie(encodeEffect(successSchemaJson)(value))
632
- })
633
- };
634
- execute = makeExecute(self);
635
- return self;
636
- };
637
- var interruptRetryPolicy = /* @__PURE__ */ min([exponential(400, 1.5), spaced("10 seconds")]).pipe(/* @__PURE__ */ setInputType(), /* @__PURE__ */ while_((meta) => meta.attempt <= 10 && hasInterrupts(meta.input)));
638
- var retryOnInterrupt = (name, policy = interruptRetryPolicy) => (effect) => flatMap2(InstanceTag3, (instance) => effect.pipe(sandbox, retry({
639
- schedule: policy,
640
- while: () => !instance.suspended
641
- }), catch_((cause) => hasInterrupts(cause) && !instance.suspended ? die3(`Activity "${name}" interrupted and retry attempts exhausted`) : failCause2(cause))));
642
- var CurrentAttempt2 = /* @__PURE__ */ Reference("effect/workflow/Activity/CurrentAttempt", {
643
- defaultValue: () => 1
644
- });
645
- var EngineTag3 = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine");
646
- var InstanceTag3 = /* @__PURE__ */ Service("effect/workflow/WorkflowEngine/WorkflowInstance");
647
- var makeExecute = /* @__PURE__ */ fnUntraced(function* (activity) {
648
- const engine = yield* EngineTag3;
649
- const instance = yield* InstanceTag3;
650
- const attempt = yield* CurrentAttempt2;
651
- yield* annotateCurrentSpan({
652
- executionId: instance.executionId
653
- });
654
- const result = yield* wrapActivityResult(engine.activityExecute(activity, attempt), (_) => _._tag === "Suspended");
655
- if (result._tag === "Suspended") {
656
- return yield* suspend2(instance);
657
- }
658
- return yield* result.exit;
659
- }, (effect, activity) => withSpan(effect, activity.name, {
660
- captureStackTrace: false
661
- }));
662
- // packages/sdk/src/loop/evidence.ts
663
- var EvidenceCheck = Struct({
664
- name: String2,
665
- command: String2,
666
- status: Literals(["passed", "failed"]),
667
- preExisting: Boolean2,
668
- durationMs: Finite,
669
- evidenceId: String2
670
- });
671
- var VerifyResult = Struct({
672
- revision: String2,
673
- tree: String2,
674
- passed: Boolean2,
675
- checks: ArraySchema(EvidenceCheck)
676
- });
677
- var verdict = (reasons) => reasons.length === 0 ? { settled: true } : { settled: false, reasons };
678
- var missing = (side) => `No verification evidence for the ${side}`;
679
- var allPass = (side, result) => {
680
- if (result === undefined)
681
- return [missing(side)];
682
- if (result.checks.length === 0)
683
- return [`No approved verification ran on the ${side} tree ${result.tree}`];
684
- return result.checks.filter((check) => check.status === "failed" && !check.preExisting).map((check) => `${check.name} fails on the ${side} tree ${result.tree}`);
685
- };
686
- var checkOn = (side, result, name) => {
687
- if (result === undefined)
688
- return { reason: missing(side) };
689
- if (name === undefined)
690
- return { reason: `No check was named for the ${side}` };
691
- const found = result.checks.find((check) => check.name === name);
692
- return found === undefined ? { reason: `No evidence for ${name} on the ${side} tree ${result.tree}` } : { found };
693
- };
694
- var passesOnHead = (head, name) => {
695
- const { found, reason } = checkOn("head", head, name);
696
- if (found === undefined)
697
- return [reason];
698
- return found.status === "passed" ? [] : [`${found.name} fails on the head tree ${head?.tree}`];
699
- };
700
- var bugReasons = (input) => {
701
- const base = checkOn("base", input.base, input.reproducing);
702
- const head = checkOn("head", input.head, input.reproducing);
703
- return [
704
- ...base.found === undefined ? [base.reason] : base.found.status === "failed" ? [] : [`${base.found.name} does not fail on the base tree ${input.base?.tree}, so the bug is not reproduced`],
705
- ...head.found === undefined ? [head.reason] : head.found.status === "passed" ? [] : [`${head.found.name} fails on the head tree ${input.head?.tree}`]
706
- ];
707
- };
708
- var conclusionReasons = (conclusion) => {
709
- if (conclusion === undefined || conclusion.text.trim() === "")
710
- return ["No conclusion was given"];
711
- return conclusion.sources.length === 0 ? ["The conclusion names no sources"] : [];
712
- };
713
- var scopeReasons = (scope) => {
714
- if (scope === undefined)
715
- return ["Review has not judged the scope"];
716
- if (scope.met)
717
- return [];
718
- return scope.unmet.length === 0 ? ["Review found the scope unmet"] : scope.unmet.map((item) => `Review found the scope unmet: ${item}`);
719
- };
720
- var evidenceGate = (input) => {
721
- switch (input.outcome) {
722
- case "feature":
723
- return verdict([...allPass("head", input.head), ...scopeReasons(input.review)]);
724
- case "bug":
725
- return verdict(bugReasons(input));
726
- case "refactor":
727
- return verdict([...allPass("base", input.base), ...allPass("head", input.head)]);
728
- case "investigation":
729
- return verdict(conclusionReasons(input.conclusion));
730
- case "docs":
731
- return verdict((input.documented ?? []).length === 0 ? ["No documented command was named"] : (input.documented ?? []).flatMap((name) => passesOnHead(input.head, name)));
732
- case "migration":
733
- return verdict(passesOnHead(input.head, input.rollback));
734
- default:
735
- return verdict(allPass("head", input.head));
736
- }
737
- };
738
-
739
- // packages/sdk/src/loop/steps.ts
740
- class StepFailed extends TaggedError2()("StepFailed", {
741
- step: String2,
742
- reason: String2
743
- }) {
744
- get message() {
745
- return `Step "${this.step}" failed: ${this.reason}`;
746
- }
747
- }
748
-
749
- class OutputInvalid extends TaggedError2()("OutputInvalid", {
750
- step: String2,
751
- message: String2
752
- }) {
753
- }
754
-
755
- class QuestionRefused extends TaggedError2()("QuestionRefused", {
756
- step: String2,
757
- answer: String2,
758
- options: ArraySchema(String2)
759
- }) {
760
- }
761
-
762
- class WaitTimedOut extends TaggedError2()("WaitTimedOut", {
763
- step: String2,
764
- event: String2
765
- }) {
766
- }
767
-
768
- class ChildFailed extends TaggedError2()("ChildFailed", {
769
- step: String2,
770
- loop: String2,
771
- reason: String2
772
- }) {
773
- get message() {
774
- return `Child Run of "${this.loop}" for Step "${this.step}" failed: ${this.reason}`;
775
- }
776
- }
777
-
778
- class CapabilityDenied extends TaggedError2()("CapabilityDenied", {
779
- step: String2,
780
- capability: Literals(LoopCapabilities),
781
- secret: optionalKey(String2)
782
- }) {
783
- get message() {
784
- 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`;
785
- }
786
- }
787
-
788
- class DuplicateStep extends TaggedError2()("DuplicateStep", {
789
- step: String2
790
- }) {
791
- }
792
-
793
- class InputInvalid extends TaggedError2()("InputInvalid", {
794
- loop: String2,
795
- message: String2
796
- }) {
797
- }
798
- var LoopEvent = Struct({ type: String2, payload: Record(String2, Json) });
799
-
800
- class LoopRun extends Service()("@kitman-sh/sdk/loop/LoopRun") {
801
- }
802
-
803
- class LoopHost extends Service()("@kitman-sh/sdk/loop/LoopHost") {
804
- }
805
- var agentWorkDeferred = (step) => make2(`agent_work/${step}`, { success: Json, error: StepFailed });
806
- var answerDeferred = (step) => make2(`ask/${step}`, { success: String2, error: StepFailed });
807
- var childDeferred = (step) => make2(`call/${step}`, { success: Json, error: ChildFailed });
808
- var eventDeferred = (step) => make2(`wait_for/${step}`, { success: LoopEvent, error: WaitTimedOut });
809
- var verifyDeferred = (step) => make2(`verify/${step}`, { success: VerifyResult, error: StepFailed });
810
- var recordStep = (name, kind, exit) => {
811
- if (isSuccess2(exit))
812
- return { name, kind, status: "succeeded", result: exit.value };
813
- if (hasInterruptsOnly(exit.cause))
814
- return;
815
- return { name, kind, status: "failed", error: squash(exit.cause) };
816
- };
817
- var takeStep = (name, kind, capability, body) => gen(function* () {
818
- const run = yield* LoopRun;
819
- if (run.names.has(name))
820
- return yield* new DuplicateStep({ step: name });
821
- if (capability !== undefined && !run.granted.has(capability))
822
- return yield* new CapabilityDenied({ step: name, capability });
823
- run.names.add(name);
824
- return yield* body.pipe(onExit((exit) => sync(() => {
825
- const record = recordStep(name, kind, exit);
826
- if (record !== undefined)
827
- run.steps.push(record);
828
- })));
829
- });
830
- var launch = (deferred, start) => make3({
831
- name: deferred.name,
832
- error: StepFailed,
833
- execute: gen(function* () {
834
- return yield* start(yield* LoopHost, yield* token(deferred));
835
- })
836
- });
837
- var toJson = (step, schema, value) => encodeUnknownEffect(toCodecJson(schema))(value).pipe(flatMap2(decodeUnknownEffect(Json)), mapError((error) => new StepFailed({ step, reason: error.message })));
838
- var agentWork = (name, options) => takeStep(name, "agent_work", "agent_work", gen(function* () {
839
- const run = yield* LoopRun;
840
- const agent = run.agents[options.agent];
841
- const undeclared = options.secrets?.find((secret) => !run.secrets.has(secret));
842
- if (undeclared !== undefined)
843
- return yield* new CapabilityDenied({ step: name, capability: "agent_work", secret: undeclared });
844
- if (agent === undefined)
845
- return yield* new StepFailed({ step: name, reason: `Agent role "${options.agent}" is not declared` });
846
- const deferred = agentWorkDeferred(name);
847
- const output = yield* jsonSchemaOf(run.loop, options.output).pipe(mapError((error) => new StepFailed({ step: name, reason: error.message })));
848
- yield* launch(deferred, (host, token2) => host.startAgentWork({
849
- step: name,
850
- role: options.agent,
851
- agent,
852
- prompt: options.prompt,
853
- output,
854
- ...options.secrets === undefined ? undefined : { secrets: options.secrets },
855
- token: token2
856
- }));
857
- const submitted = yield* await_(deferred);
858
- return yield* decodeEffect(toCodecJson(options.output))(submitted).pipe(mapError((error) => new OutputInvalid({ step: name, message: error.message })));
859
- }));
860
- var ask = (name, question) => takeStep(name, "ask", "ask", gen(function* () {
861
- const deferred = answerDeferred(name);
862
- const options = "options" in question ? question.options : undefined;
863
- yield* launch(deferred, (host, token2) => host.putQuestion({
864
- step: name,
865
- prompt: question.prompt,
866
- ...options === undefined ? undefined : { options },
867
- token: token2
868
- }));
869
- const answer = yield* await_(deferred);
870
- if (options === undefined)
871
- return answer;
872
- const offered = options.find((option) => option === answer);
873
- if (offered === undefined)
874
- return yield* new QuestionRefused({ step: name, answer, options });
875
- return offered;
876
- }));
877
- var call = (name, loop, input) => takeStep(name, "call", "call", gen(function* () {
878
- const deferred = childDeferred(name);
879
- const encoded = yield* toJson(name, loop.input, input);
880
- yield* launch(deferred, (host, token2) => host.admitChild({ step: name, loop: loop.id, input: encoded, token: token2 }));
881
- const result = yield* await_(deferred);
882
- return yield* decodeEffect(toCodecJson(loop.output))(result).pipe(mapError((error) => new ChildFailed({ step: name, loop: loop.id, reason: error.message })));
883
- }));
884
- var waitFor = (name, wait) => takeStep(name, "wait_for", undefined, gen(function* () {
885
- const deferred = eventDeferred(name);
886
- const timeoutMillis = toMillis(fromInputUnsafe(wait.timeout));
887
- yield* launch(deferred, (host, token2) => host.awaitEvent({
888
- step: name,
889
- event: wait.event,
890
- ...wait.filter === undefined ? undefined : { filter: wait.filter },
891
- timeoutMillis,
892
- token: token2
893
- }));
894
- return yield* await_(deferred);
895
- }));
896
- var verify = (name, request) => takeStep(name, "verify", "verify", gen(function* () {
897
- const deferred = verifyDeferred(name);
898
- yield* launch(deferred, (host, token2) => host.startVerification({
899
- step: name,
900
- ...request.revision === undefined ? undefined : { revision: request.revision },
901
- ...request.checks === undefined ? undefined : { checks: request.checks },
902
- token: token2
903
- }));
904
- return yield* await_(deferred);
905
- }));
906
- // packages/sdk/src/loop/plan.ts
907
- var PlanTicket = Struct({
908
- key: String2,
909
- title: String2,
910
- body: String2,
911
- acceptanceCriteria: ArraySchema(String2),
912
- repoBindingId: optional(String2),
913
- blockedBy: ArraySchema(String2),
914
- outcome: optional(LoopOutcome)
915
- });
916
- var cycleMessage = (keys) => `These tickets block each other in a cycle, so none can start: ${keys.join(", ")}`;
917
- var ticketsProblem = (tickets) => {
918
- const keys = new Set;
919
- for (const ticket of tickets) {
920
- if (keys.has(ticket.key))
921
- return `Two tickets have the key "${ticket.key}"`;
922
- keys.add(ticket.key);
923
- }
924
- for (const ticket of tickets)
925
- for (const blocker of ticket.blockedBy)
926
- if (!keys.has(blocker))
927
- return `Ticket "${ticket.key}" is blocked by "${blocker}", which is not a ticket`;
928
- const { blocked } = wavesOf(tickets);
929
- return blocked.length === 0 ? undefined : cycleMessage(blocked);
930
- };
931
- var PlanTickets = ArraySchema(PlanTicket).check(makeFilter((tickets) => ticketsProblem(tickets) ?? true));
932
-
933
- class BlockingCycle extends TaggedError2()("BlockingCycle", {
934
- tickets: ArraySchema(String2)
935
- }) {
936
- get message() {
937
- return cycleMessage(this.tickets);
938
- }
939
- }
940
- var byRepoBinding = (left, right) => (left.repoBindingId ?? "").localeCompare(right.repoBindingId ?? "");
941
- function wavesOf(tickets) {
942
- const placed = new Set;
943
- const waves = [];
944
- let left = tickets;
945
- while (left.length > 0) {
946
- const ready = left.filter((ticket) => ticket.blockedBy.every((blocker) => placed.has(blocker)));
947
- if (ready.length === 0)
948
- break;
949
- for (const ticket of ready)
950
- placed.add(ticket.key);
951
- waves.push(ready.toSorted(byRepoBinding));
952
- left = left.filter((ticket) => !placed.has(ticket.key));
953
- }
954
- return { waves, blocked: left.map((ticket) => ticket.key) };
955
- }
956
- var planWaves = (tickets) => suspend(() => {
957
- const { waves, blocked } = wavesOf(tickets);
958
- return blocked.length === 0 ? succeed5(waves) : fail4(new BlockingCycle({ tickets: blocked }));
959
- });
960
-
961
- // packages/sdk/src/loop/activities.ts
962
- var ChangeRequestRequest = Struct({
963
- title: String2,
964
- body: String2,
965
- integration: optional(String2)
966
- });
967
- var ChangeRequestResult = Struct({ id: String2, number: String2, url: String2 });
968
- var WriteBackMilestones = ["started", "change_request_opened", "merged", "failed"];
969
- var WriteBackRequest = Struct({
970
- milestone: optional(Literals(WriteBackMilestones)),
971
- changeRequestUrl: optional(String2)
972
- });
973
- var RunFile = Struct({ runFile: String2 }).pipe(decodeTo(Struct({ id: String2 }), transform2({
974
- decode: ({ runFile }) => ({ id: runFile }),
975
- encode: ({ id }) => ({ runFile: id })
976
- })));
977
- var FileRequest = Struct({ path: String2, caption: optional(String2) });
978
- var ArtifactRequest = Struct({
979
- kind: String2,
980
- title: String2,
981
- text: String2,
982
- data: optional(Json),
983
- files: optional(ArraySchema(RunFile))
984
- });
985
- var ArtifactResult = Struct({ artifactId: String2 });
986
- var NoteRequest = Struct({ text: String2, artifactId: optional(String2) });
987
- var CreateTasksRequest = Struct({ tickets: ArraySchema(PlanTicket) });
988
- var CreateTasksResult = Struct({
989
- tasks: ArraySchema(Struct({ key: String2, taskId: String2 }))
990
- });
991
- var IntegrationBranchRequest = Struct({ repoBindingId: optional(String2) });
992
- var IntegrationBranch = Struct({
993
- repoBindingId: String2,
994
- branch: String2,
995
- revision: String2
996
- });
997
- var MergeChangeRequestRequest = Struct({ changeRequestId: String2 });
998
- var MergeResult = Union([
999
- Struct({ status: Literal("merged"), revision: String2 }),
1000
- Struct({ status: Literal("conflict") })
1001
- ]);
1002
- var CommentRequest = Struct({ changeRequestId: String2, body: String2 });
1003
- var ReleaseRequest = Struct({
1004
- tag: String2,
1005
- revision: optional(String2),
1006
- title: String2,
1007
- notes: String2
1008
- });
1009
- var ReleaseResult = Struct({ tag: String2, revision: String2, url: String2 });
1010
- var TranscriptPoint = Struct({
1011
- runId: String2,
1012
- stepAttemptId: String2,
1013
- sequence: Int
1014
- });
1015
- var TranscriptsRequest = Struct({
1016
- days: Int.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo2(31))
1017
- });
1018
- var TranscriptsResult = Struct({
1019
- runs: ArraySchema(Struct({
1020
- runId: String2,
1021
- loopId: String2,
1022
- teamId: optional(String2),
1023
- failure: optional(String2),
1024
- entries: ArraySchema(Struct({ stepAttemptId: String2, sequence: Int, kind: String2, text: String2 }))
1025
- }))
1026
- });
1027
- var Citations = NonEmptyArray(TranscriptPoint);
1028
- var ProposeRequest = Union([
1029
- Struct({
1030
- kind: Literal("memory"),
1031
- teamId: String2,
1032
- content: String2,
1033
- citations: Citations
1034
- }),
1035
- Struct({
1036
- kind: Literal("task"),
1037
- title: String2,
1038
- description: String2,
1039
- teamId: optional(String2),
1040
- citations: Citations
1041
- })
1042
- ]);
1043
- var ProposeResult = Struct({ kind: Literals(["memory", "task"]), id: String2 });
1044
- var Health = Literals(["on_track", "at_risk", "off_track"]);
1045
- var ProjectActivityRequest = Struct({ projectId: String2 });
1046
- var ProjectActivityResult = Struct({
1047
- project: Struct({ id: String2, name: String2 }),
1048
- health: optional(Health),
1049
- since: optional(String2),
1050
- runs: ArraySchema(Struct({
1051
- runId: String2,
1052
- loopId: String2,
1053
- status: String2,
1054
- taskKey: optional(String2),
1055
- taskTitle: optional(String2),
1056
- summary: optional(String2),
1057
- entries: ArraySchema(Struct({ stepAttemptId: String2, sequence: Int, kind: String2, text: String2 }))
1058
- })),
1059
- taskChanges: ArraySchema(Struct({ taskKey: String2, title: String2, change: String2, at: String2 }))
1060
- });
1061
- var DraftUpdateRequest = Struct({
1062
- projectId: String2,
1063
- health: Health,
1064
- note: String2,
1065
- writtenFrom: Struct({
1066
- runs: Int,
1067
- taskChanges: Int,
1068
- since: optional(String2)
1069
- })
1070
- });
1071
- var DraftUpdateResult = Struct({ id: String2 });
1072
-
1073
- class ChangeRequestActivity extends Service()("@kitman-sh/sdk/loop/ChangeRequestActivity") {
1074
- }
1075
-
1076
- class WriteBackActivity extends Service()("@kitman-sh/sdk/loop/WriteBackActivity") {
1077
- }
1078
-
1079
- class ArtifactActivity extends Service()("@kitman-sh/sdk/loop/ArtifactActivity") {
1080
- }
1081
-
1082
- class FileActivity extends Service()("@kitman-sh/sdk/loop/FileActivity") {
1083
- }
1084
-
1085
- class NoteActivity extends Service()("@kitman-sh/sdk/loop/NoteActivity") {
1086
- }
1087
-
1088
- class CommentActivity extends Service()("@kitman-sh/sdk/loop/CommentActivity") {
1089
- }
1090
-
1091
- class CreateTasksActivity extends Service()("@kitman-sh/sdk/loop/CreateTasksActivity") {
1092
- }
1093
-
1094
- class IntegrationBranchActivity extends Service()("@kitman-sh/sdk/loop/IntegrationBranchActivity") {
1095
- }
1096
-
1097
- class MergeChangeRequestActivity extends Service()("@kitman-sh/sdk/loop/MergeChangeRequestActivity") {
1098
- }
1099
-
1100
- class ReleaseActivity extends Service()("@kitman-sh/sdk/loop/ReleaseActivity") {
1101
- }
1102
-
1103
- class TranscriptsActivity extends Service()("@kitman-sh/sdk/loop/TranscriptsActivity") {
1104
- }
1105
-
1106
- class ProposeActivity extends Service()("@kitman-sh/sdk/loop/ProposeActivity") {
1107
- }
1108
-
1109
- class ProjectActivityActivity extends Service()("@kitman-sh/sdk/loop/ProjectActivityActivity") {
1110
- }
1111
-
1112
- class DraftUpdateActivity extends Service()("@kitman-sh/sdk/loop/DraftUpdateActivity") {
1113
- }
1114
- var hostActivity = (name, kind, capability, success, execute) => takeStep(name, kind, capability, make3({ name: `${kind}/${name}`, success, error: StepFailed, execute }));
1115
- var changeRequest = (name, request) => hostActivity(name, "change_request", "change_request", ChangeRequestResult, gen(function* () {
1116
- return yield* (yield* ChangeRequestActivity).run(request, name);
1117
- }));
1118
- var writeBack = (name, request) => hostActivity(name, "write_back", "write_back", Void, gen(function* () {
1119
- return yield* (yield* WriteBackActivity).run(request, name);
1120
- }));
1121
- var artifact = (name, request) => hostActivity(name, "artifact", undefined, ArtifactResult, gen(function* () {
1122
- return yield* (yield* ArtifactActivity).run(request, name);
1123
- }));
1124
- var note = (name, request) => hostActivity(name, "note", undefined, Void, gen(function* () {
1125
- return yield* (yield* NoteActivity).run(request, name);
1126
- }));
1127
- var comment = (name, request) => hostActivity(name, "comment", "post_comment", Void, gen(function* () {
1128
- return yield* (yield* CommentActivity).run(request, name);
1129
- }));
1130
- var createTasks = (name, request) => hostActivity(name, "create_tasks", "create_tasks", CreateTasksResult, gen(function* () {
1131
- return yield* (yield* CreateTasksActivity).run(request, name);
1132
- }));
1133
- var integrationBranch = (name, request) => hostActivity(name, "integration_branch", "merge_change_request", IntegrationBranch, gen(function* () {
1134
- return yield* (yield* IntegrationBranchActivity).run(request, name);
1135
- }));
1136
- var mergeChangeRequest = (name, request) => hostActivity(name, "merge_change_request", "merge_change_request", MergeResult, gen(function* () {
1137
- return yield* (yield* MergeChangeRequestActivity).run(request, name);
1138
- }));
1139
- var release2 = (name, request) => hostActivity(name, "release", "publish_release", ReleaseResult, gen(function* () {
1140
- return yield* (yield* ReleaseActivity).run(request, name);
1141
- }));
1142
- var transcripts = (name, request) => hostActivity(name, "transcripts", "read_transcripts", TranscriptsResult, gen(function* () {
1143
- return yield* (yield* TranscriptsActivity).run(request, name);
1144
- }));
1145
- var propose = (name, request) => hostActivity(name, "propose", "propose", ProposeResult, gen(function* () {
1146
- return yield* (yield* ProposeActivity).run(request, name);
1147
- }));
1148
- var projectActivity = (name, request) => hostActivity(name, "project_activity", "read_project", ProjectActivityResult, gen(function* () {
1149
- return yield* (yield* ProjectActivityActivity).run(request, name);
1150
- }));
1151
- var draftUpdate = (name, request) => hostActivity(name, "draft_update", "draft_update", DraftUpdateResult, gen(function* () {
1152
- return yield* (yield* DraftUpdateActivity).run(request, name);
1153
- }));
1154
- // packages/sdk/src/loop/test-loop.ts
1155
- var LoopJournal = Struct({
1156
- activities: Record(String2, Json),
1157
- deferreds: Record(String2, Json)
1158
- });
1159
-
1160
- class ScriptedFailure extends TaggedClass("ScriptedFailure") {
1161
- }
1162
- // packages/sdk/src/loop/review.ts
1163
- var Severity = Literals(["blocker", "major", "minor"]);
1164
- var Finding = Struct({
1165
- severity: Severity,
1166
- file: String2,
1167
- line: Int,
1168
- detail: String2
1169
- });
1170
- var MergedFinding = Struct({
1171
- id: String2,
1172
- ...Finding.fields,
1173
- seats: ArraySchema(String2)
1174
- });
1175
- var Rebuttal = Struct({ findingId: String2, reason: String2 });
1176
- var RebuttalVerdict = Struct({ findingId: String2, accepted: Boolean2 });
1177
- var ScopeJudgement = Struct({ met: Boolean2, unmet: ArraySchema(String2) });
1178
- var rank = { blocker: 0, major: 1, minor: 2 };
1179
- var isBlocking = (finding) => finding.severity !== "minor";
1180
- var mergeFindings = (bySeat) => {
1181
- const merged = new Map;
1182
- for (const [seat, findings] of Object.entries(bySeat))
1183
- for (const finding of findings) {
1184
- const id = `${finding.file}:${finding.line}`;
1185
- const known = merged.get(id);
1186
- const seats = [...new Set([...known?.seats ?? [], seat])];
1187
- const worst = known === undefined || rank[finding.severity] < rank[known.severity] ? finding : known;
1188
- merged.set(id, { id, severity: worst.severity, file: worst.file, line: worst.line, detail: worst.detail, seats });
1189
- }
1190
- return [...merged.values()].toSorted((left, right) => rank[left.severity] - rank[right.severity]);
1191
- };
1192
- var splitDisputed = (findings, rebuttals) => {
1193
- const disputed = [];
1194
- const undisputed = [];
1195
- for (const finding of findings) {
1196
- const rebuttal = rebuttals.find((entry) => entry.findingId === finding.id);
1197
- if (rebuttal === undefined)
1198
- undisputed.push(finding);
1199
- else
1200
- disputed.push({ finding, rebuttal });
1201
- }
1202
- return { disputed, undisputed };
1203
- };
1204
- var settleRound = (round) => {
1205
- const { disputed, undisputed } = splitDisputed(round.findings, round.rebuttals);
1206
- const accepted = (entry) => {
1207
- const verdicts = round.verdicts.filter((verdict) => verdict.findingId === entry.finding.id);
1208
- return verdicts.length > 0 && verdicts.every((verdict) => verdict.accepted);
1209
- };
1210
- return {
1211
- open: undisputed,
1212
- withdrawn: disputed.filter(accepted),
1213
- standing: disputed.filter((entry) => !accepted(entry))
1214
- };
1215
- };
1216
- var rallyStop = (input) => {
1217
- const open = input.settled.open.filter(isBlocking).map((finding) => finding.id);
1218
- const standing = input.settled.standing.flatMap((entry) => isBlocking(entry.finding) ? [entry.finding.id] : []);
1219
- const unsettled = [...open, ...standing];
1220
- const stop = (reason) => ({ stop: true, reason, unsettled });
1221
- if (unsettled.length === 0)
1222
- return stop("settled");
1223
- if (standing.length > 0)
1224
- return stop("dispute_stands");
1225
- if (input.previous !== undefined && sameIds(input.previous, unsettled))
1226
- return stop("findings_returned");
1227
- return input.round >= input.maxRounds ? stop("round_cap") : { stop: false };
1228
- };
1229
- var sameIds = (left, right) => left.length === right.length && left.every((id) => right.includes(id));
1230
- // packages/sdk/src/loop/check.ts
1231
- class CheckFailed extends TaggedError2()("CheckFailed", {
1232
- loop: String2,
1233
- check: String2,
1234
- reason: String2
1235
- }) {
1236
- get detail() {
1237
- return `Check "${this.check}": ${this.reason}`;
1238
- }
1239
- get message() {
1240
- return `Loop "${this.loop}": ${this.detail}`;
1241
- }
1242
- }
1243
-
1244
- class StepNamedTwice extends TaggedError2()("StepNamedTwice", {
1245
- loop: String2,
1246
- check: String2,
1247
- step: String2
1248
- }) {
1249
- get detail() {
1250
- return `Check "${this.check}": Step "${this.step}" is named twice`;
1251
- }
1252
- get message() {
1253
- return `Loop "${this.loop}": ${this.detail}`;
1254
- }
1255
- }
1256
-
1257
- class ReplayDiverged extends TaggedError2()("ReplayDiverged", {
1258
- loop: String2,
1259
- check: String2,
1260
- first: ArraySchema(String2),
1261
- replay: ArraySchema(String2),
1262
- rerun: ArraySchema(String2)
1263
- }) {
1264
- get detail() {
1265
- const steps = (names) => names.join(", ") || "no Steps";
1266
- 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.`;
1267
- }
1268
- get message() {
1269
- return `Loop "${this.loop}": ${this.detail}`;
1270
- }
1271
- }
1272
- var LoopCheckError = Union([CheckFailed, StepNamedTwice, ReplayDiverged]);
1273
- export { LoopManifest, AgentDeclaration, KitInstallationDeclaration, KitAssignmentDeclaration, PackageDeclarations, LoopOutcome, defineLoop, ManifestInvalid, make, Suspended, make2, await_, make3, evidenceGate, ChildFailed, agentWork, ask, call, waitFor, verify, PlanTickets, planWaves, ChangeRequestResult, CreateTasksResult, TranscriptPoint, changeRequest, writeBack, artifact, note, comment, createTasks, integrationBranch, mergeChangeRequest, release2, transcripts, propose, projectActivity, draftUpdate, Finding, MergedFinding, Rebuttal, RebuttalVerdict, ScopeJudgement, isBlocking, mergeFindings, settleRound, rallyStop, LoopCheckError };