@kici-dev/engine 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -6
  3. package/dist/audit/access-log-policy.d.ts +97 -0
  4. package/dist/audit/access-log-policy.js +195 -0
  5. package/dist/audit/activity.d.ts +156 -0
  6. package/dist/audit/activity.js +175 -0
  7. package/dist/audit/retention-policy.d.ts +157 -0
  8. package/dist/audit/retention-policy.js +364 -0
  9. package/dist/bundler/index.d.ts +3 -0
  10. package/dist/bundler/index.js +3 -0
  11. package/dist/bundler/rolldown-config.d.ts +41 -0
  12. package/dist/bundler/rolldown-config.js +40 -0
  13. package/dist/chunk-gOLHoazu.js +4 -0
  14. package/dist/env/environment-allowlist.d.ts +45 -0
  15. package/dist/env/environment-allowlist.js +69 -0
  16. package/dist/environment/index.d.ts +3 -0
  17. package/dist/environment/index.js +3 -0
  18. package/dist/environment/scope-resolver.d.ts +35 -0
  19. package/dist/environment/scope-resolver.js +77 -0
  20. package/dist/environment/types.d.ts +98 -0
  21. package/dist/environment/types.js +2 -0
  22. package/dist/index.d.ts +54 -0
  23. package/dist/index.js +45 -0
  24. package/dist/labels.d.ts +106 -0
  25. package/dist/labels.js +162 -0
  26. package/dist/metrics/metric-catalog.generated.d.ts +400 -0
  27. package/dist/metrics/metric-catalog.generated.js +510 -0
  28. package/dist/protocol/dashboard-global-workflows.d.ts +9 -0
  29. package/dist/protocol/dashboard-global-workflows.js +3 -0
  30. package/dist/protocol/event-log-payload.d.ts +16 -0
  31. package/dist/protocol/event-log-payload.js +21 -0
  32. package/dist/protocol/messages/access-log.d.ts +545 -0
  33. package/dist/protocol/messages/access-log.js +175 -0
  34. package/dist/protocol/messages/actor.d.ts +100 -0
  35. package/dist/protocol/messages/actor.js +139 -0
  36. package/dist/protocol/messages/auth.d.ts +25 -0
  37. package/dist/protocol/messages/auth.js +36 -0
  38. package/dist/protocol/messages/browser.d.ts +369 -0
  39. package/dist/protocol/messages/browser.js +225 -0
  40. package/dist/protocol/messages/capabilities.d.ts +46 -0
  41. package/dist/protocol/messages/capabilities.js +42 -0
  42. package/dist/protocol/messages/common.d.ts +53 -0
  43. package/dist/protocol/messages/common.js +55 -0
  44. package/dist/protocol/messages/dashboard-global-workflows.d.ts +166 -0
  45. package/dist/protocol/messages/dashboard-global-workflows.js +80 -0
  46. package/dist/protocol/messages/dashboard.d.ts +4068 -0
  47. package/dist/protocol/messages/dashboard.js +1237 -0
  48. package/dist/protocol/messages/event-log.d.ts +49 -0
  49. package/dist/protocol/messages/event-log.js +45 -0
  50. package/dist/protocol/messages/execution-status.d.ts +164 -0
  51. package/dist/protocol/messages/execution-status.js +166 -0
  52. package/dist/protocol/messages/join.d.ts +18 -0
  53. package/dist/protocol/messages/join.js +28 -0
  54. package/dist/protocol/messages/log-pull.d.ts +27 -0
  55. package/dist/protocol/messages/log-pull.js +36 -0
  56. package/dist/protocol/messages/observe.d.ts +75 -0
  57. package/dist/protocol/messages/observe.js +70 -0
  58. package/dist/protocol/messages/orchestrator-agent.d.ts +606 -0
  59. package/dist/protocol/messages/orchestrator-agent.js +481 -0
  60. package/dist/protocol/messages/peer.d.ts +795 -0
  61. package/dist/protocol/messages/peer.js +372 -0
  62. package/dist/protocol/messages/platform-orchestrator.d.ts +1888 -0
  63. package/dist/protocol/messages/platform-orchestrator.js +379 -0
  64. package/dist/protocol/messages/run-events.d.ts +155 -0
  65. package/dist/protocol/messages/run-events.js +115 -0
  66. package/dist/protocol/messages/saas-orchestrator.d.ts +2179 -0
  67. package/dist/protocol/messages/source-registration.d.ts +103 -0
  68. package/dist/protocol/messages/source-registration.js +109 -0
  69. package/dist/protocol/messages/test-run.d.ts +59 -0
  70. package/dist/protocol/messages/test-run.js +52 -0
  71. package/dist/protocol/version.d.ts +12 -0
  72. package/dist/protocol/version.js +17 -0
  73. package/dist/provider/changed-files-fetcher.d.ts +24 -0
  74. package/dist/provider/changed-files-fetcher.js +2 -0
  75. package/dist/provider/check-run-conclusion.d.ts +15 -0
  76. package/dist/provider/check-run-conclusion.js +19 -0
  77. package/dist/provider/check-status-poster.d.ts +15 -0
  78. package/dist/provider/check-status-poster.js +2 -0
  79. package/dist/provider/clone-token-provider.d.ts +58 -0
  80. package/dist/provider/clone-token-provider.js +2 -0
  81. package/dist/provider/contributor-resolver.d.ts +22 -0
  82. package/dist/provider/contributor-resolver.js +2 -0
  83. package/dist/provider/index.d.ts +23 -0
  84. package/dist/provider/index.js +3 -0
  85. package/dist/provider/lock-file-fetcher.d.ts +24 -0
  86. package/dist/provider/lock-file-fetcher.js +2 -0
  87. package/dist/provider/repo-url-builder.d.ts +35 -0
  88. package/dist/provider/repo-url-builder.js +2 -0
  89. package/dist/provider/types.d.ts +9 -0
  90. package/dist/provider/types.js +2 -0
  91. package/dist/provider/webhook-normalizer.d.ts +163 -0
  92. package/dist/provider/webhook-normalizer.js +2 -0
  93. package/dist/registration/registerable-trigger-type.d.ts +52 -0
  94. package/dist/registration/registerable-trigger-type.js +56 -0
  95. package/dist/scaler/resource-types.d.ts +90 -0
  96. package/dist/scaler/resource-types.js +99 -0
  97. package/dist/scaler/scaler-backend-type.d.ts +16 -0
  98. package/dist/scaler/scaler-backend-type.js +20 -0
  99. package/dist/secrets/index.d.ts +7 -0
  100. package/dist/secrets/index.js +2 -0
  101. package/dist/secrets/types.d.ts +138 -0
  102. package/dist/secrets/types.js +2 -0
  103. package/dist/state-machine/index.d.ts +2 -0
  104. package/dist/state-machine/index.js +3 -0
  105. package/dist/state-machine/machine.d.ts +34 -0
  106. package/dist/state-machine/machine.js +103 -0
  107. package/dist/state-machine/types.d.ts +34 -0
  108. package/dist/state-machine/types.js +15 -0
  109. package/dist/trigger/decision-trace.d.ts +41 -0
  110. package/dist/trigger/decision-trace.js +30 -0
  111. package/dist/trigger/jsonpath-matcher.d.ts +27 -0
  112. package/dist/trigger/jsonpath-matcher.js +92 -0
  113. package/dist/trigger/matcher.d.ts +29 -0
  114. package/dist/trigger/matcher.js +704 -0
  115. package/dist/trigger/trigger-event-type.d.ts +14 -0
  116. package/dist/trigger/trigger-event-type.js +66 -0
  117. package/dist/trigger/types.d.ts +524 -0
  118. package/dist/trigger/types.js +48 -0
  119. package/dist/webhook/signature.d.ts +15 -0
  120. package/dist/webhook/signature.js +32 -0
  121. package/dist/ws/close-codes.d.ts +28 -0
  122. package/dist/ws/close-codes.js +33 -0
  123. package/dist/ws/rate-limiter.d.ts +86 -0
  124. package/dist/ws/rate-limiter.js +136 -0
  125. package/dist/ws/ws-like.d.ts +12 -0
  126. package/dist/ws/ws-like.js +2 -0
  127. package/package.json +54 -6
  128. package/sbom.spdx.json +202 -0
  129. package/index.js +0 -3
@@ -0,0 +1,481 @@
1
+ import "../../chunk-gOLHoazu.js";
2
+ import { ExecutionJobStatus, ExecutionStepStatus } from "./execution-status.js";
3
+ import { z } from "zod";
4
+ //#region src/protocol/messages/orchestrator-agent.ts
5
+ /**
6
+ * Structured git-clone auth material. Carries everything the agent needs to
7
+ * authenticate a single `git clone`:
8
+ *
9
+ * - `kind: 'basic'` — HTTPS Basic auth (PAT / password). `secret` is the
10
+ * token, `user` is the Basic-auth username (defaults filled in by the
11
+ * provider, e.g. `x-access-token` for GitHub-style PATs).
12
+ * - `kind: 'ssh'` — SSH key auth. `secret` is the PEM-encoded private key.
13
+ * `sshHostKeyPolicy` + `sshKnownHostsPem` drive StrictHostKeyChecking.
14
+ *
15
+ * Used by `sourceAuth` and `workflowAuth` on `jobDispatchSchema` so a single
16
+ * global-workflow dispatch can carry two different credentials (one per
17
+ * clone target — required for cross-provider global workflows).
18
+ */
19
+ const gitAuthSchema = z.object({
20
+ kind: z.enum(["basic", "ssh"]),
21
+ /** Basic-auth username. Omit for SSH. */
22
+ user: z.string().optional(),
23
+ /** Basic-auth password/PAT, or PEM-encoded SSH private key. */
24
+ secret: z.string(),
25
+ /** SSH-only. `accept-new` trusts first seen host keys; `pinned` requires `sshKnownHostsPem`. */
26
+ sshHostKeyPolicy: z.enum(["accept-new", "pinned"]).optional(),
27
+ /** SSH-only, required when `sshHostKeyPolicy === 'pinned'`. OpenSSH known_hosts content. */
28
+ sshKnownHostsPem: z.string().optional()
29
+ }).superRefine((val, ctx) => {
30
+ if (val.kind === "ssh" && val.sshHostKeyPolicy === "pinned" && !val.sshKnownHostsPem) ctx.addIssue({
31
+ code: z.ZodIssueCode.custom,
32
+ path: ["sshKnownHostsPem"],
33
+ message: "sshKnownHostsPem is required when sshHostKeyPolicy is \"pinned\""
34
+ });
35
+ });
36
+ /** Dispatch a job to an agent for execution. */
37
+ const jobDispatchSchema = z.object({
38
+ type: z.literal("job.dispatch"),
39
+ messageId: z.string(),
40
+ runId: z.string(),
41
+ jobId: z.string(),
42
+ repoUrl: z.string(),
43
+ ref: z.string(),
44
+ sha: z.string(),
45
+ lockFileUrl: z.string(),
46
+ /** Pass-through job configuration. Shape is `LockJob | LockDynamicJobFn` from the lock file. */
47
+ jobConfig: z.record(z.string(), z.unknown()).describe("Job configuration from the lock file (LockJob | LockDynamicJobFn)"),
48
+ timestamp: z.number(),
49
+ /** Short-lived GitHub installation token for private repo clone auth. */
50
+ token: z.string().optional(),
51
+ /** Orchestrator-provided secrets to merge into step environment. */
52
+ secrets: z.record(z.string(), z.string()).optional(),
53
+ /** Namespaced secrets by context name: { 'context-name': { KEY: 'value' } } */
54
+ namespacedSecrets: z.record(z.string(), z.record(z.string(), z.string())).optional(),
55
+ /** Max log size per step in bytes. Agent falls back to its own config default (10MB). */
56
+ maxLogSizeBytes: z.coerce.number().optional(),
57
+ /** URL or file:// path to a pre-packed `.kici/` source tarball. If present, agent extracts it into workDir instead of cloning the repo. */
58
+ sourceTarUrl: z.string().optional(),
59
+ /** SHA-256 hash of the source tarball bytes for integrity verification on download. */
60
+ sourceTarHash: z.string().optional(),
61
+ /** URL or file:// path to pre-built dependency tarball. If present, agent extracts to .kici/node_modules/ instead of running install. */
62
+ depsUrl: z.string().optional(),
63
+ /** SHA-256 hash of the dependency tarball for integrity verification. */
64
+ depsHash: z.string().optional(),
65
+ /** Trace ID propagated across tiers for distributed tracing. */
66
+ requestId: z.string().optional(),
67
+ /** Base64-encoded X25519 public key for the workflow run (for encrypting secret outputs). */
68
+ runPublicKey: z.string().optional(),
69
+ /** Plain outputs from upstream jobs (keyed by job name, then by step name). Populated for downstream jobs with `needs` dependencies. */
70
+ upstreamJobOutputs: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),
71
+ /**
72
+ * Structured clone auth for the source repo. Preferred over `token` (which
73
+ * remains as a backward-compat field for same-provider GitHub App flows
74
+ * during the transition to universal-git / cross-provider global workflows).
75
+ *
76
+ * When both `token` and `sourceAuth` are set, a Zod refinement enforces
77
+ * that they agree (`sourceAuth.kind === 'basic'` and
78
+ * `sourceAuth.secret === token`) — otherwise the dispatch is rejected to
79
+ * prevent silent credential mismatches.
80
+ */
81
+ sourceAuth: gitAuthSchema.optional(),
82
+ /**
83
+ * Structured clone auth for the **workflow** repo in a global-workflow
84
+ * dispatch (when the workflow is authored on a different source than the
85
+ * source repo). When `jobConfig.isGlobalWorkflow === true` and the two
86
+ * providers differ, the orchestrator populates `sourceAuth` from the
87
+ * inbound bundle and `workflowAuth` from the registration's bundle.
88
+ *
89
+ * For same-provider global workflows this is typically absent and the
90
+ * agent reuses `sourceAuth` for both clones.
91
+ */
92
+ workflowAuth: gitAuthSchema.optional(),
93
+ /**
94
+ * Private npm registries the agent should authenticate against before
95
+ * `npm install`. Each entry's `token` is the resolved value (the
96
+ * orchestrator already looked it up via the per-environment
97
+ * secretResolver path; protection-rule gates have already passed at this
98
+ * point). Untrusted contributors get an empty list.
99
+ */
100
+ npmRegistries: z.array(z.object({
101
+ url: z.string().url(),
102
+ scope: z.string().optional(),
103
+ alwaysAuth: z.boolean(),
104
+ token: z.string().min(1)
105
+ })).optional(),
106
+ /**
107
+ * Extra resolved secrets to project as env vars on the install
108
+ * subprocess. Keyed by the bare secret name (the qualified env: prefix
109
+ * is stripped at resolution time). For use with a customer-committed
110
+ * `.kici/.npmrc` containing `${VAR}` placeholders.
111
+ */
112
+ installEnvSecrets: z.record(z.string(), z.string()).optional()
113
+ }).superRefine((val, ctx) => {
114
+ if (val.token && val.sourceAuth) {
115
+ if (val.sourceAuth.kind !== "basic") ctx.addIssue({
116
+ code: z.ZodIssueCode.custom,
117
+ path: ["sourceAuth", "kind"],
118
+ message: "token is set; sourceAuth.kind must be \"basic\" to agree"
119
+ });
120
+ else if (val.sourceAuth.secret !== val.token) ctx.addIssue({
121
+ code: z.ZodIssueCode.custom,
122
+ path: ["sourceAuth", "secret"],
123
+ message: "token and sourceAuth.secret must match when both are set"
124
+ });
125
+ }
126
+ });
127
+ /** Cancel a running or queued job. */
128
+ const jobCancelSchema = z.object({
129
+ type: z.literal("job.cancel"),
130
+ messageId: z.string(),
131
+ runId: z.string(),
132
+ jobId: z.string(),
133
+ reason: z.string(),
134
+ /** When true, force-cancel immediately without waiting for hooks. */
135
+ force: z.boolean().optional()
136
+ });
137
+ /** Acknowledge agent registration with orchestrator-assigned settings. */
138
+ const registerAckSchema = z.object({
139
+ type: z.literal("register.ack"),
140
+ agentId: z.string(),
141
+ labels: z.array(z.string()),
142
+ scalerManaged: z.boolean().default(false),
143
+ /**
144
+ * Set when the orchestrator's scaler bound a specific queued job to this
145
+ * agent at spawn time and is preparing the dispatch.job message right now.
146
+ * Scaler-managed agents that see this flag MUST NOT arm the short
147
+ * KICI_SCALER_IDLE_TIMEOUT timer on register — the dispatch is in flight
148
+ * and may take a few seconds to arrive (provider lookup, secret merging,
149
+ * upstream output fetching all happen between register.ack and dispatch.job
150
+ * for jobs with `needs:` dependencies). Without this flag the agent races
151
+ * the orchestrator and self-shuts down before the dispatch arrives.
152
+ * If the dispatch never arrives (orchestrator crash, etc.) the agent's
153
+ * KICI_SCALER_PENDING_DISPATCH_TIMEOUT (default 60s) acts as a safety net.
154
+ */
155
+ pendingDispatch: z.boolean().optional()
156
+ });
157
+ /** Agent registration with capabilities and capacity. */
158
+ const agentRegisterSchema = z.object({
159
+ type: z.literal("agent.register"),
160
+ messageId: z.string(),
161
+ agentId: z.string(),
162
+ labels: z.array(z.string()),
163
+ /** Agent platform (os.platform(), e.g. 'linux', 'darwin', 'win32') */
164
+ platform: z.string().optional(),
165
+ /** Agent architecture (os.arch(), e.g. 'x64', 'arm64') */
166
+ arch: z.string().optional(),
167
+ /** Agent version (e.g. "0.0.1"). Optional for backward compatibility with older agents. */
168
+ version: z.string().optional(),
169
+ /** Maximum concurrent jobs this agent can handle. Defaults to 1 if not specified. */
170
+ maxConcurrency: z.number().int().positive().optional(),
171
+ /** Jobs still running on this agent (sent on reconnection to enable job recovery). */
172
+ inFlightJobs: z.array(z.object({
173
+ jobId: z.string(),
174
+ runId: z.string()
175
+ })).optional(),
176
+ /** Machine hostname (os.hostname()) */
177
+ hostname: z.string().optional(),
178
+ /** OS kernel release (os.release()) */
179
+ osRelease: z.string().optional(),
180
+ /** OS version string (os.version()) */
181
+ osVersion: z.string().optional(),
182
+ /** Total system memory in MiB */
183
+ totalMemoryMb: z.number().optional(),
184
+ /** Number of logical CPUs */
185
+ cpuCount: z.number().optional(),
186
+ /** Node.js version (process.versions.node) */
187
+ nodeVersion: z.string().optional(),
188
+ /** Username of the OS user running the agent process */
189
+ runningAsUser: z.string().optional(),
190
+ /** UID of the OS user running the agent process */
191
+ runningAsUid: z.number().optional()
192
+ });
193
+ /** Periodic agent status update. */
194
+ const agentStatusSchema = z.object({
195
+ type: z.literal("agent.status"),
196
+ messageId: z.string(),
197
+ agentId: z.string(),
198
+ activeJobs: z.number(),
199
+ /** Used memory in MiB (os.totalmem() - os.freemem()) */
200
+ memoryUsedMb: z.number().optional(),
201
+ /** Available memory in MiB (os.freemem()) */
202
+ memoryAvailableMb: z.number().optional(),
203
+ /** System uptime in seconds (os.uptime()) */
204
+ uptimeSeconds: z.number().optional()
205
+ });
206
+ /** Job execution state transition report. */
207
+ const jobStatusSchema = z.object({
208
+ type: z.literal("job.status"),
209
+ messageId: z.string(),
210
+ runId: z.string(),
211
+ jobId: z.string(),
212
+ state: ExecutionJobStatus,
213
+ timestamp: z.number(),
214
+ data: z.record(z.string(), z.unknown()).optional(),
215
+ /** Job names dropped by determinism drift (agent re-eval produced fewer jobs than expected). */
216
+ droppedJobs: z.array(z.string()).optional(),
217
+ /** Encrypted secret outputs from agent (present on job success when secret outputs exist). */
218
+ secretOutputs: z.record(z.string(), z.object({
219
+ /** Base64-encoded agent ephemeral X25519 public key (DER SPKI). */
220
+ agentPublicKey: z.string(),
221
+ /** Base64-encoded encrypted value: IV (12B) || AuthTag (16B) || Ciphertext. */
222
+ encrypted: z.string()
223
+ })).optional()
224
+ });
225
+ /**
226
+ * Streaming log chunk from step execution (agent -> orchestrator).
227
+ *
228
+ * FAST-PATHED: A manual validator exists in
229
+ * packages/orchestrator/src/ws/agent-handler.ts (isValidLogChunk).
230
+ * If you change this schema, update the manual validator in the same commit.
231
+ * See CLAUDE.md rule: "Zod fast-path sync invariant".
232
+ */
233
+ const agentLogChunkSchema = z.object({
234
+ type: z.literal("log.chunk"),
235
+ messageId: z.string(),
236
+ runId: z.string(),
237
+ jobId: z.string(),
238
+ stepIndex: z.number(),
239
+ lines: z.array(z.string()),
240
+ timestamp: z.number()
241
+ });
242
+ /** Step-level execution state report (agent -> orchestrator). */
243
+ const agentStepStatusSchema = z.object({
244
+ type: z.literal("step.status"),
245
+ messageId: z.string(),
246
+ runId: z.string(),
247
+ jobId: z.string(),
248
+ stepIndex: z.number().int().nonnegative(),
249
+ stepName: z.string(),
250
+ state: ExecutionStepStatus,
251
+ timestamp: z.number(),
252
+ data: z.record(z.string(), z.unknown()).optional(),
253
+ /** Distinguishes regular steps from hook executions. */
254
+ step_type: z.enum([
255
+ "step",
256
+ "hook:onCancel",
257
+ "hook:cleanup",
258
+ "hook:onSuccess",
259
+ "hook:onFailure",
260
+ "hook:beforeStep",
261
+ "hook:afterStep"
262
+ ]).optional(),
263
+ /** Secret key names accessed by this step via ctx.secrets.get()/expose(). Never contains values. */
264
+ secretsAccessed: z.array(z.string()).optional(),
265
+ /**
266
+ * Total raw bytes streamed by this step's LogStreamer at terminal time.
267
+ * Counts agent-side raw bytes (the same count fed to the transient
268
+ * `kici_agent_log_bytes_total` counter), so it reflects what the customer
269
+ * actually emitted — not gzip archive size or post-processing size.
270
+ * Set on terminal step states only. Reused by the orchestrator to
271
+ * accumulate per-job and per-run totals for the operator-side
272
+ * `kici_org_log_bytes` capacity-planning gauge.
273
+ */
274
+ logBytesStreamed: z.number().int().nonnegative().optional()
275
+ });
276
+ /** Periodic job heartbeat from agent to orchestrator (stale run detection). */
277
+ const jobHeartbeatSchema = z.object({
278
+ type: z.literal("job.heartbeat"),
279
+ runId: z.string(),
280
+ jobId: z.string(),
281
+ timestamp: z.number()
282
+ });
283
+ /** Operational log lines streamed from agent to orchestrator (stateful/external agents). */
284
+ const agentLogSchema = z.object({
285
+ type: z.literal("agent.log"),
286
+ messageId: z.string(),
287
+ agentId: z.string(),
288
+ lines: z.array(z.string()),
289
+ timestamp: z.number()
290
+ });
291
+ /** Agent -> Orchestrator: report that a job belongs to a concurrency group. */
292
+ const jobConcurrencyReportSchema = z.object({
293
+ type: z.literal("job.concurrency.report"),
294
+ messageId: z.string(),
295
+ runId: z.string(),
296
+ jobId: z.string(),
297
+ group: z.string()
298
+ });
299
+ /**
300
+ * Orchestrator -> Agent: acknowledge concurrency report with action to take.
301
+ *
302
+ * The orchestrator sends this in two situations:
303
+ * 1. As a direct response to a `job.concurrency.report` message — `requestId`
304
+ * correlates to the report. Action is `proceed`, `wait`, or `cancel`.
305
+ * 2. As an UNSOLICITED follow-up after the agent received `wait`. When a slot
306
+ * in the concurrency group is released (by completion, cancellation, or
307
+ * superseding), the orchestrator picks the FIFO-next queued waiter and
308
+ * sends `{ action: 'proceed' }` to the agent that's still parked on its
309
+ * second `waitForConcurrencyAck` call. `runId` / `jobId` are present in
310
+ * this case so the agent can sanity-check the wake-up matches its job.
311
+ * The agent's pending-ack slot resolves regardless of `requestId` (single
312
+ * in-flight ack per workflow-runner process).
313
+ */
314
+ const jobConcurrencyAckSchema = z.object({
315
+ type: z.literal("job.concurrency.ack"),
316
+ requestId: z.string(),
317
+ action: z.enum([
318
+ "proceed",
319
+ "wait",
320
+ "cancel"
321
+ ]),
322
+ reason: z.string().optional(),
323
+ /** Optional run identifier for unsolicited slot-release wake-ups. */
324
+ runId: z.string().optional(),
325
+ /** Optional job identifier for unsolicited slot-release wake-ups. */
326
+ jobId: z.string().optional()
327
+ });
328
+ /** Agent acknowledges receipt of configuration (e.g., MMDS handshake). */
329
+ const configAckSchema = z.object({
330
+ type: z.literal("config.ack"),
331
+ messageId: z.string(),
332
+ agentId: z.string()
333
+ });
334
+ /** Agent -> Orchestrator: request a pre-signed upload URL for cache storage. */
335
+ const cacheUploadRequestSchema = z.object({
336
+ type: z.literal("cache.upload.request"),
337
+ messageId: z.string(),
338
+ jobId: z.string(),
339
+ cacheType: z.enum(["source", "deps"]),
340
+ contentHash: z.string().optional(),
341
+ lockfileHash: z.string().optional(),
342
+ platform: z.string(),
343
+ arch: z.string()
344
+ });
345
+ /** Orchestrator -> Agent: return the pre-signed upload URL. */
346
+ const cacheUploadResponseSchema = z.object({
347
+ type: z.literal("cache.upload.response"),
348
+ requestId: z.string(),
349
+ uploadUrl: z.string()
350
+ });
351
+ /** Agent -> Orchestrator: confirm upload complete (for metadata update). */
352
+ const cacheUploadCompleteSchema = z.object({
353
+ type: z.literal("cache.upload.complete"),
354
+ messageId: z.string(),
355
+ jobId: z.string(),
356
+ cacheType: z.enum(["source", "deps"]),
357
+ contentHash: z.string().optional(),
358
+ lockfileHash: z.string().optional(),
359
+ platform: z.string(),
360
+ arch: z.string(),
361
+ /** SHA-256 hash of the dependency tarball for integrity verification. Only present for deps uploads. */
362
+ depsHash: z.string().optional()
363
+ });
364
+ /** Agent -> Orchestrator: emit a custom event from a running workflow step. */
365
+ const eventEmitSchema = z.object({
366
+ type: z.literal("event.emit"),
367
+ /** Job that is emitting the event. */
368
+ jobId: z.string(),
369
+ /** Correlates to the runner's request for response routing. */
370
+ requestId: z.string(),
371
+ /** Custom event name (e.g. 'deploy-complete'). */
372
+ eventName: z.string(),
373
+ /** Event payload (arbitrary JSON-serializable data). */
374
+ payload: z.record(z.string(), z.unknown()),
375
+ /** Optional targeting for cross-repo delivery. */
376
+ target: z.object({ repos: z.array(z.string()).optional() }).optional()
377
+ });
378
+ /** Orchestrator -> Agent: response confirming event delivery. */
379
+ const eventEmitResponseSchema = z.object({
380
+ type: z.literal("event.emit.response"),
381
+ /** Correlates to the original event.emit requestId. */
382
+ requestId: z.string(),
383
+ /** Delivery ID assigned by the orchestrator (present on success). */
384
+ deliveryId: z.string().optional(),
385
+ /** Error description (present on failure). */
386
+ error: z.string().optional()
387
+ });
388
+ /** Periodic metrics push from agent to orchestrator. */
389
+ const agentMetricsSchema = z.object({
390
+ type: z.literal("agent.metrics"),
391
+ messageId: z.string(),
392
+ agentId: z.string(),
393
+ metrics: z.array(z.object({
394
+ name: z.string(),
395
+ type: z.enum([
396
+ "counter",
397
+ "histogram",
398
+ "gauge",
399
+ "upDownCounter"
400
+ ]),
401
+ value: z.number().optional(),
402
+ labels: z.record(z.string(), z.string()).optional(),
403
+ buckets: z.array(z.object({
404
+ le: z.number(),
405
+ count: z.number()
406
+ })).optional(),
407
+ count: z.number().optional(),
408
+ sum: z.number().optional()
409
+ })),
410
+ timestamp: z.number()
411
+ });
412
+ /** Auth request sent by agent to orchestrator when connecting via WebSocket. */
413
+ const agentAuthRequestSchema = z.object({
414
+ type: z.literal("auth.request"),
415
+ token: z.string().min(1),
416
+ protocolVersion: z.number().int().positive()
417
+ });
418
+ /** Auth success response sent by orchestrator to agent after successful authentication. */
419
+ const agentAuthSuccessSchema = z.object({
420
+ type: z.literal("auth.success"),
421
+ connectionId: z.string()
422
+ });
423
+ /** Auth failure response sent by orchestrator to agent when authentication fails. */
424
+ const agentAuthFailureSchema = z.object({
425
+ type: z.literal("auth.failure"),
426
+ reason: z.string()
427
+ });
428
+ /** API request sent by agent to orchestrator (e.g., infrastructure.list). */
429
+ const agentApiRequestSchema = z.object({
430
+ type: z.literal("agent.api.request"),
431
+ /** UUID for correlating the response. */
432
+ requestId: z.string(),
433
+ /** Dot-namespaced method name (e.g., 'infrastructure.list'). */
434
+ method: z.string(),
435
+ /** Method-specific parameters. */
436
+ params: z.record(z.string(), z.unknown()).default({})
437
+ });
438
+ /** API response sent by orchestrator to agent. */
439
+ const agentApiResponseSchema = z.object({
440
+ type: z.literal("agent.api.response"),
441
+ /** Matches the original request's requestId. */
442
+ requestId: z.string(),
443
+ /** Method result (present on success). */
444
+ result: z.unknown().optional(),
445
+ /** Error description (present on failure). */
446
+ error: z.string().optional()
447
+ });
448
+ /** All messages that flow from Orchestrator to Agent. */
449
+ const orchestratorToAgentMessageSchema = z.discriminatedUnion("type", [
450
+ jobDispatchSchema,
451
+ jobCancelSchema,
452
+ registerAckSchema,
453
+ jobConcurrencyAckSchema,
454
+ cacheUploadResponseSchema,
455
+ eventEmitResponseSchema,
456
+ agentApiResponseSchema,
457
+ agentAuthSuccessSchema,
458
+ agentAuthFailureSchema
459
+ ]);
460
+ /** All messages that flow from Agent to Orchestrator. */
461
+ const agentToOrchestratorMessageSchema = z.discriminatedUnion("type", [
462
+ agentRegisterSchema,
463
+ agentStatusSchema,
464
+ jobStatusSchema,
465
+ agentLogChunkSchema,
466
+ agentStepStatusSchema,
467
+ jobHeartbeatSchema,
468
+ agentLogSchema,
469
+ jobConcurrencyReportSchema,
470
+ configAckSchema,
471
+ cacheUploadRequestSchema,
472
+ cacheUploadCompleteSchema,
473
+ eventEmitSchema,
474
+ agentApiRequestSchema,
475
+ agentMetricsSchema,
476
+ agentAuthRequestSchema
477
+ ]);
478
+ //#endregion
479
+ export { agentApiRequestSchema, agentApiResponseSchema, agentAuthFailureSchema, agentAuthRequestSchema, agentAuthSuccessSchema, agentLogChunkSchema, agentMetricsSchema, agentRegisterSchema, agentStatusSchema, agentStepStatusSchema, agentToOrchestratorMessageSchema, configAckSchema, eventEmitResponseSchema, eventEmitSchema, gitAuthSchema, jobCancelSchema, jobConcurrencyAckSchema, jobConcurrencyReportSchema, jobDispatchSchema, jobStatusSchema, orchestratorToAgentMessageSchema, registerAckSchema };
480
+
481
+ //# sourceMappingURL=orchestrator-agent.js.map