evolcore 0.0.23 → 0.0.25

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 (245) hide show
  1. package/CHANGELOG.md +583 -516
  2. package/LICENSE +21 -21
  3. package/README.md +455 -453
  4. package/bin/codex-managed-acl.ps1 +160 -155
  5. package/bin/codex-managed-hook.mjs +209 -92
  6. package/bin/ec-safe-output.js +327 -245
  7. package/bin/ec.js +29 -29
  8. package/bin/install-codex-managed-hooks.mjs +555 -544
  9. package/dist/agents/baseagent-availability.js +4 -4
  10. package/dist/agents/baseagent.js +29 -1
  11. package/dist/agents/claude-runner.js +152 -14
  12. package/dist/agents/codex/app-server-client.js +18 -8
  13. package/dist/agents/codex/catalog.js +1 -1
  14. package/dist/agents/codex/diagnostics.js +215 -0
  15. package/dist/agents/codex-runner.js +445 -63
  16. package/dist/agents/ecagent-runner.js +31 -16
  17. package/dist/agents/gemini-runner.js +82 -4
  18. package/dist/agents/runner-types.js +1 -1
  19. package/dist/aun/aid/agentmd.js +56 -4
  20. package/dist/aun/aid/index.js +1 -0
  21. package/dist/aun/aid/managed-operation.js +80 -6
  22. package/dist/aun/aid/store.js +41 -0
  23. package/dist/aun/msg/managed-operation.js +6 -1
  24. package/dist/aun/outbox.js +56 -18
  25. package/dist/aun/rpc/client.js +4 -5
  26. package/dist/aun/storage/client.js +4 -1
  27. package/dist/aun/storage/index.js +1 -1
  28. package/dist/channels/aun.js +147 -76
  29. package/dist/channels/daemon.js +7 -1
  30. package/dist/channels/dingtalk.js +1 -0
  31. package/dist/channels/feishu.js +10 -4
  32. package/dist/channels/wecom.js +2 -1
  33. package/dist/cli/agent-command.js +214 -89
  34. package/dist/cli/agent-create.js +576 -0
  35. package/dist/cli/agent.js +129 -676
  36. package/dist/cli/aun-commands.js +419 -313
  37. package/dist/cli/bench.js +20 -20
  38. package/dist/cli/config.js +20 -20
  39. package/dist/cli/contact.js +10 -10
  40. package/dist/cli/ctl-command.js +22 -20
  41. package/dist/cli/daemon-commands.js +163 -32
  42. package/dist/cli/fs-command.js +67 -67
  43. package/dist/cli/handoff-command.js +7 -7
  44. package/dist/cli/index.js +79 -79
  45. package/dist/cli/link-rules.js +21 -21
  46. package/dist/cli/managed-command-guard.js +3 -0
  47. package/dist/cli/menu-client.js +11 -11
  48. package/dist/cli/net-check.js +22 -22
  49. package/dist/cli/queue-command.js +29 -29
  50. package/dist/cli/response.js +30 -30
  51. package/dist/cli/restart-monitor.js +462 -38
  52. package/dist/cli/stats.js +161 -51
  53. package/dist/cli/trigger-command.js +56 -56
  54. package/dist/config/builtin-roles.js +3 -0
  55. package/dist/config/config-manager.js +15 -0
  56. package/dist/config/config-operation-service.js +20 -3
  57. package/dist/config/resolved-config-op.js +39 -1
  58. package/dist/core/auth/auth-gateway.js +3 -2
  59. package/dist/core/auth/authorization-audit.js +72 -19
  60. package/dist/core/auth/operation-authorizer.js +125 -7
  61. package/dist/core/auth/operation-catalog.js +26 -2
  62. package/dist/core/auth/remote-access-store.js +3 -2
  63. package/dist/core/baseagent-loader.js +4 -4
  64. package/dist/core/bootstrap-messages.js +39 -18
  65. package/dist/core/bootstrap-service.js +32 -26
  66. package/dist/core/capability/capability-manager.js +8 -4
  67. package/dist/core/capability/providers/codex-capability-provider.js +1 -1
  68. package/dist/core/command/agent-control.js +60 -26
  69. package/dist/core/command/cli-intent-parser.js +18 -0
  70. package/dist/core/command/command-handler.js +173 -36
  71. package/dist/core/command/menu-catalog.js +4 -1
  72. package/dist/core/command/menu-handler.js +315 -75
  73. package/dist/core/command/menu-protocol.js +7 -2
  74. package/dist/core/command/slash-gate.js +1 -3
  75. package/dist/core/command/slash-handler.js +166 -57
  76. package/dist/core/data-migration.js +5 -15
  77. package/dist/core/event-catalog.js +8 -0
  78. package/dist/core/evolagent.js +3 -3
  79. package/dist/core/handoff/runtime.js +3 -1
  80. package/dist/core/handoff/store.js +7 -1
  81. package/dist/core/message/im-renderer.js +13 -6
  82. package/dist/core/message/message-bridge.js +5 -36
  83. package/dist/core/message/message-utils.js +6 -3
  84. package/dist/core/message/response-engine.js +85 -27
  85. package/dist/core/model/catalog-service.js +3 -1
  86. package/dist/core/model/model-catalog.js +10 -0
  87. package/dist/core/model/model-permission.js +4 -1
  88. package/dist/core/permission/approval-gateway.js +169 -33
  89. package/dist/core/permission/tool-policy.js +56 -10
  90. package/dist/core/session/adapters/codex-session-file-adapter.js +71 -3
  91. package/dist/core/session/session-manager.js +49 -13
  92. package/dist/core/session/session-renew.js +1 -0
  93. package/dist/index.js +327 -134
  94. package/dist/ipc.js +68 -21
  95. package/dist/paths.js +23 -1
  96. package/dist/stats/billing.js +18 -4
  97. package/dist/stats/db.js +159 -159
  98. package/dist/stats/eck-vars.js +9 -9
  99. package/dist/stats/query.js +139 -139
  100. package/dist/stats/role-budget.js +6 -6
  101. package/dist/stats/writer.js +51 -51
  102. package/dist/utils/atomic-write.js +26 -2
  103. package/dist/utils/avatar-upload.js +282 -23
  104. package/dist/utils/cross-platform.js +436 -1
  105. package/dist/utils/error-dict.json +160 -160
  106. package/dist/utils/error-utils.js +11 -4
  107. package/dist/utils/macos-autostart.js +22 -22
  108. package/dist/utils/model-prices.jsonl +23 -20
  109. package/dist/utils/npm-ops.js +24 -1
  110. package/dist/utils/welcome.js +22 -22
  111. package/dist/utils/windows-autostart.js +1 -1
  112. package/ecagent/LICENSE +21 -21
  113. package/ecagent/NOTICE +11 -11
  114. package/ecagent/README.md +61 -61
  115. package/ecagent/dist/harness/compaction/branch-summarization.js +30 -30
  116. package/ecagent/dist/harness/compaction/compaction.js +83 -83
  117. package/ecagent/dist/harness/messages.js +7 -7
  118. package/kits/docs/GUIDE.md +20 -20
  119. package/kits/docs/INDEX.md +66 -66
  120. package/kits/docs/aun/CHEATSHEET.md +19 -19
  121. package/kits/docs/aun/SYNC_PROTOCOL.md +15 -15
  122. package/kits/docs/channels/aun.md +56 -56
  123. package/kits/docs/channels/feishu.md +56 -56
  124. package/kits/docs/context-assembly.md +365 -364
  125. package/kits/docs/eck_templates/GUIDE.template.md +22 -22
  126. package/kits/docs/eck_templates/INDEX.template.md +28 -28
  127. package/kits/docs/eck_templates/path-registry.template.md +33 -33
  128. package/kits/docs/eck_templates/runtime.template.md +19 -19
  129. package/kits/docs/evolcore/INDEX.md +71 -69
  130. package/kits/docs/evolcore/agent-create.md +170 -156
  131. package/kits/docs/evolcore/agent.md +83 -73
  132. package/kits/docs/evolcore/aid.md +64 -62
  133. package/kits/docs/evolcore/codex-windows-sandbox.md +146 -0
  134. package/kits/docs/evolcore/config.md +195 -195
  135. package/kits/docs/evolcore/contact.md +68 -68
  136. package/kits/docs/evolcore/ctl.md +46 -46
  137. package/kits/docs/evolcore/event.md +216 -216
  138. package/kits/docs/evolcore/fs-architecture.md +1215 -1215
  139. package/kits/docs/evolcore/fs.md +110 -110
  140. package/kits/docs/evolcore/group-collaboration.md +243 -243
  141. package/kits/docs/evolcore/group-fs.md +17 -17
  142. package/kits/docs/evolcore/group-rules.md +251 -251
  143. package/kits/docs/evolcore/group.md +152 -152
  144. package/kits/docs/evolcore/menu-client.md +34 -34
  145. package/kits/docs/evolcore/model.md +50 -50
  146. package/kits/docs/evolcore/msg.md +165 -165
  147. package/kits/docs/evolcore/response.md +75 -75
  148. package/kits/docs/evolcore/rpc.md +37 -37
  149. package/kits/docs/evolcore/self-summary.md +29 -29
  150. package/kits/docs/evolcore/stats.md +83 -83
  151. package/kits/docs/evolcore/storage.md +50 -50
  152. package/kits/docs/evolcore/trigger.md +575 -575
  153. package/kits/docs/identity/AID_PROFILE_SPEC.md +26 -26
  154. package/kits/docs/identity/PATH_OPS.md +16 -16
  155. package/kits/docs/identity/ROLE_DETAIL.md +25 -25
  156. package/kits/docs/identity/identity-tools.md +26 -26
  157. package/kits/docs/path-registry.md +62 -62
  158. package/kits/docs/prompt-loading-architecture.md +270 -269
  159. package/kits/docs/venues/aun-group.md +45 -45
  160. package/kits/docs/venues/aun-private.md +10 -10
  161. package/kits/docs/venues/client-desktop.md +10 -10
  162. package/kits/docs/venues/client-mobile.md +10 -10
  163. package/kits/docs/venues/feishu-group.md +13 -13
  164. package/kits/docs/venues/feishu-private.md +9 -9
  165. package/kits/docs/venues/group.md +25 -25
  166. package/kits/docs/venues/private.md +10 -10
  167. package/kits/eck_manifest.auxiliary.json +43 -43
  168. package/kits/eck_manifest.json +195 -183
  169. package/kits/eck_message_manifest.json +74 -74
  170. package/kits/migrations/README-role-config-v4.md +32 -32
  171. package/kits/migrations/migrate-contact-book-v2.mjs +748 -748
  172. package/kits/migrations/migrate-role-config-v4.mjs +614 -614
  173. package/kits/migrations/migrate-role-config-v5.mjs +365 -365
  174. package/kits/migrations/rename-config-file.mjs +99 -99
  175. package/kits/rules/01-overview.md +162 -162
  176. package/kits/rules/02-navigation.md +96 -96
  177. package/kits/rules/03-identity.md +39 -37
  178. package/kits/rules/04-relation.md +75 -75
  179. package/kits/rules/05-venue.md +60 -60
  180. package/kits/rules/06-channel.md +63 -63
  181. package/kits/schemas/_meta.json +53 -53
  182. package/kits/schemas/agent-config.schema.1.json +177 -177
  183. package/kits/schemas/agent-config.schema.10.json +395 -395
  184. package/kits/schemas/agent-config.schema.11.json +421 -421
  185. package/kits/schemas/agent-config.schema.12.json +427 -427
  186. package/kits/schemas/agent-config.schema.2.json +239 -239
  187. package/kits/schemas/agent-config.schema.3.json +119 -119
  188. package/kits/schemas/agent-config.schema.4.json +208 -208
  189. package/kits/schemas/agent-config.schema.5.json +326 -326
  190. package/kits/schemas/agent-config.schema.6.json +322 -322
  191. package/kits/schemas/agent-config.schema.7.json +303 -303
  192. package/kits/schemas/agent-config.schema.8.json +304 -304
  193. package/kits/schemas/agent-config.schema.9.json +364 -364
  194. package/kits/schemas/contact-book.schema.1.json +36 -36
  195. package/kits/schemas/contact-book.schema.2.json +43 -43
  196. package/kits/schemas/contact-book.schema.3.json +67 -67
  197. package/kits/schemas/daemon.schema.1.json +91 -91
  198. package/kits/schemas/daemon.schema.2.json +101 -101
  199. package/kits/schemas/daemon.schema.3.json +123 -123
  200. package/kits/schemas/daemon.schema.4.json +136 -136
  201. package/kits/schemas/daemon.schema.5.json +135 -135
  202. package/kits/schemas/daemon.schema.6.json +131 -131
  203. package/kits/schemas/defaults.schema.1.json +81 -81
  204. package/kits/schemas/defaults.schema.2.json +85 -85
  205. package/kits/schemas/defaults.schema.3.json +73 -73
  206. package/kits/schemas/defaults.schema.4.json +107 -107
  207. package/kits/schemas/defaults.schema.5.json +119 -119
  208. package/kits/schemas/menu-exec-schema-commands.md +208 -208
  209. package/kits/schemas/migrations/README.md +30 -30
  210. package/kits/schemas/relation-config.schema.1.json +158 -158
  211. package/kits/schemas/relation-config.schema.2.json +73 -73
  212. package/kits/schemas/relation-config.schema.3.json +50 -50
  213. package/kits/schemas/relation-config.schema.4.json +47 -47
  214. package/kits/schemas/relation-config.schema.5.json +47 -47
  215. package/kits/schemas/relation-config.schema.6.json +46 -46
  216. package/kits/schemas/relation-config.schema.7.json +59 -59
  217. package/kits/schemas/relation-config.schema.8.json +103 -103
  218. package/kits/schemas/role-config.schema.1.json +201 -201
  219. package/kits/schemas/role-registry.schema.1.json +35 -35
  220. package/kits/schemas/single-session.schema.1.json +31 -31
  221. package/kits/schemas/single-session.schema.2.json +57 -57
  222. package/kits/schemas/single-session.schema.3.json +32 -32
  223. package/kits/templates/bootstrap-welcome.md +17 -17
  224. package/kits/templates/message-fragments/handoff-context-to-target.md +9 -9
  225. package/kits/templates/message-fragments/handoff-request-to-target.md +19 -19
  226. package/kits/templates/message-fragments/handoff-response-to-origin.md +9 -9
  227. package/kits/templates/message-fragments/inject-default.md +2 -2
  228. package/kits/templates/message-fragments/item.md +2 -2
  229. package/kits/templates/roles/admin.json +96 -82
  230. package/kits/templates/roles/member.json +97 -96
  231. package/kits/templates/roles/owner.json +9 -9
  232. package/kits/templates/roles/visitor.json +86 -85
  233. package/kits/templates/system-fragments/baseagent.md +14 -14
  234. package/kits/templates/system-fragments/bootstrap.md +38 -29
  235. package/kits/templates/system-fragments/channel.md +64 -64
  236. package/kits/templates/system-fragments/commands.md +28 -28
  237. package/kits/templates/system-fragments/identity.md +13 -13
  238. package/kits/templates/system-fragments/relation.md +19 -19
  239. package/kits/templates/system-fragments/session.md +59 -59
  240. package/kits/templates/system-fragments/venue.md +31 -31
  241. package/package.json +98 -94
  242. package/AGENTS.md +0 -62
  243. package/dist/utils/codex-cli.js +0 -43
  244. package/skills/eclink/SKILL.md +0 -84
  245. package/skills/eclink/agents/openai.yaml +0 -4
@@ -1,544 +1,555 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { randomUUID } from 'node:crypto';
7
- import { execFileSync } from 'node:child_process';
8
- import { fileURLToPath, pathToFileURL } from 'node:url';
9
- import { isDeepStrictEqual } from 'node:util';
10
- import { parse as parseToml } from 'smol-toml';
11
-
12
- const markerStart = '# BEGIN EVOLCORE MANAGED CODEX HOOK';
13
- const markerEnd = '# END EVOLCORE MANAGED CODEX HOOK';
14
- const aclScript = fileURLToPath(new URL('./codex-managed-acl.ps1', import.meta.url));
15
-
16
- function argument(name) {
17
- const index = process.argv.indexOf(name);
18
- return index >= 0 ? process.argv[index + 1] : undefined;
19
- }
20
-
21
- function fail(message) {
22
- process.stderr.write(`[evolcore] ${message}\n`);
23
- process.exit(1);
24
- }
25
-
26
- function isGlobalInstall() {
27
- return ['1', 'true'].includes(String(process.env.npm_config_global || '').toLowerCase());
28
- }
29
-
30
- function lifecycleEvent() {
31
- const entry = Object.entries(process.env).find(([key]) => key.toLowerCase() === 'npm_lifecycle_event');
32
- return String(entry?.[1] || '').toLowerCase();
33
- }
34
-
35
- function ensureRealDirectory(directory) {
36
- let stat;
37
- try {
38
- stat = fs.lstatSync(directory);
39
- } catch (error) {
40
- if (error?.code !== 'ENOENT') {
41
- fail(`could not inspect the Codex managed requirements mountpoint ${directory}: ${error?.message || String(error)}`);
42
- }
43
- }
44
-
45
- if (stat) {
46
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
47
- fail(`Codex managed requirements mountpoint is unsafe: ${directory} must be a real directory.`);
48
- }
49
- return;
50
- }
51
-
52
- try {
53
- fs.mkdirSync(directory, { mode: 0o755 });
54
- fs.chmodSync(directory, 0o755);
55
- } catch (error) {
56
- if (error?.code === 'EEXIST') {
57
- const raced = fs.lstatSync(directory);
58
- if (raced.isDirectory() && !raced.isSymbolicLink()) return;
59
- }
60
- fail(
61
- `Linux global installation requires the real directory ${directory}, but it could not be created: `
62
- + `${error?.message || String(error)}. `
63
- + `Create it first with: sudo install -d -m 0755 ${directory}`,
64
- );
65
- }
66
-
67
- const created = fs.lstatSync(directory);
68
- if (!created.isDirectory() || created.isSymbolicLink()) {
69
- fail(`Codex managed requirements mountpoint provisioning failed: ${directory} must be a real directory.`);
70
- }
71
- process.stdout.write(`[evolcore] Prepared Codex managed requirements mountpoint at ${directory}.\n`);
72
- }
73
-
74
- function runLinuxPostinstall() {
75
- const explicitMountpoint = argument('--mountpoint');
76
- if (process.platform !== 'linux') return;
77
- // Local source installs do not launch the Linux Codex guard and must not
78
- // mutate machine-wide configuration. An explicit path is accepted only for
79
- // isolated lifecycle behavior tests.
80
- if (!isGlobalInstall() && !explicitMountpoint) return;
81
- ensureRealDirectory(explicitMountpoint || '/etc/codex');
82
- }
83
-
84
- function tomlString(value) {
85
- return JSON.stringify(value);
86
- }
87
-
88
- function windowsCommandArg(value) {
89
- // Keep filesystem separators intact; tomlString() performs the required
90
- // TOML escaping after this Windows command-line quoting step.
91
- return `"${value.replaceAll('"', '\\"')}"`;
92
- }
93
-
94
- function removeManagedBlock(source) {
95
- const original = parseToml(source);
96
- if (!source.includes(markerStart) && !source.includes(markerEnd)) return source;
97
- const unsafe = () => new Error('Ambiguous EvolCore managed Hook markers in requirements.toml. Existing configuration was not modified.');
98
- const expression = new RegExp(`^${markerStart}\\r?\\n[\\s\\S]*?^${markerEnd}(?:\\r?\\n|$)`, 'gm');
99
- const matches = [...source.matchAll(expression)];
100
- if (matches.length !== 1 || source.split(markerStart).length !== 2 || source.split(markerEnd).length !== 2) throw unsafe();
101
- const block = parseToml(matches[0][0]);
102
- const groups = block.hooks?.PreToolUse;
103
- if (!Array.isArray(groups) || groups.length !== 1
104
- || !isDeepStrictEqual(block, { hooks: { PreToolUse: groups } })) throw unsafe();
105
- const content = source.replace(matches[0][0], '');
106
- const retained = parseToml(content);
107
- const originalGroups = original.hooks?.PreToolUse;
108
- if (!Array.isArray(originalGroups)) throw unsafe();
109
- // Markers inside a TOML string are not comments. Prove that removing the
110
- // block removes only its Hook group, with every other policy unchanged.
111
- const safe = originalGroups.some((group, index) => {
112
- if (!isDeepStrictEqual(group, groups[0])) return false;
113
- const expected = structuredClone(original);
114
- expected.hooks.PreToolUse.splice(index, 1);
115
- if (!expected.hooks.PreToolUse.length && !retained.hooks?.PreToolUse) delete expected.hooks.PreToolUse;
116
- if (!Object.keys(expected.hooks).length && !retained.hooks) delete expected.hooks;
117
- return isDeepStrictEqual(expected, retained);
118
- });
119
- if (!safe) throw unsafe();
120
- return content;
121
- }
122
-
123
- function tableBounds(lines, table) {
124
- const header = table ? `[${table}]` : null;
125
- const start = header
126
- ? lines.findIndex(line => line.trim() === header || line.trim().startsWith(`${header} #`))
127
- : -1;
128
- if (table && start < 0) return null;
129
- const from = table ? start + 1 : 0;
130
- let to = lines.length;
131
- for (let index = from; index < lines.length; index += 1) {
132
- if (/^\s*\[\[?[^\]]+\]\]?\s*(?:#.*)?$/.test(lines[index])) {
133
- to = index;
134
- break;
135
- }
136
- }
137
- return { start, from, to };
138
- }
139
-
140
- function setTomlKey(source, table, key, value) {
141
- const lines = source.split('\n');
142
- let bounds = tableBounds(lines, table);
143
- if (!bounds) {
144
- if (table) {
145
- if (lines.length && lines.at(-1) !== '') lines.push('');
146
- lines.push(`[${table}]`, `${key} = ${value}`);
147
- } else {
148
- let insertAt = lines.findIndex(line => /^\s*\[/.test(line));
149
- if (insertAt < 0) insertAt = lines.length;
150
- lines.splice(insertAt, 0, `${key} = ${value}`);
151
- }
152
- return lines.join('\n');
153
- }
154
- const keyExpression = new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}\\s*=`);
155
- const existing = lines.slice(bounds.from, bounds.to).findIndex(line => keyExpression.test(line));
156
- if (existing >= 0) {
157
- lines[bounds.from + existing] = `${key} = ${value}`;
158
- } else {
159
- lines.splice(bounds.from, 0, `${key} = ${value}`);
160
- }
161
- return lines.join('\n');
162
- }
163
-
164
- export function managedHookLauncher(packageRoot) {
165
- // Keep the machine-wide entrypoint stable across npm upgrades. Those
166
- // upgrades replace the package contents at this stable global path, so
167
- // this file never needs to be rewritten just because the hook changed.
168
- const trustedPackageRoot = path.resolve(packageRoot);
169
- return `#!/usr/bin/env node
170
- import path from 'node:path';
171
- import { pathToFileURL } from 'node:url';
172
-
173
- // EVOLCORE_MANAGED_HOOK_LAUNCHER
174
- const packageRoot = ${JSON.stringify(trustedPackageRoot)};
175
-
176
- try {
177
- await import(pathToFileURL(path.join(packageRoot, 'bin', 'codex-managed-hook.mjs')).href);
178
- } catch (error) {
179
- process.stderr.write('[evolcore] failed to load the current managed hook: '
180
- + (error instanceof Error ? error.message : String(error)) + '\\n');
181
- process.exit(2);
182
- }
183
- `;
184
- }
185
-
186
- export function buildManagedRequirements(source, { targetDirectory, nodePath, hookPath }) {
187
- // Keep the existing text editor, but reject unsupported TOML layouts before
188
- // writing anything. Parsing also catches duplicate tables/keys on reinstall.
189
- let content = removeManagedBlock(source);
190
- const before = parseToml(content);
191
- content = setTomlKey(content, null, 'allow_managed_hooks_only', 'true');
192
- content = setTomlKey(content, 'features', 'hooks', 'true');
193
- content = setTomlKey(content, 'hooks', 'windows_managed_dir', tomlString(path.resolve(targetDirectory)));
194
- if (!content.endsWith('\n')) content += '\n';
195
- // Windows hook command must include %EVOLCORE_INSTANCE_SOCKET% so Codex
196
- // expands it at runtime with the per-daemon socket path
197
- const command = `${windowsCommandArg(nodePath)} ${windowsCommandArg(hookPath)} %EVOLCORE_INSTANCE_SOCKET%`;
198
- content += [
199
- markerStart,
200
- '[[hooks.PreToolUse]]',
201
- 'matcher = "*"',
202
- '',
203
- '[[hooks.PreToolUse.hooks]]',
204
- 'type = "command"',
205
- `command = ${tomlString(command)}`,
206
- `command_windows = ${tomlString(command)}`,
207
- // Intentionally omit timeout: Codex applies its documented 600-second
208
- // default for synchronous PreToolUse hooks. The application pause gate
209
- // itself has no timeout; Codex remains the outer infrastructure ceiling.
210
- 'statusMessage = "Checking EvolCore session policy"',
211
- markerEnd,
212
- '',
213
- ].join('\n');
214
- const after = parseToml(content);
215
- const expected = {
216
- ...before,
217
- allow_managed_hooks_only: true,
218
- features: { ...before.features, hooks: true },
219
- hooks: {
220
- ...before.hooks,
221
- windows_managed_dir: path.resolve(targetDirectory),
222
- PreToolUse: [
223
- ...(before.hooks?.PreToolUse || []),
224
- { matcher: '*', hooks: [{ type: 'command', command, command_windows: command, statusMessage: 'Checking EvolCore session policy' }] },
225
- ],
226
- },
227
- };
228
- if (!isDeepStrictEqual(after, expected)) {
229
- throw new Error('Could not safely update requirements.toml without changing unrelated policy. Existing configuration was not modified.');
230
- }
231
- return content;
232
- }
233
-
234
- function regularFile(file) {
235
- try {
236
- const stat = fs.lstatSync(file);
237
- if (!stat.isFile() || stat.isSymbolicLink()) return { ok: false, unsafe: true };
238
- return { ok: true };
239
- } catch (error) {
240
- if (error?.code === 'ENOENT') return { ok: false, unsafe: false };
241
- return { ok: false, unsafe: true, error };
242
- }
243
- }
244
-
245
- function sourceHasManagedMarker(source) {
246
- return source.includes(markerStart) || source.includes(markerEnd);
247
- }
248
-
249
- /** Inspect only the canonical EvolCore managed-hook targets. */
250
- export function inspectManagedHookInstallation({ requirements, managedDir, packageRoot }) {
251
- const canonicalRequirements = path.resolve(requirements);
252
- const canonicalManagedDir = path.resolve(managedDir);
253
- const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
254
- for (const directory of [path.dirname(canonicalRequirements), canonicalManagedDir]) {
255
- try {
256
- const stat = fs.lstatSync(directory);
257
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
258
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `${directory} must be a real directory` };
259
- }
260
- } catch (error) {
261
- if (error?.code !== 'ENOENT') return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: error?.message || String(error) };
262
- }
263
- }
264
- const req = regularFile(canonicalRequirements);
265
- const hook = regularFile(hookPath);
266
- if (req.unsafe || hook.unsafe) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is not a regular file' };
267
- if (!req.ok && hook.ok) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'canonical launcher exists but requirements.toml is missing' };
268
- if (req.ok && !hook.ok) {
269
- // A missing launcher can be repaired only when the requirements file is
270
- // still an untouched user configuration. If it already contains any
271
- // EvolCore-managed policy, treat the partial state as drift and fail
272
- // closed instead of guessing which policy is authoritative.
273
- try {
274
- const source = fs.readFileSync(canonicalRequirements, 'utf8');
275
- const partial = parseToml(source);
276
- const managedPolicyPresent = sourceHasManagedMarker(source)
277
- || partial.allow_managed_hooks_only !== undefined
278
- || partial.hooks?.windows_managed_dir !== undefined
279
- || partial.hooks?.managed_dir !== undefined;
280
- if (managedPolicyPresent) {
281
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements contains managed-hook policy but the canonical launcher is missing' };
282
- }
283
- } catch (error) {
284
- return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` };
285
- }
286
- }
287
- if (!req.ok || !hook.ok) return { status: 'missing', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is missing' };
288
- let parsed;
289
- try { parsed = parseToml(fs.readFileSync(canonicalRequirements, 'utf8')); }
290
- catch (error) { return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` }; }
291
- const configured = parsed.hooks?.windows_managed_dir ?? parsed.hooks?.managed_dir;
292
- const normalized = value => path.normalize(String(value || '')).toLowerCase();
293
- const launcher = fs.readFileSync(hookPath, 'utf8');
294
- const packageMarker = launcher.includes('EVOLCORE_MANAGED_HOOK_LAUNCHER')
295
- && launcher.toLowerCase().includes(JSON.stringify(path.resolve(packageRoot || process.cwd())).toLowerCase());
296
- const preToolUse = parsed.hooks?.PreToolUse;
297
- const canonicalCommand = value => {
298
- if (typeof value !== 'string' || !value || /[\r\n;&|<>]/.test(value)) return false;
299
- const withoutSocket = value.replace(/\s+%EVOLCORE_INSTANCE_SOCKET%\s*$/i, '').trim();
300
- return withoutSocket.replace(/["']+$/, '').toLowerCase().endsWith(normalized(hookPath));
301
- };
302
- const loaded = Array.isArray(preToolUse) && preToolUse.some(group => group?.matcher === '*'
303
- && Array.isArray(group.hooks) && group.hooks.some(handler => handler?.type === 'command'
304
- && handler.async !== true && typeof handler.command === 'string'
305
- && canonicalCommand(handler.command)
306
- && canonicalCommand(handler.command_windows ?? handler.commandWindows)));
307
- const valid = parsed.allow_managed_hooks_only === true
308
- && parsed.features?.hooks === true
309
- && normalized(configured) === normalized(canonicalManagedDir)
310
- && packageMarker && loaded;
311
- return valid
312
- ? { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath }
313
- : { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'managed-hook policy is missing, altered, or points outside the canonical target' };
314
- }
315
-
316
- /** Idempotently repair a missing canonical installation; unsafe edits fail closed. */
317
- export function repairManagedHookInstallation(options, acl = windowsAcl) {
318
- const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
319
- const canonicalRequirements = path.resolve(requirements);
320
- const canonicalManagedDir = path.resolve(managedDir);
321
- const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
322
- const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
323
- const state = inspectManagedHookInstallation({ requirements: canonicalRequirements, managedDir: canonicalManagedDir, packageRoot });
324
- if (state.status === 'installed') return { ...state, repaired: false, warnings: [] };
325
- if (state.status === 'unsafe') throw new Error(`Refusing automatic managed-hook repair: ${state.reason}`);
326
- if (!fs.existsSync(sourceHook)) throw new Error(`Required Hook runtime file was not found: ${sourceHook}`);
327
- const previousContent = fs.existsSync(canonicalRequirements) ? fs.readFileSync(canonicalRequirements, 'utf8') : '';
328
- const content = buildManagedRequirements(previousContent, { targetDirectory: canonicalManagedDir, nodePath, hookPath });
329
- const warnings = provisionManagedFiles({ requirements: canonicalRequirements, hookPath, sourceHook, nodePath, previousContent, content, launcher: managedHookLauncher(packageRoot) }, acl);
330
- return { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, repaired: true, warnings };
331
- }
332
-
333
- export function windowsAcl(action, payload = {}, run = execFileSync) {
334
- const executable = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
335
- try {
336
- const output = run(executable, [
337
- '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', aclScript,
338
- '-Request', Buffer.from(JSON.stringify({ action, ...payload })).toString('base64'),
339
- ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, timeout: 30_000 });
340
- return JSON.parse(output.replace(/^\uFEFF/, '').trim());
341
- } catch (error) {
342
- const detail = error.stderr?.toString().trim() || error.message || String(error);
343
- throw new Error(`Windows ACL ${action} failed (${payload.path || 'access verification'}, exit=${error.status ?? 'unknown'}): ${detail}`, { cause: error });
344
- }
345
- }
346
-
347
- function existingFile(file, io) {
348
- try {
349
- const stat = io.lstatSync(file);
350
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Expected a regular file: ${file}`);
351
- return stat;
352
- } catch (error) {
353
- if (error.code === 'ENOENT') return undefined;
354
- throw error;
355
- }
356
- }
357
-
358
- function makeReplaceable(file, io) {
359
- const stat = existingFile(file, io);
360
- // Windows' readonly attribute prevents replacement even for Administrators.
361
- // chmod affects that attribute, not the DACL. Restore it on the old inode.
362
- if (process.platform === 'win32' && stat && !(stat.mode & 0o200)) io.chmodSync(file, 0o600);
363
- }
364
-
365
- /** Keep the original inodes (including ACLs) until both replacements validate. */
366
- export function commitPreparedFiles(entries, verify, io = fs) {
367
- const records = [];
368
- try {
369
- for (const entry of entries) {
370
- const stat = existingFile(entry.file, io);
371
- const record = { ...entry, mode: stat?.mode, backup: undefined, installed: false };
372
- if (stat) {
373
- const backup = `${entry.file}.evolcore-backup-${randomUUID()}`;
374
- // A same-directory hard link retains the exact original security
375
- // descriptor. If unsupported, stop before replacing any live file.
376
- io.linkSync(entry.file, backup);
377
- record.backup = backup;
378
- }
379
- records.push(record);
380
- }
381
- for (const record of records) {
382
- makeReplaceable(record.file, io);
383
- io.renameSync(record.temporary, record.file);
384
- record.installed = true;
385
- if (record.backup) io.chmodSync(record.backup, record.mode);
386
- }
387
- verify();
388
- } catch (error) {
389
- const recoveryErrors = [];
390
- for (const record of records.toReversed()) {
391
- try {
392
- if (record.installed) {
393
- makeReplaceable(record.file, io);
394
- if (record.backup) io.renameSync(record.backup, record.file);
395
- else io.unlinkSync(record.file);
396
- }
397
- if (record.backup && io.existsSync(record.backup)) {
398
- makeReplaceable(record.backup, io);
399
- io.unlinkSync(record.backup);
400
- }
401
- if (record.mode !== undefined) io.chmodSync(record.file, record.mode);
402
- } catch (recoveryError) {
403
- recoveryErrors.push(`${record.file}: ${recoveryError.message}; original retained at ${record.backup || '(new installation)'}`);
404
- }
405
- }
406
- throw new Error(`${error.message}${recoveryErrors.length
407
- ? `; rollback incomplete: ${recoveryErrors.join(' | ')}`
408
- : '; previous files and permissions restored'}`, { cause: error });
409
- }
410
- const warnings = [];
411
- for (const record of records) {
412
- if (!record.backup) continue;
413
- try {
414
- makeReplaceable(record.backup, io);
415
- io.unlinkSync(record.backup);
416
- } catch (error) {
417
- warnings.push(`Installed successfully, but could not remove backup ${record.backup}: ${error.message}`);
418
- }
419
- }
420
- return warnings;
421
- }
422
-
423
- /** This transaction is used only by explicit provisioning, never npm upgrades. */
424
- export function provisionManagedFiles(options, acl = windowsAcl) {
425
- const { requirements, hookPath, sourceHook, nodePath, content, launcher } = options;
426
- const directory = path.dirname(hookPath);
427
- const configDirectory = path.dirname(requirements);
428
- acl('preflight');
429
- fs.mkdirSync(configDirectory, { recursive: true });
430
- const lockPath = path.join(configDirectory, '.evolcore-hooks.install.lock');
431
- let lock;
432
- try { lock = fs.openSync(lockPath, 'wx', 0o600); } catch (error) {
433
- throw new Error(`Cannot acquire installer lock ${lockPath}: ${error.message}. If an installer crashed, confirm it has stopped before removing the lock.`, { cause: error });
434
- }
435
- const staged = [];
436
- let committed = false;
437
- try {
438
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
439
- const existing = existingFile(requirements, fs);
440
- // Detect edits made after configuration generation, including a second
441
- // installer completing just before this process acquired the lock.
442
- if ((existing ? fs.readFileSync(requirements, 'utf8') : '') !== options.previousContent) {
443
- throw new Error(`Configuration changed while preparing installation: ${requirements}. Retry using the latest configuration.`);
444
- }
445
- if (fs.existsSync(directory)) {
446
- const stat = fs.lstatSync(directory);
447
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Expected a real hook directory: ${directory}`);
448
- } else {
449
- fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
450
- acl('prepare', { path: directory, directory: true });
451
- }
452
- // Existing directory ACLs are checked below, never rewritten: changing
453
- // inheritable ACEs could alter the live Hook before the transaction starts.
454
- for (const [file, value, reference] of [
455
- [hookPath, launcher, undefined],
456
- [requirements, content, existing ? requirements : undefined],
457
- ]) {
458
- const temporary = `${file}.evolcore-${randomUUID()}.tmp`;
459
- staged.push({ file, temporary, value });
460
- fs.writeFileSync(temporary, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
461
- acl('prepare', { path: temporary, reference });
462
- }
463
- const readable = [
464
- { path: configDirectory, execute: true },
465
- { path: sourceHook },
466
- { path: nodePath, execute: true },
467
- ];
468
- const verify = (temporary) => {
469
- for (const entry of staged) {
470
- const target = temporary ? entry.temporary : entry.file;
471
- if (fs.readFileSync(target, 'utf8') !== entry.value) throw new Error(`Installed content differs: ${target}`);
472
- }
473
- return acl('verify', { entries: [
474
- { path: directory, protected: true, execute: true },
475
- ...staged.map(entry => ({ path: temporary ? entry.temporary : entry.file, protected: true })),
476
- ...readable,
477
- ] });
478
- };
479
- verify(true);
480
- let accessReport;
481
- const warnings = commitPreparedFiles(staged, () => { accessReport = verify(false); });
482
- committed = true;
483
- if ([accessReport].flat().some(entry => entry?.userProbe === 'unavailable')) {
484
- warnings.push('ACLs verified, but this elevated account has no normal UAC linked token. Verify file reads and Hook execution from the intended non-elevated user before use.');
485
- }
486
- return warnings;
487
- } finally {
488
- for (const entry of staged) {
489
- try { fs.rmSync(entry.temporary, { force: true }); } catch (error) {
490
- process.stderr.write(`[evolcore] Could not clean staging file ${entry.temporary}: ${error.message}\n`);
491
- }
492
- }
493
- fs.closeSync(lock);
494
- try { fs.unlinkSync(lockPath); } catch (error) {
495
- process.stderr.write(`[evolcore] ${committed ? 'Installed; ' : ''}could not remove installer lock ${lockPath}: ${error.message}\n`);
496
- }
497
- }
498
- }
499
-
500
- function main() {
501
- // npm may preserve its parent lifecycle variable on Windows when this
502
- // script is spawned from a test runner. A global install without an
503
- // explicit package root is still the postinstall shape; never enter the
504
- // machine provisioning branch on an ordinary Windows lifecycle.
505
- if (lifecycleEvent() === 'postinstall' || (isGlobalInstall() && !argument('--package-root'))) {
506
- runLinuxPostinstall();
507
- return;
508
- }
509
- if (process.platform === 'linux' && argument('--mountpoint')) {
510
- runLinuxPostinstall();
511
- return;
512
- }
513
- if (process.platform !== 'win32') fail('Codex managed hook provisioning is only supported on Windows.');
514
- if (!argument('--package-root')) fail('--package-root is required.');
515
- const packageRoot = path.resolve(argument('--package-root'));
516
- const nodePath = path.resolve(argument('--node-path') || process.execPath);
517
- const requirements = path.resolve(argument('--requirements')
518
- || path.join(process.env.ProgramData || path.join(os.homedir(), 'ProgramData'), 'OpenAI', 'Codex', 'requirements.toml'));
519
- const targetDirectory = path.resolve(argument('--managed-dir') || path.join(path.dirname(requirements), 'EvolCore', 'hooks'));
520
- const hookPath = path.join(targetDirectory, 'pre-tool-use.mjs');
521
- const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
522
- for (const file of [sourceHook, nodePath]) {
523
- if (!fs.statSync(file).isFile()) fail(`Required Hook runtime file was not found: ${file}`);
524
- }
525
- if (argument('--repair')) {
526
- const result = repairManagedHookInstallation({ requirements, managedDir: targetDirectory, packageRoot, nodePath });
527
- process.stdout.write(`${JSON.stringify(result)}\n`);
528
- return;
529
- }
530
- const previousContent = fs.existsSync(requirements) ? fs.readFileSync(requirements, 'utf8') : '';
531
- const content = buildManagedRequirements(previousContent, { targetDirectory, nodePath, hookPath });
532
- const warnings = provisionManagedFiles({
533
- requirements, hookPath, sourceHook, nodePath, previousContent, content,
534
- launcher: managedHookLauncher(packageRoot),
535
- });
536
- for (const warning of warnings) process.stderr.write(`[evolcore] ${warning}\n`);
537
- process.stdout.write(`${JSON.stringify({ requirements, managedDir: targetDirectory, hookPath })}\n`);
538
- }
539
-
540
- if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
541
- try { main(); } catch (error) {
542
- fail(error instanceof Error ? error.message : String(error));
543
- }
544
- }
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+ import { isDeepStrictEqual } from 'node:util';
10
+ import { parse as parseToml } from 'smol-toml';
11
+
12
+ const markerStart = '# BEGIN EVOLCORE MANAGED CODEX HOOK';
13
+ const markerEnd = '# END EVOLCORE MANAGED CODEX HOOK';
14
+ const aclScript = fileURLToPath(new URL('./codex-managed-acl.ps1', import.meta.url));
15
+
16
+ function argument(name) {
17
+ const index = process.argv.indexOf(name);
18
+ return index >= 0 ? process.argv[index + 1] : undefined;
19
+ }
20
+
21
+ function hasArgument(name) {
22
+ return process.argv.includes(name);
23
+ }
24
+
25
+ function fail(message) {
26
+ process.stderr.write(`[evolcore] ${message}\n`);
27
+ process.exit(1);
28
+ }
29
+
30
+ function isGlobalInstall() {
31
+ return ['1', 'true'].includes(String(process.env.npm_config_global || '').toLowerCase());
32
+ }
33
+
34
+ function lifecycleEvent() {
35
+ const entry = Object.entries(process.env).find(([key]) => key.toLowerCase() === 'npm_lifecycle_event');
36
+ return String(entry?.[1] || '').toLowerCase();
37
+ }
38
+
39
+ function ensureRealDirectory(directory) {
40
+ let stat;
41
+ try {
42
+ stat = fs.lstatSync(directory);
43
+ } catch (error) {
44
+ if (error?.code !== 'ENOENT') {
45
+ fail(`could not inspect the Codex managed requirements mountpoint ${directory}: ${error?.message || String(error)}`);
46
+ }
47
+ }
48
+
49
+ if (stat) {
50
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
51
+ fail(`Codex managed requirements mountpoint is unsafe: ${directory} must be a real directory.`);
52
+ }
53
+ return;
54
+ }
55
+
56
+ try {
57
+ fs.mkdirSync(directory, { mode: 0o755 });
58
+ fs.chmodSync(directory, 0o755);
59
+ } catch (error) {
60
+ if (error?.code === 'EEXIST') {
61
+ const raced = fs.lstatSync(directory);
62
+ if (raced.isDirectory() && !raced.isSymbolicLink()) return;
63
+ }
64
+ fail(
65
+ `Linux global installation requires the real directory ${directory}, but it could not be created: `
66
+ + `${error?.message || String(error)}. `
67
+ + `Create it first with: sudo install -d -m 0755 ${directory}`,
68
+ );
69
+ }
70
+
71
+ const created = fs.lstatSync(directory);
72
+ if (!created.isDirectory() || created.isSymbolicLink()) {
73
+ fail(`Codex managed requirements mountpoint provisioning failed: ${directory} must be a real directory.`);
74
+ }
75
+ process.stdout.write(`[evolcore] Prepared Codex managed requirements mountpoint at ${directory}.\n`);
76
+ }
77
+
78
+ function runLinuxPostinstall() {
79
+ const explicitMountpoint = argument('--mountpoint');
80
+ if (process.platform !== 'linux') return;
81
+ // Local source installs do not launch the Linux Codex guard and must not
82
+ // mutate machine-wide configuration. An explicit path is accepted only for
83
+ // isolated lifecycle behavior tests.
84
+ if (!isGlobalInstall() && !explicitMountpoint) return;
85
+ ensureRealDirectory(explicitMountpoint || '/etc/codex');
86
+ }
87
+
88
+ function tomlString(value) {
89
+ return JSON.stringify(value);
90
+ }
91
+
92
+ function windowsCommandArg(value) {
93
+ // Keep filesystem separators intact; tomlString() performs the required
94
+ // TOML escaping after this Windows command-line quoting step.
95
+ return `"${value.replaceAll('"', '\\"')}"`;
96
+ }
97
+
98
+ function windowsPostinstallNotice() {
99
+ if (process.platform !== 'win32') return;
100
+ process.stderr.write(
101
+ '[evolcore] ec start/restart automatically checks and installs missing Codex managed hooks on Windows.\n'
102
+ + '[evolcore] Accept the Windows administrator (UAC) prompt when installation is needed; no separate setup command is required.\n',
103
+ );
104
+ }
105
+
106
+ function removeManagedBlock(source) {
107
+ const original = parseToml(source);
108
+ if (!source.includes(markerStart) && !source.includes(markerEnd)) return source;
109
+ const unsafe = () => new Error('Ambiguous EvolCore managed Hook markers in requirements.toml. Existing configuration was not modified.');
110
+ const expression = new RegExp(`^${markerStart}\\r?\\n[\\s\\S]*?^${markerEnd}(?:\\r?\\n|$)`, 'gm');
111
+ const matches = [...source.matchAll(expression)];
112
+ if (matches.length !== 1 || source.split(markerStart).length !== 2 || source.split(markerEnd).length !== 2) throw unsafe();
113
+ const block = parseToml(matches[0][0]);
114
+ const groups = block.hooks?.PreToolUse;
115
+ if (!Array.isArray(groups) || groups.length !== 1
116
+ || !isDeepStrictEqual(block, { hooks: { PreToolUse: groups } })) throw unsafe();
117
+ const content = source.replace(matches[0][0], '');
118
+ const retained = parseToml(content);
119
+ const originalGroups = original.hooks?.PreToolUse;
120
+ if (!Array.isArray(originalGroups)) throw unsafe();
121
+ // Markers inside a TOML string are not comments. Prove that removing the
122
+ // block removes only its Hook group, with every other policy unchanged.
123
+ const safe = originalGroups.some((group, index) => {
124
+ if (!isDeepStrictEqual(group, groups[0])) return false;
125
+ const expected = structuredClone(original);
126
+ expected.hooks.PreToolUse.splice(index, 1);
127
+ if (!expected.hooks.PreToolUse.length && !retained.hooks?.PreToolUse) delete expected.hooks.PreToolUse;
128
+ if (!Object.keys(expected.hooks).length && !retained.hooks) delete expected.hooks;
129
+ return isDeepStrictEqual(expected, retained);
130
+ });
131
+ if (!safe) throw unsafe();
132
+ return content;
133
+ }
134
+
135
+ function tableBounds(lines, table) {
136
+ const header = table ? `[${table}]` : null;
137
+ const start = header
138
+ ? lines.findIndex(line => line.trim() === header || line.trim().startsWith(`${header} #`))
139
+ : -1;
140
+ if (table && start < 0) return null;
141
+ const from = table ? start + 1 : 0;
142
+ let to = lines.length;
143
+ for (let index = from; index < lines.length; index += 1) {
144
+ if (/^\s*\[\[?[^\]]+\]\]?\s*(?:#.*)?$/.test(lines[index])) {
145
+ to = index;
146
+ break;
147
+ }
148
+ }
149
+ return { start, from, to };
150
+ }
151
+
152
+ function setTomlKey(source, table, key, value) {
153
+ const lines = source.split('\n');
154
+ let bounds = tableBounds(lines, table);
155
+ if (!bounds) {
156
+ if (table) {
157
+ if (lines.length && lines.at(-1) !== '') lines.push('');
158
+ lines.push(`[${table}]`, `${key} = ${value}`);
159
+ } else {
160
+ let insertAt = lines.findIndex(line => /^\s*\[/.test(line));
161
+ if (insertAt < 0) insertAt = lines.length;
162
+ lines.splice(insertAt, 0, `${key} = ${value}`);
163
+ }
164
+ return lines.join('\n');
165
+ }
166
+ const keyExpression = new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}\\s*=`);
167
+ const existing = lines.slice(bounds.from, bounds.to).findIndex(line => keyExpression.test(line));
168
+ if (existing >= 0) {
169
+ lines[bounds.from + existing] = `${key} = ${value}`;
170
+ } else {
171
+ lines.splice(bounds.from, 0, `${key} = ${value}`);
172
+ }
173
+ return lines.join('\n');
174
+ }
175
+
176
+ export function managedHookLauncher(packageRoot) {
177
+ // Keep the machine-wide entrypoint stable across npm upgrades. Those
178
+ // upgrades replace the package contents at this stable global path, so
179
+ // this file never needs to be rewritten just because the hook changed.
180
+ const trustedPackageRoot = path.resolve(packageRoot);
181
+ return `#!/usr/bin/env node
182
+ import path from 'node:path';
183
+ import { pathToFileURL } from 'node:url';
184
+
185
+ // EVOLCORE_MANAGED_HOOK_LAUNCHER
186
+ const packageRoot = ${JSON.stringify(trustedPackageRoot)};
187
+
188
+ try {
189
+ await import(pathToFileURL(path.join(packageRoot, 'bin', 'codex-managed-hook.mjs')).href);
190
+ } catch (error) {
191
+ process.stderr.write('[evolcore] failed to load the current managed hook: '
192
+ + (error instanceof Error ? error.message : String(error)) + '\\n');
193
+ process.exit(2);
194
+ }
195
+ `;
196
+ }
197
+
198
+ export function buildManagedRequirements(source, { targetDirectory, nodePath, hookPath }) {
199
+ // Keep the existing text editor, but reject unsupported TOML layouts before
200
+ // writing anything. Parsing also catches duplicate tables/keys on reinstall.
201
+ let content = removeManagedBlock(source);
202
+ const before = parseToml(content);
203
+ content = setTomlKey(content, null, 'allow_managed_hooks_only', 'true');
204
+ content = setTomlKey(content, 'features', 'hooks', 'true');
205
+ content = setTomlKey(content, 'hooks', 'windows_managed_dir', tomlString(path.resolve(targetDirectory)));
206
+ if (!content.endsWith('\n')) content += '\n';
207
+ // Windows hook command must include %EVOLCORE_INSTANCE_SOCKET% so Codex
208
+ // expands it at runtime with the per-daemon socket path
209
+ const command = `${windowsCommandArg(nodePath)} ${windowsCommandArg(hookPath)} %EVOLCORE_INSTANCE_SOCKET%`;
210
+ content += [
211
+ markerStart,
212
+ '[[hooks.PreToolUse]]',
213
+ 'matcher = "*"',
214
+ '',
215
+ '[[hooks.PreToolUse.hooks]]',
216
+ 'type = "command"',
217
+ `command = ${tomlString(command)}`,
218
+ `command_windows = ${tomlString(command)}`,
219
+ // Intentionally omit timeout: Codex applies its documented 600-second
220
+ // default for synchronous PreToolUse hooks. The application pause gate
221
+ // itself has no timeout; Codex remains the outer infrastructure ceiling.
222
+ 'statusMessage = "Checking EvolCore session policy"',
223
+ markerEnd,
224
+ '',
225
+ ].join('\n');
226
+ const after = parseToml(content);
227
+ const expected = {
228
+ ...before,
229
+ allow_managed_hooks_only: true,
230
+ features: { ...before.features, hooks: true },
231
+ hooks: {
232
+ ...before.hooks,
233
+ windows_managed_dir: path.resolve(targetDirectory),
234
+ PreToolUse: [
235
+ ...(before.hooks?.PreToolUse || []),
236
+ { matcher: '*', hooks: [{ type: 'command', command, command_windows: command, statusMessage: 'Checking EvolCore session policy' }] },
237
+ ],
238
+ },
239
+ };
240
+ if (!isDeepStrictEqual(after, expected)) {
241
+ throw new Error('Could not safely update requirements.toml without changing unrelated policy. Existing configuration was not modified.');
242
+ }
243
+ return content;
244
+ }
245
+
246
+ function regularFile(file) {
247
+ try {
248
+ const stat = fs.lstatSync(file);
249
+ if (!stat.isFile() || stat.isSymbolicLink()) return { ok: false, unsafe: true };
250
+ return { ok: true };
251
+ } catch (error) {
252
+ if (error?.code === 'ENOENT') return { ok: false, unsafe: false };
253
+ return { ok: false, unsafe: true, error };
254
+ }
255
+ }
256
+
257
+ function sourceHasManagedMarker(source) {
258
+ return source.includes(markerStart) || source.includes(markerEnd);
259
+ }
260
+
261
+ /** Inspect only the canonical EvolCore managed-hook targets. */
262
+ export function inspectManagedHookInstallation({ requirements, managedDir, packageRoot }) {
263
+ const canonicalRequirements = path.resolve(requirements);
264
+ const canonicalManagedDir = path.resolve(managedDir);
265
+ const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
266
+ for (const directory of [path.dirname(canonicalRequirements), canonicalManagedDir]) {
267
+ try {
268
+ const stat = fs.lstatSync(directory);
269
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
270
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `${directory} must be a real directory` };
271
+ }
272
+ } catch (error) {
273
+ if (error?.code !== 'ENOENT') return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: error?.message || String(error) };
274
+ }
275
+ }
276
+ const req = regularFile(canonicalRequirements);
277
+ const hook = regularFile(hookPath);
278
+ if (req.unsafe || hook.unsafe) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is not a regular file' };
279
+ if (!req.ok && hook.ok) return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'canonical launcher exists but requirements.toml is missing' };
280
+ if (req.ok && !hook.ok) {
281
+ // A missing launcher can be repaired only when the requirements file is
282
+ // still an untouched user configuration. If it already contains any
283
+ // EvolCore-managed policy, treat the partial state as drift and fail
284
+ // closed instead of guessing which policy is authoritative.
285
+ try {
286
+ const source = fs.readFileSync(canonicalRequirements, 'utf8');
287
+ const partial = parseToml(source);
288
+ const managedPolicyPresent = sourceHasManagedMarker(source)
289
+ || partial.allow_managed_hooks_only !== undefined
290
+ || partial.hooks?.windows_managed_dir !== undefined
291
+ || partial.hooks?.managed_dir !== undefined;
292
+ if (managedPolicyPresent) {
293
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements contains managed-hook policy but the canonical launcher is missing' };
294
+ }
295
+ } catch (error) {
296
+ return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` };
297
+ }
298
+ }
299
+ if (!req.ok || !hook.ok) return { status: 'missing', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'requirements or launcher is missing' };
300
+ let parsed;
301
+ try { parsed = parseToml(fs.readFileSync(canonicalRequirements, 'utf8')); }
302
+ catch (error) { return { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: `requirements.toml is invalid: ${error?.message || String(error)}` }; }
303
+ const configured = parsed.hooks?.windows_managed_dir ?? parsed.hooks?.managed_dir;
304
+ const normalized = value => path.normalize(String(value || '')).toLowerCase();
305
+ const launcher = fs.readFileSync(hookPath, 'utf8');
306
+ const packageMarker = launcher.includes('EVOLCORE_MANAGED_HOOK_LAUNCHER')
307
+ && launcher.toLowerCase().includes(JSON.stringify(path.resolve(packageRoot || process.cwd())).toLowerCase());
308
+ const preToolUse = parsed.hooks?.PreToolUse;
309
+ const canonicalCommand = value => {
310
+ if (typeof value !== 'string' || !value || /[\r\n;&|<>]/.test(value)) return false;
311
+ const withoutSocket = value.replace(/\s+%EVOLCORE_INSTANCE_SOCKET%\s*$/i, '').trim();
312
+ return withoutSocket.replace(/["']+$/, '').toLowerCase().endsWith(normalized(hookPath));
313
+ };
314
+ const loaded = Array.isArray(preToolUse) && preToolUse.some(group => group?.matcher === '*'
315
+ && Array.isArray(group.hooks) && group.hooks.some(handler => handler?.type === 'command'
316
+ && handler.async !== true && typeof handler.command === 'string'
317
+ && canonicalCommand(handler.command)
318
+ && canonicalCommand(handler.command_windows ?? handler.commandWindows)));
319
+ const valid = parsed.allow_managed_hooks_only === true
320
+ && parsed.features?.hooks === true
321
+ && normalized(configured) === normalized(canonicalManagedDir)
322
+ && packageMarker && loaded;
323
+ return valid
324
+ ? { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath }
325
+ : { status: 'unsafe', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, reason: 'managed-hook policy is missing, altered, or points outside the canonical target' };
326
+ }
327
+
328
+ /** Idempotently repair a missing canonical installation; unsafe edits fail closed. */
329
+ export function repairManagedHookInstallation(options, acl = windowsAcl) {
330
+ const { requirements, managedDir, packageRoot, nodePath = process.execPath } = options;
331
+ const canonicalRequirements = path.resolve(requirements);
332
+ const canonicalManagedDir = path.resolve(managedDir);
333
+ const hookPath = path.join(canonicalManagedDir, 'pre-tool-use.mjs');
334
+ const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
335
+ const state = inspectManagedHookInstallation({ requirements: canonicalRequirements, managedDir: canonicalManagedDir, packageRoot });
336
+ if (state.status === 'installed') return { ...state, repaired: false, warnings: [] };
337
+ if (state.status === 'unsafe') throw new Error(`Refusing automatic managed-hook repair: ${state.reason}`);
338
+ if (!fs.existsSync(sourceHook)) throw new Error(`Required Hook runtime file was not found: ${sourceHook}`);
339
+ const previousContent = fs.existsSync(canonicalRequirements) ? fs.readFileSync(canonicalRequirements, 'utf8') : '';
340
+ const content = buildManagedRequirements(previousContent, { targetDirectory: canonicalManagedDir, nodePath, hookPath });
341
+ const warnings = provisionManagedFiles({ requirements: canonicalRequirements, hookPath, sourceHook, nodePath, previousContent, content, launcher: managedHookLauncher(packageRoot) }, acl);
342
+ return { status: 'installed', requirements: canonicalRequirements, managedDir: canonicalManagedDir, hookPath, repaired: true, warnings };
343
+ }
344
+
345
+ export function windowsAcl(action, payload = {}, run = execFileSync) {
346
+ const executable = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
347
+ try {
348
+ const output = run(executable, [
349
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', aclScript,
350
+ '-Request', Buffer.from(JSON.stringify({ action, ...payload })).toString('base64'),
351
+ ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, timeout: 30_000 });
352
+ return JSON.parse(output.replace(/^\uFEFF/, '').trim());
353
+ } catch (error) {
354
+ const detail = error.stderr?.toString().trim() || error.message || String(error);
355
+ throw new Error(`Windows ACL ${action} failed (${payload.path || 'access verification'}, exit=${error.status ?? 'unknown'}): ${detail}`, { cause: error });
356
+ }
357
+ }
358
+
359
+ function existingFile(file, io) {
360
+ try {
361
+ const stat = io.lstatSync(file);
362
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Expected a regular file: ${file}`);
363
+ return stat;
364
+ } catch (error) {
365
+ if (error.code === 'ENOENT') return undefined;
366
+ throw error;
367
+ }
368
+ }
369
+
370
+ function makeReplaceable(file, io) {
371
+ const stat = existingFile(file, io);
372
+ // Windows' readonly attribute prevents replacement even for Administrators.
373
+ // chmod affects that attribute, not the DACL. Restore it on the old inode.
374
+ if (process.platform === 'win32' && stat && !(stat.mode & 0o200)) io.chmodSync(file, 0o600);
375
+ }
376
+
377
+ /** Keep the original inodes (including ACLs) until both replacements validate. */
378
+ export function commitPreparedFiles(entries, verify, io = fs) {
379
+ const records = [];
380
+ try {
381
+ for (const entry of entries) {
382
+ const stat = existingFile(entry.file, io);
383
+ const record = { ...entry, mode: stat?.mode, backup: undefined, installed: false };
384
+ if (stat) {
385
+ const backup = `${entry.file}.evolcore-backup-${randomUUID()}`;
386
+ // A same-directory hard link retains the exact original security
387
+ // descriptor. If unsupported, stop before replacing any live file.
388
+ io.linkSync(entry.file, backup);
389
+ record.backup = backup;
390
+ }
391
+ records.push(record);
392
+ }
393
+ for (const record of records) {
394
+ makeReplaceable(record.file, io);
395
+ io.renameSync(record.temporary, record.file);
396
+ record.installed = true;
397
+ if (record.backup) io.chmodSync(record.backup, record.mode);
398
+ }
399
+ verify();
400
+ } catch (error) {
401
+ const recoveryErrors = [];
402
+ for (const record of records.toReversed()) {
403
+ try {
404
+ if (record.installed) {
405
+ makeReplaceable(record.file, io);
406
+ if (record.backup) io.renameSync(record.backup, record.file);
407
+ else io.unlinkSync(record.file);
408
+ }
409
+ if (record.backup && io.existsSync(record.backup)) {
410
+ makeReplaceable(record.backup, io);
411
+ io.unlinkSync(record.backup);
412
+ }
413
+ if (record.mode !== undefined) io.chmodSync(record.file, record.mode);
414
+ } catch (recoveryError) {
415
+ recoveryErrors.push(`${record.file}: ${recoveryError.message}; original retained at ${record.backup || '(new installation)'}`);
416
+ }
417
+ }
418
+ throw new Error(`${error.message}${recoveryErrors.length
419
+ ? `; rollback incomplete: ${recoveryErrors.join(' | ')}`
420
+ : '; previous files and permissions restored'}`, { cause: error });
421
+ }
422
+ const warnings = [];
423
+ for (const record of records) {
424
+ if (!record.backup) continue;
425
+ try {
426
+ makeReplaceable(record.backup, io);
427
+ io.unlinkSync(record.backup);
428
+ } catch (error) {
429
+ warnings.push(`Installed successfully, but could not remove backup ${record.backup}: ${error.message}`);
430
+ }
431
+ }
432
+ return warnings;
433
+ }
434
+
435
+ /** This transaction is used only by explicit provisioning, never npm upgrades. */
436
+ export function provisionManagedFiles(options, acl = windowsAcl) {
437
+ const { requirements, hookPath, sourceHook, nodePath, content, launcher } = options;
438
+ const directory = path.dirname(hookPath);
439
+ const configDirectory = path.dirname(requirements);
440
+ acl('preflight');
441
+ fs.mkdirSync(configDirectory, { recursive: true });
442
+ const lockPath = path.join(configDirectory, '.evolcore-hooks.install.lock');
443
+ let lock;
444
+ try { lock = fs.openSync(lockPath, 'wx', 0o600); } catch (error) {
445
+ throw new Error(`Cannot acquire installer lock ${lockPath}: ${error.message}. If an installer crashed, confirm it has stopped before removing the lock.`, { cause: error });
446
+ }
447
+ const staged = [];
448
+ let committed = false;
449
+ try {
450
+ fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, started: new Date().toISOString() }));
451
+ const existing = existingFile(requirements, fs);
452
+ // Detect edits made after configuration generation, including a second
453
+ // installer completing just before this process acquired the lock.
454
+ if ((existing ? fs.readFileSync(requirements, 'utf8') : '') !== options.previousContent) {
455
+ throw new Error(`Configuration changed while preparing installation: ${requirements}. Retry using the latest configuration.`);
456
+ }
457
+ if (fs.existsSync(directory)) {
458
+ const stat = fs.lstatSync(directory);
459
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Expected a real hook directory: ${directory}`);
460
+ } else {
461
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
462
+ acl('prepare', { path: directory, directory: true });
463
+ }
464
+ // Existing directory ACLs are checked below, never rewritten: changing
465
+ // inheritable ACEs could alter the live Hook before the transaction starts.
466
+ for (const [file, value, reference] of [
467
+ [hookPath, launcher, undefined],
468
+ [requirements, content, existing ? requirements : undefined],
469
+ ]) {
470
+ const temporary = `${file}.evolcore-${randomUUID()}.tmp`;
471
+ staged.push({ file, temporary, value });
472
+ fs.writeFileSync(temporary, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
473
+ acl('prepare', { path: temporary, reference });
474
+ }
475
+ const readable = [
476
+ { path: configDirectory, execute: true },
477
+ { path: sourceHook },
478
+ { path: nodePath, execute: true },
479
+ ];
480
+ const verify = (temporary) => {
481
+ for (const entry of staged) {
482
+ const target = temporary ? entry.temporary : entry.file;
483
+ if (fs.readFileSync(target, 'utf8') !== entry.value) throw new Error(`Installed content differs: ${target}`);
484
+ }
485
+ return acl('verify', { entries: [
486
+ { path: directory, protected: true, execute: true },
487
+ ...staged.map(entry => ({ path: temporary ? entry.temporary : entry.file, protected: true })),
488
+ ...readable,
489
+ ] });
490
+ };
491
+ verify(true);
492
+ let accessReport;
493
+ const warnings = commitPreparedFiles(staged, () => { accessReport = verify(false); });
494
+ committed = true;
495
+ if ([accessReport].flat().some(entry => entry?.userProbe === 'unavailable')) {
496
+ warnings.push('ACLs verified, but this elevated account has no normal UAC linked token. Verify file reads and Hook execution from the intended non-elevated user before use.');
497
+ }
498
+ return warnings;
499
+ } finally {
500
+ for (const entry of staged) {
501
+ try { fs.rmSync(entry.temporary, { force: true }); } catch (error) {
502
+ process.stderr.write(`[evolcore] Could not clean staging file ${entry.temporary}: ${error.message}\n`);
503
+ }
504
+ }
505
+ fs.closeSync(lock);
506
+ try { fs.unlinkSync(lockPath); } catch (error) {
507
+ process.stderr.write(`[evolcore] ${committed ? 'Installed; ' : ''}could not remove installer lock ${lockPath}: ${error.message}\n`);
508
+ }
509
+ }
510
+ }
511
+
512
+ function main() {
513
+ // An explicit package root selects provisioning, even if the elevated
514
+ // child inherited npm lifecycle variables. Ordinary postinstall skips it.
515
+ if (!argument('--package-root') && (lifecycleEvent() === 'postinstall' || isGlobalInstall())) {
516
+ runLinuxPostinstall();
517
+ windowsPostinstallNotice();
518
+ return;
519
+ }
520
+ if (process.platform === 'linux' && argument('--mountpoint')) {
521
+ runLinuxPostinstall();
522
+ return;
523
+ }
524
+ if (process.platform !== 'win32') fail('Codex managed hook provisioning is only supported on Windows.');
525
+ if (!argument('--package-root')) fail('--package-root is required.');
526
+ const packageRoot = path.resolve(argument('--package-root'));
527
+ const nodePath = path.resolve(argument('--node-path') || process.execPath);
528
+ const requirements = path.resolve(argument('--requirements')
529
+ || path.join(process.env.ProgramData || path.join(os.homedir(), 'ProgramData'), 'OpenAI', 'Codex', 'requirements.toml'));
530
+ const targetDirectory = path.resolve(argument('--managed-dir') || path.join(path.dirname(requirements), 'EvolCore', 'hooks'));
531
+ const hookPath = path.join(targetDirectory, 'pre-tool-use.mjs');
532
+ const sourceHook = path.join(packageRoot, 'bin', 'codex-managed-hook.mjs');
533
+ for (const file of [sourceHook, nodePath]) {
534
+ if (!fs.statSync(file).isFile()) fail(`Required Hook runtime file was not found: ${file}`);
535
+ }
536
+ if (hasArgument('--repair')) {
537
+ const result = repairManagedHookInstallation({ requirements, managedDir: targetDirectory, packageRoot, nodePath });
538
+ process.stdout.write(`${JSON.stringify(result)}\n`);
539
+ return;
540
+ }
541
+ const previousContent = fs.existsSync(requirements) ? fs.readFileSync(requirements, 'utf8') : '';
542
+ const content = buildManagedRequirements(previousContent, { targetDirectory, nodePath, hookPath });
543
+ const warnings = provisionManagedFiles({
544
+ requirements, hookPath, sourceHook, nodePath, previousContent, content,
545
+ launcher: managedHookLauncher(packageRoot),
546
+ });
547
+ for (const warning of warnings) process.stderr.write(`[evolcore] ${warning}\n`);
548
+ process.stdout.write(`${JSON.stringify({ requirements, managedDir: targetDirectory, hookPath })}\n`);
549
+ }
550
+
551
+ if (process.argv[1] && pathToFileURL(fs.realpathSync(process.argv[1])).href === import.meta.url) {
552
+ try { main(); } catch (error) {
553
+ fail(error instanceof Error ? error.message : String(error));
554
+ }
555
+ }