agy-bar 0.9.2 → 0.9.3

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/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to **agy-bar** are documented here.
4
4
 
5
+ ## [0.9.3] - 2026-11-26
6
+
7
+ ### Added
8
+ - **Official Native Antigravity CLI `title` Hook (`src/title.mjs`, `src/installer.mjs`)**:
9
+ - Upgraded terminal tab/window title sync to Antigravity CLI's official `settings.json` `"title"` command interface (`https://antigravity.google/docs/cli/title`) so `agy` itself drives window/tab titles cleanly on **macOS, Linux, and native Windows Terminal** with zero `/dev/tty` escape-sequence interleaving and zero `ps` subprocesses.
10
+ - `agy-bar install` automatically configures `settings.title` (backing up previous settings for clean `uninstall` restoration, refusing to overwrite unrelated custom `title` commands, and supporting `--no-title` opt-out); `agy-bar doctor` now verifies native title health.
11
+ - Uses a lightweight per-session `.title` marker so `statusline.mjs` automatically steps aside once native `title` is active while seamlessly keeping hardened `/dev/tty` fallback for un-restarted sessions.
12
+
13
+ ### Fixed
14
+ - **Hardened Fallback Tab Title Sync (`src/tab-title.mjs`, `src/statusline.mjs`, `src/telemetry.mjs`)**:
15
+ - Ran fallback tab-title sync synchronously before async SQLite scans to prevent out-of-order `working`/`idle` races, cached `lastTabTty` for zero-`ps` direct writes with `O_NOCTTY`, widened `ps` timeout to `500ms`, and stopped persisting `lastTabTitle` on failed writes so retries happen automatically.
16
+ - **Account Isolation Key (`src/quota-sync.mjs`)**:
17
+ - Included AGY's live top-level `payload.email` field when computing the non-PII SHA-1 account key for local cross-terminal quota sync.
18
+
5
19
  ## [0.9.2] - 2026-11-26
6
20
 
7
21
  ### Added
package/README.md CHANGED
@@ -82,7 +82,7 @@ Running 3–5 `agy` sessions across different repos? Open `agy-bar monitor` in a
82
82
 
83
83
  ### 5. Automatic Terminal Tab Titles (`●` / `● [N]` / `?` / `✓`) & Agent Summarization (`agy-bar title`)
84
84
 
85
- Replaces identical `agy --dangerously-skip-permissions` tabs across Ghostty, iTerm2, Kitty, WezTerm, macOS Terminal, and VS Code with live activity state (`●` working, `● [N]` running subagents, `?` waiting for user input/confirmation, `✗` error, `✓` truly idle) + concise topic title via standard OSC 0/2 (zero extra tokens; safely skipped on native Windows):
85
+ Replaces identical `agy --dangerously-skip-permissions` tabs across Ghostty, iTerm2, Kitty, WezTerm, macOS Terminal, Windows Terminal, and VS Code using **Antigravity CLI's official `title` hook** (`settings.json` → `title`, with automatic OSC 0/2 fallback for older sessions) to show live activity state (`●` working, `● [N]` running subagents, `?` waiting for user input/confirmation, `✗` error, `✓` truly idle) + concise topic title (zero extra tokens, full macOS / Linux / Windows support):
86
86
 
87
87
  ![agy-bar live Ghostty tab titles comparison](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-tab-titles.png)
88
88
 
@@ -100,7 +100,7 @@ Replaces identical `agy --dangerously-skip-permissions` tabs across Ghostty, iTe
100
100
 
101
101
  | Guarantee | How It Works |
102
102
  | --- | --- |
103
- | **100% Official `statusLine` Hook** | Zero binary patching, zero Electron injection, zero Google/AGY private API calls, zero account credential access. Survives every AGY update cleanly. |
103
+ | **100% Official `statusLine` + `title` Hooks** | Zero binary patching, zero Electron injection, zero Google/AGY private API calls, zero account credential access. Survives every AGY update cleanly. |
104
104
  | **Read-Only Local Telemetry** | SQLite conversation scans (`Node >= 22.13`) open DBs in `readOnly: true` mode and extract **only numeric timestamps & token counts** — never prompts or replies. |
105
105
  | **Transparent Network Policy** | Statusline rendering itself **never touches the network**. Only an optional 24-hour background sync fetches public unauthenticated pricing JSON (`models.dev` / `LiteLLM`); run `agy-bar config set pricingAutoSync off` for strict offline mode. |
106
106
  | **Zero-Dep Fast Hot Path** | `0` runtime dependencies, zero-subprocess idle refreshes (PID fast-path + 3s Git cache + SQLite `mtime` skip + 5-min Windows theme cache), and atomic file writes across concurrent terminals. |
package/README.zh-CN.md CHANGED
@@ -82,7 +82,7 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
82
82
 
83
83
  ### 5. 终端标签页标题自动同步 (`●` / `● [N]` / `?` / `✓`) 与 Agent 摘要 (`agy-bar title`)
84
84
 
85
- 彻底告别多开时所有标签页都叫 `agy --dangerously-skip-permissions` 的烦恼:在 macOS / Linux / WSL 下的 Ghostty、iTerm2、Kitty、WezTerm、Terminal.app、VS Code 中通过标准 OSC 0/2 自动同步精确状态(`●` 工作中、`● [N]` 子代理运行中、`?` 等待你确认/输入、`✗` 报错、`✓` 全部完成)与精简主题(零额外 Token;原生 Windows 自动安全跳过):
85
+ 彻底告别多开时所有标签页都叫 `agy --dangerously-skip-permissions` 的烦恼:接入 **Antigravity CLI 官方原生 `title` 接口**(`settings.json` → `title`,旧会话自动回退 OSC 0/2),在 macOS / Linux / 原生 Windows Terminal 下的 Ghostty、iTerm2、Kitty、WezTerm、Terminal.app、VS Code 中稳定同步精确状态(`●` 工作中、`● [N]` 子代理运行中、`?` 等待你确认/输入、`✗` 报错、`✓` 全部完成)与精简主题(零额外 Token、无字节交错):
86
86
 
87
87
  ![agy-bar Ghostty 标签页标题真机对比](https://raw.githubusercontent.com/xy-tuoren/agy-bar/main/assets/live-tab-titles.png)
88
88
 
@@ -100,7 +100,7 @@ CTX ▮▮▮▯▯▯▯▯ 42.6% (1.0M) │ CACHE 88%·3m42s │ TTFT 1.9s·15
100
100
 
101
101
  | 承诺 | 实现机制 |
102
102
  | --- | --- |
103
- | **100% 官方原生 `statusLine` 接口** | 不修改/不注入任何客户端二进制,不调用任何 Google/AGY 私有接口,不接触账号凭据;官方任意升级不失效、零封号风险。 |
103
+ | **100% 官方原生 `statusLine` + `title` 接口** | 不修改/不注入任何客户端二进制,不调用任何 Google/AGY 私有接口,不接触账号凭据;官方任意升级不失效、零封号风险。 |
104
104
  | **只读本地数值遥测** | SQLite 历史扫描(`Node >= 22.13`)全程 `readOnly: true`,**仅提取数值时间戳与 Token 计数**,绝不读取聊天正文。 |
105
105
  | **透明联网策略** | 底栏渲染热路径**完全不联网**;仅默认每 24 小时后台异步拉取一次公开免鉴权的 `models.dev` / `LiteLLM` 参考单价,随时可 `agy-bar config set pricingAutoSync off` 严格离线。 |
106
106
  | **零依赖极致流畅** | `0` 第三方依赖,空闲刷新零子进程(PID 快速路径 + 3s Git 缓存 + SQLite `mtime` 跳过 + 5 分钟 Windows 主题缓存),多终端并发采用原子写防文件损坏。 |
package/bin/agy-bar.mjs CHANGED
@@ -76,9 +76,10 @@ export const HELP_TEXT = [
76
76
  'Usage: agy-bar <command> [options]',
77
77
  '',
78
78
  'Commands:',
79
- ' install [options] Install statusline + global ~/.local/bin/agy-bar command',
79
+ ' install [options] Install statusline + native AGY title hook + global agy-bar CLI',
80
80
  ' --proxy-hook Also install managed agy() shell hook without prompting',
81
81
  ' --no-proxy-hook Skip shell hook without prompting (leaves ~/.zshrc untouched)',
82
+ ' --no-title Skip configuring AGY native settings.json title hook',
82
83
  ' --no-skill Skip installing the companion /agy-bar skill',
83
84
  ' --no-shim Skip installing the ~/.local/bin/agy-bar shortcut command',
84
85
  ' -y, --yes Non-interactive install (keeps ~/.zshrc untouched unless --proxy-hook)',
@@ -174,6 +175,8 @@ function parseFlags(args) {
174
175
  else if (arg === '--with-skill') flags.withSkill = true;
175
176
  else if (arg === '--no-shim') flags.withShim = false;
176
177
  else if (arg === '--with-shim') flags.withShim = true;
178
+ else if (arg === '--no-title') flags.withTitle = false;
179
+ else if (arg === '--with-title') flags.withTitle = true;
177
180
  else if (arg === '--no-shell-hook' || arg === '--no-proxy-hook') flags.withShellHook = false;
178
181
  else if (arg === '--with-shell-hook' || arg === '--proxy-hook') flags.withShellHook = true;
179
182
  else if (arg === '--yes' || arg === '-y') flags.yes = true;
@@ -267,6 +270,7 @@ export async function main(argv = process.argv.slice(2)) {
267
270
  const result = installAgyBar({
268
271
  withSkill: flags.withSkill ?? true,
269
272
  withShim,
273
+ withTitle: flags.withTitle ?? true,
270
274
  withShellHook: hookDecision.enable,
271
275
  shell: flags.shell ?? null,
272
276
  preset: flags.preset ?? null,
@@ -274,6 +278,11 @@ export async function main(argv = process.argv.slice(2)) {
274
278
  barStyle: flags.barStyle ?? null,
275
279
  });
276
280
  console.log(`Installed agy-bar statusline at ${result.scriptPath}`);
281
+ if (result.titleScriptPath) {
282
+ console.log(`Installed native AGY title hook at ${result.titleScriptPath}`);
283
+ } else if (result.titleWarning) {
284
+ console.log(`Note: ${result.titleWarning}`);
285
+ }
277
286
  console.log(`Updated AGY settings: ${result.settingsPath}`);
278
287
  if (result.shimPath) {
279
288
  console.log(`Installed global CLI command: ${result.shimPath}`);
@@ -469,7 +478,7 @@ export async function main(argv = process.argv.slice(2)) {
469
478
  );
470
479
  const writeRes = renderedTitle && cfg.tabTitle ? writeOscTitle(renderedTitle) : { written: false, tty: null };
471
480
  if (writeRes.written) {
472
- updateSessionTabTitle(updated.sessionId, renderedTitle, { hostPid: writeRes.hostPid });
481
+ updateSessionTabTitle(updated.sessionId, renderedTitle, { hostPid: writeRes.hostPid, tty: writeRes.tty });
473
482
  }
474
483
  console.log(
475
484
  flags.clear
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-bar",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "description": "Zero-dependency terminal statusline, no-TUN proxy launcher, exact TTFT & tok/s speed, 5-min cache TTL countdown, live pricing cache, automatic tab titles, 52-week token heatmap, and multi-CLI monitor for Antigravity CLI (agy).",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/installer.mjs CHANGED
@@ -33,6 +33,10 @@ export function installedScriptPath(home = homedir()) {
33
33
  return join(installedAppDir(home), 'src', 'statusline.mjs');
34
34
  }
35
35
 
36
+ export function installedTitleScriptPath(home = homedir()) {
37
+ return join(installedAppDir(home), 'src', 'title.mjs');
38
+ }
39
+
36
40
  export function installedCliPath(home = homedir()) {
37
41
  return join(installedAppDir(home), 'bin', 'agy-bar.mjs');
38
42
  }
@@ -49,11 +53,11 @@ function shQuote(value) {
49
53
  return `'${String(value).replaceAll("'", "'\\''")}'`;
50
54
  }
51
55
 
52
- export function buildCommand(executable, scriptPath, platform = process.platform) {
56
+ export function buildCommand(executable, scriptPath, platform = process.platform, exportName = 'runStatusline') {
53
57
  if (platform === 'win32') {
54
58
  // Avoid spaces, quotes, and '>' redirection operators for Windows cmd /c safety.
55
59
  const encodedUrl = Buffer.from(pathToFileURL(scriptPath).href).toString('base64');
56
- return `node -e import(Buffer.from('${encodedUrl}','base64').toString()).then(function(m){m.runStatusline()})`;
60
+ return `node -e import(Buffer.from('${encodedUrl}','base64').toString()).then(function(m){m.${exportName}()})`;
57
61
  }
58
62
  return `${shQuote(executable)} ${shQuote(scriptPath)}`;
59
63
  }
@@ -112,6 +116,7 @@ export function isAgyBarCommand(command, backup = null) {
112
116
  if (typeof command !== 'string' || !command.trim()) return false;
113
117
  if (command.includes('agy-bar')) return true;
114
118
  if (backup?.installedCommand && command === backup.installedCommand) return true;
119
+ if (backup?.installedTitleCommand && command === backup.installedTitleCommand) return true;
115
120
 
116
121
  // Windows buildCommand() base64-encodes the file:// URL for cmd /c safety.
117
122
  const b64Match = /Buffer\.from\('([A-Za-z0-9+/=]+)','base64'\)/.exec(command);
@@ -159,6 +164,7 @@ export function installAgyBar({
159
164
  env = process.env,
160
165
  withSkill = true,
161
166
  withShim = true,
167
+ withTitle = true,
162
168
  withShellHook = false,
163
169
  shell = null,
164
170
  preset = null,
@@ -176,6 +182,7 @@ export function installAgyBar({
176
182
 
177
183
  const appDir = installedAppDir(home);
178
184
  const scriptPath = installedScriptPath(home);
185
+ const titleScriptPath = installedTitleScriptPath(home);
179
186
  const cliPath = installedCliPath(home);
180
187
  const settingsPath = agySettingsPath(home);
181
188
  const backupPath = backupFilePath(home);
@@ -208,19 +215,56 @@ export function installAgyBar({
208
215
 
209
216
  const settings = existsSync(settingsPath) ? readJson(settingsPath) : {};
210
217
  const existingBackup = existsSync(backupPath) ? readJson(backupPath) : null;
211
- const command = buildCommand(executable, scriptPath, platform);
218
+ const command = buildCommand(executable, scriptPath, platform, 'runStatusline');
219
+ const titleCommand = buildCommand(executable, titleScriptPath, platform, 'runTitleCommand');
220
+
221
+ const existingTitleOurs = Boolean(
222
+ settings.title &&
223
+ (settings.title?.command === existingBackup?.installedTitleCommand ||
224
+ isAgyBarCommand(settings.title?.command, existingBackup)),
225
+ );
226
+ const hasUnrelatedTitle = Boolean(settings.title && !existingTitleOurs);
227
+ let titleInstalled = false;
228
+ let titleWarning = null;
212
229
 
213
230
  // Keep the original backup across upgrades unless the user switched away to another renderer.
214
- const backup =
231
+ const statusLineBackup =
215
232
  existingBackup && settings.statusLine?.command === existingBackup.installedCommand
216
- ? { ...existingBackup, installedCommand: command }
233
+ ? {
234
+ hadStatusLine: existingBackup.hadStatusLine,
235
+ statusLine: existingBackup.statusLine,
236
+ installedCommand: command,
237
+ }
217
238
  : {
218
239
  hadStatusLine: Object.hasOwn(settings, 'statusLine'),
219
240
  statusLine: settings.statusLine ?? null,
220
241
  installedCommand: command,
221
242
  };
222
243
 
223
- writeJson(backupPath, backup);
244
+ let titleBackup;
245
+ if (existingBackup && Object.hasOwn(existingBackup, 'hadTitle') && existingTitleOurs) {
246
+ titleBackup = {
247
+ hadTitle: existingBackup.hadTitle,
248
+ title: existingBackup.title,
249
+ installedTitleCommand: withTitle ? titleCommand : existingBackup.installedTitleCommand ?? null,
250
+ };
251
+ } else if (withTitle && !hasUnrelatedTitle) {
252
+ titleBackup = {
253
+ hadTitle: Object.hasOwn(settings, 'title'),
254
+ title: settings.title ?? null,
255
+ installedTitleCommand: titleCommand,
256
+ };
257
+ } else if (existingBackup && Object.hasOwn(existingBackup, 'hadTitle')) {
258
+ titleBackup = {
259
+ hadTitle: existingBackup.hadTitle,
260
+ title: existingBackup.title,
261
+ installedTitleCommand: existingBackup.installedTitleCommand ?? null,
262
+ };
263
+ } else {
264
+ titleBackup = {};
265
+ }
266
+
267
+ writeJson(backupPath, { ...statusLineBackup, ...titleBackup });
224
268
 
225
269
  settings.statusLine = {
226
270
  type: 'command',
@@ -228,11 +272,28 @@ export function installAgyBar({
228
272
  enabled: true,
229
273
  stack_with_default: false,
230
274
  };
275
+
276
+ if (withTitle) {
277
+ if (hasUnrelatedTitle) {
278
+ titleWarning = 'Kept existing custom AGY title command in settings.json (pass --no-title to silence this note).';
279
+ } else {
280
+ settings.title = {
281
+ type: 'command',
282
+ command: titleCommand,
283
+ enabled: savedConfig.tabTitle !== false,
284
+ };
285
+ titleInstalled = true;
286
+ }
287
+ }
288
+
231
289
  writeJson(settingsPath, settings);
232
290
 
233
291
  return {
234
292
  installed: true,
235
293
  scriptPath,
294
+ titleScriptPath: titleInstalled ? titleScriptPath : null,
295
+ titleCommand: titleInstalled ? titleCommand : null,
296
+ titleWarning,
236
297
  cliPath,
237
298
  shimPath,
238
299
  shimWarning,
@@ -261,22 +322,50 @@ export function uninstallAgyBar({
261
322
  const hadApp = existsSync(appDir);
262
323
  const hadCfgDir = existsSync(cfgDir);
263
324
  let restored = false;
325
+ let titleRestored = false;
264
326
 
265
327
  if (hadBackup) {
266
328
  const backup = readJson(backupPath);
267
329
  if (existsSync(settingsPath)) {
268
330
  const settings = readJson(settingsPath);
331
+ let settingsChanged = false;
269
332
  if (settings.statusLine?.command === backup.installedCommand) {
270
333
  if (backup.hadStatusLine) {
271
334
  settings.statusLine = backup.statusLine;
272
335
  } else {
273
336
  delete settings.statusLine;
274
337
  }
275
- writeJson(settingsPath, settings);
276
338
  restored = true;
339
+ settingsChanged = true;
340
+ }
341
+ if (
342
+ backup.installedTitleCommand &&
343
+ (settings.title?.command === backup.installedTitleCommand || isAgyBarCommand(settings.title?.command, backup))
344
+ ) {
345
+ if (backup.hadTitle) {
346
+ settings.title = backup.title;
347
+ } else {
348
+ delete settings.title;
349
+ }
350
+ titleRestored = true;
351
+ settingsChanged = true;
352
+ }
353
+ if (settingsChanged) {
354
+ writeJson(settingsPath, settings);
277
355
  }
278
356
  }
279
357
  rmSync(backupPath, { force: true, maxRetries: 3, retryDelay: 50 });
358
+ } else if (existsSync(settingsPath)) {
359
+ try {
360
+ const settings = readJson(settingsPath);
361
+ if (isAgyBarCommand(settings.title?.command)) {
362
+ delete settings.title;
363
+ writeJson(settingsPath, settings);
364
+ titleRestored = true;
365
+ }
366
+ } catch {
367
+ // Ignore malformed settings.json during orphan cleanup.
368
+ }
280
369
  }
281
370
 
282
371
  const shimRemoved = uninstallCliShim({ home, platform });
@@ -295,12 +384,13 @@ export function uninstallAgyBar({
295
384
  }
296
385
 
297
386
  const removedAnything = Boolean(
298
- hadBackup || hadApp || shimRemoved || hookResult.removed || skillResult?.removed || (purge && hadCfgDir),
387
+ hadBackup || hadApp || shimRemoved || hookResult.removed || skillResult?.removed || titleRestored || (purge && hadCfgDir),
299
388
  );
300
389
  if (!removedAnything) {
301
390
  return {
302
391
  uninstalled: false,
303
392
  restored: false,
393
+ titleRestored: false,
304
394
  shimRemoved: false,
305
395
  shellHookRemoved: false,
306
396
  shellHookPaths: [],
@@ -313,6 +403,7 @@ export function uninstallAgyBar({
313
403
  return {
314
404
  uninstalled: true,
315
405
  restored,
406
+ titleRestored,
316
407
  shimRemoved,
317
408
  shellHookRemoved: hookResult.removed,
318
409
  shellHookPaths: hookResult.rcPaths,
@@ -329,6 +420,7 @@ export function uninstallAgyBar({
329
420
  export function runDoctor({ home = homedir(), platform = process.platform, env = process.env } = {}) {
330
421
  const settingsPath = agySettingsPath(home);
331
422
  const scriptPath = installedScriptPath(home);
423
+ const titleScriptPath = installedTitleScriptPath(home);
332
424
  const shimDest = cliShimPath(home, platform);
333
425
  const cfgPath = configPath(home);
334
426
  const skillPath = targetSkillPath(home);
@@ -368,6 +460,8 @@ export function runDoctor({ home = homedir(), platform = process.platform, env =
368
460
 
369
461
  let statusLineEnabled = false;
370
462
  let settingsDetail = 'settings.json not found';
463
+ let nativeTitleActive = false;
464
+ let nativeTitleDetail = 'not configured (run "agy-bar install" to enable native cross-platform tab titles)';
371
465
  let backup = null;
372
466
  const backupPath = backupFilePath(home);
373
467
  if (existsSync(backupPath)) {
@@ -388,6 +482,16 @@ export function runDoctor({ home = homedir(), platform = process.platform, env =
388
482
  : settings.statusLine
389
483
  ? `statusLine points to another command (${settings.statusLine.command || 'unknown'})`
390
484
  : 'statusLine not configured';
485
+
486
+ const titleIsOurs = isAgyBarCommand(settings.title?.command, backup);
487
+ nativeTitleActive = settings.title?.enabled === true && titleIsOurs && existsSync(titleScriptPath);
488
+ nativeTitleDetail = nativeTitleActive
489
+ ? 'title.enabled = true (agy-bar native title active — macOS/Linux/Windows)'
490
+ : titleIsOurs && settings.title?.enabled === false
491
+ ? 'title.enabled = false (disabled in settings.json; run "/title on" in agy)'
492
+ : settings.title
493
+ ? `title points to another command (${settings.title.command || 'unknown'})`
494
+ : nativeTitleDetail;
391
495
  } catch (err) {
392
496
  settingsDetail = `Failed to parse settings.json: ${err.message}`;
393
497
  }
@@ -397,6 +501,12 @@ export function runDoctor({ home = homedir(), platform = process.platform, env =
397
501
  ok: statusLineEnabled,
398
502
  detail: settingsDetail,
399
503
  });
504
+ checks.push({
505
+ name: 'AGY native title',
506
+ ok: nativeTitleActive,
507
+ optional: true,
508
+ detail: nativeTitleDetail,
509
+ });
400
510
 
401
511
  const skillInstalled = existsSync(skillPath);
402
512
  checks.push({
@@ -63,6 +63,7 @@ export function isWeeklyBucketBlocking(bucketId, quotaMap, now = Date.now()) {
63
63
 
64
64
  export function extractAccountKey(payload) {
65
65
  const raw =
66
+ payload?.email ||
66
67
  payload?.account?.email ||
67
68
  payload?.user_email ||
68
69
  payload?.account?.id ||
@@ -10,7 +10,8 @@ import { extractAccountKey, syncSharedQuota } from './quota-sync.mjs';
10
10
  import { renderFallback, renderStatusline } from './render.mjs';
11
11
  import { readLatestStepTiming } from './step-timing.mjs';
12
12
  import { syncTabTitle } from './tab-title.mjs';
13
- import { maybeCaptureRedactedPayload, peekSessionState, recordTelemetry, updateSessionTabTitle } from './telemetry.mjs';
13
+ import { deriveSessionId, maybeCaptureRedactedPayload, peekSessionState, recordTelemetry, resolveSessionTitles } from './telemetry.mjs';
14
+ import { isNativeTitleActive } from './title.mjs';
14
15
 
15
16
  const GIT_DIRTY_CACHE_MS = 3000;
16
17
 
@@ -55,6 +56,27 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
55
56
  : null,
56
57
  })
57
58
  : null;
59
+
60
+ // Sync terminal tab title synchronously before async DB scans when AGY's native
61
+ // `settings.json.title` hook is not already driving this session's title.
62
+ let tabSync = null;
63
+ if (!plain && config.tabTitle) {
64
+ const sessionIdForTitle = deriveSessionId(effectivePayload);
65
+ if (!isNativeTitleActive(sessionIdForTitle, { now, hostPid: process.ppid })) {
66
+ const { customTitle } = resolveSessionTitles(effectivePayload, prevSession);
67
+ tabSync = syncTabTitle(effectivePayload, {
68
+ config,
69
+ git,
70
+ customTitle,
71
+ prevTabTitle: prevSession?.lastTabTitle || null,
72
+ prevTabHostPid: prevSession?.lastTabHostPid ?? null,
73
+ prevTabTty: prevSession?.lastTabTty || null,
74
+ hostPidHint: process.ppid,
75
+ resolveOpts: { env },
76
+ });
77
+ }
78
+ }
79
+
58
80
  const stepTiming = config.dbTiming
59
81
  ? await readLatestStepTiming(effectivePayload, { prevDbStamp: prevSession?.dbStamp ?? null })
60
82
  : null;
@@ -63,6 +85,7 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
63
85
  git,
64
86
  stepTiming,
65
87
  prevSession,
88
+ tabSync,
66
89
  cacheTtlSec: config.cacheTtlSec,
67
90
  enableLedger: config.ledger,
68
91
  });
@@ -94,21 +117,6 @@ export async function runStatusline({ stdin = process.stdin, stdout = process.st
94
117
  ? { ...telemetry, sessionCostUsd: effectiveSessionCostUsd }
95
118
  : telemetry;
96
119
 
97
- if (!plain && config.tabTitle) {
98
- const tab = syncTabTitle(effectivePayload, {
99
- config,
100
- git,
101
- customTitle: telemetry.customTitle,
102
- prevTabTitle: telemetry.prevTabTitle,
103
- prevTabHostPid: telemetry.prevTabHostPid,
104
- hostPidHint: process.ppid,
105
- resolveOpts: { env },
106
- });
107
- if (tab.changed && tab.title) {
108
- updateSessionTabTitle(telemetry.sessionId, tab.title, { hostPid: tab.hostPid });
109
- }
110
- }
111
-
112
120
  if (config.pricingAutoSync) {
113
121
  maybeTriggerBackgroundPricingSync({ enabled: true, now, env });
114
122
  }
package/src/tab-title.mjs CHANGED
@@ -5,6 +5,7 @@ import { classifyAgentActivity } from './agent-state.mjs';
5
5
  import { clipPlain, sanitizeText, visibleWidth } from './ansi.mjs';
6
6
 
7
7
  const VALID_TTY_RE = /^(?:tty[a-z0-9]+|pts\/\d+)$/i;
8
+ const VALID_DEV_TTY_RE = /^\/dev\/(?:tty[a-z0-9]+|pts\/\d+)$/i;
8
9
 
9
10
  const FILLER_PREFIXES = [
10
11
  /^(?:请|麻烦|能不能|可以|能否)?(?:帮我|给我|帮忙)/,
@@ -85,7 +86,7 @@ function defaultReadProc(pid) {
85
86
  try {
86
87
  const out = execFileSync('ps', ['-o', 'ppid=,tty=,comm=', '-p', String(pid)], {
87
88
  encoding: 'utf8',
88
- timeout: 120,
89
+ timeout: 500,
89
90
  stdio: ['ignore', 'pipe', 'ignore'],
90
91
  }).trim();
91
92
  if (!out) return null;
@@ -153,25 +154,53 @@ export function resolveTerminalTty(opts = {}) {
153
154
  return resolveTerminalTarget(opts).tty;
154
155
  }
155
156
 
156
- export function writeOscTitle(title, { ttyPath = null, writer = null, resolveOpts = {} } = {}) {
157
+ export function writeOscTitle(title, { ttyPath = null, writer = null, resolveOpts = {}, writeToTty = null } = {}) {
157
158
  const seq = formatOscTitle(title);
158
- if (!seq) return { written: false, tty: null, hostPid: null, sequence: '' };
159
+ if (!seq) return { written: false, tty: null, hostPid: null, sequence: '', error: 'empty_title' };
159
160
 
160
161
  if (typeof writer === 'function') {
161
162
  writer(seq);
162
- return { written: true, tty: ttyPath || 'custom', hostPid: null, sequence: seq };
163
+ return { written: true, tty: ttyPath || 'custom', hostPid: null, sequence: seq, error: null };
163
164
  }
164
165
 
165
166
  const resolved = ttyPath ? { tty: ttyPath, hostPid: null } : resolveTerminalTarget(resolveOpts);
166
- if (!resolved.tty) return { written: false, tty: null, hostPid: null, sequence: seq };
167
+ if (!resolved.tty) return { written: false, tty: null, hostPid: null, sequence: seq, error: 'no_tty' };
168
+
169
+ if (typeof writeToTty === 'function') {
170
+ try {
171
+ const ok = writeToTty(resolved.tty, seq);
172
+ return {
173
+ written: ok !== false,
174
+ tty: resolved.tty,
175
+ hostPid: resolved.hostPid,
176
+ sequence: seq,
177
+ error: ok === false ? 'write_failed' : null,
178
+ };
179
+ } catch (err) {
180
+ return {
181
+ written: false,
182
+ tty: resolved.tty,
183
+ hostPid: resolved.hostPid,
184
+ sequence: seq,
185
+ error: err?.code || err?.message || 'write_failed',
186
+ };
187
+ }
188
+ }
167
189
 
168
190
  let fd = null;
169
191
  try {
170
- fd = openSync(resolved.tty, 'w');
192
+ const flags = (constants.O_WRONLY ?? 1) | (constants.O_NOCTTY ?? 0);
193
+ fd = openSync(resolved.tty, flags);
171
194
  writeSync(fd, seq);
172
- return { written: true, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq };
173
- } catch {
174
- return { written: false, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq };
195
+ return { written: true, tty: resolved.tty, hostPid: resolved.hostPid, sequence: seq, error: null };
196
+ } catch (err) {
197
+ return {
198
+ written: false,
199
+ tty: resolved.tty,
200
+ hostPid: resolved.hostPid,
201
+ sequence: seq,
202
+ error: err?.code || err?.message || 'write_failed',
203
+ };
175
204
  } finally {
176
205
  if (fd !== null) {
177
206
  try {
@@ -191,33 +220,51 @@ export function syncTabTitle(
191
220
  customTitle = null,
192
221
  prevTabTitle = null,
193
222
  prevTabHostPid = null,
223
+ prevTabTty = null,
194
224
  hostPidHint = null,
195
225
  force = false,
196
226
  ttyPath = null,
197
227
  writer = null,
228
+ writeToTty = null,
198
229
  resolveOpts = {},
199
230
  } = {},
200
231
  ) {
201
232
  if (config.tabTitle === false) {
202
- return { changed: false, written: false, title: null, tty: null, hostPid: null };
233
+ return { changed: false, written: false, title: null, tty: null, hostPid: null, error: null };
203
234
  }
204
235
 
205
236
  const title = buildTabTitle(payload, { config, git, customTitle });
206
237
  if (!title) {
207
- return { changed: false, written: false, title: null, tty: null, hostPid: null };
238
+ return { changed: false, written: false, title: null, tty: null, hostPid: null, error: null };
208
239
  }
209
240
 
210
- // Fast path: skip spawning `ps` when neither title nor host agy PID changed.
241
+ const sameHostHint =
242
+ prevTabHostPid !== null && typeof hostPidHint === 'number' && hostPidHint === prevTabHostPid;
243
+
244
+ // Fast path 1: skip spawning `ps` when neither title nor host agy PID changed.
245
+ if (!force && !writer && !ttyPath && title === prevTabTitle && sameHostHint) {
246
+ return { changed: false, written: false, title, tty: prevTabTty || null, hostPid: prevTabHostPid, error: null };
247
+ }
248
+
249
+ // Fast path 2: on title/state change under the same agy host PID, write directly to cached TTY (zero `ps` spawns).
211
250
  if (
212
- !force &&
213
251
  !writer &&
214
252
  !ttyPath &&
215
- title === prevTabTitle &&
216
- prevTabHostPid !== null &&
217
- typeof hostPidHint === 'number' &&
218
- hostPidHint === prevTabHostPid
253
+ sameHostHint &&
254
+ typeof prevTabTty === 'string' &&
255
+ VALID_DEV_TTY_RE.test(prevTabTty)
219
256
  ) {
220
- return { changed: false, written: false, title, tty: null, hostPid: prevTabHostPid };
257
+ const fastWrite = writeOscTitle(title, { ttyPath: prevTabTty, writeToTty });
258
+ if (fastWrite.written) {
259
+ return {
260
+ changed: true,
261
+ written: true,
262
+ title,
263
+ tty: prevTabTty,
264
+ hostPid: prevTabHostPid,
265
+ error: null,
266
+ };
267
+ }
221
268
  }
222
269
 
223
270
  const resolved = !writer && !ttyPath ? resolveTerminalTarget(resolveOpts) : { tty: ttyPath, hostPid: null };
@@ -225,9 +272,16 @@ export function syncTabTitle(
225
272
  const hostUnknownBefore = resolved.hostPid !== null && prevTabHostPid === null;
226
273
 
227
274
  if (!force && title === prevTabTitle && !hostChanged && !hostUnknownBefore) {
228
- return { changed: false, written: false, title, tty: resolved.tty, hostPid: resolved.hostPid };
275
+ return { changed: false, written: false, title, tty: resolved.tty, hostPid: resolved.hostPid, error: null };
229
276
  }
230
277
 
231
- const result = writeOscTitle(title, { ttyPath: resolved.tty, writer, resolveOpts });
232
- return { changed: true, written: result.written, title, tty: result.tty, hostPid: resolved.hostPid };
278
+ const result = writeOscTitle(title, { ttyPath: resolved.tty, writer, writeToTty, resolveOpts });
279
+ return {
280
+ changed: true,
281
+ written: result.written,
282
+ title,
283
+ tty: result.tty,
284
+ hostPid: resolved.hostPid ?? (sameHostHint ? prevTabHostPid : null),
285
+ error: result.error || null,
286
+ };
233
287
  }
package/src/telemetry.mjs CHANGED
@@ -158,6 +158,19 @@ function pickQuotaSnapshot(quota) {
158
158
  return Object.keys(out).length > 0 ? out : null;
159
159
  }
160
160
 
161
+ export function resolveSessionTitles(payload = {}, prev = null) {
162
+ const conversationTitle = sanitizeText(payload?.conversation_title || '') || prev?.conversationTitle || null;
163
+ // If user explicitly renamed the conversation via /rename (conversation_title changed),
164
+ // clear any older custom tab override automatically.
165
+ let customTitle = prev?.customTitle || null;
166
+ let customTitleBase = prev?.customTitleBase ?? null;
167
+ if (customTitle && conversationTitle && customTitleBase && conversationTitle !== customTitleBase) {
168
+ customTitle = null;
169
+ customTitleBase = null;
170
+ }
171
+ return { conversationTitle, customTitle, customTitleBase };
172
+ }
173
+
161
174
  export function recordTelemetry(
162
175
  payload = {},
163
176
  {
@@ -165,6 +178,7 @@ export function recordTelemetry(
165
178
  git = null,
166
179
  stepTiming = null,
167
180
  prevSession = undefined,
181
+ tabSync = null,
168
182
  baseDir = configDir(homedir()),
169
183
  cacheTtlSec = 300,
170
184
  enableLedger = true,
@@ -376,15 +390,21 @@ export function recordTelemetry(
376
390
  const cacheRemainingSec =
377
391
  lastActivityAt !== null ? Math.max(0, Math.round((cacheTtlMs - (now - lastActivityAt)) / 1000)) : null;
378
392
 
379
- const conversationTitle = sanitizeText(p.conversation_title || '') || prev?.conversationTitle || null;
380
- // If user explicitly renamed the conversation via /rename (conversation_title changed),
381
- // clear any older custom tab override automatically.
382
- let customTitle = prev?.customTitle || null;
383
- let customTitleBase = prev?.customTitleBase ?? null;
384
- if (customTitle && conversationTitle && customTitleBase && conversationTitle !== customTitleBase) {
385
- customTitle = null;
386
- customTitleBase = null;
387
- }
393
+ const { conversationTitle, customTitle, customTitleBase } = resolveSessionTitles(p, prev);
394
+ const tabWritten = Boolean(tabSync?.written && tabSync.title);
395
+ const nextTabTitle = tabWritten ? tabSync.title : prev?.lastTabTitle || null;
396
+ const nextTabHostPid = tabWritten
397
+ ? (tabSync.hostPid ?? prev?.lastTabHostPid ?? null)
398
+ : (prev?.lastTabHostPid ?? null);
399
+ const nextTabTty = tabWritten
400
+ ? (tabSync.tty && tabSync.tty !== 'custom' ? tabSync.tty : prev?.lastTabTty ?? null)
401
+ : (prev?.lastTabTty ?? null);
402
+ const nextTabUpdatedAt = tabWritten ? now : prev?.lastTabUpdatedAt ?? null;
403
+ const nextTabError = tabWritten
404
+ ? null
405
+ : tabSync?.changed && !tabSync.written
406
+ ? tabSync.error || 'write_failed'
407
+ : prev?.lastTabError ?? null;
388
408
 
389
409
  const nextState = {
390
410
  sessionId,
@@ -409,8 +429,11 @@ export function recordTelemetry(
409
429
  conversationTitle,
410
430
  customTitle,
411
431
  customTitleBase,
412
- lastTabTitle: prev?.lastTabTitle || null,
413
- lastTabHostPid: prev?.lastTabHostPid ?? null,
432
+ lastTabTitle: nextTabTitle,
433
+ lastTabHostPid: nextTabHostPid,
434
+ lastTabTty: nextTabTty,
435
+ lastTabUpdatedAt: nextTabUpdatedAt,
436
+ lastTabError: nextTabError,
414
437
  model: modelName,
415
438
  effort: sanitizeText(p.model?.effort || '') || null,
416
439
  usedPct,
@@ -456,12 +479,17 @@ export function recordTelemetry(
456
479
  lastActivityAt,
457
480
  conversationTitle,
458
481
  customTitle,
459
- prevTabTitle: prev?.lastTabTitle || null,
460
- prevTabHostPid: prev?.lastTabHostPid ?? null,
482
+ prevTabTitle: nextTabTitle,
483
+ prevTabHostPid: nextTabHostPid,
484
+ prevTabTty: nextTabTty,
461
485
  };
462
486
  }
463
487
 
464
- export function updateSessionTabTitle(sessionId, tabTitle, { hostPid = null, baseDir = configDir(homedir()) } = {}) {
488
+ export function updateSessionTabTitle(
489
+ sessionId,
490
+ tabTitle,
491
+ { hostPid = null, tty = null, now = Date.now(), baseDir = configDir(homedir()) } = {},
492
+ ) {
465
493
  if (!sessionId) return false;
466
494
  const sFile = join(sessionsDir(baseDir), `${sessionId}.json`);
467
495
  const prev = readSessionFile(sFile);
@@ -469,7 +497,14 @@ export function updateSessionTabTitle(sessionId, tabTitle, { hostPid = null, bas
469
497
  try {
470
498
  writeFileAtomic(
471
499
  sFile,
472
- JSON.stringify({ ...prev, lastTabTitle: tabTitle, ...(hostPid !== null ? { lastTabHostPid: hostPid } : {}) }) + '\n',
500
+ JSON.stringify({
501
+ ...prev,
502
+ lastTabTitle: tabTitle,
503
+ lastTabUpdatedAt: now,
504
+ lastTabError: null,
505
+ ...(hostPid !== null ? { lastTabHostPid: hostPid } : {}),
506
+ ...(tty && tty !== 'custom' ? { lastTabTty: tty } : {}),
507
+ }) + '\n',
473
508
  );
474
509
  return true;
475
510
  } catch {
@@ -519,6 +554,7 @@ export function listSessions({ baseDir = configDir(homedir()), now = Date.now(),
519
554
  if (prune) {
520
555
  try {
521
556
  rmSync(full, { force: true });
557
+ rmSync(full.replace(/\.json$/, '.title'), { force: true });
522
558
  } catch {
523
559
  // Ignore prune errors.
524
560
  }
package/src/title.mjs ADDED
@@ -0,0 +1,136 @@
1
+ import { existsSync, readFileSync, realpathSync, writeFileSync, mkdirSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { sanitizeText } from './ansi.mjs';
6
+ import { configDir, loadConfig } from './config.mjs';
7
+ import { readGitInfo } from './git.mjs';
8
+ import { buildTabTitle } from './tab-title.mjs';
9
+ import { deriveSessionId, peekSessionState, resolveSessionTitles, sessionsDir } from './telemetry.mjs';
10
+
11
+ const NATIVE_TITLE_FRESH_MS = 60_000;
12
+ const NATIVE_TITLE_TOUCH_INTERVAL_MS = 120_000;
13
+
14
+ export function nativeTitleMarkerPath(sessionId, baseDir = configDir(homedir())) {
15
+ return join(sessionsDir(baseDir), `${sessionId}.title`);
16
+ }
17
+
18
+ export function touchNativeTitleMarker(
19
+ sessionId,
20
+ { now = Date.now(), hostPid = process.ppid, baseDir = configDir(homedir()) } = {},
21
+ ) {
22
+ if (!sessionId) return false;
23
+ const markerPath = nativeTitleMarkerPath(sessionId, baseDir);
24
+ try {
25
+ if (existsSync(markerPath)) {
26
+ const [rawTs, rawPid] = readFileSync(markerPath, 'utf8').trim().split(':');
27
+ const prevTs = Number(rawTs);
28
+ const prevPid = Number(rawPid);
29
+ if (
30
+ Number.isFinite(prevTs) &&
31
+ now - prevTs < NATIVE_TITLE_TOUCH_INTERVAL_MS &&
32
+ Number.isFinite(prevPid) &&
33
+ prevPid === hostPid
34
+ ) {
35
+ return true;
36
+ }
37
+ }
38
+ mkdirSync(dirname(markerPath), { recursive: true });
39
+ writeFileSync(markerPath, `${now}:${Number.isFinite(hostPid) ? hostPid : 0}\n`, 'utf8');
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ export function isNativeTitleActive(
47
+ sessionId,
48
+ { now = Date.now(), hostPid = process.ppid, baseDir = configDir(homedir()) } = {},
49
+ ) {
50
+ if (!sessionId) return false;
51
+ const markerPath = nativeTitleMarkerPath(sessionId, baseDir);
52
+ if (!existsSync(markerPath)) return false;
53
+ try {
54
+ const [rawTs, rawPid] = readFileSync(markerPath, 'utf8').trim().split(':');
55
+ const ts = Number(rawTs);
56
+ const pid = Number(rawPid);
57
+ if (!Number.isFinite(ts) || ts <= 0) return false;
58
+ const ageMs = now - ts;
59
+ if (ageMs < 0) return true;
60
+ if (ageMs < NATIVE_TITLE_FRESH_MS) return true;
61
+ if (ageMs < 24 * 60 * 60 * 1000 && Number.isFinite(pid) && pid > 1 && typeof hostPid === 'number' && pid === hostPid) {
62
+ return true;
63
+ }
64
+ return false;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ export function renderNativeTitle(
71
+ payload = {},
72
+ { config = loadConfig(), prevSession = undefined, baseDir = configDir(homedir()), now = Date.now(), hostPid = process.ppid, touchMarker = true } = {},
73
+ ) {
74
+ if (config.tabTitle === false) return '';
75
+
76
+ const p = payload && typeof payload === 'object' ? payload : {};
77
+ const sessionId = deriveSessionId(p);
78
+ const prev = prevSession !== undefined ? prevSession : peekSessionState(p, { baseDir });
79
+ const { customTitle } = resolveSessionTitles(p, prev);
80
+
81
+ const cwd = p?.workspace?.current_dir || p?.cwd || prev?.cwd || null;
82
+ const needsGit =
83
+ config.tabTitleSource === 'dir' ||
84
+ (!customTitle && !sanitizeText(p?.conversation_title || ''));
85
+ let git = null;
86
+ if (needsGit && cwd) {
87
+ if (prev && prev.cwd === cwd && prev.branch) {
88
+ git = { branch: prev.branch, dirty: Boolean(prev.dirty) };
89
+ } else {
90
+ // Zero-subprocess .git/HEAD lookup only.
91
+ git = readGitInfo(cwd, { checkDirty: false, checkDiff: false });
92
+ }
93
+ }
94
+
95
+ const title = buildTabTitle(p, { config, git, customTitle });
96
+ if (touchMarker) {
97
+ touchNativeTitleMarker(sessionId, { now, hostPid, baseDir });
98
+ }
99
+ return title ? sanitizeText(title).replace(/[\r\n\t]+/g, ' ') : '';
100
+ }
101
+
102
+ export async function runTitleCommand({
103
+ stdin = process.stdin,
104
+ stdout = process.stdout,
105
+ baseDir = configDir(homedir()),
106
+ config = undefined,
107
+ } = {}) {
108
+ let raw = '';
109
+ for await (const chunk of stdin) {
110
+ raw += chunk;
111
+ }
112
+
113
+ try {
114
+ const payload = raw.trim() ? JSON.parse(raw) : {};
115
+ const cfg = config ?? loadConfig();
116
+ const title = renderNativeTitle(payload, { config: cfg, baseDir });
117
+ if (title) {
118
+ stdout.write(`${title}\n`);
119
+ }
120
+ } catch {
121
+ // Never emit error noise into the terminal window title.
122
+ }
123
+ }
124
+
125
+ function isDirectInvocation() {
126
+ if (!process.argv[1]) return false;
127
+ try {
128
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
129
+ } catch {
130
+ return resolve(process.argv[1]) === fileURLToPath(import.meta.url);
131
+ }
132
+ }
133
+
134
+ if (isDirectInvocation()) {
135
+ await runTitleCommand();
136
+ }