@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/codex/answer.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The panel's answers for one app (Codex or ZCode): modes, stats, settings and the board. Each request is one of a
|
|
2
|
+
// few fixed operations. The app's module sets TWOCMD_DATA first, so settings and the board live in its own folder.
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
import { readFileSync, rmSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
import { basename, dirname } from 'node:path'
|
|
7
|
+
import { boardHtml, buttonKinds, buttonText, normalizeButtons } from '../dsh/board.js'
|
|
8
|
+
import { readTasks, saveTask } from '../dsh/ledger.js'
|
|
9
|
+
import { money, refreshWhenDue } from '../dsh/market.js'
|
|
10
|
+
import { changeSettings, chosenLanguage, settingsFor } from '../dsh/settings.js'
|
|
11
|
+
import { statsOf } from '../dsh/stats.js'
|
|
12
|
+
import { pathOf, readJson, readSettings } from '../dsh/store.js'
|
|
13
|
+
import { checkUpdate, siteUrl } from '../dsh/update.js'
|
|
14
|
+
|
|
15
|
+
const { RUNTIME_MODES, normalizeMode } = createRequire(import.meta.url)('../hooks/2cmd-config.js')
|
|
16
|
+
// The person's browser or default app for a link or a file.
|
|
17
|
+
const opener = target => (process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', target]] : process.platform === 'darwin' ? ['/usr/bin/open', [target]] : ['xdg-open', [target]])
|
|
18
|
+
const run = (file, args, input) => new Promise((resolve, reject) => {
|
|
19
|
+
const child = spawn(file, args, { stdio: ['pipe', 'ignore', 'ignore'] })
|
|
20
|
+
child.on('error', reject)
|
|
21
|
+
child.on('close', code => (code === 0 ? resolve() : reject(new Error(`${basename(file)} failed`))))
|
|
22
|
+
child.stdin.on('error', () => {})
|
|
23
|
+
child.stdin.end(input)
|
|
24
|
+
})
|
|
25
|
+
/** Opens a link or a file in the person's browser or default app. */
|
|
26
|
+
export const openTarget = target => run(...opener(target))
|
|
27
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
|
|
28
|
+
|
|
29
|
+
// Shown until the plugin has run in a conversation, for apps where 2Cmd is a plugin (ZCode, WorkBuddy, Antigravity).
|
|
30
|
+
export const PLUGIN_WAITING = {
|
|
31
|
+
en: 'Send a message to start. Still empty? Enable the 2Cmd plugin',
|
|
32
|
+
'zh-Hans': '发消息后显示;没有就检查 2Cmd 插件是否已启用',
|
|
33
|
+
'zh-Hant': '傳送訊息後顯示;沒有就檢查 2Cmd 外掛是否已啟用',
|
|
34
|
+
ja: 'メッセージ送信後に表示。出ない場合は 2Cmd プラグインを有効に',
|
|
35
|
+
ko: '메시지를 보내면 표시됩니다. 없으면 2Cmd 플러그인을 켜세요',
|
|
36
|
+
es: 'Envía un mensaje. ¿Sigue vacío? Activa el plugin 2Cmd',
|
|
37
|
+
fr: 'Envoyez un message. Toujours vide ? Activez le plugin 2Cmd',
|
|
38
|
+
de: 'Nachricht senden. Noch leer? Das 2Cmd-Plugin aktivieren',
|
|
39
|
+
pt: 'Envie uma mensagem. Continua vazio? Ative o plugin 2Cmd',
|
|
40
|
+
ru: 'Отправьте сообщение. Всё ещё пусто? Включите плагин 2Cmd',
|
|
41
|
+
vi: 'Hãy gửi một tin nhắn. Vẫn trống? Hãy bật plugin 2Cmd',
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* host: the button commands to use; app: its name in the texts; waiting: shown until the plugin has run in a
|
|
46
|
+
* conversation; idPattern: what a conversation id looks like; eventsOf(id, live): its turns, in dsh/stats.js events.
|
|
47
|
+
* liveOf(id) ({ mode, cwd, transcript }) and pendingPath(id) are where the hooks keep the mode, if not in TWOCMD_DATA.
|
|
48
|
+
* inline: the board and the copied text are returned (Antigravity's panel shows them itself) instead of opened here.
|
|
49
|
+
*/
|
|
50
|
+
export function createAnswer({ host, app, waiting, idPattern, eventsOf, liveOf = id => readJson(pathOf('live', `${id}.json`)), pendingPath = id => pathOf('pending', id), inline = false }) {
|
|
51
|
+
// The texts come from DSH; only its name differs.
|
|
52
|
+
const { strings: STRINGS } = JSON.parse(readFileSync(new URL('../dsh/bundle.json', import.meta.url), 'utf8').replaceAll('DeepSeek Harness', app))
|
|
53
|
+
|
|
54
|
+
const packFor = (language) => {
|
|
55
|
+
const id = String(language)
|
|
56
|
+
return [id, /^zh-(hant|tw|hk|mo)/i.test(id) ? 'zh-Hant' : id.startsWith('zh') ? 'zh-Hans' : id.split('-')[0]].find(x => Object.hasOwn(STRINGS, x)) ?? 'en'
|
|
57
|
+
}
|
|
58
|
+
const fill = (text, values) => text.replace(/\{(\w+)\}/g, (whole, key) => values[key] ?? whole)
|
|
59
|
+
const cash = (value, { currency, rate }, language) => {
|
|
60
|
+
const amount = value * rate
|
|
61
|
+
const digits = amount > 0 && amount < 0.01 ? 4 : amount < 100 ? 2 : undefined
|
|
62
|
+
return new Intl.NumberFormat(language, { style: 'currency', currency, currencyDisplay: currency === 'USD' ? 'narrowSymbol' : 'symbol', minimumFractionDigits: digits, maximumFractionDigits: digits }).format(amount)
|
|
63
|
+
}
|
|
64
|
+
const short = n => (n < 1000 ? String(n) : n < 1e6 ? `${(n / 1000).toFixed(1)}k` : `${(n / 1e6).toFixed(1)}M`)
|
|
65
|
+
const elapsed = (ms) => {
|
|
66
|
+
const s = Math.round(ms / 1000)
|
|
67
|
+
return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function pendingMode(id) {
|
|
71
|
+
try { return normalizeMode(readFileSync(pendingPath(id), 'utf8')) } catch { return null }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const saved = new Map() // conversation id -> what the board last got, so unchanged stats are not written again
|
|
75
|
+
function state(id, t, pack) {
|
|
76
|
+
refreshWhenDue()
|
|
77
|
+
const live = liveOf(id)
|
|
78
|
+
const mode = normalizeMode(live?.mode)
|
|
79
|
+
const stats = statsOf(eventsOf(id, live))
|
|
80
|
+
const mark = JSON.stringify([stats.turns, stats.tokens, stats.ms, stats.cost?.total, mode])
|
|
81
|
+
if (stats.turns > 0 && saved.get(id) !== mark) {
|
|
82
|
+
try {
|
|
83
|
+
saveTask({ id, snapshotEvents: () => [], header: { cwd: typeof live?.cwd === 'string' ? live.cwd : '' } }, stats, mode ?? 'off')
|
|
84
|
+
saved.set(id, mark)
|
|
85
|
+
} catch (error) {
|
|
86
|
+
console.warn(`2cmd: could not save the board: ${error.code ?? error.name}`)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (mode && mode !== 'off') resume.set(id, mode)
|
|
90
|
+
const m = money()
|
|
91
|
+
const { cost, cache } = stats
|
|
92
|
+
return {
|
|
93
|
+
mode, // null: the 2Cmd plugin has not run in this conversation
|
|
94
|
+
pending: pendingMode(id),
|
|
95
|
+
resume: resume.get(id) ?? 'reuse',
|
|
96
|
+
model: stats.model,
|
|
97
|
+
cells: [
|
|
98
|
+
[t.cost, cost ? cash(cost.total, m, pack) : '–', cost ? fill(t.costSub, { last: cash(cost.last, m, pack), avg: cash(cost.avg, m, pack) }) : ''],
|
|
99
|
+
[t.tokens, stats.tokens ? short(stats.tokens) : '–', fill(t.turnsN, { n: stats.turns })],
|
|
100
|
+
[t.cache, cache ? `${cache.last}%` : '–', cache ? fill(t.cacheSub, { n: cache.turns, v: cache.avg }) : ''],
|
|
101
|
+
[t.time, stats.ms ? elapsed(stats.ms) : '–', stats.ms ? fill(t.avgTurn, { t: elapsed(stats.ms / stats.turns) }) : ''],
|
|
102
|
+
],
|
|
103
|
+
buttons: normalizeButtons(readSettings().buttons, host).map(button => ({ ...button, text: buttonText(button, host) })),
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const resume = new Map() // conversation id -> the mode 启用 goes back to
|
|
107
|
+
|
|
108
|
+
function choose(id, mode) {
|
|
109
|
+
const current = normalizeMode(liveOf(id)?.mode)
|
|
110
|
+
const file = pendingPath(id)
|
|
111
|
+
if (mode === current) return rmSync(file, { force: true })
|
|
112
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
|
|
113
|
+
// Renamed into place, so the hook never reads half a word.
|
|
114
|
+
const temporary = `${dirname(file)}/.${basename(file)}.tmp`
|
|
115
|
+
writeFileSync(temporary, mode, { mode: 0o600 })
|
|
116
|
+
renameSync(temporary, file)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
/** One request from the panel. Anything that is not exactly one of these is refused. */
|
|
121
|
+
return async function answer(request, { system = run } = {}) {
|
|
122
|
+
const { op, id } = request ?? {}
|
|
123
|
+
const chosen = chosenLanguage()
|
|
124
|
+
const pack = packFor(chosen === 'auto' ? request?.language : chosen)
|
|
125
|
+
const t = STRINGS[pack]
|
|
126
|
+
if (op === 'start') return { t: { ...t, waiting: waiting[pack] ?? waiting.en }, pack }
|
|
127
|
+
// With each button kind's own text, which the settings fill in when a kind is chosen.
|
|
128
|
+
const withTexts = data => ({ ...data, texts: Object.fromEntries(buttonKinds(host).map(kind => [kind, buttonText({ kind }, host) ?? ''])) })
|
|
129
|
+
if (op === 'settings') return withTexts(settingsFor(host))
|
|
130
|
+
if (op === 'change') {
|
|
131
|
+
const changed = await changeSettings(request.change, host)
|
|
132
|
+
if (changed) return withTexts(changed)
|
|
133
|
+
}
|
|
134
|
+
// Check for updates, when the person asks; a newer version is installed again from 2Cmd's site.
|
|
135
|
+
if (op === 'update') return checkUpdate(VERSION)
|
|
136
|
+
if (op === 'site') {
|
|
137
|
+
await system(...opener(siteUrl(pack)))
|
|
138
|
+
return {}
|
|
139
|
+
}
|
|
140
|
+
if (op === 'board') {
|
|
141
|
+
const { currency, rate } = money()
|
|
142
|
+
const tasks = readTasks().map(task => ({ ...task, cost: typeof task.cost === 'number' ? task.cost * rate : null }))
|
|
143
|
+
const html = boardHtml(tasks, Date.now(), { lang: pack, t }, currency === 'USD' ? undefined : currency)
|
|
144
|
+
if (inline) return { html }
|
|
145
|
+
mkdirSync(pathOf(), { recursive: true, mode: 0o700 })
|
|
146
|
+
writeFileSync(pathOf('board.html'), html, { mode: 0o600 })
|
|
147
|
+
await system(...opener(pathOf('board.html')))
|
|
148
|
+
return {}
|
|
149
|
+
}
|
|
150
|
+
if (typeof id === 'string' && idPattern.test(id)) {
|
|
151
|
+
if (op === 'mode' && RUNTIME_MODES.includes(request.mode)) choose(id, request.mode)
|
|
152
|
+
else if (op === 'copy') {
|
|
153
|
+
const { model, cells, mode } = state(id, t, pack)
|
|
154
|
+
const rows = [[t.model, model || '–'], ...cells, [t.mode, mode ?? '–'], [t.session, id]]
|
|
155
|
+
const text = ['## 2Cmd', '', '| | |', '|---|---|', ...rows.map(([label, value, sub]) => `| ${label} | ${value}${sub ? ` · ${sub}` : ''} |`)].join('\n')
|
|
156
|
+
if (inline) return { text }
|
|
157
|
+
await system('/usr/bin/pbcopy', [], text)
|
|
158
|
+
return {}
|
|
159
|
+
} else if (op !== 'state') throw new Error('refused')
|
|
160
|
+
return state(id, t, pack)
|
|
161
|
+
}
|
|
162
|
+
throw new Error('refused')
|
|
163
|
+
}
|
|
164
|
+
}
|
package/codex/data.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Answers the Codex panel: Codex's own folder, conversation ids and records, on top of answer.mjs.
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { createEvents } from './stats.mjs'
|
|
5
|
+
|
|
6
|
+
const codexHome = process.env.CODEX_HOME || join(homedir(), '.codex')
|
|
7
|
+
process.env.TWOCMD_DATA = join(codexHome, '2cmd') // before the shared modules load; hooks/2cmd-runtime.js uses the same folder
|
|
8
|
+
const { createAnswer } = await import('./answer.mjs')
|
|
9
|
+
|
|
10
|
+
// Shown until the plugin has run in a conversation; without it, modes and stats do nothing.
|
|
11
|
+
const WAITING = {
|
|
12
|
+
en: 'Send a message to start. Still empty? Trust the 2Cmd hooks',
|
|
13
|
+
'zh-Hans': '发消息后显示;没有就检查钩子是否已信任',
|
|
14
|
+
'zh-Hant': '傳送訊息後顯示;沒有就檢查 hooks 是否已信任',
|
|
15
|
+
ja: 'メッセージ送信後に表示。出ない場合はフックの信頼を確認',
|
|
16
|
+
ko: '메시지를 보내면 표시됩니다. 없으면 훅 신뢰를 확인하세요',
|
|
17
|
+
es: 'Envía un mensaje. ¿Sigue vacío? Confía en los hooks',
|
|
18
|
+
fr: 'Envoyez un message. Toujours vide ? Approuvez les hooks',
|
|
19
|
+
de: 'Nachricht senden. Noch leer? Den Hooks vertrauen',
|
|
20
|
+
pt: 'Envie uma mensagem. Continua vazio? Confie nos hooks',
|
|
21
|
+
ru: 'Отправьте сообщение. Всё ещё пусто? Разрешите хуки',
|
|
22
|
+
vi: 'Hãy gửi một tin nhắn. Vẫn trống? Hãy tin cậy các hook',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const answer = createAnswer({
|
|
26
|
+
host: 'codex',
|
|
27
|
+
app: 'Codex',
|
|
28
|
+
waiting: WAITING,
|
|
29
|
+
idPattern: /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,
|
|
30
|
+
eventsOf: createEvents(codexHome),
|
|
31
|
+
})
|
package/codex/pty.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Runs one command in a pseudo-terminal for codex/terminal.mjs, which Node cannot open without a native module.
|
|
2
|
+
|
|
3
|
+
Usage: python3 pty.py ROWS COLS COMMAND [ARGS...]
|
|
4
|
+
fd 0 goes to the command, its screen comes out on fd 1, and a line "ROWS COLS" on fd 3 resizes it.
|
|
5
|
+
Exits with the command's exit status. Standard library only; macOS and Linux.
|
|
6
|
+
"""
|
|
7
|
+
import errno
|
|
8
|
+
import fcntl
|
|
9
|
+
import os
|
|
10
|
+
import select
|
|
11
|
+
import struct
|
|
12
|
+
import sys
|
|
13
|
+
import termios
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resize(fd, rows, cols):
|
|
17
|
+
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def write_all(fd, data):
|
|
21
|
+
while data:
|
|
22
|
+
data = data[os.write(fd, data):]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main():
|
|
26
|
+
rows, cols, argv = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3:]
|
|
27
|
+
master, slave = os.openpty()
|
|
28
|
+
resize(master, rows, cols) # before the command starts, so its first frame has the right size
|
|
29
|
+
pid = os.fork()
|
|
30
|
+
if pid == 0:
|
|
31
|
+
os.close(master)
|
|
32
|
+
os.setsid()
|
|
33
|
+
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
|
|
34
|
+
for fd in (0, 1, 2):
|
|
35
|
+
os.dup2(slave, fd)
|
|
36
|
+
if slave > 2:
|
|
37
|
+
os.close(slave)
|
|
38
|
+
try:
|
|
39
|
+
os.execvp(argv[0], argv)
|
|
40
|
+
except OSError as error:
|
|
41
|
+
os.write(2, ('2cmd: cannot run %s: %s\r\n' % (argv[0], error.strerror)).encode())
|
|
42
|
+
os._exit(127)
|
|
43
|
+
os.close(slave)
|
|
44
|
+
|
|
45
|
+
inputs = [0, master, 3]
|
|
46
|
+
control = b''
|
|
47
|
+
while True:
|
|
48
|
+
ready = select.select(inputs, [], [])[0]
|
|
49
|
+
if master in ready:
|
|
50
|
+
try:
|
|
51
|
+
data = os.read(master, 65536)
|
|
52
|
+
except OSError as error:
|
|
53
|
+
if error.errno != errno.EIO:
|
|
54
|
+
raise
|
|
55
|
+
data = b''
|
|
56
|
+
if not data:
|
|
57
|
+
break # the command closed its terminal
|
|
58
|
+
write_all(1, data)
|
|
59
|
+
if 0 in ready:
|
|
60
|
+
data = os.read(0, 65536)
|
|
61
|
+
if data:
|
|
62
|
+
write_all(master, data)
|
|
63
|
+
else:
|
|
64
|
+
inputs.remove(0)
|
|
65
|
+
if 3 in ready:
|
|
66
|
+
data = os.read(3, 4096)
|
|
67
|
+
if not data:
|
|
68
|
+
inputs.remove(3)
|
|
69
|
+
control += data
|
|
70
|
+
while b'\n' in control:
|
|
71
|
+
line, control = control.split(b'\n', 1)
|
|
72
|
+
size = line.split()
|
|
73
|
+
if len(size) == 2 and all(part.isdigit() for part in size):
|
|
74
|
+
resize(master, int(size[0]), int(size[1])) # the kernel sends the command SIGWINCH
|
|
75
|
+
|
|
76
|
+
status = os.waitpid(pid, 0)[1]
|
|
77
|
+
sys.exit(os.WEXITSTATUS(status) if os.WIFEXITED(status) else 128 + os.WTERMSIG(status))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
main()
|
package/codex/stats.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Turns a Codex conversation record into the events dsh/stats.js understands. The record also holds the chat, so a
|
|
2
|
+
// line is only parsed when its first characters say it is a token count. Everything else gives up its time or model.
|
|
3
|
+
import { closeSync, fstatSync, openSync, readSync, realpathSync } from 'node:fs'
|
|
4
|
+
import { basename, join, sep } from 'node:path'
|
|
5
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
6
|
+
|
|
7
|
+
const HEAD = /^\{"timestamp":"([^"]{10,40})",(?:"[a-z_]{1,30}":(?:\d+|null|"[^"\\]{0,80}"),)*?"type":"(?:(turn_context)"|event_msg","payload":\{"type":"(task_started|turn_started|token_count|task_complete|turn_complete|turn_aborted)")/
|
|
8
|
+
const CHUNK = 1 << 20
|
|
9
|
+
|
|
10
|
+
/** Only a record in Codex's own folders that belongs to this conversation. */
|
|
11
|
+
export function recordPath(file, id, codexHome) {
|
|
12
|
+
if (typeof file !== 'string' || !basename(file).endsWith(`${id}.jsonl`)) return undefined
|
|
13
|
+
try {
|
|
14
|
+
const real = realpathSync(file)
|
|
15
|
+
const home = realpathSync(codexHome)
|
|
16
|
+
return ['sessions', 'archived_sessions'].some(dir => real.startsWith(join(home, dir) + sep)) ? real : undefined
|
|
17
|
+
} catch {
|
|
18
|
+
return undefined // no record yet
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const count = value => (Number.isSafeInteger(value) && value >= 0 ? value : 0)
|
|
23
|
+
|
|
24
|
+
export function createReader() {
|
|
25
|
+
const events = []
|
|
26
|
+
let turn = 0
|
|
27
|
+
let open = false
|
|
28
|
+
let model = ''
|
|
29
|
+
let lastTotal
|
|
30
|
+
|
|
31
|
+
const line = (text) => {
|
|
32
|
+
const head = HEAD.exec(text.slice(0, 400))
|
|
33
|
+
if (!head) return
|
|
34
|
+
const time = Date.parse(head[1])
|
|
35
|
+
if (Number.isNaN(time)) return
|
|
36
|
+
if (head[2]) {
|
|
37
|
+
model = /"model":"([^"\\]{1,100})"/.exec(text)?.[1] ?? model
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
if (head[3].endsWith('started')) {
|
|
41
|
+
events.push({ type: 'turn/start', time, data: { turn: ++turn } })
|
|
42
|
+
open = true
|
|
43
|
+
} else if (head[3] !== 'token_count') {
|
|
44
|
+
if (open) events.push({ type: 'turn/end', time, data: { turn } })
|
|
45
|
+
open = false
|
|
46
|
+
} else {
|
|
47
|
+
let info
|
|
48
|
+
try { info = JSON.parse(text).payload.info } catch { return }
|
|
49
|
+
const total = info?.total_token_usage?.total_tokens
|
|
50
|
+
const used = info?.last_token_usage
|
|
51
|
+
// Codex repeats the last count when only the account limits change.
|
|
52
|
+
if (!used || typeof total !== 'number' || total === lastTotal) return
|
|
53
|
+
lastTotal = total
|
|
54
|
+
if (turn === 0) turn = 1
|
|
55
|
+
// Codex counts cached tokens as part of the input.
|
|
56
|
+
const cacheReadTokens = count(used.cached_input_tokens)
|
|
57
|
+
const cacheWriteTokens = count(used.cache_write_input_tokens)
|
|
58
|
+
const usage = { inputTokens: Math.max(0, count(used.input_tokens) - cacheReadTokens - cacheWriteTokens), cacheReadTokens, cacheWriteTokens, outputTokens: count(used.output_tokens) }
|
|
59
|
+
events.push({ type: 'assistant/message', time, data: { turn, usage, message: { source: { model } } } })
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let file, inode, offset = 0, rest = '', decoder = new StringDecoder('utf8')
|
|
64
|
+
const reset = () => {
|
|
65
|
+
events.length = 0
|
|
66
|
+
;[turn, open, model, lastTotal, offset, rest, decoder] = [0, false, '', undefined, 0, '', new StringDecoder('utf8')]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Reads only what was added since last time, and starts over if the file was replaced. */
|
|
70
|
+
return function read(path) {
|
|
71
|
+
const fd = openSync(path, 'r')
|
|
72
|
+
try {
|
|
73
|
+
const { size, ino } = fstatSync(fd)
|
|
74
|
+
if (path !== file || ino !== inode || size < offset) reset()
|
|
75
|
+
file = path
|
|
76
|
+
inode = ino
|
|
77
|
+
const buffer = Buffer.allocUnsafe(Math.min(CHUNK, Math.max(1, size - offset)))
|
|
78
|
+
while (offset < size) {
|
|
79
|
+
const n = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset)
|
|
80
|
+
if (n === 0) break
|
|
81
|
+
offset += n
|
|
82
|
+
const lines = (rest + decoder.write(buffer.subarray(0, n))).split('\n')
|
|
83
|
+
rest = lines.pop()
|
|
84
|
+
lines.forEach(line)
|
|
85
|
+
}
|
|
86
|
+
return events
|
|
87
|
+
} finally {
|
|
88
|
+
closeSync(fd)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** eventsOf(conversation id, its live file) -> its events, keeping a reader for the last few conversations. */
|
|
94
|
+
export function createEvents(codexHome) {
|
|
95
|
+
const readers = new Map()
|
|
96
|
+
return function eventsOf(id, live) {
|
|
97
|
+
const file = recordPath(live?.transcript, id, codexHome)
|
|
98
|
+
if (!file) return []
|
|
99
|
+
const read = readers.get(id) ?? createReader()
|
|
100
|
+
readers.delete(id)
|
|
101
|
+
readers.set(id, read)
|
|
102
|
+
if (readers.size > 5) readers.delete(readers.keys().next().value)
|
|
103
|
+
return read(file)
|
|
104
|
+
}
|
|
105
|
+
}
|