@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,200 @@
1
+ #!/usr/bin/env node
2
+ // 2cmd — the session's opening snapshot: where the work stands (branch, uncommitted files), how to
3
+ // check it (test and lint commands), the top-level folders, and the codebase map below. It saves the
4
+ // opening `git status`, `ls` and search turns. Only names reach the model, never free text from the
5
+ // repo (commit messages, script bodies), so a cloned repo cannot plant instructions in it.
6
+ //
7
+ // Codebase map: what already exists, so "reuse first" costs no search.
8
+ //
9
+ // Lists the top-level functions, classes and exports of the project's source files, one line
10
+ // per folder, inside a character budget. No model, no dependencies: `git ls-files` (or a short
11
+ // directory walk) plus a regex per language. Tests, generated and vendored files are skipped;
12
+ // shared code (utils, lib, services, components, hooks) is listed first when the budget is tight.
13
+ //
14
+ // 2cmd: regex, not a parser. Misses nested or dynamic definitions; a tree-sitter index is the
15
+ // upgrade if the map ever needs to be exact.
16
+
17
+ const fs = require('fs');
18
+ const os = require('os');
19
+ const path = require('path');
20
+ const { execFileSync } = require('child_process');
21
+
22
+ // In UTF-8 bytes (the name is older), for the whole snapshot. The map gets what the other parts leave.
23
+ const BUDGET = Number(process.env.TWOCMD_MAP_CHARS || 2500);
24
+ const MAX_FILES = 4000;
25
+ const SRC = /\.(py|js|jsx|mjs|cjs|ts|tsx|go|rs|rb|java|kt|php|swift|cs)$/;
26
+ const SKIP_DIR = /(^|\/)(node_modules|\.git|dist|build|out|vendor|venv|\.venv|__pycache__|coverage|\.next|target|migrations|versions|fixtures|tests?|__tests__|spec)(\/|$)/;
27
+ const SKIP_FILE = /(^|\/)(test_[^/]*|[^/]*(_test|\.test|\.spec|\.gen|\.min|\.d)\.[a-z]+)$/;
28
+ const NAME = /^(?:type\s+)?(?:[\w$]+\s+as\s+)?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)$/;
29
+ const SAFE_PATH = /^[\w.@+$()[\]\/-]+$/;
30
+ const SHARED = /(util|helper|lib|common|shared|service|component|hook|core|model|schema|api)/i;
31
+
32
+ const PATTERNS = {
33
+ py: [/^(?:async\s+)?def\s+([A-Za-z]\w*)/gm, /^class\s+([A-Za-z]\w*)/gm],
34
+ js: [/^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*)/gm,
35
+ /^export\s*\{([^}]*)\}/gm],
36
+ go: [/^func\s+(?:\([^)]*\)\s*)?([A-Z]\w*)/gm, /^type\s+([A-Z]\w*)/gm],
37
+ rs: [/^pub\s+(?:async\s+)?(?:fn|struct|enum|trait|type)\s+(\w+)/gm],
38
+ rb: [/^\s*(?:def|class|module)\s+([A-Za-z][\w.]*)/gm],
39
+ jvm: [/^\s*(?:public\s+)?(?:static\s+)?(?:final\s+)?(?:class|interface|enum|record)\s+(\w+)/gm],
40
+ };
41
+ const LANG = { py: 'py', js: 'js', jsx: 'js', mjs: 'js', cjs: 'js', ts: 'js', tsx: 'js', go: 'go', rs: 'rs',
42
+ rb: 'rb', java: 'jvm', kt: 'jvm', swift: 'jvm', cs: 'jvm', php: 'jvm' };
43
+
44
+ function listFiles(root) {
45
+ try {
46
+ // 64 MiB: in repos with many tracked files `git ls-files` overflows Node's 1 MiB
47
+ // default, and the catch below reads that as "not a git repo" and falls back to a
48
+ // walk that ignores .gitignore. The list is capped at MAX_FILES * 5 lines anyway.
49
+ const tracked = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000, maxBuffer: 64 * 1024 * 1024 })
50
+ .split('\n').filter(Boolean).slice(0, MAX_FILES * 5);
51
+ if (tracked.length) return tracked;
52
+ } catch (e) { /* not a git repo: walk below */ }
53
+ {
54
+ // No git, or an untracked folder inside a parent repo (git ls-files is then empty, not an error).
55
+ const out = [];
56
+ (function walk(dir, depth) {
57
+ if (depth > 6 || out.length > MAX_FILES * 5) return;
58
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
59
+ if (ent.name.startsWith('.')) continue;
60
+ const rel = path.relative(root, path.join(dir, ent.name)).replace(/\\/g, '/');
61
+ if (ent.isDirectory()) { if (!SKIP_DIR.test(rel + '/')) walk(path.join(dir, ent.name), depth + 1); }
62
+ else out.push(rel);
63
+ }
64
+ })(root, 0);
65
+ return out;
66
+ }
67
+ }
68
+
69
+ function namesIn(file, text) {
70
+ const lang = LANG[path.extname(file).slice(1)];
71
+ const names = [];
72
+ for (const re of PATTERNS[lang] || []) {
73
+ for (const m of text.matchAll(re)) {
74
+ for (const n of m[1].split(',').map((s) => (s.trim().match(NAME) || [])[1]).filter(Boolean)) {
75
+ if (!n.startsWith('_') && !names.includes(n)) names.push(n);
76
+ }
77
+ }
78
+ }
79
+ return names;
80
+ }
81
+
82
+ const bytes = (s) => Buffer.byteLength(s, 'utf8');
83
+
84
+ function buildMap(root = process.cwd(), budget = BUDGET, all = listFiles(root)) {
85
+ const files = all
86
+ .filter((f) => SAFE_PATH.test(f) && SRC.test(f) && !SKIP_DIR.test(f) && !SKIP_FILE.test(f))
87
+ .slice(0, MAX_FILES)
88
+ .sort((a, b) => (SHARED.test(b) - SHARED.test(a)) || a.localeCompare(b));
89
+ // One line per directory: names are enough to know something exists; grep finds the file.
90
+ const dirs = new Map();
91
+ for (const f of files) {
92
+ let text;
93
+ try {
94
+ if (!fs.lstatSync(path.join(root, f)).isFile()) continue;
95
+ text = fs.readFileSync(path.join(root, f), 'utf8').slice(0, 65536);
96
+ } catch (e) { continue; }
97
+ const names = namesIn(f, text);
98
+ if (!names.length) continue;
99
+ const dir = path.dirname(f) === '.' ? '.' : path.dirname(f);
100
+ dirs.set(dir, [...(dirs.get(dir) || []), names]);
101
+ }
102
+ const lines = [];
103
+ let used = 0;
104
+ let skipped = 0;
105
+ for (const [dir, perFile] of dirs) {
106
+ // The first exports say what a file is; in a folder of many files (a UI kit) one name each.
107
+ const names = [...new Set(perFile.flatMap((n) => n.slice(0, perFile.length > 8 ? 1 : 3)))];
108
+ const line = `${dir}/: ${names.slice(0, 30).join(', ')}${names.length > 30 ? ', ...' : ''}`;
109
+ if (used + bytes(line) > budget) { skipped++; continue; }
110
+ lines.push(line);
111
+ used += bytes(line) + 1;
112
+ }
113
+ if (!lines.length) return '';
114
+ return 'Codebase map (what already exists; reuse it, read a file only when you need its details):\n' +
115
+ lines.join('\n') + (skipped ? `\n(${skipped} more folders not listed)` : '');
116
+ }
117
+
118
+ // "a, b, c (+4 more)" within a byte limit; items arrive in the order they should be kept.
119
+ function list(label, items, limit) {
120
+ const shown = [];
121
+ for (const item of items) {
122
+ const more = items.length - shown.length - 1;
123
+ const line = `${label}${[...shown, item].join(', ')}${more ? ` (+${more} more)` : ''}`;
124
+ if (bytes(line) > limit) break;
125
+ shown.push(item);
126
+ }
127
+ if (!shown.length) return '';
128
+ return `${label}${shown.join(', ')}${shown.length < items.length ? ` (+${items.length - shown.length} more)` : ''}`;
129
+ }
130
+
131
+ // Branch, ahead/behind and uncommitted files from one `git status`. A path git has to quote (spaces,
132
+ // newlines, odd bytes) or that is not a plain name is counted, never shown.
133
+ function gitState(root, limit) {
134
+ let out;
135
+ try {
136
+ out = execFileSync('git', ['status', '--porcelain=v1', '--branch'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1500, maxBuffer: 4 * 1024 * 1024 });
137
+ } catch (e) { return ''; }
138
+ const [head = '', ...rest] = out.split('\n');
139
+ const name = head.replace(/^## (No commits yet on )?/, '').split('...')[0].split(' ')[0];
140
+ const track = (/\[((?:ahead|behind) \d+(?:, behind \d+)?)\]$/.exec(head) || [])[1];
141
+ const branch = SAFE_PATH.test(name) ? name : 'a detached or unusual branch';
142
+ const changed = rest.filter(Boolean).map((l) => [l.slice(0, 2).trim(), l.slice(3).split(' -> ').pop()]);
143
+ const plain = changed.filter(([, f]) => SAFE_PATH.test(f)).map(([code, f]) => `${code} ${f}`);
144
+ const hidden = changed.length - plain.length;
145
+ const where = `Git: on ${branch}${track ? ` (${track})` : ''}; `;
146
+ if (!changed.length) return `${where}nothing uncommitted`;
147
+ return list(`${where}uncommitted: `, plain.concat(hidden ? [`${hidden} other file${hidden > 1 ? 's' : ''}`] : []), limit) || `${where}${changed.length} uncommitted files`;
148
+ }
149
+
150
+ // Test, type and lint commands the project declares at its root. Only the script names: a script's
151
+ // body is free text, and the name is enough to run it.
152
+ function checks(root, limit) {
153
+ const has = (f) => fs.existsSync(path.join(root, f));
154
+ const read = (f) => { try { return fs.readFileSync(path.join(root, f), 'utf8').slice(0, 65536); } catch (e) { return ''; } };
155
+ const out = [];
156
+ try {
157
+ const scripts = Object.keys(JSON.parse(read('package.json')).scripts || {});
158
+ const pm = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lock') || has('bun.lockb') ? 'bun' : 'npm';
159
+ for (const n of scripts) {
160
+ // `bun test` is bun's own runner, not the script, so bun always gets `run`.
161
+ if (/^(test|lint|typecheck|type-check|check|tsc)(:[\w:-]+)?$/.test(n)) out.push(n === 'test' && pm !== 'bun' ? `${pm} test` : `${pm} run ${n}`);
162
+ }
163
+ } catch (e) { /* no package.json, or not JSON */ }
164
+ if (has('pytest.ini') || /\bpytest\b/.test(read('pyproject.toml') + read('setup.cfg') + read('tox.ini'))) out.push('pytest');
165
+ for (const m of read('Makefile').matchAll(/^(test|check|lint)\s*:/gm)) out.push(`make ${m[1]}`);
166
+ if (has('go.mod')) out.push('go test ./...');
167
+ if (has('Cargo.toml')) out.push('cargo test');
168
+ return list('Checks: ', [...new Set(out)], limit);
169
+ }
170
+
171
+ // Top-level folders, the biggest first, without generated and hidden ones.
172
+ const GENERATED = /^(node_modules|dist|build|out|vendor|venv|\.venv|__pycache__|coverage|\.next|target)$/;
173
+ function layout(files, limit) {
174
+ const count = new Map();
175
+ for (const f of files) {
176
+ const top = f.split('/')[0];
177
+ if (f.includes('/') && !top.startsWith('.') && !GENERATED.test(top) && SAFE_PATH.test(top)) count.set(top, (count.get(top) || 0) + 1);
178
+ }
179
+ return list('Top level: ', [...count].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([d, n]) => `${d}/ (${n})`), limit);
180
+ }
181
+
182
+ // The home folder, its parent or a drive root is not a project: walking it is slow and would put the
183
+ // names of private folders in front of the model.
184
+ function notAProject(root) {
185
+ const r = path.resolve(root);
186
+ const home = path.resolve(os.homedir());
187
+ return r === path.parse(r).root || r === home || r === path.dirname(home);
188
+ }
189
+
190
+ function buildSnapshot(root = process.cwd()) {
191
+ if (notAProject(root)) return '';
192
+ const files = listFiles(root);
193
+ const head = [gitState(root, 600), checks(root, 250), layout(files, 400)].filter(Boolean);
194
+ const map = buildMap(root, BUDGET - head.reduce((n, l) => n + bytes(l) + 1, 0), files);
195
+ return [...head, map].filter(Boolean).join('\n');
196
+ }
197
+
198
+ module.exports = { buildMap, buildSnapshot };
199
+
200
+ if (require.main === module) process.stdout.write(buildSnapshot(process.argv[2] || process.cwd()) + '\n');
@@ -0,0 +1,248 @@
1
+ #!/usr/bin/env node
2
+ // 2cmd — UserPromptSubmit hook to track which 2cmd mode is active
3
+ // Inspects user input for /2cmd commands and writes mode to flag file
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { spawn } = require('child_process');
8
+ const { getClaudeDir, getDefaultMode, isDeactivationCommand, normalizeMode, writeDefaultMode } = require('./2cmd-config');
9
+ const {
10
+ clearMode,
11
+ cursorRuleNotice,
12
+ cursorRulePath,
13
+ isAntigravity,
14
+ isCodeBuddy,
15
+ isCodex,
16
+ isCopilot,
17
+ isCursor,
18
+ isQoder,
19
+ isZCode,
20
+ readMode,
21
+ sessionData,
22
+ setMode,
23
+ writeHookOutput,
24
+ useSession,
25
+ } = require('./2cmd-runtime');
26
+ const { get2CmdInstructions } = require('./2cmd-instructions');
27
+
28
+ // 面板上选好、等下条消息生效的档位(见 band/register.tsx)。读到后就删除,只生效一次。
29
+ function takePending(sessionId) {
30
+ if (typeof sessionId !== 'string' || !/^[\w-]+$/.test(sessionId)) return null;
31
+ const file = sessionData ? path.join(sessionData, 'pending', sessionId) : path.join(getClaudeDir(), '2cmd-pending', sessionId);
32
+ try {
33
+ const mode = fs.readFileSync(file, 'utf8').trim();
34
+ fs.unlinkSync(file);
35
+ return normalizeMode(mode);
36
+ } catch (e) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ let input = '';
42
+ let done = false;
43
+
44
+ function finish() {
45
+ if (done) return;
46
+ done = true;
47
+ try {
48
+ // Strip UTF-8 BOM some shells prepend when piping (breaks JSON.parse)
49
+ const data = JSON.parse(input.replace(/^\uFEFF/, ''));
50
+ const prompt = (data.prompt || '').trim().toLowerCase();
51
+ useSession(data);
52
+
53
+ // Cursor with the always-on rule in the workspace: no hook can change or
54
+ // switch off a rule, so answer the command with the notice instead of
55
+ // writing a mode the rule would contradict (#817). Ordinary prompts
56
+ // stay silent as usual.
57
+ if (isCursor && (/^[/@$]2cmd/.test(prompt) || isDeactivationCommand(prompt))) {
58
+ const rule = cursorRulePath();
59
+ if (rule) {
60
+ writeHookOutput('UserPromptSubmit', readMode() || 'off', cursorRuleNotice(rule));
61
+ return;
62
+ }
63
+ }
64
+
65
+ // Match /2cmd commands
66
+ let modeSwitched = false;
67
+ let deactivated = false;
68
+ let defaultNotice = '';
69
+ if (/^[/@$]2cmd/.test(prompt)) {
70
+ const parts = prompt.split(/\s+/);
71
+ const cmd = parts[0].replace(/^[@$]/, '/');
72
+ const arg = parts[1] || '';
73
+
74
+ let mode = null;
75
+ let isReportOnly = false;
76
+
77
+ // /2cmd-review is a one-shot skill, not a session level (#736).
78
+ // Matching it here used to setMode('review'), which latched
79
+ // INDEPENDENT_MODES for the rest of the session.
80
+ if (cmd === '/2cmd' || cmd === '/2cmd:2cmd') {
81
+ // `/2cmd default <mode>` persists the default to config (survives
82
+ // restarts). Plain switches stay session-scoped ("sticks until session
83
+ // end"), so this is the only path that writes config. review is not a
84
+ // valid default (#377), so only runtime levels are accepted.
85
+ if (arg === 'default') {
86
+ const dmode = normalizeMode(parts[2]);
87
+ if (dmode) {
88
+ writeDefaultMode(dmode);
89
+ defaultNotice = 'TWOCMD DEFAULT SET — new sessions start in ' + dmode + '.';
90
+ if (!isQoder) writeHookOutput('UserPromptSubmit', dmode, defaultNotice);
91
+ }
92
+ // Qoder still needs this turn's ruleset: the block below folds the
93
+ // notice into it. mode stays null, so the session level is untouched.
94
+ if (!isQoder) return; // don't fall through to the session-mode switch
95
+ }
96
+ // `/2cmd band [on|off]` shows or hides the band above the Claude Code
97
+ // prompt (hooks/band reads this flag). It outlives the session; absent = shown.
98
+ // Other hosts have no band, so there the word stays an unknown argument.
99
+ if (arg === 'band' && !isCopilot && !isCodex && !isQoder && !isCodeBuddy && !isCursor && !isZCode && !isAntigravity) {
100
+ // `/2cmd band import`: past sessions into the board, in the background, so the prompt
101
+ // is answered right away while the transcripts are read. Detached, it outlives this hook's
102
+ // process.exit below.
103
+ if (parts[2] === 'import') {
104
+ spawn(process.execPath, [path.join(__dirname, '2cmd-band-import.js')], { detached: true, stdio: 'ignore' });
105
+ writeHookOutput('UserPromptSubmit', readMode() || 'off', 'TWOCMD BAND IMPORT: past Claude Code sessions (cost, agent time, tokens) are being added to the board in the background. Open the board in a minute. Confirm in one short line.');
106
+ return;
107
+ }
108
+ const flag = path.join(getClaudeDir(), '.2cmd-band');
109
+ let hidden = false;
110
+ try { hidden = fs.readFileSync(flag, 'utf8').trim() === 'off'; } catch (e) {}
111
+ const show = parts[2] === 'on' ? true : parts[2] === 'off' ? false : hidden;
112
+ if (show) {
113
+ try { fs.unlinkSync(flag); } catch (e) {}
114
+ } else {
115
+ fs.mkdirSync(path.dirname(flag), { recursive: true });
116
+ fs.writeFileSync(flag, 'off');
117
+ }
118
+ writeHookOutput('UserPromptSubmit', readMode() || 'off', show
119
+ ? 'TWOCMD BAND ON: the band shows above the prompt again. The 2cmd level is unchanged. Confirm in one short line.'
120
+ : 'TWOCMD BAND OFF: the band above the prompt is hidden, `/2cmd band` brings it back. The 2cmd level is unchanged. Confirm in one short line.');
121
+ return;
122
+ }
123
+ if (normalizeMode(arg)) mode = normalizeMode(arg);
124
+ else if (arg === '') {
125
+ // Bare /2cmd switches 2cmd on: off → the default level (reuse if
126
+ // the default is off too); already on → keep the level, report it (#639).
127
+ const live = readMode();
128
+ if (live && live !== 'off') {
129
+ isReportOnly = true;
130
+ mode = live;
131
+ } else {
132
+ mode = getDefaultMode() === 'off' ? 'reuse' : getDefaultMode();
133
+ }
134
+ }
135
+ }
136
+
137
+ if (isReportOnly) {
138
+ // On Qoder the ruleset block below already reports; a second write
139
+ // here would put two JSON objects on stdout.
140
+ if (!isQoder) {
141
+ writeHookOutput(
142
+ 'UserPromptSubmit',
143
+ mode,
144
+ 'TWOCMD MODE ACTIVE — level: ' + mode,
145
+ );
146
+ }
147
+ } else if (mode && mode !== 'off') {
148
+ setMode(mode);
149
+ modeSwitched = true;
150
+ // 2cmd: Qoder needs the full ruleset every turn, so when a mode
151
+ // switch happens we fold the confirmation into the ruleset output
152
+ // below (one JSON on stdout) instead of emitting two separate writes.
153
+ if (!isQoder) {
154
+ // Cursor (#817) and Codex have no /2cmd command that would load
155
+ // the skill body for the new level, and the SessionStart ruleset is
156
+ // filtered to the start level, so the tracker delivers that level's
157
+ // ruleset along with the confirmation.
158
+ const header = 'TWOCMD MODE CHANGED — level: ' + mode;
159
+ writeHookOutput(
160
+ 'UserPromptSubmit',
161
+ mode,
162
+ (isCodex || isCursor || isZCode || isAntigravity) ? header + '\n\n' + get2CmdInstructions(mode) : header,
163
+ );
164
+ }
165
+ } else if (mode === 'off') {
166
+ if (isQoder) setMode('off');
167
+ else clearMode();
168
+
169
+ deactivated = true;
170
+ writeHookOutput('UserPromptSubmit', 'off', 'TWOCMD MODE OFF');
171
+ }
172
+ }
173
+
174
+ // Detect deactivation
175
+ if (!modeSwitched && !deactivated && isDeactivationCommand(prompt)) {
176
+ if (isQoder) setMode('off');
177
+ else clearMode();
178
+
179
+ deactivated = true;
180
+ writeHookOutput('UserPromptSubmit', 'off', 'TWOCMD MODE OFF');
181
+ }
182
+
183
+ // 用户输入的切换命令优先,丢弃面板上的选择;其他消息会让选择生效,规则随这条消息一起发送。
184
+ // 查询档位、band、default 等 /2cmd 命令不影响选择。
185
+ if (modeSwitched || deactivated) {
186
+ takePending(data.session_id);
187
+ } else if (!/^[/@$]2cmd(:2cmd)?(\s|$)/.test(prompt)) {
188
+ const pending = takePending(data.session_id);
189
+ if (pending === 'off') {
190
+ clearMode();
191
+ writeHookOutput('UserPromptSubmit', 'off', 'TWOCMD MODE OFF\n\nFrom this message on, do not use any 2Cmd rules loaded earlier in this session.');
192
+ } else if (pending) {
193
+ setMode(pending);
194
+ writeHookOutput('UserPromptSubmit', pending,
195
+ 'TWOCMD MODE CHANGED — level: ' + pending + '\n\nFrom this message on, these rules replace any earlier 2Cmd rules in this session.\n\n' + get2CmdInstructions(pending));
196
+ }
197
+ }
198
+
199
+ // Qoder has no SessionStart event, so UserPromptSubmit does double duty:
200
+ // activate the default mode on first prompt (if no flag exists yet), then
201
+ // inject the ruleset on every prompt. Claude Code/Codex do this in
202
+ // SessionStart via 2cmd-activate.js; Qoder can't, so we do it here.
203
+ // Skip when deactivated — user just turned 2cmd off.
204
+ if (isQoder && !deactivated) {
205
+ let currentMode = readMode();
206
+ if (!currentMode) {
207
+ // First prompt in session — initialize from config/env default
208
+ currentMode = getDefaultMode();
209
+ if (currentMode !== 'off') {
210
+ try { setMode(currentMode); } catch (e) {}
211
+ }
212
+ }
213
+ if (currentMode && currentMode !== 'off') {
214
+ // 2cmd: one JSON per invocation — mode-switch confirmation is
215
+ // folded into the ruleset header so Qoder gets both in one write.
216
+ const header = (defaultNotice ? defaultNotice + '\n\n' : '') + (modeSwitched
217
+ ? 'TWOCMD MODE CHANGED — level: ' + currentMode + '\n\n'
218
+ : '');
219
+ writeHookOutput('UserPromptSubmit', currentMode, header + get2CmdInstructions(currentMode));
220
+ } else if (defaultNotice) {
221
+ writeHookOutput('UserPromptSubmit', currentMode, defaultNotice);
222
+ }
223
+ }
224
+ } catch (e) {
225
+ // Silent fail
226
+ }
227
+ }
228
+
229
+ process.stdin.setEncoding('utf8');
230
+ process.stdin.on('data', chunk => { input += chunk; });
231
+ // Exit on 'end', not just finish(): the fallback timer below must stay ref'd
232
+ // (see #790) so it can actually fire when stdin is stuck, and a ref'd timer
233
+ // would otherwise keep the process alive for its full 1000ms on this normal
234
+ // fast path.
235
+ process.stdin.on('end', () => { finish(); process.exit(0); });
236
+
237
+ // Never hang the session. On Windows, Claude Code runs this hook through a
238
+ // PowerShell `if {}` wrapper that can swallow the piped prompt JSON, so stdin
239
+ // 'end' never fires and the hook blocks forever — freezing the session (#443).
240
+ // On error, or after a short fallback, process whatever arrived (recovering the
241
+ // mode if data came without EOF) and exit. The fallback timer MUST stay ref'd:
242
+ // on Windows a stuck ref'd stdin handle keeps the event loop alive, and an
243
+ // unref'd timer competing with it is never scheduled — so the fallback was
244
+ // dead code in exactly the #443/#790 case it exists for, and the hook hung
245
+ // until Claude Code's external 5s watchdog killed it (#790). Mirrors the
246
+ // best-effort, never-block contract the other lifecycle hooks already follow.
247
+ process.stdin.on('error', () => { finish(); process.exit(0); });
248
+ setTimeout(() => { finish(); process.exit(0); }, 1000);