@soiljs/cloud 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,837 @@
1
+ import { randomUUID, createHash } from 'crypto';
2
+ import { gzipSync } from 'zlib';
3
+ import { resolve, join } from 'path';
4
+ import { mkdir, readFile, open, rename, rm } from 'fs/promises';
5
+
6
+ // src/index.ts
7
+
8
+ // ../cloud-protocol/src/index.ts
9
+ var PROTOCOL_VERSION = "1";
10
+ var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ var text = (v) => typeof v === "string" && v.length > 0;
12
+ var integer = (v) => Number.isSafeInteger(v) && v >= 0;
13
+ var date = (v) => text(v) && Number.isFinite(Date.parse(v));
14
+ var oneOf = (v, values) => typeof v === "string" && values.includes(v);
15
+ var optional = (v, key, check) => v[key] === void 0 || check(v[key]);
16
+ var scope = (v) => object(v) && optional(v, "tenantId", text) && optional(v, "projectId", text);
17
+ var capabilities = (v) => object(v) && ["allowRemoteApproval", "allowRemoteCancel", "allowRemoteSteer", "allowRemoteResume"].every(
18
+ (k) => typeof v[k] === "boolean"
19
+ );
20
+ var manifest = (v) => object(v) && text(v.agentId) && text(v.version) && text(v.configHash) && Array.isArray(v.tools) && v.tools.every(text);
21
+ var correlation = (v, sessionOnly = false) => text(v.sessionId) && ["rootTurnId", "turnId", "traceId", "spanId"].every(
22
+ (k) => sessionOnly ? typeof v[k] === "string" : text(v[k])
23
+ ) && optional(v, "scope", scope) && ["parentTurnId", "stepId", "parentSpanId"].every((k) => optional(v, k, text)) && optional(v, "attemptNo", integer);
24
+ function isCommandPayload(v) {
25
+ if (!object(v) || !text(v.turnId)) return false;
26
+ const bool = (x) => typeof x === "boolean";
27
+ switch (v.kind) {
28
+ case "approve":
29
+ return text(v.approvalId) && oneOf(v.decision, ["approved", "rejected"]) && optional(v, "reason", text);
30
+ case "cancel":
31
+ return optional(v, "reason", text) && optional(v, "drainQueued", (x) => oneOf(x, ["keep", "cancel"]));
32
+ case "resume":
33
+ return true;
34
+ case "steer":
35
+ return text(v.input) && optional(v, "urgency", (x) => oneOf(x, ["next_iteration", "interrupt"])) && ["fallbackToNewTurn", "supersedeApprovals"].every((k) => optional(v, k, bool));
36
+ case "resolve_unknown": {
37
+ const r = v.resolution;
38
+ return text(v.stepId) && object(r) && (r.kind === "confirmed_completed" && Object.hasOwn(r, "output") || r.kind === "confirmed_not_executed" && bool(r.retry) || r.kind === "marked_failed" && text(r.reason));
39
+ }
40
+ default:
41
+ return false;
42
+ }
43
+ }
44
+ function isCommandEnvelope(v) {
45
+ return object(v) && text(v.commandId) && date(v.issuedAt) && optional(v, "scope", scope) && object(v.actor) && text(v.actor.id) && optional(v.actor, "role", text) && oneOf(v.actor.source, ["local_api", "cloud_console", "system"]) && isCommandPayload(v.payload);
46
+ }
47
+ function isCommandReceipt(v) {
48
+ return object(v) && text(v.commandId) && date(v.processedAt) && oneOf(v.status, ["applied", "duplicate", "rejected"]) && optional(v, "resultTurnId", text) && optional(
49
+ v,
50
+ "rejectionReason",
51
+ (x) => oneOf(x, [
52
+ "unauthorized",
53
+ "scope_mismatch",
54
+ "not_found",
55
+ "invalid_state",
56
+ "turn_already_terminal"
57
+ ])
58
+ ) && (v.status !== "rejected" || text(v.rejectionReason));
59
+ }
60
+ function isRealtimeEvent(v) {
61
+ return object(v) && correlation(v) && oneOf(v.type, ["text.delta", "reasoning.delta", "tool.call.delta", "tool.progress"]) && date(v.occurredAt) && v.seq === void 0 && v.eventId === void 0 && optional(v, "delta", (x) => typeof x === "string") && optional(v, "message", (x) => typeof x === "string") && optional(v, "data", object);
62
+ }
63
+ function isConfigSnapshot(v) {
64
+ return object(v) && ["agentId", "version", "configHash", "signature"].every((k) => text(v[k])) && date(v.issuedAt) && object(v.values);
65
+ }
66
+ function isWssFrame(v) {
67
+ if (!object(v)) return false;
68
+ switch (v.type) {
69
+ case "runtime.hello":
70
+ return v.protocolVersion === PROTOCOL_VERSION && ["token", "runtimeId", "runtimeName", "storageKind"].every((k) => text(v[k])) && Array.isArray(v.agents) && v.agents.every(manifest) && capabilities(v.capabilities);
71
+ case "runtime.hello_ack":
72
+ return v.protocolVersion === PROTOCOL_VERSION;
73
+ case "ping":
74
+ return date(v.timestamp) && integer(v.activeTurns) && integer(v.outboxDepth);
75
+ case "pong":
76
+ return date(v.timestamp);
77
+ case "watch.start":
78
+ case "watch.stop":
79
+ return text(v.turnId);
80
+ case "realtime.event":
81
+ return text(v.runtimeId) && isRealtimeEvent(v.event);
82
+ case "command.deliver":
83
+ return isCommandEnvelope(v.envelope) && v.envelope.actor.source === "cloud_console" && oneOf(v.deliveryMode, ["require_online", "queue_until_online"]) && date(v.expiresAt);
84
+ case "command.ack":
85
+ return text(v.commandId) && v.stage === "received_by_runtime";
86
+ case "command.receipt":
87
+ return isCommandReceipt(v.receipt);
88
+ case "command.receipt_ack":
89
+ return text(v.commandId);
90
+ case "commands.pull_pending":
91
+ return text(v.runtimeId);
92
+ case "config.snapshot":
93
+ return isConfigSnapshot(v.snapshot);
94
+ default:
95
+ return false;
96
+ }
97
+ }
98
+ function parseWssFrame(json) {
99
+ const value = JSON.parse(json);
100
+ if (!isWssFrame(value)) throw new TypeError("Invalid cloud protocol frame");
101
+ return value;
102
+ }
103
+ function isIngestEventsResponse(v) {
104
+ return object(v) && integer(v.ackedUpToSeq);
105
+ }
106
+ function isArtifactRef(v) {
107
+ return object(v) && text(v.uri) && typeof v.sha256 === "string" && /^[a-f0-9]{64}$/.test(v.sha256) && integer(v.byteSize) && text(v.contentType);
108
+ }
109
+ function isIngestArtifactsResponse(v) {
110
+ return object(v) && typeof v.sha256 === "string" && /^[a-f0-9]{64}$/.test(v.sha256);
111
+ }
112
+
113
+ // src/redaction.ts
114
+ var secretKey = /^(authorization|proxy-authorization|cookie|set-cookie|(?:x[-_])?api[-_]?key|token|access[-_]?token|refresh[-_]?token|password|passwd|secret|credentials?|client[-_]?secret|private[-_]?key)$/i;
115
+ var metadataKeys = /* @__PURE__ */ new Set([
116
+ "status",
117
+ "durationMs",
118
+ "toolName",
119
+ "usage",
120
+ "usageTotals",
121
+ "completeness",
122
+ "hasIncompleteUsage",
123
+ "incompleteCount",
124
+ "completeCount",
125
+ "protocolId",
126
+ "modelId",
127
+ "attemptNo",
128
+ "inputTokens",
129
+ "outputTokens",
130
+ "cacheReadTokens",
131
+ "cacheWriteTokens",
132
+ "costMicros",
133
+ "code",
134
+ "errorCode",
135
+ "iteration",
136
+ "kind",
137
+ "agentId",
138
+ "agentVersion",
139
+ "configHash",
140
+ "approvalId",
141
+ "decision",
142
+ "commandId",
143
+ "artifacts",
144
+ "sha256",
145
+ "byteSize",
146
+ "contentType"
147
+ ]);
148
+ function metadata(value) {
149
+ if (Array.isArray(value)) return value.map(metadata);
150
+ if (value && typeof value === "object")
151
+ return Object.fromEntries(
152
+ Object.entries(value).filter(([key]) => metadataKeys.has(key)).map(([key, item]) => [key, metadata(item)])
153
+ );
154
+ return value;
155
+ }
156
+ function redactText(value, fields = []) {
157
+ let clean = value.replace(
158
+ /-----BEGIN [\w ]*PRIVATE KEY-----[\s\S]*?-----END [\w ]*PRIVATE KEY-----/g,
159
+ "[REDACTED]"
160
+ ).replace(/\bBearer\s+[^\s"'<>]+/gi, "Bearer [REDACTED]").replace(/\b(?:set-cookie|cookie)\s*:\s*[^\r\n]+/gi, "Cookie: [REDACTED]").replace(
161
+ /\b(?:sk-[a-zA-Z0-9_-]{8,}|gh[pousr]_[a-zA-Z0-9_]{10,}|AKIA[A-Z0-9]{16}|eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\b/g,
162
+ "[REDACTED]"
163
+ ).replace(
164
+ /\b(authorization|(?:x[-_])?api[-_]?key|token|access[-_]?token|refresh[-_]?token|password|secret|cookie|set-cookie)["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi,
165
+ "$1=[REDACTED]"
166
+ );
167
+ for (const field of fields) {
168
+ const name = field.split(".").at(-1).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
169
+ if (name)
170
+ clean = clean.replace(
171
+ new RegExp(`\\b(${name})["']?\\s*[:=]\\s*(?:"[^"]*"|'[^']*'|[^\\s,;}]+)`, "gi"),
172
+ "$1=[REDACTED]"
173
+ );
174
+ }
175
+ return clean;
176
+ }
177
+ function redact(value, fields = []) {
178
+ const names = new Set(fields.filter((f) => !f.includes(".")).map((f) => f.toLowerCase()));
179
+ const paths = new Set(fields.map((f) => f.toLowerCase()));
180
+ const seen = /* @__PURE__ */ new WeakSet();
181
+ const visit = (item, path) => {
182
+ if (typeof item === "string") return redactText(item, fields);
183
+ if (typeof item === "function" || typeof item === "symbol" || typeof item === "bigint" || typeof item === "number" && !Number.isFinite(item))
184
+ throw new TypeError("Unsupported export payload");
185
+ if (item === null || typeof item !== "object") return item;
186
+ if (seen.has(item)) return "[REDACTED]";
187
+ seen.add(item);
188
+ try {
189
+ if (Array.isArray(item)) return item.map((v) => visit(v, path));
190
+ const result = /* @__PURE__ */ Object.create(null);
191
+ for (const [key, entry] of Object.entries(item)) {
192
+ const next = path ? `${path}.${key}` : key;
193
+ result[key] = secretKey.test(key) || names.has(key.toLowerCase()) || paths.has(next.toLowerCase()) ? "[REDACTED]" : visit(entry, next);
194
+ }
195
+ return result;
196
+ } finally {
197
+ seen.delete(item);
198
+ }
199
+ };
200
+ return visit(value, "");
201
+ }
202
+ function redactEvent(event, mode, fields) {
203
+ const clean = {};
204
+ for (const key of [
205
+ "type",
206
+ "seq",
207
+ "eventId",
208
+ "occurredAt",
209
+ "scope",
210
+ "sessionId",
211
+ "rootTurnId",
212
+ "parentTurnId",
213
+ "turnId",
214
+ "stepId",
215
+ "attemptNo",
216
+ "traceId",
217
+ "spanId",
218
+ "parentSpanId",
219
+ "data",
220
+ "delta",
221
+ "message"
222
+ ]) {
223
+ if (key in event) clean[key] = event[key];
224
+ }
225
+ if (event.scope)
226
+ clean.scope = {
227
+ ...event.scope.tenantId === void 0 ? {} : { tenantId: event.scope.tenantId },
228
+ ...event.scope.projectId === void 0 ? {} : { projectId: event.scope.projectId }
229
+ };
230
+ if (mode === "metadata_only") {
231
+ delete clean.delta;
232
+ delete clean.message;
233
+ if (event.data) clean.data = metadata(event.data);
234
+ } else {
235
+ if ("delta" in clean && typeof clean.delta === "string")
236
+ clean.delta = redactText(clean.delta, fields);
237
+ if ("message" in clean && typeof clean.message === "string")
238
+ clean.message = redactText(clean.message, fields);
239
+ }
240
+ if (clean.data) clean.data = redact(clean.data, fields);
241
+ return clean;
242
+ }
243
+ var ConnectorState = class {
244
+ constructor(dir, runtimeId) {
245
+ this.dir = dir;
246
+ this.runtimeId = runtimeId;
247
+ }
248
+ dir;
249
+ runtimeId;
250
+ data = { runtimeId: "", pending: [], snapshots: [] };
251
+ writes = Promise.resolve();
252
+ async open() {
253
+ await mkdir(this.dir, { recursive: true, mode: 448 });
254
+ try {
255
+ const value = JSON.parse(await readFile(join(this.dir, "connector.json"), "utf8"));
256
+ if (typeof value !== "object" || value === null) throw new Error("Invalid connector state");
257
+ const v = value;
258
+ if (typeof v.runtimeId !== "string" || !v.runtimeId || !Array.isArray(v.pending) || !v.pending.every(
259
+ (p) => isCommandEnvelope(p.envelope) && (!p.receipt || isCommandReceipt(p.receipt) && p.receipt.commandId === p.envelope.commandId)
260
+ ) || !Array.isArray(v.snapshots) || !v.snapshots.every(isConfigSnapshot))
261
+ throw new Error("Invalid connector state");
262
+ if (this.runtimeId && this.runtimeId !== v.runtimeId)
263
+ throw new Error("Runtime identity differs from connector state");
264
+ this.data = v;
265
+ } catch (error) {
266
+ if (error.code !== "ENOENT") throw error;
267
+ this.data.runtimeId = this.runtimeId ?? randomUUID();
268
+ await this.save();
269
+ }
270
+ }
271
+ save() {
272
+ const content = JSON.stringify(this.data);
273
+ const write = this.writes.catch(() => {
274
+ }).then(async () => {
275
+ const destination = join(this.dir, "connector.json");
276
+ const temp = `${destination}.${randomUUID()}.tmp`;
277
+ try {
278
+ const file = await open(temp, "wx", 384);
279
+ try {
280
+ await file.writeFile(content);
281
+ await file.sync();
282
+ } finally {
283
+ await file.close();
284
+ }
285
+ await rename(temp, destination);
286
+ const dir = await open(this.dir, "r");
287
+ try {
288
+ await dir.sync();
289
+ } finally {
290
+ await dir.close();
291
+ }
292
+ } finally {
293
+ await rm(temp, { force: true });
294
+ }
295
+ });
296
+ this.writes = write;
297
+ return write;
298
+ }
299
+ async close() {
300
+ await this.writes.catch(() => {
301
+ });
302
+ }
303
+ };
304
+
305
+ // src/index.ts
306
+ function cloudConnector(config) {
307
+ const settings = config.transport ?? {};
308
+ const capabilities2 = {
309
+ allowRemoteApproval: false,
310
+ allowRemoteCancel: false,
311
+ allowRemoteSteer: false,
312
+ allowRemoteResume: false,
313
+ ...config.commands
314
+ };
315
+ const obs = config.observability ?? {};
316
+ const mode = obs.payloadMode ?? "redacted_full";
317
+ const fields = obs.redactFields ?? [];
318
+ const state = new ConnectorState(resolve(config.stateDir ?? ".soil-cloud"), config.runtimeId);
319
+ const request = settings.fetch ?? globalThis.fetch;
320
+ let runtime;
321
+ let stopped = true;
322
+ let socket;
323
+ let ready = false;
324
+ let initialized = false;
325
+ let unsubscribe;
326
+ let controller = new AbortController();
327
+ let connectFailures = 0;
328
+ let exportFailures = 0;
329
+ let artifactFailures = 0;
330
+ let nextConnect = 0;
331
+ let nextExport = 0;
332
+ let nextArtifact = 0;
333
+ let lastHeartbeat = 0;
334
+ let lastSeen = 0;
335
+ let connectedAt = 0;
336
+ let authToken = "";
337
+ let timer;
338
+ let maintenance;
339
+ let exporting;
340
+ let artifactExport;
341
+ let initializing;
342
+ let commandWork;
343
+ let messageChain = Promise.resolve();
344
+ const processing = /* @__PURE__ */ new Set();
345
+ const receiptSent = /* @__PURE__ */ new Map();
346
+ const retryCommandAt = /* @__PURE__ */ new Map();
347
+ const watched = /* @__PURE__ */ new Set();
348
+ const realtime = [];
349
+ const artifactQueue = /* @__PURE__ */ new Map();
350
+ const artifactDone = /* @__PURE__ */ new Set();
351
+ const heartbeatMs = settings.heartbeatMs ?? 3e4;
352
+ const pollMs = settings.pollIntervalMs ?? 1e3;
353
+ const backoff = (failures) => Math.min(
354
+ settings.retryMaxMs ?? 6e4,
355
+ (settings.retryBaseMs ?? 1e3) * 2 ** Math.min(failures, 20)
356
+ ) * (0.5 + (settings.random ?? Math.random)() * 0.5);
357
+ const token = async () => {
358
+ const signal = AbortSignal.any([
359
+ controller.signal,
360
+ AbortSignal.timeout(settings.requestTimeoutMs ?? 1e4)
361
+ ]);
362
+ signal.throwIfAborted();
363
+ return new Promise((resolve2, reject) => {
364
+ const abort = () => reject(signal.reason);
365
+ signal.addEventListener("abort", abort, { once: true });
366
+ Promise.resolve().then(() => typeof config.token === "function" ? config.token() : config.token).then(
367
+ (value) => {
368
+ signal.removeEventListener("abort", abort);
369
+ resolve2(value);
370
+ },
371
+ (error) => {
372
+ signal.removeEventListener("abort", abort);
373
+ reject(error);
374
+ }
375
+ );
376
+ });
377
+ };
378
+ const send = (frame, handshake = false) => {
379
+ if (stopped || !socket || socket.readyState !== 1 || !ready && !handshake) return false;
380
+ try {
381
+ socket.send(JSON.stringify(frame));
382
+ return true;
383
+ } catch {
384
+ disconnect();
385
+ return false;
386
+ }
387
+ };
388
+ function disconnect() {
389
+ const previous = socket;
390
+ socket = void 0;
391
+ ready = false;
392
+ watched.clear();
393
+ realtime.length = 0;
394
+ nextConnect = Date.now() + backoff(connectFailures++);
395
+ try {
396
+ previous?.close();
397
+ } catch {
398
+ }
399
+ }
400
+ async function post(path, payload) {
401
+ const url = new URL(path, config.endpoint);
402
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
403
+ throw new Error("Console requires TLS outside loopback");
404
+ const bytes = gzipSync(JSON.stringify(payload));
405
+ return request(url, {
406
+ method: "POST",
407
+ headers: {
408
+ authorization: `Bearer ${await token()}`,
409
+ "content-type": "application/json",
410
+ "content-encoding": "gzip"
411
+ },
412
+ body: bytes,
413
+ signal: AbortSignal.any([
414
+ controller.signal,
415
+ AbortSignal.timeout(settings.requestTimeoutMs ?? 1e4)
416
+ ]),
417
+ redirect: "error"
418
+ });
419
+ }
420
+ function queueArtifacts(value) {
421
+ if (mode === "metadata_only" || obs.artifacts?.mode !== "auto_under_limit") return;
422
+ if (isArtifactRef(value)) {
423
+ if (value.byteSize <= obs.artifacts.maxBytes && /^(text\/|application\/(json|[^;]+\+json)(;|$))/.test(value.contentType) && !artifactDone.has(value.sha256) && artifactQueue.size < 128)
424
+ artifactQueue.set(value.sha256, value);
425
+ } else if (Array.isArray(value)) {
426
+ for (const item of value) queueArtifacts(item);
427
+ } else if (value && typeof value === "object") {
428
+ for (const item of Object.values(value)) queueArtifacts(item);
429
+ }
430
+ }
431
+ async function exportEvents() {
432
+ if (!runtime || stopped) return;
433
+ try {
434
+ const batch = await runtime.storage.outbox.read({ consumerId: "cloud-console", limit: 200 });
435
+ if (stopped) return;
436
+ if (!batch.events.length && !batch.gap) {
437
+ nextExport = Date.now() + pollMs;
438
+ return;
439
+ }
440
+ const fromSeq = batch.gap?.fromSeq ?? batch.events[0].seq;
441
+ const toSeq = batch.events.at(-1)?.seq ?? batch.gap.toSeq;
442
+ const payload = {
443
+ runtimeId: state.data.runtimeId,
444
+ fromSeq,
445
+ toSeq,
446
+ events: [
447
+ ...batch.gap ? [{ type: "outbox.gap", ...batch.gap }] : [],
448
+ ...batch.events.map((e) => redactEvent(e, mode, fields))
449
+ ]
450
+ };
451
+ const response = await post("/v1/ingest/events", payload);
452
+ if (response.status !== 200) throw new Error("Ingest not acknowledged");
453
+ const ack = await response.json();
454
+ if (!isIngestEventsResponse(ack) || ack.ackedUpToSeq < fromSeq || ack.ackedUpToSeq > toSeq || batch.gap && ack.ackedUpToSeq < batch.gap.toSeq)
455
+ throw new Error("Invalid ingest acknowledgement");
456
+ if (stopped) return;
457
+ await runtime.storage.outbox.ack({ consumerId: "cloud-console", upToSeq: ack.ackedUpToSeq });
458
+ for (const event of batch.events)
459
+ if (event.seq <= ack.ackedUpToSeq) queueArtifacts(event.data);
460
+ exportFailures = 0;
461
+ nextExport = Date.now();
462
+ } catch {
463
+ nextExport = Date.now() + backoff(exportFailures++);
464
+ }
465
+ }
466
+ async function exportArtifact() {
467
+ const ref = artifactQueue.values().next().value;
468
+ if (!ref || !runtime || obs.artifacts?.mode !== "auto_under_limit") return;
469
+ try {
470
+ const data = await runtime.storage.artifacts.get(ref);
471
+ if (!data || data.byteLength > obs.artifacts.maxBytes) {
472
+ artifactQueue.delete(ref.sha256);
473
+ return;
474
+ }
475
+ let content;
476
+ try {
477
+ const text2 = new TextDecoder("utf-8", { fatal: true }).decode(data);
478
+ content = /json/.test(ref.contentType) ? JSON.stringify(redact(JSON.parse(text2), fields)) : redactText(text2, fields);
479
+ } catch {
480
+ artifactQueue.delete(ref.sha256);
481
+ return;
482
+ }
483
+ const bytes = Buffer.from(content);
484
+ if (bytes.byteLength > obs.artifacts.maxBytes) {
485
+ artifactQueue.delete(ref.sha256);
486
+ return;
487
+ }
488
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
489
+ const payload = {
490
+ runtimeId: state.data.runtimeId,
491
+ sourceSha256: ref.sha256,
492
+ artifact: { ...ref, uri: `sha256:${sha256}`, sha256, byteSize: bytes.byteLength },
493
+ encoding: "utf8",
494
+ content
495
+ };
496
+ const response = await post("/v1/ingest/artifacts", payload);
497
+ const ack = response.status === 200 ? await response.json() : void 0;
498
+ if (!isIngestArtifactsResponse(ack) || ack.sha256 !== sha256)
499
+ throw new Error("Artifact not acknowledged");
500
+ artifactQueue.delete(ref.sha256);
501
+ artifactDone.add(ref.sha256);
502
+ if (artifactDone.size > 1024) artifactDone.delete(artifactDone.values().next().value);
503
+ artifactFailures = 0;
504
+ } catch {
505
+ nextArtifact = Date.now() + backoff(artifactFailures++);
506
+ }
507
+ }
508
+ const allowed = (envelope) => {
509
+ switch (envelope.payload.kind) {
510
+ case "approve":
511
+ return capabilities2.allowRemoteApproval;
512
+ case "cancel":
513
+ return capabilities2.allowRemoteCancel;
514
+ case "steer":
515
+ return capabilities2.allowRemoteSteer;
516
+ case "resolve_unknown":
517
+ case "resume":
518
+ return capabilities2.allowRemoteResume;
519
+ }
520
+ };
521
+ async function processCommand(pending) {
522
+ const id = pending.envelope.commandId;
523
+ if (processing.has(id) || !runtime || stopped || (retryCommandAt.get(id) ?? 0) > Date.now())
524
+ return;
525
+ processing.add(id);
526
+ try {
527
+ await state.save();
528
+ send({ type: "command.ack", commandId: id, stage: "received_by_runtime" });
529
+ if (!pending.receipt) {
530
+ if (!allowed(pending.envelope))
531
+ pending.receipt = {
532
+ commandId: id,
533
+ status: "rejected",
534
+ processedAt: (/* @__PURE__ */ new Date()).toISOString(),
535
+ rejectionReason: "unauthorized"
536
+ };
537
+ else {
538
+ try {
539
+ pending.receipt = await runtime.commands.dispatch(pending.envelope);
540
+ } catch (error) {
541
+ const reason = typeof error === "object" && error !== null && "code" in error && error.code === "COMMAND_REJECTED" && "rejectionReason" in error ? error.rejectionReason : void 0;
542
+ const rejected = {
543
+ commandId: id,
544
+ status: "rejected",
545
+ processedAt: (/* @__PURE__ */ new Date()).toISOString(),
546
+ rejectionReason: reason
547
+ };
548
+ if (!isCommandReceipt(rejected)) throw error;
549
+ pending.receipt = rejected;
550
+ }
551
+ }
552
+ }
553
+ if (!isCommandReceipt(pending.receipt) || pending.receipt.commandId !== id)
554
+ throw new Error("Invalid Runtime receipt");
555
+ await state.save();
556
+ if (send({ type: "command.receipt", receipt: pending.receipt }))
557
+ receiptSent.set(id, Date.now());
558
+ } catch {
559
+ retryCommandAt.set(id, Date.now() + backoff(1));
560
+ } finally {
561
+ processing.delete(id);
562
+ }
563
+ }
564
+ function launchCommand(pending) {
565
+ commandWork ??= processCommand(pending).finally(() => {
566
+ commandWork = void 0;
567
+ });
568
+ }
569
+ async function snapshot(snapshot2) {
570
+ const policy = config.configuration;
571
+ if (policy?.mode !== "hybrid") return;
572
+ const whitelist = policy.allowedFields[snapshot2.agentId];
573
+ if (!whitelist || Object.keys(snapshot2.values).some(
574
+ (key) => !whitelist.includes(key) || /tool|credential|permission|scope|capabilit/i.test(key)
575
+ ) || !await policy.verify(snapshot2))
576
+ return;
577
+ const old = state.data.snapshots.find((s) => s.agentId === snapshot2.agentId);
578
+ if (old && Date.parse(old.issuedAt) >= Date.parse(snapshot2.issuedAt)) return;
579
+ state.data.snapshots = [
580
+ ...state.data.snapshots.filter((s) => s.agentId !== snapshot2.agentId),
581
+ snapshot2
582
+ ];
583
+ await state.save();
584
+ await policy.stage(snapshot2);
585
+ }
586
+ async function receive(frame) {
587
+ if (stopped) return;
588
+ if (frame.type === "runtime.hello_ack") {
589
+ ready = true;
590
+ connectFailures = 0;
591
+ lastSeen = Date.now();
592
+ send({ type: "commands.pull_pending", runtimeId: state.data.runtimeId });
593
+ receiptSent.clear();
594
+ return;
595
+ }
596
+ if (!ready) return;
597
+ lastSeen = Date.now();
598
+ switch (frame.type) {
599
+ case "ping":
600
+ send({ type: "pong", timestamp: frame.timestamp });
601
+ break;
602
+ case "watch.start":
603
+ if (obs.streamRealtimeDeltas && watched.size < (obs.maxWatches ?? 128))
604
+ watched.add(frame.turnId);
605
+ break;
606
+ case "watch.stop":
607
+ watched.delete(frame.turnId);
608
+ for (let i = realtime.length - 1; i >= 0; i--)
609
+ if (realtime[i].turnId === frame.turnId) realtime.splice(i, 1);
610
+ break;
611
+ case "command.deliver": {
612
+ if (Date.parse(frame.expiresAt) <= Date.now()) return;
613
+ let pending = state.data.pending.find(
614
+ (p) => p.envelope.commandId === frame.envelope.commandId
615
+ );
616
+ if (pending && JSON.stringify(pending.envelope) !== JSON.stringify(frame.envelope)) return;
617
+ if (!pending) {
618
+ pending = { envelope: frame.envelope };
619
+ state.data.pending.push(pending);
620
+ }
621
+ await state.save();
622
+ send({
623
+ type: "command.ack",
624
+ commandId: frame.envelope.commandId,
625
+ stage: "received_by_runtime"
626
+ });
627
+ launchCommand(pending);
628
+ break;
629
+ }
630
+ case "command.receipt_ack": {
631
+ if (!receiptSent.has(frame.commandId)) return;
632
+ state.data.pending = state.data.pending.filter(
633
+ (p) => p.envelope.commandId !== frame.commandId
634
+ );
635
+ await state.save();
636
+ receiptSent.delete(frame.commandId);
637
+ retryCommandAt.delete(frame.commandId);
638
+ break;
639
+ }
640
+ case "config.snapshot":
641
+ await snapshot(frame.snapshot);
642
+ break;
643
+ }
644
+ }
645
+ async function connect() {
646
+ authToken = await token();
647
+ if (stopped) return;
648
+ const url = new URL("/v1/connect", config.endpoint);
649
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))
650
+ throw new Error("Console requires TLS outside loopback");
651
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
652
+ const current = (settings.webSocketFactory ?? ((url2) => new WebSocket(url2)))(url.toString());
653
+ socket = current;
654
+ connectedAt = Date.now();
655
+ current.addEventListener("open", () => {
656
+ if (socket !== current || stopped) return;
657
+ send(
658
+ {
659
+ type: "runtime.hello",
660
+ protocolVersion: PROTOCOL_VERSION,
661
+ token: authToken,
662
+ runtimeId: state.data.runtimeId,
663
+ runtimeName: config.runtimeName ?? state.data.runtimeId,
664
+ storageKind: runtime.storage.kind,
665
+ agents: config.agents ?? [],
666
+ capabilities: capabilities2
667
+ },
668
+ true
669
+ );
670
+ });
671
+ current.addEventListener("message", (event) => {
672
+ if (socket !== current || stopped || typeof event.data !== "string" || event.data.length > 1048576)
673
+ return;
674
+ try {
675
+ const frame = parseWssFrame(event.data);
676
+ messageChain = messageChain.then(() => socket === current ? receive(frame) : void 0).catch(() => {
677
+ });
678
+ } catch {
679
+ }
680
+ });
681
+ const lost = () => {
682
+ if (socket === current) disconnect();
683
+ };
684
+ current.addEventListener("close", lost);
685
+ current.addEventListener("error", lost);
686
+ }
687
+ async function maintain() {
688
+ if (stopped || !initialized) return;
689
+ if (!socket && Date.now() >= nextConnect) {
690
+ try {
691
+ await connect();
692
+ } catch {
693
+ disconnect();
694
+ }
695
+ }
696
+ if (!ready) {
697
+ if (socket && Date.now() - connectedAt > (settings.requestTimeoutMs ?? 1e4)) disconnect();
698
+ return;
699
+ }
700
+ if (Date.now() - lastSeen > heartbeatMs * 3) {
701
+ disconnect();
702
+ return;
703
+ }
704
+ if (Date.now() - lastHeartbeat >= heartbeatMs) {
705
+ if (await token() !== authToken) {
706
+ disconnect();
707
+ return;
708
+ }
709
+ const batch = await runtime.storage.outbox.read({
710
+ consumerId: "cloud-console",
711
+ limit: 1e3
712
+ });
713
+ const active = await runtime.storage.ledger.listRecoverableTurns({ limit: 1e3 });
714
+ send({
715
+ type: "ping",
716
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
717
+ activeTurns: active.filter((t) => t.status === "running").length,
718
+ outboxDepth: batch.events.length
719
+ });
720
+ lastHeartbeat = Date.now();
721
+ }
722
+ for (const pending of state.data.pending)
723
+ if (Date.now() - (receiptSent.get(pending.envelope.commandId) ?? 0) >= (settings.receiptRetryMs ?? 1e3)) {
724
+ launchCommand(pending);
725
+ }
726
+ while (realtime.length && socket && socket.bufferedAmount < (obs.maxRealtimeBytes ?? 262144)) {
727
+ const event = realtime.shift();
728
+ if (watched.has(event.turnId))
729
+ send({ type: "realtime.event", runtimeId: state.data.runtimeId, event });
730
+ }
731
+ }
732
+ async function initialize() {
733
+ try {
734
+ await state.open();
735
+ if (stopped) return;
736
+ const policy = config.configuration;
737
+ if (policy?.mode === "hybrid")
738
+ for (const cached of state.data.snapshots) {
739
+ const keys = policy.allowedFields[cached.agentId];
740
+ if (keys && Object.keys(cached.values).every(
741
+ (k) => keys.includes(k) && !/tool|credential|permission|scope|capabilit/i.test(k)
742
+ ) && await policy.verify(cached))
743
+ await policy.stage(cached);
744
+ }
745
+ initialized = true;
746
+ } catch {
747
+ }
748
+ }
749
+ function tick() {
750
+ if (stopped) return;
751
+ if (!initialized) {
752
+ initializing ??= initialize().finally(() => {
753
+ initializing = void 0;
754
+ });
755
+ return;
756
+ }
757
+ maintenance ??= maintain().catch(() => {
758
+ }).finally(() => {
759
+ maintenance = void 0;
760
+ });
761
+ if (!exporting && Date.now() >= nextExport)
762
+ exporting = exportEvents().finally(() => {
763
+ exporting = void 0;
764
+ });
765
+ if (!artifactExport && artifactQueue.size && Date.now() >= nextArtifact)
766
+ artifactExport = exportArtifact().finally(() => {
767
+ artifactExport = void 0;
768
+ });
769
+ }
770
+ const connector = {
771
+ get runtimeId() {
772
+ return initialized ? state.data.runtimeId : void 0;
773
+ },
774
+ get connected() {
775
+ return ready;
776
+ },
777
+ async open(host) {
778
+ if (!stopped) return;
779
+ stopped = false;
780
+ runtime = host;
781
+ controller = new AbortController();
782
+ try {
783
+ unsubscribe = host.subscribeRealtime?.(connector.onRealtimeEvent);
784
+ } catch {
785
+ }
786
+ timer = setInterval(tick, Math.min(pollMs, 100));
787
+ timer.unref();
788
+ tick();
789
+ },
790
+ async close() {
791
+ stopped = true;
792
+ ready = false;
793
+ initialized = false;
794
+ if (timer) clearInterval(timer);
795
+ controller.abort();
796
+ try {
797
+ unsubscribe?.();
798
+ } catch {
799
+ }
800
+ try {
801
+ socket?.close();
802
+ } catch {
803
+ }
804
+ socket = void 0;
805
+ watched.clear();
806
+ realtime.length = 0;
807
+ await Promise.allSettled([
808
+ initializing,
809
+ maintenance,
810
+ exporting,
811
+ artifactExport,
812
+ commandWork,
813
+ messageChain
814
+ ]);
815
+ await state.close();
816
+ },
817
+ onDurableEvent() {
818
+ },
819
+ onRealtimeEvent(event) {
820
+ if (stopped || !ready || !obs.streamRealtimeDeltas || !watched.has(event.turnId)) return;
821
+ try {
822
+ const clean = redactEvent(event, mode, fields);
823
+ if (Buffer.byteLength(JSON.stringify(clean)) > (obs.maxRealtimeBytes ?? 262144)) return;
824
+ const limit = Math.max(0, obs.realtimeBufferSize ?? 256);
825
+ if (!limit) return;
826
+ while (realtime.length >= limit) realtime.shift();
827
+ realtime.push(clean);
828
+ } catch {
829
+ }
830
+ }
831
+ };
832
+ return connector;
833
+ }
834
+
835
+ export { cloudConnector, redact, redactEvent, redactText };
836
+ //# sourceMappingURL=index.js.map
837
+ //# sourceMappingURL=index.js.map