@kitman-sh/sdk 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/build/index.js +215 -0
  2. package/dist/chunk-f3d6cvkg.js +958 -0
  3. package/dist/chunk-jnxc0c54.js +3963 -0
  4. package/dist/loop/index.js +193 -0
  5. package/dist/program/index.js +24 -0
  6. package/package.json +29 -4
  7. package/types/packages/core/src/a2a.d.ts +577 -0
  8. package/types/packages/core/src/agent-capabilities.d.ts +1424 -0
  9. package/types/packages/core/src/agent-environment.d.ts +2429 -0
  10. package/types/packages/core/src/agent-launch-snapshot.d.ts +44 -0
  11. package/types/packages/core/src/agent-sandbox-policy.d.ts +31 -0
  12. package/types/packages/core/src/approval-queue.d.ts +126 -0
  13. package/types/packages/core/src/audit.d.ts +52 -0
  14. package/types/packages/core/src/change-delivery.d.ts +39 -0
  15. package/types/packages/core/src/change-request-review.d.ts +146 -0
  16. package/types/packages/core/src/change-request.d.ts +432 -0
  17. package/types/packages/core/src/common.d.ts +6 -0
  18. package/types/packages/core/src/connection.d.ts +33 -0
  19. package/types/packages/core/src/context-feedback.d.ts +89 -0
  20. package/types/packages/core/src/context-pack.d.ts +182 -0
  21. package/types/packages/core/src/crypto.d.ts +11 -0
  22. package/types/packages/core/src/data-lifecycle.d.ts +195 -0
  23. package/types/packages/core/src/decision.d.ts +48 -0
  24. package/types/packages/core/src/delivery-operation.d.ts +125 -0
  25. package/types/packages/core/src/delivery-policy.d.ts +174 -0
  26. package/types/packages/core/src/engineering-resources.d.ts +26 -0
  27. package/types/packages/core/src/enterprise-code-host.d.ts +21 -0
  28. package/types/packages/core/src/epic-delivery.d.ts +38 -0
  29. package/types/packages/core/src/extension.d.ts +35 -0
  30. package/types/packages/core/src/external-effect.d.ts +313 -0
  31. package/types/packages/core/src/fix-flow.d.ts +149 -0
  32. package/types/packages/core/src/following.d.ts +59 -0
  33. package/types/packages/core/src/github-delivery-fixtures.d.ts +28 -0
  34. package/types/packages/core/src/github-delivery.d.ts +78 -0
  35. package/types/packages/core/src/gitlab-delivery-fixtures.d.ts +26 -0
  36. package/types/packages/core/src/gitlab-delivery.d.ts +76 -0
  37. package/types/packages/core/src/global-search.d.ts +42 -0
  38. package/types/packages/core/src/id.d.ts +1 -0
  39. package/types/packages/core/src/index.d.ts +74 -0
  40. package/types/packages/core/src/integration.d.ts +137 -0
  41. package/types/packages/core/src/intent.d.ts +260 -0
  42. package/types/packages/core/src/json.d.ts +10 -0
  43. package/types/packages/core/src/kit-taxonomy.d.ts +21 -0
  44. package/types/packages/core/src/kit.d.ts +1489 -0
  45. package/types/packages/core/src/live.d.ts +8309 -0
  46. package/types/packages/core/src/loop-layers.d.ts +59 -0
  47. package/types/packages/core/src/loop-version.d.ts +59 -0
  48. package/types/packages/core/src/loop.d.ts +3076 -0
  49. package/types/packages/core/src/me.d.ts +31 -0
  50. package/types/packages/core/src/memory.d.ts +88 -0
  51. package/types/packages/core/src/my-teams.d.ts +1230 -0
  52. package/types/packages/core/src/notification.d.ts +181 -0
  53. package/types/packages/core/src/observability.d.ts +175 -0
  54. package/types/packages/core/src/package-declarations.d.ts +427 -0
  55. package/types/packages/core/src/package.d.ts +369 -0
  56. package/types/packages/core/src/personal-development-profile.d.ts +11 -0
  57. package/types/packages/core/src/platform-release.d.ts +60 -0
  58. package/types/packages/core/src/program-credential.d.ts +10 -0
  59. package/types/packages/core/src/project.d.ts +64 -0
  60. package/types/packages/core/src/proposal.d.ts +292 -0
  61. package/types/packages/core/src/provider-safe-text.d.ts +2 -0
  62. package/types/packages/core/src/redaction.d.ts +73 -0
  63. package/types/packages/core/src/repo-binding.d.ts +123 -0
  64. package/types/packages/core/src/run-journal.d.ts +28 -0
  65. package/types/packages/core/src/run-launch.d.ts +67 -0
  66. package/types/packages/core/src/run.d.ts +566 -0
  67. package/types/packages/core/src/runner-eligibility.d.ts +39 -0
  68. package/types/packages/core/src/runner-routing.d.ts +11 -0
  69. package/types/packages/core/src/runner-trust.d.ts +67 -0
  70. package/types/packages/core/src/runner.d.ts +3672 -0
  71. package/types/packages/core/src/runtime-type.d.ts +36 -0
  72. package/types/packages/core/src/schedule.d.ts +136 -0
  73. package/types/packages/core/src/schema.d.ts +89 -0
  74. package/types/packages/core/src/scope-directory.d.ts +100 -0
  75. package/types/packages/core/src/secret.d.ts +37 -0
  76. package/types/packages/core/src/session.d.ts +90 -0
  77. package/types/packages/core/src/step-brief.d.ts +50 -0
  78. package/types/packages/core/src/sync-kit.d.ts +587 -0
  79. package/types/packages/core/src/task-detail.d.ts +491 -0
  80. package/types/packages/core/src/task-execution-record.d.ts +620 -0
  81. package/types/packages/core/src/task-key.d.ts +9 -0
  82. package/types/packages/core/src/task.d.ts +543 -0
  83. package/types/packages/core/src/trigger-dispatch.d.ts +421 -0
  84. package/types/packages/core/src/work-unit.d.ts +725 -0
  85. package/types/packages/core/src/workspace.d.ts +50 -0
  86. package/types/packages/live/src/rpc/runner-client.d.ts +938 -0
  87. package/types/packages/live/src/rpc/runner-group.d.ts +730 -0
  88. package/types/packages/sdk/src/build/index.d.ts +45 -0
  89. package/types/packages/sdk/src/loop/activities.d.ts +187 -0
  90. package/types/packages/sdk/src/loop/check.d.ts +39 -0
  91. package/types/packages/sdk/src/loop/config.d.ts +68 -0
  92. package/types/packages/sdk/src/loop/define.d.ts +69 -0
  93. package/types/packages/sdk/src/loop/evidence.d.ts +66 -0
  94. package/types/packages/sdk/src/loop/index.d.ts +9 -0
  95. package/types/packages/sdk/src/loop/plan.d.ts +43 -0
  96. package/types/packages/sdk/src/loop/review.d.ts +86 -0
  97. package/types/packages/sdk/src/loop/steps.d.ts +224 -0
  98. package/types/packages/sdk/src/loop/test-loop.d.ts +112 -0
  99. package/types/packages/sdk/src/program/engine.d.ts +144 -0
  100. package/types/packages/sdk/src/program/host.d.ts +48 -0
  101. package/types/packages/sdk/src/program/index.d.ts +2 -0
  102. package/README.md +0 -3
@@ -0,0 +1,958 @@
1
+ // @bun
2
+ import {
3
+ guard,
4
+ Id,
5
+ Timestamp,
6
+ AgentSandboxNetwork,
7
+ LoopStepOutput,
8
+ StepBrief,
9
+ LoopManifest,
10
+ ManifestInvalid2,
11
+ loopManifest2,
12
+ StepFailed2,
13
+ agentWorkDeferred2,
14
+ answerDeferred2,
15
+ childDeferred2,
16
+ eventDeferred2,
17
+ verifyDeferred2,
18
+ loopWorkflow2,
19
+ executeLoop2,
20
+ LoopCheckError2,
21
+ checkLoop2
22
+ } from "./chunk-jnxc0c54.js";
23
+ // packages/core/src/repo-binding.ts
24
+ import * as Schema from "effect/Schema";
25
+ var RepoBindingPathPrefixPattern = "^(?!/)(?!.*\\\\)(?!.*(?:^|/)\\.\\.?(?:/|$))(?!.*//)\\S+$";
26
+ var RepoBindingProvider = Schema.Union([
27
+ Schema.Literal("github"),
28
+ Schema.Literal("gitlab"),
29
+ Schema.Literal("generic_git")
30
+ ]);
31
+ var RepoBindingStatus = Schema.Union([Schema.Literal("active"), Schema.Literal("disabled")]);
32
+ var RepoBindingCredentialProviderType = Schema.Union([
33
+ Schema.Literal("env"),
34
+ Schema.Literal("file"),
35
+ Schema.Literal("exec")
36
+ ]);
37
+ var RepoBindingAccessMode = Schema.Union([
38
+ Schema.Literal("local_checkout"),
39
+ Schema.Literal("managed_clone"),
40
+ Schema.Literal("runner_secret_provider")
41
+ ]);
42
+ var RepoBindingCredentialRef = Schema.Union([
43
+ Schema.Struct({ kind: Schema.Literal("none") }),
44
+ Schema.Struct({ kind: Schema.Literal("local_env"), envName: Schema.String.check(Schema.isMinLength(1)) }),
45
+ Schema.Struct({
46
+ kind: Schema.Literal("runner_secret"),
47
+ runnerSecretName: Schema.String.check(Schema.isMinLength(1)),
48
+ providerType: RepoBindingCredentialProviderType
49
+ }),
50
+ Schema.Struct({ kind: Schema.Literal("ssh_agent") })
51
+ ]);
52
+ var RepoBinding = Schema.Struct({
53
+ id: Id,
54
+ workspaceId: Id,
55
+ projectId: Id,
56
+ provider: RepoBindingProvider,
57
+ host: Schema.String.check(Schema.isMinLength(1)),
58
+ owner: Schema.String.check(Schema.isMinLength(1)),
59
+ name: Schema.String.check(Schema.isMinLength(1)),
60
+ repositoryUrl: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
61
+ pathPrefix: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isPattern(new RegExp(RepoBindingPathPrefixPattern, "u")))),
62
+ defaultTargetBranch: Schema.String.check(Schema.isMinLength(1)),
63
+ expectedBranch: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
64
+ expectedCommitSha: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
65
+ credentialRefs: Schema.Array(RepoBindingCredentialRef),
66
+ status: RepoBindingStatus,
67
+ createdAt: Timestamp,
68
+ updatedAt: Timestamp
69
+ });
70
+ var RepoBindingCreate = Schema.Struct({
71
+ provider: RepoBindingProvider,
72
+ host: Schema.String.check(Schema.isMinLength(1)),
73
+ owner: Schema.String.check(Schema.isMinLength(1)),
74
+ name: Schema.String.check(Schema.isMinLength(1)),
75
+ repositoryUrl: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
76
+ pathPrefix: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isPattern(new RegExp(RepoBindingPathPrefixPattern, "u")))),
77
+ defaultTargetBranch: Schema.String.check(Schema.isMinLength(1)),
78
+ expectedBranch: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
79
+ expectedCommitSha: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1))),
80
+ credentialRefs: Schema.optionalKey(Schema.Array(RepoBindingCredentialRef))
81
+ });
82
+ var RepoBindingTargetOverride = Schema.Struct({
83
+ targetBranch: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1)))
84
+ });
85
+ var RepoBindingList = Schema.Struct({ items: Schema.Array(RepoBinding) });
86
+ var RunnerRepoBindingCapability = Schema.Struct({
87
+ repoBindingId: Id,
88
+ provider: RepoBindingProvider,
89
+ host: Schema.String.check(Schema.isMinLength(1)),
90
+ accessModes: Schema.Array(RepoBindingAccessMode),
91
+ credentialProviderTypes: Schema.Array(RepoBindingCredentialProviderType),
92
+ authenticated: Schema.Boolean,
93
+ canPush: Schema.optionalKey(Schema.Boolean)
94
+ });
95
+ // packages/core/src/work-unit.ts
96
+ import * as Schema2 from "effect/Schema";
97
+ import * as Struct3 from "effect/Struct";
98
+ var WorkUnitLease = Schema2.Struct({
99
+ leaseOwnerId: Id,
100
+ runnerReplicaId: Id,
101
+ leaseId: Id,
102
+ attempt: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(1)),
103
+ fencingToken: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240), Schema2.isPattern(new RegExp("^[A-Za-z0-9._:-]+$", "u"))),
104
+ capacitySlot: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
105
+ leaseExpiresAt: Timestamp,
106
+ lastHeartbeatAt: Timestamp
107
+ });
108
+ var WorkUnitLeaseProjection = Schema2.Struct(Struct3.map(WorkUnitLease.fields, Schema2.optionalKey));
109
+ var WorkUnitRepoBinding = Schema2.Struct({
110
+ id: Id,
111
+ provider: RepoBindingProvider,
112
+ host: Schema2.String.check(Schema2.isMinLength(1)),
113
+ owner: Schema2.String.check(Schema2.isMinLength(1)),
114
+ name: Schema2.String.check(Schema2.isMinLength(1)),
115
+ repositoryUrl: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1))),
116
+ pathPrefix: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1))),
117
+ defaultTargetBranch: Schema2.String.check(Schema2.isMinLength(1)),
118
+ expectedBranch: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1))),
119
+ expectedCommitSha: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1)))
120
+ });
121
+ var WorkUnitLeaseInput = Schema2.Struct({
122
+ leaseOwnerId: Id,
123
+ runnerReplicaId: Id,
124
+ leaseId: Id,
125
+ attempt: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(1)),
126
+ fencingToken: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240), Schema2.isPattern(new RegExp("^[A-Za-z0-9._:-]+$", "u"))),
127
+ capacitySlot: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240))
128
+ });
129
+ var WorkUnitStatus = Schema2.Union([
130
+ Schema2.Literal("pending"),
131
+ Schema2.Literal("claimed"),
132
+ Schema2.Literal("running"),
133
+ Schema2.Literal("waiting"),
134
+ Schema2.Literal("blocked"),
135
+ Schema2.Literal("completed"),
136
+ Schema2.Literal("failed"),
137
+ Schema2.Literal("canceled"),
138
+ Schema2.Literal("expired")
139
+ ]);
140
+ var LoopCheckout = Schema2.Union([Schema2.Literal("none"), Schema2.Literal("read"), Schema2.Literal("write")]);
141
+ var AgentStepWorkUnit = Schema2.Struct({
142
+ kind: Schema2.Literal("agent_step"),
143
+ id: Id,
144
+ projectId: Schema2.optionalKey(Id),
145
+ runId: Id,
146
+ stepKey: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
147
+ attempt: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(1)),
148
+ lease: WorkUnitLease,
149
+ brief: StepBrief,
150
+ stepCredential: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(512)),
151
+ checkout: LoopCheckout,
152
+ repoBinding: Schema2.optionalKey(WorkUnitRepoBinding),
153
+ branch: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1))),
154
+ baseRevision: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1))),
155
+ network: Schema2.optionalKey(AgentSandboxNetwork),
156
+ sandbox: Schema2.optionalKey(Schema2.Literal("docker")),
157
+ secrets: Schema2.optionalKey(Schema2.Record(Schema2.String, Schema2.String)),
158
+ runBaseRevision: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1)))
159
+ });
160
+ var RunJournal = Schema2.Struct({
161
+ activities: Schema2.Record(Schema2.String, Schema2.Unknown),
162
+ deferreds: Schema2.Record(Schema2.String, Schema2.Unknown)
163
+ });
164
+ var OrchestrationWorkUnit = Schema2.Struct({
165
+ kind: Schema2.Literal("orchestration"),
166
+ id: Id,
167
+ projectId: Schema2.optionalKey(Id),
168
+ runId: Id,
169
+ loopDigest: Schema2.String.check(Schema2.isMinLength(64), Schema2.isMaxLength(64), Schema2.isPattern(new RegExp("^[a-f0-9]{64}$", "u"))),
170
+ input: Schema2.Unknown,
171
+ granted: Schema2.Array(Schema2.String),
172
+ lease: WorkUnitLease,
173
+ journal: RunJournal,
174
+ program: Schema2.Struct({
175
+ loopId: Schema2.String.check(Schema2.isMinLength(1)),
176
+ credential: Schema2.String.check(Schema2.isMinLength(1))
177
+ })
178
+ });
179
+ var ProgramWorkUnit = OrchestrationWorkUnit.mapFields(Struct3.omit(["program"]));
180
+ var ApprovedCheck = Schema2.Struct({
181
+ name: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(120), Schema2.isPattern(new RegExp("^[A-Za-z0-9][A-Za-z0-9._:-]*$", "u"))),
182
+ command: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(2000)),
183
+ workingDirectory: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(500)))
184
+ });
185
+ var VerificationWorkUnit = Schema2.Struct({
186
+ kind: Schema2.Literal("verification"),
187
+ id: Id,
188
+ projectId: Id,
189
+ runId: Id,
190
+ stepKey: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
191
+ lease: WorkUnitLease,
192
+ repoBinding: WorkUnitRepoBinding,
193
+ revision: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
194
+ checks: Schema2.Array(ApprovedCheck).check(Schema2.isMinLength(1), Schema2.isMaxLength(50))
195
+ });
196
+ var WorkUnit = Schema2.Union([OrchestrationWorkUnit, AgentStepWorkUnit, VerificationWorkUnit]);
197
+ var WorkUnitClaimResult = Schema2.Struct({ workUnit: Schema2.optionalKey(WorkUnit) });
198
+ var WorkUnitClaimInput = Schema2.Struct({
199
+ projectId: Schema2.optionalKey(Id),
200
+ runnerReplicaId: Id,
201
+ capacitySlot: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
202
+ idempotencyKey: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
203
+ leaseDurationSeconds: Schema2.optionalKey(Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(1), Schema2.isLessThanOrEqualTo(3600)))
204
+ });
205
+ var WorkUnitHeartbeatInput = Schema2.Struct({
206
+ workUnitId: Id,
207
+ lease: WorkUnitLeaseInput,
208
+ leaseDurationSeconds: Schema2.optionalKey(Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(1), Schema2.isLessThanOrEqualTo(3600)))
209
+ });
210
+ var WorkUnitHeartbeatResult = Schema2.Struct({
211
+ settled: Schema2.Boolean,
212
+ outputSubmitted: Schema2.optionalKey(Schema2.Boolean)
213
+ });
214
+ var WorkUnitReleaseInput = Schema2.Struct({
215
+ workUnitId: Id,
216
+ lease: WorkUnitLeaseInput
217
+ });
218
+ var CheckEvidence = Schema2.Struct({
219
+ name: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(120)),
220
+ command: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(2000)),
221
+ status: Schema2.Union([Schema2.Literal("passed"), Schema2.Literal("failed")]),
222
+ exitCode: Schema2.optionalKey(Schema2.Int),
223
+ durationMs: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0)),
224
+ outputTail: Schema2.String.check(Schema2.isMaxLength(8000))
225
+ });
226
+ var TreeEvidence = Schema2.Struct({
227
+ revision: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
228
+ tree: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(120)),
229
+ checks: Schema2.Array(CheckEvidence).check(Schema2.isMaxLength(50))
230
+ });
231
+ var VerificationEvidence = Schema2.Struct({ head: TreeEvidence, baseline: Schema2.optionalKey(TreeEvidence) });
232
+ var BoundaryChange = Schema2.Struct({
233
+ kind: Schema2.Literal("change"),
234
+ changedPaths: Schema2.Array(Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(4096))).check(Schema2.isMaxLength(1000)),
235
+ omittedPaths: Schema2.Int.check(Schema2.isGreaterThanOrEqualTo(0)),
236
+ files: Schema2.Array(Schema2.Struct({
237
+ path: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(4096)),
238
+ excerpt: Schema2.String.check(Schema2.isMaxLength(250000)),
239
+ redacted: Schema2.Boolean,
240
+ truncated: Schema2.Boolean
241
+ })).check(Schema2.isMaxLength(20)),
242
+ truncated: Schema2.Boolean
243
+ });
244
+ var WorkUnitOutcome = Schema2.Struct({
245
+ status: Schema2.Union([
246
+ Schema2.Literal("completed"),
247
+ Schema2.Literal("failed"),
248
+ Schema2.Literal("blocked"),
249
+ Schema2.Literal("canceled")
250
+ ]),
251
+ result: Schema2.optionalKey(LoopStepOutput),
252
+ revision: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(120))),
253
+ evidence: Schema2.optionalKey(VerificationEvidence),
254
+ boundary: Schema2.optionalKey(BoundaryChange),
255
+ failureSummary: Schema2.optionalKey(Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(4000)))
256
+ });
257
+ var WorkUnitCompletion = Schema2.Struct({
258
+ workUnitId: Id,
259
+ lease: WorkUnitLeaseInput,
260
+ idempotencyKey: Schema2.String.check(Schema2.isMinLength(1), Schema2.isMaxLength(240)),
261
+ outcome: WorkUnitOutcome
262
+ });
263
+ // packages/core/src/run-journal.ts
264
+ import * as Effect from "effect/Effect";
265
+ import * as Exit from "effect/Exit";
266
+ import * as Schema3 from "effect/Schema";
267
+ var journalEntryMaxBytes = 256 * 1024;
268
+ var JournalExit = Schema3.toCodecJson(Schema3.Exit(Schema3.Json, Schema3.Json, Schema3.Defect()));
269
+ var encodeJournalExit = (exit) => Schema3.encodeUnknownEffect(JournalExit)(Exit.map(exit, (value) => value ?? null));
270
+ var decodeJournalExit = Schema3.decodeUnknownEffect(JournalExit);
271
+ var JournalStepFailed = Schema3.TaggedStruct("StepFailed", { step: Schema3.String, reason: Schema3.String });
272
+ var JournalChildFailed = Schema3.TaggedStruct("ChildFailed", {
273
+ step: Schema3.String,
274
+ loop: Schema3.String,
275
+ reason: Schema3.String
276
+ });
277
+ var JournalWaitTimedOut = Schema3.TaggedStruct("WaitTimedOut", { step: Schema3.String, event: Schema3.String });
278
+ var journalEntryBytes = (entry) => new TextEncoder().encode(JSON.stringify(entry)).byteLength;
279
+ // packages/sdk/src/program/engine.ts
280
+ import * as Cause from "effect/Cause";
281
+ import * as Data from "effect/Data";
282
+ import * as Duration from "effect/Duration";
283
+ import * as Effect2 from "effect/Effect";
284
+ import * as Exit3 from "effect/Exit";
285
+ import * as Fiber from "effect/Fiber";
286
+ import * as Layer from "effect/Layer";
287
+ import * as Option from "effect/Option";
288
+ import * as Schema5 from "effect/Schema";
289
+
290
+ // packages/live/src/rpc/runner-group.ts
291
+ import * as Schema4 from "effect/Schema";
292
+ import { Rpc, RpcGroup, RpcMiddleware } from "effect/rpc";
293
+ var RunnerHeaders = { runnerId: "x-kitman-runner-id", protocolVersion: "x-kitman-rpc-protocol" };
294
+ var RunnerRpcProtocolVersion = 1;
295
+
296
+ class RunnerRpcError extends Schema4.TaggedError()("RunnerRpcError", {
297
+ code: Schema4.String,
298
+ message: Schema4.String,
299
+ status: Schema4.Finite
300
+ }) {
301
+ }
302
+
303
+ class RunnerAuthentication extends RpcMiddleware.Service()("RunnerAuthentication", {
304
+ error: RunnerRpcError
305
+ }) {
306
+ }
307
+ var EventFilterValue = Schema4.Union([Schema4.String, Schema4.Finite, Schema4.Boolean, Schema4.Null]);
308
+ var WorkAvailable = Schema4.TaggedStruct("WorkAvailable", {});
309
+ var LeaseRevoked = Schema4.TaggedStruct("LeaseRevoked", { workUnitId: Schema4.String });
310
+ var Settled = Schema4.TaggedStruct("Settled", { workUnitId: Schema4.String });
311
+ var Canceled = Schema4.TaggedStruct("Canceled", { workUnitId: Schema4.String });
312
+ var RunSettled = Schema4.TaggedStruct("RunSettled", { runId: Schema4.String });
313
+ var Steer = Schema4.TaggedStruct("Steer", {
314
+ workUnitId: Schema4.String,
315
+ messageId: Schema4.String,
316
+ text: Schema4.String
317
+ });
318
+ var SessionUpdated = Schema4.TaggedStruct("SessionUpdated", { workUnitId: Schema4.String });
319
+ var RunnerSignal = Schema4.Union([
320
+ WorkAvailable,
321
+ LeaseRevoked,
322
+ Settled,
323
+ Canceled,
324
+ RunSettled,
325
+ Steer,
326
+ SessionUpdated
327
+ ]);
328
+ var ProgramLease = Schema4.Struct({
329
+ workUnitId: Schema4.String,
330
+ leaseOwnerId: Schema4.String,
331
+ runnerReplicaId: Schema4.String,
332
+ leaseId: Schema4.String,
333
+ attempt: Schema4.Int,
334
+ fencingToken: Schema4.String,
335
+ capacitySlot: Schema4.String
336
+ });
337
+ var CheckpointSession = Schema4.Struct({
338
+ harness: Schema4.String,
339
+ id: Schema4.String,
340
+ name: Schema4.String,
341
+ content: Schema4.Uint8ArrayFromBase64
342
+ });
343
+ var StepCheckpoint = Schema4.Struct({
344
+ ref: Schema4.optionalKey(Schema4.String),
345
+ revision: Schema4.optionalKey(Schema4.String),
346
+ session: Schema4.optionalKey(CheckpointSession)
347
+ });
348
+ var SuggestedVerification = Schema4.Struct({
349
+ name: Schema4.String,
350
+ command: Schema4.String,
351
+ workingDirectory: Schema4.optional(Schema4.String)
352
+ });
353
+ var ProgramOutcome = Schema4.Union([
354
+ Schema4.Struct({ status: Schema4.Literal("completed"), output: Schema4.Json }),
355
+ Schema4.Struct({ status: Schema4.Literal("failed"), failureSummary: Schema4.String })
356
+ ]);
357
+
358
+ class RunnerRpcs extends RpcGroup.make(Rpc.make("Claim", {
359
+ payload: WorkUnitClaimInput,
360
+ success: WorkUnitClaimResult,
361
+ error: RunnerRpcError
362
+ }), Rpc.make("Heartbeat", {
363
+ payload: WorkUnitHeartbeatInput,
364
+ success: WorkUnitHeartbeatResult,
365
+ error: RunnerRpcError
366
+ }), Rpc.make("Complete", {
367
+ payload: WorkUnitCompletion,
368
+ error: RunnerRpcError
369
+ }), Rpc.make("Release", {
370
+ payload: WorkUnitReleaseInput,
371
+ error: RunnerRpcError
372
+ }), Rpc.make("RecordActivity", {
373
+ payload: { lease: ProgramLease, name: Schema4.String, attempt: Schema4.Int, exit: Schema4.Json },
374
+ error: RunnerRpcError
375
+ }), Rpc.make("DeferredDone", {
376
+ payload: { lease: ProgramLease, name: Schema4.String, exit: Schema4.Json },
377
+ error: RunnerRpcError
378
+ }), Rpc.make("ScheduleClock", {
379
+ payload: { lease: ProgramLease, name: Schema4.String, deferredName: Schema4.String, durationMillis: Schema4.Int },
380
+ error: RunnerRpcError
381
+ }), Rpc.make("PutQuestion", {
382
+ payload: {
383
+ lease: ProgramLease,
384
+ step: Schema4.String,
385
+ prompt: Schema4.String,
386
+ options: Schema4.optional(Schema4.Array(Schema4.String)),
387
+ verification: Schema4.optional(SuggestedVerification),
388
+ deferredName: Schema4.String
389
+ },
390
+ success: Schema4.Struct({ questionId: Schema4.String }),
391
+ error: RunnerRpcError
392
+ }), Rpc.make("StartAgentStep", {
393
+ payload: {
394
+ lease: ProgramLease,
395
+ step: Schema4.String,
396
+ deferredName: Schema4.String,
397
+ role: Schema4.String,
398
+ agentId: Schema4.String,
399
+ prompt: Schema4.String,
400
+ outputSchema: Schema4.Json,
401
+ secrets: Schema4.optionalKey(Schema4.Array(Schema4.String))
402
+ },
403
+ success: Schema4.Struct({ stepAttemptId: Schema4.String }),
404
+ error: RunnerRpcError
405
+ }), Rpc.make("StartVerification", {
406
+ payload: {
407
+ lease: ProgramLease,
408
+ step: Schema4.String,
409
+ deferredName: Schema4.String,
410
+ revision: Schema4.optionalKey(Schema4.String),
411
+ checks: Schema4.optional(Schema4.Array(Schema4.String))
412
+ },
413
+ success: Schema4.Struct({ verificationId: Schema4.String }),
414
+ error: RunnerRpcError
415
+ }), Rpc.make("KnownEvidence", {
416
+ payload: { lease: ProgramLease, trees: Schema4.Array(Schema4.String) },
417
+ success: Schema4.Array(Schema4.Struct({ tree: Schema4.String, name: Schema4.String, command: Schema4.String })),
418
+ error: RunnerRpcError
419
+ }), Rpc.make("AwaitEvent", {
420
+ payload: {
421
+ lease: ProgramLease,
422
+ step: Schema4.String,
423
+ deferredName: Schema4.String,
424
+ event: Schema4.String,
425
+ filter: Schema4.optional(Schema4.Record(Schema4.String, Schema4.Union([EventFilterValue, Schema4.Array(EventFilterValue)]))),
426
+ timeoutMillis: Schema4.Int
427
+ },
428
+ error: RunnerRpcError
429
+ }), Rpc.make("AdmitChild", {
430
+ payload: {
431
+ lease: ProgramLease,
432
+ step: Schema4.String,
433
+ loop: Schema4.String,
434
+ input: Schema4.Json,
435
+ deferredName: Schema4.String
436
+ },
437
+ success: Schema4.Struct({ runId: Schema4.String }),
438
+ error: RunnerRpcError
439
+ }), Rpc.make("StoreArtifact", {
440
+ payload: {
441
+ lease: ProgramLease,
442
+ step: Schema4.String,
443
+ kind: Schema4.String,
444
+ title: Schema4.String,
445
+ text: Schema4.String,
446
+ data: Schema4.optional(Schema4.Json)
447
+ },
448
+ success: Schema4.Struct({ artifactId: Schema4.String }),
449
+ error: RunnerRpcError
450
+ }), Rpc.make("RecordNote", {
451
+ payload: {
452
+ lease: ProgramLease,
453
+ step: Schema4.String,
454
+ text: Schema4.String,
455
+ artifactId: Schema4.optional(Schema4.String)
456
+ },
457
+ error: RunnerRpcError
458
+ }), Rpc.make("PerformHostEffect", {
459
+ payload: {
460
+ lease: ProgramLease,
461
+ step: Schema4.String,
462
+ effect: Schema4.Union([
463
+ Schema4.Struct({ kind: Schema4.Literal("post_comment"), changeRequestId: Schema4.String, body: Schema4.String }),
464
+ Schema4.Struct({
465
+ kind: Schema4.Literal("change_request"),
466
+ title: Schema4.String,
467
+ body: Schema4.String,
468
+ integration: Schema4.optionalKey(Schema4.String)
469
+ }),
470
+ Schema4.Struct({
471
+ kind: Schema4.Literal("write_back"),
472
+ milestone: Schema4.optionalKey(Schema4.Literals(["started", "change_request_opened", "merged", "failed"])),
473
+ changeRequestUrl: Schema4.optionalKey(Schema4.String)
474
+ })
475
+ ])
476
+ },
477
+ success: Schema4.UndefinedOr(Schema4.Struct({ id: Schema4.String, number: Schema4.String, url: Schema4.String })),
478
+ error: RunnerRpcError
479
+ }), Rpc.make("CreatePlanTasks", {
480
+ payload: {
481
+ lease: ProgramLease,
482
+ tickets: Schema4.Array(Schema4.Struct({
483
+ key: Schema4.String,
484
+ title: Schema4.String,
485
+ body: Schema4.String,
486
+ acceptanceCriteria: Schema4.Array(Schema4.String),
487
+ blockedBy: Schema4.Array(Schema4.String),
488
+ outcome: Schema4.optionalKey(Schema4.Literals(["feature", "bug", "refactor", "investigation", "docs", "migration"]))
489
+ }))
490
+ },
491
+ success: Schema4.Array(Schema4.Struct({ key: Schema4.String, taskId: Schema4.String })),
492
+ error: RunnerRpcError
493
+ }), Rpc.make("IntegrationBranch", {
494
+ payload: { lease: ProgramLease, repoBindingId: Schema4.optionalKey(Schema4.String) },
495
+ success: Schema4.Struct({ repoBindingId: Schema4.String, branch: Schema4.String, revision: Schema4.String }),
496
+ error: RunnerRpcError
497
+ }), Rpc.make("MergeChangeRequest", {
498
+ payload: { lease: ProgramLease, step: Schema4.String, changeRequestId: Schema4.String },
499
+ success: Schema4.Union([
500
+ Schema4.Struct({ status: Schema4.Literal("merged"), revision: Schema4.String }),
501
+ Schema4.Struct({ status: Schema4.Literal("conflict") })
502
+ ]),
503
+ error: RunnerRpcError
504
+ }), Rpc.make("PublishRelease", {
505
+ payload: {
506
+ lease: ProgramLease,
507
+ step: Schema4.String,
508
+ tag: Schema4.String,
509
+ revision: Schema4.optionalKey(Schema4.String),
510
+ title: Schema4.String,
511
+ notes: Schema4.String
512
+ },
513
+ success: Schema4.Struct({ tag: Schema4.String, revision: Schema4.String, url: Schema4.String }),
514
+ error: RunnerRpcError
515
+ }), Rpc.make("ReportSteer", {
516
+ payload: { workUnitId: Schema4.String, messageId: Schema4.String, delivered: Schema4.Boolean },
517
+ success: Schema4.Void,
518
+ error: RunnerRpcError
519
+ }), Rpc.make("SaveCheckpoint", {
520
+ payload: { lease: ProgramLease, checkpoint: StepCheckpoint },
521
+ success: Schema4.Void,
522
+ error: RunnerRpcError
523
+ }), Rpc.make("ResumeCheckpoint", {
524
+ payload: { lease: ProgramLease },
525
+ success: Schema4.UndefinedOr(StepCheckpoint),
526
+ error: RunnerRpcError
527
+ }), Rpc.make("SettledCheckpoints", {
528
+ success: Schema4.Array(Schema4.Struct({
529
+ stepAttemptId: Schema4.String,
530
+ ref: Schema4.optionalKey(Schema4.String),
531
+ repoBinding: Schema4.optionalKey(WorkUnitRepoBinding)
532
+ })),
533
+ error: RunnerRpcError
534
+ }), Rpc.make("ForgetCheckpoints", {
535
+ payload: { stepAttemptIds: Schema4.Array(Schema4.String) },
536
+ success: Schema4.Void,
537
+ error: RunnerRpcError
538
+ }), Rpc.make("Bundle", {
539
+ payload: { digest: Schema4.String },
540
+ success: Schema4.Struct({ bundle: Schema4.String }),
541
+ error: RunnerRpcError
542
+ }), Rpc.make("SettledRuns", {
543
+ payload: { runIds: Schema4.Array(Schema4.String) },
544
+ success: Schema4.Array(Schema4.String),
545
+ error: RunnerRpcError
546
+ }), Rpc.make("ProgramSecrets", {
547
+ payload: { lease: ProgramLease },
548
+ success: Schema4.Record(Schema4.String, Schema4.String),
549
+ error: RunnerRpcError
550
+ }), Rpc.make("Suspend", { payload: { lease: ProgramLease }, error: RunnerRpcError }), Rpc.make("FinishProgram", { payload: { lease: ProgramLease, outcome: ProgramOutcome }, error: RunnerRpcError }), Rpc.make("Signals", {
551
+ payload: { runnerReplicaId: Schema4.String },
552
+ success: RunnerSignal,
553
+ error: RunnerRpcError,
554
+ stream: true
555
+ })).middleware(RunnerAuthentication) {
556
+ }
557
+
558
+ // packages/sdk/src/program/engine.ts
559
+ import { Workflow, WorkflowEngine } from "effect/workflow";
560
+
561
+ class JournalWriteFailed2 extends Data.TaggedError("JournalWriteFailed") {
562
+ get message() {
563
+ return `Journal write failed: ${this.cause.message}`;
564
+ }
565
+ }
566
+ var written = (effect) => effect.pipe(Effect2.catch((cause) => Effect2.die(new JournalWriteFailed2({ cause }))));
567
+ var entryFor = (name, exit) => Effect2.gen(function* () {
568
+ const entry = yield* Effect2.orDie(encodeJournalExit(exit));
569
+ const bytes = journalEntryBytes(entry);
570
+ if (bytes > journalEntryMaxBytes)
571
+ return yield* Effect2.die(`"${name}" result is over the ${journalEntryMaxBytes}-byte journal cap (${bytes} bytes); store large content as a Run artifact`);
572
+ return entry;
573
+ });
574
+ var decoded = (entry) => Effect2.orDie(decodeJournalExit(entry));
575
+ var JournalEntries = Schema5.Record(Schema5.String, Schema5.Json);
576
+ var isSuspended = Schema5.is(Workflow.Suspended);
577
+ var makeEncodedEngine = (recorded, journal) => Effect2.gen(function* () {
578
+ const scope2 = yield* Effect2.scope;
579
+ const entries = (journalPart) => Effect2.map(Effect2.orDie(Schema5.decodeUnknownEffect(JournalEntries)(journalPart)), Object.entries);
580
+ const activities = new Map(yield* entries(recorded.activities));
581
+ const deferreds = new Map(yield* entries(recorded.deferreds));
582
+ const workflows = new Map;
583
+ const executions = new Map;
584
+ const start = (executionId, execution) => Effect2.gen(function* () {
585
+ const execute = workflows.get(execution.workflow._tag);
586
+ if (execute === undefined)
587
+ return yield* Effect2.die(`Workflow ${execution.workflow._tag} is not registered`);
588
+ const instance = WorkflowEngine.WorkflowInstance.initial(execution.workflow, executionId);
589
+ execution.fiber = yield* execute(execution.payload, executionId).pipe(Workflow.intoResult, Effect2.provideService(WorkflowEngine.WorkflowEngine, engine), Effect2.provideService(WorkflowEngine.WorkflowInstance, instance), Effect2.forkIn(scope2));
590
+ });
591
+ const encoded = {
592
+ register: (workflow, execute) => Effect2.sync(() => void workflows.set(workflow._tag, execute)),
593
+ execute: (workflow, options) => Effect2.gen(function* () {
594
+ let execution = executions.get(options.executionId);
595
+ if (execution === undefined) {
596
+ execution = { workflow, payload: options.payload, fiber: undefined };
597
+ executions.set(options.executionId, execution);
598
+ yield* start(options.executionId, execution);
599
+ }
600
+ if (options.discard || execution.fiber === undefined)
601
+ return;
602
+ return yield* Fiber.join(execution.fiber);
603
+ }),
604
+ poll: (_workflow, executionId) => Effect2.sync(() => {
605
+ const exit = executions.get(executionId)?.fiber?.pollUnsafe();
606
+ return exit !== undefined && Exit3.isSuccess(exit) ? Option.some(exit.value) : Option.none();
607
+ }),
608
+ interrupt: (_workflow, executionId) => interrupt2(executionId),
609
+ interruptUnsafe: (_workflow, executionId) => interrupt2(executionId),
610
+ resume: (_workflow, executionId) => Effect2.suspend(() => {
611
+ const execution = executions.get(executionId);
612
+ const exit = execution?.fiber?.pollUnsafe();
613
+ return execution !== undefined && exit !== undefined && Exit3.isSuccess(exit) && isSuspended(exit.value) ? start(executionId, execution) : Effect2.void;
614
+ }),
615
+ activityExecute: (activity, attempt) => Effect2.gen(function* () {
616
+ const key = `${activity.name}/${attempt}`;
617
+ const replayed = activities.get(key);
618
+ if (replayed !== undefined)
619
+ return new Workflow.Complete({ exit: yield* decoded(replayed) });
620
+ const instance = yield* WorkflowEngine.WorkflowInstance;
621
+ const result = yield* activity.executeEncoded.pipe(Workflow.intoResult, Effect2.provideService(WorkflowEngine.WorkflowInstance, WorkflowEngine.WorkflowInstance.initial(instance.workflow, instance.executionId)));
622
+ if (result instanceof Workflow.Complete && !(Exit3.isFailure(result.exit) && journalLoss(result.exit.cause))) {
623
+ const entry = yield* entryFor(activity.name, result.exit);
624
+ yield* written(journal.recordActivity({ name: activity.name, attempt, exit: entry }));
625
+ activities.set(key, entry);
626
+ }
627
+ return result;
628
+ }),
629
+ deferredResult: (deferred) => Effect2.suspend(() => {
630
+ const entry = deferreds.get(deferred.name);
631
+ return entry === undefined ? Effect2.succeedNone : Effect2.asSome(decoded(entry));
632
+ }),
633
+ deferredDone: (options) => Effect2.gen(function* () {
634
+ if (deferreds.has(options.deferredName))
635
+ return;
636
+ const entry = yield* entryFor(options.deferredName, options.exit);
637
+ yield* written(journal.deferredDone({ name: options.deferredName, exit: entry }));
638
+ deferreds.set(options.deferredName, entry);
639
+ yield* encoded.resume(executions.get(options.executionId)?.workflow ?? emptyWorkflow, options.executionId);
640
+ }),
641
+ scheduleClock: (_workflow, { clock }) => deferreds.has(clock.deferred.name) ? Effect2.void : written(journal.scheduleClock({
642
+ name: clock.name,
643
+ deferredName: clock.deferred.name,
644
+ durationMillis: Duration.toMillis(clock.duration)
645
+ }))
646
+ };
647
+ const interrupt2 = (executionId) => Effect2.suspend(() => {
648
+ const fiber = executions.get(executionId)?.fiber;
649
+ return fiber === undefined ? Effect2.void : Fiber.interrupt(fiber);
650
+ });
651
+ const engine = WorkflowEngine.makeUnsafe(encoded);
652
+ return { engine, encoded };
653
+ });
654
+ var emptyWorkflow = Workflow.make("kitman-loop/none", { payload: {}, idempotencyKey: () => "none" });
655
+ var replayStatuses = new Set([401, 403, 409, 429]);
656
+ var isRunnerRpcError = Schema5.is(RunnerRpcError);
657
+ var refusedStep2 = (cause) => {
658
+ if ("code" in cause && (cause.code === "capability_denied" || cause.code === "step_refused"))
659
+ return true;
660
+ return isRunnerRpcError(cause) && cause.status >= 400 && cause.status < 500 && !replayStatuses.has(cause.status);
661
+ };
662
+ var requested = (step, request) => request.pipe(Effect2.catch((cause) => refusedStep2(cause) ? Effect2.fail(new StepFailed2({ step, reason: cause.message })) : Effect2.die(new JournalWriteFailed2({ cause }))));
663
+ var runnerHost = (journal) => ({
664
+ putQuestion: (launch) => requested(launch.step, journal.putQuestion({
665
+ step: launch.step,
666
+ prompt: launch.prompt,
667
+ deferredName: answerDeferred2(launch.step).name,
668
+ ...launch.options === undefined ? undefined : { options: launch.options },
669
+ ...launch.verification === undefined ? undefined : { verification: launch.verification }
670
+ })).pipe(Effect2.asVoid),
671
+ startVerification: (launch) => requested(launch.step, journal.startVerification({
672
+ step: launch.step,
673
+ deferredName: verifyDeferred2(launch.step).name,
674
+ ...launch.revision === undefined ? undefined : { revision: launch.revision },
675
+ ...launch.checks === undefined ? undefined : { checks: launch.checks }
676
+ })).pipe(Effect2.asVoid),
677
+ startAgentWork: (launch) => requested(launch.step, journal.startAgentStep({
678
+ step: launch.step,
679
+ deferredName: agentWorkDeferred2(launch.step).name,
680
+ role: launch.role,
681
+ agentId: launch.agent,
682
+ prompt: launch.prompt,
683
+ outputSchema: launch.output,
684
+ ...launch.secrets === undefined ? undefined : { secrets: launch.secrets }
685
+ })).pipe(Effect2.asVoid),
686
+ admitChild: (launch) => requested(launch.step, journal.admitChild({
687
+ step: launch.step,
688
+ loop: launch.loop,
689
+ input: launch.input,
690
+ deferredName: childDeferred2(launch.step).name
691
+ })).pipe(Effect2.asVoid),
692
+ awaitEvent: (launch) => requested(launch.step, journal.awaitEvent({
693
+ step: launch.step,
694
+ deferredName: eventDeferred2(launch.step).name,
695
+ event: launch.event,
696
+ ...launch.filter === undefined ? undefined : { filter: launch.filter },
697
+ timeoutMillis: launch.timeoutMillis
698
+ }))
699
+ });
700
+ var runnerActivities = (journal) => ({
701
+ changeRequest: {
702
+ run: (request, step) => requested(step, journal.performHostEffect({
703
+ step,
704
+ effect: {
705
+ kind: "change_request",
706
+ title: request.title,
707
+ body: request.body,
708
+ ...request.integration === undefined ? undefined : { integration: request.integration }
709
+ }
710
+ })).pipe(Effect2.filterOrFail((opened) => opened !== undefined, () => new StepFailed2({ step, reason: "Kitman opened no ChangeRequest" })))
711
+ },
712
+ writeBack: {
713
+ run: (request, step) => requested(step, journal.performHostEffect({
714
+ step,
715
+ effect: {
716
+ kind: "write_back",
717
+ ...request.milestone === undefined ? undefined : { milestone: request.milestone },
718
+ ...request.changeRequestUrl === undefined ? undefined : { changeRequestUrl: request.changeRequestUrl }
719
+ }
720
+ })).pipe(Effect2.asVoid)
721
+ },
722
+ artifact: { run: (request, step) => requested(step, journal.storeArtifact({ step, ...request })) },
723
+ note: { run: (request, step) => requested(step, journal.recordNote({ step, ...request })) },
724
+ createTasks: {
725
+ run: (request, step) => requested(step, Effect2.map(journal.createPlanTasks(request.tickets), (tasks) => ({ tasks })))
726
+ },
727
+ integrationBranch: {
728
+ run: (request, step) => requested(step, journal.integrationBranch(request.repoBindingId))
729
+ },
730
+ mergeChangeRequest: {
731
+ run: (request, step) => requested(step, journal.mergeChangeRequest({ step, ...request }))
732
+ },
733
+ release: {
734
+ run: ({ revision, ...request }, step) => requested(step, journal.publishRelease({ step, ...request, ...revision === undefined ? undefined : { revision } }))
735
+ },
736
+ comment: {
737
+ run: (request, step) => requested(step, journal.performHostEffect({ step, effect: { kind: "post_comment", ...request } })).pipe(Effect2.asVoid)
738
+ }
739
+ });
740
+ var describeFailure = (cause) => {
741
+ const error = Cause.squash(cause);
742
+ const summary = error instanceof Error ? "_tag" in error ? `${String(error._tag)}: ${error.message}` : error.message : String(error);
743
+ return summary.slice(0, 4000) || "Program failed";
744
+ };
745
+ var journalLoss = (cause) => cause.reasons.flatMap((reason) => Cause.isDieReason(reason) && reason.defect instanceof JournalWriteFailed2 ? [reason.defect] : [])[0];
746
+ var runProgram2 = (loop, work, journal) => Effect2.scoped(Effect2.gen(function* () {
747
+ const { engine, encoded } = yield* makeEncodedEngine(work.journal, journal);
748
+ const workflow = loopWorkflow2(loop);
749
+ const execute = executeLoop2(loop, {
750
+ host: runnerHost(journal),
751
+ activities: runnerActivities(journal),
752
+ granted: new Set(loop.capabilities.filter((capability) => work.granted.includes(capability)))
753
+ });
754
+ yield* Layer.build(workflow.toLayer(execute).pipe(Layer.provide(Layer.succeed(WorkflowEngine.WorkflowEngine)(engine))));
755
+ const result = yield* encoded.execute(workflow, {
756
+ executionId: work.runId,
757
+ payload: { input: work.input },
758
+ discard: false
759
+ });
760
+ if (isSuspended(result)) {
761
+ yield* written(journal.suspend);
762
+ return "suspended";
763
+ }
764
+ if (Exit3.isSuccess(result.exit)) {
765
+ const output = yield* Schema5.encodeUnknownEffect(Schema5.toCodecJson(loop.output))(result.exit.value).pipe(Effect2.flatMap(Schema5.decodeUnknownEffect(Schema5.Json)), Effect2.option);
766
+ if (Option.isSome(output)) {
767
+ yield* written(journal.finish({ status: "completed", output: output.value }));
768
+ return "completed";
769
+ }
770
+ yield* written(journal.finish({ status: "failed", failureSummary: "Program output does not encode as JSON" }));
771
+ return "failed";
772
+ }
773
+ const lost = journalLoss(result.exit.cause);
774
+ if (lost !== undefined)
775
+ return yield* lost;
776
+ yield* written(journal.finish({ status: "failed", failureSummary: describeFailure(result.exit.cause) }));
777
+ return "failed";
778
+ })).pipe(Effect2.catchDefect((defect) => defect instanceof JournalWriteFailed2 ? Effect2.fail(defect) : Effect2.die(defect)));
779
+ var programLease2 = (work) => ({
780
+ workUnitId: work.id,
781
+ leaseOwnerId: work.lease.leaseOwnerId,
782
+ runnerReplicaId: work.lease.runnerReplicaId,
783
+ leaseId: work.lease.leaseId,
784
+ attempt: work.lease.attempt,
785
+ fencingToken: work.lease.fencingToken,
786
+ capacitySlot: work.lease.capacitySlot
787
+ });
788
+ var rpcProgramJournal2 = (rpc, work) => {
789
+ const lease = programLease2(work);
790
+ return {
791
+ recordActivity: (entry) => rpc.recordActivity({ lease, ...entry }),
792
+ deferredDone: (entry) => rpc.deferredDone({ lease, ...entry }),
793
+ scheduleClock: (clock) => rpc.scheduleClock({ lease, ...clock }),
794
+ putQuestion: (question) => rpc.putQuestion({
795
+ lease,
796
+ step: question.step,
797
+ prompt: question.prompt,
798
+ deferredName: question.deferredName,
799
+ ...question.options === undefined ? undefined : { options: [...question.options] },
800
+ ...question.verification === undefined ? undefined : { verification: question.verification }
801
+ }),
802
+ startVerification: (verification) => rpc.startVerification({
803
+ lease,
804
+ step: verification.step,
805
+ deferredName: verification.deferredName,
806
+ ...verification.revision === undefined ? undefined : { revision: verification.revision },
807
+ ...verification.checks === undefined ? undefined : { checks: [...verification.checks] }
808
+ }),
809
+ startAgentStep: ({ secrets, ...step }) => rpc.startAgentStep({ lease, ...step, ...secrets === undefined ? undefined : { secrets: [...secrets] } }),
810
+ awaitEvent: (wait) => rpc.awaitEvent({ lease, ...wait }),
811
+ admitChild: (child) => rpc.admitChild({ lease, ...child }),
812
+ storeArtifact: (artifact) => rpc.storeArtifact({ lease, ...artifact }),
813
+ recordNote: (note) => rpc.recordNote({ lease, ...note }),
814
+ performHostEffect: (request) => rpc.performHostEffect({ lease, ...request }),
815
+ createPlanTasks: (tickets) => rpc.createPlanTasks({
816
+ lease,
817
+ tickets: tickets.map((ticket) => ({
818
+ key: ticket.key,
819
+ title: ticket.title,
820
+ body: ticket.body,
821
+ acceptanceCriteria: ticket.acceptanceCriteria,
822
+ blockedBy: ticket.blockedBy,
823
+ ...ticket.outcome === undefined ? undefined : { outcome: ticket.outcome }
824
+ }))
825
+ }),
826
+ integrationBranch: (repoBindingId) => rpc.integrationBranch({ lease, ...repoBindingId === undefined ? undefined : { repoBindingId } }),
827
+ mergeChangeRequest: (request) => rpc.mergeChangeRequest({ lease, ...request }),
828
+ publishRelease: (request) => rpc.publishRelease({ lease, ...request }),
829
+ suspend: rpc.suspend({ lease }),
830
+ finish: (outcome) => rpc.finishProgram({ lease, outcome })
831
+ };
832
+ };
833
+
834
+ // packages/live/src/rpc/runner-client.ts
835
+ import * as Effect3 from "effect/Effect";
836
+ import * as Layer2 from "effect/Layer";
837
+ import * as Stream from "effect/Stream";
838
+ import { RpcClient, RpcSerialization } from "effect/rpc";
839
+ import * as Socket from "effect/socket/Socket";
840
+ var runnerWebSocketProtocol = (url) => RpcClient.layerProtocolSocket({ retryTransientErrors: true }).pipe(Layer2.provide(Socket.layerWebSocket(url)), Layer2.provide(Socket.layerWebSocketConstructorGlobal), Layer2.provide(RpcSerialization.layerJson));
841
+ function runnerRpcUrl(apiUrl) {
842
+ const url = new URL("/v1/runners/rpc", apiUrl);
843
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
844
+ return url.toString();
845
+ }
846
+ var makeRunnerRpcClient = (options) => Effect3.gen(function* () {
847
+ const protocol = yield* Layer2.build(options.protocol);
848
+ const client = yield* RpcClient.make(RunnerRpcs).pipe(Effect3.provideContext(protocol));
849
+ const authorized = (call) => Effect3.flatMap(options.bearer, (token) => RpcClient.withHeaders(call, {
850
+ authorization: `Bearer ${token}`,
851
+ [RunnerHeaders.runnerId]: options.runnerId,
852
+ [RunnerHeaders.protocolVersion]: String(RunnerRpcProtocolVersion)
853
+ }));
854
+ return {
855
+ claim: (input) => authorized(client.Claim(input)),
856
+ heartbeat: (input) => authorized(client.Heartbeat(input)),
857
+ complete: (input) => authorized(client.Complete(input)),
858
+ release: (input) => authorized(client.Release(input)),
859
+ recordActivity: (input) => authorized(client.RecordActivity(input)),
860
+ deferredDone: (input) => authorized(client.DeferredDone(input)),
861
+ scheduleClock: (input) => authorized(client.ScheduleClock(input)),
862
+ putQuestion: (input) => authorized(client.PutQuestion(input)),
863
+ programSecrets: (input) => authorized(client.ProgramSecrets(input)),
864
+ suspend: (input) => authorized(client.Suspend(input)),
865
+ finishProgram: (input) => authorized(client.FinishProgram(input)),
866
+ startAgentStep: (input) => authorized(client.StartAgentStep(input)),
867
+ startVerification: (input) => authorized(client.StartVerification(input)),
868
+ knownEvidence: (input) => authorized(client.KnownEvidence(input)),
869
+ awaitEvent: (input) => authorized(client.AwaitEvent(input)),
870
+ admitChild: (input) => authorized(client.AdmitChild(input)),
871
+ storeArtifact: (input) => authorized(client.StoreArtifact(input)),
872
+ recordNote: (input) => authorized(client.RecordNote(input)),
873
+ performHostEffect: (input) => authorized(client.PerformHostEffect(input)),
874
+ createPlanTasks: (input) => authorized(client.CreatePlanTasks(input)),
875
+ integrationBranch: (input) => authorized(client.IntegrationBranch(input)),
876
+ mergeChangeRequest: (input) => authorized(client.MergeChangeRequest(input)),
877
+ publishRelease: (input) => authorized(client.PublishRelease(input)),
878
+ bundle: (digest) => authorized(client.Bundle({ digest })),
879
+ settledRuns: (runIds) => authorized(client.SettledRuns({ runIds })),
880
+ reportSteer: (input) => authorized(client.ReportSteer(input)),
881
+ saveCheckpoint: (input) => authorized(client.SaveCheckpoint(input)),
882
+ resumeCheckpoint: (input) => authorized(client.ResumeCheckpoint(input)),
883
+ settledCheckpoints: authorized(client.SettledCheckpoints()),
884
+ forgetCheckpoints: (stepAttemptIds) => authorized(client.ForgetCheckpoints({ stepAttemptIds })),
885
+ listen: (runnerReplicaId, onSignal) => authorized(Stream.runForEach(client.Signals({ runnerReplicaId }), onSignal))
886
+ };
887
+ });
888
+
889
+ // packages/sdk/src/program/host.ts
890
+ import * as BunRuntime from "@effect/platform-bun/BunRuntime";
891
+ import * as Config from "effect/Config";
892
+ import * as ConfigProvider from "effect/ConfigProvider";
893
+ import * as Effect4 from "effect/Effect";
894
+ import * as Option2 from "effect/Option";
895
+ import * as Redacted2 from "effect/Redacted";
896
+ import * as Schema6 from "effect/Schema";
897
+ var describeFlag2 = "--kitman-describe";
898
+ var Described2 = Schema6.Union([
899
+ Schema6.TaggedStruct("Described", {
900
+ loops: Schema6.Array(LoopManifest),
901
+ agents: Schema6.Record(Schema6.String, Schema6.Json),
902
+ schedules: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.Json)),
903
+ kits: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.Json))
904
+ }),
905
+ Schema6.TaggedStruct("Refused", { error: Schema6.Union([ManifestInvalid2, LoopCheckError2]) })
906
+ ]);
907
+ var encodeDescribed = Schema6.encodeEffect(Schema6.fromJsonString(Schema6.toCodecJson(Described2)));
908
+
909
+ class ProgramRefused extends Schema6.TaggedError()("ProgramRefused", { reason: Schema6.String }) {
910
+ get message() {
911
+ return this.reason;
912
+ }
913
+ }
914
+ var programSecrets2 = (rpc, lease) => rpc.programSecrets({ lease }).pipe(Effect4.asSome, Effect4.catchIf(refusedStep2, (error) => Effect4.as(rpc.finishProgram({
915
+ lease,
916
+ outcome: { status: "failed", failureSummary: `Kitman refused the Loop its Secrets: ${error.message}` }
917
+ }), Option2.none())));
918
+ var describe = (config) => Effect4.gen(function* () {
919
+ const loops = yield* Effect4.forEach(config.loops, loopManifest2);
920
+ for (const loop of config.loops)
921
+ for (const check of loop.checks ?? [])
922
+ yield* checkLoop2(loop, check);
923
+ return {
924
+ _tag: "Described",
925
+ loops,
926
+ agents: config.agents ?? {},
927
+ ...config.schedules === undefined ? undefined : { schedules: config.schedules },
928
+ ...config.kits === undefined ? undefined : { kits: config.kits }
929
+ };
930
+ }).pipe(Effect4.catch((error) => Effect4.succeed({ _tag: "Refused", error })), Effect4.flatMap(encodeDescribed), Effect4.flatMap((described) => Effect4.callback((resume) => void process.stdout.write(described, () => resume(Effect4.void)))), Effect4.as(0));
931
+ var readStdin = Effect4.tryPromise(() => Bun.stdin.text());
932
+ var isWorkUnit = guard(ProgramWorkUnit);
933
+ var host = (config) => Effect4.gen(function* () {
934
+ const loopId = yield* Config.String("KITMAN_LOOP_ID");
935
+ const apiUrl = yield* Config.String("KITMAN_API_URL");
936
+ const credential = yield* Config.Redacted("KITMAN_PROGRAM_CREDENTIAL");
937
+ const work = yield* Schema6.decodeEffect(Schema6.fromJsonString(Schema6.Unknown))(yield* readStdin);
938
+ if (!isWorkUnit(work))
939
+ return yield* new ProgramRefused({ reason: "stdin holds no orchestration Work Unit" });
940
+ const loop = config.loops.find((candidate) => candidate.id === loopId);
941
+ if (loop === undefined)
942
+ return yield* new ProgramRefused({ reason: `The Package declares no Loop "${loopId}"` });
943
+ const rpc = yield* makeRunnerRpcClient({
944
+ runnerId: work.lease.leaseOwnerId,
945
+ bearer: Effect4.sync(() => Redacted2.value(credential)),
946
+ protocol: runnerWebSocketProtocol(runnerRpcUrl(apiUrl))
947
+ });
948
+ const secrets = (loop.secrets ?? []).length === 0 ? Option2.some({}) : yield* programSecrets2(rpc, programLease2(work));
949
+ if (Option2.isNone(secrets))
950
+ return 0;
951
+ return yield* runProgram2(loop, work, rpcProgramJournal2(rpc, work)).pipe(Effect4.provideService(ConfigProvider.ConfigProvider, ConfigProvider.fromUnknown(secrets.value)), Effect4.as(0), Effect4.catchTag("JournalWriteFailed", (error) => Effect4.as(Effect4.logError(error.message), 1)));
952
+ }).pipe(Effect4.scoped, Effect4.catch((error) => Effect4.as(Effect4.logError(error.message), 2)));
953
+ var runPackage2 = (config) => {
954
+ const program = process.argv.includes(describeFlag2) ? describe(config) : host(config);
955
+ BunRuntime.runMain(program.pipe(Effect4.flatMap((code) => Effect4.sync(() => process.exit(code)))));
956
+ };
957
+
958
+ export { RunnerRpcProtocolVersion, JournalWriteFailed2, refusedStep2, runProgram2, programLease2, rpcProgramJournal2, describeFlag2, Described2, programSecrets2, runPackage2 };