@2cmddev/2cmd 0.0.0-stage → 0.1.5

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 (93) hide show
  1. package/.opencode/command/2cmd-audit.md +5 -0
  2. package/.opencode/command/2cmd-debt.md +5 -0
  3. package/.opencode/command/2cmd-gain.md +5 -0
  4. package/.opencode/command/2cmd-help.md +5 -0
  5. package/.opencode/command/2cmd-review.md +5 -0
  6. package/.opencode/command/2cmd.md +5 -0
  7. package/.opencode/plugins/2cmd-frontmatter.cjs +63 -0
  8. package/.opencode/plugins/2cmd.mjs +206 -0
  9. package/.opencode/plugins/index.js +4 -0
  10. package/.qoder/rules/2cmd.md +31 -0
  11. package/.qoder-plugin/plugin.json +16 -0
  12. package/.zcode-plugin/plugin.json +13 -0
  13. package/AGENTS.md +33 -0
  14. package/LICENSE +22 -0
  15. package/README.md +133 -2
  16. package/codex/answer.mjs +164 -0
  17. package/codex/data.mjs +31 -0
  18. package/codex/pty.py +80 -0
  19. package/codex/stats.mjs +105 -0
  20. package/codex/terminal.mjs +388 -0
  21. package/dsh/LICENSE +22 -0
  22. package/dsh/board.js +782 -0
  23. package/dsh/build.mjs +47 -0
  24. package/dsh/bundle.json +2104 -0
  25. package/dsh/client.js +877 -0
  26. package/dsh/cordis.patch.yml +3 -0
  27. package/dsh/index.js +185 -0
  28. package/dsh/ledger.js +50 -0
  29. package/dsh/market.js +152 -0
  30. package/dsh/package.json +24 -0
  31. package/dsh/prices.json +1812 -0
  32. package/dsh/settings-text.mjs +520 -0
  33. package/dsh/settings.js +42 -0
  34. package/dsh/stats.js +106 -0
  35. package/dsh/store.js +32 -0
  36. package/dsh/update-prices.mjs +9 -0
  37. package/dsh/update.js +27 -0
  38. package/dsh/voice-helper/Info.plist +13 -0
  39. package/dsh/voice-helper/Transcript.swift +21 -0
  40. package/dsh/voice-helper/build.sh +10 -0
  41. package/dsh/voice-helper/main.swift +70 -0
  42. package/dsh/voice-helper/test.swift +17 -0
  43. package/dsh/voice.js +63 -0
  44. package/hooks/2cmd-activate.js +219 -0
  45. package/hooks/2cmd-antigravity.js +64 -0
  46. package/hooks/2cmd-band-import.js +305 -0
  47. package/hooks/2cmd-config.js +186 -0
  48. package/hooks/2cmd-instructions.js +104 -0
  49. package/hooks/2cmd-map.js +200 -0
  50. package/hooks/2cmd-mode-tracker.js +248 -0
  51. package/hooks/2cmd-runtime.js +245 -0
  52. package/hooks/2cmd-statusline.ps1 +24 -0
  53. package/hooks/2cmd-statusline.sh +18 -0
  54. package/hooks/2cmd-subagent.js +100 -0
  55. package/hooks/band/board.ts +720 -0
  56. package/hooks/band/buttons.ts +60 -0
  57. package/hooks/band/i18n/de.ts +149 -0
  58. package/hooks/band/i18n/en.ts +150 -0
  59. package/hooks/band/i18n/es.ts +149 -0
  60. package/hooks/band/i18n/fr.ts +149 -0
  61. package/hooks/band/i18n/index.ts +42 -0
  62. package/hooks/band/i18n/ja.ts +149 -0
  63. package/hooks/band/i18n/ko.ts +149 -0
  64. package/hooks/band/i18n/pt.ts +149 -0
  65. package/hooks/band/i18n/ru.ts +149 -0
  66. package/hooks/band/i18n/vi.ts +149 -0
  67. package/hooks/band/i18n/zh-Hans.ts +149 -0
  68. package/hooks/band/i18n/zh-Hant.ts +149 -0
  69. package/hooks/band/logo.ts +3 -0
  70. package/hooks/band/metrics.ts +373 -0
  71. package/hooks/band/register.tsx +681 -0
  72. package/hooks/band/types.d.ts +45 -0
  73. package/hooks/band/windows-board.mjs +20 -0
  74. package/hooks/claude-band.json +6 -0
  75. package/hooks/claude-codex-hooks.json +41 -0
  76. package/hooks/codebuddy-hooks.json +20 -0
  77. package/hooks/copilot-hooks.json +21 -0
  78. package/hooks/cursor-hooks.json +17 -0
  79. package/hooks/qoder-hooks.json +26 -0
  80. package/hooks/zcode-hooks.json +26 -0
  81. package/package.json +56 -4
  82. package/pi-extension/index.js +258 -0
  83. package/pi-extension/names.js +19 -0
  84. package/pi-extension/package.json +8 -0
  85. package/scripts/cursor-hooks.js +145 -0
  86. package/scripts/uninstall.js +92 -0
  87. package/skills/2cmd/SKILL.md +55 -0
  88. package/skills/2cmd-audit/SKILL.md +105 -0
  89. package/skills/2cmd-debt/SKILL.md +46 -0
  90. package/skills/2cmd-gain/SKILL.md +53 -0
  91. package/skills/2cmd-help/SKILL.md +87 -0
  92. package/skills/2cmd-review/SKILL.md +143 -0
  93. package/skills/plugin.json +5 -0
@@ -0,0 +1,245 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { createHash } = require('crypto');
5
+ const { getClaudeDir, getQoderDir, normalizeMode } = require('./2cmd-config');
6
+
7
+ const STATE_FILE = '.2cmd-active';
8
+
9
+ // 2cmd: VS Code Copilot never sets COPILOT_PLUGIN_DATA — it only injects
10
+ // CLAUDE_PLUGIN_ROOT, pointed at an install path under .vscode/agent-plugins/
11
+ // (#528). Without this fallback isCopilot was false, so 2cmd assumed
12
+ // native Claude Code and emitted the statusline nudge, which VS Code Copilot
13
+ // doesn't read.
14
+ function isVsCodeCopilotRoot(pluginRoot) {
15
+ if (!pluginRoot) return false;
16
+ return pluginRoot.split(/[\\/]+/).includes('agent-plugins') &&
17
+ pluginRoot.toLowerCase().includes('.vscode');
18
+ }
19
+
20
+ // Antigravity: set by hooks/2cmd-antigravity.js, which runs these hooks for it and turns their output into injectSteps.
21
+ const isAntigravity = process.env.TWOCMD_HOST === 'antigravity';
22
+ const isCopilot = !isAntigravity && (Boolean(process.env.COPILOT_PLUGIN_DATA) ||
23
+ isVsCodeCopilotRoot(process.env.CLAUDE_PLUGIN_ROOT));
24
+ // Antigravity may also set PLUGIN_DATA, so it is ruled out before Codex.
25
+ const isCodex = !isAntigravity && !isCopilot && Boolean(process.env.PLUGIN_DATA);
26
+ const isQoder = !isAntigravity && !isCopilot && !isCodex && Boolean(process.env.QODER_SESSION_ID);
27
+ // CodeBuddy (#854) loads the Claude-format plugin and sets CLAUDE_PLUGIN_ROOT
28
+ // too, but adds CODEBUDDY_PLUGIN_ROOT only for its own plugin hook processes.
29
+ const isCodeBuddy = !isAntigravity && !isCopilot && !isCodex && !isQoder && Boolean(process.env.CODEBUDDY_PLUGIN_ROOT);
30
+ // ZCode also sets the CLAUDE_* aliases, but ZCODE_PLUGIN_ROOT only for plugin hooks.
31
+ // It reads JSON stdout only, so raw Claude-style text would be dropped.
32
+ const isZCode = !isAntigravity && !isCopilot && !isCodex && !isQoder && !isCodeBuddy && Boolean(process.env.ZCODE_PLUGIN_ROOT);
33
+ // Cursor (#817): CURSOR_VERSION is set only in the environment Cursor builds
34
+ // for hook processes (Cursor 3.20.17 assigns it in exactly one place, the hook
35
+ // env builder), so it never leaks into a Claude Code session running inside
36
+ // Cursor's terminal. Cursor also sets it when it runs a Claude-format plugin's
37
+ // hooks next to CLAUDE_PLUGIN_ROOT, and it needs Cursor-shaped JSON either
38
+ // way, so this check comes after the hosts with their own data dirs.
39
+ const isCursor = !isAntigravity && !isCopilot && !isCodex && !isQoder && !isCodeBuddy && !isZCode && Boolean(process.env.CURSOR_VERSION);
40
+
41
+ let stateDir = getClaudeDir();
42
+ if (isCodex) stateDir = process.env.PLUGIN_DATA;
43
+ // COPILOT_PLUGIN_DATA is unset under VS Code Copilot, so fall back to
44
+ // getClaudeDir() rather than building a path from undefined.
45
+ if (isCopilot) stateDir = process.env.COPILOT_PLUGIN_DATA || getClaudeDir();
46
+ if (isQoder) stateDir = getQoderDir();
47
+ // The plugin's own data folder keeps WorkBuddy's modes apart from the CodeBuddy CLI's, which shares ~/.codebuddy.
48
+ if (isCodeBuddy) stateDir = process.env.CODEBUDDY_CONFIG_DIR || process.env.CODEBUDDY_PLUGIN_DATA || path.join(os.homedir(), '.codebuddy');
49
+ if (isCursor) stateDir = path.join(os.homedir(), '.cursor');
50
+ if (isZCode) stateDir = process.env.ZCODE_PLUGIN_DATA || path.join(os.homedir(), '.zcode', '2cmd');
51
+ // Antigravity's App, CLI and IDE share ~/.gemini; its plugin folder is read-only.
52
+ const antigravityData = path.join(os.homedir(), '.gemini', '2cmd');
53
+ if (isAntigravity) stateDir = antigravityData;
54
+
55
+ const statePath = path.join(stateDir, STATE_FILE);
56
+
57
+ // Claude Code hands every hook its project dir, so the live mode is kept per
58
+ // project and concurrent sessions in different repos stop overwriting each other
59
+ // (#662, #809). Hosts without it keep the single shared flag.
60
+ // 2cmd: sessions in the SAME repo still share one mode, and the statusline
61
+ // scripts read the shared flag (last write wins); key by session_id if either matters.
62
+ const projectDir = (process.env.CLAUDE_PROJECT_DIR || '').trim();
63
+ // Replacing separators with '_' aliases e.g. /work/a/b and /work/a_b (#662).
64
+ // Do not read old sanitized keys: they cannot be assigned to one project safely.
65
+ const projectStatePath = projectDir
66
+ ? path.join(stateDir, '2cmd-modes',
67
+ createHash('sha256').update(path.normalize(projectDir)).digest('hex'))
68
+ : null;
69
+
70
+ // Codex gives its hooks no project dir, so its live mode is kept per conversation. The optional desktop panel
71
+ // (codex/) reads these files and leaves its choices in `pending` next to them.
72
+ const codexData = path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), '2cmd');
73
+ // ZCode's optional panel (zcode/) works the same way, from a fixed folder it can find without the plugin's id.
74
+ const zcodeData = path.join(os.homedir(), '.zcode', '2cmd');
75
+ // WorkBuddy's panel (workbuddy/) too, in the app's own folder (~/.workbuddy-ai/2cmd for WorkBuddy AI), found from its
76
+ // config dir or from the plugin data dir inside it (<app>/plugins/data/<plugin>). The CodeBuddy CLI gets the same.
77
+ const pluginData = process.env.CODEBUDDY_PLUGIN_DATA || '';
78
+ const codebuddyHome = process.env.CODEBUDDY_CONFIG_DIR
79
+ || (path.basename(path.dirname(pluginData)) === 'data' && path.basename(path.resolve(pluginData, '..', '..')) === 'plugins' ? path.resolve(pluginData, '..', '..', '..') : stateDir);
80
+ const codebuddyData = path.join(codebuddyHome, '2cmd');
81
+ const sessionData = isCodex ? codexData : isZCode ? zcodeData : isAntigravity ? antigravityData : isCodeBuddy ? codebuddyData : null;
82
+ let session = null; // { file, mode, transcript, cwd }
83
+
84
+ function saveSession(mode) {
85
+ if (!session) return;
86
+ session.mode = mode;
87
+ const { file, ...info } = session;
88
+ const temporary = file + '.' + process.pid + '.tmp';
89
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
90
+ fs.writeFileSync(temporary, JSON.stringify(info), { mode: 0o600 });
91
+ fs.renameSync(temporary, file); // the panel never reads half a file
92
+ }
93
+
94
+ // Call with the hook's input before reading or changing the mode. Other hosts are unaffected.
95
+ function useSession(data) {
96
+ if (!sessionData || !data || typeof data.session_id !== 'string' || !/^[\w-]{1,100}$/.test(data.session_id)) return;
97
+ const file = path.join(sessionData, 'live', data.session_id + '.json');
98
+ let saved = {};
99
+ try { saved = JSON.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (e) { /* a new conversation */ }
100
+ session = { file, mode: saved.mode, transcript: saved.transcript, cwd: saved.cwd };
101
+ // A subagent shares its parent's session_id but has a record of its own.
102
+ if (data.agent_id) return;
103
+ if (typeof data.cwd === 'string') session.cwd = data.cwd;
104
+ if (typeof data.transcript_path === 'string') session.transcript = data.transcript_path;
105
+ if (saved.mode && (session.transcript !== saved.transcript || session.cwd !== saved.cwd)) {
106
+ try { saveSession(saved.mode); } catch (e) { /* only the panel needs it */ }
107
+ }
108
+ }
109
+
110
+ // The mode saved for this conversation, including 'off'. Null when there is none.
111
+ const sessionMode = () => (session && normalizeMode(session.mode)) || null;
112
+
113
+ // The shared flag is still written, for the statusline and project-less hosts.
114
+ function setMode(mode) {
115
+ saveSession(mode);
116
+ for (const file of [projectStatePath, statePath]) {
117
+ if (!file) continue;
118
+ fs.mkdirSync(path.dirname(file), { recursive: true });
119
+ fs.writeFileSync(file, mode);
120
+ }
121
+ }
122
+
123
+ function clearMode() {
124
+ try { saveSession('off'); } catch (e) {}
125
+ for (const file of [projectStatePath, statePath]) {
126
+ if (file) try { fs.unlinkSync(file); } catch (e) {}
127
+ }
128
+ }
129
+
130
+ // Live mode written by activate/mode-tracker. Absent flag = 2cmd off.
131
+ function readMode() {
132
+ if (sessionMode()) return sessionMode() === 'off' ? null : sessionMode();
133
+ try {
134
+ return fs.readFileSync(projectStatePath || statePath, 'utf8').trim() || null;
135
+ } catch (e) {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ // Cursor's always-on project rule (.cursor/rules/2cmd.mdc) already puts the
141
+ // ruleset in front of every prompt and no hook can switch a rule off, so while
142
+ // it is in the workspace the hooks step back instead of injecting a second,
143
+ // possibly contradicting, copy (#817). Cursor hands every hook the workspace
144
+ // root as CURSOR_PROJECT_DIR; project hooks also run from that directory.
145
+ // 2cmd: first workspace root only, a rule in a secondary folder of a
146
+ // multi-root workspace goes undetected.
147
+ function cursorRulePath() {
148
+ const root = process.env.CURSOR_PROJECT_DIR || process.cwd();
149
+ const rule = path.join(root, '.cursor', 'rules', '2cmd.mdc');
150
+ return fs.existsSync(rule) ? rule : null;
151
+ }
152
+
153
+ function cursorRuleNotice(rule) {
154
+ return 'TWOCMD: the always-on Cursor rule ' + rule + ' is active in this workspace and ' +
155
+ 'already carries the 2cmd ruleset, so the 2cmd hooks injected nothing further. ' +
156
+ 'Mode switching (/2cmd hindsight|reuse|pushback|scout|off, "stop 2cmd") is unavailable while ' +
157
+ 'that rule exists. When the user tries to switch or turn off 2cmd, tell them to ' +
158
+ 'delete that rule so hooks.json can manage the level.';
159
+ }
160
+
161
+ // Synchronous: every hook calls process.exit() right after this, and on macOS a pipe
162
+ // write is async, so a pending write died with the process (#1043).
163
+ function writeOut(text) {
164
+ fs.writeSync(1, text);
165
+ }
166
+
167
+ function writeHookOutput(event, mode, context = '') {
168
+ if (isCopilot) {
169
+ // Copilot reads additionalContext on SessionStart; ignores output elsewhere.
170
+ writeOut(JSON.stringify(
171
+ event === 'SessionStart' && context ? { additionalContext: context } : {}));
172
+ return;
173
+ }
174
+ if (isCodex) {
175
+ // No systemMessage: Codex maps it to a yellow `warning:` entry (and de-greens the
176
+ // completed-hook bullet), reading as an error every session (#605). The mode still
177
+ // shows via the additionalContext "hook context:" line — active level when on,
178
+ // "TWOCMD MODE OFF" when off (that path passes context too).
179
+ // 2cmd: if openai/codex#16933 lands and hides additionalContext, restore a
180
+ // non-warning mode signal here.
181
+ const output = {};
182
+ if (context) {
183
+ output.hookSpecificOutput = {
184
+ hookEventName: event,
185
+ additionalContext: context,
186
+ };
187
+ }
188
+ writeOut(JSON.stringify(output));
189
+ return;
190
+ }
191
+ if (isQoder || isCodeBuddy || isZCode || isAntigravity) {
192
+ // Qoder: hookSpecificOutput JSON, same shape as Codex minus systemMessage.
193
+ // UserPromptSubmit additionalContext is injected into the Agent's conversation.
194
+ // CodeBuddy would take raw stdout too, but also echoes it into the chat.
195
+ const output = {};
196
+ if (context) {
197
+ output.hookSpecificOutput = {
198
+ hookEventName: event,
199
+ additionalContext: context,
200
+ };
201
+ }
202
+ writeOut(JSON.stringify(output));
203
+ return;
204
+ }
205
+ if (isCursor) {
206
+ // Cursor parses stdout as JSON and treats empty stdout as "nothing to
207
+ // say"; raw text would be logged as a parse error. sessionStart takes
208
+ // additional_context into the conversation's system context;
209
+ // beforeSubmitPrompt needs continue:true and, in Cursor 3.20.17, injects
210
+ // additional_context into that turn (docs/cursor-hooks.md).
211
+ if (!context) return;
212
+ const output = { additional_context: context };
213
+ if (event === 'UserPromptSubmit') output.continue = true;
214
+ writeOut(JSON.stringify(output));
215
+ return;
216
+ }
217
+ // Native Claude: SessionStart accepts raw stdout, but SubagentStart needs the
218
+ // hookSpecificOutput JSON form or the context is dropped.
219
+ if (event === 'SubagentStart') {
220
+ writeOut(JSON.stringify(
221
+ { hookSpecificOutput: { hookEventName: event, additionalContext: context } }));
222
+ return;
223
+ }
224
+ writeOut(context);
225
+ }
226
+
227
+ module.exports = {
228
+ clearMode,
229
+ codexData,
230
+ sessionData,
231
+ cursorRuleNotice,
232
+ cursorRulePath,
233
+ isCodeBuddy,
234
+ isCodex,
235
+ isCopilot,
236
+ isCursor,
237
+ isAntigravity,
238
+ isQoder,
239
+ isZCode,
240
+ readMode,
241
+ sessionMode,
242
+ setMode,
243
+ useSession,
244
+ writeHookOutput,
245
+ };
@@ -0,0 +1,24 @@
1
+ # CLAUDE_CONFIG_DIR overrides ~/.claude, matching where the hooks write the flag (issue #34)
2
+ $ClaudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
3
+ $Flag = Join-Path $ClaudeDir ".2cmd-active"
4
+ if (-not (Test-Path $Flag)) {
5
+ exit 0
6
+ }
7
+
8
+ $Mode = ""
9
+ try {
10
+ $Mode = (Get-Content $Flag -ErrorAction Stop | Select-Object -First 1).Trim()
11
+ } catch {
12
+ exit 0
13
+ }
14
+
15
+ $Esc = [char]27
16
+ # pushback is the high-intensity mode; flag it amber so it stands out from the
17
+ # default green. The level is still in the text, so color is a redundant cue.
18
+ $Color = if ($Mode -eq "pushback") { "173" } else { "108" }
19
+ if ([string]::IsNullOrEmpty($Mode) -or $Mode -eq "reuse") {
20
+ [Console]::Write("${Esc}[38;5;${Color}m[2CMD]${Esc}[0m")
21
+ } else {
22
+ $Suffix = $Mode.ToUpperInvariant()
23
+ [Console]::Write("${Esc}[38;5;${Color}m[2CMD:$Suffix]${Esc}[0m")
24
+ }
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env bash
2
+ # CLAUDE_CONFIG_DIR overrides ~/.claude, matching where the hooks write the flag (issue #34)
3
+ flag="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.2cmd-active"
4
+ [ -f "$flag" ] || exit 0
5
+
6
+ mode=$(head -n1 "$flag" | tr -d '[:space:]')
7
+
8
+ # pushback is the high-intensity mode; flag it amber so it stands out from the
9
+ # default green at a glance. The level is still in the text, so color is a
10
+ # redundant cue, not the only one.
11
+ color=108
12
+ [ "$mode" = "pushback" ] && color=173
13
+
14
+ if [ -z "$mode" ] || [ "$mode" = "reuse" ]; then
15
+ printf '\033[38;5;%sm[2CMD]\033[0m' "$color"
16
+ else
17
+ printf '\033[38;5;%sm[2CMD:%s]\033[0m' "$color" "$(printf '%s' "$mode" | tr '[:lower:]' '[:upper:]')"
18
+ fi
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ // 2cmd — Claude Code SubagentStart hook
3
+ //
4
+ // SessionStart context is parent-thread only and never reaches subagents, so
5
+ // without this every Task-spawned agent runs 2cmd-unaware (issue #252).
6
+ // When 2cmd mode is active, inject the same ruleset into each subagent.
7
+ //
8
+ // Scoping (opt-in, issue #506): set TWOCMD_SUBAGENT_MATCHER to a regex and
9
+ // the ruleset is injected only into subagents whose agent_type matches. The
10
+ // regex is unanchored and case-insensitive — "explore|general" matches either,
11
+ // "^general$" is exact. Unset means inject into every subagent, as before.
12
+
13
+ const { get2CmdInstructions } = require('./2cmd-instructions');
14
+ const { isCodex, readMode, useSession, writeHookOutput } = require('./2cmd-runtime');
15
+ const vm = require('vm');
16
+
17
+ let mode = readMode();
18
+
19
+ // Absent flag or off → 2cmd isn't active; inject nothing. In Codex the conversation's own mode decides, and
20
+ // it is only known once stdin has been read.
21
+ if (!isCodex && (!mode || mode === 'off')) {
22
+ process.exit(0);
23
+ }
24
+
25
+ function inject() {
26
+ if (!mode || mode === 'off') return;
27
+ try {
28
+ writeHookOutput('SubagentStart', mode, get2CmdInstructions(mode));
29
+ } catch (e) {
30
+ // Silent fail — a stdout error at hook exit must not surface as a hook failure.
31
+ }
32
+ }
33
+
34
+ // A bad regex must never crash the hook; treat it as "no matcher" and inject.
35
+ let matcherRe = null;
36
+ try {
37
+ if (process.env.TWOCMD_SUBAGENT_MATCHER) {
38
+ matcherRe = new RegExp(process.env.TWOCMD_SUBAGENT_MATCHER, 'i');
39
+ }
40
+ } catch (e) {
41
+ matcherRe = null;
42
+ }
43
+
44
+ // No matcher → keep the original synchronous, stdin-independent path. On Windows
45
+ // the PowerShell `if {}` wrapper can swallow the piped JSON so stdin 'end' never
46
+ // fires (#443); the default path must not wait on stdin or it would stall every
47
+ // subagent spawn.
48
+ if (!matcherRe && !isCodex) {
49
+ inject();
50
+ process.exit(0);
51
+ }
52
+
53
+ // Matcher set → read agent_type from stdin and skip only on a definite
54
+ // mismatch. Missing/unparseable agent_type, a stdin error, or the timeout all
55
+ // fail open (inject), so scoping never silently drops the persona.
56
+ let input = '';
57
+ let done = false;
58
+
59
+ function finish() {
60
+ if (done) return;
61
+ done = true;
62
+
63
+ let agentType = '';
64
+ try {
65
+ // Strip UTF-8 BOM some shells prepend when piping (breaks JSON.parse)
66
+ const data = JSON.parse(input.replace(/^\uFEFF/, ''));
67
+ agentType = String(data.agent_type || '').trim();
68
+ useSession(data);
69
+ mode = readMode();
70
+ } catch (e) {
71
+ // Unparseable payload — fall through and inject to be safe.
72
+ }
73
+ // .test() is synchronous, so a backtracking-heavy matcher like (a+)+$ would
74
+ // block the event loop and the fallback timer below could never fire (#658).
75
+ // Run it under a vm timeout; a timeout fails open like every other doubt.
76
+ let matches = true;
77
+ try {
78
+ if (matcherRe && agentType) {
79
+ matches = vm.runInNewContext('re.test(s)', { re: matcherRe, s: agentType }, { timeout: 100 });
80
+ }
81
+ } catch (e) {
82
+ matches = true;
83
+ }
84
+ if (!matches) {
85
+ process.exit(0);
86
+ }
87
+ inject();
88
+ }
89
+
90
+ process.stdin.setEncoding('utf8');
91
+ process.stdin.on('data', chunk => { input += chunk; });
92
+ // Exit on 'end' (not just finish()) so the ref'd fallback timer below can't
93
+ // add its full 1000ms to the normal fast path.
94
+ process.stdin.on('end', () => { finish(); process.exit(0); });
95
+ // Never block the session (#443): recover on stdin error or a short fallback.
96
+ // The fallback stays ref'd: on Windows a stuck ref'd stdin keeps the loop
97
+ // alive and an unref'd timer is never scheduled, so the hook hung to the
98
+ // external watchdog instead of exiting at 1s (#790).
99
+ process.stdin.on('error', () => { finish(); process.exit(0); });
100
+ setTimeout(() => { finish(); process.exit(0); }, 1000);