@agent-vm/gondolin-adapter 0.0.69 → 0.0.71

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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { ResolveAllResponse } from "@1password/sdk";
2
1
  import { BuildConfig, BuildConfig as BuildConfig$1, CreateHttpHooksResult, EnableIngressOptions, EnableSshOptions, IngressRoute as IngressRoute$1, ShadowPredicate, ShadowProviderOptions, VMOptions, VirtualProvider, getDefaultBuildConfig } from "@earendil-works/gondolin";
2
+ import { MediatedSecretSpec } from "@agent-vm/secret-management";
3
3
 
4
4
  //#region src/build-pipeline.d.ts
5
5
  interface BuildImageOptions {
@@ -92,70 +92,6 @@ declare function normalizeHostname(rawHostname: string): string;
92
92
  declare function dedupeStable(values: readonly string[]): string[];
93
93
  declare function compilePolicy(sources: PolicySources): string[];
94
94
  //#endregion
95
- //#region src/types.d.ts
96
- interface SecretSpec {
97
- readonly hosts: readonly string[];
98
- readonly value: string;
99
- }
100
- type SecretRef = {
101
- readonly source: '1password';
102
- readonly ref: string;
103
- } | {
104
- readonly source: 'environment';
105
- readonly ref: string;
106
- };
107
- //#endregion
108
- //#region src/secret-resolver.d.ts
109
- interface SecretResolverClient {
110
- readonly secrets: {
111
- resolve(secretReference: string): Promise<string>;
112
- resolveAll(secretReferences: readonly string[]): Promise<ResolveAllResponse>;
113
- };
114
- }
115
- interface SecretResolver {
116
- resolve(ref: SecretRef): Promise<string>;
117
- resolveAll(refs: Record<string, SecretRef>): Promise<Record<string, string>>;
118
- }
119
- type TokenSource = {
120
- readonly type: 'op-cli';
121
- readonly ref: string;
122
- } | {
123
- readonly type: 'env';
124
- readonly envVar?: string | undefined;
125
- } | {
126
- readonly type: 'keychain';
127
- readonly service: string;
128
- readonly account: string;
129
- };
130
- interface ExecFileOptions {
131
- readonly env?: Readonly<Record<string, string | undefined>>;
132
- readonly input?: string | undefined;
133
- readonly redactErrorOutput?: boolean | undefined;
134
- }
135
- interface ExecFileResult {
136
- readonly stdout: string;
137
- readonly stderr: string;
138
- }
139
- declare function resolveServiceAccountToken(source: TokenSource, dependencies?: {
140
- readonly execFileAsync?: (command: string, args: readonly string[], options?: ExecFileOptions) => Promise<ExecFileResult>;
141
- }): Promise<string>;
142
- interface CreateSecretResolverDependencies {
143
- readonly createClient?: (config: {
144
- auth: string;
145
- integrationName: string;
146
- integrationVersion: string;
147
- }) => Promise<SecretResolverClient>;
148
- readonly execFileAsync?: (command: string, args: readonly string[], options?: ExecFileOptions) => Promise<ExecFileResult>;
149
- readonly integrationName?: string;
150
- readonly integrationVersion?: string;
151
- }
152
- declare function createSecretResolver(options: {
153
- readonly serviceAccountToken: string;
154
- }, dependencies?: CreateSecretResolverDependencies): Promise<SecretResolver>;
155
- declare function createOpCliSecretResolver(options: {
156
- readonly serviceAccountToken: string;
157
- }, dependencies?: Pick<CreateSecretResolverDependencies, 'execFileAsync'>): Promise<SecretResolver>;
158
- //#endregion
159
95
  //#region src/vm-adapter.d.ts
160
96
  declare const SYNTHETIC_DNS_IPV4_BENCHMARK = "198.18.0.1";
161
97
  declare const SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK = "::ffff:198.18.0.1";
@@ -192,7 +128,7 @@ interface ManagedVmDependencies {
192
128
  createVm(vmOptions: VMOptions): Promise<ManagedVmInstance>;
193
129
  createHttpHooks(options: {
194
130
  readonly allowedHosts: readonly string[];
195
- readonly secrets: Record<string, SecretSpec>;
131
+ readonly secrets: Record<string, MediatedSecretSpec>;
196
132
  readonly onRequest?: (request: Request) => Promise<Request | Response | void>;
197
133
  readonly onResponse?: (response: Response) => Promise<Response | void>;
198
134
  }): Pick<CreateHttpHooksResult, 'env' | 'httpHooks'>;
@@ -219,7 +155,7 @@ interface CreateVmOptions {
219
155
  readonly cpus: number;
220
156
  readonly rootfsMode: 'readonly' | 'memory' | 'cow';
221
157
  readonly allowedHosts: readonly string[];
222
- readonly secrets: Record<string, SecretSpec>;
158
+ readonly secrets: Record<string, MediatedSecretSpec>;
223
159
  readonly vfsMounts: Record<string, VfsMountSpec>;
224
160
  readonly tcpHosts?: Record<string, string>;
225
161
  readonly env?: Record<string, string>;
@@ -254,5 +190,5 @@ declare function writeFileAtomically(filePath: string, content: string, options?
254
190
  readonly mode?: number;
255
191
  }): Promise<void>;
256
192
  //#endregion
257
- export { type BuildConfig, BuildImageOptions, BuildImageResult, BuildOutput, CreatePinnedRealFsProviderOptions, CreateSecretResolverDependencies, CreateVmOptions, ExecFileOptions, ExecFileResult, ExecResult, IngressAccess, IngressRoute, ManagedVm, ManagedVmDependencies, ManagedVmInstance, PinnedRealFsRoot, PolicySources, ResolveGondolinMinimumZigVersionOptions, ResolvedVolume, RuntimeMountPolicyConfig, SYNTHETIC_DNS_IPV4_BENCHMARK, SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK, SecretRef, SecretResolver, SecretResolverClient, SecretSpec, SshAccess, TokenSource, VfsMountSpec, VolumeConfigEntry, WritableMountPolicy, assertPinnedRealFsRoot, buildImage, buildImageAssetFileNames, closePinnedRealFsRoot, compilePolicy, computeBuildFingerprint, computeEffectiveBuildFingerprint, createManagedVm, createOpCliSecretResolver, createPinnedRealFsProvider, createSecretResolver, dedupeStable, ensureVolumeDir, getDefaultBuildConfig, hasBuiltImageAssets, normalizeHostname, parseMinimumZigVersion, pinRealFsRoot, resolveGondolinMinimumZigVersion, resolveGondolinPackageJsonPath, resolveGondolinPackageSpec, resolveGuestMountPath, resolveServiceAccountToken, resolveVolumeDirs, validateRuntimeMountPolicy, validateWritableMount, writeFileAtomically };
193
+ export { type BuildConfig, BuildImageOptions, BuildImageResult, BuildOutput, CreatePinnedRealFsProviderOptions, CreateVmOptions, ExecResult, IngressAccess, IngressRoute, ManagedVm, ManagedVmDependencies, ManagedVmInstance, PinnedRealFsRoot, PolicySources, ResolveGondolinMinimumZigVersionOptions, ResolvedVolume, RuntimeMountPolicyConfig, SYNTHETIC_DNS_IPV4_BENCHMARK, SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK, SshAccess, VfsMountSpec, VolumeConfigEntry, WritableMountPolicy, assertPinnedRealFsRoot, buildImage, buildImageAssetFileNames, closePinnedRealFsRoot, compilePolicy, computeBuildFingerprint, computeEffectiveBuildFingerprint, createManagedVm, createPinnedRealFsProvider, dedupeStable, ensureVolumeDir, getDefaultBuildConfig, hasBuiltImageAssets, normalizeHostname, parseMinimumZigVersion, pinRealFsRoot, resolveGondolinMinimumZigVersion, resolveGondolinPackageJsonPath, resolveGondolinPackageSpec, resolveGuestMountPath, resolveVolumeDirs, validateRuntimeMountPolicy, validateWritableMount, writeFileAtomically };
258
194
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/build-pipeline.ts","../src/gondolin-package.ts","../src/mount-policy.ts","../src/pinned-realfs.ts","../src/policy-compiler.ts","../src/types.ts","../src/secret-resolver.ts","../src/vm-adapter.ts","../src/volume-manager.ts","../src/write-file-atomically.ts"],"mappings":";;;;UAaiB,iBAAA;EAAA,SACP,WAAA,EAAa,aAAA;EAAA,SACb,QAAA;EAFwB;;EAAA,SAKxB,SAAA;EAAA,SACA,SAAA;EAAA,SACA,gBAAA;EAAA,SACA,MAAA,GAAS,WAAA;AAAA;AAAA,UAGF,WAAA;EAChB,KAAA,CAAM,KAAA,WAAgB,UAAA;AAAA;AAAA,UAGN,gBAAA;EAAA,SACP,KAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;AAAA;AAAA,cAGG,wBAAA;AAAA,UAOH,yBAAA;EAAA,SACA,WAAA,IACR,WAAA,EAAa,aAAA,EACb,eAAA,UACA,SAAA,cACI,OAAA;EAAA,SACI,eAAA;AAAA;AAAA,iBAwCY,mBAAA,CAAoB,mBAAA,WAA8B,OAAA;AAAA,iBAqExD,uBAAA,CACf,WAAA,EAAa,aAAA,EACb,eAAA,WACA,gBAAA;AAAA,iBAUqB,gCA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uB,OAAA,CAAQ,aAAA;EACvD,aAAA,IAAiB,iBAAA;EACjB,gBAAA,CAAiB,MAAA,WAAiB,YAAA;EAClC,KAAA,IAAS,OAAA;AAAA;AAAA,iBAwKY,eAAA,CACrB,OAAA,EAAS,eAAA,EACT,YAAA,GAAc,qBAAA,GACZ,OAAA,CAAQ,SAAA;;;UCvRM,iBAAA;EAAA,SACP,SAAA;AAAA;AAAA,UAGO,cAAA;EAAA,SACP,OAAA;EAAA,SACA,SAAA;AAAA;AAAA,iBAGY,eAAA,CACrB,SAAA,UACA,aAAA,UACA,UAAA,WACE,OAAA;AAAA,iBAMmB,iBAAA,CACrB,SAAA,UACA,aAAA,UACA,OAAA,EAAS,QAAA,CAAS,MAAA,SAAe,iBAAA,KAC/B,OAAA,CAAQ,MAAA,SAAe,cAAA;;;iBCxBJ,mBAAA,CACrB,QAAA,UACA,OAAA,UACA,OAAA;EAAA,SACU,IAAA;AAAA,IAER,OAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/build-pipeline.ts","../src/gondolin-package.ts","../src/mount-policy.ts","../src/pinned-realfs.ts","../src/policy-compiler.ts","../src/vm-adapter.ts","../src/volume-manager.ts","../src/write-file-atomically.ts"],"mappings":";;;;UAaiB,iBAAA;EAAA,SACP,WAAA,EAAa,aAAA;EAAA,SACb,QAAA;EAFwB;;EAAA,SAKxB,SAAA;EAAA,SACA,SAAA;EAAA,SACA,gBAAA;EAAA,SACA,MAAA,GAAS,WAAA;AAAA;AAAA,UAGF,WAAA;EAChB,KAAA,CAAM,KAAA,WAAgB,UAAA;AAAA;AAAA,UAGN,gBAAA;EAAA,SACP,KAAA;EAAA,SACA,WAAA;EAAA,SACA,SAAA;AAAA;AAAA,cAGG,wBAAA;AAAA,UAOH,yBAAA;EAAA,SACA,WAAA,IACR,WAAA,EAAa,aAAA,EACb,eAAA,UACA,SAAA,cACI,OAAA;EAAA,SACI,eAAA;AAAA;AAAA,iBAwCY,mBAAA,CAAoB,mBAAA,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AA,WAAiB,YAAA;EAClC,KAAA,IAAS,OAAA;AAAA;AAAA,iBAwKY,eAAA,CACrB,OAAA,EAAS,eAAA,EACT,YAAA,GAAc,qBAAA,GACZ,OAAA,CAAQ,SAAA;;;UCvRM,iBAAA;EAAA,SACP,SAAA;AAAA;AAAA,UAGO,cAAA;EAAA,SACP,OAAA;EAAA,SACA,SAAA;AAAA;AAAA,iBAGY,eAAA,CACrB,SAAA,UACA,aAAA,UACA,UAAA,WACE,OAAA;AAAA,iBAMmB,iBAAA,CACrB,SAAA,UACA,aAAA,UACA,OAAA,EAAS,QAAA,CAAS,MAAA,SAAe,iBAAA,KAC/B,OAAA,CAAQ,MAAA,SAAe,cAAA;;;iBCxBJ,mBAAA,CACrB,QAAA,UACA,OAAA,UACA,OAAA;EAAA,SACU,IAAA;AAAA,IAER,OAAA"}
package/dist/index.js CHANGED
@@ -1,11 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
- import crypto, { randomUUID } from "node:crypto";
2
+ import crypto from "node:crypto";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import fs$1 from "node:fs";
7
- import { execFile } from "node:child_process";
8
- import { createClient } from "@1password/sdk";
9
7
  import { MemoryProvider, ReadonlyProvider, RealFSProvider, ShadowProvider, VM, createHttpHooks, createShadowPathPredicate, getDefaultBuildConfig } from "@earendil-works/gondolin";
10
8
  //#region src/rootfs-init-extra.ts
11
9
  const agentVmRootfsInitExtraScript = `# Generated by agent-vm.
@@ -354,425 +352,6 @@ function compilePolicy(sources) {
354
352
  ]);
355
353
  }
356
354
  //#endregion
357
- //#region src/secret-resolver.ts
358
- function formatUnknownError(error) {
359
- if (error instanceof AggregateError) {
360
- const childMessages = readAggregateErrorChildren(error).map(formatUnknownError);
361
- if (childMessages.length === 0) return error.message;
362
- const separator = error.message.endsWith(".") ? "" : ".";
363
- return `${error.message}${separator} Details: ${childMessages.join("; ")}`;
364
- }
365
- return error instanceof Error ? error.message : String(error);
366
- }
367
- var RedactedExecFileError = class extends Error {
368
- safeDetail;
369
- constructor(message, safeDetail, options) {
370
- super(message, options);
371
- this.safeDetail = safeDetail;
372
- this.name = "RedactedExecFileError";
373
- }
374
- };
375
- var OpInjectOutputError = class extends Error {
376
- constructor(message) {
377
- super(message);
378
- this.name = "OpInjectOutputError";
379
- }
380
- };
381
- function formatErrorMetadataValue(value) {
382
- if (typeof value === "number" || typeof value === "string") return String(value);
383
- }
384
- function readErrorCode(error) {
385
- if (!("code" in error)) return;
386
- return formatErrorMetadataValue(error.code);
387
- }
388
- function readErrorSignal(error) {
389
- if (!("signal" in error)) return;
390
- return formatErrorMetadataValue(error.signal);
391
- }
392
- function formatRedactedExecErrorDetail(error) {
393
- const exitCode = readErrorCode(error) ?? "unknown";
394
- const signal = readErrorSignal(error);
395
- return signal === void 0 ? `exit code ${exitCode}` : `exit code ${exitCode}, signal ${signal}`;
396
- }
397
- function createExecFileError(options) {
398
- if (options.redactErrorOutput) {
399
- const safeDetail = formatRedactedExecErrorDetail(options.error);
400
- return new RedactedExecFileError(`${options.command} failed: ${safeDetail}`, safeDetail);
401
- }
402
- const errorDetail = options.stderr.trim() || options.error.message;
403
- return /* @__PURE__ */ new Error(`${options.command} failed: ${errorDetail}`);
404
- }
405
- function formatStdinWriteErrorDetail(error) {
406
- const errorCode = readErrorCode(error);
407
- return errorCode === void 0 ? "stdin write failed" : `stdin write failed: ${errorCode}`;
408
- }
409
- function createStdinWriteError(command, error, redactErrorOutput) {
410
- if (redactErrorOutput) {
411
- const safeDetail = formatStdinWriteErrorDetail(error);
412
- return new RedactedExecFileError(`${command} failed writing stdin: ${safeDetail}`, safeDetail, { cause: error });
413
- }
414
- return new Error(`${command} failed writing stdin: ${formatUnknownError(error)}`, { cause: error });
415
- }
416
- function ensureMacOsForKeychain() {
417
- if (process.platform !== "darwin") throw new Error("Keychain token source is only supported on macOS. Use an env or op-cli token source on this platform so cmd-ts can surface a clear startup error.");
418
- }
419
- function execFileAsync(command, args, options) {
420
- return new Promise((resolve, reject) => {
421
- let hasSettled = false;
422
- const rejectOnce = (error) => {
423
- if (hasSettled) return;
424
- hasSettled = true;
425
- reject(error);
426
- };
427
- const resolveOnce = (result) => {
428
- if (hasSettled) return;
429
- hasSettled = true;
430
- resolve(result);
431
- };
432
- const child = execFile(command, [...args], {
433
- env: options?.env,
434
- timeout: 3e4
435
- }, (error, stdout, stderr) => {
436
- if (error) {
437
- rejectOnce(createExecFileError({
438
- command,
439
- error,
440
- redactErrorOutput: options?.redactErrorOutput,
441
- stderr
442
- }));
443
- return;
444
- }
445
- resolveOnce({
446
- stdout,
447
- stderr
448
- });
449
- });
450
- if (options?.input !== void 0) {
451
- if (!child.stdin) {
452
- child.kill();
453
- rejectOnce(/* @__PURE__ */ new Error(`${command} did not expose stdin for input`));
454
- return;
455
- }
456
- child.stdin.once("error", (error) => {
457
- child.kill();
458
- rejectOnce(createStdinWriteError(command, error, options.redactErrorOutput));
459
- });
460
- child.stdin.end(options.input);
461
- }
462
- });
463
- }
464
- const SAFE_IDENTIFIER_PATTERN = /^[\w.@-]+$/u;
465
- async function resolveServiceAccountToken(source, dependencies) {
466
- const exec = dependencies?.execFileAsync ?? execFileAsync;
467
- switch (source.type) {
468
- case "op-cli": {
469
- const token = (await exec("op", ["read", source.ref], { redactErrorOutput: true })).stdout.trim();
470
- if (token.length === 0) throw new Error("op-cli token resolution returned empty value");
471
- return token;
472
- }
473
- case "env": {
474
- const envVar = source.envVar ?? "OP_SERVICE_ACCOUNT_TOKEN";
475
- const token = process.env[envVar]?.trim();
476
- if (!token) throw new Error(`Environment variable ${envVar} is not set`);
477
- return token;
478
- }
479
- case "keychain": {
480
- ensureMacOsForKeychain();
481
- if (!SAFE_IDENTIFIER_PATTERN.test(source.service)) throw new Error("Keychain service name contains invalid characters");
482
- if (!SAFE_IDENTIFIER_PATTERN.test(source.account)) throw new Error("Keychain account name contains invalid characters");
483
- const token = (await exec("security", [
484
- "find-generic-password",
485
- "-s",
486
- source.service,
487
- "-a",
488
- source.account,
489
- "-w"
490
- ])).stdout.trim();
491
- if (token.length === 0) throw new Error("Keychain token resolution returned empty value");
492
- return token;
493
- }
494
- default: throw new Error(`Unsupported token source: ${JSON.stringify(source)}`);
495
- }
496
- }
497
- async function resolveSecretWithOpCli(serviceAccountToken, secretReference, exec) {
498
- return stripOpReadStdoutTerminator((await exec("op", ["read", secretReference], {
499
- env: createOpCliServiceAccountEnv(serviceAccountToken),
500
- redactErrorOutput: true
501
- })).stdout);
502
- }
503
- function stripOpReadStdoutTerminator(stdout) {
504
- if (stdout.endsWith("\r\n")) return stdout.slice(0, -2);
505
- if (stdout.endsWith("\n")) return stdout.slice(0, -1);
506
- return stdout;
507
- }
508
- const opCliProcessPlumbingEnvNames = [
509
- "APPDATA",
510
- "ALL_PROXY",
511
- "all_proxy",
512
- "COMSPEC",
513
- "HOME",
514
- "HTTP_PROXY",
515
- "http_proxy",
516
- "HTTPS_PROXY",
517
- "https_proxy",
518
- "LANG",
519
- "LC_ALL",
520
- "LC_CTYPE",
521
- "LOCALAPPDATA",
522
- "NO_PROXY",
523
- "no_proxy",
524
- "PATH",
525
- "SSL_CERT_DIR",
526
- "SSL_CERT_FILE",
527
- "TEMP",
528
- "TMP",
529
- "TMPDIR",
530
- "TZ",
531
- "USERPROFILE",
532
- "WINDIR",
533
- "XDG_CACHE_HOME",
534
- "XDG_CONFIG_HOME",
535
- "XDG_DATA_HOME",
536
- "XDG_RUNTIME_DIR"
537
- ];
538
- function createOpCliServiceAccountEnv(serviceAccountToken) {
539
- const env = {};
540
- for (const envName of opCliProcessPlumbingEnvNames) {
541
- const envValue = process.env[envName];
542
- if (envValue !== void 0) env[envName] = envValue;
543
- }
544
- env.OP_SERVICE_ACCOUNT_TOKEN = serviceAccountToken;
545
- return env;
546
- }
547
- const opInjectTemplateDelimiterPattern = /(?:\{\{|\}\})/u;
548
- function assertOpInjectTemplateSafeReference(entry) {
549
- if (!opInjectTemplateDelimiterPattern.test(entry.secretRef.ref) && !entry.secretRef.ref.includes("\0") && !entry.secretRef.ref.includes("\r") && !entry.secretRef.ref.includes("\n")) return;
550
- throw new OpInjectOutputError(`op inject template rejected unsafe 1Password reference for secret '${entry.secretName}'.`);
551
- }
552
- async function resolveAllSecretsWithOpCli(serviceAccountToken, refs, exec) {
553
- try {
554
- return await resolveAllSecretsWithOpInject(serviceAccountToken, refs, exec);
555
- } catch (error) {
556
- const sanitizedInjectError = sanitizeOpInjectError(error);
557
- try {
558
- return await resolveAllSecretsWithSerialOpReads(serviceAccountToken, refs, exec);
559
- } catch (readError) {
560
- if (readError instanceof AggregateError) throw createAggregateErrorWithCause({
561
- cause: readError,
562
- errors: [sanitizedInjectError, ...readAggregateErrorChildren(readError)],
563
- message: readError.message
564
- });
565
- throw createAggregateErrorWithCause({
566
- cause: readError,
567
- errors: [sanitizedInjectError, readError],
568
- message: "op inject and serial op read both failed."
569
- });
570
- }
571
- }
572
- }
573
- function sanitizeOpInjectError(error) {
574
- if (error instanceof RedactedExecFileError) return /* @__PURE__ */ new Error(`op inject failed before serial op read: ${error.safeDetail}`);
575
- if (error instanceof OpInjectOutputError) return /* @__PURE__ */ new Error(`op inject failed before serial op read: ${error.message}`);
576
- const errorType = error instanceof Error ? error.name : typeof error;
577
- return /* @__PURE__ */ new Error(`op inject failed before serial op read: ${errorType}`);
578
- }
579
- function readAggregateErrorChildren(error) {
580
- const errorChildren = error.errors;
581
- return Array.isArray(errorChildren) ? errorChildren : [];
582
- }
583
- function createAggregateErrorWithCause(options) {
584
- const aggregateError = new AggregateError(options.errors, options.message);
585
- aggregateError.cause = options.cause;
586
- return aggregateError;
587
- }
588
- function createFallbackStageError(stage, error) {
589
- return new Error(`${stage} failed before op CLI fallback: ${formatUnknownError(error)}`, { cause: error });
590
- }
591
- function createFallbackFailureError(options) {
592
- if (options.fallbackError instanceof AggregateError) return createAggregateErrorWithCause({
593
- cause: options.fallbackError,
594
- errors: [options.stageError, ...readAggregateErrorChildren(options.fallbackError)],
595
- message: options.fallbackError.message
596
- });
597
- return createAggregateErrorWithCause({
598
- cause: options.fallbackError,
599
- errors: [options.stageError, options.fallbackError],
600
- message: options.message
601
- });
602
- }
603
- function opInjectStartMarker(markerId) {
604
- return `agent-vm-op-inject-start:${markerId}`;
605
- }
606
- function opInjectEndMarker(markerId) {
607
- return `agent-vm-op-inject-end:${markerId}`;
608
- }
609
- function createOpInjectEntries(refs) {
610
- return Object.entries(refs).map(([secretName, secretRef]) => ({
611
- markerId: randomUUID(),
612
- secretName,
613
- secretRef
614
- }));
615
- }
616
- function buildOpInjectTemplate(entries) {
617
- return entries.map((entry) => {
618
- assertOpInjectTemplateSafeReference(entry);
619
- return [
620
- opInjectStartMarker(entry.markerId),
621
- `{{ ${entry.secretRef.ref} }}`,
622
- opInjectEndMarker(entry.markerId)
623
- ].join("\n");
624
- }).join("\n");
625
- }
626
- function findUniqueOpInjectMarker(options) {
627
- const markerIndex = options.output.indexOf(options.marker);
628
- if (markerIndex === -1) throw new OpInjectOutputError(`op inject output omitted ${options.markerDescription} marker for secret '${options.secretName}' (${options.secretReference}).`);
629
- if (options.output.indexOf(options.marker, markerIndex + options.marker.length) !== -1) throw new OpInjectOutputError(`op inject output for secret '${options.secretName}' (${options.secretReference}) contained repeated ${options.markerDescription} marker.`);
630
- return markerIndex;
631
- }
632
- function extractInjectedSecret(options) {
633
- const startToken = `${opInjectStartMarker(options.entry.markerId)}\n`;
634
- const endToken = `\n${opInjectEndMarker(options.entry.markerId)}`;
635
- const secretStartIndex = findUniqueOpInjectMarker({
636
- marker: startToken,
637
- markerDescription: "start",
638
- output: options.output,
639
- secretName: options.entry.secretName,
640
- secretReference: options.entry.secretRef.ref
641
- }) + startToken.length;
642
- const secretEndIndex = findUniqueOpInjectMarker({
643
- marker: endToken,
644
- markerDescription: "end",
645
- output: options.output,
646
- secretName: options.entry.secretName,
647
- secretReference: options.entry.secretRef.ref
648
- });
649
- return options.output.slice(secretStartIndex, secretEndIndex);
650
- }
651
- function mapOpInjectOutput(entries, output) {
652
- return Object.fromEntries(entries.map((entry) => [entry.secretName, extractInjectedSecret({
653
- entry,
654
- output
655
- })]));
656
- }
657
- async function resolveAllSecretsWithOpInject(serviceAccountToken, refs, exec) {
658
- const entries = createOpInjectEntries(refs);
659
- if (entries.length === 0) return {};
660
- return mapOpInjectOutput(entries, (await exec("op", [
661
- "inject",
662
- "--in-file",
663
- "/dev/stdin"
664
- ], {
665
- env: createOpCliServiceAccountEnv(serviceAccountToken),
666
- input: buildOpInjectTemplate(entries),
667
- redactErrorOutput: true
668
- })).stdout);
669
- }
670
- async function resolveAllSecretsWithSerialOpReads(serviceAccountToken, refs, exec) {
671
- const resolvedSecrets = {};
672
- const failures = [];
673
- for (const [secretName, secretRef] of Object.entries(refs)) try {
674
- resolvedSecrets[secretName] = await resolveSecretWithOpCli(serviceAccountToken, secretRef.ref, exec);
675
- } catch (error) {
676
- failures.push(new Error(`Failed to resolve secret '${secretName}' from '${secretRef.ref}' via op read: ${formatUnknownError(error)}`, { cause: error }));
677
- }
678
- if (failures.length > 0) throw new AggregateError(failures, `Failed to resolve ${String(failures.length)} secret(s) via op read.`);
679
- return resolvedSecrets;
680
- }
681
- function formatResolveReferenceError(error) {
682
- return "message" in error && typeof error.message === "string" ? `${error.type}: ${error.message}` : error.type;
683
- }
684
- function readSdkBatchSecret(options) {
685
- const individualResponse = options.response.individualResponses[options.secretReference];
686
- if (!individualResponse) throw new Error(`1Password SDK resolveAll response omitted '${options.secretName}' (${options.secretReference}).`);
687
- if (individualResponse.content !== void 0) return individualResponse.content.secret;
688
- if (individualResponse.error !== void 0) throw new Error(`1Password SDK resolveAll failed for '${options.secretName}' (${options.secretReference}): ${formatResolveReferenceError(individualResponse.error)}`);
689
- throw new Error(`1Password SDK resolveAll returned neither content nor error for '${options.secretName}' (${options.secretReference}).`);
690
- }
691
- function mapSdkResolveAllResponse(refs, response) {
692
- return Object.fromEntries(Object.entries(refs).map(([secretName, secretRef]) => [secretName, readSdkBatchSecret({
693
- response,
694
- secretName,
695
- secretReference: secretRef.ref
696
- })]));
697
- }
698
- async function createSecretResolver(options, dependencies = {}) {
699
- const exec = dependencies.execFileAsync ?? execFileAsync;
700
- try {
701
- const client = await (dependencies.createClient ?? createClient)({
702
- auth: options.serviceAccountToken,
703
- integrationName: dependencies.integrationName ?? "agent-vm",
704
- integrationVersion: dependencies.integrationVersion ?? "0.0.1"
705
- });
706
- return {
707
- resolve: async (ref) => {
708
- try {
709
- return await client.secrets.resolve(ref.ref);
710
- } catch (error) {
711
- const sdkResolveError = createFallbackStageError("1Password SDK resolve", error);
712
- try {
713
- return await resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec);
714
- } catch (fallbackError) {
715
- throw createFallbackFailureError({
716
- fallbackError,
717
- message: "1Password SDK resolve and op CLI fallback both failed.",
718
- stageError: sdkResolveError
719
- });
720
- }
721
- }
722
- },
723
- resolveAll: async (refs) => {
724
- try {
725
- return mapSdkResolveAllResponse(refs, await client.secrets.resolveAll(Object.values(refs).map((secretRef) => secretRef.ref)));
726
- } catch (error) {
727
- const sdkResolveAllError = createFallbackStageError("1Password SDK resolveAll", error);
728
- try {
729
- return await resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec);
730
- } catch (fallbackError) {
731
- throw createFallbackFailureError({
732
- fallbackError,
733
- message: "1Password SDK resolveAll and op CLI fallback both failed.",
734
- stageError: sdkResolveAllError
735
- });
736
- }
737
- }
738
- }
739
- };
740
- } catch (error) {
741
- const sdkClientCreationError = createFallbackStageError("1Password SDK client creation", error);
742
- return {
743
- resolve: async (ref) => {
744
- try {
745
- return await resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec);
746
- } catch (fallbackError) {
747
- throw createFallbackFailureError({
748
- fallbackError,
749
- message: "1Password SDK client creation and op CLI fallback both failed.",
750
- stageError: sdkClientCreationError
751
- });
752
- }
753
- },
754
- resolveAll: async (refs) => {
755
- try {
756
- return await resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec);
757
- } catch (fallbackError) {
758
- throw createFallbackFailureError({
759
- fallbackError,
760
- message: "1Password SDK client creation and op CLI fallback both failed.",
761
- stageError: sdkClientCreationError
762
- });
763
- }
764
- }
765
- };
766
- }
767
- }
768
- async function createOpCliSecretResolver(options, dependencies = {}) {
769
- const exec = dependencies.execFileAsync ?? execFileAsync;
770
- return {
771
- resolve: async (ref) => await resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec),
772
- resolveAll: async (refs) => await resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec)
773
- };
774
- }
775
- //#endregion
776
355
  //#region src/vm-adapter.ts
777
356
  const SYNTHETIC_DNS_IPV4_BENCHMARK = "198.18.0.1";
778
357
  const SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK = "::ffff:198.18.0.1";
@@ -962,6 +541,6 @@ async function writeFileAtomically(filePath, content, options = {}) {
962
541
  }
963
542
  }
964
543
  //#endregion
965
- export { SYNTHETIC_DNS_IPV4_BENCHMARK, SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK, assertPinnedRealFsRoot, buildImage, buildImageAssetFileNames, closePinnedRealFsRoot, compilePolicy, computeBuildFingerprint, computeEffectiveBuildFingerprint, createManagedVm, createOpCliSecretResolver, createPinnedRealFsProvider, createSecretResolver, dedupeStable, ensureVolumeDir, getDefaultBuildConfig, hasBuiltImageAssets, normalizeHostname, parseMinimumZigVersion, pinRealFsRoot, resolveGondolinMinimumZigVersion, resolveGondolinPackageJsonPath, resolveGondolinPackageSpec, resolveGuestMountPath, resolveServiceAccountToken, resolveVolumeDirs, validateRuntimeMountPolicy, validateWritableMount, writeFileAtomically };
544
+ export { SYNTHETIC_DNS_IPV4_BENCHMARK, SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK, assertPinnedRealFsRoot, buildImage, buildImageAssetFileNames, closePinnedRealFsRoot, compilePolicy, computeBuildFingerprint, computeEffectiveBuildFingerprint, createManagedVm, createPinnedRealFsProvider, dedupeStable, ensureVolumeDir, getDefaultBuildConfig, hasBuiltImageAssets, normalizeHostname, parseMinimumZigVersion, pinRealFsRoot, resolveGondolinMinimumZigVersion, resolveGondolinPackageJsonPath, resolveGondolinPackageSpec, resolveGuestMountPath, resolveVolumeDirs, validateRuntimeMountPolicy, validateWritableMount, writeFileAtomically };
966
545
 
967
546
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fs"],"sources":["../src/rootfs-init-extra.ts","../src/build-pipeline.ts","../src/gondolin-package.ts","../src/mount-policy.ts","../src/pinned-realfs.ts","../src/policy-compiler.ts","../src/secret-resolver.ts","../src/vm-adapter.ts","../src/volume-manager.ts","../src/write-file-atomically.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { BuildConfig } from '@earendil-works/gondolin';\n\nexport const agentVmRootfsInitExtraScript = `# Generated by agent-vm.\n# Gondolin mounts devtmpfs over /dev at boot, so Docker-image /dev symlinks are hidden.\nmkdir -p /dev\nln -sfn /proc/self/fd /dev/fd 2>/dev/null || true\nln -sfn /proc/self/fd/0 /dev/stdin 2>/dev/null || true\nln -sfn /proc/self/fd/1 /dev/stdout 2>/dev/null || true\nln -sfn /proc/self/fd/2 /dev/stderr 2>/dev/null || true\nif [ ! -e /dev/ptmx ] && [ -e /dev/pts/ptmx ]; then\n ln -sfn pts/ptmx /dev/ptmx 2>/dev/null || true\nfi\n`;\n\ninterface PrepareRootfsInitExtraOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly imagePath: string;\n\treadonly rootfsInitExtraContent: string;\n}\n\ninterface ResolveRootfsInitExtraOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly configDir?: string;\n}\n\nexport interface ResolvedRootfsInitExtra {\n\treadonly content: string;\n\treadonly fingerprintInput: {\n\t\treadonly agentVmRootfsInitExtra: string;\n\t\treadonly deploymentRootfsInitExtra?: string;\n\t};\n}\n\nfunction resolveBuildConfigPath(filePath: string, configDir: string | undefined): string {\n\treturn path.isAbsolute(filePath) ? filePath : path.resolve(configDir ?? process.cwd(), filePath);\n}\n\nasync function readExistingRootfsInitExtra(\n\tbuildConfig: BuildConfig,\n\tconfigDir: string | undefined,\n): Promise<string | undefined> {\n\tconst existingRootfsInitExtra = buildConfig.init?.rootfsInitExtra;\n\tif (!existingRootfsInitExtra) {\n\t\treturn undefined;\n\t}\n\n\tconst resolvedRootfsInitExtra = resolveBuildConfigPath(existingRootfsInitExtra, configDir);\n\ttry {\n\t\treturn await fs.readFile(resolvedRootfsInitExtra, 'utf8');\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(\n\t\t\t`Failed to read Gondolin rootfs init extra '${resolvedRootfsInitExtra}': ${message}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nfunction composeRootfsInitExtra(existingRootfsInitExtra: string | undefined): string {\n\treturn existingRootfsInitExtra\n\t\t? `${agentVmRootfsInitExtraScript.trimEnd()}\\n\\n${existingRootfsInitExtra}`\n\t\t: agentVmRootfsInitExtraScript;\n}\n\nexport async function resolveRootfsInitExtra(\n\toptions: ResolveRootfsInitExtraOptions,\n): Promise<ResolvedRootfsInitExtra> {\n\tconst existingRootfsInitExtra = await readExistingRootfsInitExtra(\n\t\toptions.buildConfig,\n\t\toptions.configDir,\n\t);\n\n\treturn {\n\t\tcontent: composeRootfsInitExtra(existingRootfsInitExtra),\n\t\tfingerprintInput: {\n\t\t\tagentVmRootfsInitExtra: agentVmRootfsInitExtraScript,\n\t\t\t...(existingRootfsInitExtra === undefined\n\t\t\t\t? {}\n\t\t\t\t: { deploymentRootfsInitExtra: existingRootfsInitExtra }),\n\t\t},\n\t};\n}\n\nexport async function prepareBuildConfigWithAgentVmRootfsInitExtra(\n\toptions: PrepareRootfsInitExtraOptions,\n): Promise<BuildConfig> {\n\tconst rootfsInitExtraPath = path.join(options.imagePath, 'agent-vm-rootfs-init-extra.sh');\n\n\tawait fs.writeFile(rootfsInitExtraPath, options.rootfsInitExtraContent, {\n\t\tencoding: 'utf8',\n\t\tmode: 0o755,\n\t});\n\n\treturn {\n\t\t...options.buildConfig,\n\t\tinit: {\n\t\t\t...options.buildConfig.init,\n\t\t\trootfsInitExtra: rootfsInitExtraPath,\n\t\t},\n\t};\n}\n","import crypto from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { BuildConfig, BuildOptions } from '@earendil-works/gondolin';\n\nimport {\n\tprepareBuildConfigWithAgentVmRootfsInitExtra,\n\tresolveRootfsInitExtra,\n} from './rootfs-init-extra.js';\n\nexport type { BuildConfig } from '@earendil-works/gondolin';\n\nexport interface BuildImageOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly cacheDir: string;\n\t/** Directory to resolve relative paths in buildConfig (e.g. postBuild.copy.src).\n\t * Defaults to process.cwd() if not provided. */\n\treadonly configDir?: string;\n\treadonly fullReset?: boolean;\n\treadonly fingerprintInput?: unknown;\n\treadonly output?: BuildOutput;\n}\n\nexport interface BuildOutput {\n\twrite(chunk: string | Uint8Array): boolean;\n}\n\nexport interface BuildImageResult {\n\treadonly built: boolean;\n\treadonly fingerprint: string;\n\treadonly imagePath: string;\n}\n\nexport const buildImageAssetFileNames = [\n\t'manifest.json',\n\t'rootfs.ext4',\n\t'initramfs.cpio.lz4',\n\t'vmlinuz-virt',\n] as const;\n\ninterface BuildPipelineDependencies {\n\treadonly buildAssets?: (\n\t\tbuildConfig: BuildConfig,\n\t\toutputDirectory: string,\n\t\tconfigDir?: string,\n\t) => Promise<unknown>;\n\treadonly gondolinVersion?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction stableSerialize(value: unknown): string {\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((entry) => stableSerialize(entry)).join(',')}]`;\n\t}\n\n\tif (isRecord(value)) {\n\t\tconst objectEntries = Object.entries(value)\n\t\t\t.filter(([, entryValue]) => entryValue !== undefined)\n\t\t\t.toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));\n\t\treturn `{${objectEntries\n\t\t\t.map(([entryKey, entryValue]) => `${JSON.stringify(entryKey)}:${stableSerialize(entryValue)}`)\n\t\t\t.join(',')}}`;\n\t}\n\n\treturn JSON.stringify(value);\n}\n\nfunction isMissingPathError(error: unknown): boolean {\n\treturn typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (!isMissingPathError(error)) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nexport async function hasBuiltImageAssets(outputDirectoryPath: string): Promise<boolean> {\n\tfor (const fileName of buildImageAssetFileNames) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each missing file points at the same image generation\n\t\tif (!(await pathExists(path.join(outputDirectoryPath, fileName)))) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nasync function loadBuildAssets(): Promise<\n\t(buildConfig: BuildConfig, outputDirectory: string, configDir?: string) => Promise<unknown>\n> {\n\tconst gondolinModule = await import('@earendil-works/gondolin');\n\treturn async (\n\t\tbuildConfig: BuildConfig,\n\t\toutputDirectory: string,\n\t\tconfigDir?: string,\n\t): Promise<unknown> =>\n\t\tawait gondolinModule.buildAssets(buildConfig, {\n\t\t\toutputDir: outputDirectory,\n\t\t\tverbose: false,\n\t\t\t...(configDir ? { configDir } : {}),\n\t\t} satisfies BuildOptions);\n}\n\nfunction createRedirectedWrite(output: BuildOutput): typeof process.stderr.write {\n\treturn ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tconst writeCallback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n\t\tconst wrote = output.write(chunk);\n\t\twriteCallback?.();\n\t\treturn wrote;\n\t}) as typeof process.stderr.write;\n}\n\nasync function withCapturedBuildOutput<TResult>(\n\toutput: BuildOutput | undefined,\n\tfn: () => Promise<TResult>,\n): Promise<TResult> {\n\tif (!output) {\n\t\treturn await fn();\n\t}\n\n\tconst originalStderrWrite = process.stderr.write.bind(process.stderr);\n\tconst originalStdoutWrite = process.stdout.write.bind(process.stdout);\n\tconst originalCi = process.env.CI;\n\tconst redirectedWrite = createRedirectedWrite(output);\n\n\tprocess.stderr.write = redirectedWrite;\n\tprocess.stdout.write = redirectedWrite;\n\tprocess.env.CI = 'true';\n\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tprocess.stderr.write = originalStderrWrite;\n\t\tprocess.stdout.write = originalStdoutWrite;\n\t\tif (originalCi === undefined) {\n\t\t\tdelete process.env.CI;\n\t\t} else {\n\t\t\tprocess.env.CI = originalCi;\n\t\t}\n\t}\n}\n\nexport function computeBuildFingerprint(\n\tbuildConfig: BuildConfig,\n\tgondolinVersion: string = 'unknown',\n\tfingerprintInput?: unknown,\n): string {\n\tconst payload =\n\t\tfingerprintInput === undefined\n\t\t\t? `${stableSerialize(buildConfig)}|${gondolinVersion}`\n\t\t\t: `${stableSerialize(buildConfig)}|${gondolinVersion}|${stableSerialize(fingerprintInput)}`;\n\n\treturn crypto.createHash('sha256').update(payload).digest('hex').slice(0, 16);\n}\n\nexport async function computeEffectiveBuildFingerprint(options: {\n\treadonly buildConfig: BuildConfig;\n\treadonly configDir?: string;\n\treadonly fingerprintInput?: unknown;\n\treadonly gondolinVersion?: string;\n}): Promise<{\n\treadonly fingerprint: string;\n\treadonly rootfsInitExtraContent: string;\n}> {\n\tconst resolvedRootfsInitExtra = await resolveRootfsInitExtra({\n\t\tbuildConfig: options.buildConfig,\n\t\t...(options.configDir ? { configDir: options.configDir } : {}),\n\t});\n\tconst fingerprint = computeBuildFingerprint(options.buildConfig, options.gondolinVersion, {\n\t\tagentVmRootfsInitExtra: resolvedRootfsInitExtra.fingerprintInput,\n\t\t...(options.fingerprintInput === undefined\n\t\t\t? {}\n\t\t\t: { callerFingerprintInput: options.fingerprintInput }),\n\t});\n\n\treturn {\n\t\tfingerprint,\n\t\trootfsInitExtraContent: resolvedRootfsInitExtra.content,\n\t};\n}\n\nexport async function buildImage(\n\toptions: BuildImageOptions,\n\tdependencies: BuildPipelineDependencies = {},\n): Promise<BuildImageResult> {\n\tconst effectiveBuildFingerprint = await computeEffectiveBuildFingerprint({\n\t\tbuildConfig: options.buildConfig,\n\t\t...(options.configDir ? { configDir: options.configDir } : {}),\n\t\t...(options.fingerprintInput === undefined\n\t\t\t? {}\n\t\t\t: { fingerprintInput: options.fingerprintInput }),\n\t\t...(dependencies.gondolinVersion ? { gondolinVersion: dependencies.gondolinVersion } : {}),\n\t});\n\tconst fingerprint = effectiveBuildFingerprint.fingerprint;\n\tconst imagePath = path.join(options.cacheDir, fingerprint);\n\n\tif (options.fullReset) {\n\t\tawait fs.rm(imagePath, { recursive: true, force: true });\n\t}\n\n\tif (await hasBuiltImageAssets(imagePath)) {\n\t\treturn {\n\t\t\tbuilt: false,\n\t\t\tfingerprint,\n\t\t\timagePath,\n\t\t};\n\t}\n\n\tawait fs.mkdir(imagePath, { recursive: true });\n\tconst buildAssetsImplementation = dependencies.buildAssets ?? (await loadBuildAssets());\n\tconst effectiveBuildConfig = await prepareBuildConfigWithAgentVmRootfsInitExtra({\n\t\tbuildConfig: options.buildConfig,\n\t\timagePath,\n\t\trootfsInitExtraContent: effectiveBuildFingerprint.rootfsInitExtraContent,\n\t});\n\tawait withCapturedBuildOutput(options.output, async () => {\n\t\tawait buildAssetsImplementation(effectiveBuildConfig, imagePath, options.configDir);\n\t});\n\n\tif (!(await hasBuiltImageAssets(imagePath))) {\n\t\tthrow new Error(`Expected Gondolin assets to be written to ${imagePath}.`);\n\t}\n\n\treturn {\n\t\tbuilt: true,\n\t\tfingerprint,\n\t\timagePath,\n\t};\n}\n","import fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nconst requireFromHere = createRequire(import.meta.url);\n\nconst gondolinPackageJsonSchema = z.object({\n\tversion: z.string().min(1),\n});\n\nfunction isMissingFileError(error: unknown): boolean {\n\treturn typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nfunction getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nexport function parseMinimumZigVersion(rawContents: string): string {\n\tconst match = rawContents.match(/\\.minimum_zig_version\\s*=\\s*\"([^\"]*)\"/u);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t'minimum_zig_version declaration not found. Expected a line like `.minimum_zig_version = \"0.15.2\"`.',\n\t\t);\n\t}\n\n\tconst version = match[1];\n\tif (!version) {\n\t\tthrow new Error('minimum_zig_version is empty.');\n\t}\n\treturn version;\n}\n\nexport function resolveGondolinPackageJsonPath(): string {\n\treturn requireFromHere.resolve('@earendil-works/gondolin/package.json');\n}\n\nexport async function resolveGondolinPackageSpec(): Promise<string> {\n\tconst packageJsonPath = resolveGondolinPackageJsonPath();\n\tconst parsed: unknown = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n\tconst packageJson = gondolinPackageJsonSchema.parse(parsed);\n\treturn `@earendil-works/gondolin@${packageJson.version}`;\n}\n\nexport interface ResolveGondolinMinimumZigVersionOptions {\n\treadonly buildZigZonPath?: string;\n}\n\nasync function resolveDefaultBuildZigZonPath(): Promise<string> {\n\tconst packageJsonPath = resolveGondolinPackageJsonPath();\n\treturn path.join(path.dirname(packageJsonPath), 'dist', 'guest', 'build.zig.zon');\n}\n\nexport async function resolveGondolinMinimumZigVersion(\n\toptions: ResolveGondolinMinimumZigVersionOptions = {},\n): Promise<string> {\n\tconst zonPath = options.buildZigZonPath ?? (await resolveDefaultBuildZigZonPath());\n\tlet rawContents: string;\n\ttry {\n\t\trawContents = await fs.readFile(zonPath, 'utf8');\n\t} catch (error) {\n\t\tif (isMissingFileError(error)) {\n\t\t\tthrow new Error(`Missing Gondolin build.zig.zon at '${zonPath}'.`, { cause: error });\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Failed to read Gondolin build.zig.zon at '${zonPath}': ${getErrorMessage(error)}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\n\ttry {\n\t\treturn parseMinimumZigVersion(rawContents);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to parse Gondolin build.zig.zon at '${zonPath}': ${getErrorMessage(error)}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nconst AUTH_GUEST_PATH_PREFIXES = [\n\t'/home/agent/.aws',\n\t'/home/agent/.claude',\n\t'/home/agent/.codex',\n\t'/home/agent/.gemini',\n\t'/home/openclaw/.aws',\n\t'/home/openclaw/.claude',\n\t'/home/openclaw/.codex',\n\t'/home/openclaw/.gemini',\n\t'/home/openclaw/.openclaw',\n] as const;\n\nexport interface WritableMountPolicy {\n\treadonly allowAuthWrite: boolean;\n\treadonly writableAllowedGuestPrefixes: readonly string[];\n}\n\nexport interface RuntimeMountPolicyConfig {\n\treadonly extraMounts: Readonly<Record<string, string>>;\n\treadonly mountControls: WritableMountPolicy;\n}\n\nfunction resolveAuthHostPrefixes(hostHome: string): readonly string[] {\n\treturn [\n\t\tpath.join(hostHome, '.aws'),\n\t\tpath.join(hostHome, '.claude'),\n\t\tpath.join(hostHome, '.codex'),\n\t\tpath.join(hostHome, '.gemini'),\n\t];\n}\n\nexport function resolveGuestMountPath(guestPath: string, workDir: string): string {\n\tif (path.isAbsolute(guestPath)) {\n\t\treturn path.resolve(guestPath);\n\t}\n\n\treturn path.resolve(workDir, guestPath);\n}\n\nfunction isPathWithinPrefix(candidatePath: string, prefixPath: string): boolean {\n\tconst relativePath = path.relative(prefixPath, candidatePath);\n\treturn relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));\n}\n\nasync function normalizeHostPath(hostPath: string): Promise<string> {\n\tconst resolvedHostPath = path.resolve(hostPath);\n\n\ttry {\n\t\treturn await fs.realpath(resolvedHostPath);\n\t} catch {\n\t\treturn resolvedHostPath;\n\t}\n}\n\nfunction pathsOverlap(candidatePath: string, protectedPath: string): boolean {\n\treturn (\n\t\tisPathWithinPrefix(candidatePath, protectedPath) ||\n\t\tisPathWithinPrefix(protectedPath, candidatePath)\n\t);\n}\n\nexport function validateWritableMount(\n\tguestPath: string,\n\tpolicy: WritableMountPolicy,\n\toptions: { readonly workDir: string },\n): void {\n\tconst resolvedGuestPath = resolveGuestMountPath(guestPath, options.workDir);\n\tconst resolvedAllowedPrefixes = policy.writableAllowedGuestPrefixes.map((allowedPrefix) =>\n\t\tresolveGuestMountPath(allowedPrefix, options.workDir),\n\t);\n\n\tconst isAllowedGuestPath = resolvedAllowedPrefixes.some((allowedPrefix) =>\n\t\tisPathWithinPrefix(resolvedGuestPath, allowedPrefix),\n\t);\n\tif (!isAllowedGuestPath) {\n\t\tthrow new Error(\n\t\t\t`Writable mount guest path '${resolvedGuestPath}' is outside writable allowlist [${resolvedAllowedPrefixes.join(', ')}].`,\n\t\t);\n\t}\n\n\tif (!policy.allowAuthWrite) {\n\t\tconst targetsProtectedGuestPath = AUTH_GUEST_PATH_PREFIXES.some((authPrefix) =>\n\t\t\tisPathWithinPrefix(resolvedGuestPath, authPrefix),\n\t\t);\n\t\tif (targetsProtectedGuestPath) {\n\t\t\tthrow new Error(\n\t\t\t\t`Writable mount guest path '${resolvedGuestPath}' targets an auth mount path. Set mountControls.allowAuthWrite=true to permit auth writes.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport async function validateRuntimeMountPolicy(\n\tconfig: RuntimeMountPolicyConfig,\n\toptions: { readonly hostHome: string; readonly workDir: string },\n): Promise<void> {\n\tconst mountEntries = Object.entries(config.extraMounts);\n\tfor (const [guestPath] of mountEntries) {\n\t\tvalidateWritableMount(guestPath, config.mountControls, options);\n\t}\n\n\tif (config.mountControls.allowAuthWrite) {\n\t\treturn;\n\t}\n\n\tconst absoluteHostMountEntries = mountEntries.filter(([, hostPath]) => path.isAbsolute(hostPath));\n\tconst [protectedHostPaths, writableHostPaths] = await Promise.all([\n\t\tPromise.all(\n\t\t\tresolveAuthHostPrefixes(options.hostHome).map(\n\t\t\t\tasync (authHostPrefix) => await normalizeHostPath(authHostPrefix),\n\t\t\t),\n\t\t),\n\t\tPromise.all(\n\t\t\tabsoluteHostMountEntries.map(async ([, hostPath]) => await normalizeHostPath(hostPath)),\n\t\t),\n\t]);\n\n\tfor (const resolvedWritableHostPath of writableHostPaths) {\n\t\tconst overlapsProtectedHostPath = protectedHostPaths.some((authHostPrefix) =>\n\t\t\tpathsOverlap(resolvedWritableHostPath, authHostPrefix),\n\t\t);\n\n\t\tif (overlapsProtectedHostPath) {\n\t\t\tthrow new Error(\n\t\t\t\t`Writable host path '${resolvedWritableHostPath}' targets an auth host directory. Set mountControls.allowAuthWrite=true to permit auth writes.`,\n\t\t\t);\n\t\t}\n\t}\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { VirtualProvider } from '@earendil-works/gondolin';\n\nexport interface PinnedRealFsRoot {\n\treadonly hostPath: string;\n\treadonly realPath: string;\n\treadonly fd: number;\n\treadonly device: number;\n\treadonly inode: number;\n}\n\nexport interface CreatePinnedRealFsProviderOptions {\n\treadonly root: PinnedRealFsRoot;\n\treadonly createRealFsProvider: (hostPath: string) => VirtualProvider;\n}\n\nfunction formatRootIdentity(root: PinnedRealFsRoot): string {\n\treturn `${root.device}:${root.inode}`;\n}\n\nfunction openDirectoryNoFollow(candidatePath: string): number {\n\treturn fs.openSync(\n\t\tcandidatePath,\n\t\tfs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,\n\t);\n}\n\nexport function pinRealFsRoot(hostPath: string): PinnedRealFsRoot {\n\tif (!hostPath || !path.isAbsolute(hostPath)) {\n\t\tthrow new Error(`Pinned RealFS root must be a non-empty absolute path: ${hostPath}`);\n\t}\n\n\tconst resolvedHostPath = path.resolve(hostPath);\n\tconst fd = openDirectoryNoFollow(resolvedHostPath);\n\ttry {\n\t\tconst stats = fs.fstatSync(fd);\n\t\tif (!stats.isDirectory()) {\n\t\t\tthrow new Error(`Pinned RealFS root is not a directory: ${resolvedHostPath}`);\n\t\t}\n\t\tconst realPath = fs.realpathSync(resolvedHostPath);\n\t\tconst realPathStats = fs.statSync(realPath);\n\t\tif (realPathStats.dev !== stats.dev || realPathStats.ino !== stats.ino) {\n\t\t\tthrow new Error(\n\t\t\t\t`Pinned RealFS root changed while opening: ${resolvedHostPath} opened ${stats.dev}:${stats.ino} but resolved to ${realPathStats.dev}:${realPathStats.ino}`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tdevice: stats.dev,\n\t\t\tfd,\n\t\t\thostPath: resolvedHostPath,\n\t\t\tinode: stats.ino,\n\t\t\trealPath,\n\t\t};\n\t} catch (error) {\n\t\tfs.closeSync(fd);\n\t\tthrow error;\n\t}\n}\n\nexport function closePinnedRealFsRoot(root: PinnedRealFsRoot): void {\n\tfs.closeSync(root.fd);\n}\n\nexport function assertPinnedRealFsRoot(root: PinnedRealFsRoot): void {\n\tconst pinnedStats = fs.fstatSync(root.fd);\n\tconst currentStats = fs.statSync(root.realPath);\n\tif (\n\t\tpinnedStats.dev !== root.device ||\n\t\tpinnedStats.ino !== root.inode ||\n\t\tcurrentStats.dev !== root.device ||\n\t\tcurrentStats.ino !== root.inode\n\t) {\n\t\tthrow new Error(\n\t\t\t`Pinned RealFS root changed before mount access: ${root.realPath} expected ${formatRootIdentity(root)} got ${currentStats.dev}:${currentStats.ino}`,\n\t\t);\n\t}\n}\n\ntype ProviderMethod = (...args: unknown[]) => unknown;\n\n/* oxlint-disable typescript-eslint/no-unsafe-type-assertion -- Reflect.get()\n loses the method signature from Gondolin's VirtualProvider union. The proxy\n keeps the same provider object and only wraps callable properties with the\n pinned-root assertion. */\nexport function createPinnedRealFsProvider(\n\toptions: CreatePinnedRealFsProviderOptions,\n): VirtualProvider {\n\tassertPinnedRealFsRoot(options.root);\n\tconst provider = options.createRealFsProvider(options.root.realPath);\n\n\treturn new Proxy(provider, {\n\t\tget(target: VirtualProvider, property: string | symbol, receiver: unknown): unknown {\n\t\t\tconst value = Reflect.get(target, property, receiver) as unknown;\n\t\t\tif (typeof value !== 'function') {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\treturn (...methodArguments: readonly unknown[]): unknown => {\n\t\t\t\tassertPinnedRealFsRoot(options.root);\n\t\t\t\treturn Reflect.apply(value as ProviderMethod, target, methodArguments);\n\t\t\t};\n\t\t},\n\t});\n}\n/* oxlint-enable typescript-eslint/no-unsafe-type-assertion */\n","export interface PolicySources {\n\treadonly base: readonly string[];\n\treadonly profile: readonly string[];\n\treadonly extra: readonly string[];\n}\n\nexport function normalizeHostname(rawHostname: string): string {\n\treturn rawHostname.trim().toLowerCase().replace(/\\.+$/u, '');\n}\n\nexport function dedupeStable(values: readonly string[]): string[] {\n\tconst seenHostnames = new Set<string>();\n\tconst normalizedValues: string[] = [];\n\n\tfor (const value of values) {\n\t\tconst normalizedValue = normalizeHostname(value);\n\t\tif (normalizedValue.length === 0 || normalizedValue.startsWith('#')) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!seenHostnames.has(normalizedValue)) {\n\t\t\tseenHostnames.add(normalizedValue);\n\t\t\tnormalizedValues.push(normalizedValue);\n\t\t}\n\t}\n\n\treturn normalizedValues;\n}\n\nexport function compilePolicy(sources: PolicySources): string[] {\n\treturn dedupeStable([...sources.base, ...sources.profile, ...sources.extra]);\n}\n","import { execFile } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\n\nimport { createClient, type ResolveAllResponse, type ResolveReferenceError } from '@1password/sdk';\n\nimport type { SecretRef } from './types.js';\n\nexport interface SecretResolverClient {\n\treadonly secrets: {\n\t\tresolve(secretReference: string): Promise<string>;\n\t\tresolveAll(secretReferences: readonly string[]): Promise<ResolveAllResponse>;\n\t};\n}\n\nexport interface SecretResolver {\n\tresolve(ref: SecretRef): Promise<string>;\n\tresolveAll(refs: Record<string, SecretRef>): Promise<Record<string, string>>;\n}\n\n// --- Token source: how to obtain the 1Password service account token ---\n\nexport type TokenSource =\n\t| { readonly type: 'op-cli'; readonly ref: string }\n\t| { readonly type: 'env'; readonly envVar?: string | undefined }\n\t| { readonly type: 'keychain'; readonly service: string; readonly account: string };\n\nexport interface ExecFileOptions {\n\treadonly env?: Readonly<Record<string, string | undefined>>;\n\treadonly input?: string | undefined;\n\treadonly redactErrorOutput?: boolean | undefined;\n}\n\nexport interface ExecFileResult {\n\treadonly stdout: string;\n\treadonly stderr: string;\n}\n\nfunction formatUnknownError(error: unknown): string {\n\tif (error instanceof AggregateError) {\n\t\tconst childMessages = readAggregateErrorChildren(error).map(formatUnknownError);\n\t\tif (childMessages.length === 0) {\n\t\t\treturn error.message;\n\t\t}\n\t\tconst separator = error.message.endsWith('.') ? '' : '.';\n\t\treturn `${error.message}${separator} Details: ${childMessages.join('; ')}`;\n\t}\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nclass RedactedExecFileError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly safeDetail: string,\n\t\toptions?: { readonly cause?: unknown },\n\t) {\n\t\tsuper(message, options);\n\t\tthis.name = 'RedactedExecFileError';\n\t}\n}\n\nclass OpInjectOutputError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'OpInjectOutputError';\n\t}\n}\n\nfunction formatErrorMetadataValue(value: unknown): string | undefined {\n\tif (typeof value === 'number' || typeof value === 'string') {\n\t\treturn String(value);\n\t}\n\treturn undefined;\n}\n\nfunction readErrorCode(error: Error): string | undefined {\n\tif (!('code' in error)) {\n\t\treturn undefined;\n\t}\n\treturn formatErrorMetadataValue(error.code);\n}\n\nfunction readErrorSignal(error: Error): string | undefined {\n\tif (!('signal' in error)) {\n\t\treturn undefined;\n\t}\n\treturn formatErrorMetadataValue(error.signal);\n}\n\nfunction formatRedactedExecErrorDetail(error: Error): string {\n\tconst exitCode = readErrorCode(error) ?? 'unknown';\n\tconst signal = readErrorSignal(error);\n\treturn signal === undefined ? `exit code ${exitCode}` : `exit code ${exitCode}, signal ${signal}`;\n}\n\nfunction createExecFileError(options: {\n\treadonly command: string;\n\treadonly error: Error;\n\treadonly redactErrorOutput?: boolean | undefined;\n\treadonly stderr: string;\n}): Error {\n\tif (options.redactErrorOutput) {\n\t\tconst safeDetail = formatRedactedExecErrorDetail(options.error);\n\t\treturn new RedactedExecFileError(`${options.command} failed: ${safeDetail}`, safeDetail);\n\t}\n\n\tconst errorDetail = options.stderr.trim() || options.error.message;\n\treturn new Error(`${options.command} failed: ${errorDetail}`);\n}\n\nfunction formatStdinWriteErrorDetail(error: Error): string {\n\tconst errorCode = readErrorCode(error);\n\treturn errorCode === undefined ? 'stdin write failed' : `stdin write failed: ${errorCode}`;\n}\n\nfunction createStdinWriteError(command: string, error: Error, redactErrorOutput?: boolean): Error {\n\tif (redactErrorOutput) {\n\t\tconst safeDetail = formatStdinWriteErrorDetail(error);\n\t\treturn new RedactedExecFileError(`${command} failed writing stdin: ${safeDetail}`, safeDetail, {\n\t\t\tcause: error,\n\t\t});\n\t}\n\treturn new Error(`${command} failed writing stdin: ${formatUnknownError(error)}`, {\n\t\tcause: error,\n\t});\n}\n\nfunction ensureMacOsForKeychain(): void {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error(\n\t\t\t'Keychain token source is only supported on macOS. Use an env or op-cli token source on this platform so cmd-ts can surface a clear startup error.',\n\t\t);\n\t}\n}\n\nfunction execFileAsync(\n\tcommand: string,\n\targs: readonly string[],\n\toptions?: ExecFileOptions,\n): Promise<ExecFileResult> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet hasSettled = false;\n\t\tconst rejectOnce = (error: Error): void => {\n\t\t\tif (hasSettled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thasSettled = true;\n\t\t\treject(error);\n\t\t};\n\t\tconst resolveOnce = (result: ExecFileResult): void => {\n\t\t\tif (hasSettled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thasSettled = true;\n\t\t\tresolve(result);\n\t\t};\n\t\tconst child = execFile(\n\t\t\tcommand,\n\t\t\t[...args],\n\t\t\t{ env: options?.env, timeout: 30_000 },\n\t\t\t(error, stdout, stderr) => {\n\t\t\t\tif (error) {\n\t\t\t\t\trejectOnce(\n\t\t\t\t\t\tcreateExecFileError({\n\t\t\t\t\t\t\tcommand,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\tredactErrorOutput: options?.redactErrorOutput,\n\t\t\t\t\t\t\tstderr,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolveOnce({ stdout, stderr });\n\t\t\t},\n\t\t);\n\t\tif (options?.input !== undefined) {\n\t\t\tif (!child.stdin) {\n\t\t\t\tchild.kill();\n\t\t\t\trejectOnce(new Error(`${command} did not expose stdin for input`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchild.stdin.once('error', (error: Error) => {\n\t\t\t\tchild.kill();\n\t\t\t\trejectOnce(createStdinWriteError(command, error, options.redactErrorOutput));\n\t\t\t});\n\t\t\tchild.stdin.end(options.input);\n\t\t}\n\t});\n}\n\nconst SAFE_IDENTIFIER_PATTERN = /^[\\w.@-]+$/u;\n\nexport async function resolveServiceAccountToken(\n\tsource: TokenSource,\n\tdependencies?: {\n\t\treadonly execFileAsync?: (\n\t\t\tcommand: string,\n\t\t\targs: readonly string[],\n\t\t\toptions?: ExecFileOptions,\n\t\t) => Promise<ExecFileResult>;\n\t},\n): Promise<string> {\n\tconst exec = dependencies?.execFileAsync ?? execFileAsync;\n\n\tswitch (source.type) {\n\t\tcase 'op-cli': {\n\t\t\t// Uses `op read` which triggers biometric auth (Touch ID) on macOS\n\t\t\tconst result = await exec('op', ['read', source.ref], { redactErrorOutput: true });\n\t\t\tconst token = result.stdout.trim();\n\t\t\tif (token.length === 0) {\n\t\t\t\tthrow new Error('op-cli token resolution returned empty value');\n\t\t\t}\n\n\t\t\treturn token;\n\t\t}\n\n\t\tcase 'env': {\n\t\t\tconst envVar = source.envVar ?? 'OP_SERVICE_ACCOUNT_TOKEN';\n\t\t\tconst token = process.env[envVar]?.trim();\n\t\t\tif (!token) {\n\t\t\t\tthrow new Error(`Environment variable ${envVar} is not set`);\n\t\t\t}\n\n\t\t\treturn token;\n\t\t}\n\n\t\tcase 'keychain': {\n\t\t\tensureMacOsForKeychain();\n\n\t\t\t// Validate keychain identifiers to prevent argument injection\n\t\t\tif (!SAFE_IDENTIFIER_PATTERN.test(source.service)) {\n\t\t\t\tthrow new Error('Keychain service name contains invalid characters');\n\t\t\t}\n\n\t\t\tif (!SAFE_IDENTIFIER_PATTERN.test(source.account)) {\n\t\t\t\tthrow new Error('Keychain account name contains invalid characters');\n\t\t\t}\n\n\t\t\t// macOS Keychain via `security find-generic-password`\n\t\t\tconst result = await exec('security', [\n\t\t\t\t'find-generic-password',\n\t\t\t\t'-s',\n\t\t\t\tsource.service,\n\t\t\t\t'-a',\n\t\t\t\tsource.account,\n\t\t\t\t'-w',\n\t\t\t]);\n\t\t\tconst token = result.stdout.trim();\n\t\t\tif (token.length === 0) {\n\t\t\t\tthrow new Error('Keychain token resolution returned empty value');\n\t\t\t}\n\n\t\t\treturn token;\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported token source: ${JSON.stringify(source)}`);\n\t}\n}\n\n// --- Secret resolver: uses the token to resolve secrets via 1Password SDK ---\n\nexport interface CreateSecretResolverDependencies {\n\treadonly createClient?: (config: {\n\t\tauth: string;\n\t\tintegrationName: string;\n\t\tintegrationVersion: string;\n\t}) => Promise<SecretResolverClient>;\n\treadonly execFileAsync?: (\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions?: ExecFileOptions,\n\t) => Promise<ExecFileResult>;\n\treadonly integrationName?: string;\n\treadonly integrationVersion?: string;\n}\n\nasync function resolveSecretWithOpCli(\n\tserviceAccountToken: string,\n\tsecretReference: string,\n\texec: (\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions?: ExecFileOptions,\n\t) => Promise<ExecFileResult>,\n): Promise<string> {\n\tconst result = await exec('op', ['read', secretReference], {\n\t\tenv: createOpCliServiceAccountEnv(serviceAccountToken),\n\t\tredactErrorOutput: true,\n\t});\n\treturn stripOpReadStdoutTerminator(result.stdout);\n}\n\nfunction stripOpReadStdoutTerminator(stdout: string): string {\n\tif (stdout.endsWith('\\r\\n')) {\n\t\treturn stdout.slice(0, -2);\n\t}\n\tif (stdout.endsWith('\\n')) {\n\t\treturn stdout.slice(0, -1);\n\t}\n\treturn stdout;\n}\n\n// This is an allowlist for process plumbing only. Do not add ambient OP_* auth\n// variables here; they can switch `op` away from agent-vm's service account token.\nconst opCliProcessPlumbingEnvNames = [\n\t'APPDATA',\n\t'ALL_PROXY',\n\t'all_proxy',\n\t'COMSPEC',\n\t'HOME',\n\t'HTTP_PROXY',\n\t'http_proxy',\n\t'HTTPS_PROXY',\n\t'https_proxy',\n\t'LANG',\n\t'LC_ALL',\n\t'LC_CTYPE',\n\t'LOCALAPPDATA',\n\t'NO_PROXY',\n\t'no_proxy',\n\t'PATH',\n\t'SSL_CERT_DIR',\n\t'SSL_CERT_FILE',\n\t'TEMP',\n\t'TMP',\n\t'TMPDIR',\n\t'TZ',\n\t'USERPROFILE',\n\t'WINDIR',\n\t'XDG_CACHE_HOME',\n\t'XDG_CONFIG_HOME',\n\t'XDG_DATA_HOME',\n\t'XDG_RUNTIME_DIR',\n] satisfies readonly string[];\n\nfunction createOpCliServiceAccountEnv(\n\tserviceAccountToken: string,\n): Readonly<Record<string, string | undefined>> {\n\tconst env: Record<string, string | undefined> = {};\n\tfor (const envName of opCliProcessPlumbingEnvNames) {\n\t\tconst envValue = process.env[envName];\n\t\tif (envValue !== undefined) {\n\t\t\tenv[envName] = envValue;\n\t\t}\n\t}\n\tenv.OP_SERVICE_ACCOUNT_TOKEN = serviceAccountToken;\n\treturn env;\n}\n\nconst opInjectTemplateDelimiterPattern = /(?:\\{\\{|\\}\\})/u;\n\nfunction assertOpInjectTemplateSafeReference(entry: OpInjectEntry): void {\n\tif (\n\t\t!opInjectTemplateDelimiterPattern.test(entry.secretRef.ref) &&\n\t\t!entry.secretRef.ref.includes('\\u0000') &&\n\t\t!entry.secretRef.ref.includes('\\r') &&\n\t\t!entry.secretRef.ref.includes('\\n')\n\t) {\n\t\treturn;\n\t}\n\tthrow new OpInjectOutputError(\n\t\t`op inject template rejected unsafe 1Password reference for secret '${entry.secretName}'.`,\n\t);\n}\n\nasync function resolveAllSecretsWithOpCli(\n\tserviceAccountToken: string,\n\trefs: Record<string, SecretRef>,\n\texec: (\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions?: ExecFileOptions,\n\t) => Promise<ExecFileResult>,\n): Promise<Record<string, string>> {\n\ttry {\n\t\treturn await resolveAllSecretsWithOpInject(serviceAccountToken, refs, exec);\n\t} catch (error) {\n\t\tconst sanitizedInjectError = sanitizeOpInjectError(error);\n\t\ttry {\n\t\t\treturn await resolveAllSecretsWithSerialOpReads(serviceAccountToken, refs, exec);\n\t\t} catch (readError) {\n\t\t\tif (readError instanceof AggregateError) {\n\t\t\t\tconst readErrorChildren = readAggregateErrorChildren(readError);\n\t\t\t\tthrow createAggregateErrorWithCause({\n\t\t\t\t\tcause: readError,\n\t\t\t\t\terrors: [sanitizedInjectError, ...readErrorChildren],\n\t\t\t\t\tmessage: readError.message,\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow createAggregateErrorWithCause({\n\t\t\t\tcause: readError,\n\t\t\t\terrors: [sanitizedInjectError, readError],\n\t\t\t\tmessage: 'op inject and serial op read both failed.',\n\t\t\t});\n\t\t}\n\t}\n}\n\nfunction sanitizeOpInjectError(error: unknown): Error {\n\tif (error instanceof RedactedExecFileError) {\n\t\treturn new Error(`op inject failed before serial op read: ${error.safeDetail}`);\n\t}\n\tif (error instanceof OpInjectOutputError) {\n\t\treturn new Error(`op inject failed before serial op read: ${error.message}`);\n\t}\n\tconst errorType = error instanceof Error ? error.name : typeof error;\n\treturn new Error(`op inject failed before serial op read: ${errorType}`);\n}\n\nfunction readAggregateErrorChildren(error: AggregateError): readonly unknown[] {\n\tconst errorChildren: unknown = error.errors;\n\treturn Array.isArray(errorChildren) ? errorChildren : [];\n}\n\nfunction createAggregateErrorWithCause(options: {\n\treadonly cause: unknown;\n\treadonly errors: readonly unknown[];\n\treadonly message: string;\n}): AggregateError {\n\tconst aggregateError = new AggregateError(options.errors, options.message);\n\taggregateError.cause = options.cause;\n\treturn aggregateError;\n}\n\nfunction createFallbackStageError(stage: string, error: unknown): Error {\n\treturn new Error(`${stage} failed before op CLI fallback: ${formatUnknownError(error)}`, {\n\t\tcause: error,\n\t});\n}\n\nfunction createFallbackFailureError(options: {\n\treadonly fallbackError: unknown;\n\treadonly message: string;\n\treadonly stageError: Error;\n}): AggregateError {\n\tif (options.fallbackError instanceof AggregateError) {\n\t\treturn createAggregateErrorWithCause({\n\t\t\tcause: options.fallbackError,\n\t\t\terrors: [options.stageError, ...readAggregateErrorChildren(options.fallbackError)],\n\t\t\tmessage: options.fallbackError.message,\n\t\t});\n\t}\n\treturn createAggregateErrorWithCause({\n\t\tcause: options.fallbackError,\n\t\terrors: [options.stageError, options.fallbackError],\n\t\tmessage: options.message,\n\t});\n}\n\ninterface OpInjectEntry {\n\treadonly markerId: string;\n\treadonly secretName: string;\n\treadonly secretRef: SecretRef;\n}\n\nfunction opInjectStartMarker(markerId: string): string {\n\treturn `agent-vm-op-inject-start:${markerId}`;\n}\n\nfunction opInjectEndMarker(markerId: string): string {\n\treturn `agent-vm-op-inject-end:${markerId}`;\n}\n\nfunction createOpInjectEntries(refs: Record<string, SecretRef>): readonly OpInjectEntry[] {\n\treturn Object.entries(refs).map(([secretName, secretRef]) => ({\n\t\tmarkerId: randomUUID(),\n\t\tsecretName,\n\t\tsecretRef,\n\t}));\n}\n\nfunction buildOpInjectTemplate(entries: readonly OpInjectEntry[]): string {\n\treturn entries\n\t\t.map((entry) => {\n\t\t\tassertOpInjectTemplateSafeReference(entry);\n\t\t\treturn [\n\t\t\t\topInjectStartMarker(entry.markerId),\n\t\t\t\t`{{ ${entry.secretRef.ref} }}`,\n\t\t\t\topInjectEndMarker(entry.markerId),\n\t\t\t].join('\\n');\n\t\t})\n\t\t.join('\\n');\n}\n\nfunction findUniqueOpInjectMarker(options: {\n\treadonly marker: string;\n\treadonly markerDescription: string;\n\treadonly output: string;\n\treadonly secretName: string;\n\treadonly secretReference: string;\n}): number {\n\tconst markerIndex = options.output.indexOf(options.marker);\n\tif (markerIndex === -1) {\n\t\tthrow new OpInjectOutputError(\n\t\t\t`op inject output omitted ${options.markerDescription} marker for secret '${options.secretName}' (${options.secretReference}).`,\n\t\t);\n\t}\n\tconst repeatedMarkerIndex = options.output.indexOf(\n\t\toptions.marker,\n\t\tmarkerIndex + options.marker.length,\n\t);\n\tif (repeatedMarkerIndex !== -1) {\n\t\tthrow new OpInjectOutputError(\n\t\t\t`op inject output for secret '${options.secretName}' (${options.secretReference}) contained repeated ${options.markerDescription} marker.`,\n\t\t);\n\t}\n\treturn markerIndex;\n}\n\nfunction extractInjectedSecret(options: {\n\treadonly entry: OpInjectEntry;\n\treadonly output: string;\n}): string {\n\tconst startToken = `${opInjectStartMarker(options.entry.markerId)}\\n`;\n\tconst endToken = `\\n${opInjectEndMarker(options.entry.markerId)}`;\n\tconst valueStartIndex = findUniqueOpInjectMarker({\n\t\tmarker: startToken,\n\t\tmarkerDescription: 'start',\n\t\toutput: options.output,\n\t\tsecretName: options.entry.secretName,\n\t\tsecretReference: options.entry.secretRef.ref,\n\t});\n\tconst secretStartIndex = valueStartIndex + startToken.length;\n\tconst secretEndIndex = findUniqueOpInjectMarker({\n\t\tmarker: endToken,\n\t\tmarkerDescription: 'end',\n\t\toutput: options.output,\n\t\tsecretName: options.entry.secretName,\n\t\tsecretReference: options.entry.secretRef.ref,\n\t});\n\treturn options.output.slice(secretStartIndex, secretEndIndex);\n}\n\nfunction mapOpInjectOutput(\n\tentries: readonly OpInjectEntry[],\n\toutput: string,\n): Record<string, string> {\n\treturn Object.fromEntries(\n\t\tentries.map((entry) => [\n\t\t\tentry.secretName,\n\t\t\textractInjectedSecret({\n\t\t\t\tentry,\n\t\t\t\toutput,\n\t\t\t}),\n\t\t]),\n\t);\n}\n\nasync function resolveAllSecretsWithOpInject(\n\tserviceAccountToken: string,\n\trefs: Record<string, SecretRef>,\n\texec: (\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions?: ExecFileOptions,\n\t) => Promise<ExecFileResult>,\n): Promise<Record<string, string>> {\n\tconst entries = createOpInjectEntries(refs);\n\tif (entries.length === 0) {\n\t\treturn {};\n\t}\n\n\tconst result = await exec('op', ['inject', '--in-file', '/dev/stdin'], {\n\t\tenv: createOpCliServiceAccountEnv(serviceAccountToken),\n\t\tinput: buildOpInjectTemplate(entries),\n\t\tredactErrorOutput: true,\n\t});\n\treturn mapOpInjectOutput(entries, result.stdout);\n}\n\nasync function resolveAllSecretsWithSerialOpReads(\n\tserviceAccountToken: string,\n\trefs: Record<string, SecretRef>,\n\texec: (\n\t\tcommand: string,\n\t\targs: readonly string[],\n\t\toptions?: ExecFileOptions,\n\t) => Promise<ExecFileResult>,\n): Promise<Record<string, string>> {\n\tconst resolvedSecrets: Record<string, string> = {};\n\tconst failures: Error[] = [];\n\n\tfor (const [secretName, secretRef] of Object.entries(refs)) {\n\t\ttry {\n\t\t\t// Sequential resolution avoids concurrent `op read` failures with the same service account token.\n\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop\n\t\t\tresolvedSecrets[secretName] = await resolveSecretWithOpCli(\n\t\t\t\tserviceAccountToken,\n\t\t\t\tsecretRef.ref,\n\t\t\t\texec,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfailures.push(\n\t\t\t\tnew Error(\n\t\t\t\t\t`Failed to resolve secret '${secretName}' from '${secretRef.ref}' via op read: ${formatUnknownError(error)}`,\n\t\t\t\t\t{ cause: error },\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tif (failures.length > 0) {\n\t\tthrow new AggregateError(\n\t\t\tfailures,\n\t\t\t`Failed to resolve ${String(failures.length)} secret(s) via op read.`,\n\t\t);\n\t}\n\n\treturn resolvedSecrets;\n}\n\nfunction formatResolveReferenceError(error: ResolveReferenceError): string {\n\treturn 'message' in error && typeof error.message === 'string'\n\t\t? `${error.type}: ${error.message}`\n\t\t: error.type;\n}\n\nfunction readSdkBatchSecret(options: {\n\treadonly response: ResolveAllResponse;\n\treadonly secretName: string;\n\treadonly secretReference: string;\n}): string {\n\tconst individualResponse = options.response.individualResponses[options.secretReference];\n\tif (!individualResponse) {\n\t\tthrow new Error(\n\t\t\t`1Password SDK resolveAll response omitted '${options.secretName}' (${options.secretReference}).`,\n\t\t);\n\t}\n\tif (individualResponse.content !== undefined) {\n\t\treturn individualResponse.content.secret;\n\t}\n\tif (individualResponse.error !== undefined) {\n\t\tthrow new Error(\n\t\t\t`1Password SDK resolveAll failed for '${options.secretName}' (${options.secretReference}): ${formatResolveReferenceError(individualResponse.error)}`,\n\t\t);\n\t}\n\tthrow new Error(\n\t\t`1Password SDK resolveAll returned neither content nor error for '${options.secretName}' (${options.secretReference}).`,\n\t);\n}\n\nfunction mapSdkResolveAllResponse(\n\trefs: Record<string, SecretRef>,\n\tresponse: ResolveAllResponse,\n): Record<string, string> {\n\treturn Object.fromEntries(\n\t\tObject.entries(refs).map(([secretName, secretRef]) => [\n\t\t\tsecretName,\n\t\t\treadSdkBatchSecret({\n\t\t\t\tresponse,\n\t\t\t\tsecretName,\n\t\t\t\tsecretReference: secretRef.ref,\n\t\t\t}),\n\t\t]),\n\t);\n}\n\nexport async function createSecretResolver(\n\toptions: {\n\t\treadonly serviceAccountToken: string;\n\t},\n\tdependencies: CreateSecretResolverDependencies = {},\n): Promise<SecretResolver> {\n\tconst exec = dependencies.execFileAsync ?? execFileAsync;\n\ttry {\n\t\tconst client = await (dependencies.createClient ?? createClient)({\n\t\t\tauth: options.serviceAccountToken,\n\t\t\tintegrationName: dependencies.integrationName ?? 'agent-vm',\n\t\t\tintegrationVersion: dependencies.integrationVersion ?? '0.0.1',\n\t\t});\n\n\t\treturn {\n\t\t\tresolve: async (ref: SecretRef): Promise<string> => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await client.secrets.resolve(ref.ref);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst sdkResolveError = createFallbackStageError('1Password SDK resolve', error);\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec);\n\t\t\t\t\t} catch (fallbackError) {\n\t\t\t\t\t\tthrow createFallbackFailureError({\n\t\t\t\t\t\t\tfallbackError,\n\t\t\t\t\t\t\tmessage: '1Password SDK resolve and op CLI fallback both failed.',\n\t\t\t\t\t\t\tstageError: sdkResolveError,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tresolveAll: async (refs: Record<string, SecretRef>): Promise<Record<string, string>> => {\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await client.secrets.resolveAll(\n\t\t\t\t\t\tObject.values(refs).map((secretRef) => secretRef.ref),\n\t\t\t\t\t);\n\t\t\t\t\treturn mapSdkResolveAllResponse(refs, response);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst sdkResolveAllError = createFallbackStageError('1Password SDK resolveAll', error);\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec);\n\t\t\t\t\t} catch (fallbackError) {\n\t\t\t\t\t\tthrow createFallbackFailureError({\n\t\t\t\t\t\t\tfallbackError,\n\t\t\t\t\t\t\tmessage: '1Password SDK resolveAll and op CLI fallback both failed.',\n\t\t\t\t\t\t\tstageError: sdkResolveAllError,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconst sdkClientCreationError = createFallbackStageError('1Password SDK client creation', error);\n\t\treturn {\n\t\t\tresolve: async (ref: SecretRef): Promise<string> => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec);\n\t\t\t\t} catch (fallbackError) {\n\t\t\t\t\tthrow createFallbackFailureError({\n\t\t\t\t\t\tfallbackError,\n\t\t\t\t\t\tmessage: '1Password SDK client creation and op CLI fallback both failed.',\n\t\t\t\t\t\tstageError: sdkClientCreationError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t\tresolveAll: async (refs: Record<string, SecretRef>): Promise<Record<string, string>> => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec);\n\t\t\t\t} catch (fallbackError) {\n\t\t\t\t\tthrow createFallbackFailureError({\n\t\t\t\t\t\tfallbackError,\n\t\t\t\t\t\tmessage: '1Password SDK client creation and op CLI fallback both failed.',\n\t\t\t\t\t\tstageError: sdkClientCreationError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t}\n}\n\nexport async function createOpCliSecretResolver(\n\toptions: {\n\t\treadonly serviceAccountToken: string;\n\t},\n\tdependencies: Pick<CreateSecretResolverDependencies, 'execFileAsync'> = {},\n): Promise<SecretResolver> {\n\tconst exec = dependencies.execFileAsync ?? execFileAsync;\n\n\treturn {\n\t\tresolve: async (ref: SecretRef): Promise<string> =>\n\t\t\tawait resolveSecretWithOpCli(options.serviceAccountToken, ref.ref, exec),\n\t\tresolveAll: async (refs: Record<string, SecretRef>): Promise<Record<string, string>> =>\n\t\t\tawait resolveAllSecretsWithOpCli(options.serviceAccountToken, refs, exec),\n\t};\n}\n","import {\n\tMemoryProvider,\n\tReadonlyProvider,\n\tRealFSProvider,\n\tShadowProvider,\n\tVM,\n\tcreateHttpHooks,\n\tcreateShadowPathPredicate,\n\ttype CreateHttpHooksResult,\n\ttype EnableIngressOptions,\n\ttype EnableSshOptions,\n\ttype IngressRoute as GondolinIngressRoute,\n\ttype ShadowPredicate,\n\ttype ShadowProviderOptions,\n\ttype VMOptions,\n\ttype VirtualProvider,\n} from '@earendil-works/gondolin';\n\nimport {\n\tclosePinnedRealFsRoot,\n\tcreatePinnedRealFsProvider,\n\ttype PinnedRealFsRoot,\n} from './pinned-realfs.js';\nimport type { SecretSpec } from './types.js';\n\nexport const SYNTHETIC_DNS_IPV4_BENCHMARK = '198.18.0.1';\nexport const SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK = '::ffff:198.18.0.1';\n\nexport interface ExecResult {\n\treadonly exitCode: number;\n\treadonly stdout: string;\n\treadonly stderr: string;\n}\n\nexport type IngressRoute = GondolinIngressRoute;\n\nexport interface SshAccess {\n\treadonly host: string;\n\treadonly command?: string;\n\treadonly identityFile?: string;\n\treadonly port: number;\n\treadonly user?: string;\n}\n\nexport interface IngressAccess {\n\treadonly host: string;\n\treadonly port: number;\n}\n\nexport interface ManagedVmInstance {\n\treadonly id: string;\n\texec(command: string): Promise<{\n\t\treadonly exitCode: number;\n\t\treadonly stdout?: string;\n\t\treadonly stderr?: string;\n\t}>;\n\tenableSsh(options?: EnableSshOptions): Promise<SshAccess>;\n\tenableIngress(options?: EnableIngressOptions): Promise<IngressAccess>;\n\tsetIngressRoutes(routes: readonly IngressRoute[]): void;\n\tclose(): Promise<void>;\n}\n\nexport interface ManagedVmDependencies {\n\tcreateVm(vmOptions: VMOptions): Promise<ManagedVmInstance>;\n\tcreateHttpHooks(options: {\n\t\treadonly allowedHosts: readonly string[];\n\t\treadonly secrets: Record<string, SecretSpec>;\n\t\treadonly onRequest?: (request: Request) => Promise<Request | Response | void>;\n\t\treadonly onResponse?: (response: Response) => Promise<Response | void>;\n\t}): Pick<CreateHttpHooksResult, 'env' | 'httpHooks'>;\n\tclosePinnedRealFsRoot(root: PinnedRealFsRoot): void;\n\tcreatePinnedRealFsProvider(root: PinnedRealFsRoot): VirtualProvider;\n\tcreateRealFsProvider(hostPath: string): VirtualProvider;\n\tcreateReadonlyProvider(provider: VirtualProvider): VirtualProvider;\n\tcreateMemoryProvider(): VirtualProvider;\n\tcreateShadowProvider(provider: VirtualProvider, options: ShadowProviderOptions): VirtualProvider;\n\tcreateShadowPathPredicate(paths: readonly string[]): ShadowPredicate;\n}\n\nexport interface VfsMountSpec {\n\treadonly kind: 'realfs' | 'realfs-readonly' | 'memory' | 'shadow';\n\treadonly hostPath?: string;\n\treadonly pinnedHostRoot?: PinnedRealFsRoot;\n\treadonly shadowConfig?: {\n\t\treadonly deny: readonly string[];\n\t\treadonly tmpfs: readonly string[];\n\t};\n}\n\nexport interface CreateVmOptions {\n\treadonly imagePath: string;\n\treadonly memory: string;\n\treadonly cpus: number;\n\treadonly rootfsMode: 'readonly' | 'memory' | 'cow';\n\treadonly allowedHosts: readonly string[];\n\treadonly secrets: Record<string, SecretSpec>;\n\treadonly vfsMounts: Record<string, VfsMountSpec>;\n\treadonly tcpHosts?: Record<string, string>;\n\treadonly env?: Record<string, string>;\n\treadonly sessionLabel?: string;\n\treadonly onRequest?: (request: Request) => Promise<Request | Response | void>;\n\treadonly onResponse?: (response: Response) => Promise<Response | void>;\n}\n\nexport interface ManagedVm {\n\treadonly id: string;\n\texec(command: string): Promise<ExecResult>;\n\tenableSsh(options?: EnableSshOptions): Promise<SshAccess>;\n\tenableIngress(options?: EnableIngressOptions): Promise<IngressAccess>;\n\tgetVmInstance(): ManagedVmInstance;\n\tsetIngressRoutes(routes: readonly IngressRoute[]): void;\n\tclose(): Promise<void>;\n}\n\n/* oxlint-disable typescript-eslint/no-unsafe-type-assertion -- VM.create() returns\n Gondolin's concrete VM class; this adapter exposes only the narrower\n ManagedVmInstance interface used by agent-vm. */\nfunction createDefaultDependencies(): ManagedVmDependencies {\n\tconst createDefaultRealFsProvider = (hostPath: string): VirtualProvider =>\n\t\tnew RealFSProvider(hostPath);\n\treturn {\n\t\tcreateVm: async (vmOptions: VMOptions): Promise<ManagedVmInstance> =>\n\t\t\t(await VM.create(vmOptions)) as unknown as ManagedVmInstance,\n\t\tcreateHttpHooks: (hookOptions) =>\n\t\t\tcreateHttpHooks({\n\t\t\t\tallowedHosts: [...hookOptions.allowedHosts],\n\t\t\t\tsecrets: Object.fromEntries(\n\t\t\t\t\tObject.entries(hookOptions.secrets).map(([secretName, secretSpec]) => [\n\t\t\t\t\t\tsecretName,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thosts: [...secretSpec.hosts],\n\t\t\t\t\t\t\tvalue: secretSpec.value,\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\t...(hookOptions.onRequest ? { onRequest: hookOptions.onRequest } : {}),\n\t\t\t\t...(hookOptions.onResponse ? { onResponse: hookOptions.onResponse } : {}),\n\t\t\t}),\n\t\tclosePinnedRealFsRoot,\n\t\tcreatePinnedRealFsProvider: (root: PinnedRealFsRoot): VirtualProvider =>\n\t\t\tcreatePinnedRealFsProvider({\n\t\t\t\tcreateRealFsProvider: createDefaultRealFsProvider,\n\t\t\t\troot,\n\t\t\t}),\n\t\tcreateRealFsProvider: createDefaultRealFsProvider,\n\t\tcreateReadonlyProvider: (provider: VirtualProvider): VirtualProvider =>\n\t\t\tnew ReadonlyProvider(provider),\n\t\tcreateMemoryProvider: (): VirtualProvider => new MemoryProvider(),\n\t\tcreateShadowProvider: (\n\t\t\tprovider: VirtualProvider,\n\t\t\tshadowOptions: ShadowProviderOptions,\n\t\t): VirtualProvider => new ShadowProvider(provider, shadowOptions),\n\t\tcreateShadowPathPredicate: (paths: readonly string[]): ShadowPredicate =>\n\t\t\tcreateShadowPathPredicate([...paths]),\n\t};\n}\n/* oxlint-enable typescript-eslint/no-unsafe-type-assertion */\n\nfunction normalizeShadowPath(pathValue: string): string {\n\tconst trimmedPath = pathValue.trim();\n\tif (trimmedPath.startsWith('/')) {\n\t\treturn trimmedPath;\n\t}\n\n\tconst relativePath = trimmedPath.startsWith('./') ? trimmedPath.slice('./'.length) : trimmedPath;\n\treturn `/${relativePath}`;\n}\n\nfunction createRealFsProviderForSpec(\n\tmountSpec: VfsMountSpec,\n\tdependencies: ManagedVmDependencies,\n\tmountKind: string,\n): VirtualProvider {\n\tif (mountSpec.pinnedHostRoot) {\n\t\treturn dependencies.createPinnedRealFsProvider(mountSpec.pinnedHostRoot);\n\t}\n\tif (mountSpec.hostPath) {\n\t\treturn dependencies.createRealFsProvider(mountSpec.hostPath);\n\t}\n\n\tthrow new Error(`${mountKind} mounts require hostPath or pinnedHostRoot`);\n}\n\nfunction createProviderFromSpec(\n\tmountSpec: VfsMountSpec,\n\tdependencies: ManagedVmDependencies,\n): VirtualProvider {\n\tswitch (mountSpec.kind) {\n\t\tcase 'memory':\n\t\t\treturn dependencies.createMemoryProvider();\n\t\tcase 'realfs': {\n\t\t\treturn createRealFsProviderForSpec(mountSpec, dependencies, 'realfs');\n\t\t}\n\t\tcase 'realfs-readonly': {\n\t\t\treturn dependencies.createReadonlyProvider(\n\t\t\t\tcreateRealFsProviderForSpec(mountSpec, dependencies, 'realfs-readonly'),\n\t\t\t);\n\t\t}\n\t\tcase 'shadow': {\n\t\t\tconst baseProvider =\n\t\t\t\tmountSpec.hostPath || mountSpec.pinnedHostRoot\n\t\t\t\t\t? createRealFsProviderForSpec(mountSpec, dependencies, 'shadow')\n\t\t\t\t\t: dependencies.createMemoryProvider();\n\n\t\t\tlet shadowProvider = baseProvider;\n\t\t\tconst shadowConfig = mountSpec.shadowConfig;\n\n\t\t\tif (shadowConfig?.deny.length) {\n\t\t\t\tshadowProvider = dependencies.createShadowProvider(shadowProvider, {\n\t\t\t\t\tshouldShadow: dependencies.createShadowPathPredicate(\n\t\t\t\t\t\tshadowConfig.deny.map((shadowPath) => normalizeShadowPath(shadowPath)),\n\t\t\t\t\t),\n\t\t\t\t\twriteMode: 'deny',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (shadowConfig?.tmpfs.length) {\n\t\t\t\tshadowProvider = dependencies.createShadowProvider(shadowProvider, {\n\t\t\t\t\tshouldShadow: dependencies.createShadowPathPredicate(\n\t\t\t\t\t\tshadowConfig.tmpfs.map((shadowPath) => normalizeShadowPath(shadowPath)),\n\t\t\t\t\t),\n\t\t\t\t\twriteMode: 'tmpfs',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn shadowProvider;\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(`Unsupported VFS mount kind: ${String(mountSpec.kind)}`);\n\t\t}\n\t}\n}\n\nfunction createVfsMounts(\n\tvfsMounts: Record<string, VfsMountSpec>,\n\tdependencies: ManagedVmDependencies,\n): Record<string, VirtualProvider> {\n\tconst mountMap: Record<string, VirtualProvider> = {};\n\n\tfor (const [guestPath, mountSpec] of Object.entries(vfsMounts)) {\n\t\tmountMap[guestPath] = createProviderFromSpec(mountSpec, dependencies);\n\t}\n\n\treturn mountMap;\n}\n\nfunction collectPinnedRealFsRoots(\n\tvfsMounts: Record<string, VfsMountSpec>,\n): readonly PinnedRealFsRoot[] {\n\tconst roots = new Map<number, PinnedRealFsRoot>();\n\tfor (const mountSpec of Object.values(vfsMounts)) {\n\t\tif (mountSpec.pinnedHostRoot) {\n\t\t\troots.set(mountSpec.pinnedHostRoot.fd, mountSpec.pinnedHostRoot);\n\t\t}\n\t}\n\treturn [...roots.values()];\n}\n\nfunction closePinnedRealFsRoots(\n\troots: readonly PinnedRealFsRoot[],\n\tdependencies: ManagedVmDependencies,\n): void {\n\tfor (const root of roots) {\n\t\tdependencies.closePinnedRealFsRoot(root);\n\t}\n}\n\nfunction closePinnedRealFsRootsAfterFailure(\n\troots: readonly PinnedRealFsRoot[],\n\tdependencies: ManagedVmDependencies,\n): void {\n\ttry {\n\t\tclosePinnedRealFsRoots(roots, dependencies);\n\t} catch {\n\t\t// Preserve the VM creation failure; leaked-fd risk is lower than hiding\n\t\t// the root cause of a failed lease.\n\t}\n}\n\nexport async function createManagedVm(\n\toptions: CreateVmOptions,\n\tdependencies: ManagedVmDependencies = createDefaultDependencies(),\n): Promise<ManagedVm> {\n\tconst hasTcpHosts = options.tcpHosts && Object.keys(options.tcpHosts).length > 0;\n\tconst pinnedRealFsRoots = collectPinnedRealFsRoots(options.vfsMounts);\n\tlet vmInstance: ManagedVmInstance;\n\ttry {\n\t\tconst hookBundle = dependencies.createHttpHooks({\n\t\t\tallowedHosts: options.allowedHosts,\n\t\t\tsecrets: options.secrets,\n\t\t\t...(options.onRequest ? { onRequest: options.onRequest } : {}),\n\t\t\t...(options.onResponse ? { onResponse: options.onResponse } : {}),\n\t\t});\n\t\tvmInstance = await dependencies.createVm({\n\t\t\t...(options.imagePath.length > 0 ? { sandbox: { imagePath: options.imagePath } } : {}),\n\t\t\t...(options.sessionLabel ? { sessionLabel: options.sessionLabel } : {}),\n\t\t\trootfs: {\n\t\t\t\tmode: options.rootfsMode,\n\t\t\t},\n\t\t\tmemory: options.memory,\n\t\t\tcpus: options.cpus,\n\t\t\tenv: {\n\t\t\t\t...hookBundle.env,\n\t\t\t\t...options.env,\n\t\t\t},\n\t\t\thttpHooks: hookBundle.httpHooks,\n\t\t\tvfs: {\n\t\t\t\tfuseMount: '/data',\n\t\t\t\tmounts: createVfsMounts(options.vfsMounts, dependencies),\n\t\t\t},\n\t\t\t...(hasTcpHosts\n\t\t\t\t? {\n\t\t\t\t\t\tdns: {\n\t\t\t\t\t\t\tmode: 'synthetic',\n\t\t\t\t\t\t\tsyntheticIPv4: SYNTHETIC_DNS_IPV4_BENCHMARK,\n\t\t\t\t\t\t\tsyntheticIPv6: SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK,\n\t\t\t\t\t\t\tsyntheticHostMapping: 'per-host',\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttcp: {\n\t\t\t\t\t\t\thosts: options.tcpHosts,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t} catch (error) {\n\t\tclosePinnedRealFsRootsAfterFailure(pinnedRealFsRoots, dependencies);\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tid: vmInstance.id,\n\t\tasync exec(command: string): Promise<ExecResult> {\n\t\t\tconst executionResult = await vmInstance.exec(command);\n\t\t\treturn {\n\t\t\t\texitCode: executionResult.exitCode,\n\t\t\t\tstdout: executionResult.stdout ?? '',\n\t\t\t\tstderr: executionResult.stderr ?? '',\n\t\t\t};\n\t\t},\n\t\tasync enableSsh(sshOptions?: EnableSshOptions): Promise<SshAccess> {\n\t\t\treturn await vmInstance.enableSsh(sshOptions);\n\t\t},\n\t\tasync enableIngress(ingressOptions?: EnableIngressOptions): Promise<IngressAccess> {\n\t\t\treturn await vmInstance.enableIngress(ingressOptions);\n\t\t},\n\t\tgetVmInstance(): ManagedVmInstance {\n\t\t\treturn vmInstance;\n\t\t},\n\t\tsetIngressRoutes(routes: readonly IngressRoute[]): void {\n\t\t\tvmInstance.setIngressRoutes(routes);\n\t\t},\n\t\tasync close(): Promise<void> {\n\t\t\tlet closeError: unknown;\n\t\t\ttry {\n\t\t\t\tawait vmInstance.close();\n\t\t\t} catch (error) {\n\t\t\t\tcloseError = error;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tclosePinnedRealFsRoots(pinnedRealFsRoots, dependencies);\n\t\t\t} catch (error) {\n\t\t\t\tcloseError ??= error;\n\t\t\t}\n\t\t\tif (closeError !== undefined) {\n\t\t\t\tthrow closeError;\n\t\t\t}\n\t\t},\n\t};\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface VolumeConfigEntry {\n\treadonly guestPath: string;\n}\n\nexport interface ResolvedVolume {\n\treadonly hostDir: string;\n\treadonly guestPath: string;\n}\n\nexport async function ensureVolumeDir(\n\tcacheBase: string,\n\tworkspaceHash: string,\n\tvolumeName: string,\n): Promise<string> {\n\tconst volumeDirectory = path.join(cacheBase, workspaceHash, volumeName);\n\tawait fs.mkdir(volumeDirectory, { recursive: true });\n\treturn volumeDirectory;\n}\n\nexport async function resolveVolumeDirs(\n\tcacheBase: string,\n\tworkspaceHash: string,\n\tvolumes: Readonly<Record<string, VolumeConfigEntry>>,\n): Promise<Record<string, ResolvedVolume>> {\n\tconst resolvedVolumeEntries = await Promise.all(\n\t\tObject.entries(volumes).map(\n\t\t\tasync ([volumeName, volumeConfig]) =>\n\t\t\t\t[\n\t\t\t\t\tvolumeName,\n\t\t\t\t\t{\n\t\t\t\t\t\tguestPath: volumeConfig.guestPath,\n\t\t\t\t\t\thostDir: await ensureVolumeDir(cacheBase, workspaceHash, volumeName),\n\t\t\t\t\t},\n\t\t\t\t] satisfies readonly [string, ResolvedVolume],\n\t\t),\n\t);\n\n\treturn Object.fromEntries(resolvedVolumeEntries);\n}\n","import fs from 'node:fs/promises';\n\nexport async function writeFileAtomically(\n\tfilePath: string,\n\tcontent: string,\n\toptions: {\n\t\treadonly mode?: number;\n\t} = {},\n): Promise<void> {\n\tconst temporaryFilePath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n\tawait fs.writeFile(temporaryFilePath, content, {\n\t\tencoding: 'utf8',\n\t\t...(options.mode ? { mode: options.mode } : {}),\n\t});\n\ttry {\n\t\tawait fs.rename(temporaryFilePath, filePath);\n\t} catch (renameError) {\n\t\ttry {\n\t\t\tawait fs.rm(temporaryFilePath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to replace '${filePath}' (${renameError instanceof Error ? renameError.message : JSON.stringify(renameError)}) and failed to remove temporary file '${temporaryFilePath}': ${cleanupError instanceof Error ? cleanupError.message : JSON.stringify(cleanupError)}`,\n\t\t\t\t{ cause: cleanupError },\n\t\t\t);\n\t\t}\n\t\tthrow renameError;\n\t}\n}\n"],"mappings":";;;;;;;;;;AAKA,MAAa,+BAA+B;;;;;;;;;;;AA+B5C,SAAS,uBAAuB,UAAkB,WAAuC;CACxF,OAAO,KAAK,WAAW,SA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AoB,GAAG,SAAS,GAAG,QAAQ,IAAI,GAAG,KAAK,KAAK,CAAC;CACnE,MAAM,GAAG,UAAU,mBAAmB,SAAS;EAC9C,UAAU;EACV,GAAI,QAAQ,OAAO,EAAE,MAAM,QAAQ,MAAM,GAAG,EAAE;EAC9C,CAAC;CACF,IAAI;EACH,MAAM,GAAG,OAAO,mBAAmB,SAAS;UACpC,aAAa;EACrB,IAAI;GACH,MAAM,GAAG,GAAG,mBAAmB,EAAE,OAAO,MAAM,CAAC;WACvC,cAAc;GACtB,MAAM,IAAI,MACT,sBAAsB,SAAS,KAAK,uBAAuB,QAAQ,YAAY,UAAU,KAAK,UAAU,YAAY,CAAC,yCAAyC,kBAAkB,KAAK,wBAAwB,QAAQ,aAAa,UAAU,KAAK,UAAU,aAAa,IACxQ,EAAE,OAAO,cAAc,CACvB;;EAEF,MAAM"}
1
+ {"version":3,"file":"index.js","names":["fs"],"sources":["../src/rootfs-init-extra.ts","../src/build-pipeline.ts","../src/gondolin-package.ts","../src/mount-policy.ts","../src/pinned-realfs.ts","../src/policy-compiler.ts","../src/vm-adapter.ts","../src/volume-manager.ts","../src/write-file-atomically.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { BuildConfig } from '@earendil-works/gondolin';\n\nexport const agentVmRootfsInitExtraScript = `# Generated by agent-vm.\n# Gondolin mounts devtmpfs over /dev at boot, so Docker-image /dev symlinks are hidden.\nmkdir -p /dev\nln -sfn /proc/self/fd /dev/fd 2>/dev/null || true\nln -sfn /proc/self/fd/0 /dev/stdin 2>/dev/null || true\nln -sfn /proc/self/fd/1 /dev/stdout 2>/dev/null || true\nln -sfn /proc/self/fd/2 /dev/stderr 2>/dev/null || true\nif [ ! -e /dev/ptmx ] && [ -e /dev/pts/ptmx ]; then\n ln -sfn pts/ptmx /dev/ptmx 2>/dev/null || true\nfi\n`;\n\ninterface PrepareRootfsInitExtraOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly imagePath: string;\n\treadonly rootfsInitExtraContent: string;\n}\n\ninterface ResolveRootfsInitExtraOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly configDir?: string;\n}\n\nexport interface ResolvedRootfsInitExtra {\n\treadonly content: string;\n\treadonly fingerprintInput: {\n\t\treadonly agentVmRootfsInitExtra: string;\n\t\treadonly deploymentRootfsInitExtra?: string;\n\t};\n}\n\nfunction resolveBuildConfigPath(filePath: string, configDir: string | undefined): string {\n\treturn path.isAbsolute(filePath) ? filePath : path.resolve(configDir ?? process.cwd(), filePath);\n}\n\nasync function readExistingRootfsInitExtra(\n\tbuildConfig: BuildConfig,\n\tconfigDir: string | undefined,\n): Promise<string | undefined> {\n\tconst existingRootfsInitExtra = buildConfig.init?.rootfsInitExtra;\n\tif (!existingRootfsInitExtra) {\n\t\treturn undefined;\n\t}\n\n\tconst resolvedRootfsInitExtra = resolveBuildConfigPath(existingRootfsInitExtra, configDir);\n\ttry {\n\t\treturn await fs.readFile(resolvedRootfsInitExtra, 'utf8');\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(\n\t\t\t`Failed to read Gondolin rootfs init extra '${resolvedRootfsInitExtra}': ${message}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n\nfunction composeRootfsInitExtra(existingRootfsInitExtra: string | undefined): string {\n\treturn existingRootfsInitExtra\n\t\t? `${agentVmRootfsInitExtraScript.trimEnd()}\\n\\n${existingRootfsInitExtra}`\n\t\t: agentVmRootfsInitExtraScript;\n}\n\nexport async function resolveRootfsInitExtra(\n\toptions: ResolveRootfsInitExtraOptions,\n): Promise<ResolvedRootfsInitExtra> {\n\tconst existingRootfsInitExtra = await readExistingRootfsInitExtra(\n\t\toptions.buildConfig,\n\t\toptions.configDir,\n\t);\n\n\treturn {\n\t\tcontent: composeRootfsInitExtra(existingRootfsInitExtra),\n\t\tfingerprintInput: {\n\t\t\tagentVmRootfsInitExtra: agentVmRootfsInitExtraScript,\n\t\t\t...(existingRootfsInitExtra === undefined\n\t\t\t\t? {}\n\t\t\t\t: { deploymentRootfsInitExtra: existingRootfsInitExtra }),\n\t\t},\n\t};\n}\n\nexport async function prepareBuildConfigWithAgentVmRootfsInitExtra(\n\toptions: PrepareRootfsInitExtraOptions,\n): Promise<BuildConfig> {\n\tconst rootfsInitExtraPath = path.join(options.imagePath, 'agent-vm-rootfs-init-extra.sh');\n\n\tawait fs.writeFile(rootfsInitExtraPath, options.rootfsInitExtraContent, {\n\t\tencoding: 'utf8',\n\t\tmode: 0o755,\n\t});\n\n\treturn {\n\t\t...options.buildConfig,\n\t\tinit: {\n\t\t\t...options.buildConfig.init,\n\t\t\trootfsInitExtra: rootfsInitExtraPath,\n\t\t},\n\t};\n}\n","import crypto from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { BuildConfig, BuildOptions } from '@earendil-works/gondolin';\n\nimport {\n\tprepareBuildConfigWithAgentVmRootfsInitExtra,\n\tresolveRootfsInitExtra,\n} from './rootfs-init-extra.js';\n\nexport type { BuildConfig } from '@earendil-works/gondolin';\n\nexport interface BuildImageOptions {\n\treadonly buildConfig: BuildConfig;\n\treadonly cacheDir: string;\n\t/** Directory to resolve relative paths in buildConfig (e.g. postBuild.copy.src).\n\t * Defaults to process.cwd() if not provided. */\n\treadonly configDir?: string;\n\treadonly fullReset?: boolean;\n\treadonly fingerprintInput?: unknown;\n\treadonly output?: BuildOutput;\n}\n\nexport interface BuildOutput {\n\twrite(chunk: string | Uint8Array): boolean;\n}\n\nexport interface BuildImageResult {\n\treadonly built: boolean;\n\treadonly fingerprint: string;\n\treadonly imagePath: string;\n}\n\nexport const buildImageAssetFileNames = [\n\t'manifest.json',\n\t'rootfs.ext4',\n\t'initramfs.cpio.lz4',\n\t'vmlinuz-virt',\n] as const;\n\ninterface BuildPipelineDependencies {\n\treadonly buildAssets?: (\n\t\tbuildConfig: BuildConfig,\n\t\toutputDirectory: string,\n\t\tconfigDir?: string,\n\t) => Promise<unknown>;\n\treadonly gondolinVersion?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction stableSerialize(value: unknown): string {\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map((entry) => stableSerialize(entry)).join(',')}]`;\n\t}\n\n\tif (isRecord(value)) {\n\t\tconst objectEntries = Object.entries(value)\n\t\t\t.filter(([, entryValue]) => entryValue !== undefined)\n\t\t\t.toSorted(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));\n\t\treturn `{${objectEntries\n\t\t\t.map(([entryKey, entryValue]) => `${JSON.stringify(entryKey)}:${stableSerialize(entryValue)}`)\n\t\t\t.join(',')}}`;\n\t}\n\n\treturn JSON.stringify(value);\n}\n\nfunction isMissingPathError(error: unknown): boolean {\n\treturn typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (!isMissingPathError(error)) {\n\t\t\tthrow error;\n\t\t}\n\t\treturn false;\n\t}\n}\n\nexport async function hasBuiltImageAssets(outputDirectoryPath: string): Promise<boolean> {\n\tfor (const fileName of buildImageAssetFileNames) {\n\t\t// oxlint-disable-next-line no-await-in-loop -- each missing file points at the same image generation\n\t\tif (!(await pathExists(path.join(outputDirectoryPath, fileName)))) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nasync function loadBuildAssets(): Promise<\n\t(buildConfig: BuildConfig, outputDirectory: string, configDir?: string) => Promise<unknown>\n> {\n\tconst gondolinModule = await import('@earendil-works/gondolin');\n\treturn async (\n\t\tbuildConfig: BuildConfig,\n\t\toutputDirectory: string,\n\t\tconfigDir?: string,\n\t): Promise<unknown> =>\n\t\tawait gondolinModule.buildAssets(buildConfig, {\n\t\t\toutputDir: outputDirectory,\n\t\t\tverbose: false,\n\t\t\t...(configDir ? { configDir } : {}),\n\t\t} satisfies BuildOptions);\n}\n\nfunction createRedirectedWrite(output: BuildOutput): typeof process.stderr.write {\n\treturn ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tconst writeCallback = typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;\n\t\tconst wrote = output.write(chunk);\n\t\twriteCallback?.();\n\t\treturn wrote;\n\t}) as typeof process.stderr.write;\n}\n\nasync function withCapturedBuildOutput<TResult>(\n\toutput: BuildOutput | undefined,\n\tfn: () => Promise<TResult>,\n): Promise<TResult> {\n\tif (!output) {\n\t\treturn await fn();\n\t}\n\n\tconst originalStderrWrite = process.stderr.write.bind(process.stderr);\n\tconst originalStdoutWrite = process.stdout.write.bind(process.stdout);\n\tconst originalCi = process.env.CI;\n\tconst redirectedWrite = createRedirectedWrite(output);\n\n\tprocess.stderr.write = redirectedWrite;\n\tprocess.stdout.write = redirectedWrite;\n\tprocess.env.CI = 'true';\n\n\ttry {\n\t\treturn await fn();\n\t} finally {\n\t\tprocess.stderr.write = originalStderrWrite;\n\t\tprocess.stdout.write = originalStdoutWrite;\n\t\tif (originalCi === undefined) {\n\t\t\tdelete process.env.CI;\n\t\t} else {\n\t\t\tprocess.env.CI = originalCi;\n\t\t}\n\t}\n}\n\nexport function computeBuildFingerprint(\n\tbuildConfig: BuildConfig,\n\tgondolinVersion: string = 'unknown',\n\tfingerprintInput?: unknown,\n): string {\n\tconst payload =\n\t\tfingerprintInput === undefined\n\t\t\t? `${stableSerialize(buildConfig)}|${gondolinVersion}`\n\t\t\t: `${stableSerialize(buildConfig)}|${gondolinVersion}|${stableSerialize(fingerprintInput)}`;\n\n\treturn crypto.createHash('sha256').update(payload).digest('hex').slice(0, 16);\n}\n\nexport async function computeEffectiveBuildFingerprint(options: {\n\treadonly buildConfig: BuildConfig;\n\treadonly configDir?: string;\n\treadonly fingerprintInput?: unknown;\n\treadonly gondolinVersion?: string;\n}): Promise<{\n\treadonly fingerprint: string;\n\treadonly rootfsInitExtraContent: string;\n}> {\n\tconst resolvedRootfsInitExtra = await resolveRootfsInitExtra({\n\t\tbuildConfig: options.buildConfig,\n\t\t...(options.configDir ? { configDir: options.configDir } : {}),\n\t});\n\tconst fingerprint = computeBuildFingerprint(options.buildConfig, options.gondolinVersion, {\n\t\tagentVmRootfsInitExtra: resolvedRootfsInitExtra.fingerprintInput,\n\t\t...(options.fingerprintInput === undefined\n\t\t\t? {}\n\t\t\t: { callerFingerprintInput: options.fingerprintInput }),\n\t});\n\n\treturn {\n\t\tfingerprint,\n\t\trootfsInitExtraContent: resolvedRootfsInitExtra.content,\n\t};\n}\n\nexport async function buildImage(\n\toptions: BuildImageOptions,\n\tdependencies: BuildPipelineDependencies = {},\n): Promise<BuildImageResult> {\n\tconst effectiveBuildFingerprint = await computeEffectiveBuildFingerprint({\n\t\tbuildConfig: options.buildConfig,\n\t\t...(options.configDir ? { configDir: options.configDir } : {}),\n\t\t...(options.fingerprintInput === undefined\n\t\t\t? {}\n\t\t\t: { fingerprintInput: options.fingerprintInput }),\n\t\t...(dependencies.gondolinVersion ? { gondolinVersion: dependencies.gondolinVersion } : {}),\n\t});\n\tconst fingerprint = effectiveBuildFingerprint.fingerprint;\n\tconst imagePath = path.join(options.cacheDir, fingerprint);\n\n\tif (options.fullReset) {\n\t\tawait fs.rm(imagePath, { recursive: true, force: true });\n\t}\n\n\tif (await hasBuiltImageAssets(imagePath)) {\n\t\treturn {\n\t\t\tbuilt: false,\n\t\t\tfingerprint,\n\t\t\timagePath,\n\t\t};\n\t}\n\n\tawait fs.mkdir(imagePath, { recursive: true });\n\tconst buildAssetsImplementation = dependencies.buildAssets ?? (await loadBuildAssets());\n\tconst effectiveBuildConfig = await prepareBuildConfigWithAgentVmRootfsInitExtra({\n\t\tbuildConfig: options.buildConfig,\n\t\timagePath,\n\t\trootfsInitExtraContent: effectiveBuildFingerprint.rootfsInitExtraContent,\n\t});\n\tawait withCapturedBuildOutput(options.output, async () => {\n\t\tawait buildAssetsImplementation(effectiveBuildConfig, imagePath, options.configDir);\n\t});\n\n\tif (!(await hasBuiltImageAssets(imagePath))) {\n\t\tthrow new Error(`Expected Gondolin assets to be written to ${imagePath}.`);\n\t}\n\n\treturn {\n\t\tbuilt: true,\n\t\tfingerprint,\n\t\timagePath,\n\t};\n}\n","import fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nconst requireFromHere = createRequire(import.meta.url);\n\nconst gondolinPackageJsonSchema = z.object({\n\tversion: z.string().min(1),\n});\n\nfunction isMissingFileError(error: unknown): boolean {\n\treturn typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';\n}\n\nfunction getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nexport function parseMinimumZigVersion(rawContents: string): string {\n\tconst match = rawContents.match(/\\.minimum_zig_version\\s*=\\s*\"([^\"]*)\"/u);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t'minimum_zig_version declaration not found. Expected a line like `.minimum_zig_version = \"0.15.2\"`.',\n\t\t);\n\t}\n\n\tconst version = match[1];\n\tif (!version) {\n\t\tthrow new Error('minimum_zig_version is empty.');\n\t}\n\treturn version;\n}\n\nexport function resolveGondolinPackageJsonPath(): string {\n\treturn requireFromHere.resolve('@earendil-works/gondolin/package.json');\n}\n\nexport async function resolveGondolinPackageSpec(): Promise<string> {\n\tconst packageJsonPath = resolveGondolinPackageJsonPath();\n\tconst parsed: unknown = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));\n\tconst packageJson = gondolinPackageJsonSchema.parse(parsed);\n\treturn `@earendil-works/gondolin@${packageJson.version}`;\n}\n\nexport interface ResolveGondolinMinimumZigVersionOptions {\n\treadonly buildZigZonPath?: string;\n}\n\nasync function resolveDefaultBuildZigZonPath(): Promise<string> {\n\tconst packageJsonPath = resolveGondolinPackageJsonPath();\n\treturn path.join(path.dirname(packageJsonPath), 'dist', 'guest', 'build.zig.zon');\n}\n\nexport async function resolveGondolinMinimumZigVersion(\n\toptions: ResolveGondolinMinimumZigVersionOptions = {},\n): Promise<string> {\n\tconst zonPath = options.buildZigZonPath ?? (await resolveDefaultBuildZigZonPath());\n\tlet rawContents: string;\n\ttry {\n\t\trawContents = await fs.readFile(zonPath, 'utf8');\n\t} catch (error) {\n\t\tif (isMissingFileError(error)) {\n\t\t\tthrow new Error(`Missing Gondolin build.zig.zon at '${zonPath}'.`, { cause: error });\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Failed to read Gondolin build.zig.zon at '${zonPath}': ${getErrorMessage(error)}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\n\ttry {\n\t\treturn parseMinimumZigVersion(rawContents);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Failed to parse Gondolin build.zig.zon at '${zonPath}': ${getErrorMessage(error)}`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nconst AUTH_GUEST_PATH_PREFIXES = [\n\t'/home/agent/.aws',\n\t'/home/agent/.claude',\n\t'/home/agent/.codex',\n\t'/home/agent/.gemini',\n\t'/home/openclaw/.aws',\n\t'/home/openclaw/.claude',\n\t'/home/openclaw/.codex',\n\t'/home/openclaw/.gemini',\n\t'/home/openclaw/.openclaw',\n] as const;\n\nexport interface WritableMountPolicy {\n\treadonly allowAuthWrite: boolean;\n\treadonly writableAllowedGuestPrefixes: readonly string[];\n}\n\nexport interface RuntimeMountPolicyConfig {\n\treadonly extraMounts: Readonly<Record<string, string>>;\n\treadonly mountControls: WritableMountPolicy;\n}\n\nfunction resolveAuthHostPrefixes(hostHome: string): readonly string[] {\n\treturn [\n\t\tpath.join(hostHome, '.aws'),\n\t\tpath.join(hostHome, '.claude'),\n\t\tpath.join(hostHome, '.codex'),\n\t\tpath.join(hostHome, '.gemini'),\n\t];\n}\n\nexport function resolveGuestMountPath(guestPath: string, workDir: string): string {\n\tif (path.isAbsolute(guestPath)) {\n\t\treturn path.resolve(guestPath);\n\t}\n\n\treturn path.resolve(workDir, guestPath);\n}\n\nfunction isPathWithinPrefix(candidatePath: string, prefixPath: string): boolean {\n\tconst relativePath = path.relative(prefixPath, candidatePath);\n\treturn relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));\n}\n\nasync function normalizeHostPath(hostPath: string): Promise<string> {\n\tconst resolvedHostPath = path.resolve(hostPath);\n\n\ttry {\n\t\treturn await fs.realpath(resolvedHostPath);\n\t} catch {\n\t\treturn resolvedHostPath;\n\t}\n}\n\nfunction pathsOverlap(candidatePath: string, protectedPath: string): boolean {\n\treturn (\n\t\tisPathWithinPrefix(candidatePath, protectedPath) ||\n\t\tisPathWithinPrefix(protectedPath, candidatePath)\n\t);\n}\n\nexport function validateWritableMount(\n\tguestPath: string,\n\tpolicy: WritableMountPolicy,\n\toptions: { readonly workDir: string },\n): void {\n\tconst resolvedGuestPath = resolveGuestMountPath(guestPath, options.workDir);\n\tconst resolvedAllowedPrefixes = policy.writableAllowedGuestPrefixes.map((allowedPrefix) =>\n\t\tresolveGuestMountPath(allowedPrefix, options.workDir),\n\t);\n\n\tconst isAllowedGuestPath = resolvedAllowedPrefixes.some((allowedPrefix) =>\n\t\tisPathWithinPrefix(resolvedGuestPath, allowedPrefix),\n\t);\n\tif (!isAllowedGuestPath) {\n\t\tthrow new Error(\n\t\t\t`Writable mount guest path '${resolvedGuestPath}' is outside writable allowlist [${resolvedAllowedPrefixes.join(', ')}].`,\n\t\t);\n\t}\n\n\tif (!policy.allowAuthWrite) {\n\t\tconst targetsProtectedGuestPath = AUTH_GUEST_PATH_PREFIXES.some((authPrefix) =>\n\t\t\tisPathWithinPrefix(resolvedGuestPath, authPrefix),\n\t\t);\n\t\tif (targetsProtectedGuestPath) {\n\t\t\tthrow new Error(\n\t\t\t\t`Writable mount guest path '${resolvedGuestPath}' targets an auth mount path. Set mountControls.allowAuthWrite=true to permit auth writes.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport async function validateRuntimeMountPolicy(\n\tconfig: RuntimeMountPolicyConfig,\n\toptions: { readonly hostHome: string; readonly workDir: string },\n): Promise<void> {\n\tconst mountEntries = Object.entries(config.extraMounts);\n\tfor (const [guestPath] of mountEntries) {\n\t\tvalidateWritableMount(guestPath, config.mountControls, options);\n\t}\n\n\tif (config.mountControls.allowAuthWrite) {\n\t\treturn;\n\t}\n\n\tconst absoluteHostMountEntries = mountEntries.filter(([, hostPath]) => path.isAbsolute(hostPath));\n\tconst [protectedHostPaths, writableHostPaths] = await Promise.all([\n\t\tPromise.all(\n\t\t\tresolveAuthHostPrefixes(options.hostHome).map(\n\t\t\t\tasync (authHostPrefix) => await normalizeHostPath(authHostPrefix),\n\t\t\t),\n\t\t),\n\t\tPromise.all(\n\t\t\tabsoluteHostMountEntries.map(async ([, hostPath]) => await normalizeHostPath(hostPath)),\n\t\t),\n\t]);\n\n\tfor (const resolvedWritableHostPath of writableHostPaths) {\n\t\tconst overlapsProtectedHostPath = protectedHostPaths.some((authHostPrefix) =>\n\t\t\tpathsOverlap(resolvedWritableHostPath, authHostPrefix),\n\t\t);\n\n\t\tif (overlapsProtectedHostPath) {\n\t\t\tthrow new Error(\n\t\t\t\t`Writable host path '${resolvedWritableHostPath}' targets an auth host directory. Set mountControls.allowAuthWrite=true to permit auth writes.`,\n\t\t\t);\n\t\t}\n\t}\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { VirtualProvider } from '@earendil-works/gondolin';\n\nexport interface PinnedRealFsRoot {\n\treadonly hostPath: string;\n\treadonly realPath: string;\n\treadonly fd: number;\n\treadonly device: number;\n\treadonly inode: number;\n}\n\nexport interface CreatePinnedRealFsProviderOptions {\n\treadonly root: PinnedRealFsRoot;\n\treadonly createRealFsProvider: (hostPath: string) => VirtualProvider;\n}\n\nfunction formatRootIdentity(root: PinnedRealFsRoot): string {\n\treturn `${root.device}:${root.inode}`;\n}\n\nfunction openDirectoryNoFollow(candidatePath: string): number {\n\treturn fs.openSync(\n\t\tcandidatePath,\n\t\tfs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,\n\t);\n}\n\nexport function pinRealFsRoot(hostPath: string): PinnedRealFsRoot {\n\tif (!hostPath || !path.isAbsolute(hostPath)) {\n\t\tthrow new Error(`Pinned RealFS root must be a non-empty absolute path: ${hostPath}`);\n\t}\n\n\tconst resolvedHostPath = path.resolve(hostPath);\n\tconst fd = openDirectoryNoFollow(resolvedHostPath);\n\ttry {\n\t\tconst stats = fs.fstatSync(fd);\n\t\tif (!stats.isDirectory()) {\n\t\t\tthrow new Error(`Pinned RealFS root is not a directory: ${resolvedHostPath}`);\n\t\t}\n\t\tconst realPath = fs.realpathSync(resolvedHostPath);\n\t\tconst realPathStats = fs.statSync(realPath);\n\t\tif (realPathStats.dev !== stats.dev || realPathStats.ino !== stats.ino) {\n\t\t\tthrow new Error(\n\t\t\t\t`Pinned RealFS root changed while opening: ${resolvedHostPath} opened ${stats.dev}:${stats.ino} but resolved to ${realPathStats.dev}:${realPathStats.ino}`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tdevice: stats.dev,\n\t\t\tfd,\n\t\t\thostPath: resolvedHostPath,\n\t\t\tinode: stats.ino,\n\t\t\trealPath,\n\t\t};\n\t} catch (error) {\n\t\tfs.closeSync(fd);\n\t\tthrow error;\n\t}\n}\n\nexport function closePinnedRealFsRoot(root: PinnedRealFsRoot): void {\n\tfs.closeSync(root.fd);\n}\n\nexport function assertPinnedRealFsRoot(root: PinnedRealFsRoot): void {\n\tconst pinnedStats = fs.fstatSync(root.fd);\n\tconst currentStats = fs.statSync(root.realPath);\n\tif (\n\t\tpinnedStats.dev !== root.device ||\n\t\tpinnedStats.ino !== root.inode ||\n\t\tcurrentStats.dev !== root.device ||\n\t\tcurrentStats.ino !== root.inode\n\t) {\n\t\tthrow new Error(\n\t\t\t`Pinned RealFS root changed before mount access: ${root.realPath} expected ${formatRootIdentity(root)} got ${currentStats.dev}:${currentStats.ino}`,\n\t\t);\n\t}\n}\n\ntype ProviderMethod = (...args: unknown[]) => unknown;\n\n/* oxlint-disable typescript-eslint/no-unsafe-type-assertion -- Reflect.get()\n loses the method signature from Gondolin's VirtualProvider union. The proxy\n keeps the same provider object and only wraps callable properties with the\n pinned-root assertion. */\nexport function createPinnedRealFsProvider(\n\toptions: CreatePinnedRealFsProviderOptions,\n): VirtualProvider {\n\tassertPinnedRealFsRoot(options.root);\n\tconst provider = options.createRealFsProvider(options.root.realPath);\n\n\treturn new Proxy(provider, {\n\t\tget(target: VirtualProvider, property: string | symbol, receiver: unknown): unknown {\n\t\t\tconst value = Reflect.get(target, property, receiver) as unknown;\n\t\t\tif (typeof value !== 'function') {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\treturn (...methodArguments: readonly unknown[]): unknown => {\n\t\t\t\tassertPinnedRealFsRoot(options.root);\n\t\t\t\treturn Reflect.apply(value as ProviderMethod, target, methodArguments);\n\t\t\t};\n\t\t},\n\t});\n}\n/* oxlint-enable typescript-eslint/no-unsafe-type-assertion */\n","export interface PolicySources {\n\treadonly base: readonly string[];\n\treadonly profile: readonly string[];\n\treadonly extra: readonly string[];\n}\n\nexport function normalizeHostname(rawHostname: string): string {\n\treturn rawHostname.trim().toLowerCase().replace(/\\.+$/u, '');\n}\n\nexport function dedupeStable(values: readonly string[]): string[] {\n\tconst seenHostnames = new Set<string>();\n\tconst normalizedValues: string[] = [];\n\n\tfor (const value of values) {\n\t\tconst normalizedValue = normalizeHostname(value);\n\t\tif (normalizedValue.length === 0 || normalizedValue.startsWith('#')) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!seenHostnames.has(normalizedValue)) {\n\t\t\tseenHostnames.add(normalizedValue);\n\t\t\tnormalizedValues.push(normalizedValue);\n\t\t}\n\t}\n\n\treturn normalizedValues;\n}\n\nexport function compilePolicy(sources: PolicySources): string[] {\n\treturn dedupeStable([...sources.base, ...sources.profile, ...sources.extra]);\n}\n","import type { MediatedSecretSpec } from '@agent-vm/secret-management';\nimport {\n\tMemoryProvider,\n\tReadonlyProvider,\n\tRealFSProvider,\n\tShadowProvider,\n\tVM,\n\tcreateHttpHooks,\n\tcreateShadowPathPredicate,\n\ttype CreateHttpHooksResult,\n\ttype EnableIngressOptions,\n\ttype EnableSshOptions,\n\ttype IngressRoute as GondolinIngressRoute,\n\ttype ShadowPredicate,\n\ttype ShadowProviderOptions,\n\ttype VMOptions,\n\ttype VirtualProvider,\n} from '@earendil-works/gondolin';\n\nimport {\n\tclosePinnedRealFsRoot,\n\tcreatePinnedRealFsProvider,\n\ttype PinnedRealFsRoot,\n} from './pinned-realfs.js';\n\nexport const SYNTHETIC_DNS_IPV4_BENCHMARK = '198.18.0.1';\nexport const SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK = '::ffff:198.18.0.1';\n\nexport interface ExecResult {\n\treadonly exitCode: number;\n\treadonly stdout: string;\n\treadonly stderr: string;\n}\n\nexport type IngressRoute = GondolinIngressRoute;\n\nexport interface SshAccess {\n\treadonly host: string;\n\treadonly command?: string;\n\treadonly identityFile?: string;\n\treadonly port: number;\n\treadonly user?: string;\n}\n\nexport interface IngressAccess {\n\treadonly host: string;\n\treadonly port: number;\n}\n\nexport interface ManagedVmInstance {\n\treadonly id: string;\n\texec(command: string): Promise<{\n\t\treadonly exitCode: number;\n\t\treadonly stdout?: string;\n\t\treadonly stderr?: string;\n\t}>;\n\tenableSsh(options?: EnableSshOptions): Promise<SshAccess>;\n\tenableIngress(options?: EnableIngressOptions): Promise<IngressAccess>;\n\tsetIngressRoutes(routes: readonly IngressRoute[]): void;\n\tclose(): Promise<void>;\n}\n\nexport interface ManagedVmDependencies {\n\tcreateVm(vmOptions: VMOptions): Promise<ManagedVmInstance>;\n\tcreateHttpHooks(options: {\n\t\treadonly allowedHosts: readonly string[];\n\t\treadonly secrets: Record<string, MediatedSecretSpec>;\n\t\treadonly onRequest?: (request: Request) => Promise<Request | Response | void>;\n\t\treadonly onResponse?: (response: Response) => Promise<Response | void>;\n\t}): Pick<CreateHttpHooksResult, 'env' | 'httpHooks'>;\n\tclosePinnedRealFsRoot(root: PinnedRealFsRoot): void;\n\tcreatePinnedRealFsProvider(root: PinnedRealFsRoot): VirtualProvider;\n\tcreateRealFsProvider(hostPath: string): VirtualProvider;\n\tcreateReadonlyProvider(provider: VirtualProvider): VirtualProvider;\n\tcreateMemoryProvider(): VirtualProvider;\n\tcreateShadowProvider(provider: VirtualProvider, options: ShadowProviderOptions): VirtualProvider;\n\tcreateShadowPathPredicate(paths: readonly string[]): ShadowPredicate;\n}\n\nexport interface VfsMountSpec {\n\treadonly kind: 'realfs' | 'realfs-readonly' | 'memory' | 'shadow';\n\treadonly hostPath?: string;\n\treadonly pinnedHostRoot?: PinnedRealFsRoot;\n\treadonly shadowConfig?: {\n\t\treadonly deny: readonly string[];\n\t\treadonly tmpfs: readonly string[];\n\t};\n}\n\nexport interface CreateVmOptions {\n\treadonly imagePath: string;\n\treadonly memory: string;\n\treadonly cpus: number;\n\treadonly rootfsMode: 'readonly' | 'memory' | 'cow';\n\treadonly allowedHosts: readonly string[];\n\treadonly secrets: Record<string, MediatedSecretSpec>;\n\treadonly vfsMounts: Record<string, VfsMountSpec>;\n\treadonly tcpHosts?: Record<string, string>;\n\treadonly env?: Record<string, string>;\n\treadonly sessionLabel?: string;\n\treadonly onRequest?: (request: Request) => Promise<Request | Response | void>;\n\treadonly onResponse?: (response: Response) => Promise<Response | void>;\n}\n\nexport interface ManagedVm {\n\treadonly id: string;\n\texec(command: string): Promise<ExecResult>;\n\tenableSsh(options?: EnableSshOptions): Promise<SshAccess>;\n\tenableIngress(options?: EnableIngressOptions): Promise<IngressAccess>;\n\tgetVmInstance(): ManagedVmInstance;\n\tsetIngressRoutes(routes: readonly IngressRoute[]): void;\n\tclose(): Promise<void>;\n}\n\n/* oxlint-disable typescript-eslint/no-unsafe-type-assertion -- VM.create() returns\n Gondolin's concrete VM class; this adapter exposes only the narrower\n ManagedVmInstance interface used by agent-vm. */\nfunction createDefaultDependencies(): ManagedVmDependencies {\n\tconst createDefaultRealFsProvider = (hostPath: string): VirtualProvider =>\n\t\tnew RealFSProvider(hostPath);\n\treturn {\n\t\tcreateVm: async (vmOptions: VMOptions): Promise<ManagedVmInstance> =>\n\t\t\t(await VM.create(vmOptions)) as unknown as ManagedVmInstance,\n\t\tcreateHttpHooks: (hookOptions) =>\n\t\t\tcreateHttpHooks({\n\t\t\t\tallowedHosts: [...hookOptions.allowedHosts],\n\t\t\t\tsecrets: Object.fromEntries(\n\t\t\t\t\tObject.entries(hookOptions.secrets).map(([secretName, secretSpec]) => [\n\t\t\t\t\t\tsecretName,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\thosts: [...secretSpec.hosts],\n\t\t\t\t\t\t\tvalue: secretSpec.value,\n\t\t\t\t\t\t},\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\t...(hookOptions.onRequest ? { onRequest: hookOptions.onRequest } : {}),\n\t\t\t\t...(hookOptions.onResponse ? { onResponse: hookOptions.onResponse } : {}),\n\t\t\t}),\n\t\tclosePinnedRealFsRoot,\n\t\tcreatePinnedRealFsProvider: (root: PinnedRealFsRoot): VirtualProvider =>\n\t\t\tcreatePinnedRealFsProvider({\n\t\t\t\tcreateRealFsProvider: createDefaultRealFsProvider,\n\t\t\t\troot,\n\t\t\t}),\n\t\tcreateRealFsProvider: createDefaultRealFsProvider,\n\t\tcreateReadonlyProvider: (provider: VirtualProvider): VirtualProvider =>\n\t\t\tnew ReadonlyProvider(provider),\n\t\tcreateMemoryProvider: (): VirtualProvider => new MemoryProvider(),\n\t\tcreateShadowProvider: (\n\t\t\tprovider: VirtualProvider,\n\t\t\tshadowOptions: ShadowProviderOptions,\n\t\t): VirtualProvider => new ShadowProvider(provider, shadowOptions),\n\t\tcreateShadowPathPredicate: (paths: readonly string[]): ShadowPredicate =>\n\t\t\tcreateShadowPathPredicate([...paths]),\n\t};\n}\n/* oxlint-enable typescript-eslint/no-unsafe-type-assertion */\n\nfunction normalizeShadowPath(pathValue: string): string {\n\tconst trimmedPath = pathValue.trim();\n\tif (trimmedPath.startsWith('/')) {\n\t\treturn trimmedPath;\n\t}\n\n\tconst relativePath = trimmedPath.startsWith('./') ? trimmedPath.slice('./'.length) : trimmedPath;\n\treturn `/${relativePath}`;\n}\n\nfunction createRealFsProviderForSpec(\n\tmountSpec: VfsMountSpec,\n\tdependencies: ManagedVmDependencies,\n\tmountKind: string,\n): VirtualProvider {\n\tif (mountSpec.pinnedHostRoot) {\n\t\treturn dependencies.createPinnedRealFsProvider(mountSpec.pinnedHostRoot);\n\t}\n\tif (mountSpec.hostPath) {\n\t\treturn dependencies.createRealFsProvider(mountSpec.hostPath);\n\t}\n\n\tthrow new Error(`${mountKind} mounts require hostPath or pinnedHostRoot`);\n}\n\nfunction createProviderFromSpec(\n\tmountSpec: VfsMountSpec,\n\tdependencies: ManagedVmDependencies,\n): VirtualProvider {\n\tswitch (mountSpec.kind) {\n\t\tcase 'memory':\n\t\t\treturn dependencies.createMemoryProvider();\n\t\tcase 'realfs': {\n\t\t\treturn createRealFsProviderForSpec(mountSpec, dependencies, 'realfs');\n\t\t}\n\t\tcase 'realfs-readonly': {\n\t\t\treturn dependencies.createReadonlyProvider(\n\t\t\t\tcreateRealFsProviderForSpec(mountSpec, dependencies, 'realfs-readonly'),\n\t\t\t);\n\t\t}\n\t\tcase 'shadow': {\n\t\t\tconst baseProvider =\n\t\t\t\tmountSpec.hostPath || mountSpec.pinnedHostRoot\n\t\t\t\t\t? createRealFsProviderForSpec(mountSpec, dependencies, 'shadow')\n\t\t\t\t\t: dependencies.createMemoryProvider();\n\n\t\t\tlet shadowProvider = baseProvider;\n\t\t\tconst shadowConfig = mountSpec.shadowConfig;\n\n\t\t\tif (shadowConfig?.deny.length) {\n\t\t\t\tshadowProvider = dependencies.createShadowProvider(shadowProvider, {\n\t\t\t\t\tshouldShadow: dependencies.createShadowPathPredicate(\n\t\t\t\t\t\tshadowConfig.deny.map((shadowPath) => normalizeShadowPath(shadowPath)),\n\t\t\t\t\t),\n\t\t\t\t\twriteMode: 'deny',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (shadowConfig?.tmpfs.length) {\n\t\t\t\tshadowProvider = dependencies.createShadowProvider(shadowProvider, {\n\t\t\t\t\tshouldShadow: dependencies.createShadowPathPredicate(\n\t\t\t\t\t\tshadowConfig.tmpfs.map((shadowPath) => normalizeShadowPath(shadowPath)),\n\t\t\t\t\t),\n\t\t\t\t\twriteMode: 'tmpfs',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn shadowProvider;\n\t\t}\n\t\tdefault: {\n\t\t\tthrow new Error(`Unsupported VFS mount kind: ${String(mountSpec.kind)}`);\n\t\t}\n\t}\n}\n\nfunction createVfsMounts(\n\tvfsMounts: Record<string, VfsMountSpec>,\n\tdependencies: ManagedVmDependencies,\n): Record<string, VirtualProvider> {\n\tconst mountMap: Record<string, VirtualProvider> = {};\n\n\tfor (const [guestPath, mountSpec] of Object.entries(vfsMounts)) {\n\t\tmountMap[guestPath] = createProviderFromSpec(mountSpec, dependencies);\n\t}\n\n\treturn mountMap;\n}\n\nfunction collectPinnedRealFsRoots(\n\tvfsMounts: Record<string, VfsMountSpec>,\n): readonly PinnedRealFsRoot[] {\n\tconst roots = new Map<number, PinnedRealFsRoot>();\n\tfor (const mountSpec of Object.values(vfsMounts)) {\n\t\tif (mountSpec.pinnedHostRoot) {\n\t\t\troots.set(mountSpec.pinnedHostRoot.fd, mountSpec.pinnedHostRoot);\n\t\t}\n\t}\n\treturn [...roots.values()];\n}\n\nfunction closePinnedRealFsRoots(\n\troots: readonly PinnedRealFsRoot[],\n\tdependencies: ManagedVmDependencies,\n): void {\n\tfor (const root of roots) {\n\t\tdependencies.closePinnedRealFsRoot(root);\n\t}\n}\n\nfunction closePinnedRealFsRootsAfterFailure(\n\troots: readonly PinnedRealFsRoot[],\n\tdependencies: ManagedVmDependencies,\n): void {\n\ttry {\n\t\tclosePinnedRealFsRoots(roots, dependencies);\n\t} catch {\n\t\t// Preserve the VM creation failure; leaked-fd risk is lower than hiding\n\t\t// the root cause of a failed lease.\n\t}\n}\n\nexport async function createManagedVm(\n\toptions: CreateVmOptions,\n\tdependencies: ManagedVmDependencies = createDefaultDependencies(),\n): Promise<ManagedVm> {\n\tconst hasTcpHosts = options.tcpHosts && Object.keys(options.tcpHosts).length > 0;\n\tconst pinnedRealFsRoots = collectPinnedRealFsRoots(options.vfsMounts);\n\tlet vmInstance: ManagedVmInstance;\n\ttry {\n\t\tconst hookBundle = dependencies.createHttpHooks({\n\t\t\tallowedHosts: options.allowedHosts,\n\t\t\tsecrets: options.secrets,\n\t\t\t...(options.onRequest ? { onRequest: options.onRequest } : {}),\n\t\t\t...(options.onResponse ? { onResponse: options.onResponse } : {}),\n\t\t});\n\t\tvmInstance = await dependencies.createVm({\n\t\t\t...(options.imagePath.length > 0 ? { sandbox: { imagePath: options.imagePath } } : {}),\n\t\t\t...(options.sessionLabel ? { sessionLabel: options.sessionLabel } : {}),\n\t\t\trootfs: {\n\t\t\t\tmode: options.rootfsMode,\n\t\t\t},\n\t\t\tmemory: options.memory,\n\t\t\tcpus: options.cpus,\n\t\t\tenv: {\n\t\t\t\t...hookBundle.env,\n\t\t\t\t...options.env,\n\t\t\t},\n\t\t\thttpHooks: hookBundle.httpHooks,\n\t\t\tvfs: {\n\t\t\t\tfuseMount: '/data',\n\t\t\t\tmounts: createVfsMounts(options.vfsMounts, dependencies),\n\t\t\t},\n\t\t\t...(hasTcpHosts\n\t\t\t\t? {\n\t\t\t\t\t\tdns: {\n\t\t\t\t\t\t\tmode: 'synthetic',\n\t\t\t\t\t\t\tsyntheticIPv4: SYNTHETIC_DNS_IPV4_BENCHMARK,\n\t\t\t\t\t\t\tsyntheticIPv6: SYNTHETIC_DNS_IPV6_IPV4_MAPPED_BENCHMARK,\n\t\t\t\t\t\t\tsyntheticHostMapping: 'per-host',\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttcp: {\n\t\t\t\t\t\t\thosts: options.tcpHosts,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t});\n\t} catch (error) {\n\t\tclosePinnedRealFsRootsAfterFailure(pinnedRealFsRoots, dependencies);\n\t\tthrow error;\n\t}\n\n\treturn {\n\t\tid: vmInstance.id,\n\t\tasync exec(command: string): Promise<ExecResult> {\n\t\t\tconst executionResult = await vmInstance.exec(command);\n\t\t\treturn {\n\t\t\t\texitCode: executionResult.exitCode,\n\t\t\t\tstdout: executionResult.stdout ?? '',\n\t\t\t\tstderr: executionResult.stderr ?? '',\n\t\t\t};\n\t\t},\n\t\tasync enableSsh(sshOptions?: EnableSshOptions): Promise<SshAccess> {\n\t\t\treturn await vmInstance.enableSsh(sshOptions);\n\t\t},\n\t\tasync enableIngress(ingressOptions?: EnableIngressOptions): Promise<IngressAccess> {\n\t\t\treturn await vmInstance.enableIngress(ingressOptions);\n\t\t},\n\t\tgetVmInstance(): ManagedVmInstance {\n\t\t\treturn vmInstance;\n\t\t},\n\t\tsetIngressRoutes(routes: readonly IngressRoute[]): void {\n\t\t\tvmInstance.setIngressRoutes(routes);\n\t\t},\n\t\tasync close(): Promise<void> {\n\t\t\tlet closeError: unknown;\n\t\t\ttry {\n\t\t\t\tawait vmInstance.close();\n\t\t\t} catch (error) {\n\t\t\t\tcloseError = error;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tclosePinnedRealFsRoots(pinnedRealFsRoots, dependencies);\n\t\t\t} catch (error) {\n\t\t\t\tcloseError ??= error;\n\t\t\t}\n\t\t\tif (closeError !== undefined) {\n\t\t\t\tthrow closeError;\n\t\t\t}\n\t\t},\n\t};\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nexport interface VolumeConfigEntry {\n\treadonly guestPath: string;\n}\n\nexport interface ResolvedVolume {\n\treadonly hostDir: string;\n\treadonly guestPath: string;\n}\n\nexport async function ensureVolumeDir(\n\tcacheBase: string,\n\tworkspaceHash: string,\n\tvolumeName: string,\n): Promise<string> {\n\tconst volumeDirectory = path.join(cacheBase, workspaceHash, volumeName);\n\tawait fs.mkdir(volumeDirectory, { recursive: true });\n\treturn volumeDirectory;\n}\n\nexport async function resolveVolumeDirs(\n\tcacheBase: string,\n\tworkspaceHash: string,\n\tvolumes: Readonly<Record<string, VolumeConfigEntry>>,\n): Promise<Record<string, ResolvedVolume>> {\n\tconst resolvedVolumeEntries = await Promise.all(\n\t\tObject.entries(volumes).map(\n\t\t\tasync ([volumeName, volumeConfig]) =>\n\t\t\t\t[\n\t\t\t\t\tvolumeName,\n\t\t\t\t\t{\n\t\t\t\t\t\tguestPath: volumeConfig.guestPath,\n\t\t\t\t\t\thostDir: await ensureVolumeDir(cacheBase, workspaceHash, volumeName),\n\t\t\t\t\t},\n\t\t\t\t] satisfies readonly [string, ResolvedVolume],\n\t\t),\n\t);\n\n\treturn Object.fromEntries(resolvedVolumeEntries);\n}\n","import fs from 'node:fs/promises';\n\nexport async function writeFileAtomically(\n\tfilePath: string,\n\tcontent: string,\n\toptions: {\n\t\treadonly mode?: number;\n\t} = {},\n): Promise<void> {\n\tconst temporaryFilePath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n\tawait fs.writeFile(temporaryFilePath, content, {\n\t\tencoding: 'utf8',\n\t\t...(options.mode ? { mode: options.mode } : {}),\n\t});\n\ttry {\n\t\tawait fs.rename(temporaryFilePath, filePath);\n\t} catch (renameError) {\n\t\ttry {\n\t\t\tawait fs.rm(temporaryFilePath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to replace '${filePath}' (${renameError instanceof Error ? renameError.message : JSON.stringify(renameError)}) and failed to remove temporary file '${temporaryFilePath}': ${cleanupError instanceof Error ? cleanupError.message : JSON.stringify(cleanupError)}`,\n\t\t\t\t{ cause: cleanupError },\n\t\t\t);\n\t\t}\n\t\tthrow renameError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EAAE,OAAO,MAAM,CAAC;WACvC,cAAc;GACtB,MAAM,IAAI,MACT,sBAAsB,SAAS,KAAK,uBAAuB,QAAQ,YAAY,UAAU,KAAK,UAAU,YAAY,CAAC,yCAAyC,kBAAkB,KAAK,wBAAwB,QAAQ,aAAa,UAAU,KAAK,UAAU,aAAa,IACxQ,EAAE,OAAO,cAAc,CACvB;;EAEF,MAAM"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-vm/gondolin-adapter",
3
- "version": "0.0.69",
3
+ "version": "0.0.71",
4
4
  "description": "Adapter over @earendil-works/gondolin: VM build pipeline, image cache, and secret resolver.",
5
5
  "homepage": "https://github.com/ShravanSunder/agent-vm#readme",
6
6
  "bugs": {
@@ -29,9 +29,9 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@1password/sdk": "^0.4.0",
33
32
  "@earendil-works/gondolin": "0.9.1",
34
- "zod": "^4.4.3"
33
+ "zod": "^4.4.3",
34
+ "@agent-vm/secret-management": "0.0.71"
35
35
  },
36
36
  "scripts": {
37
37
  "build": "tsdown",