Repository navigation
Expand file tree
/
Copy pathworker.ts
More file actions
7009 lines (6828 loc) · 280 KB
/
Copy pathworker.ts
File metadata and controls
7009 lines (6828 loc) · 280 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { reduceCredentialPolicy } from "@openclaw-enterprise/occ";
import {
assertExecutionReleaseAllowed,
credentialSourceMatchesSnapshot,
revisionCredentialSourceSnapshot,
} from "@openclaw-enterprise/contracts";
import type { CredentialProxyDriver } from "@openclaw-enterprise/contracts";
import { isDeepStrictEqual } from "node:util";
import { installationDriverConfigurations } from "./composition/installation-config.ts";
import {
DriverConfigurationRegistry,
type DriverConfigurationRegistration,
} from "@openclaw-enterprise/occ";
import { reconcileSandboxPolicy, failAbandonedSandboxPolicies } from "./worker/sandbox-policy.ts";
import { isSecretHarnessAuth, isServiceAccountHarnessAuth } from "@openclaw-enterprise/contracts";
import { isPositiveSafeInteger } from "@openclaw-enterprise/utils";
import { randomUUID } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { isSandboxFacet, normalizeSecretBindings } from "@openclaw-enterprise/contracts";
import type {
Agent,
AgentRevision,
AgentRevisionMetadata,
CredentialSource,
AuditEvent,
AuthorizationDecision,
AuthorizationRequest,
ComputeDriver,
ComputePrepareRevisionFailureDiagnostic,
CredentialWithdrawal,
PluginDeploymentWarning,
PluginDriver,
ComputeReadiness,
RepositoryPolicyDriver,
NativeRepositorySender,
RepositoryCredentialMaterialRef,
ComputeRevisionContext,
ConfigurationDriver,
Driver,
IAMDriver,
Installation,
Namespace,
NamespaceDeleteResult,
NamespaceEnsureResult,
BackendDefinition,
SandboxDriver,
SandboxHarnessObservation,
CredentialGatewayDriver,
SecretBindings,
SecretDriver,
ResolvedHarnessAuth,
RuntimeFailureEvidence,
SecretEnvironmentProjection,
SecretReference,
} from "@openclaw-enterprise/contracts";
import {
NativeIAMDriver,
validatePersistedNativeIAMState,
type NativeIAMState,
} from "@openclaw-enterprise/iam";
import {
PostgresPlatformState,
PostgresWorkQueue,
OpenClawController,
ActivationFailedError,
ComputePreparationFailedError,
ActivationPendingError,
CredentialSourceRevisionError,
CredentialWithdrawalRefusedError,
DependencyUnavailableError,
KubernetesSecretWriteForbiddenError,
PersistedStateInvalidError,
SandboxGatewayUnauthorizedError,
SandboxGatewayUnavailableError,
SANDBOX_DELETION_UNCONFIRMED,
operationRefusalHintCode,
type OperationRefusalHintCode,
RepositoryGitProfileUnsupportedError,
RepositoryGitSenderUnqualifiedError,
SandboxRevisionUnsupportedError,
SandboxRepositoryRecipientUnverifiedError,
ScopeViolationError,
TransientDependencyError,
WorkClaimLostError,
CREDENTIAL_WITHDRAWAL_TARGET,
credentialWithdrawalCompanionRevisions,
isCredentialWithdrawalWork,
isRepositoryCleanupWork,
isRepositoryExpiryCleanupWork,
repositoryCleanupRevisionId,
revisionAdmittedBeforeWork,
isRepositoryRuntimeRetirementWork,
provisioningEffectReceipt as provisioningEffectReceiptForRecord,
provisioningPendingEffect,
type ClaimedWork,
type ControllerWork,
type NativeWorkerSupport,
type InstalledDriver,
type ProvisioningEffectReceipt,
type PlatformReadView,
type PlatformUnitOfWork,
type PostgresPool,
type PostgresQueryClient,
type PostgresWorkQueueOptions,
validateRuntimeFailureEvidence,
} from "@openclaw-enterprise/occ";
import {
backendDefinitionMap,
removeNamespacePolicy,
removedPolicyDetails,
validateBackendDefinitions,
validateServiceAccountBackendBinding,
} from "@openclaw-enterprise/occ";
import type { InstallationRuntimeDrivers } from "./composition/installation-config.ts";
import { resolveApprovedHarness } from "./composition/production-harness.ts";
import { ComputeCleanupFailedError } from "./drivers/compute/cleanup-failure.ts";
import {
ComputeStopYieldedError,
withComputeAbortSignal,
withComputeWorkWaiting,
withYieldingComputeStop,
} from "./drivers/compute/operation-context.ts";
import type { OccMetrics, WorkKind, WorkOutcome } from "./metrics/index.ts";
import {
isStopYieldedCode,
PredecessorStopYieldedError,
type StopYieldedCode,
StopYields,
stopWithDrainYield,
stopYieldedCode,
stopYieldRecheckMs,
} from "./worker/stop-yields.ts";
import {
RepositoryCredentialAuthorityError,
repositoryCleanupFailureCode,
RepositoryCredentialLifecycle,
StandingRepositorySessionDisposingError,
} from "./worker/repository-credentials.ts";
/**
* Connection limits for the worker's main PostgreSQL pool. The worker is serial, so one query
* on a connection that went silent (a failover or partition with no RST) would otherwise stop
* every claim forever. `query_timeout` is client-side: it abandons the query, the transaction
* owner discards the connection, and the loop retries on a fresh one. It is not sent to the
* server, so poolers and migrations are unaffected. Size it well above any legitimate query.
* TCP keepalive only prunes dead idle connections eventually (kernel probe defaults apply).
*/
export function workerDatabasePoolOptions(timeoutMs: number) {
const timeout = positiveInteger(timeoutMs, "Worker database timeout");
return {
keepAlive: true,
keepAliveInitialDelayMillis: 10_000,
connectionTimeoutMillis: timeout,
query_timeout: timeout,
} as const;
}
export interface ControllerWorkerOptions {
readonly metrics?: OccMetrics;
readonly pool: PostgresPool & PostgresQueryClient;
readonly mode?: "development" | "production";
readonly drivers?: InstallationRuntimeDrivers;
readonly computeDriver?: ComputeDriver;
readonly sandboxDriver?: SandboxDriver;
readonly credentialGatewayDriver?: CredentialGatewayDriver;
readonly proxyDriver?: CredentialProxyDriver;
readonly pollIntervalMs?: number;
readonly leaseDurationMs?: number;
readonly maxAttempts?: number;
readonly convergenceTimeoutMs?: number;
readonly emit?: (event: Readonly<Record<string, unknown>>) => void;
readonly onHealthy?: () => Promise<void>;
/**
* Called, at most once per health interval, when the run loop starts a pass or a claim
* heartbeat renews. It goes quiet only while the loop is stuck, so a liveness probe can tell
* a wedged worker from one waiting out a database outage (each pass then fails fast).
*/
readonly onProgress?: () => Promise<void>;
}
type Observation = NamespaceEnsureResult | NamespaceDeleteResult;
type Outcome = "success" | "pending" | "retry" | "permanent";
// A revision whose runtime is not ready yet is progress, not a failure. Recheck
// it on a short cadence so earlier transient failures on the same Work do not
// stretch readiness waits through the queue's exponential retry backoff. The
// worker is serial and each recheck is a full preparation pass (0.2-1.7 s live),
// so the cadence grows with the deployment's age, from 500 ms to 5 s at 200 s:
// a runtime that stays unready for minutes cannot take half the worker (D223).
const REVISION_READINESS_RECHECK_MS = 500;
const REVISION_READINESS_RECHECK_MAX_MS = 5_000;
const REVISION_READINESS_RECHECK_AGE_DIVISOR = 40;
// Pending reason codes for an unready revision. Compute may say why it waits.
const REVISION_PENDING_CODES: Readonly<Record<string, string>> = Object.freeze({
WORKLOAD_UNSCHEDULABLE: "REVISION_UNSCHEDULABLE",
WORKLOAD_IMAGE_PULL_FAILED: "REVISION_IMAGE_PULL_FAILED",
NAMESPACE_POD_QUOTA_EXCEEDED: "NAMESPACE_POD_QUOTA_EXCEEDED",
WORKSPACE_NODE_PENDING: "WORKSPACE_NODE_PENDING",
WORKSPACE_SETUP_RETRYING: "WORKSPACE_SETUP_RETRYING",
HARNESS_CREDENTIAL_BOOTSTRAP_PENDING: "HARNESS_CREDENTIAL_BOOTSTRAP_PENDING",
REPOSITORY_GIT_ROUTE_PENDING: "REPOSITORY_GIT_ROUTE_PENDING",
});
const REVISION_READINESS_CODES: ReadonlySet<string> = new Set([
"REVISION_INCOMPLETE",
"WORKSPACE_NODE_BINDING_PENDING",
"REPOSITORY_GIT_MATERIAL_PENDING",
"WORKSPACE_NODE_RECONNECT_PENDING",
...Object.values(REVISION_PENDING_CODES),
]);
// A candidate revision's own deployment work: the only work that observes its OAuth bootstrap.
// An active revision's source is already consumed.
function isCandidateDeployment(claim: ClaimedWork): boolean {
return claim.idempotencyKey === `agent_revision:${claim.revisionId}:reconcile`;
}
// A refused candidate whose stop keeps failing waits on that stop, which can block the serial
// worker for minutes (Kubernetes waits for gateway and Agent Pods to terminate). Each failed stop
// doubles its recheck from the readiness cadence up to 5 minutes, and waits at least four times
// as long as that stop took, so a blocked stop holds at most a fifth of the worker and other
// Agents' work runs between attempts (finding 1002).
const REFUSED_CANDIDATE_STOP_RECHECK_MAX_MS = 300_000;
// Refusals that authorizeRevision and resolveRevisionBackend decide again on every pass, before
// a stored refusal's stop is retried; one that no longer stands lifts the stored refusal.
const REDECIDED_REFUSAL_CODES: ReadonlySet<string> = new Set([
"ACTOR_REVOKED",
"AUTHORIZATION_DENIED",
"INVALID_AGENT_PRINCIPAL",
"HARNESS_AUTH_REQUIRED",
"INVALID_HARNESS_AUTH",
"INVALID_SECRET_BINDINGS",
"BACKEND_UNAVAILABLE",
"HARNESS_AUTH_SOURCE_CHANGED",
"SERVICE_ACCOUNT_BACKEND_MISMATCH",
]);
const REFUSED_CANDIDATE_STOP_DURATION_FACTOR = 4;
// A repository cleanup that another pass cannot settle (an invalidated attempt or a cleanup
// error, with no session still closing) still rechecks so its obligation stays visible, but
// the delay grows with the work row's age, as for long readiness rechecks: age / 40, at least
// the configured interval and at most 10 minutes.
const REPOSITORY_CLEANUP_RECHECK_MAX_MS = 600_000;
const REPOSITORY_CLEANUP_RECHECK_AGE_DIVISOR = 40;
function repositoryCleanupRecheckMs(intervalMs: number, ageMs: number): number {
return Math.max(
intervalMs,
Math.min(
REPOSITORY_CLEANUP_RECHECK_MAX_MS,
Math.round(ageMs / REPOSITORY_CLEANUP_RECHECK_AGE_DIVISOR),
),
);
}
const LOGGED_ERROR_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
// A Kubernetes Status reason is one bare CamelCase word, such as Forbidden.
const LOGGED_STATUS_REASON = /^[A-Za-z]{1,64}$/u;
function loggedHttpStatus(error: unknown): number | undefined {
const status =
error !== null && typeof error === "object"
? (error as { readonly code?: unknown }).code
: undefined;
return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599
? status
: undefined;
}
/**
* The HTTP status and Status reason on an error's `cause`. A Driver error that
* replaces an SDK error, to keep private request data out of logs (a Kubernetes
* private Secret write) or to classify it as transient, keeps them there.
*/
function causeStatusLogFields(error: object): {
readonly status?: number;
readonly reason?: string;
} {
const cause = (error as { readonly cause?: unknown }).cause;
const status = loggedHttpStatus(cause);
if (status === undefined) {
return {};
}
const reason = (cause as { readonly reason?: unknown }).reason;
return {
status,
...(typeof reason === "string" && LOGGED_STATUS_REASON.test(reason) ? { reason } : {}),
};
}
/**
* The cleanup failures a Compute Driver reported beside each primary failure the worker took out
* of a ComputeCleanupFailedError, so the pass's log line still shows that cleanup failed.
*/
const computeCleanupFailures = new WeakMap<object, readonly unknown[]>();
/**
* The failure a Compute Driver operation's outcome follows. A Driver whose cleanup also failed
* reports both; the operation's own failure decides, so a refusal still fails at once and an
* outage still waits, and the cleanup failure is kept for the log fields (finding 2268). A
* primary failure that is not an object cannot carry that record, so its aggregate stays whole
* and is classified as before. A Driver can throw one error object again (a memoized client
* failure), so a failure without a failed cleanup clears any record it kept.
*/
function primaryComputeFailure(error: unknown): unknown {
if (!(error instanceof ComputeCleanupFailedError)) {
if (error !== null && typeof error === "object") {
computeCleanupFailures.delete(error);
}
return error;
}
const primary = error.primary;
if (primary === null || typeof primary !== "object" || error.cleanupFailures.length === 0) {
return error;
}
computeCleanupFailures.set(primary, error.cleanupFailures);
return primary;
}
/** The error class a log line may name: its own name or constructor's, else `Error`. */
function loggedErrorClass(error: unknown): string {
const record = error !== null && typeof error === "object" ? error : undefined;
return (
(record === undefined
? undefined
: [(record as { readonly name?: unknown }).name, record.constructor?.name].find(
(candidate): candidate is string =>
typeof candidate === "string" &&
candidate !== "Error" &&
LOGGED_ERROR_NAME.test(candidate),
)) ?? "Error"
);
}
/**
* Log fields that say which dependency failed and why, without provider text:
* a transient dependency names itself and a closed reason; any other failure
* gives its error class and any fixed Driver request diagnostic. Other errors add
* the HTTP status of an SDK error, its own or its cause's, and the Status reason a cause keeps.
* A failure whose Compute cleanup also failed adds `cleanupCause`, the first cleanup failure's
* class, so a failed cleanup never reads as a clean one (finding 2268).
*/
function revisionFailureLogFields(error: unknown): {
readonly dependency?: string;
readonly cause?: string;
readonly status?: number;
readonly reason?: string;
readonly method?: string;
readonly grpcStatus?: number;
readonly validationCategory?: string;
readonly cleanupCause?: string;
} {
return { ...primaryFailureLogFields(error), ...computeCleanupLogFields(error) };
}
/** `cleanupCause` when the Compute cleanup after this failure failed too, else nothing. */
function computeCleanupLogFields(error: unknown): { readonly cleanupCause?: string } {
if (error === null || typeof error !== "object") {
return {};
}
// A Sandbox gateway outage reaches the log as the transient failure that wraps it.
const cause = (error as { readonly cause?: unknown }).cause;
const cleanup =
computeCleanupFailures.get(error) ??
(cause !== null && typeof cause === "object" ? computeCleanupFailures.get(cause) : undefined);
return cleanup === undefined ? {} : { cleanupCause: loggedErrorClass(cleanup[0]) };
}
function primaryFailureLogFields(error: unknown): {
readonly dependency?: string;
readonly cause?: string;
readonly status?: number;
readonly reason?: string;
readonly method?: string;
readonly grpcStatus?: number;
readonly validationCategory?: string;
} {
if (error instanceof TransientDependencyError) {
return { dependency: error.dependency, cause: error.reason, ...causeStatusLogFields(error) };
}
const record = error !== null && typeof error === "object" ? error : undefined;
const errorClass = loggedErrorClass(error);
if (error instanceof DependencyUnavailableError && error.requestDiagnostic !== undefined) {
const { method, grpcStatus, validationCategory } = error.requestDiagnostic;
return { cause: errorClass, method, grpcStatus, validationCategory };
}
// Kubernetes SDK errors carry the HTTP status in `code`.
const status = loggedHttpStatus(record);
if (status !== undefined) {
return { cause: errorClass, status };
}
return record === undefined
? { cause: errorClass }
: { cause: errorClass, ...causeStatusLogFields(record) };
}
/** An invalid row: reading it again fails the same way until someone repairs it. */
function unrecoverableRead(error: unknown): boolean {
return error instanceof ScopeViolationError || error instanceof PersistedStateInvalidError;
}
/**
* The dependency a revision pass waits for when its failure clears by itself: within the
* convergence deadline, without spending the attempt budget (D28). A Sandbox gateway that did not
* answer at all (down or restarting) is one (findings 1658, 2040), at every step of the pass that
* calls it: the candidate's preparation and an exclusive predecessor's stop, which the next pass
* repeats. Other work (an Agent stop or deletion, a credential withdrawal, a Namespace) keeps its
* attempt budget: it has no convergence deadline to bound the wait.
*/
function revisionDependencyFailure(error: unknown): TransientDependencyError | undefined {
if (error instanceof TransientDependencyError) {
return error;
}
return error instanceof SandboxGatewayUnavailableError
? new TransientDependencyError(
"sandbox_gateway",
"unavailable",
"The Sandbox gateway did not answer.",
{ cause: error },
)
: undefined;
}
/** Why a claim-owned effect lost its claim; the `CLAIM_LOST` log line names it as `cause`. */
type ClaimLossCause =
| "CLAIM_RENEWAL_REFUSED"
| "CLAIM_RENEWAL_LATE"
| "CLAIM_RENEWAL_FAILED"
| "CLAIM_LEASE_LAPSED"
| "WORKER_STOPPING";
/** A claim lost around an external effect. Keeps the base error's name for its callers. */
class ClaimLeaseLostError extends WorkClaimLostError {
readonly lossCause: ClaimLossCause;
constructor(lossCause: ClaimLossCause) {
super();
this.lossCause = lossCause;
}
}
/**
* Stopping a refused candidate failed or yielded to other Work. The pass waits as
* `REFUSED_CANDIDATE_STOP_PENDING`, whose evidence and log keep the refusal code the stop was
* for, and its log names the stop's own failure.
*/
class RefusedCandidateStopError extends Error {
readonly refusal: string;
/** How long the unfinished stop held the worker. */
readonly durationMs: number;
/** The stop yielded to other Work rather than failing, so it does not double the backoff. */
readonly yielded: boolean;
constructor(refusal: string, durationMs: number, cause: unknown) {
super("The refused AgentRevision candidate could not be stopped.", { cause });
this.name = "RefusedCandidateStopError";
this.refusal = refusal;
this.durationMs = durationMs;
this.yielded = cause instanceof ComputeStopYieldedError;
}
/**
* The refusal stands, but it is not published while its candidate may still serve: the work
* waits on the stop's own dependency and the next pass repeats the refusal and the stop.
*/
pending(): {
readonly result: RevisionDispatchResult;
readonly logFields: Readonly<Record<string, string | number>>;
} {
return {
result: {
outcome: "pending",
code: "REFUSED_CANDIDATE_STOP_PENDING",
refusedCandidate: this.refusal,
refusedStopMs: this.durationMs,
...(this.yielded ? { refusedStopYielded: true } : {}),
},
logFields: { ...revisionFailureLogFields(this.cause), refusal: this.refusal },
};
}
}
/**
* The pending result of an activation pass that did not finish: a dependency
* that is converging and a known activation wait keep their own codes (D330);
* anything else stays REVISION_FINALIZATION_INCOMPLETE.
*/
function activationPendingResult(error: unknown): {
readonly outcome: "pending";
readonly code: string;
readonly dependencyFailure?: TransientDependencyError;
} {
if (error instanceof TransientDependencyError) {
return { outcome: "pending", code: error.code, dependencyFailure: error };
}
if (error instanceof ActivationPendingError) {
return { outcome: "pending", code: error.code };
}
return { outcome: "pending", code: "REVISION_FINALIZATION_INCOMPLETE" };
}
function revisionPendingCode(observation: unknown): string {
const reason = (observation as { readonly pendingReason?: unknown }).pendingReason;
return typeof reason === "string" && Object.hasOwn(REVISION_PENDING_CODES, reason)
? REVISION_PENDING_CODES[reason]!
: "REVISION_INCOMPLETE";
}
function revisionReadinessRecheckMs(ageMs: number): number {
return Math.min(
REVISION_READINESS_RECHECK_MAX_MS,
Math.max(
REVISION_READINESS_RECHECK_MS,
Math.round(ageMs / REVISION_READINESS_RECHECK_AGE_DIVISOR),
),
);
}
interface DispatchResult {
readonly outcome: Outcome;
readonly code: string;
readonly observation?: Observation;
readonly decision?: AuthorizationDecision;
readonly authorization?: AuthorizationRequest;
}
interface RevisionDispatchResult extends DispatchResult {
/** Terminal preparation requires durable retirement of this exact revision. */
readonly cleanupFailedPreparation?: true;
/** A transient dependency failure, retried until the convergence deadline. */
readonly dependencyFailure?: TransientDependencyError;
/**
* A refusal whose exclusive candidate could not be stopped yet. Its pending passes outlast
* the attempt budget and the convergence deadline: ending the work would leave the refused
* candidate serving with nothing left to stop it.
*/
readonly refusedCandidate?: string;
/** A refused active release is terminal only after observing its admitted grant withdrawn. */
readonly rejectedExecutionWithdrawal?: "pending" | "withdrawn";
/** How long the refused candidate's unfinished stop took; it lengthens the recheck. */
readonly refusedStopMs?: number;
/** That stop yielded to other Work; later rechecks do not count it as a failure. */
readonly refusedStopYielded?: boolean;
/** This pass already ran the refused candidate's stop, so publishing does not run it again. */
readonly refusedCandidateStopped?: boolean;
readonly data?: Readonly<Record<string, unknown>>;
readonly resultData?: Readonly<Record<string, unknown>>;
readonly revision?: Readonly<AgentRevision>;
readonly previous?: Readonly<AgentRevision>;
readonly supersededBy?: Readonly<AgentRevision>;
readonly expectedActiveRevisionId?: string;
readonly context?: ComputeRevisionContext;
}
interface AgentStopDispatchResult extends DispatchResult {
readonly agent?: Readonly<Agent>;
readonly revision?: Readonly<AgentRevision>;
}
interface CredentialWithdrawalAttempt {
readonly credentialSourceId: string;
/** The withdrawal's own requester, whose `agent:operate` authorizes its detach. */
readonly requestedBy: string;
readonly code: string;
/** True once the gateway confirmed revocation or the Sandbox no longer exists. */
readonly revoked: boolean;
/** Present when the requester no longer holds `agent:operate`; nothing was detached. */
readonly denial?: Pick<DispatchResult, "authorization" | "decision">;
}
interface CredentialWithdrawalDispatchResult extends DispatchResult {
/** One entry per pending withdrawal this pass reached; absent when none was pending. */
readonly attempts?: readonly CredentialWithdrawalAttempt[];
/** Earlier attempts already settled every withdrawal; this one changed nothing. */
readonly nothingPending?: boolean;
}
function unrevokedAttempts(
withdrawals: readonly Readonly<CredentialWithdrawal>[],
code: string,
): CredentialWithdrawalAttempt[] {
return withdrawals.map(({ credentialSourceId, requestedBy }) => ({
credentialSourceId,
requestedBy,
code,
revoked: false,
}));
}
const CREDENTIAL_WITHDRAWAL_REQUIRES_RUNTIME_RETIREMENT =
"CREDENTIAL_WITHDRAWAL_REQUIRES_RUNTIME_RETIREMENT";
/** Retry unconfirmed reductions; fail a refused withdrawal only after attempting the others. */
function settleCredentialWithdrawal(
attempts: readonly CredentialWithdrawalAttempt[],
): CredentialWithdrawalDispatchResult {
if (
attempts.some(
({ revoked, denial, code }) =>
!revoked &&
denial === undefined &&
code !== CREDENTIAL_WITHDRAWAL_REQUIRES_RUNTIME_RETIREMENT,
)
) {
return { outcome: "retry", code: "CREDENTIAL_WITHDRAWAL_PENDING", attempts };
}
const failed = attempts.find(
({ denial, code }) =>
denial !== undefined || code === CREDENTIAL_WITHDRAWAL_REQUIRES_RUNTIME_RETIREMENT,
);
return failed === undefined
? { outcome: "success", code: "CREDENTIALS_WITHDRAWN", attempts }
: { outcome: "permanent", code: failed.code, attempts };
}
/**
* A pending withdrawal whose last attempt found its requester without `agent:operate` waits
* for a replay: only an operator who still holds it can take it over and queue an attempt
* that can succeed, so maintenance does not queue another denied attempt. One Compute refused
* (CredentialWithdrawalRefusedError) waits too: an operator corrects the cause, then replays.
*/
const CREDENTIAL_WITHDRAWAL_REPLAY_REASONS: ReadonlySet<string> = new Set([
"AUTHORIZATION_DENIED",
"ACTOR_REVOKED",
"CREDENTIAL_WITHDRAWAL_MISCONFIGURED",
CREDENTIAL_WITHDRAWAL_REQUIRES_RUNTIME_RETIREMENT,
"CREDENTIAL_WITHDRAWAL_OWNERSHIP_CONFLICT",
]);
function credentialWithdrawalAwaitsReplay(withdrawal: Readonly<CredentialWithdrawal>): boolean {
return (
withdrawal.lastReason !== undefined &&
CREDENTIAL_WITHDRAWAL_REPLAY_REASONS.has(withdrawal.lastReason)
);
}
/**
* Later attempt series a withdrawal gets after its work runs out of attempts on a retryable
* failure: 30 s, 1, 2 and 4 min, then every 5 min, about an hour in all.
*/
const MAX_CREDENTIAL_WITHDRAWAL_RECOVERIES = 15;
const CREDENTIAL_WITHDRAWAL_RECOVERY_BASE_MS = 30_000;
const CREDENTIAL_WITHDRAWAL_RECOVERY_MAX_MS = 300_000;
const CREDENTIAL_WITHDRAWAL_RECOVERY_SUFFIX = /:recovery:([1-9][0-9]*)$/;
/**
* The series after the claimed one. Every series of one request shares the request's work key
* with its number appended, so a series is queued once and the chain stays bounded; a replay is
* a new request whose chain starts again.
*/
function nextCredentialWithdrawalRecovery(idempotencyKey: string): {
readonly idempotencyKey: string;
readonly number: number;
} {
const current = CREDENTIAL_WITHDRAWAL_RECOVERY_SUFFIX.exec(idempotencyKey);
const requestKey = current === null ? idempotencyKey : idempotencyKey.slice(0, current.index);
const number = (current === null ? 0 : Number(current[1])) + 1;
return { idempotencyKey: `${requestKey}:recovery:${number}`, number };
}
function credentialWithdrawalRecoveryDelayMs(recovery: number): number {
return Math.min(
CREDENTIAL_WITHDRAWAL_RECOVERY_MAX_MS,
CREDENTIAL_WITHDRAWAL_RECOVERY_BASE_MS * 2 ** Math.min(recovery - 1, 10),
);
}
/**
* Native Harness exposures the worker withdraws outside a preparation pass: a revision already
* active when the worker starts, deployed by a controller that kept the exposure for the
* Sandbox's lifetime (finding 1669), and a candidate that failed for good while its Sandbox
* stays for diagnosis (finding 1672). Attempts: at once, then 30 s, 1, 2 and 4 min later; the
* fifth failure is logged by code and the revision left until the next start.
*/
const MAX_HARNESS_EXPOSURE_WITHDRAWAL_ATTEMPTS = 5;
const HARNESS_EXPOSURE_WITHDRAWAL_RETRY_BASE_MS = 30_000;
/**
* The sweep step runs on passes that follow an empty claim, and after this many claimed passes
* in a row regardless, so a queue that is never empty cannot starve it (finding 1695).
*/
const HARNESS_EXPOSURE_SWEEP_CLAIMED_PASSES = 5;
interface PendingHarnessExposureWithdrawal {
readonly revision: Readonly<AgentRevision>;
attempts: number;
dueAt: number;
}
/** The code a failed exposure withdrawal is logged with; never the provider's text. */
function harnessExposureWithdrawalCode(error: unknown): string {
if (error instanceof TransientDependencyError) {
return error.code;
}
const code = (error as { readonly code?: unknown } | null)?.code;
return typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/u.test(code)
? code
: "HARNESS_EXPOSURE_WITHDRAWAL_FAILED";
}
/**
* The operator guidance a failed stop, deletion or withdrawal logs with its code, as a fixed code
* (findings 1694, 2245): the log sanitizer keeps no free text.
*/
function refusalHintField(
terminal: boolean,
code: string,
): { readonly hintCode?: OperationRefusalHintCode } {
const hintCode = terminal ? operationRefusalHintCode(code) : undefined;
return hintCode === undefined ? {} : { hintCode };
}
/** A revision whose Sandbox Driver may hold a native Harness exposure for this Compute. */
function holdsNativeHarnessExposure(
revision: Readonly<AgentRevision>,
compute: Pick<ComputeDriver, "id" | "implementation">,
): boolean {
return (
revision.harness.mode === "dedicated" &&
revision.harness.id === "openclaw" &&
revision.sandboxDriverId !== undefined &&
revision.compute.id === compute.id &&
revision.compute.implementation === compute.implementation
);
}
/** A revision's first pending withdrawal, preferring one that does not await a replay. */
function firstPendingCredentialWithdrawal(
withdrawals: readonly Readonly<CredentialWithdrawal>[],
): Readonly<CredentialWithdrawal> | undefined {
const pending = withdrawals.filter(({ state }) => state === "pending");
return pending.find((withdrawal) => !credentialWithdrawalAwaitsReplay(withdrawal)) ?? pending[0];
}
/**
* A pending withdrawal that needs an attempt queued: it does not await a replay, and no attempt
* for its revision is queued or running. Every path that queues withdrawal work without an
* operator request (maintenance, a later series) checks this, so each revision keeps one chain.
*/
async function credentialWithdrawalNeedsAttempt(
unit: PlatformUnitOfWork,
withdrawal: Readonly<CredentialWithdrawal>,
): Promise<boolean> {
return (
withdrawal.state === "pending" &&
!credentialWithdrawalAwaitsReplay(withdrawal) &&
!(await unit.operations.hasOutstandingCredentialWithdrawalWork(
withdrawal.namespaceId,
withdrawal.revisionId,
))
);
}
/** Each requester's withdrawn source ids, in attempt order. */
function sourceIdsByRequester(
attempts: readonly CredentialWithdrawalAttempt[],
): Map<string, string[]> {
const grouped = new Map<string, string[]>();
for (const { requestedBy, credentialSourceId } of attempts) {
grouped.set(requestedBy, [...(grouped.get(requestedBy) ?? []), credentialSourceId]);
}
return grouped;
}
/** The revision's admitted sources once each: its Harness source first, then the others. */
function revisionCredentialSourceIds(revision: Readonly<AgentRevision>): readonly string[] {
const harnessSourceId = revisionHarnessSourceId(revision);
return [
...(harnessSourceId === undefined ? [] : [harnessSourceId]),
...(revision.credentialSources ?? [])
.map(({ sourceId }) => sourceId)
.filter((sourceId) => sourceId !== harnessSourceId),
];
}
function revisionHarnessSourceId(revision: Readonly<AgentRevision>): string | undefined {
return revision.harnessAuth.method === "credential_source"
? revision.harnessAuth.sourceId
: undefined;
}
interface AgentDeletionDispatchResult extends DispatchResult {
readonly namespace?: Readonly<Namespace>;
readonly agent?: Readonly<Agent>;
readonly revisions?: readonly Readonly<AgentRevision>[];
readonly delayMs?: number;
readonly abandonedProvisioningEffect?: {
readonly workId: string;
readonly receipt: ProvisioningEffectReceipt;
};
}
function positiveInteger(value: number, name: string): number {
if (!isPositiveSafeInteger(value)) {
throw new Error(`${name} must be a positive safe integer.`);
}
return value;
}
function workOperation(claim: ControllerWork): string {
if (isCredentialWithdrawalWork(claim)) {
return "agent_revision.credential_withdrawal";
}
if (claim.revisionId !== undefined) {
return "agent_revision.reconcile";
}
if (claim.agentTarget === "stopped") {
return "agent.stop";
}
if (claim.agentTarget === "deleted") {
return "agent.delete";
}
if (claim.namespaceTarget === "deleted") {
return "namespace.delete";
}
if (claim.namespaceTarget === "ready") {
return "namespace.ensure";
}
return "work.reconcile";
}
// Worker-local phase timing for one deployment work item. It spans the passes
// this process observes; a restart or eviction starts a new record.
interface DeployTiming {
passes: number;
passStartedAt: number;
prepareMs: number;
firstUnreadyAt: number | undefined;
readinessWaitMs: number | undefined;
readyAt: number | undefined;
}
const MAX_DEPLOY_TIMINGS = 256;
const SAFE_COMPUTE_FAILURE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
const SAFE_COMPUTE_FAILURE_STAGE = /^[a-z][a-z0-9_]{0,63}$/;
const SAFE_COMPUTE_FAILURE_CLASS = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
const MAX_COMPUTE_FAILURE_MESSAGE_LENGTH = 256;
function printableComputeFailureMessage(value: string): boolean {
return (
value.length <= MAX_COMPUTE_FAILURE_MESSAGE_LENGTH &&
[...value].every((character) => {
const codePoint = character.codePointAt(0)!;
return codePoint >= 32 && codePoint !== 127;
})
);
}
function validComputeFailureDiagnostic(
value: ComputePrepareRevisionFailureDiagnostic | undefined,
): value is ComputePrepareRevisionFailureDiagnostic {
return (
value !== undefined &&
SAFE_COMPUTE_FAILURE_CODE.test(value.code) &&
SAFE_COMPUTE_FAILURE_STAGE.test(value.stage) &&
(value.errorClass === undefined || SAFE_COMPUTE_FAILURE_CLASS.test(value.errorClass)) &&
(value.message === undefined || printableComputeFailureMessage(value.message)) &&
(value.status === undefined ||
(Number.isSafeInteger(value.status) && value.status >= 0 && value.status <= 999))
);
}
/** A yielded stop's log lines name how often this worker saw its stop yield (finding 1094). */
function stopYieldsField(stopYields: number | undefined): { stopYields?: number } {
return stopYields === undefined ? {} : { stopYields };
}
function workLogFields(claim: ClaimedWork): {
readonly workId: string;
readonly attempt: number;
readonly operation: string;
} {
return {
workId: claim.idempotencyKey,
attempt: claim.attemptCount,
operation: workOperation(claim),
};
}
function validDriver(driver: ComputeDriver): boolean {
return (
typeof driver.id === "string" &&
driver.id.trim().length > 0 &&
driver.capability === "compute" &&
typeof driver.implementation === "string" &&
driver.implementation.trim().length > 0 &&
typeof driver.ensureNamespace === "function" &&
typeof driver.deleteNamespace === "function" &&
typeof driver.prepareRevision === "function" &&
typeof driver.stopRevision === "function" &&
typeof driver.retireRevision === "function" &&
(driver.deleteAgentRuntimeCredentials === undefined ||
typeof driver.deleteAgentRuntimeCredentials === "function")
);
}
function validSandboxDriver(driver: SandboxDriver): boolean {
return (
typeof driver.id === "string" &&
driver.id.trim().length > 0 &&
driver.capability === "sandbox" &&
typeof driver.implementation === "string" &&
driver.implementation.trim().length > 0 &&
Array.isArray(driver.facets) &&
driver.facets.length > 0 &&
driver.facets.every(isSandboxFacet) &&
(driver.ensureNamespace === undefined || typeof driver.ensureNamespace === "function") &&
(driver.provisionHarness === undefined || typeof driver.provisionHarness === "function") &&
typeof driver.cleanup === "function"
);
}
function validSecretDriver(driver: SecretDriver): boolean {
return (
typeof driver.id === "string" &&
driver.id.trim().length > 0 &&
driver.capability === "secret" &&
typeof driver.implementation === "string" &&
driver.implementation.trim().length > 0 &&
typeof driver.create === "function" &&
typeof driver.update === "function" &&
typeof driver.delete === "function" &&
typeof driver.resolve === "function" &&
(driver.withValue === undefined || typeof driver.withValue === "function")
);
}
function validLifecycleHooks(driver: Driver): boolean {
const hooks = driver.computeLifecycleHooks;
if (hooks === undefined) {
return true;
}
if (typeof hooks !== "object" || hooks === null || Array.isArray(hooks)) {
return false;
}
const phases = new Set([
"afterNamespacePrepared",
"beforeWorkloadStart",
"beforeWorkloadStop",
"beforeNamespaceDelete",
]);
const candidate = hooks as unknown as Record<string, unknown>;
return (
Object.keys(candidate).length > 0 &&
Object.entries(candidate).every(
([phase, callback]) => phases.has(phase) && typeof callback === "function",
)
);
}
/** A Driver's optional Namespace failure reason, kept only when bounded and printable. */
function namespaceFailureReason(observation: Observation): string | undefined {
const reason = (observation as { readonly reason?: unknown }).reason;
return typeof reason === "string" && reason.length > 0 && printableComputeFailureMessage(reason)
? reason
: undefined;
}
function validObservation(value: unknown, namespaceId: string, target: "ready" | "deleted") {
if (typeof value !== "object" || value === null || Object.hasOwn(value, "installationId")) {
return false;
}
const observation = value as Partial<NamespaceEnsureResult & NamespaceDeleteResult>;
if (
observation.namespaceId !== namespaceId ||
(observation.failure !== undefined &&
observation.failure !== "retryable" &&
observation.failure !== "permanent")
) {
return false;
}
return target === "ready"
? typeof observation.namespaceReady === "boolean"
: typeof observation.namespaceDeleted === "boolean";
}
function validRevisionObservation(value: unknown, revision: Readonly<AgentRevision>): boolean {
if (typeof value !== "object" || value === null || Object.hasOwn(value, "installationId")) {
return false;
}
const observation = value as Record<string, unknown>;
if (
observation.warnings !== undefined &&
computePluginWarnings(observation.warnings, revision) === undefined
) {
return false;
}
return (
observation.namespaceId === revision.namespaceId &&
observation.agentId === revision.agentId &&
observation.revisionId === revision.id &&
typeof observation.ready === "boolean"
);
}
function computePluginWarnings(
warnings: unknown,
revision: Readonly<AgentRevision>,
): readonly PluginDeploymentWarning[] | undefined {
if (warnings === undefined) {
return Object.freeze([]);