@aiwg/cockpit 2026.10.1 → 2026.10.4

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.
@@ -86,14 +86,43 @@ async function resolveExecutorBearer(tokenFile) {
86
86
  return token;
87
87
  }
88
88
 
89
- async function executorFetch(target, init = {}) {
89
+ function parseExecutorUrl(value) {
90
+ let url;
91
+ try { url = new URL(value); }
92
+ catch (cause) { throw executorAuthError('executor_target_refused', 'executor URL must be absolute HTTP(S)', cause); }
93
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
94
+ throw executorAuthError('executor_target_refused', 'executor URL must use HTTP(S) without URL credentials');
95
+ }
96
+ return url;
97
+ }
98
+
99
+ function allowedExecutorTarget(target, executorUrl = executorRequestContext.getStore()?.executorOrigin ?? EXECUTOR_URL) {
100
+ const url = parseExecutorUrl(target);
101
+ // The operator-configured origin is the allowlist, including scheme and port.
102
+ // AgentCards and request data cannot add destinations to it.
103
+ const origin = parseExecutorUrl(executorUrl).origin;
104
+ if (url.origin !== origin) {
105
+ throw executorAuthError('executor_target_refused', 'outbound target is outside the configured executor origin');
106
+ }
107
+ return url;
108
+ }
109
+
110
+ async function executorFetch(target, init = {}, executorUrl = executorRequestContext.getStore()?.executorOrigin ?? EXECUTOR_URL, hasFallback = false) {
111
+ const url = allowedExecutorTarget(target, executorUrl);
90
112
  const context = executorRequestContext.getStore();
91
113
  const headers = new Headers(init.headers);
92
- if (context && new URL(target).origin === context.executorOrigin && !headers.has('authorization')) {
114
+ if (context && url.origin === context.executorOrigin && !headers.has('authorization')) {
93
115
  const token = await resolveExecutorBearer(context.executorTokenFile);
94
116
  if (token) headers.set('authorization', `Bearer ${token}`);
95
117
  }
96
- return fetch(target, { ...init, headers });
118
+ const response = await fetch(url, { ...init, headers, redirect: 'manual' });
119
+ const text = !response.ok ? await logUpstreamError(response, hasFallback) : '';
120
+ if (response.type === 'opaqueredirect' || response.status === 0 || (response.status >= 300 && response.status < 400)) {
121
+ // Even same-origin redirects could replay credentials and a body to another agent or admin path.
122
+ throw executorAuthError('executor_redirect_refused', 'executor redirect refused');
123
+ }
124
+ // Error consumers must not resume an unbounded read of the original stream.
125
+ return response.ok ? response : new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers });
97
126
  }
98
127
 
99
128
  /** Serve a static file from the built web app, sandboxed to WEB_DIST. Returns true if served. */
@@ -532,11 +561,118 @@ export async function createUserIndexGraph(body, projectRoot = process.cwd()) {
532
561
  return { name, definition: config.index.graphs[name], config_path: configPath };
533
562
  }
534
563
 
564
+ // Keep validated retry metadata local to the projected response, never in its JSON.
565
+ const upstreamRetryAfter = new WeakMap();
566
+
535
567
  function json(res, status, body) {
536
- res.writeHead(status, { 'content-type': 'application/json' });
568
+ const retryAfter = [429, 503].includes(status) && body && upstreamRetryAfter.get(body);
569
+ res.writeHead(status, { 'content-type': 'application/json', ...(retryAfter ? { 'retry-after': retryAfter } : {}) });
537
570
  res.end(JSON.stringify(body));
538
571
  }
539
572
 
573
+ function redactErrorText(value) {
574
+ return String(value ?? '')
575
+ .replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi, (value) => {
576
+ try { const url = new URL(value); return `${url.origin}${url.pathname}`; }
577
+ catch { return '[redacted URL]'; }
578
+ })
579
+ .replace(/(authorization["']?\s*[:=]\s*["']?)Digest\s+[^\r\n]*/gi, '$1[redacted]')
580
+ .replace(/(authorization["']?\s*[:=]\s*["']?)(?:[A-Za-z][\w.-]*\s+)?[^\s,;]+/gi, '$1[redacted]')
581
+ .replace(/\bBearer\s+[^\s"'<>]+/gi, 'Bearer [redacted]')
582
+ .replace(/((?:token|secret|password|api[_-]?key)["']?\s*[=:]\s*["']?)[^\s,;"']+/gi, '$1[redacted]');
583
+ }
584
+
585
+ function bridgeErrorBody(err, code = err?.code ?? 'bridge_upstream_error') {
586
+ console.error('[cockpit-bridge] request failed', {
587
+ code: redactErrorText(code), message: redactErrorText(err?.message ?? err), stack: redactErrorText(err?.stack),
588
+ });
589
+ // Exception codes can also contain subprocess or upstream diagnostics.
590
+ const publicCodes = new Set([
591
+ 'bridge_upstream_error', 'upstream_not_found', 'upstream_method_not_allowed',
592
+ 'executor_credential_unavailable', 'executor_credential_invalid', 'executor_credential_permissions',
593
+ 'executor_unauthenticated', 'executor_forbidden', 'executor_trust_required', 'executor_refused',
594
+ 'executor_target_refused', 'executor_redirect_refused', 'executor_attach_target_refused', 'mock_executor_refused',
595
+ 'activity_invalid_request', 'activity_scope_required', 'activity_invalid_filter',
596
+ 'activity_malformed_envelope', 'activity_malformed_export', 'activity_upstream_error',
597
+ 'reconnect_failed', 'approval_response_failed', 'session_screen_unavailable',
598
+ 'invalid_graph_definition', 'artifact_not_found', 'ambiguous_artifact', 'clone_failed',
599
+ 'agent_not_registered', 'session_create_missing_id', 'OG_CONTRACT_UNSUPPORTED',
600
+ ]);
601
+ if (!publicCodes.has(code)) code = 'bridge_upstream_error';
602
+ const validationMessages = {
603
+ activity_invalid_request: 'Activity request must be an object.',
604
+ activity_scope_required: 'Activity requires tenant_id, host_id, instance_id and agent_id.',
605
+ activity_invalid_filter: 'Activity filters must use supported names and values; limit must be 1..1000.',
606
+ };
607
+ const message = validationMessages[code] ?? 'Bridge request failed.';
608
+ const recovery = code === 'executor_trust_required' && [
609
+ 'Sandbox CA and bootstrap trust are ready.',
610
+ 'Refresh sandbox CA/bootstrap readiness, rotate stale trust material, then reload Cockpit.',
611
+ 'Plaintext local development mode only; enable sandbox mTLS before using remote or shared executors.',
612
+ 'Configure sandbox CA provider and client trust refs before connecting Cockpit.',
613
+ ].includes(err?.recovery) ? err.recovery : undefined;
614
+ return { error: code, message, ...(recovery ? { recovery } : {}) };
615
+ }
616
+
617
+ async function logUpstreamError(response, hasFallback = false) {
618
+ const reader = response.clone().body?.getReader();
619
+ // Tee cancellation waits for both branches; start it without awaiting the other reader.
620
+ void response.body?.cancel().catch(() => {});
621
+ const chunks = [];
622
+ let size = 0;
623
+ let timeout;
624
+ try {
625
+ if (reader) await Promise.race([
626
+ (async () => {
627
+ while (size < 8192) {
628
+ const { done, value } = await reader.read();
629
+ if (done) break;
630
+ const chunk = Buffer.from(value.subarray(0, 8192 - size));
631
+ chunks.push(chunk);
632
+ size += chunk.length;
633
+ }
634
+ })(),
635
+ new Promise((resolve) => { timeout = setTimeout(resolve, 1000); }),
636
+ ]);
637
+ } catch {
638
+ // Preserve any bounded diagnostic already read.
639
+ } finally {
640
+ clearTimeout(timeout);
641
+ void reader?.cancel().catch(() => {});
642
+ }
643
+ const text = Buffer.concat(chunks, size).toString('utf8');
644
+ let body;
645
+ try { body = JSON.stringify(redactAuditValue(JSON.parse(text))); }
646
+ catch { body = text; }
647
+ const log = hasFallback && [404, 405].includes(response.status) ? console.debug : console.error;
648
+ log('[cockpit-bridge] upstream request failed', {
649
+ status: response.status,
650
+ body: Buffer.from(redactErrorText(body)).subarray(0, 4096).toString('utf8').replace(/\uFFFD$/, ''),
651
+ });
652
+ return text;
653
+ }
654
+
655
+ function safeUpstreamError(status, body) {
656
+ const code = typeof body?.code === 'string' && body.code === body.code.trim() && /^[a-z0-9_.-]{1,64}$/.test(body.code) ? body.code : undefined;
657
+ return { ...(code ? { code } : {}), status };
658
+ }
659
+
660
+ function upstreamErrorBody(status, body, headers) {
661
+ // Preserve only locally defined projections needed for recovery/negotiation.
662
+ const managed = managedDockerLaunchError(status, body);
663
+ const generic = { error: 'bridge_upstream_error', message: 'Bridge request failed.' };
664
+ const projected = managed.body !== body ? managed.body
665
+ : isA2AVersionNotSupported(status, body) ? { ...generic, error: 'version_not_supported', code: 'version_not_supported' }
666
+ : generic;
667
+ const retryAfter = headers?.get('retry-after');
668
+ if ([429, 503].includes(status) && retryAfter && (
669
+ /^[0-9]+$/.test(retryAfter) ||
670
+ (/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(retryAfter) &&
671
+ Number.isFinite(Date.parse(retryAfter)) && new Date(retryAfter).toUTCString() === retryAfter)
672
+ )) upstreamRetryAfter.set(projected, retryAfter);
673
+ return projected;
674
+ }
675
+
540
676
  function redactAuditValue(value) {
541
677
  if (value === undefined || value === null) return value;
542
678
  if (Array.isArray(value)) return value.map(redactAuditValue);
@@ -600,7 +736,7 @@ async function proxy(res, method, target) {
600
736
  err.upstreamStatus = r.status;
601
737
  throw err;
602
738
  }
603
- return json(res, r.status, body);
739
+ return json(res, r.status, r.ok ? body : upstreamErrorBody(r.status, body, r.headers));
604
740
  }
605
741
 
606
742
  const SAFE_FALLBACK_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
@@ -623,13 +759,15 @@ function rethrowExecutorSecurityError(err) {
623
759
  if (
624
760
  [401, 403].includes(Number(err?.upstreamStatus)) ||
625
761
  String(err?.code ?? '').startsWith('executor_credential_') ||
762
+ err?.code === 'executor_redirect_refused' ||
626
763
  String(err?.code ?? '').startsWith('executor_trust_')
627
764
  ) throw err;
628
765
  }
629
766
 
630
- export async function fetchJsonFirst(candidates, { method = 'GET', headers, body: requestBodyOption, timeoutMs = 0 } = {}) {
767
+ export async function fetchJsonFirst(candidates, { method = 'GET', headers, body: requestBodyOption, timeoutMs = 0, executorUrl = executorRequestContext.getStore()?.executorOrigin ?? EXECUTOR_URL } = {}) {
631
768
  const failures = [];
632
- for (const candidate of candidates) {
769
+ let refused = 0;
770
+ for (const [index, candidate] of candidates.entries()) {
633
771
  const target = typeof candidate === 'string' ? candidate : candidate.target;
634
772
  const requestMethod = typeof candidate === 'string' ? method : candidate.method ?? method;
635
773
  const requestHeaders = typeof candidate === 'string' ? headers : candidate.headers ?? headers;
@@ -638,9 +776,15 @@ export async function fetchJsonFirst(candidates, { method = 'GET', headers, body
638
776
  const timeout = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
639
777
  let r;
640
778
  try {
641
- r = await executorFetch(target, { method: requestMethod, headers: requestHeaders, body: requestBody, ...(controller ? { signal: controller.signal } : {}) });
779
+ r = await executorFetch(target, { method: requestMethod, headers: requestHeaders, body: requestBody, ...(controller ? { signal: controller.signal } : {}) }, executorUrl, index + 1 < candidates.length);
642
780
  } catch (err) {
643
- if (String(err?.code ?? '').startsWith('executor_credential_')) throw err;
781
+ rethrowExecutorSecurityError(err);
782
+ if (err?.code === 'executor_target_refused') {
783
+ refused++;
784
+ bridgeErrorBody(err);
785
+ failures.push(`${target} -> refused`);
786
+ continue; // No request was sent; a fixed fallback is safe even for POST.
787
+ }
644
788
  const failure = isAbortError(err) && timeoutMs > 0
645
789
  ? `${target} -> timeout after ${timeoutMs}ms`
646
790
  : `${target} -> ${String(err?.message ?? err)}`;
@@ -661,8 +805,9 @@ export async function fetchJsonFirst(candidates, { method = 'GET', headers, body
661
805
  }
662
806
  if (r.ok) return { target, status: r.status, body: responseBody };
663
807
  failures.push(`${target} -> ${r.status}`);
664
- if (r.status !== 404 && r.status !== 405) return { target, status: r.status, body: responseBody, failures };
808
+ if (r.status !== 404 && r.status !== 405) return { target, status: r.status, body: upstreamErrorBody(r.status, responseBody, r.headers), adminError: safeUpstreamError(r.status, responseBody), failures };
665
809
  }
810
+ if (refused && refused === candidates.length) throw executorAuthError('executor_target_refused', 'no allowed upstream candidates');
666
811
  throw new Error(failures.join('; ') || 'no upstream candidates');
667
812
  }
668
813
 
@@ -696,7 +841,7 @@ async function assertRealExecutor(executorUrl, allowMockExecutor) {
696
841
  async function probeExecutor(executorUrl) {
697
842
  for (const path of ['/healthz/http', '/healthz', '/health']) {
698
843
  try {
699
- const r = await executorFetch(`${executorUrl}${path}`, { signal: AbortSignal.timeout(1_500) });
844
+ const r = await executorFetch(`${executorUrl}${path}`, { signal: AbortSignal.timeout(1_500) }, executorUrl);
700
845
  if (r.ok) return true;
701
846
  } catch {
702
847
  // Try the next health endpoint.
@@ -735,7 +880,7 @@ async function getExecutorCapabilities(executorUrl) {
735
880
  status: 'unreachable',
736
881
  source: null,
737
882
  host_runtime_enabled: false,
738
- error: String(err?.message ?? err),
883
+ error: bridgeErrorBody(err).message,
739
884
  };
740
885
  }
741
886
  }
@@ -758,7 +903,7 @@ async function getMcpDiscovery(executorUrl) {
758
903
  enabled: false,
759
904
  status: 'disabled',
760
905
  reason_code: 'mcp.discovery_unavailable',
761
- error: String(err?.message ?? err),
906
+ error: bridgeErrorBody(err).message,
762
907
  }, executorUrl);
763
908
  }
764
909
  }
@@ -830,11 +975,11 @@ async function proxyMcpRequest(req, res, executorUrl, mcpTokenFile) {
830
975
  if (typeof protocolVersion === 'string' && protocolVersion.trim()) {
831
976
  headers['mcp-protocol-version'] = protocolVersion.trim();
832
977
  }
833
- const response = await fetch(target, {
978
+ const response = await executorFetch(target, {
834
979
  method: 'POST',
835
980
  headers,
836
981
  body: JSON.stringify(body),
837
- });
982
+ }, executorUrl);
838
983
  status = response.status;
839
984
  const responseBody = await response.json().catch(() => ({}));
840
985
  await appendAudit('sandbox.mcp.proxy', {
@@ -842,7 +987,7 @@ async function proxyMcpRequest(req, res, executorUrl, mcpTokenFile) {
842
987
  method: rpcMethod,
843
988
  status,
844
989
  });
845
- return json(res, status, responseBody);
990
+ return json(res, status, response.ok ? responseBody : upstreamErrorBody(status, responseBody, response.headers));
846
991
  } catch (err) {
847
992
  await appendAudit('sandbox.mcp.proxy', {
848
993
  result: 'error',
@@ -897,16 +1042,13 @@ async function proxyFirst(res, candidates, options) {
897
1042
  return json(res, status, body);
898
1043
  } catch (err) {
899
1044
  if ([401, 403].includes(Number(err?.upstreamStatus))) {
900
- return json(res, Number(err.upstreamStatus), { error: err.code, message: String(err.message) });
1045
+ return json(res, Number(err.upstreamStatus), bridgeErrorBody(err));
901
1046
  }
902
- if (String(err?.code ?? '').startsWith('executor_credential_')) throw err;
1047
+ rethrowExecutorSecurityError(err);
903
1048
  const message = String(err?.message ?? err);
904
1049
  const notFound = / -> 404(?:;|$)/.test(message);
905
1050
  const methodNotAllowed = / -> 405(?:;|$)/.test(message);
906
- return json(res, notFound ? 404 : methodNotAllowed ? 405 : 502, {
907
- error: notFound ? 'upstream_not_found' : methodNotAllowed ? 'upstream_method_not_allowed' : 'bridge_upstream_error',
908
- message,
909
- });
1051
+ return json(res, notFound ? 404 : methodNotAllowed ? 405 : 502, bridgeErrorBody(err, notFound ? 'upstream_not_found' : methodNotAllowed ? 'upstream_method_not_allowed' : 'bridge_upstream_error'));
910
1052
  }
911
1053
  }
912
1054
 
@@ -934,7 +1076,7 @@ function defaultAssetRef(instanceId, action) {
934
1076
 
935
1077
  function upstreamBridgeError(err) {
936
1078
  rethrowExecutorSecurityError(err);
937
- return { status: 502, body: { error: 'bridge_upstream_error', message: String(err?.message ?? err) } };
1079
+ return { status: 502, body: bridgeErrorBody(err) };
938
1080
  }
939
1081
 
940
1082
  async function providerFastStartAction(upstreamUrl, instanceId, action, body = {}) {
@@ -1210,7 +1352,7 @@ async function reconnectInstance(upstreamUrl, instanceId) {
1210
1352
  body: {
1211
1353
  error: 'reconnect_failed',
1212
1354
  message: `Could not run agent-reconnect in ${dockerName}. Repull/rebuild the agent image if it predates agentic-sandbox v2026.7.5.`,
1213
- detail: String(err?.message ?? err),
1355
+ detail: bridgeErrorBody(err, 'reconnect_failed').message,
1214
1356
  },
1215
1357
  };
1216
1358
  }
@@ -1266,7 +1408,7 @@ async function reconnectInstance(upstreamUrl, instanceId) {
1266
1408
  body: {
1267
1409
  error: 'reconnect_failed',
1268
1410
  message: `Could not signal agent-client in VM ${domain} via qemu-guest-agent. The bridge host needs virsh access to the libvirt domain and the guest-agent channel must be up (agentic-sandbox#633).`,
1269
- detail: String(err?.message ?? err),
1411
+ detail: bridgeErrorBody(err, 'reconnect_failed').message,
1270
1412
  },
1271
1413
  };
1272
1414
  }
@@ -1848,7 +1990,17 @@ async function discoverCockpitA2AInterface(executorUrl, instanceId) {
1848
1990
  const { body: card } = await fetchJsonFirst([
1849
1991
  `${executorUrl}/agents/${encodeURIComponent(instanceId)}/.well-known/agent-card.json`,
1850
1992
  ]);
1851
- return { card, selected: selectCockpitA2AInterface(card, cockpitA2ASettings().policy) };
1993
+ return { card, selected: allowedCockpitA2AInterface(executorUrl, instanceId, selectCockpitA2AInterface(card, cockpitA2ASettings().policy)) };
1994
+ }
1995
+
1996
+ function allowedCockpitA2AInterface(executorUrl, instanceId, selected) {
1997
+ const target = allowedExecutorTarget(selected.url, executorUrl);
1998
+ const paths = [`/agents/${encodeURIComponent(instanceId)}`, `/api/v1/agents/${encodeURIComponent(instanceId)}`];
1999
+ if (!paths.includes(target.pathname.replace(/\/+$/, '')) || target.search || target.hash) {
2000
+ throw executorAuthError('executor_target_refused', 'AgentCard interface is outside the requested agent endpoint');
2001
+ }
2002
+ // Reconstruct from trusted configuration and the validated agent path.
2003
+ return { ...selected, url: `${parseExecutorUrl(executorUrl).origin}${target.pathname.replace(/\/+$/, '')}` };
1852
2004
  }
1853
2005
 
1854
2006
  function cockpitA2AHeaders(version, mutating = false) {
@@ -1876,6 +2028,8 @@ async function negotiatedCockpitA2ARequest(executorUrl, instanceId, candidatesFo
1876
2028
  try {
1877
2029
  ({ card, selected } = await discoverCockpitA2AInterface(executorUrl, instanceId));
1878
2030
  } catch (error) {
2031
+ rethrowExecutorSecurityError(error);
2032
+ if (error?.code === 'executor_target_refused') bridgeErrorBody(error);
1879
2033
  // Pre-AgentCard executors remain supported only under the explicit legacy
1880
2034
  // policy. Auto and 1.0 must negotiate from advertised interfaces.
1881
2035
  if (settings.policy !== '0.3') throw error;
@@ -1896,7 +2050,7 @@ async function negotiatedCockpitA2ARequest(executorUrl, instanceId, candidatesFo
1896
2050
  settings.allowFallback &&
1897
2051
  isA2AVersionNotSupported(result.status, result.body)
1898
2052
  ) {
1899
- active = selectCockpitA2AInterface(card, '0.3');
2053
+ active = allowedCockpitA2AInterface(executorUrl, instanceId, selectCockpitA2AInterface(card, '0.3'));
1900
2054
  fallbackReason = `${result.body?.type ?? result.body?.code ?? 'VersionNotSupportedError'}`;
1901
2055
  result = await fetchJsonFirst(candidatesFor(active));
1902
2056
  }
@@ -2002,7 +2156,7 @@ async function getAgentBackedHostInventory(executorUrl, degradedDetail) {
2002
2156
  /** Normalize the executor's admin inventory into the Bridge's UI shape. */
2003
2157
  async function getInventory(executorUrl, { requireSandboxMtls = false } = {}) {
2004
2158
  const bootstrapTrust = await getBootstrapTrustPosture(executorUrl, { requireSandboxMtls });
2005
- const { target, status, body } = await fetchJsonFirst([
2159
+ const { target, status, body, adminError } = await fetchJsonFirst([
2006
2160
  `${executorUrl}/admin/instances`,
2007
2161
  `${executorUrl}/api/v2/admin/instances`,
2008
2162
  ]);
@@ -2022,7 +2176,7 @@ async function getInventory(executorUrl, { requireSandboxMtls = false } = {}) {
2022
2176
  fetched_at: new Date().toISOString(),
2023
2177
  count: 0,
2024
2178
  degraded_admin_inventory: detail,
2025
- admin_error: body,
2179
+ admin_error: adminError,
2026
2180
  bootstrap_trust: bootstrapTrust,
2027
2181
  instances: [],
2028
2182
  };
@@ -2096,6 +2250,7 @@ async function listInstanceTasks(executorUrl, instanceId) {
2096
2250
  }
2097
2251
  return asArrayFromEnvelope(result.body, ['tasks', 'items', 'data']).map(normalizeCockpitA2ATask);
2098
2252
  } catch (error) {
2253
+ rethrowExecutorSecurityError(error);
2099
2254
  if (settings.policy !== '0.3') throw error;
2100
2255
  const candidates = unique([instanceId, agentId]).flatMap((id) => [
2101
2256
  `${executorUrl}/agents/${encodeURIComponent(id)}/tasks`,
@@ -2249,7 +2404,34 @@ function normalizeMissionStatus(status) {
2249
2404
  return value;
2250
2405
  }
2251
2406
 
2407
+ function assertNoWorkerMissionBinding(value) {
2408
+ const seen = new Set();
2409
+ const seenRecords = new Set();
2410
+ function extensions(item) {
2411
+ if (!item || typeof item !== 'object' || Array.isArray(item) || seen.has(item)) return;
2412
+ seen.add(item);
2413
+ if (Object.hasOwn(item, 'aiwg.worker-dispatch')) {
2414
+ throw Object.assign(new Error('OG_CONTRACT_UNSUPPORTED: Cockpit projection does not advertise worker contract support.'), { code: 'OG_CONTRACT_UNSUPPORTED' });
2415
+ }
2416
+ for (const [key, child] of Object.entries(item)) if (key.startsWith('aiwg.source.')) {
2417
+ extensions(child);
2418
+ record(child);
2419
+ }
2420
+ }
2421
+ function record(item) {
2422
+ if (!item || typeof item !== 'object' || Array.isArray(item) || seenRecords.has(item)) return;
2423
+ seenRecords.add(item);
2424
+ // Every mission-v1 carrier, plus native protocol metadata/artifacts.
2425
+ extensions(item.extensions);
2426
+ extensions(item.metadata);
2427
+ if (Array.isArray(item.status?.artifacts)) item.status.artifacts.forEach(record);
2428
+ if (Array.isArray(item.artifacts)) item.artifacts.forEach(record);
2429
+ }
2430
+ record(value);
2431
+ }
2432
+
2252
2433
  export function missionSummary(mission) {
2434
+ assertNoWorkerMissionBinding(mission);
2253
2435
  const canonical = mission?.apiVersion === 'mission.aiwg.io/v1' && mission?.kind === 'Mission';
2254
2436
  const canonicalStatus = canonical ? mission.status ?? {} : {};
2255
2437
  const canonicalMetadata = canonical ? mission.metadata ?? {} : {};
@@ -2436,7 +2618,8 @@ function fleetParentState(records) {
2436
2618
  return 'active';
2437
2619
  }
2438
2620
 
2439
- function fleetMissionProjection(record, sessionId) {
2621
+ export function fleetMissionProjection(record, sessionId) {
2622
+ assertNoWorkerMissionBinding(record);
2440
2623
  const lineage = record.lineage ?? {};
2441
2624
  const status = record.status ?? {};
2442
2625
  const artifacts = Array.isArray(status.artifacts) ? status.artifacts : [];
@@ -2631,7 +2814,7 @@ async function respondApproval(executorUrl, approvalId, decision) {
2631
2814
  return { status: result.status, body: normalizeCockpitA2ATaskResponse(result.body) };
2632
2815
  } catch (e) {
2633
2816
  rethrowExecutorSecurityError(e);
2634
- return { status: 409, body: { error: 'approval_response_failed', detail: String(e?.message ?? e) } };
2817
+ return { status: 409, body: bridgeErrorBody(e, 'approval_response_failed') };
2635
2818
  }
2636
2819
  }
2637
2820
 
@@ -2679,16 +2862,16 @@ async function getSessionScreen(executorUrl, instanceId, sessionId) {
2679
2862
  });
2680
2863
  try {
2681
2864
  const { body, target, status } = await fetchJsonFirst(paths);
2865
+ if (status >= 400) return { status, body };
2682
2866
  return { status, body: normalizeScreenSnapshot(body, { instanceId, sessionId, source: target }) };
2683
2867
  } catch (e) {
2684
2868
  rethrowExecutorSecurityError(e);
2685
2869
  return {
2686
2870
  status: 404,
2687
2871
  body: {
2688
- error: 'session_screen_unavailable',
2872
+ ...bridgeErrorBody(e, 'session_screen_unavailable'),
2689
2873
  instance_id: instanceId,
2690
2874
  session_id: sessionId,
2691
- detail: String(e?.message ?? e),
2692
2875
  },
2693
2876
  };
2694
2877
  }
@@ -2862,7 +3045,7 @@ function writeUpgradeHead(socket, response) {
2862
3045
  socket.write('\r\n');
2863
3046
  }
2864
3047
 
2865
- async function proxyExecutorWebsocket({ req, socket, head, target, executorTokenFile }) {
3048
+ async function proxyExecutorWebsocket({ req, socket, head, target, executorTokenFile, executorUrl }) {
2866
3049
  const token = await resolveExecutorBearer(executorTokenFile);
2867
3050
  const requestedProtocols = String(req.headers['sec-websocket-protocol'] ?? '')
2868
3051
  .split(',')
@@ -2881,7 +3064,7 @@ async function proxyExecutorWebsocket({ req, socket, head, target, executorToken
2881
3064
  const transport = target.protocol === 'wss:' ? https : http;
2882
3065
  const requestTarget = new URL(target);
2883
3066
  requestTarget.protocol = target.protocol === 'wss:' ? 'https:' : 'http:';
2884
- const upstreamRequest = transport.request(requestTarget, { method: 'GET', headers });
3067
+ const upstreamRequest = transport.request(allowedExecutorTarget(requestTarget, executorUrl), { method: 'GET', headers });
2885
3068
  upstreamRequest.on('upgrade', (response, upstreamSocket, upstreamHead) => {
2886
3069
  writeUpgradeHead(socket, response);
2887
3070
  if (head.length) upstreamSocket.write(head);
@@ -2968,6 +3151,7 @@ export function createBridge({
2968
3151
  throw new Error(`AIWG_COCKPIT_A2A_PROTOCOL_POLICY must be 0.3, 1.0, or auto (received '${a2aProtocolPolicy}')`);
2969
3152
  }
2970
3153
  const upstreamUrl = executorUrl;
3154
+ const executorAddress = parseExecutorUrl(upstreamUrl);
2971
3155
  const TOKEN = token ?? randomBytes(24).toString('hex');
2972
3156
  const bootstrapNonces = new Map();
2973
3157
  const browserSessions = new Map();
@@ -3006,22 +3190,25 @@ export function createBridge({
3006
3190
  const requestAuth = (req) => bearerAuthed(req, TOKEN)
3007
3191
  ? { kind: 'bearer', csrf: TOKEN }
3008
3192
  : sessionAuth(req);
3009
- const executorOrigin = new URL(upstreamUrl).origin;
3193
+ const executorOrigin = executorAddress.origin;
3010
3194
  const requestContext = Object.freeze({
3011
3195
  executorOrigin, executorTokenFile, a2aProtocolPolicy, allowA2AProtocolFallback,
3012
3196
  libraryDir: instanceLibraryDir, auditDir: instanceAuditDir,
3013
3197
  mcpTokenFile, localDockerFallback, localLibvirtFallback, aiwgCommand,
3014
3198
  corpusRoots: instanceCorpusRoots, contributionDirs: instanceContributionDirs,
3015
3199
  });
3016
- const executorAddress = new URL(upstreamUrl);
3017
3200
  const attachTargets = new Map();
3018
3201
  const issueAttachUrl = (req, value) => {
3019
3202
  const target = new URL(String(value));
3203
+ const protocol = executorAddress.protocol === 'https:' ? 'wss:' : 'ws:';
3204
+ const port = (url) => url.port || (['https:', 'wss:'].includes(url.protocol) ? '443' : '80');
3020
3205
  const sameHost = target.hostname === executorAddress.hostname ||
3021
3206
  (isLocalHostName(target.hostname) && isLocalHostName(executorAddress.hostname));
3022
- if (!['ws:', 'wss:'].includes(target.protocol) || !sameHost || !/^\/agents\/[^/]+\/sessions\/[^/]+\/attach$/.test(target.pathname)) {
3207
+ if (target.protocol !== protocol || !sameHost || port(target) !== port(executorAddress) ||
3208
+ target.username || target.password || !/^\/agents\/[^/]+\/sessions\/[^/]+\/attach$/.test(target.pathname)) {
3023
3209
  throw executorAuthError('executor_attach_target_refused', 'executor returned an attach URL outside the allowed PTY endpoint');
3024
3210
  }
3211
+ target.host = executorAddress.host;
3025
3212
  const id = randomBytes(18).toString('base64url');
3026
3213
  attachTargets.set(id, target);
3027
3214
  if (attachTargets.size > 1024) attachTargets.delete(attachTargets.keys().next().value);
@@ -3131,7 +3318,7 @@ export function createBridge({
3131
3318
  await getBootstrapTrustPosture(upstreamUrl, { requireSandboxMtls: true });
3132
3319
  }
3133
3320
  } catch (err) {
3134
- return json(res, Number(err?.upstreamStatus) || 502, { error: err.code ?? 'executor_refused', message: String(err?.message ?? err), recovery: err?.recovery });
3321
+ return json(res, Number(err?.upstreamStatus) || 502, bridgeErrorBody(err, err.code ?? 'executor_refused'));
3135
3322
  }
3136
3323
  }
3137
3324
  if (url.pathname === '/api/events' && req.method === 'GET') {
@@ -3155,7 +3342,7 @@ export function createBridge({
3155
3342
  return json(res, 200, await getBootstrapTrustPosture(upstreamUrl, { requireSandboxMtls }));
3156
3343
  }
3157
3344
  if (url.pathname === '/api/mcp/discovery' && req.method === 'GET') return json(res, 200, await getMcpDiscovery(upstreamUrl));
3158
- if (url.pathname === '/api/mcp' && req.method === 'POST') return proxyMcpRequest(req, res, upstreamUrl, mcpTokenFile);
3345
+ if (url.pathname === '/api/mcp' && req.method === 'POST') return await proxyMcpRequest(req, res, upstreamUrl, mcpTokenFile);
3159
3346
  if (url.pathname === '/api/running') return json(res, 200, await getRunning(upstreamUrl));
3160
3347
  if (url.pathname === '/api/missions' && req.method === 'GET') return json(res, 200, await getMissions(upstreamUrl));
3161
3348
  if (url.pathname === '/api/missions' && req.method === 'POST') {
@@ -3172,7 +3359,7 @@ export function createBridge({
3172
3359
  await appendAudit('activity.coverage.queried', { scope: activityRequest(parsed.body).scope, complete: result.body?.completeness?.complete === true });
3173
3360
  return json(res, result.status, result.body);
3174
3361
  } catch (error) {
3175
- return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), { error: error?.code ?? 'activity_upstream_error', message: String(error?.message ?? error) });
3362
+ return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), bridgeErrorBody(error, error?.code ?? 'activity_upstream_error'));
3176
3363
  }
3177
3364
  }
3178
3365
  if (url.pathname === '/api/activity/timeline' && req.method === 'POST') {
@@ -3184,7 +3371,7 @@ export function createBridge({
3184
3371
  await appendAudit('activity.timeline.queried', { scope: activityRequest(parsed.body).scope, event_count: result.body.events.length, complete: result.body.completeness.complete });
3185
3372
  return json(res, result.status, result.body);
3186
3373
  } catch (error) {
3187
- return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), { error: error?.code ?? 'activity_upstream_error', message: String(error?.message ?? error) });
3374
+ return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), bridgeErrorBody(error, error?.code ?? 'activity_upstream_error'));
3188
3375
  }
3189
3376
  }
3190
3377
  if (url.pathname === '/api/activity/export' && req.method === 'POST') {
@@ -3199,7 +3386,7 @@ export function createBridge({
3199
3386
  res.setHeader('cache-control', 'no-store');
3200
3387
  return json(res, result.status, result.body);
3201
3388
  } catch (error) {
3202
- return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), { error: error?.code ?? 'activity_upstream_error', message: String(error?.message ?? error) });
3389
+ return json(res, Number(error?.upstreamStatus) || (String(error?.code).startsWith('activity_') ? 400 : 502), bridgeErrorBody(error, error?.code ?? 'activity_upstream_error'));
3203
3390
  }
3204
3391
  }
3205
3392
  if (url.pathname === '/api/loadouts') return json(res, 200, await getLoadouts(upstreamUrl));
@@ -3222,7 +3409,7 @@ export function createBridge({
3222
3409
  return json(res, 201, { ok: true, graph });
3223
3410
  } catch (error) {
3224
3411
  await appendAudit('index.graph.create.rejected', { request_ts: requested.ts, reason: String(error?.message ?? error) });
3225
- return json(res, 400, { error: 'invalid_graph_definition', detail: String(error?.message ?? error) });
3412
+ return json(res, 400, bridgeErrorBody(error, 'invalid_graph_definition'));
3226
3413
  }
3227
3414
  }
3228
3415
  if (url.pathname === '/api/audit' && req.method === 'GET') {
@@ -3274,13 +3461,13 @@ export function createBridge({
3274
3461
  headers: { 'content-type': 'application/json' },
3275
3462
  body: requestBody,
3276
3463
  },
3277
- ]).catch((err) => ({ status: 502, body: { error: 'bridge_upstream_error', message: String(err?.message ?? err) } }));
3464
+ ]).catch((err) => ({ status: 502, body: bridgeErrorBody(err) }));
3278
3465
  const projected = managedDockerLaunchError(result.status, result.body);
3279
3466
  await appendAudit('instance.launch.result', { request_ts: before.ts, status: projected.status, result: projected.body });
3280
3467
  return json(res, projected.status, projected.body);
3281
3468
  }
3282
3469
  if ((m = url.pathname.match(/^\/api\/operations\/([^/]+)$/)) && req.method === 'GET') {
3283
- return proxyFirst(res, [
3470
+ return await proxyFirst(res, [
3284
3471
  `${upstreamUrl}/api/v2/admin/operations/${encodeURIComponent(m[1])}`,
3285
3472
  ]);
3286
3473
  }
@@ -3340,7 +3527,7 @@ export function createBridge({
3340
3527
  const body = await readFile(resolved, 'utf8');
3341
3528
  return json(res, 200, { type, name: name ?? deriveName(resolved), path: resolved, body });
3342
3529
  } catch (e) {
3343
- return json(res, 404, { error: 'artifact_not_found', detail: String(e?.message ?? e) });
3530
+ return json(res, 404, bridgeErrorBody(e, 'artifact_not_found'));
3344
3531
  }
3345
3532
  }
3346
3533
  // Fallback: resolve by name via the CLI. Map ambiguity/not-found to 4xx — an
@@ -3351,10 +3538,7 @@ export function createBridge({
3351
3538
  } catch (e) {
3352
3539
  const detail = String(e?.message ?? e);
3353
3540
  const ambiguous = /ambiguous/i.test(detail);
3354
- return json(res, ambiguous ? 409 : 404, {
3355
- error: ambiguous ? 'ambiguous_artifact' : 'artifact_not_found',
3356
- detail,
3357
- });
3541
+ return json(res, ambiguous ? 409 : 404, bridgeErrorBody(e, ambiguous ? 'ambiguous_artifact' : 'artifact_not_found'));
3358
3542
  }
3359
3543
  }
3360
3544
  // user asset library — browse / clone-from-catalog / delete. AIWG install files
@@ -3365,7 +3549,7 @@ export function createBridge({
3365
3549
  return json(res, 201, await cloneToLibrary({
3366
3550
  type: url.searchParams.get('type'), name: url.searchParams.get('name'), path: url.searchParams.get('path'),
3367
3551
  }));
3368
- } catch (e) { return json(res, 400, { error: 'clone_failed', detail: String(e?.message ?? e) }); }
3552
+ } catch (e) { return json(res, 400, bridgeErrorBody(e, 'clone_failed')); }
3369
3553
  }
3370
3554
  {
3371
3555
  const lm = url.pathname.match(/^\/api\/library\/(.+)$/);
@@ -3436,9 +3620,8 @@ export function createBridge({
3436
3620
  // Preserve the original create failure; reuse is a recovery path only.
3437
3621
  }
3438
3622
  return json(res, 409, {
3439
- error: 'agent_not_registered',
3623
+ ...bridgeErrorBody(err, 'agent_not_registered'),
3440
3624
  message: 'The instance is visible in inventory, but its agent has not registered yet; PTY sessions are not ready.',
3441
- detail: String(err?.message ?? err),
3442
3625
  });
3443
3626
  }
3444
3627
  const { status, body } = sessionCreate;
@@ -3454,7 +3637,7 @@ export function createBridge({
3454
3637
  const wsBase = upstreamUrl.replace(/^http/i, 'ws');
3455
3638
  const sessionId = body.id ?? body.session_id ?? body.sessionId;
3456
3639
  if (status >= 200 && status < 300 && !sessionId && !body.attach_url && !body.attachUrl && !body.pty_ws_url && !body.ptyWsUrl) {
3457
- return json(res, 502, { error: 'session_create_missing_id', message: 'executor created no attachable session identifier', body });
3640
+ return json(res, 502, bridgeErrorBody(new Error(JSON.stringify(body)), 'session_create_missing_id'));
3458
3641
  }
3459
3642
  let attachUrl = body.attach_url ?? body.attachUrl;
3460
3643
  if (!attachUrl && (body.pty_ws_url ?? body.ptyWsUrl)) {
@@ -3504,7 +3687,7 @@ export function createBridge({
3504
3687
  const result = await fetchJsonFirst([
3505
3688
  `${upstreamUrl}/admin/instances/${encodeURIComponent(m[1])}/${m[2]}`,
3506
3689
  `${upstreamUrl}/api/v2/admin/instances/${encodeURIComponent(m[1])}/${m[2]}`,
3507
- ], { method: 'POST' }).catch((err) => ({ status: 502, body: { error: 'bridge_upstream_error', message: String(err?.message ?? err) } }));
3690
+ ], { method: 'POST' }).catch((err) => ({ status: 502, body: bridgeErrorBody(err) }));
3508
3691
  await appendAudit('instance.lifecycle.requested', { instance_id: decodeURIComponent(m[1]), action: m[2], status: result.status, result: result.body });
3509
3692
  return json(res, result.status, result.body);
3510
3693
  }
@@ -3582,7 +3765,7 @@ export function createBridge({
3582
3765
  return json(res, status, body);
3583
3766
  }
3584
3767
  if (url.pathname === '/api/cost' && req.method === 'GET')
3585
- return proxy(res, 'GET', `${upstreamUrl}/admin/cost`);
3768
+ return await proxy(res, 'GET', `${upstreamUrl}/admin/cost`);
3586
3769
 
3587
3770
  if (url.pathname === '/api/health') return json(res, 200, {
3588
3771
  status: 'ok',
@@ -3622,7 +3805,7 @@ export function createBridge({
3622
3805
  json(res, 404, { error: 'not_found', path: url.pathname });
3623
3806
  } catch (err) {
3624
3807
  const status = Number(err?.status) || Number(err?.upstreamStatus) || 502;
3625
- json(res, status, { error: err?.code ?? 'bridge_upstream_error', message: String(err?.message ?? err) });
3808
+ json(res, status, bridgeErrorBody(err));
3626
3809
  }
3627
3810
  };
3628
3811
  const server = http.createServer((req, res) => executorRequestContext.run(
@@ -3648,7 +3831,7 @@ export function createBridge({
3648
3831
  socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
3649
3832
  return;
3650
3833
  }
3651
- await proxyExecutorWebsocket({ req, socket, head, target, executorTokenFile });
3834
+ await proxyExecutorWebsocket({ req, socket, head, target, executorTokenFile, executorUrl: upstreamUrl });
3652
3835
  } catch {
3653
3836
  if (!socket.destroyed) socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
3654
3837
  }