@2cmddev/2cmd 0.0.0-stage → 0.1.2
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.
- package/.opencode/command/2cmd-audit.md +5 -0
- package/.opencode/command/2cmd-debt.md +5 -0
- package/.opencode/command/2cmd-gain.md +5 -0
- package/.opencode/command/2cmd-help.md +5 -0
- package/.opencode/command/2cmd-review.md +5 -0
- package/.opencode/command/2cmd.md +5 -0
- package/.opencode/plugins/2cmd-frontmatter.cjs +63 -0
- package/.opencode/plugins/2cmd.mjs +206 -0
- package/.opencode/plugins/index.js +4 -0
- package/.qoder/rules/2cmd.md +31 -0
- package/.qoder-plugin/plugin.json +16 -0
- package/.zcode-plugin/plugin.json +13 -0
- package/AGENTS.md +33 -0
- package/LICENSE +22 -0
- package/README.md +133 -2
- package/codex/answer.mjs +164 -0
- package/codex/data.mjs +31 -0
- package/codex/pty.py +80 -0
- package/codex/stats.mjs +105 -0
- package/codex/terminal.mjs +388 -0
- package/dsh/LICENSE +22 -0
- package/dsh/board.js +782 -0
- package/dsh/build.mjs +47 -0
- package/dsh/bundle.json +2104 -0
- package/dsh/client.js +877 -0
- package/dsh/cordis.patch.yml +3 -0
- package/dsh/index.js +185 -0
- package/dsh/ledger.js +50 -0
- package/dsh/market.js +152 -0
- package/dsh/package.json +24 -0
- package/dsh/prices.json +1812 -0
- package/dsh/settings-text.mjs +520 -0
- package/dsh/settings.js +42 -0
- package/dsh/stats.js +106 -0
- package/dsh/store.js +32 -0
- package/dsh/update-prices.mjs +9 -0
- package/dsh/update.js +27 -0
- package/dsh/voice-helper/Info.plist +13 -0
- package/dsh/voice-helper/Transcript.swift +21 -0
- package/dsh/voice-helper/build.sh +10 -0
- package/dsh/voice-helper/main.swift +70 -0
- package/dsh/voice-helper/test.swift +17 -0
- package/dsh/voice.js +63 -0
- package/hooks/2cmd-activate.js +219 -0
- package/hooks/2cmd-antigravity.js +64 -0
- package/hooks/2cmd-band-import.js +305 -0
- package/hooks/2cmd-config.js +186 -0
- package/hooks/2cmd-instructions.js +104 -0
- package/hooks/2cmd-map.js +200 -0
- package/hooks/2cmd-mode-tracker.js +248 -0
- package/hooks/2cmd-runtime.js +245 -0
- package/hooks/2cmd-statusline.ps1 +24 -0
- package/hooks/2cmd-statusline.sh +18 -0
- package/hooks/2cmd-subagent.js +100 -0
- package/hooks/band/board.ts +720 -0
- package/hooks/band/buttons.ts +60 -0
- package/hooks/band/i18n/de.ts +149 -0
- package/hooks/band/i18n/en.ts +150 -0
- package/hooks/band/i18n/es.ts +149 -0
- package/hooks/band/i18n/fr.ts +149 -0
- package/hooks/band/i18n/index.ts +42 -0
- package/hooks/band/i18n/ja.ts +149 -0
- package/hooks/band/i18n/ko.ts +149 -0
- package/hooks/band/i18n/pt.ts +149 -0
- package/hooks/band/i18n/ru.ts +149 -0
- package/hooks/band/i18n/vi.ts +149 -0
- package/hooks/band/i18n/zh-Hans.ts +149 -0
- package/hooks/band/i18n/zh-Hant.ts +149 -0
- package/hooks/band/logo.ts +3 -0
- package/hooks/band/metrics.ts +373 -0
- package/hooks/band/register.tsx +681 -0
- package/hooks/band/types.d.ts +45 -0
- package/hooks/band/windows-board.mjs +20 -0
- package/hooks/claude-band.json +6 -0
- package/hooks/claude-codex-hooks.json +41 -0
- package/hooks/codebuddy-hooks.json +20 -0
- package/hooks/copilot-hooks.json +21 -0
- package/hooks/cursor-hooks.json +17 -0
- package/hooks/qoder-hooks.json +26 -0
- package/hooks/zcode-hooks.json +26 -0
- package/package.json +56 -4
- package/pi-extension/index.js +258 -0
- package/pi-extension/names.js +19 -0
- package/pi-extension/package.json +8 -0
- package/scripts/cursor-hooks.js +145 -0
- package/scripts/uninstall.js +92 -0
- package/skills/2cmd/SKILL.md +55 -0
- package/skills/2cmd-audit/SKILL.md +105 -0
- package/skills/2cmd-debt/SKILL.md +46 -0
- package/skills/2cmd-gain/SKILL.md +53 -0
- package/skills/2cmd-help/SKILL.md +87 -0
- package/skills/2cmd-review/SKILL.md +143 -0
- package/skills/plugin.json +5 -0
package/dsh/stats.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Stats and costs from a DSH session's events.
|
|
2
|
+
import { findPrice } from './market.js'
|
|
3
|
+
|
|
4
|
+
/** Matches provider prefixes (`anthropic/…`), suffixes (`…[1m]`) and dated or `-latest` names to the plain id. */
|
|
5
|
+
export function modelPrice(model) {
|
|
6
|
+
const id = String(model ?? '').trim().toLowerCase().replace(/\[[^\]]*\]$/, '')
|
|
7
|
+
for (const name of [id, id.slice(id.lastIndexOf('/') + 1)]) {
|
|
8
|
+
for (const key of [name, name.replace(/-\d{8}$/, ''), name.replace(/-latest$/, '')]) {
|
|
9
|
+
const price = findPrice(key)
|
|
10
|
+
if (price) return price
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return undefined
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** One request at list price, in USD. A prompt over a tier's size is billed whole at that tier. */
|
|
17
|
+
export function costOf(model, usage) {
|
|
18
|
+
const price = modelPrice(model)
|
|
19
|
+
if (!price) return undefined
|
|
20
|
+
const read = usage.cacheReadTokens ?? 0
|
|
21
|
+
const write = usage.cacheWriteTokens ?? 0
|
|
22
|
+
const prompt = usage.inputTokens + read + write
|
|
23
|
+
const rate = price.tiers?.findLast(tier => prompt > tier.size) ?? price
|
|
24
|
+
return (usage.inputTokens * rate.input + usage.outputTokens * rate.output
|
|
25
|
+
+ read * (rate.cache_read ?? rate.input) + write * (rate.cache_write ?? rate.input)) / 1e6
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Rounded down, so anything short of 100% never shows as 100%.
|
|
29
|
+
const hitRate = (read, input) => Math.floor((read / input) * 1000) / 10
|
|
30
|
+
|
|
31
|
+
/** This session only: subagents run in sessions of their own. Null means unknown, never zero. */
|
|
32
|
+
export function statsOf(events) {
|
|
33
|
+
const turns = new Map()
|
|
34
|
+
const turnOf = n => {
|
|
35
|
+
if (!turns.has(n)) turns.set(n, { cost: 0, read: 0, input: 0, ms: 0, start: undefined, used: false })
|
|
36
|
+
return turns.get(n)
|
|
37
|
+
}
|
|
38
|
+
// Some adapters leave the cache count out when it is zero. Once a model has reported one, a missing count is a miss.
|
|
39
|
+
const reports = new Set(events.filter(({ type, data }) => type === 'assistant/message' && data.usage?.cacheReadTokens !== undefined).map(({ data }) => data.message.source.model))
|
|
40
|
+
let tokens = 0
|
|
41
|
+
let priced = true
|
|
42
|
+
let partial = false
|
|
43
|
+
// Time spent waiting for an answer or an approval is not AI time. Overlapping waits count once.
|
|
44
|
+
const waits = new Set()
|
|
45
|
+
let waitStart = 0
|
|
46
|
+
let waited = 0
|
|
47
|
+
const stopWaiting = (id, time) => {
|
|
48
|
+
if (waits.delete(id) && waits.size === 0) waited += time - waitStart
|
|
49
|
+
}
|
|
50
|
+
const startWaiting = (id, time) => {
|
|
51
|
+
if (waits.size === 0) waitStart = time
|
|
52
|
+
waits.add(id)
|
|
53
|
+
}
|
|
54
|
+
let started = null
|
|
55
|
+
let model = ''
|
|
56
|
+
for (const { type, time, data } of events) {
|
|
57
|
+
if (type === 'turn/start') {
|
|
58
|
+
turnOf(data.turn).start = time
|
|
59
|
+
waits.clear()
|
|
60
|
+
waited = 0
|
|
61
|
+
} else if (type === 'tool/call' && data.name === 'ask_user_question') startWaiting(data.callId, time)
|
|
62
|
+
else if (type === 'tool/result') stopWaiting(data.message.toolCallId, time)
|
|
63
|
+
else if (type === 'approval/asked') startWaiting(`approval:${data.id}`, time)
|
|
64
|
+
else if (type === 'approval/decided') stopWaiting(`approval:${data.id}`, time)
|
|
65
|
+
else if (type === 'turn/end') {
|
|
66
|
+
const turn = turnOf(data.turn)
|
|
67
|
+
if (waits.size > 0) waited += time - waitStart
|
|
68
|
+
waits.clear()
|
|
69
|
+
if (turn.start !== undefined) turn.ms = Math.max(0, time - turn.start - waited)
|
|
70
|
+
} else if (type === 'assistant/message') {
|
|
71
|
+
const turn = turnOf(data.turn)
|
|
72
|
+
turn.used = true
|
|
73
|
+
started ??= turn.start ?? time ?? null
|
|
74
|
+
const { usage } = data
|
|
75
|
+
model = data.message.source.model ?? model
|
|
76
|
+
if (!modelPrice(data.message.source.model)) priced = false
|
|
77
|
+
// A stopped reply reports no usage but may still cost money, so the real total can be higher.
|
|
78
|
+
if (!usage) {
|
|
79
|
+
partial = true
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
turn.cost += costOf(data.message.source.model, usage) ?? 0
|
|
83
|
+
const read = usage.cacheReadTokens ?? 0
|
|
84
|
+
const input = usage.inputTokens + read + (usage.cacheWriteTokens ?? 0)
|
|
85
|
+
tokens += input + usage.outputTokens
|
|
86
|
+
if (reports.has(data.message.source.model)) {
|
|
87
|
+
turn.read += read
|
|
88
|
+
turn.input += input
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const used = [...turns.values()].filter(turn => turn.used)
|
|
93
|
+
const cached = used.filter(turn => turn.input > 0)
|
|
94
|
+
const sum = (list, key) => list.reduce((total, turn) => total + turn[key], 0)
|
|
95
|
+
const n = used.length
|
|
96
|
+
const last = cached.at(-1)
|
|
97
|
+
return {
|
|
98
|
+
turns: n,
|
|
99
|
+
tokens,
|
|
100
|
+
model,
|
|
101
|
+
started,
|
|
102
|
+
cost: n > 0 && priced ? { total: sum(used, 'cost'), last: used.at(-1).cost, avg: sum(used, 'cost') / n, partial } : null,
|
|
103
|
+
cache: last ? { last: hitRate(last.read, last.input), avg: hitRate(sum(cached, 'read'), sum(cached, 'input')), turns: cached.length } : null,
|
|
104
|
+
ms: sum(used, 'ms'),
|
|
105
|
+
}
|
|
106
|
+
}
|
package/dsh/store.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Files in the host's own folder (DSH's, unless TWOCMD_DATA names another): settings, board data, and cached prices and rates.
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
export const pathOf = (...parts) => {
|
|
7
|
+
if (process.env.TWOCMD_DATA) return join(process.env.TWOCMD_DATA, ...parts)
|
|
8
|
+
const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
|
|
9
|
+
return join(home.replace(/^~(?=$|[\\/])/, homedir()), '2cmd', ...parts)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Undefined when the file is missing or broken. */
|
|
13
|
+
export function readJson(file) {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(file, 'utf8'))
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error.code !== 'ENOENT') console.warn(`2cmd: skipped ${file}: ${error.message}`)
|
|
18
|
+
return undefined
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** DSH's 2Cmd settings: the currency and the panel buttons. */
|
|
23
|
+
export const readSettings = () => readJson(pathOf('settings.json')) ?? {}
|
|
24
|
+
export const saveSettings = patch => writeJson(pathOf('settings.json'), { ...readSettings(), ...patch })
|
|
25
|
+
|
|
26
|
+
/** Replaces the file in one step, so a crash never leaves half of it. */
|
|
27
|
+
export function writeJson(file, value) {
|
|
28
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
|
|
29
|
+
const temporary = `${file}.${process.pid}.tmp`
|
|
30
|
+
writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 })
|
|
31
|
+
renameSync(temporary, file)
|
|
32
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Updates the bundled prices before a release: node dsh/update-prices.mjs [saved models.dev api.json]
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { trimPrices } from './market.js'
|
|
4
|
+
|
|
5
|
+
const [file] = process.argv.slice(2)
|
|
6
|
+
const catalogue = file ? JSON.parse(readFileSync(file, 'utf8')) : await (await fetch('https://models.dev/api.json', { signal: AbortSignal.timeout(60_000) })).json()
|
|
7
|
+
const models = trimPrices(catalogue)
|
|
8
|
+
writeFileSync(new URL('prices.json', import.meta.url), JSON.stringify({ source: 'models.dev', updated: new Date().toISOString(), models }, null, 1) + '\n')
|
|
9
|
+
console.log(`prices: ${Object.keys(models).length} models`)
|
package/dsh/update.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Check for updates: the newest version on 2cmd.dev, read only when the person asks. The request carries no data.
|
|
2
|
+
// A newer one is installed again from the site, with the command shown there.
|
|
3
|
+
const VERSION = 'https://2cmd.dev/api/version.json' // written by site/build.js from package.json
|
|
4
|
+
const SEMVER = /^\d+\.\d+\.\d+$/
|
|
5
|
+
|
|
6
|
+
const parts = version => version.split('.').map(Number)
|
|
7
|
+
/** Whether a is a later x.y.z than b. */
|
|
8
|
+
export function isNewer(a, b) {
|
|
9
|
+
const [x, y] = [parts(a), parts(b)]
|
|
10
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i]
|
|
11
|
+
return false
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** 2Cmd's site in one of the panel's language packs. */
|
|
15
|
+
export const siteUrl = pack => `https://2cmd.dev/${{ en: '', 'zh-Hans': 'zh/', 'zh-Hant': 'zh-hant/' }[pack] ?? `${pack}/`}`
|
|
16
|
+
|
|
17
|
+
/** { current, latest, newer }; without latest when the site could not be read. */
|
|
18
|
+
export async function checkUpdate(current, get = fetch) {
|
|
19
|
+
try {
|
|
20
|
+
const response = await get(VERSION, { signal: AbortSignal.timeout(8000), cache: 'no-store' })
|
|
21
|
+
const { version } = response.ok ? await response.json() : {}
|
|
22
|
+
if (typeof version !== 'string' || !SEMVER.test(version) || !SEMVER.test(current)) return { current }
|
|
23
|
+
return { current, latest: version, newer: isNewer(version, current) }
|
|
24
|
+
} catch {
|
|
25
|
+
return { current }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
|
+
<plist version="1.0"><dict>
|
|
4
|
+
<key>CFBundleIdentifier</key><string>io.github.2cmddev.2cmd.voice</string>
|
|
5
|
+
<key>CFBundleName</key><string>2Cmd Voice</string>
|
|
6
|
+
<key>CFBundleExecutable</key><string>TwoCmdVoice</string>
|
|
7
|
+
<key>CFBundlePackageType</key><string>APPL</string>
|
|
8
|
+
<key>CFBundleShortVersionString</key><string>1.0</string>
|
|
9
|
+
<key>CFBundleVersion</key><string>1</string>
|
|
10
|
+
<key>LSMinimumSystemVersion</key><string>13.0</string>
|
|
11
|
+
<key>LSUIElement</key><true/>
|
|
12
|
+
<key>NSSpeechRecognitionUsageDescription</key><string>Turns your voice into text for DeepSeek Harness. It is recognized on this Mac.</string>
|
|
13
|
+
</dict></plist>
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// After a pause, macOS starts over with the next sentence, and its final result has only the last one.
|
|
2
|
+
// So each finished sentence is kept by its start time. A later result that starts at the same time or
|
|
3
|
+
// earlier covers the same speech again, so it replaces what it covers instead of repeating it.
|
|
4
|
+
struct Transcript {
|
|
5
|
+
private var sentences: [(start: Double, text: String)] = []
|
|
6
|
+
|
|
7
|
+
mutating func add(_ text: String, start: Double) {
|
|
8
|
+
if text.isEmpty { return }
|
|
9
|
+
sentences.removeAll { $0.start >= start - 0.01 }
|
|
10
|
+
sentences.append((start, text))
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/// Puts a space only between text that uses spaces, so not between Chinese or Japanese sentences.
|
|
14
|
+
var text: String {
|
|
15
|
+
sentences.reduce(into: "") { result, sentence in
|
|
16
|
+
let wide = { (c: Character?) in (c?.unicodeScalars.first?.value ?? 0) >= 0x2E80 }
|
|
17
|
+
if !result.isEmpty, !wide(result.last), !wide(sentence.text.first) { result += " " }
|
|
18
|
+
result += sentence.text
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Builds TwoCmdVoice.app in the given folder: dsh/voice-helper/build.sh <folder>
|
|
3
|
+
# The ad-hoc signature is for this Mac only. Sharing the app needs an Apple Developer ID signature and notarization.
|
|
4
|
+
set -eu
|
|
5
|
+
here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
6
|
+
app="$1/TwoCmdVoice.app"
|
|
7
|
+
mkdir -p "$app/Contents/MacOS"
|
|
8
|
+
cp "$here/Info.plist" "$app/Contents/Info.plist"
|
|
9
|
+
xcrun swiftc -O -swift-version 5 -target "$(uname -m)-apple-macos13.0" "$here/main.swift" "$here/Transcript.swift" -o "$app/Contents/MacOS/TwoCmdVoice"
|
|
10
|
+
codesign --force --sign - "$app"
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Turns one recording into text with macOS speech recognition, on this Mac only. DSH's own app does not declare
|
|
2
|
+
// the speech permission, so this small app asks for it instead.
|
|
3
|
+
// TwoCmdVoice <folder> <language> reads <folder>/audio.wav, writes <folder>/result.json
|
|
4
|
+
// TwoCmdVoice --status <folder> <language> never shows a permission prompt
|
|
5
|
+
import Foundation
|
|
6
|
+
import Speech
|
|
7
|
+
|
|
8
|
+
var args = Array(CommandLine.arguments.dropFirst())
|
|
9
|
+
let statusOnly = args.first == "--status"
|
|
10
|
+
if statusOnly { args.removeFirst() }
|
|
11
|
+
guard args.count == 2 else { exit(2) }
|
|
12
|
+
let folder = URL(fileURLWithPath: args[0], isDirectory: true)
|
|
13
|
+
let audio = folder.appendingPathComponent("audio.wav")
|
|
14
|
+
|
|
15
|
+
func finish(_ result: [String: Any]) -> Never {
|
|
16
|
+
if let data = try? JSONSerialization.data(withJSONObject: result) {
|
|
17
|
+
try? data.write(to: folder.appendingPathComponent("result.json"), options: .atomic)
|
|
18
|
+
}
|
|
19
|
+
exit(0)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let language = args[1] == "auto" ? Locale.preferredLanguages.first ?? "en-US" : args[1]
|
|
23
|
+
let regions = ["zh": "zh-CN", "en": "en-US", "ja": "ja-JP", "ko": "ko-KR", "es": "es-ES", "fr": "fr-FR", "de": "de-DE", "pt": "pt-BR", "ru": "ru-RU", "vi": "vi-VN"]
|
|
24
|
+
// "zh-Hans-US" and the like are not speech languages, so try the language and region, then the language alone.
|
|
25
|
+
let parts = Locale(identifier: language)
|
|
26
|
+
let code = parts.language.languageCode?.identifier ?? "en"
|
|
27
|
+
let script = parts.language.script?.identifier
|
|
28
|
+
let wanted = [language, code == "zh" && script == "Hant" ? "zh-TW" : nil, parts.region.map { "\(code)-\($0.identifier)" }, regions[code]].compactMap { $0 }
|
|
29
|
+
let known = Set(SFSpeechRecognizer.supportedLocales().map { $0.identifier.replacingOccurrences(of: "_", with: "-") })
|
|
30
|
+
let locale = wanted.first(where: known.contains) ?? language
|
|
31
|
+
|
|
32
|
+
let recognizer = known.contains(locale) ? SFSpeechRecognizer(locale: Locale(identifier: locale)) : nil
|
|
33
|
+
let onDevice = recognizer?.supportsOnDeviceRecognition ?? false
|
|
34
|
+
if statusOnly {
|
|
35
|
+
finish(["authorization": SFSpeechRecognizer.authorizationStatus().rawValue, "locale": locale, "onDevice": onDevice])
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// DSH deletes the folder to cancel.
|
|
39
|
+
let watch = DispatchSource.makeTimerSource(queue: .main)
|
|
40
|
+
watch.schedule(deadline: .now() + 0.2, repeating: 0.2)
|
|
41
|
+
watch.setEventHandler { if !FileManager.default.fileExists(atPath: audio.path) { exit(0) } }
|
|
42
|
+
watch.resume()
|
|
43
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 115) { finish(["error": "timeout"]) }
|
|
44
|
+
|
|
45
|
+
var task: SFSpeechRecognitionTask?
|
|
46
|
+
var transcript = Transcript()
|
|
47
|
+
SFSpeechRecognizer.requestAuthorization { status in
|
|
48
|
+
DispatchQueue.main.async {
|
|
49
|
+
guard status == .authorized else { finish(["error": "permission"]) }
|
|
50
|
+
// Never falls back to Apple's servers.
|
|
51
|
+
guard let recognizer, onDevice else { finish(["error": "language"]) }
|
|
52
|
+
let request = SFSpeechURLRecognitionRequest(url: audio)
|
|
53
|
+
request.requiresOnDeviceRecognition = true
|
|
54
|
+
request.shouldReportPartialResults = true // sentences before a pause only arrive this way
|
|
55
|
+
request.addsPunctuation = true
|
|
56
|
+
request.taskHint = .dictation
|
|
57
|
+
task = recognizer.recognitionTask(with: request) { result, error in
|
|
58
|
+
// Only finished sentences have this metadata and real start times.
|
|
59
|
+
if let result, result.isFinal || result.speechRecognitionMetadata != nil {
|
|
60
|
+
let best = result.bestTranscription
|
|
61
|
+
transcript.add(best.formattedString, start: best.segments.first?.timestamp ?? 0)
|
|
62
|
+
if result.isFinal { finish(["text": transcript.text]) }
|
|
63
|
+
}
|
|
64
|
+
guard let error = error as NSError? else { return }
|
|
65
|
+
if error.domain == "kAFAssistantErrorDomain" && error.code == 1110 { finish(["text": transcript.text]) } // no more speech heard
|
|
66
|
+
finish(["error": error.domain == "kLSRErrorDomain" && error.code == 201 ? "dictation" : "failed"])
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
RunLoop.main.run()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Checks Transcript.swift without speech recognition or a permission prompt. tests/dsh.test.js runs it on a Mac.
|
|
2
|
+
@main struct Test {
|
|
3
|
+
static func join(_ sentences: (Double, String)...) -> String {
|
|
4
|
+
var transcript = Transcript()
|
|
5
|
+
for (start, text) in sentences { transcript.add(text, start: start) }
|
|
6
|
+
return transcript.text
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
static func main() {
|
|
10
|
+
precondition(join() == "")
|
|
11
|
+
precondition(join((0.15, "第一句。"), (5.04, "第二句。")) == "第一句。第二句。", "a pause keeps the first sentence")
|
|
12
|
+
precondition(join((0.15, "第一句。"), (0.15, "第一句。第二句。")) == "第一句。第二句。", "a result for everything does not repeat it")
|
|
13
|
+
precondition(join((0.15, "one"), (5, "two"), (5, "two!")) == "one two!", "a repeated last sentence is replaced")
|
|
14
|
+
precondition(join((0.15, "第一句。"), (9, "")) == "第一句。", "an empty last result keeps the rest")
|
|
15
|
+
print("ok")
|
|
16
|
+
}
|
|
17
|
+
}
|
package/dsh/voice.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Adds macOS speech recognition to DSH's own voice service, next to its built-in recognizer.
|
|
2
|
+
// Appears only when the helper app (voice-helper/) is installed. Recordings stay on this Mac.
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
import { existsSync } from 'node:fs'
|
|
5
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { pathOf, readJson, writeJson } from './store.js'
|
|
9
|
+
|
|
10
|
+
export const SYSTEM = '2cmd-macos'
|
|
11
|
+
const LANGUAGES = ['auto', 'zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'pt', 'ru', 'vi']
|
|
12
|
+
const TIMEOUT = 120_000
|
|
13
|
+
|
|
14
|
+
// `open` starts the helper as its own app, so macOS uses the helper's speech permission, not DSH's.
|
|
15
|
+
function launch(app, args) {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
const child = spawn('/usr/bin/open', ['-W', '-n', '-g', app, '--args', ...args], { stdio: 'ignore' })
|
|
18
|
+
child.once('error', reject)
|
|
19
|
+
child.once('exit', code => (code === 0 ? resolve() : reject(new Error('2cmd-voice:failed'))))
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `start` is replaceable for tests. */
|
|
24
|
+
export function systemProvider(app, start = launch) {
|
|
25
|
+
return {
|
|
26
|
+
info: { id: SYSTEM, name: 'macOS', location: 'host-local', languages: LANGUAGES },
|
|
27
|
+
async transcribe({ audio, language }, signal) {
|
|
28
|
+
signal.throwIfAborted()
|
|
29
|
+
const folder = await mkdtemp(join(tmpdir(), '2cmd-voice-'))
|
|
30
|
+
const remove = () => rm(folder, { recursive: true, force: true })
|
|
31
|
+
// The helper quits when its recording is gone.
|
|
32
|
+
const limit = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT)])
|
|
33
|
+
const stop = () => { void remove().catch(() => {}) }
|
|
34
|
+
limit.addEventListener('abort', stop, { once: true })
|
|
35
|
+
const begun = performance.now()
|
|
36
|
+
try {
|
|
37
|
+
await writeFile(join(folder, 'audio.wav'), audio, { mode: 0o600 })
|
|
38
|
+
limit.throwIfAborted()
|
|
39
|
+
await start(app, [folder, language])
|
|
40
|
+
limit.throwIfAborted()
|
|
41
|
+
const result = JSON.parse(await readFile(join(folder, 'result.json'), 'utf8').catch(() => '{"error":"failed"}'))
|
|
42
|
+
if (typeof result.text !== 'string') throw new Error(`2cmd-voice:${result.error ?? 'failed'}`)
|
|
43
|
+
// DSH sends 16 kHz mono PCM16 after a 44-byte header.
|
|
44
|
+
return { text: result.text.trim(), audioSeconds: Math.max(0, audio.byteLength - 44) / 32000, inferenceSeconds: (performance.now() - begun) / 1000 }
|
|
45
|
+
} finally {
|
|
46
|
+
limit.removeEventListener('abort', stop)
|
|
47
|
+
await remove()
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function addSystemVoice(ctx) {
|
|
54
|
+
const app = pathOf('voice', 'TwoCmdVoice.app')
|
|
55
|
+
if (process.platform !== 'darwin' || !existsSync(app)) return
|
|
56
|
+
ctx.effect(() => ctx.speechToText.register(systemProvider(app)), '2cmd: macOS voice')
|
|
57
|
+
// System voice becomes the default once. After that the user's own choice stands.
|
|
58
|
+
const marker = pathOf('voice', 'default.json')
|
|
59
|
+
if (readJson(marker)?.done) return
|
|
60
|
+
ctx.speechToText.configure({ providerId: SYSTEM, language: 'auto' })
|
|
61
|
+
.then(() => writeJson(marker, { done: true }))
|
|
62
|
+
.catch(error => console.warn(`2cmd: could not make system voice the default: ${error.message}`))
|
|
63
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 2cmd — Claude Code SessionStart activation hook (also Codex, Copilot,
|
|
3
|
+
// Grok, CodeBuddy and Cursor sessionStart)
|
|
4
|
+
//
|
|
5
|
+
// Runs on every session start:
|
|
6
|
+
// 1. Writes flag file at $CLAUDE_CONFIG_DIR/.2cmd-active (defaults to ~/.claude; statusline reads this)
|
|
7
|
+
// 2. Emits 2cmd ruleset as hidden SessionStart context
|
|
8
|
+
// 3. Detects missing statusline config and emits setup nudge
|
|
9
|
+
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const { execFileSync } = require('child_process');
|
|
13
|
+
const { getConfigDir, getDefaultMode, getClaudeDir, isShellSafe } = require('./2cmd-config');
|
|
14
|
+
const { get2CmdInstructions } = require('./2cmd-instructions');
|
|
15
|
+
const {
|
|
16
|
+
clearMode,
|
|
17
|
+
cursorRuleNotice,
|
|
18
|
+
cursorRulePath,
|
|
19
|
+
isAntigravity,
|
|
20
|
+
isCodeBuddy,
|
|
21
|
+
isCodex,
|
|
22
|
+
isCopilot,
|
|
23
|
+
isCursor,
|
|
24
|
+
isZCode,
|
|
25
|
+
readMode,
|
|
26
|
+
sessionMode,
|
|
27
|
+
setMode,
|
|
28
|
+
useSession,
|
|
29
|
+
writeHookOutput,
|
|
30
|
+
} = require('./2cmd-runtime');
|
|
31
|
+
|
|
32
|
+
const claudeDir = getClaudeDir();
|
|
33
|
+
const settingsPath = path.join(claudeDir, 'settings.json');
|
|
34
|
+
|
|
35
|
+
function activate(mode) {
|
|
36
|
+
// "off" mode — skip activation entirely, don't write flag or emit rules
|
|
37
|
+
if (mode === 'off') {
|
|
38
|
+
clearMode();
|
|
39
|
+
process.exit(0);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Cursor with the always-on rule in the workspace: the rule already carries the
|
|
43
|
+
// ruleset and would contradict any other level, so leave the flag alone and
|
|
44
|
+
// hand the model a one-line notice instead of a second copy (#817).
|
|
45
|
+
if (isCursor) {
|
|
46
|
+
const rule = cursorRulePath();
|
|
47
|
+
if (rule) {
|
|
48
|
+
try {
|
|
49
|
+
writeHookOutput('SessionStart', mode, cursorRuleNotice(rule));
|
|
50
|
+
} catch (e) {
|
|
51
|
+
// Silent fail — stdout closed/EPIPE at hook exit must not surface as a hook failure
|
|
52
|
+
}
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 1. Write flag file
|
|
58
|
+
try {
|
|
59
|
+
setMode(mode);
|
|
60
|
+
} catch (e) {
|
|
61
|
+
// Silent fail -- flag is best-effort, don't block the hook
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 2. Emit the 2cmd ruleset, filtered to the active intensity level.
|
|
65
|
+
let output = get2CmdInstructions(mode);
|
|
66
|
+
|
|
67
|
+
// 2a. The person's own additions, kept outside the plugin folder so an update never overwrites them.
|
|
68
|
+
// shortcut: 16 KB at most, so a stray big file cannot flood the context.
|
|
69
|
+
try {
|
|
70
|
+
const own = fs.readFileSync(path.join(getConfigDir(), 'rules.md'), 'utf8').slice(0, 16384).trim();
|
|
71
|
+
if (own) output += '\n\n## Your own rules (2cmd/rules.md, next to config.json)\n\n' + own;
|
|
72
|
+
} catch (e) { /* none */ }
|
|
73
|
+
|
|
74
|
+
// 2b. Opening snapshot (2cmd-map.js): branch and uncommitted files, check commands, top-level folders
|
|
75
|
+
// and the codebase map, so the opening `git status`, `ls` and searches are not needed. Fail open: the map
|
|
76
|
+
// gets 3 s, well inside the 15 s hook limit, so a stalled map never costs the rules (#1079, #1157).
|
|
77
|
+
// shortcut: a map slower than 3 s is still dropped; a cached per-repo map would lift that if it shows up.
|
|
78
|
+
// hindsight leaves the work alone, and the map tells the AI to reuse code, so it gets no map.
|
|
79
|
+
if (mode !== 'review' && mode !== 'hindsight' && process.env.TWOCMD_MAP !== '0') try {
|
|
80
|
+
const map = execFileSync(process.execPath, [path.join(__dirname, '2cmd-map.js')], {
|
|
81
|
+
encoding: 'utf8', timeout: 3000, maxBuffer: 64 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
|
|
82
|
+
}).trimEnd();
|
|
83
|
+
if (map) output += '\n\n' + map;
|
|
84
|
+
} catch (e) { /* no map */ }
|
|
85
|
+
|
|
86
|
+
// 3. Detect missing statusline config — nudge Claude to help set it up
|
|
87
|
+
if (!isCodex && !isCopilot && !isCursor && !isCodeBuddy && !isZCode && !isAntigravity) try {
|
|
88
|
+
const isWindows = process.platform === 'win32';
|
|
89
|
+
let statusCommand = null;
|
|
90
|
+
if (fs.existsSync(settingsPath)) {
|
|
91
|
+
// Strip UTF-8 BOM some editors prepend on Windows (breaks JSON.parse)
|
|
92
|
+
const raw = fs.readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, '');
|
|
93
|
+
const settings = JSON.parse(raw);
|
|
94
|
+
if (settings.statusLine) {
|
|
95
|
+
statusCommand = String(settings.statusLine.command || '');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A statusLine already set up before #1032 can still run a script from a
|
|
100
|
+
// plugin version that has since been deleted. Only absolute paths are checked,
|
|
101
|
+
// so ~ or $HOME forms are never mistaken for missing files.
|
|
102
|
+
const ref = statusCommand &&
|
|
103
|
+
statusCommand.match(/"([^"]*2cmd-statusline\.(?:sh|ps1))"|(\S*2cmd-statusline\.(?:sh|ps1))/);
|
|
104
|
+
const refPath = ref ? (ref[1] || ref[2]) : null;
|
|
105
|
+
// isShellSafe keeps quotes, newlines and shell metacharacters from
|
|
106
|
+
// settings.json out of the model context.
|
|
107
|
+
// On Windows only drive-letter or UNC paths count: a Git Bash path such as
|
|
108
|
+
// /c/Users/... is absolute to Node but does not resolve, so it would be
|
|
109
|
+
// flagged as broken while it works.
|
|
110
|
+
const checkable = refPath && isShellSafe(refPath) && path.isAbsolute(refPath) &&
|
|
111
|
+
(!isWindows || /^([A-Za-z]:[\\/]|\\\\)/.test(refPath));
|
|
112
|
+
const stalePath = checkable && !fs.existsSync(refPath) ? refPath : null;
|
|
113
|
+
|
|
114
|
+
// The plugin root is a versioned cache dir (.../2cmd/4.12.0/) that Claude
|
|
115
|
+
// Code deletes on update, so a statusLine pointing into it goes blank after the
|
|
116
|
+
// next update (#1032). Point it at a copy in the config dir instead. A statusLine
|
|
117
|
+
// that already runs 2cmd keeps its script type, so its copy stays fresh.
|
|
118
|
+
const usePs1 = refPath ? refPath.endsWith('.ps1') : isWindows;
|
|
119
|
+
const scriptName = usePs1 ? '2cmd-statusline.ps1' : '2cmd-statusline.sh';
|
|
120
|
+
const scriptPath = path.join(claudeDir, scriptName);
|
|
121
|
+
|
|
122
|
+
// Nudge at most once — the flag file marks that the user has already seen
|
|
123
|
+
// (and implicitly declined) the statusline setup offer. Repeating it every
|
|
124
|
+
// session start turns a helpful hint into a nag. A broken path is nudged once
|
|
125
|
+
// per path: the flag records it.
|
|
126
|
+
const nudgeFlagPath = path.join(claudeDir, '.2cmd-statusline-nudged');
|
|
127
|
+
let nudged = null;
|
|
128
|
+
try { nudged = fs.readFileSync(nudgeFlagPath, 'utf8'); } catch (e) { /* not nudged yet */ }
|
|
129
|
+
const nudge = stalePath ? nudged !== stalePath : statusCommand === null && nudged === null;
|
|
130
|
+
|
|
131
|
+
// Refresh the copy every session so script fixes ship with plugin updates.
|
|
132
|
+
// Copy to a new temp file, then rename: the rename replaces a symlink at
|
|
133
|
+
// scriptPath instead of writing through it, and a concurrent session never
|
|
134
|
+
// runs a half-written script.
|
|
135
|
+
if (nudge || fs.existsSync(scriptPath)) {
|
|
136
|
+
const tmpPath = scriptPath + '.' + process.pid + '.tmp';
|
|
137
|
+
try {
|
|
138
|
+
fs.copyFileSync(path.join(__dirname, scriptName), tmpPath, fs.constants.COPYFILE_EXCL);
|
|
139
|
+
fs.chmodSync(tmpPath, 0o644);
|
|
140
|
+
fs.renameSync(tmpPath, scriptPath);
|
|
141
|
+
} finally {
|
|
142
|
+
try { fs.unlinkSync(tmpPath); } catch (e) { /* renamed */ }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (nudge) {
|
|
147
|
+
try { fs.writeFileSync(nudgeFlagPath, stalePath || ''); } catch (e) { /* best-effort */ }
|
|
148
|
+
if (stalePath) {
|
|
149
|
+
output += "\n\n" +
|
|
150
|
+
"STATUSLINE BROKEN: The statusLine in " + settingsPath + " runs " + stalePath +
|
|
151
|
+
", which no longer exists (the 2cmd plugin was updated and its old version removed), " +
|
|
152
|
+
"so the 2cmd badge is blank. Replace that path with " + scriptPath + ", which survives updates, " +
|
|
153
|
+
"quoting it for your shell. Keep the rest of the command. " +
|
|
154
|
+
"Proactively offer to fix this for the user on first interaction.";
|
|
155
|
+
} else if (isShellSafe(scriptPath)) {
|
|
156
|
+
const command = isWindows
|
|
157
|
+
? `powershell -ExecutionPolicy Bypass -File "${scriptPath}"`
|
|
158
|
+
: `bash "${scriptPath}"`;
|
|
159
|
+
const statusLineSnippet =
|
|
160
|
+
'"statusLine": { "type": "command", "command": ' + JSON.stringify(command) + ' }';
|
|
161
|
+
output += "\n\n" +
|
|
162
|
+
"STATUSLINE SETUP NEEDED: The 2cmd plugin includes a statusline badge showing active mode " +
|
|
163
|
+
"(e.g. [2CMD], [2CMD:PUSHBACK]). It is not configured yet. " +
|
|
164
|
+
"To enable, add this to " + settingsPath + ": " +
|
|
165
|
+
statusLineSnippet + " " +
|
|
166
|
+
"Proactively offer to set this up for the user on first interaction.";
|
|
167
|
+
} else {
|
|
168
|
+
// 2cmd: config dir path has shell metacharacters; don't embed it in a
|
|
169
|
+
// command snippet; have the agent wire it up by hand instead.
|
|
170
|
+
output += "\n\n" +
|
|
171
|
+
"STATUSLINE SETUP NEEDED: The 2cmd plugin includes a statusline badge showing active mode. " +
|
|
172
|
+
"Its path contains characters unsafe to embed in a shell command, so configure it manually: " +
|
|
173
|
+
"add a statusLine command of type \"command\" that runs " + scriptName +
|
|
174
|
+
" from " + claudeDir + " to " + settingsPath + ", quoting/escaping the path for your shell. " +
|
|
175
|
+
"Proactively offer to set this up for the user on first interaction.";
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
} catch (e) {
|
|
179
|
+
// Silent fail — don't block session start over statusline detection
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
try {
|
|
183
|
+
writeHookOutput('SessionStart', mode, output);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
// Silent fail — stdout closed/EPIPE at hook exit must not surface as a hook failure
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Compaction re-runs SessionStart inside the same conversation, so it keeps the
|
|
190
|
+
// live level (or stays off after "stop 2cmd") instead of resetting to the
|
|
191
|
+
// default. Claude Code and Codex pass the trigger as `source` on stdin; reading
|
|
192
|
+
// it there keeps the hook entry, and the trust Codex gave it, unchanged.
|
|
193
|
+
let input = '';
|
|
194
|
+
let done = false;
|
|
195
|
+
|
|
196
|
+
function finish() {
|
|
197
|
+
if (done) return;
|
|
198
|
+
done = true;
|
|
199
|
+
let source = '';
|
|
200
|
+
try {
|
|
201
|
+
// Strip UTF-8 BOM some shells prepend when piping (breaks JSON.parse)
|
|
202
|
+
const data = JSON.parse(input.replace(/^\uFEFF/, ''));
|
|
203
|
+
source = data.source;
|
|
204
|
+
useSession(data);
|
|
205
|
+
} catch (e) {
|
|
206
|
+
// No payload, or an unparseable one: treat it as a fresh session
|
|
207
|
+
}
|
|
208
|
+
// A Codex conversation opened again keeps the mode it was left in. Other hosts have no saved mode here.
|
|
209
|
+
if (source === 'resume' && sessionMode()) return activate(sessionMode());
|
|
210
|
+
activate(source === 'compact' ? (readMode() || 'off') : getDefaultMode());
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
process.stdin.setEncoding('utf8');
|
|
214
|
+
process.stdin.on('data', chunk => { input += chunk; });
|
|
215
|
+
// Never hang the session start (#443, #790): like the mode tracker, recover on a
|
|
216
|
+
// stdin error or after a short ref'd fallback, and start at the default level.
|
|
217
|
+
process.stdin.on('end', () => { finish(); process.exit(0); });
|
|
218
|
+
process.stdin.on('error', () => { finish(); process.exit(0); });
|
|
219
|
+
setTimeout(() => { finish(); process.exit(0); }, 1000);
|