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,245 +1,327 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs';
3
- import path from 'path';
4
- import { spawn } from 'child_process';
5
-
6
- const MAX_OUTPUT_BYTES = 1024 * 1024;
7
- const EC_EXECUTABLES = new Set(['ec']);
8
- const HOST_PROCESS_EXECUTABLES = new Set(['ps', 'pgrep', 'pidof', 'kill', 'pkill', 'killall']);
9
- const HEAD_EXECUTABLE = ['/usr/bin/head', '/bin/head'].find(candidate => {
10
- try {
11
- return fs.statSync(candidate).isFile();
12
- } catch {
13
- return false;
14
- }
15
- });
16
-
17
- function fail(message) {
18
- process.stderr.write(`ec-safe-output: ${message}\n`);
19
- process.exit(2);
20
- }
21
-
22
- function sameOrDescendant(candidate, parent) {
23
- const relative = path.relative(parent, candidate);
24
- return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
25
- }
26
-
27
- function decodePayload(encoded) {
28
- try {
29
- const value = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
30
- if (!value || value.v !== 1 || !Array.isArray(value.argv) || value.argv.some(arg => typeof arg !== 'string')) return null;
31
- return value;
32
- } catch {
33
- return null;
34
- }
35
- }
36
-
37
- function validateCommand(payload) {
38
- const executable = path.basename(payload.argv[0] ?? '').toLowerCase();
39
- if (payload.kind === 'ec') return EC_EXECUTABLES.has(executable);
40
- if (payload.kind !== 'host-process' || !HOST_PROCESS_EXECUTABLES.has(executable)) return false;
41
- return !payload.argv.some(arg => /\bnode(?:js|\.exe)?\b/i.test(arg));
42
- }
43
-
44
- function validateStdinOnlyHeadArgs(args) {
45
- if (args === undefined) return true;
46
- if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string')) return false;
47
- let optionsEnded = false;
48
- let expectsOptionValue = false;
49
- for (const arg of args) {
50
- if (expectsOptionValue) {
51
- expectsOptionValue = false;
52
- continue;
53
- }
54
- if (optionsEnded) {
55
- if (arg !== '-') return false;
56
- continue;
57
- }
58
- if (arg === '--') {
59
- optionsEnded = true;
60
- continue;
61
- }
62
- if (arg === '-') continue;
63
- if (!arg.startsWith('-')) return false;
64
- if (arg === '-n' || arg === '-c' || arg === '--lines' || arg === '--bytes') {
65
- expectsOptionValue = true;
66
- }
67
- }
68
- return true;
69
- }
70
-
71
- function resolveExecutionPaths(payload) {
72
- if (typeof payload.workspace !== 'string' || typeof payload.cwd !== 'string') fail('invalid workspace');
73
- let workspace;
74
- let cwd;
75
- try {
76
- workspace = fs.realpathSync(payload.workspace);
77
- cwd = fs.realpathSync(payload.cwd);
78
- } catch {
79
- fail('workspace or cwd does not exist');
80
- }
81
- if (!sameOrDescendant(cwd, workspace)) fail('cwd escapes workspace');
82
- return { workspace, cwd };
83
- }
84
-
85
- function resolveManagedTempRoot() {
86
- const raw = typeof process.env.TMPDIR === 'string' ? process.env.TMPDIR.trim() : '';
87
- if (!raw || !path.isAbsolute(raw)) fail('managed TMPDIR is unavailable');
88
- try {
89
- const root = fs.realpathSync(raw);
90
- if (!fs.statSync(root).isDirectory()) fail('managed TMPDIR is not a directory');
91
- return root;
92
- } catch {
93
- fail('managed TMPDIR is unavailable');
94
- }
95
- }
96
-
97
- function openOutputFile(payload, paths) {
98
- if (payload.outputPath === undefined) return undefined;
99
- if (typeof payload.outputPath !== 'string' || !payload.outputPath) fail('output path is invalid');
100
-
101
- const isManagedTempOutput = path.isAbsolute(payload.outputPath);
102
- const outputRoot = isManagedTempOutput ? resolveManagedTempRoot() : paths.workspace;
103
- const target = isManagedTempOutput
104
- ? path.resolve(payload.outputPath)
105
- : path.resolve(paths.cwd, payload.outputPath);
106
- const parent = path.dirname(target);
107
- let realParent;
108
- try {
109
- realParent = fs.realpathSync(parent);
110
- if (!fs.statSync(realParent).isDirectory()) fail('output parent is not a directory');
111
- } catch {
112
- fail('output parent does not exist');
113
- }
114
- const canonicalTarget = path.join(realParent, path.basename(target));
115
- if (!sameOrDescendant(canonicalTarget, outputRoot)) {
116
- fail(isManagedTempOutput ? 'output path escapes managed TMPDIR' : 'output path escapes workspace');
117
- }
118
- if (!isManagedTempOutput) {
119
- const relative = path.relative(paths.workspace, canonicalTarget);
120
- if (relative === '.git' || relative.startsWith(`.git${path.sep}`)) fail('output path may not target Git metadata');
121
- }
122
-
123
- const noFollow = fs.constants.O_NOFOLLOW ?? 0;
124
- try {
125
- const fd = fs.openSync(
126
- canonicalTarget,
127
- fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,
128
- 0o600,
129
- );
130
- if (!fs.fstatSync(fd).isFile()) {
131
- fs.closeSync(fd);
132
- fail('output target is not a regular file');
133
- }
134
- return { fd, target: canonicalTarget };
135
- } catch (error) {
136
- fail(error?.code === 'EEXIST' ? 'output file already exists' : 'unable to create output file');
137
- }
138
- }
139
-
140
- const payload = decodePayload(process.argv[2]);
141
- if (!payload) fail('invalid payload');
142
- if (!validateCommand(payload)) fail('command is not permitted');
143
- if (!validateStdinOnlyHeadArgs(payload.headArgs)) fail('head may only consume stdin');
144
- if (payload.headArgs !== undefined && !HEAD_EXECUTABLE) fail('trusted head executable is unavailable');
145
-
146
- const paths = resolveExecutionPaths(payload);
147
- const output = openOutputFile(payload, paths);
148
- let bytesWritten = 0;
149
- let limitReached = false;
150
- let writeFailed = false;
151
-
152
- function writeLimited(chunk) {
153
- if (limitReached || writeFailed) return;
154
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
155
- const allowed = Math.min(buffer.length, MAX_OUTPUT_BYTES - bytesWritten);
156
- if (allowed <= 0) {
157
- limitReached = true;
158
- return;
159
- }
160
- const slice = buffer.subarray(0, allowed);
161
- try {
162
- if (output) fs.writeSync(output.fd, slice);
163
- else process.stdout.write(slice);
164
- bytesWritten += slice.length;
165
- if (bytesWritten >= MAX_OUTPUT_BYTES) limitReached = true;
166
- } catch {
167
- writeFailed = true;
168
- }
169
- }
170
-
171
- const head = payload.headArgs === undefined
172
- ? undefined
173
- : spawn(HEAD_EXECUTABLE, payload.headArgs, {
174
- cwd: paths.cwd,
175
- env: process.env,
176
- stdio: ['pipe', 'pipe', 'inherit'],
177
- });
178
- if (head) {
179
- head.stdout.on('data', writeLimited);
180
- // Early-exit options such as --help or a small -n/-c close stdin before the
181
- // EC process finishes. Ignore EPIPE and keep draining EC output below.
182
- head.stdin.on('error', () => {});
183
- }
184
-
185
- const child = spawn(payload.argv[0], payload.argv.slice(1), {
186
- cwd: paths.cwd,
187
- env: process.env,
188
- stdio: ['ignore', 'pipe', payload.mergeStderr ? 'pipe' : 'inherit'],
189
- });
190
- const sourceStreams = [child.stdout, ...(payload.mergeStderr ? [child.stderr] : [])];
191
- if (head) {
192
- for (const stream of sourceStreams) {
193
- // The no-op data listener keeps draining the source if head exits early.
194
- stream.on('data', () => {});
195
- stream.pipe(head.stdin, { end: false });
196
- }
197
- } else {
198
- for (const stream of sourceStreams) stream.on('data', writeLimited);
199
- }
200
-
201
- child.once('error', error => {
202
- if (output) {
203
- try { fs.closeSync(output.fd); } catch {}
204
- try { fs.unlinkSync(output.target); } catch {}
205
- }
206
- fail(`unable to start command: ${error.message}`);
207
- });
208
-
209
- let sourceClosed = false;
210
- let sourceCode = 1;
211
- let headClosed = !head;
212
- let headCode = 1;
213
-
214
- function finish() {
215
- if (!sourceClosed || !headClosed) return;
216
- if (output) {
217
- try { fs.closeSync(output.fd); } catch { writeFailed = true; }
218
- }
219
- if (writeFailed) {
220
- if (output) try { fs.unlinkSync(output.target); } catch {}
221
- fail('failed to write command output');
222
- }
223
- if (output) process.stderr.write(`Saved output to ${output.target}\n`);
224
- process.exitCode = head ? headCode : sourceCode;
225
- }
226
-
227
- if (head) {
228
- head.once('error', error => {
229
- writeFailed = true;
230
- process.stderr.write(`ec-safe-output: unable to start head: ${error.message}\n`);
231
- });
232
- head.once('close', code => {
233
- headCode = code ?? 1;
234
- headClosed = true;
235
- for (const stream of sourceStreams) stream.unpipe(head.stdin);
236
- finish();
237
- });
238
- }
239
-
240
- child.once('close', code => {
241
- sourceCode = code ?? 1;
242
- sourceClosed = true;
243
- if (head && !head.stdin.destroyed) head.stdin.end();
244
- finish();
245
- });
1
+ #!/usr/bin/env node
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { spawn } from 'child_process';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
8
+ const EC_EXECUTABLES = new Set(['ec']);
9
+ const HOST_PROCESS_EXECUTABLES = new Set(['ps', 'pgrep', 'pidof', 'kill', 'pkill', 'killall']);
10
+ const IS_WINDOWS = process.platform === 'win32';
11
+ const HELPER_DIR = path.dirname(fileURLToPath(import.meta.url));
12
+ // A rooted POSIX path is not absolute on Windows: Node resolves `/usr/bin/head`
13
+ // onto the current drive as `C:\usr\bin\head`. Keep these fixed candidates as
14
+ // the trusted fast path where they are genuinely absolute, and discover the
15
+ // executable through PATH everywhere else.
16
+ const POSIX_HEAD_CANDIDATES = ['/usr/bin/head', '/bin/head'];
17
+
18
+ function isRegularFile(candidate) {
19
+ try {
20
+ return fs.statSync(candidate).isFile();
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ function pathExtensionCandidates() {
27
+ if (!IS_WINDOWS) return [''];
28
+ const configured = (process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD')
29
+ .split(';')
30
+ .map(value => value.trim())
31
+ .filter(Boolean);
32
+ // The extensionless name is tried first so an explicitly named file wins over
33
+ // a same-named shim; npm publishes both `ec` (sh) and `ec.cmd` on Windows.
34
+ return ['', ...configured];
35
+ }
36
+
37
+ /**
38
+ * Resolve one executable to an absolute path without invoking a shell.
39
+ * `spawn` performs no PATH or PATHEXT lookup on Windows, which is why a bare
40
+ * command name has to be materialized here before the child is started.
41
+ */
42
+ function resolveExecutablePath(executable) {
43
+ if (executable.includes('/') || executable.includes('\\')) {
44
+ return isRegularFile(executable) ? path.resolve(executable) : undefined;
45
+ }
46
+ const entries = (process.env.PATH || '').split(path.delimiter).filter(Boolean);
47
+ for (const entry of entries) {
48
+ for (const extension of pathExtensionCandidates()) {
49
+ const candidate = path.join(entry, `${executable}${extension}`);
50
+ if (isRegularFile(candidate)) return path.resolve(candidate);
51
+ }
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ function resolveHeadExecutable() {
57
+ if (!IS_WINDOWS) {
58
+ const fixed = POSIX_HEAD_CANDIDATES.find(isRegularFile);
59
+ if (fixed) return fixed;
60
+ }
61
+ return resolveExecutablePath('head');
62
+ }
63
+
64
+ const HEAD_EXECUTABLE = resolveHeadExecutable();
65
+
66
+ /**
67
+ * Resolve the concrete process for a validated payload.
68
+ *
69
+ * For `ec`, prefer this package's own Node entrypoint next to the helper. It is
70
+ * the same installation that published this file, needs no PATH lookup, and
71
+ * avoids the Windows batch shim entirely — `CreateProcess` cannot execute a
72
+ * `.cmd` wrapper, so `spawn('ec')` fails with ENOENT there.
73
+ */
74
+ function resolveChildProcessCommand(payload) {
75
+ if (payload.kind === 'ec') {
76
+ const nodeEntrypoint = path.join(HELPER_DIR, 'ec.js');
77
+ // On Windows CreateProcess cannot execute the npm `.cmd` shim reliably,
78
+ // so prefer this package's Node entrypoint. POSIX hosts can resolve the
79
+ // trusted `ec` executable normally; this also preserves caller-provided
80
+ // PATH shims used by isolated runtimes and tests.
81
+ if (IS_WINDOWS && isRegularFile(nodeEntrypoint)) {
82
+ return { file: process.execPath, args: [nodeEntrypoint, ...payload.argv.slice(1)] };
83
+ }
84
+ }
85
+ const resolved = resolveExecutablePath(payload.argv[0]);
86
+ if (!resolved) fail(`unable to resolve executable: ${payload.argv[0]}`);
87
+ // Quoting rules for batch files differ from CreateProcess argument parsing,
88
+ // so a `.cmd`/`.bat` target could execute something other than this argv.
89
+ if (IS_WINDOWS && /\.(?:cmd|bat)$/i.test(resolved)) {
90
+ fail(`refusing to run a batch wrapper: ${resolved}`);
91
+ }
92
+ return { file: resolved, args: payload.argv.slice(1) };
93
+ }
94
+
95
+ function fail(message) {
96
+ process.stderr.write(`ec-safe-output: ${message}\n`);
97
+ process.exit(2);
98
+ }
99
+
100
+ function sameOrDescendant(candidate, parent) {
101
+ const relative = path.relative(parent, candidate);
102
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
103
+ }
104
+
105
+ function decodePayload(encoded) {
106
+ try {
107
+ const value = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
108
+ if (!value || value.v !== 1 || !Array.isArray(value.argv) || value.argv.some(arg => typeof arg !== 'string')) return null;
109
+ return value;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ function validateCommand(payload) {
116
+ const executable = path.basename(payload.argv[0] ?? '').toLowerCase();
117
+ if (payload.kind === 'ec') return EC_EXECUTABLES.has(executable);
118
+ if (payload.kind !== 'host-process' || !HOST_PROCESS_EXECUTABLES.has(executable)) return false;
119
+ return !payload.argv.some(arg => /\bnode(?:js|\.exe)?\b/i.test(arg));
120
+ }
121
+
122
+ function validateStdinOnlyHeadArgs(args) {
123
+ if (args === undefined) return true;
124
+ if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string')) return false;
125
+ let optionsEnded = false;
126
+ let expectsOptionValue = false;
127
+ for (const arg of args) {
128
+ if (expectsOptionValue) {
129
+ expectsOptionValue = false;
130
+ continue;
131
+ }
132
+ if (optionsEnded) {
133
+ if (arg !== '-') return false;
134
+ continue;
135
+ }
136
+ if (arg === '--') {
137
+ optionsEnded = true;
138
+ continue;
139
+ }
140
+ if (arg === '-') continue;
141
+ if (!arg.startsWith('-')) return false;
142
+ if (arg === '-n' || arg === '-c' || arg === '--lines' || arg === '--bytes') {
143
+ expectsOptionValue = true;
144
+ }
145
+ }
146
+ return true;
147
+ }
148
+
149
+ function resolveExecutionPaths(payload) {
150
+ if (typeof payload.workspace !== 'string' || typeof payload.cwd !== 'string') fail('invalid workspace');
151
+ let workspace;
152
+ let cwd;
153
+ try {
154
+ workspace = fs.realpathSync(payload.workspace);
155
+ cwd = fs.realpathSync(payload.cwd);
156
+ } catch {
157
+ fail('workspace or cwd does not exist');
158
+ }
159
+ if (!sameOrDescendant(cwd, workspace)) fail('cwd escapes workspace');
160
+ return { workspace, cwd };
161
+ }
162
+
163
+ function resolveManagedTempRoot() {
164
+ const raw = typeof process.env.TMPDIR === 'string' ? process.env.TMPDIR.trim() : '';
165
+ if (!raw || !path.isAbsolute(raw)) fail('managed TMPDIR is unavailable');
166
+ try {
167
+ const root = fs.realpathSync(raw);
168
+ if (!fs.statSync(root).isDirectory()) fail('managed TMPDIR is not a directory');
169
+ return root;
170
+ } catch {
171
+ fail('managed TMPDIR is unavailable');
172
+ }
173
+ }
174
+
175
+ function openOutputFile(payload, paths) {
176
+ if (payload.outputPath === undefined) return undefined;
177
+ if (typeof payload.outputPath !== 'string' || !payload.outputPath) fail('output path is invalid');
178
+
179
+ const isManagedTempOutput = path.isAbsolute(payload.outputPath);
180
+ const outputRoot = isManagedTempOutput ? resolveManagedTempRoot() : paths.workspace;
181
+ const target = isManagedTempOutput
182
+ ? path.resolve(payload.outputPath)
183
+ : path.resolve(paths.cwd, payload.outputPath);
184
+ const parent = path.dirname(target);
185
+ let realParent;
186
+ try {
187
+ realParent = fs.realpathSync(parent);
188
+ if (!fs.statSync(realParent).isDirectory()) fail('output parent is not a directory');
189
+ } catch {
190
+ fail('output parent does not exist');
191
+ }
192
+ const canonicalTarget = path.join(realParent, path.basename(target));
193
+ if (!sameOrDescendant(canonicalTarget, outputRoot)) {
194
+ fail(isManagedTempOutput ? 'output path escapes managed TMPDIR' : 'output path escapes workspace');
195
+ }
196
+ if (!isManagedTempOutput) {
197
+ const relative = path.relative(paths.workspace, canonicalTarget);
198
+ if (relative === '.git' || relative.startsWith(`.git${path.sep}`)) fail('output path may not target Git metadata');
199
+ }
200
+
201
+ const noFollow = fs.constants.O_NOFOLLOW ?? 0;
202
+ try {
203
+ const fd = fs.openSync(
204
+ canonicalTarget,
205
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow,
206
+ 0o600,
207
+ );
208
+ if (!fs.fstatSync(fd).isFile()) {
209
+ fs.closeSync(fd);
210
+ fail('output target is not a regular file');
211
+ }
212
+ return { fd, target: canonicalTarget };
213
+ } catch (error) {
214
+ fail(error?.code === 'EEXIST' ? 'output file already exists' : 'unable to create output file');
215
+ }
216
+ }
217
+
218
+ const payload = decodePayload(process.argv[2]);
219
+ if (!payload) fail('invalid payload');
220
+ if (!validateCommand(payload)) fail('command is not permitted');
221
+ if (!validateStdinOnlyHeadArgs(payload.headArgs)) fail('head may only consume stdin');
222
+ if (payload.headArgs !== undefined && !HEAD_EXECUTABLE) fail('trusted head executable is unavailable');
223
+
224
+ // Resolve the child executable before anything with a side effect: an
225
+ // unresolvable command must not leave an empty create-only output file behind.
226
+ const childCommand = resolveChildProcessCommand(payload);
227
+ const paths = resolveExecutionPaths(payload);
228
+ const output = openOutputFile(payload, paths);
229
+ let bytesWritten = 0;
230
+ let limitReached = false;
231
+ let writeFailed = false;
232
+
233
+ function writeLimited(chunk) {
234
+ if (limitReached || writeFailed) return;
235
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
236
+ const allowed = Math.min(buffer.length, MAX_OUTPUT_BYTES - bytesWritten);
237
+ if (allowed <= 0) {
238
+ limitReached = true;
239
+ return;
240
+ }
241
+ const slice = buffer.subarray(0, allowed);
242
+ try {
243
+ if (output) fs.writeSync(output.fd, slice);
244
+ else process.stdout.write(slice);
245
+ bytesWritten += slice.length;
246
+ if (bytesWritten >= MAX_OUTPUT_BYTES) limitReached = true;
247
+ } catch {
248
+ writeFailed = true;
249
+ }
250
+ }
251
+
252
+ const head = payload.headArgs === undefined
253
+ ? undefined
254
+ : spawn(HEAD_EXECUTABLE, payload.headArgs, {
255
+ cwd: paths.cwd,
256
+ env: process.env,
257
+ stdio: ['pipe', 'pipe', 'inherit'],
258
+ });
259
+ if (head) {
260
+ head.stdout.on('data', writeLimited);
261
+ // Early-exit options such as --help or a small -n/-c close stdin before the
262
+ // EC process finishes. Ignore EPIPE and keep draining EC output below.
263
+ head.stdin.on('error', () => {});
264
+ }
265
+
266
+ const child = spawn(childCommand.file, childCommand.args, {
267
+ cwd: paths.cwd,
268
+ env: process.env,
269
+ stdio: ['ignore', 'pipe', payload.mergeStderr ? 'pipe' : 'inherit'],
270
+ windowsHide: IS_WINDOWS,
271
+ });
272
+ const sourceStreams = [child.stdout, ...(payload.mergeStderr ? [child.stderr] : [])];
273
+ if (head) {
274
+ for (const stream of sourceStreams) {
275
+ // The no-op data listener keeps draining the source if head exits early.
276
+ stream.on('data', () => {});
277
+ stream.pipe(head.stdin, { end: false });
278
+ }
279
+ } else {
280
+ for (const stream of sourceStreams) stream.on('data', writeLimited);
281
+ }
282
+
283
+ child.once('error', error => {
284
+ if (output) {
285
+ try { fs.closeSync(output.fd); } catch {}
286
+ try { fs.unlinkSync(output.target); } catch {}
287
+ }
288
+ fail(`unable to start command: ${error.message}`);
289
+ });
290
+
291
+ let sourceClosed = false;
292
+ let sourceCode = 1;
293
+ let headClosed = !head;
294
+ let headCode = 1;
295
+
296
+ function finish() {
297
+ if (!sourceClosed || !headClosed) return;
298
+ if (output) {
299
+ try { fs.closeSync(output.fd); } catch { writeFailed = true; }
300
+ }
301
+ if (writeFailed) {
302
+ if (output) try { fs.unlinkSync(output.target); } catch {}
303
+ fail('failed to write command output');
304
+ }
305
+ if (output) process.stderr.write(`Saved output to ${output.target}\n`);
306
+ process.exitCode = head ? headCode : sourceCode;
307
+ }
308
+
309
+ if (head) {
310
+ head.once('error', error => {
311
+ writeFailed = true;
312
+ process.stderr.write(`ec-safe-output: unable to start head: ${error.message}\n`);
313
+ });
314
+ head.once('close', code => {
315
+ headCode = code ?? 1;
316
+ headClosed = true;
317
+ for (const stream of sourceStreams) stream.unpipe(head.stdin);
318
+ finish();
319
+ });
320
+ }
321
+
322
+ child.once('close', code => {
323
+ sourceCode = code ?? 1;
324
+ sourceClosed = true;
325
+ if (head && !head.stdin.destroyed) head.stdin.end();
326
+ finish();
327
+ });
package/bin/ec.js CHANGED
@@ -1,29 +1,29 @@
1
- #!/usr/bin/env node
2
- import fs from 'fs';
3
- import path from 'path';
4
- import { spawnSync } from 'child_process';
5
- import { fileURLToPath, pathToFileURL } from 'url';
6
- import { createRequire } from 'module';
7
-
8
- const require = createRequire(import.meta.url);
9
- const here = path.dirname(fileURLToPath(import.meta.url));
10
- const repoRoot = path.resolve(here, '..');
11
- const srcEntry = path.join(repoRoot, 'src', 'cli', 'index.ts');
12
- const distEntry = path.join(repoRoot, 'dist', 'cli', 'index.js');
13
- const args = process.argv.slice(2);
14
-
15
- if (fs.existsSync(srcEntry)) {
16
- try {
17
- const tsxImport = pathToFileURL(require.resolve('tsx')).href;
18
- const result = spawnSync(process.execPath, ['--import', tsxImport, srcEntry, ...args], { stdio: 'inherit' });
19
- process.exit(result.status ?? (result.error ? 1 : 0));
20
- } catch {}
21
- }
22
-
23
- if (fs.existsSync(distEntry)) {
24
- const result = spawnSync(process.execPath, [distEntry, ...args], { stdio: 'inherit' });
25
- process.exit(result.status ?? (result.error ? 1 : 0));
26
- }
27
-
28
- console.error('ec: missing CLI entrypoint');
29
- process.exit(1);
1
+ #!/usr/bin/env node
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { spawnSync } from 'child_process';
5
+ import { fileURLToPath, pathToFileURL } from 'url';
6
+ import { createRequire } from 'module';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const here = path.dirname(fileURLToPath(import.meta.url));
10
+ const repoRoot = path.resolve(here, '..');
11
+ const srcEntry = path.join(repoRoot, 'src', 'cli', 'index.ts');
12
+ const distEntry = path.join(repoRoot, 'dist', 'cli', 'index.js');
13
+ const args = process.argv.slice(2);
14
+
15
+ if (fs.existsSync(srcEntry)) {
16
+ try {
17
+ const tsxImport = pathToFileURL(require.resolve('tsx')).href;
18
+ const result = spawnSync(process.execPath, ['--import', tsxImport, srcEntry, ...args], { stdio: 'inherit' });
19
+ process.exit(result.status ?? (result.error ? 1 : 0));
20
+ } catch {}
21
+ }
22
+
23
+ if (fs.existsSync(distEntry)) {
24
+ const result = spawnSync(process.execPath, [distEntry, ...args], { stdio: 'inherit' });
25
+ process.exit(result.status ?? (result.error ? 1 : 0));
26
+ }
27
+
28
+ console.error('ec: missing CLI entrypoint');
29
+ process.exit(1);