@dailephd/my-centcom 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,653 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
4
+ import { basename, isAbsolute, join } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { createFiniteCliDriver } from '../plugins/drivers/finiteCliDriver.js';
7
+ import { createOperationCatalog } from '../plugins/registry/operationCatalog.js';
8
+ import { createOperationCatalogFromRegistry } from '../plugins/registry/registryOperationCatalog.js';
9
+ import { createVerifiedCapabilityRegistry } from '../plugins/registry/verifiedCapabilityRegistry.js';
10
+ import { RunExecutor } from '../runs/runExecutor.js';
11
+ import { createGitObserver } from '../context/gitObservation.js';
12
+ import { createProjectReadIssuer, PROJECT_READ_SWEEP_INTERVAL_MS } from '../context/projectReadIssuer.js';
13
+ import { assessProjectReadAudit } from '../context/projectReadService.js';
14
+ import { CODEX_MCP_ONLY_MODEL, codexProjectReadMcpArgs } from '../plugins/drivers/codexMcpConfig.js';
15
+ import { PROJECT_READ_AUDIT_SUBDIR, PROJECT_READ_ENV_CAPABILITY } from '../../../../packages/contracts/dist/index.js';
16
+ import { redactText } from './evidenceRedaction.js';
17
+ import { createWindowsJobSupervisor } from './windows/windowsJobSupervisor.js';
18
+ import { ExecutionTelemetry } from '../storage/executionTelemetry.js';
19
+ import { CodingWorkflowService } from '../runs/codingWorkflowService.js';
20
+ import { CodingAuthority } from '../projects/codingAuthority.js';
21
+ import { createGitEvidence } from '../context/gitEvidence.js';
22
+ import { createMxcTestExecutor } from './mxcExecution.js';
23
+ import { syntheticSourceFingerprint } from './mxcIntegrity.js';
24
+ import { modelExecutionReadiness } from './modelExecutionPolicy.js';
25
+ import { TrustedCliConsent, isTrustedProposalRun } from '../projects/trustedCliConsent.js';
26
+ import { REVIEWED_CA_BUNDLES, stagedCaFileOf, verifyCaBundleFile } from './trustedCaBundle.js';
27
+ import { REVIEWED_AGENT_BUILDS, grantRestrictedReadOnly, stageMcpOnlyModelCatalog, stageProjectReadAdapter, stagedDirOf, stagedEntrypointOf, verifyTree } from './trustedAgentStaging.js';
28
+ /**
29
+ * PRODUCTION profiles. Adding one is a code review, never a configuration value. Only these are offered by a normal start.
30
+ */
31
+ export const PRODUCTION_PROFILES = Object.freeze({
32
+ // Installed Codex CLI, read-only, prompt on stdin. Its behaviour under the restricted identity with a real model is NOT verified (REAL_MODEL_NOT_VERIFIED).
33
+ 'codex-exec-readonly-stdin': {
34
+ id: 'codex-exec-readonly-stdin',
35
+ description: 'installed codex.exe exec --json --ephemeral --sandbox read-only; prompt on stdin',
36
+ executableName: 'codex.exe',
37
+ codeInputs: 0,
38
+ // SW-067: the sign-in must live in the isolated CODEX_HOME as a file (the default 'auto' may use the user's Windows credential store, which the restricted identity cannot reach and which would not be isolated).
39
+ buildArgs: (_code, ctx) => ['exec', '--json', '--ephemeral', '--sandbox', 'read-only', '--skip-git-repo-check', '-c', 'cli_auth_credentials_store=file', ...(ctx?.mcp ? codexProjectReadMcpArgs(ctx.mcp) : [])],
40
+ projectReadMcp: true,
41
+ timeoutMs: 120_000,
42
+ agentHome: { CODEX_HOME: 'codex', LOCALAPPDATA: 'local', APPDATA: 'roaming' },
43
+ stagedBuild: 'codex-0.167.0-win32-x64',
44
+ caBundle: 'mozilla-node-v24.20.0-win-x64',
45
+ },
46
+ });
47
+ /**
48
+ * DEV SMOKE profiles (SW-061): benign, non-network reference implementations (node.exe running ONE pinned script that speaks the JSONL frame shapes). They exist so the
49
+ * whole pipeline can be exercised without any agent or model. They are NOT offered by a normal start; they are available only when trusted startup is told so
50
+ * explicitly (devSmokeProfiles), and every start with that mode on announces it. A row that uses one is invalidated at the next start without the mode.
51
+ */
52
+ export const DEV_SMOKE_PROFILES = Object.freeze({
53
+ // Benign reference implementation: Node running ONE pinned script that speaks the documented JSONL frame shapes. Used for unattended engineering tests.
54
+ 'reference-script-stdin': {
55
+ id: 'reference-script-stdin',
56
+ description: 'node.exe running one pinned script; prompt on stdin; JSONL frames',
57
+ executableName: 'node.exe',
58
+ codeInputs: 1,
59
+ buildArgs: (code) => ['--preserve-symlinks', '--preserve-symlinks-main', code[0], 'exec', '--json', '--mode', 'stdin-echo'],
60
+ timeoutMs: 40_000,
61
+ },
62
+ // SW-069: the benign reference with the SAME trusted environment (isolated home + pinned CA bundle) as the Codex profile, so the effective environment and file access of the
63
+ // restricted identity can be verified through the real production path without any agent or model.
64
+ 'reference-script-agent-env': {
65
+ id: 'reference-script-agent-env',
66
+ description: 'node.exe running one pinned script with the Codex-style isolated home and pinned CA bundle; prompt on stdin; JSONL frames',
67
+ executableName: 'node.exe',
68
+ codeInputs: 1,
69
+ buildArgs: (code) => ['--preserve-symlinks', '--preserve-symlinks-main', code[0], 'exec', '--json', '--mode', 'stdin-echo'],
70
+ timeoutMs: 40_000,
71
+ agentHome: { CODEX_HOME: 'codex', LOCALAPPDATA: 'local', APPDATA: 'roaming' },
72
+ caBundle: 'mozilla-node-v24.20.0-win-x64',
73
+ },
74
+ // SW-074 NON-MODEL harness profile: the production Codex arguments PLUS a loopback-only scripted "Responses" endpoint (tests/fixtures/sw074MockResponsesServer.mjs) in place of the
75
+ // real model provider. It lets the real Codex binary, the restricted identity, the MCP configuration and the capability lifecycle be exercised end to end WITHOUT any model call,
76
+ // credential or outside network. The port comes from the test process's own environment at build time and must be a bare loopback port; never offered by a normal start.
77
+ 'codex-exec-mock-provider-mcp-stdin': {
78
+ scriptedModelOnly: true,
79
+ id: 'codex-exec-mock-provider-mcp-stdin',
80
+ description: 'installed codex.exe exec against a scripted loopback endpoint (no model) with the project-read MCP server; prompt on stdin',
81
+ executableName: 'codex.exe',
82
+ codeInputs: 0,
83
+ buildArgs: (_code, ctx) => {
84
+ const port = ctx?.devMockResponsesPort;
85
+ if (typeof port !== 'number' || !Number.isInteger(port) || port < 1024 || port > 65535)
86
+ throw new Error('MOCK_PORT_MISSING');
87
+ return ['exec', '--json', '--ephemeral', '--sandbox', 'read-only', '--skip-git-repo-check', '-c', 'cli_auth_credentials_store=file',
88
+ '-c', 'model_provider="mock"', '-c', 'model_providers.mock.name="mock"', '-c', `model_providers.mock.base_url="http://127.0.0.1:${port}/v1"`, '-c', 'model_providers.mock.wire_api="responses"',
89
+ ...(ctx?.mcp ? codexProjectReadMcpArgs(ctx.mcp) : [])];
90
+ },
91
+ timeoutMs: 120_000,
92
+ agentHome: { CODEX_HOME: 'codex', LOCALAPPDATA: 'local', APPDATA: 'roaming' },
93
+ stagedBuild: 'codex-0.167.0-win32-x64',
94
+ caBundle: 'mozilla-node-v24.20.0-win-x64',
95
+ projectReadMcp: true,
96
+ },
97
+ // Benign reference: same pinned-script shape, but the script stays alive and never reads stdin, so cancellation, timeout and crash behaviour can be tested.
98
+ 'reference-script-stall': {
99
+ id: 'reference-script-stall',
100
+ description: 'node.exe running one pinned script that stalls; used to exercise cancel, timeout and crash recovery',
101
+ executableName: 'node.exe',
102
+ codeInputs: 1,
103
+ buildArgs: (code) => ['--preserve-symlinks', '--preserve-symlinks-main', code[0], 'exec', '--json', '--mode', 'stdin-stall'],
104
+ timeoutMs: 40_000,
105
+ },
106
+ });
107
+ /** Every reviewed profile (the union). Use profilesFor() to know which are ACTIVE for a given start. */
108
+ export const REVIEWED_PROFILES = Object.freeze({ ...PRODUCTION_PROFILES, ...DEV_SMOKE_PROFILES });
109
+ export const profilesFor = (devSmokeProfiles) => (devSmokeProfiles ? REVIEWED_PROFILES : PRODUCTION_PROFILES);
110
+ export class ProvisionError extends Error {
111
+ code;
112
+ constructor(code) {
113
+ super(code);
114
+ this.code = code;
115
+ this.name = 'ProvisionError';
116
+ }
117
+ }
118
+ const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
119
+ const WIN = process.platform === 'win32';
120
+ const sysRoot = () => process.env.SystemRoot ?? 'C:\\Windows';
121
+ /** Presentation of reviewed capabilities only; a label never authorizes execution. */
122
+ export function reviewedTaskPresentation(profileId) {
123
+ const profile = REVIEWED_PROFILES[profileId];
124
+ return profile ? { agentLabel: profile.projectReadMcp ? (profile.scriptedModelOnly ? 'Scripted CLI (test only)' : 'Codex CLI') : 'Reference CLI (test only)', coding: profile.projectReadMcp === true, ...(profile.projectReadMcp && !profile.scriptedModelOnly ? { strictReady: modelExecutionReadiness().ready } : {}) } : undefined;
125
+ }
126
+ function manifestFor(profile, pluginId, operationId, codeInputs, ctx) {
127
+ return JSON.stringify({
128
+ schemaVersion: 1, id: pluginId, kind: 'agent', name: pluginId, version: '0.0.0-provisioned', description: `operator provisioned (${profile.id})`, state: 'registered',
129
+ operations: {
130
+ [operationId]: {
131
+ id: operationId, name: operationId, description: profile.description, effectClass: 'read', inputSchema: {},
132
+ executablePolicy: { executable: profile.executableName, args: [...profile.buildArgs(codeInputs, ctx)], allowShell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] },
133
+ timeoutMs: profile.timeoutMs, outputBounds: { maxOutputBytes: 65536 }, projectCwdRequired: true, inputTransport: { kind: 'stdin_utf8', maxBytes: 32768 },
134
+ },
135
+ },
136
+ });
137
+ }
138
+ /**
139
+ * Git for the C07 observation is found ONLY at the standard install locations under Program Files; PATH is never searched (so a hostile PATH entry cannot
140
+ * substitute the binary). Absent Git is a clear provisioning error, not a fallback.
141
+ */
142
+ export function findGit() {
143
+ const drive = process.env.SystemDrive && /^[A-Za-z]:$/.test(process.env.SystemDrive) ? process.env.SystemDrive : 'C:';
144
+ const roots = [process.env.ProgramFiles, process.env.ProgramW6432, `${drive}\\Program Files`].filter((r) => typeof r === 'string' && isAbsolute(r));
145
+ for (const r of roots) {
146
+ for (const rel of [['Git', 'cmd', 'git.exe'], ['Git', 'mingw64', 'bin', 'git.exe']]) {
147
+ const p = join(r, ...rel);
148
+ try {
149
+ if (existsSync(p) && lstatSync(p).isFile() && !lstatSync(p).isSymbolicLink())
150
+ return realpathSync.native(p);
151
+ }
152
+ catch { /* try the next location */ }
153
+ }
154
+ }
155
+ throw new ProvisionError('GIT_UNAVAILABLE');
156
+ }
157
+ export async function createProvisionedExecution(owners) {
158
+ const { ledger, authority, now, projectRoot } = owners;
159
+ const trustedCliConsent = new TrustedCliConsent(ledger, now);
160
+ const runtimeRoot = owners.runtimeRoot ?? join(projectRoot, '.switchyard-data');
161
+ const active = profilesFor(owners.devSmokeProfiles === true);
162
+ const telemetry = owners.telemetry ?? new ExecutionTelemetry(ledger, now);
163
+ void owners.coordinator;
164
+ const registry = createVerifiedCapabilityRegistry({ now });
165
+ let catalog = createOperationCatalog();
166
+ const selections = [];
167
+ const executors = new Map();
168
+ const retired = new Map(); // disabled plugins keep their executor ONLY so an in-flight run can still be cancelled
169
+ const inflight = new Set();
170
+ let supervisor;
171
+ let mxcSupervisor;
172
+ let git;
173
+ let childTemp;
174
+ const invalidated = [];
175
+ // An operator disable takes effect IMMEDIATELY and synchronously, before the (asynchronous, re-hashing) catalog rebuild finishes.
176
+ const disabledNow = new Set();
177
+ const keyOf = (pluginId, operationId) => JSON.stringify([pluginId, operationId]);
178
+ // ---- SW-074 project-read MCP: the reviewed adapter closure, the capability issuer and the per-run evidence hook ------------------------------------------------------
179
+ let issuerInst;
180
+ const issuer = () => {
181
+ if (!issuerInst) {
182
+ const grantsDir = join(runtimeRoot, 'mcp-grants');
183
+ if (owners.projectRead === undefined) {
184
+ mkdirSync(grantsDir, { recursive: true });
185
+ if (lstatSync(grantsDir).isSymbolicLink())
186
+ throw new ProvisionError('MCP_SERVER_UNAVAILABLE');
187
+ grantRestrictedReadOnly(realpathSync.native(grantsDir)); // read-only for the agent identity: it can never write, replace or extend a capability
188
+ }
189
+ const viewsRoot = join(runtimeRoot, 'project-views');
190
+ if (owners.projectRead === undefined) {
191
+ mkdirSync(viewsRoot, { recursive: true });
192
+ if (lstatSync(viewsRoot).isSymbolicLink())
193
+ throw new ProvisionError('MCP_SERVER_UNAVAILABLE');
194
+ grantRestrictedReadOnly(realpathSync.native(viewsRoot));
195
+ } // read+execute only, inherited by each new view
196
+ issuerInst = owners.projectRead ?? createProjectReadIssuer({ ledger, authority, grantsDir, now, viewsRoot: realpathSync.native(viewsRoot) });
197
+ const t = setInterval(() => { try {
198
+ issuerInst?.sweep();
199
+ }
200
+ catch { /* the next sweep retries; every request also re-verifies the descriptor */ } }, PROJECT_READ_SWEEP_INTERVAL_MS);
201
+ if (typeof t.unref === 'function')
202
+ t.unref();
203
+ }
204
+ return issuerInst;
205
+ };
206
+ function mcpLayout(stagedBuild) {
207
+ try {
208
+ const build = stagedBuild !== undefined ? REVIEWED_AGENT_BUILDS[stagedBuild] : undefined;
209
+ if (!build)
210
+ throw new Error('no reviewed build');
211
+ const node = realpathSync.native(process.execPath);
212
+ const staged = stageProjectReadAdapter(projectRoot); // digest-named, read+execute only for the restricted identity, never repaired if it differs
213
+ if (!lstatSync(staged.serverScript).isFile() || !lstatSync(node).isFile())
214
+ throw new Error('not a file');
215
+ const catalog = stageMcpOnlyModelCatalog(projectRoot, realpathSync.native(stagedEntrypointOf(join(projectRoot, '.switchyard-data', 'agents'), build)), CODEX_MCP_ONLY_MODEL);
216
+ return { cfg: { nodeExecutable: node, serverScript: realpathSync.native(staged.serverScript), modelCatalog: realpathSync.native(catalog.path), proposeTool: true }, closure: [...staged.files, catalog] };
217
+ }
218
+ catch {
219
+ throw new ProvisionError('MCP_SERVER_UNAVAILABLE');
220
+ }
221
+ }
222
+ const mcpRuns = new Map();
223
+ const viewChecks = new Map();
224
+ /** Content-free MCP evidence: verified reads and refusals from the hash-chained audit, appended to the run's durable execution evidence. */
225
+ function recordMcpEvidence(runId) {
226
+ const m = mcpRuns.get(runId);
227
+ mcpRuns.delete(runId);
228
+ if (!m)
229
+ return;
230
+ const note = (data) => { try {
231
+ ledger.appendExecutionEvidence(runId, { ts: iso(), kind: 'NOTE', data: data.slice(0, 1000), truncated: data.length > 1000 });
232
+ }
233
+ catch { /* degraded evidence is reported by the caller's finish */ } };
234
+ const vc = viewChecks.get(runId);
235
+ viewChecks.delete(runId);
236
+ if (m.view)
237
+ note(`PROJECT_VIEW view=${m.view.viewId} files=${m.view.files} bytes=${m.view.bytes} manifest=${m.view.manifestSha256.slice(0, 16)} omitted=${Object.entries(m.view.omitted).map(([k, v]) => `${k}:${v}`).join(',') || '-'} integrityAtRelease=${vc ? (vc.ok ? 'VERIFIED' : 'FAILED:' + vc.problems.slice(0, 3).join('|')) : 'NOT_CHECKED'} removed=true`);
238
+ let text = '';
239
+ try {
240
+ text = readFileSync(join(m.auditDir, `${m.capabilityId}.audit.jsonl`), 'utf8');
241
+ }
242
+ catch {
243
+ note(`MCP_PROJECT_READ capability=${m.capabilityId} audit=ABSENT (no tool call reached the adapter)`);
244
+ return;
245
+ }
246
+ const a = assessProjectReadAudit({ auditText: text, capabilityId: m.capabilityId });
247
+ note(`MCP_PROJECT_READ capability=${m.capabilityId} chain=${a.chainIntact ? 'INTACT' : 'BROKEN'} records=${a.records} allowedReads=${a.allowedReads} refusals=${a.refusals} refusalCodes=${a.refusalCodes.join(',') || '-'}`);
248
+ if (!a.chainIntact)
249
+ return;
250
+ const principalId = ledger.getRunOwnerPrincipalId(runId);
251
+ const run = principalId ? ledger.getRunDetailForPrincipal(principalId, runId) : undefined;
252
+ if (principalId && run && coding && new CodingAuthority({ ledger, now }).authorize({ principalId, projectId: run.projectId, runId, operation: 'PROPOSE' }).ok) {
253
+ const imported = coding.ingestProposals({ principalId, projectId: run.projectId, runId, capabilityId: m.capabilityId, auditText: text, proposalsDir: join(childTemp, 'mcp-proposals') });
254
+ note(`CODING_PROPOSALS imported=${imported.ok ? imported.items.filter((i) => i.ok).length : 0} decision=${imported.ok ? 'CHECKED' : imported.code}`);
255
+ }
256
+ let n = 0;
257
+ for (const line of text.split('\n').filter(Boolean)) {
258
+ let r;
259
+ try {
260
+ r = JSON.parse(line);
261
+ }
262
+ catch {
263
+ break;
264
+ }
265
+ if (r.event !== 'TOOL_CALL')
266
+ continue;
267
+ if (++n > 40) {
268
+ note('MCP_TOOL_CALL further calls omitted (bounded)');
269
+ break;
270
+ }
271
+ note(redactText(`MCP_TOOL_CALL seq=${String(r.seq)} tool=${String(r.tool)} decision=${String(r.decision)}${r.code ? ` code=${String(r.code)}` : ''} path=${String(r.pathDisplay ?? '-')} file=${typeof r.fileSha256 === 'string' ? r.fileSha256.slice(0, 16) : '-'} returned=${typeof r.returnedSha256 === 'string' ? r.returnedSha256.slice(0, 16) : '-'} bytes=${String(r.returnedBytes ?? '-')}`, { max: 400 }).text);
272
+ }
273
+ }
274
+ const iso = () => new Date(now()).toISOString();
275
+ let coding;
276
+ async function codingWorkflow() {
277
+ await ensureRuntime();
278
+ if (!coding) {
279
+ coding = new CodingWorkflowService({ ledger, authority: new CodingAuthority({ ledger, now }), trustedCliConsent,
280
+ git: createGitEvidence({ gitExecutablePath: findGit() }), tests: createMxcTestExecutor({ projectRoot, supervisor: mxcSupervisor, tempBoundary: join(childTemp, 'coding-tests'),
281
+ ...(owners.devSmokeProfiles === true && owners.devMockResponsesPort !== undefined && owners.syntheticTestAcceptance ? { syntheticWorkspaceBoundary: join(runtimeRoot, 'coding-workspaces') } : {}) }), telemetry,
282
+ prepareAccess: () => { },
283
+ workspacesRoot: join(runtimeRoot, 'coding-workspaces'), journalsRoot: owners.codingJournalRoot ?? join(runtimeRoot, 'coding-journals'),
284
+ testTempRoot: join(childTemp, 'coding-tests'), ...(owners.devSmokeProfiles === true && owners.devMockResponsesPort !== undefined && owners.syntheticTestAcceptance ? {
285
+ offlineDisposableProjectsRoot: join(projectRoot, '.switchyard-dev', 'cache'),
286
+ offlineDisposableRunAllowed: (runId) => {
287
+ const principal = ledger.getRunOwnerPrincipalId(runId);
288
+ const run = principal ? ledger.getRunDetailForPrincipal(principal, runId) : undefined;
289
+ const selected = run ? ledger.listProvisionedOperations().find((p) => p.pluginId === run.pluginId && p.operationId === run.operationId && p.enabled) : undefined;
290
+ try {
291
+ const original = run ? ledger.getProjectRoot(run.projectId) : undefined;
292
+ return selected !== undefined && active[selected.profileId]?.scriptedModelOnly === true && original === realpathSync.native(owners.syntheticTestAcceptance.sourceRoot)
293
+ && syntheticSourceFingerprint(original) === owners.syntheticTestAcceptance.sourceSha256;
294
+ }
295
+ catch {
296
+ return false;
297
+ }
298
+ },
299
+ } : {}), now });
300
+ coding.recover(ledger.findRecoverableCodingProposals());
301
+ coding.recoverReviewedPatches();
302
+ coding.recoverReviewedCommits();
303
+ }
304
+ return coding;
305
+ }
306
+ async function ensureRuntime() {
307
+ if (supervisor && git && childTemp)
308
+ return;
309
+ if (!WIN)
310
+ throw new ProvisionError('HELPER_UNAVAILABLE');
311
+ try {
312
+ // The helper is built from the tracked C# source with the pinned in-box compiler (SW-046); its digest is the one this process then pins.
313
+ const mod = await import(pathToFileURL(join(projectRoot, 'apps', 'daemon', 'src', 'runtime', 'windows', 'buildSupervisor.mjs')).href);
314
+ let built;
315
+ try {
316
+ built = mod.verifyBuild();
317
+ }
318
+ catch {
319
+ mod.buildSupervisor();
320
+ built = mod.verifyBuild();
321
+ }
322
+ supervisor = createWindowsJobSupervisor({ helperPath: built.helperPath, helperSha256: built.helperSha256, executionIdentity: 'RESTRICTED_LOW_INTEGRITY' });
323
+ mxcSupervisor = createWindowsJobSupervisor({ helperPath: built.helperPath, helperSha256: built.helperSha256, executionIdentity: 'CALLER_TOKEN' });
324
+ }
325
+ catch (e) {
326
+ if (e instanceof ProvisionError)
327
+ throw e;
328
+ throw new ProvisionError('HELPER_UNAVAILABLE');
329
+ }
330
+ try {
331
+ git = createGitObserver({ gitExecutablePath: findGit() });
332
+ }
333
+ catch {
334
+ throw new ProvisionError('GIT_UNAVAILABLE');
335
+ }
336
+ try {
337
+ // A daemon-owned scratch directory for the CHILD's TEMP: restricted-writable and Low integrity, and nothing else. It is created under the shared runtime
338
+ // data directory (never the private ledger directory) and is the only location whose ACL this process changes.
339
+ const dir = join(runtimeRoot, 'child-tmp');
340
+ mkdirSync(dir, { recursive: true });
341
+ if (lstatSync(dir).isSymbolicLink())
342
+ throw new Error('link');
343
+ const real = realpathSync.native(dir);
344
+ const icacls = join(sysRoot(), 'System32', 'icacls.exe');
345
+ execFileSync(icacls, [real, '/grant', '*S-1-5-12:(OI)(CI)(M)'], { windowsHide: true, stdio: 'ignore', timeout: 30_000 });
346
+ execFileSync(icacls, [real, '/setintegritylevel', '(OI)(CI)L'], { windowsHide: true, stdio: 'ignore', timeout: 30_000 });
347
+ childTemp = real;
348
+ }
349
+ catch {
350
+ throw new ProvisionError('CHILD_TEMP_UNAVAILABLE');
351
+ }
352
+ }
353
+ async function rebuildCatalog() {
354
+ catalog = selections.length === 0 ? createOperationCatalog() : await createOperationCatalogFromRegistry(registry, selections);
355
+ }
356
+ function attachExecutor(pluginId, profile) {
357
+ const mcp = profile.projectReadMcp === true ? mcpLayout(profile.stagedBuild) : undefined;
358
+ let trustedEnvironment;
359
+ const agentsRoot = join(projectRoot, '.switchyard-data', 'agents');
360
+ const caEntry = profile.caBundle !== undefined ? REVIEWED_CA_BUNDLES[profile.caBundle] : undefined;
361
+ if (profile.agentHome) {
362
+ const base = join(childTemp, 'agent-home', pluginId);
363
+ const entries = {};
364
+ for (const [envName, sub] of Object.entries(profile.agentHome)) {
365
+ const d = join(base, sub);
366
+ mkdirSync(d, { recursive: true });
367
+ entries[envName] = realpathSync.native(d);
368
+ }
369
+ trustedEnvironment = { containmentRoot: realpathSync.native(base), entries };
370
+ if (caEntry)
371
+ trustedEnvironment.files = { CODEX_CA_CERTIFICATE: { path: realpathSync.native(stagedCaFileOf(agentsRoot, caEntry)), sha256: caEntry.pemSha256 } };
372
+ }
373
+ const baseDriver = createFiniteCliDriver({
374
+ pluginId, registry, supervisor: supervisor, childTempDirectory: childTemp, outputProfile: 'codex-exec-jsonl-v1', enableStdinTransport: true, now,
375
+ ...(trustedEnvironment ? { trustedEnvironment } : {}),
376
+ ...(mcp && trustedEnvironment ? {
377
+ runEnvironment: {
378
+ resolve: (inv) => {
379
+ const principalId = ledger.getRunOwnerPrincipalId(inv.runId);
380
+ const proposeTool = principalId !== undefined && new CodingAuthority({ ledger, now }).authorize({ principalId, projectId: inv.projectId, runId: inv.runId, operation: 'PROPOSE' }).ok;
381
+ const issued = issuer().issue({ runId: inv.runId, projectId: inv.projectId, pluginId: inv.pluginId, operationId: inv.operationId, authorizationGrantId: inv.authorizationGrantId }, { proposeTool });
382
+ if (!issued.ok)
383
+ return undefined;
384
+ try {
385
+ const auditDir = join(childTemp, PROJECT_READ_AUDIT_SUBDIR); // inherits the restricted-writable, Low-integrity child scratch ACL
386
+ mkdirSync(auditDir, { recursive: true });
387
+ const realAudit = realpathSync.native(auditDir);
388
+ mcpRuns.set(inv.runId, { capabilityId: issued.capabilityId, auditDir: realAudit, ...(issued.view ? { view: { viewId: issued.view.viewId, root: issued.view.root, files: issued.view.files, bytes: issued.view.bytes, manifestSha256: issued.view.manifestSha256, omitted: { ...issued.view.omitted } } } : {}) });
389
+ return { files: { [PROJECT_READ_ENV_CAPABILITY]: { path: issued.descriptorPath, sha256: issued.descriptorSha256 } }, ...(issued.view ? { workingDirectory: issued.view.root } : {}) };
390
+ }
391
+ catch {
392
+ issuer().revoke(inv.runId);
393
+ return undefined;
394
+ }
395
+ },
396
+ release: (runId) => { try {
397
+ const vv = issuer().verifyView(runId);
398
+ if (vv)
399
+ viewChecks.set(runId, vv);
400
+ issuer().revoke(runId);
401
+ }
402
+ finally {
403
+ recordMcpEvidence(runId);
404
+ } },
405
+ },
406
+ } : {}),
407
+ });
408
+ // SW-067: a staged-tree profile re-verifies every sibling file of the vendor tree immediately before the launch decision (prepare) and again right before the
409
+ // process is created (invoke). The registry already re-hashes the entrypoint itself on both paths.
410
+ let driver = baseDriver;
411
+ if (profile.stagedBuild !== undefined || caEntry !== undefined || mcp !== undefined) {
412
+ const build = profile.stagedBuild !== undefined ? REVIEWED_AGENT_BUILDS[profile.stagedBuild] : undefined;
413
+ const dir = build ? stagedDirOf(agentsRoot, build.id) : undefined;
414
+ const caFile = caEntry ? stagedCaFileOf(agentsRoot, caEntry) : undefined;
415
+ const treeOk = () => (build && dir ? verifyTree(dir, build, { hashEntrypoint: false }).ok : true);
416
+ // Credentials remain in the existing isolated home. Unreviewed home
417
+ // configuration could add other MCP servers despite our reviewed flags.
418
+ const trustedConfigOk = () => !trustedEnvironment?.entries.CODEX_HOME || !existsSync(join(trustedEnvironment.entries.CODEX_HOME, 'config.toml'));
419
+ const mcpPinned = mcp ? mcp.closure : [];
420
+ const mcpOk = () => { try {
421
+ return mcpPinned.every((f) => createHash('sha256').update(readFileSync(f.path)).digest('hex') === f.sha256);
422
+ }
423
+ catch {
424
+ return false;
425
+ } };
426
+ const caOk = () => (caEntry && caFile ? verifyCaBundleFile(caFile, caEntry).ok : true);
427
+ const envNames = trustedEnvironment ? ['SystemRoot', 'TEMP', 'TMP', ...Object.keys(trustedEnvironment.entries), ...Object.keys(trustedEnvironment.files ?? {}), ...(mcp ? [PROJECT_READ_ENV_CAPABILITY] : [])].sort() : undefined;
428
+ const ca = caEntry && caFile ? verifyCaBundleFile(caFile, caEntry) : undefined;
429
+ const pinnedFiles = caEntry || mcp ? { ...(caEntry ? { CODEX_CA_CERTIFICATE: `sha256:${caEntry.pemSha256} certs=${caEntry.certCount} earliestNotAfter=${ca && ca.ok ? ca.earliestNotAfter : 'unknown'}` } : {}), ...(mcp ? { PROJECT_READ_MCP_ADAPTER: mcpPinned.map((f) => f.sha256.slice(0, 16)).join('+') } : {}) } : undefined;
430
+ driver = Object.freeze({
431
+ ...baseDriver,
432
+ prepare: async (runId, operationId) => {
433
+ if (isTrustedProposalRun(ledger, runId)) {
434
+ if (!trustedCliConsent.authorize(runId))
435
+ return { ok: false, code: 'TRUSTED_CLI_CONSENT_REQUIRED' };
436
+ if (!trustedConfigOk())
437
+ return { ok: false, code: 'TRUSTED_CLI_CONFIG_UNREVIEWED' };
438
+ }
439
+ else if (profile.projectReadMcp && !profile.scriptedModelOnly)
440
+ return { ok: false, code: modelExecutionReadiness().code };
441
+ if (!treeOk())
442
+ return { ok: false, code: 'EXECUTABLE_CHANGED' };
443
+ if (!caOk())
444
+ return { ok: false, code: 'CA_BUNDLE_CHANGED' };
445
+ if (!mcpOk())
446
+ return { ok: false, code: 'EXECUTABLE_CHANGED' };
447
+ const r = await baseDriver.prepare(runId, operationId);
448
+ return r.ok ? { ok: true, plan: Object.freeze({ ...r.plan, ...(envNames ? { environmentNames: envNames } : {}), ...(pinnedFiles ? { pinnedFiles } : {}) }) } : r;
449
+ },
450
+ invoke: async (request) => {
451
+ if (isTrustedProposalRun(ledger, request.runId)) {
452
+ if (!trustedCliConsent.authorize(request.runId))
453
+ throw Object.assign(new Error('TRUSTED_CLI_CONSENT_REQUIRED'), { code: 'TRUSTED_CLI_CONSENT_REQUIRED' });
454
+ if (!trustedConfigOk())
455
+ throw Object.assign(new Error('TRUSTED_CLI_CONFIG_UNREVIEWED'), { code: 'TRUSTED_CLI_CONFIG_UNREVIEWED' });
456
+ ledger.appendCodingEvent({ at: iso(), runId: request.runId, subjectKind: 'GRANT', subjectId: request.runId, event: 'TRUSTED_CLI_LAUNCH_AUTHORIZED', decision: 'ALLOWED', detail: { mode: 'TRUSTED_LOCAL_CLI_PROPOSAL_ONLY', identity: 'RESTRICTED_LOW_INTEGRITY', isolation: 'NOT_ISOLATED' } });
457
+ }
458
+ else if (profile.projectReadMcp && !profile.scriptedModelOnly)
459
+ throw Object.assign(new Error(modelExecutionReadiness().code), { code: modelExecutionReadiness().code });
460
+ if (!treeOk())
461
+ throw Object.assign(new Error('EXECUTABLE_CHANGED'), { code: 'EXECUTABLE_CHANGED' });
462
+ if (!caOk())
463
+ throw Object.assign(new Error('CA_BUNDLE_CHANGED'), { code: 'CA_BUNDLE_CHANGED' });
464
+ if (!mcpOk())
465
+ throw Object.assign(new Error('EXECUTABLE_CHANGED'), { code: 'EXECUTABLE_CHANGED' });
466
+ return baseDriver.invoke(request);
467
+ },
468
+ });
469
+ }
470
+ executors.set(pluginId, new RunExecutor(ledger, authority, driver, git, now, { telemetry, requireTelemetry: true }));
471
+ }
472
+ /** Cheap, side-effect-free validation of a request against its reviewed profile. Runs BEFORE any helper, Git or filesystem preparation. */
473
+ function validate(a) {
474
+ const profile = Object.prototype.hasOwnProperty.call(active, a.profileId) ? active[a.profileId] : undefined;
475
+ if (!profile)
476
+ throw new ProvisionError('PROFILE_UNKNOWN');
477
+ if (!ID.test(a.pluginId) || !ID.test(a.operationId))
478
+ throw new ProvisionError('ARGUMENT_INVALID');
479
+ const code = a.codeInputPath === undefined ? [] : [a.codeInputPath];
480
+ if (code.length !== profile.codeInputs)
481
+ throw new ProvisionError('ARGUMENT_INVALID');
482
+ for (const p of [a.executablePath, ...code])
483
+ if (typeof p !== 'string' || !isAbsolute(p) || p.split(/[\\/]+/).includes('..'))
484
+ throw new ProvisionError('ARGUMENT_INVALID');
485
+ if (basename(a.executablePath).toLowerCase() !== profile.executableName)
486
+ throw new ProvisionError('EXECUTABLE_REFUSED');
487
+ if (profile.caBundle !== undefined) {
488
+ const ca = REVIEWED_CA_BUNDLES[profile.caBundle];
489
+ if (!ca || profile.agentHome === undefined || !verifyCaBundleFile(stagedCaFileOf(join(projectRoot, '.switchyard-data', 'agents'), ca), ca).ok)
490
+ throw new ProvisionError('CA_BUNDLE_INVALID');
491
+ }
492
+ if (profile.projectReadMcp === true) {
493
+ if (profile.agentHome === undefined)
494
+ throw new ProvisionError('MCP_SERVER_UNAVAILABLE');
495
+ mcpLayout(profile.stagedBuild);
496
+ }
497
+ if (profile.stagedBuild !== undefined) {
498
+ // The executable must BE the staged entrypoint of the reviewed build, and the whole staged tree must still match the reviewed list.
499
+ const build = REVIEWED_AGENT_BUILDS[profile.stagedBuild];
500
+ const stagingRoot = join(projectRoot, '.switchyard-data', 'agents');
501
+ let same = false;
502
+ try {
503
+ same = realpathSync.native(a.executablePath).toLowerCase() === realpathSync.native(stagedEntrypointOf(stagingRoot, build)).toLowerCase();
504
+ }
505
+ catch {
506
+ same = false;
507
+ }
508
+ if (!build || !same || !verifyTree(stagedDirOf(stagingRoot, build.id), build).ok)
509
+ throw new ProvisionError('EXECUTABLE_REFUSED');
510
+ }
511
+ return { profile, code };
512
+ }
513
+ /** Validates and pins one provisioning request WITHOUT persisting it. Returns the pinned digests. */
514
+ async function pin(a) {
515
+ const { profile, code } = validate(a);
516
+ try {
517
+ const rec = await registry.register({ manifestJson: manifestFor(profile, a.pluginId, a.operationId, code, { ...(profile.projectReadMcp === true ? { mcp: mcpLayout(profile.stagedBuild).cfg } : {}), ...(owners.devSmokeProfiles === true && owners.devMockResponsesPort !== undefined ? { devMockResponsesPort: owners.devMockResponsesPort } : {}) }), executablePath: a.executablePath, codeInputPaths: code });
518
+ return { sha: rec.executable.sha256, fingerprint: rec.manifestFingerprint, codeSha: rec.codeInputsSha256 };
519
+ }
520
+ catch {
521
+ throw new ProvisionError('REGISTRATION_REFUSED');
522
+ }
523
+ }
524
+ // ---- startup: re-verify every enabled row against the digests the operator saw -----------------------------------------------------------------
525
+ let enabledAtStartup = 0;
526
+ try {
527
+ telemetry.purgeExpired();
528
+ }
529
+ catch { /* retention is best-effort; it runs again at the next start */ }
530
+ let telemetryOk = true;
531
+ try {
532
+ telemetry.assertWritable();
533
+ }
534
+ catch {
535
+ telemetryOk = false;
536
+ }
537
+ const rows = ledger.listProvisionedOperations().filter((r) => r.enabled);
538
+ if (!telemetryOk) {
539
+ for (const r of rows) {
540
+ ledger.disableProvisionedOperation(r.pluginId, r.operationId, 'TELEMETRY_UNAVAILABLE', iso());
541
+ invalidated.push(`${r.pluginId}/${r.operationId}`);
542
+ }
543
+ rows.length = 0;
544
+ }
545
+ if (rows.length > 0) {
546
+ try {
547
+ await ensureRuntime();
548
+ }
549
+ catch {
550
+ for (const r of rows) {
551
+ ledger.disableProvisionedOperation(r.pluginId, r.operationId, 'RUNTIME_UNAVAILABLE', iso());
552
+ invalidated.push(`${r.pluginId}/${r.operationId}`);
553
+ }
554
+ rows.length = 0;
555
+ }
556
+ }
557
+ for (const r of rows) {
558
+ const key = `${r.pluginId}/${r.operationId}`;
559
+ try {
560
+ const pinned = await pin({ pluginId: r.pluginId, operationId: r.operationId, profileId: r.profileId, executablePath: r.executablePath, ...(r.codeInputs[0] ? { codeInputPath: r.codeInputs[0] } : {}) });
561
+ if (pinned.sha !== r.executableSha256 || pinned.fingerprint !== r.manifestFingerprint || pinned.codeSha !== r.codeInputsSha256)
562
+ throw new ProvisionError('REGISTRATION_REFUSED');
563
+ selections.push({ pluginId: r.pluginId, operationId: r.operationId });
564
+ attachExecutor(r.pluginId, active[r.profileId]);
565
+ enabledAtStartup += 1;
566
+ }
567
+ catch {
568
+ ledger.disableProvisionedOperation(r.pluginId, r.operationId, 'RECHECK_FAILED_AT_STARTUP', iso());
569
+ invalidated.push(key);
570
+ }
571
+ }
572
+ if (selections.length > 0)
573
+ await rebuildCatalog();
574
+ return {
575
+ close: async () => { await coding?.close(); },
576
+ codingWorkflow,
577
+ resolve: (op) => (op && disabledNow.has(keyOf(op.pluginId, op.operationId)) ? undefined : catalog.resolve(op)),
578
+ invalidatedAtStartup: invalidated,
579
+ enabledAtStartup,
580
+ promptCapBytes: (pluginId, operationId) => {
581
+ const rec = registry.get(pluginId);
582
+ return rec?.operations.find((o) => o.operationId === operationId)?.inputTransport?.maxBytes ?? 16384;
583
+ },
584
+ async provisionOperation(a) {
585
+ if (ledger.listProvisionedOperations().some((r) => r.pluginId === a.pluginId && r.operationId === a.operationId))
586
+ throw new ProvisionError('ALREADY_PROVISIONED');
587
+ if (registry.get(a.pluginId))
588
+ throw new ProvisionError('ALREADY_PROVISIONED'); // the registry has no unregister: one plugin id per daemon lifetime
589
+ validate(a); // a malformed or unreviewed request is refused before the helper, Git or any directory is touched
590
+ // SW-068 acceptance gate: a real-CLI operation is not enabled unless execution telemetry is initialized and writable (fail closed).
591
+ try {
592
+ telemetry.assertWritable();
593
+ }
594
+ catch {
595
+ throw new ProvisionError('TELEMETRY_UNAVAILABLE');
596
+ }
597
+ await ensureRuntime();
598
+ const pinned = await pin(a);
599
+ try {
600
+ ledger.insertProvisionedOperation({
601
+ pluginId: a.pluginId, operationId: a.operationId, profileId: a.profileId, executablePath: registry.get(a.pluginId).executable.canonicalPath,
602
+ executableSha256: pinned.sha, codeInputs: registry.get(a.pluginId).codeInputs.map((c) => c.canonicalPath), codeInputsSha256: pinned.codeSha, manifestFingerprint: pinned.fingerprint, createdAt: iso(),
603
+ }, iso());
604
+ }
605
+ catch {
606
+ throw new ProvisionError('PERSIST_FAILED');
607
+ }
608
+ selections.push({ pluginId: a.pluginId, operationId: a.operationId });
609
+ attachExecutor(a.pluginId, active[a.profileId]);
610
+ await rebuildCatalog();
611
+ return { executableSha256: pinned.sha, manifestFingerprint: pinned.fingerprint };
612
+ },
613
+ listProvisioned: () => ledger.listProvisionedOperations().map((r) => ({ pluginId: r.pluginId, operationId: r.operationId, profileId: r.profileId, enabled: r.enabled, executableSha256: r.executableSha256, disabledReason: r.disabledReason })),
614
+ disableProvisioned(pluginId, operationId) {
615
+ const ok = ledger.disableProvisionedOperation(pluginId, operationId, 'DISABLED_BY_OPERATOR', iso());
616
+ if (!ok)
617
+ return false;
618
+ disabledNow.add(keyOf(pluginId, operationId));
619
+ const i = selections.findIndex((s) => s.pluginId === pluginId && s.operationId === operationId);
620
+ if (i >= 0)
621
+ selections.splice(i, 1);
622
+ const ex = executors.get(pluginId);
623
+ if (ex) {
624
+ retired.set(pluginId, ex);
625
+ executors.delete(pluginId);
626
+ }
627
+ void rebuildCatalog();
628
+ return true;
629
+ },
630
+ launcher: {
631
+ launch(principalId, runId) {
632
+ const run = ledger.getRunDetailForPrincipal(principalId, runId);
633
+ const ex = run ? executors.get(run.pluginId) : undefined;
634
+ if (!ex)
635
+ return; // nothing provisioned for this plugin: the run stays QUEUED and nothing starts
636
+ const p = ex.execute(principalId, runId).catch(() => undefined);
637
+ inflight.add(p);
638
+ void p.finally(() => inflight.delete(p));
639
+ },
640
+ async cancel(principalId, runId) {
641
+ const run = ledger.getRunDetailForPrincipal(principalId, runId);
642
+ if (!run)
643
+ return 'NOT_FOUND';
644
+ const ex = executors.get(run.pluginId) ?? retired.get(run.pluginId);
645
+ if (!ex)
646
+ return 'NOT_EXECUTING';
647
+ const r = await ex.cancel(principalId, runId);
648
+ return r.kind === 'CANCEL_REQUESTED' ? 'REQUESTED' : r.kind === 'NOT_FOUND' ? 'NOT_FOUND' : 'NOT_EXECUTING';
649
+ },
650
+ },
651
+ };
652
+ }
653
+ //# sourceMappingURL=provisionedExecution.js.map