sideby 0.38.1 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +6 -0
  3. package/dist/src/cli/commands.js +120 -1
  4. package/dist/src/cli/json-schemas.js +44 -2
  5. package/dist/src/cli/main.js +37 -0
  6. package/dist/src/core/cli-commands.js +26 -2
  7. package/dist/src/core/config.d.ts +14 -0
  8. package/dist/src/core/config.js +21 -0
  9. package/dist/src/core/launch.d.ts +5 -0
  10. package/dist/src/core/launch.js +11 -1
  11. package/dist/src/core/progress-state.d.ts +94 -0
  12. package/dist/src/core/progress-state.js +240 -0
  13. package/dist/src/core/progress.d.ts +36 -0
  14. package/dist/src/core/progress.js +77 -0
  15. package/dist/src/core/prompt-origin.d.ts +40 -0
  16. package/dist/src/core/prompt-origin.js +98 -0
  17. package/dist/src/core/search-catalog.js +43 -0
  18. package/dist/src/core/unattended-attended.d.ts +109 -0
  19. package/dist/src/core/unattended-attended.js +337 -0
  20. package/dist/src/core/unattended-pending.d.ts +14 -2
  21. package/dist/src/core/unattended-pending.js +27 -3
  22. package/dist/src/core/unattended-state.d.ts +19 -1
  23. package/dist/src/core/unattended-state.js +31 -5
  24. package/dist/src/core/unattended-wait.d.ts +86 -0
  25. package/dist/src/core/unattended-wait.js +125 -0
  26. package/dist/src/core/unattended.d.ts +29 -2
  27. package/dist/src/core/unattended.js +48 -6
  28. package/dist/src/handoff/hook.js +19 -4
  29. package/dist/src/network/hook.js +4 -8
  30. package/dist/src/panel/handler.d.ts +3 -0
  31. package/dist/src/panel/handler.js +31 -1
  32. package/dist/src/panel/i18n.d.ts +27 -0
  33. package/dist/src/panel/i18n.js +56 -2
  34. package/dist/src/panel/page-script.js +118 -4
  35. package/dist/src/panel/page-styles.js +21 -0
  36. package/dist/src/progress/hook.d.ts +57 -0
  37. package/dist/src/progress/hook.js +258 -0
  38. package/dist/src/runtime.d.ts +9 -0
  39. package/dist/src/runtime.js +45 -2
  40. package/dist/src/types.d.ts +5 -0
  41. package/dist/src/unattended/hook.d.ts +26 -6
  42. package/dist/src/unattended/hook.js +361 -25
  43. package/package.json +1 -1
  44. package/schemas/config.json +27 -0
  45. package/schemas/progress.json +137 -0
  46. package/schemas/unattended-defer.json +5 -0
  47. package/schemas/unattended-pending.json +5 -0
  48. package/schemas/unattended.json +54 -2
  49. package/skills/sideby/SKILL.md +4 -1
  50. package/skills/sideby/references/progress.md +25 -0
  51. package/skills/sideby/references/unattended.md +25 -3
@@ -12,15 +12,24 @@
12
12
  // written as plain text (`{"decision":"block","reason":…}` on stdout), keeping the question; and it declines an MCP
13
13
  // server's form, keeping what the server asked. In Claude it also runs in the background after a turn that failed for
14
14
  // a passing reason (`StopFailure`, `asyncRewake`): it waits, then wakes the session with exit 2 so the turn goes on, at
15
- // most three times in a row, and keeps a Pending Decision when that did not help (Turn Retry, ADR-0067). A failure
16
- // before the decision is made does nothing: that is
15
+ // most three times in a row, and keeps a Pending Decision when that did not help (Turn Retry, ADR-0067). And in Claude
16
+ // it runs in the background on every prompt (`UserPromptSubmit`, `async`): a prompt a person typed makes that session
17
+ // an Attended Session for 30 minutes, which it leaves alone as if the mode were off, telling the user once (ADR-0075).
18
+ // A question or a permission prompt Claude Code shows, in an Attended Session or while the mode is off, is watched in
19
+ // the background (Answer Wait, ADR-0077): once it has waited `unattended.answerWait` minutes with nobody answering and
20
+ // the mode is on, it is refused as the mode would refuse it, and so is a turn that ended on a question written as text
21
+ // (a second `Stop` entry, `asyncRewake`). It never answers anything with "yes".
22
+ // A failure before the decision is made does nothing: that is
17
23
  // how a session behaves without the feature (unlike `network-hook`, which blocks when it cannot tell). Once the
18
24
  // decision is to refuse, it refuses: keeping the Pending Decision and writing the reason are best effort, and their
19
25
  // failure neither allows the call nor adds any output of its own.
20
26
  import { resolvePaths } from '../core/paths.js';
21
- import { addPendingDecision } from '../core/unattended-pending.js';
27
+ import { hostMade, launchPrompt, sidebyMessage } from '../core/prompt-origin.js';
28
+ import { ATTENDED_MS, markAttended, markTold, ownTranscript, promptOrigin, readAttended, sessionUnattended, } from '../core/unattended-attended.js';
29
+ import { addPendingDecision, withdrawPendingDecision, } from '../core/unattended-pending.js';
22
30
  import { clearRetryStreak, countFailure, passingFailure, RETRY_LIMIT, readRetryStreak, retryDelay, retryGaveUpText, retryMessage, } from '../core/unattended-retry.js';
23
31
  import { clockText, readUnattendedConfig, readUnattendedOverride, UNATTENDED_ENV, unattendedState, } from '../core/unattended-state.js';
32
+ import { lastLook, waitedMinutes, watchScreen } from '../core/unattended-wait.js';
24
33
  export const UNATTENDED_HOOK_COMMAND = 'sideby unattended-hook';
25
34
  /** The tool each Host's model asks the user with. */
26
35
  export const ASK_TOOLS = {
@@ -103,21 +112,31 @@ export function questionText(input) {
103
112
  }
104
113
  return parts.join('\n\n') || JSON.stringify(input);
105
114
  }
106
- /** What the model reads instead of an answer. */
107
- export function questionReason(state, now, zh, kept) {
115
+ /**
116
+ * What the model reads instead of an answer. `waited`: the question was on screen this many minutes with nobody
117
+ * answering (Answer Wait); the session shows the text too, so it opens with what happened for the person coming back.
118
+ */
119
+ export function questionReason(state, now, zh, kept, waited) {
108
120
  const until = state.until ? clockText(Date.parse(state.until), now.getTime(), zh) : undefined;
109
121
  const session = state.reason === 'session';
110
122
  if (zh) {
111
123
  const when = session ? '(这个会话)' : until ? `(到 ${until})` : '(没有结束时间)';
112
124
  const keep = kept ? 'sideby 已把这个问题记下,等用户回来看' : 'sideby 没能记下这个问题,请写进最终汇报';
113
- return `未显示:sideby 无人值守已开启${when},现在没人能回答,${keep}。不要再问。能撤回的选择按推荐的选项继续,在最终汇报里写出这个问题和你的选择。删除、对外发送或发布、部署、付费等难撤回的操作不要做:跳过它,运行 \`sideby unattended defer "<一句话>"\` 记下,再继续做其余的事。`;
125
+ const head = waited
126
+ ? `${waited} 分钟没人回答:sideby 无人值守已开启${when},会话不再等回答,${keep}。`
127
+ : `未显示:sideby 无人值守已开启${when},现在没人能回答,${keep}。`;
128
+ return `${head}不要再问。能撤回的选择按推荐的选项继续,在最终汇报里写出这个问题和你的选择。删除、对外发送或发布、部署、付费等难撤回的操作不要做:跳过它,运行 \`sideby unattended defer "<一句话>"\` 记下,再继续做其余的事。`;
114
129
  }
115
130
  const when = session ? 'for this session' : until ? `until ${until}` : 'with no end set';
116
131
  const keep = kept
117
132
  ? 'sideby kept this question for the user to look at later'
118
133
  : 'sideby could not keep this question, so put it in your final report';
119
- return `Not shown: sideby's Unattended Mode is on ${when}, so nobody is here to answer, and ${keep}. Do not ask again. Where the choice can be undone, go on with the recommended option, and list the question and your choice in your final report. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and go on with the rest.`;
134
+ const head = waited
135
+ ? `No answer after ${minutesText(waited)}: sideby's Unattended Mode is on ${when}, so the session goes on without one, and ${keep}.`
136
+ : `Not shown: sideby's Unattended Mode is on ${when}, so nobody is here to answer, and ${keep}.`;
137
+ return `${head} Do not ask again. Where the choice can be undone, go on with the recommended option, and list the question and your choice in your final report. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and go on with the rest.`;
120
138
  }
139
+ const minutesText = (n) => (n === 1 ? '1 minute' : `${n} minutes`);
121
140
  /** How much of the end of the model's last message is read to tell whether it ends on a question. */
122
141
  export const QUESTION_TAIL = 600;
123
142
  /**
@@ -213,20 +232,29 @@ export function endingQuestion(message) {
213
232
  return question;
214
233
  return undefined;
215
234
  }
216
- /** What the model reads when it ended its turn on a question and nobody is here to answer. */
217
- export function stopReason(state, now, zh, kept) {
235
+ /**
236
+ * What the model reads when it ended its turn on a question and nobody is here to answer. `waited`: the question was
237
+ * left this many minutes with no reply (Answer Wait); this note then wakes the session, and is not the user's reply.
238
+ */
239
+ export function stopReason(state, now, zh, kept, waited) {
218
240
  const until = state.until ? clockText(Date.parse(state.until), now.getTime(), zh) : undefined;
219
241
  const session = state.reason === 'session';
220
242
  if (zh) {
221
243
  const when = session ? '(这个会话)' : until ? `(到 ${until})` : '(没有结束时间)';
222
244
  const keep = kept ? 'sideby 已把你的问题记下,等用户回来看' : 'sideby 没能记下你的问题,请写进最终汇报';
223
- return `没人能回答:sideby 无人值守已开启${when},${keep}。不要等回复,也不要再问。能撤回的选择按推荐的选项继续,一直做到完。删除、对外发送或发布、部署、付费等难撤回的操作不要做:跳过它,运行 \`sideby unattended defer "<一句话>"\` 记下,再做完其余的事。最后写一份最终汇报,列出你做的每个选择和记下的每件事,不提任何问题。`;
245
+ const head = waited
246
+ ? `${waited} 分钟没人回复你的问题:sideby 无人值守已开启${when},${keep}。这条不是用户的回复。`
247
+ : `没人能回答:sideby 无人值守已开启${when},${keep}。`;
248
+ return `${head}不要等回复,也不要再问。能撤回的选择按推荐的选项继续,一直做到完。删除、对外发送或发布、部署、付费等难撤回的操作不要做:跳过它,运行 \`sideby unattended defer "<一句话>"\` 记下,再做完其余的事。最后写一份最终汇报,列出你做的每个选择和记下的每件事,不提任何问题。`;
224
249
  }
225
250
  const when = session ? 'for this session' : until ? `until ${until}` : 'with no end set';
226
251
  const keep = kept
227
252
  ? 'sideby kept your question for the user to look at later'
228
253
  : 'sideby could not keep your question, so put it in your final report';
229
- return `Nobody is here to answer: sideby's Unattended Mode is on ${when}, and ${keep}. Do not wait for an answer and do not ask again. Where the choice can be undone, go on with the recommended option and carry on to the end. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and finish the rest. Then end with a final report that lists each choice you made and each item you recorded, without asking anything.`;
254
+ const head = waited
255
+ ? `Nobody replied to your question for ${minutesText(waited)}: sideby's Unattended Mode is on ${when}, and ${keep}. This note is not the user's reply.`
256
+ : `Nobody is here to answer: sideby's Unattended Mode is on ${when}, and ${keep}.`;
257
+ return `${head} Do not wait for an answer and do not ask again. Where the choice can be undone, go on with the recommended option and carry on to the end. Do not do anything hard to undo (deleting, sending or posting anything outside, publishing, deploying, paying): skip it, record it with \`sideby unattended defer "<one sentence>"\`, and finish the rest. Then end with a final report that lists each choice you made and each item you recorded, without asking anything.`;
230
258
  }
231
259
  /** What a declined MCP form is kept as: the server's name and what it asked, never a field's value. */
232
260
  export function elicitationText(v) {
@@ -319,15 +347,34 @@ export function permissionText(tool, input) {
319
347
  }
320
348
  return tool;
321
349
  }
322
- /** What the model reads instead of the permission prompt Claude Code would have shown. */
323
- export function permissionReason(state, now, kept) {
350
+ /**
351
+ * What the model reads instead of the permission prompt Claude Code would have shown. `waited`: the prompt was on
352
+ * screen this many minutes with nobody answering (Answer Wait).
353
+ */
354
+ export function permissionReason(state, now, kept, waited) {
324
355
  const until = state.until ? clockText(Date.parse(state.until), now.getTime(), false) : undefined;
325
356
  const when = state.reason === 'session' ? 'for this session' : until ? `until ${until}` : 'with no end set';
326
357
  const keep = kept ? ' sideby kept this request for the user to look at later.' : '';
327
- return `Not allowed: Claude Code wanted a person to confirm this action, and nobody is here (sideby's Unattended Mode is on ${when}).${keep} Rewrite it so it needs no confirmation: literal paths, "\${VAR:?}" for variables in rm targets, plain bash syntax, and rm as a command of its own. Or skip it, record it with \`sideby unattended defer "<what and why>"\`, and go on with the rest.`;
358
+ const head = waited
359
+ ? `Not allowed: nobody confirmed this action in ${minutesText(waited)}, and sideby's Unattended Mode is on ${when}.`
360
+ : `Not allowed: Claude Code wanted a person to confirm this action, and nobody is here (sideby's Unattended Mode is on ${when}).`;
361
+ return `${head}${keep} Rewrite it so it needs no confirmation: literal paths, "\${VAR:?}" for variables in rm targets, plain bash syntax, and rm as a command of its own. Or skip it, record it with \`sideby unattended defer "<what and why>"\`, and go on with the rest.`;
362
+ }
363
+ /**
364
+ * What the user reads once in an Attended Session while Unattended Mode is on (ADR-0075), as a `systemMessage`: shown
365
+ * in the session, never to the model.
366
+ */
367
+ export function attendedNotice(state, zh) {
368
+ const session = state.reason === 'session';
369
+ if (zh)
370
+ return `sideby:你在,这个会话在你最后一条消息后 30 分钟内照常问你。${session ? '它是按无人值守启动的,30 分钟没人打字后恢复。' : '其他会话仍然无人值守。要全部关掉,运行 `sideby unattended off`。'}`;
371
+ return `sideby: you're here, so this session asks you as usual for 30 minutes after your last message. ${session ? 'It was started unattended, and goes back to that once nobody has typed for 30 minutes.' : 'Other sessions stay unattended. To turn Unattended Mode off everywhere, run `sideby unattended off`.'}`;
328
372
  }
329
- /** What to do with this call: undefined allows it. Any error here allows it too (the caller catches it). */
330
- async function decide(argv, env, input, now) {
373
+ /**
374
+ * What to do with this call: undefined allows it. Any error here allows it too (the caller catches it). A permission
375
+ * request (in Claude, also the ask tool's) that is not refused at once may first wait for a person (Answer Wait).
376
+ */
377
+ async function decide(argv, env, input, now, deps) {
331
378
  const [family = '', event = ''] = argv;
332
379
  const askTool = ASK_TOOLS[family];
333
380
  const permission = family === 'claude' && event === 'PermissionRequest';
@@ -345,19 +392,45 @@ async function decide(argv, env, input, now) {
345
392
  if (sessionId)
346
393
  await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
347
394
  }
348
- const { schedule } = await readUnattendedConfig(paths.configFile);
395
+ const { schedule, answerWait } = await readUnattendedConfig(paths.configFile);
349
396
  const override = await readUnattendedOverride(paths.stateDir);
350
397
  const state = unattendedState({ schedule, override, now, session: env[UNATTENDED_ENV] === '1' });
351
- if (!state.on)
398
+ // Answer Wait: what Claude Code shows is watched while the mode is off too, since it may come on before anyone answers.
399
+ const watch = permission && answerWait !== null;
400
+ if (!state.on && !watch)
352
401
  return undefined;
353
402
  const raw = early ?? (await readInput(input));
354
403
  const zh = prefersChinese(env);
355
404
  const account = text(env.SIDEBY_ACCOUNT, 256);
405
+ /**
406
+ * An Attended Session (ADR-0075) is left alone, as when the mode is off: undefined while the session is not one.
407
+ * Where a `systemMessage` reaches the user (`Stop`, the ask tool's `PreToolUse`), the first such call of a stretch
408
+ * tells them once.
409
+ */
410
+ const attended = async (sessionId, tell) => {
411
+ if (family !== 'claude' || !sessionId)
412
+ return undefined;
413
+ const r = await readAttended(paths.stateDir, sessionId, now);
414
+ if (!r)
415
+ return undefined;
416
+ if (!tell || r.toldAt)
417
+ return {};
418
+ return {
419
+ answer: {
420
+ json: (systemMessage) => ({ systemMessage }),
421
+ reason: () => attendedNotice(state, zh),
422
+ keep: () => markTold(paths.stateDir, sessionId, r.since, now),
423
+ },
424
+ };
425
+ };
356
426
  if (stop || elicitation) {
357
427
  const v = parseObject(raw);
358
428
  if (!v)
359
429
  return undefined;
360
430
  const sessionId = text(v.session_id, 256);
431
+ const here = await attended(sessionId, stop);
432
+ if (here)
433
+ return here.answer;
361
434
  const cwd = text(v.cwd);
362
435
  const where = {
363
436
  family,
@@ -391,6 +464,17 @@ async function decide(argv, env, input, now) {
391
464
  const payload = parsePayload(raw);
392
465
  if (!payload)
393
466
  return undefined;
467
+ if (permission) {
468
+ // Asked in front of someone (an Attended Session) or while the mode is off: shown, and watched while it waits.
469
+ const shown = state.on ? await attended(payload.sessionId, false) : {};
470
+ if (shown)
471
+ return watch ? answerAfterWait(payload, env, now.getTime(), deps) : undefined;
472
+ }
473
+ else if (payload.tool === askTool) {
474
+ const here = await attended(payload.sessionId, true);
475
+ if (here)
476
+ return here.answer;
477
+ }
394
478
  if (permission)
395
479
  return {
396
480
  json: (message) => ({
@@ -431,6 +515,24 @@ async function decide(argv, env, input, now) {
431
515
  * record.
432
516
  */
433
517
  export async function runUnattendedHook(argv, env, input, io, deps = {}) {
518
+ if (argv[0] === 'claude' && argv[1] === 'UserPromptSubmit') {
519
+ // In the background: its output and exit code change nothing, and it never holds a prompt back.
520
+ await notePrompt(env, input, deps).catch(() => { });
521
+ return 0;
522
+ }
523
+ if (argv[0] === 'claude' && argv[1] === 'StopWait') {
524
+ // In the background (`asyncRewake`): exit 2 wakes the idle session with the note on stderr.
525
+ try {
526
+ const wake = await wakeAfterWait(env, input, deps);
527
+ if (!wake)
528
+ return 0;
529
+ io.err.write(`${wake}\n`);
530
+ return 2;
531
+ }
532
+ catch {
533
+ return 0;
534
+ }
535
+ }
434
536
  if (argv[0] === 'claude' && argv[1] === 'StopFailure') {
435
537
  try {
436
538
  const wake = await retryAfterFailure(env, input, deps);
@@ -446,7 +548,7 @@ export async function runUnattendedHook(argv, env, input, io, deps = {}) {
446
548
  let refusal;
447
549
  const now = deps.now ? deps.now() : new Date();
448
550
  try {
449
- refusal = await decide(argv, env, input, now);
551
+ refusal = await decide(argv, env, input, now, deps);
450
552
  }
451
553
  catch {
452
554
  return 0;
@@ -479,12 +581,246 @@ export async function runUnattendedHook(argv, env, input, io, deps = {}) {
479
581
  }
480
582
  return 2;
481
583
  }
482
- /** Whether Unattended Mode is on right now, read fresh from the Schedule and the manual state. */
483
- async function isOn(env, now) {
584
+ /**
585
+ * Whether the session is unattended right now: Unattended Mode is on, read fresh from the Schedule and the manual
586
+ * state, and the session is not an Attended Session.
587
+ */
588
+ async function isOn(env, now, sessionId) {
589
+ const paths = resolvePaths(env);
590
+ return (await sessionUnattended({
591
+ stateDir: paths.stateDir,
592
+ configFile: paths.configFile,
593
+ session: env[UNATTENDED_ENV] === '1',
594
+ sessionId,
595
+ now,
596
+ })).on;
597
+ }
598
+ /** Unattended Mode for the whole computer (or this `--unattended` session) at `at`, read fresh; an Attended Session counts as on. */
599
+ async function modeAt(env, at) {
484
600
  const paths = resolvePaths(env);
485
- const { schedule } = await readUnattendedConfig(paths.configFile);
601
+ const { schedule, answerWait } = await readUnattendedConfig(paths.configFile);
486
602
  const override = await readUnattendedOverride(paths.stateDir);
487
- return unattendedState({ schedule, override, now, session: env[UNATTENDED_ENV] === '1' }).on;
603
+ return {
604
+ state: unattendedState({ schedule, override, now: at, session: env[UNATTENDED_ENV] === '1' }),
605
+ answerWait,
606
+ };
607
+ }
608
+ /** The clock, the wait and the Host, as Answer Wait's watches use them. */
609
+ function waitTools(deps) {
610
+ const clock = () => (deps.now ? deps.now() : new Date()).getTime();
611
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
612
+ const startPpid = process.ppid;
613
+ const parentGone = deps.parentGone ?? (() => process.ppid !== startPpid || process.ppid === 1);
614
+ return { clock, sleep, parentGone, pid: deps.hostPid ?? startPpid };
615
+ }
616
+ /**
617
+ * Watches what the session shows (`watchScreen`), then keeps the Pending Decision only while it is still so: one last
618
+ * look just before keeping and again after, with the wait and the mode read afresh (a person may answer meanwhile, the
619
+ * mode go off, or the wait be made longer). When the dialog ended or the wait is now never, nothing is decided
620
+ * (undefined); when the longer wait has not passed or the mode is off, it goes on watching the same dialog. A decision
621
+ * kept before such a change is taken back. Otherwise what the hook answers with: when it went on (`at`), how long it
622
+ * waited, the mode then, and whether the decision was kept. What is left is the moment between the last look and the
623
+ * Host reading the answer: a person who answers then has their answer applied and a denial that comes after it
624
+ * changes nothing (ADR-0077); a wake-up is told it is not their reply.
625
+ */
626
+ async function actAfterWait(opts) {
627
+ const { env, deps, sessionId } = opts;
628
+ const t = waitTools(deps);
629
+ const settings = async () => {
630
+ const m = await modeAt(env, new Date(t.clock()));
631
+ return { wait: m.answerWait, on: m.state.on };
632
+ };
633
+ const look = {
634
+ env,
635
+ pid: t.pid,
636
+ sessionId,
637
+ startedAt: opts.start,
638
+ clock: t.clock,
639
+ parentGone: t.parentGone,
640
+ settings,
641
+ ...(opts.moved ? { moved: opts.moved } : {}),
642
+ };
643
+ const stateDir = resolvePaths(env).stateDir;
644
+ let mark;
645
+ for (;;) {
646
+ mark = await watchScreen({
647
+ ...look,
648
+ expect: opts.expect,
649
+ sleep: t.sleep,
650
+ ...(opts.shownBy !== undefined ? { shownBy: opts.shownBy } : {}),
651
+ ...(mark ? { from: mark } : {}),
652
+ });
653
+ if (!mark)
654
+ return undefined;
655
+ await deps.beforeAct?.();
656
+ const first = await lastLook({ ...look, mark });
657
+ if (first === 'stop')
658
+ return undefined;
659
+ if (first === 'wait')
660
+ continue;
661
+ const at = new Date(t.clock());
662
+ const waited = waitedMinutes(opts.start, at.getTime());
663
+ const { state } = await modeAt(env, at);
664
+ let kept;
665
+ try {
666
+ kept = await addPendingDecision(stateDir, opts.keep(at, waited), at, { dedupe: true });
667
+ }
668
+ catch {
669
+ // Best effort: the reason then asks for it in the final report instead.
670
+ }
671
+ await deps.afterKeep?.();
672
+ const second = await lastLook({ ...look, mark });
673
+ if (second === 'act')
674
+ return { at, waited, state, kept: kept !== undefined };
675
+ if (kept)
676
+ await withdrawPendingDecision(stateDir, kept, at).catch(() => { });
677
+ if (second === 'stop')
678
+ return undefined;
679
+ }
680
+ }
681
+ /**
682
+ * Answer Wait for a question or a permission prompt Claude Code shows (spec §3.37 item 7, ADR-0077): watches the
683
+ * session record while the dialog stays on screen and, once it has waited `unattended.answerWait` minutes and
684
+ * Unattended Mode is on (counting an Attended Session as on: nobody answered), refuses it as the mode would, keeping a
685
+ * Pending Decision with how long it waited. Anything that says someone answered, or that it cannot tell, lets it be
686
+ * (undefined): the record does not show a dialog (a subagent's request, which Claude Code shows only after the hooks,
687
+ * or a session that shows none), the dialog ended or another took its place, the Host is gone, or the wait is now
688
+ * never; looked at once more just before and after keeping the Pending Decision (`actAfterWait`); a dialog put on screen
689
+ * after the hook began is another one (this one was answered meanwhile) and is never taken for it. It never answers
690
+ * "yes": the only decision it gives is a denial.
691
+ */
692
+ async function answerAfterWait(payload, env, start, deps) {
693
+ // Claude Code runs a subagent's hooks before it shows the prompt: holding one would hide it from the person.
694
+ if (payload.agentId || !payload.sessionId)
695
+ return undefined;
696
+ const sessionId = payload.sessionId;
697
+ const account = text(env.SIDEBY_ACCOUNT, 256);
698
+ const where = {
699
+ family: 'claude',
700
+ ...(account ? { account } : {}),
701
+ sessionId,
702
+ ...(payload.cwd ? { cwd: payload.cwd } : {}),
703
+ };
704
+ const question = payload.tool === ASK_TOOLS.claude;
705
+ const done = await actAfterWait({
706
+ env,
707
+ deps,
708
+ sessionId,
709
+ expect: 'waiting',
710
+ start,
711
+ // The dialog this request put on screen was there before the hook began; one put up later is another dialog.
712
+ shownBy: start,
713
+ keep: (_at, waited) => question
714
+ ? { kind: 'question', ...where, text: questionText(payload.input), waited }
715
+ : { kind: 'permission', ...where, text: permissionText(payload.tool, payload.input), waited },
716
+ });
717
+ if (!done)
718
+ return undefined;
719
+ const { at, waited, state, kept } = done;
720
+ const deny = (message) => ({
721
+ hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny', message } },
722
+ });
723
+ // Kept already (and checked after): the answer only says whether that worked.
724
+ return {
725
+ json: deny,
726
+ reason: () => question
727
+ ? questionReason(state, at, prefersChinese(env), kept, waited)
728
+ : permissionReason(state, at, kept, waited),
729
+ };
730
+ }
731
+ /**
732
+ * Answer Wait for a turn that ended on a question written as text (spec §3.37 item 7, ADR-0077): Claude's second `Stop`
733
+ * entry, in the background (`asyncRewake`). When the session is not unattended right now (the mode is off, or it is an
734
+ * Attended Session: otherwise the first `Stop` entry already keeps the turn going) and the last message ends on a
735
+ * question, it watches the session record while the session waits for a prompt. Once nobody replied for
736
+ * `unattended.answerWait` minutes and the mode is on, it keeps the question as a Pending Decision and returns the note
737
+ * that wakes the session (exit 2). A new turn (a reply, a notification), a prompt someone typed after this `Stop` (the
738
+ * Attended Session's record, which also catches a reply whose turn ended before this hook first read the record), the
739
+ * Host gone, the wait set to never, or anything it cannot tell: undefined, nothing happens.
740
+ */
741
+ async function wakeAfterWait(env, input, deps) {
742
+ const t = waitTools(deps);
743
+ const start = t.clock();
744
+ const v = parseObject(await readInput(input));
745
+ // Only a first Stop (`stop_hook_active` false) of the main session.
746
+ if (v?.stop_hook_active !== false || v.agent_id !== undefined)
747
+ return undefined;
748
+ const sessionId = text(v.session_id, 256);
749
+ const message = typeof v.last_assistant_message === 'string' ? v.last_assistant_message : '';
750
+ const question = sessionId ? endingQuestion(message) : undefined;
751
+ if (!sessionId || !question)
752
+ return undefined;
753
+ if ((await modeAt(env, new Date(start))).answerWait === null)
754
+ return undefined;
755
+ if (await isOn(env, new Date(start), sessionId))
756
+ return undefined;
757
+ const stateDir = resolvePaths(env).stateDir;
758
+ // Someone typed after this Stop: the question is answered, even when that turn already ended.
759
+ const moved = async () => {
760
+ const r = await readAttended(stateDir, sessionId, new Date(t.clock()));
761
+ return r !== undefined && Date.parse(r.at) > start;
762
+ };
763
+ const account = text(env.SIDEBY_ACCOUNT, 256);
764
+ const cwd = text(v.cwd);
765
+ const done = await actAfterWait({
766
+ env,
767
+ deps,
768
+ sessionId,
769
+ expect: 'idle',
770
+ start,
771
+ moved,
772
+ keep: (_at, waited) => ({
773
+ kind: 'question',
774
+ family: 'claude',
775
+ ...(account ? { account } : {}),
776
+ sessionId,
777
+ ...(cwd ? { cwd } : {}),
778
+ text: question,
779
+ waited,
780
+ }),
781
+ });
782
+ if (!done)
783
+ return undefined;
784
+ return stopReason(done.state, done.at, prefersChinese(env), done.kept, done.waited);
785
+ }
786
+ /** A prompt id as Claude Code writes it; anything else is not looked for. */
787
+ const PROMPT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
788
+ /**
789
+ * Claude's background `UserPromptSubmit` entry (spec §3.37 "有人在的会话", ADR-0075): makes the session an Attended
790
+ * Session when a person typed the prompt. Not counted: a prompt Claude Code made itself, a Message `sideby send`
791
+ * delivered, a prompt sideby put on the command line (or a session whose launch did not say which those are), a
792
+ * subagent's, and any prompt whose line in the session's own transcript does not say `human` within the wait. The
793
+ * transcript line decides, not the input: its text is checked as the prompt is, and its time is when the stretch is
794
+ * counted from, so an input made by hand that names another file, the launch's prompt or an old prompt marks nothing
795
+ * new. Nothing of the prompt is kept.
796
+ */
797
+ async function notePrompt(env, input, deps) {
798
+ const v = parseObject(await readInput(input));
799
+ if (!v || v.agent_id !== undefined)
800
+ return;
801
+ const sessionId = text(v.session_id, 256);
802
+ const promptId = typeof v.prompt_id === 'string' && PROMPT_ID.test(v.prompt_id) ? v.prompt_id : undefined;
803
+ const prompt = typeof v.prompt === 'string' ? v.prompt : undefined;
804
+ const transcript = typeof v.transcript_path === 'string' ? v.transcript_path : undefined;
805
+ if (!sessionId || !promptId || prompt === undefined || !transcript)
806
+ return;
807
+ const notTyped = (s) => hostMade(s) || sidebyMessage(s) || launchPrompt(s, env);
808
+ if (notTyped(prompt) || !(await ownTranscript(transcript, sessionId, env)))
809
+ return;
810
+ const clock = deps.now ?? (() => new Date());
811
+ const line = await promptOrigin(transcript, promptId, {
812
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
813
+ clock: () => clock().getTime(),
814
+ });
815
+ if (line?.origin !== 'human' || line.text === undefined || line.at === undefined || notTyped(line.text))
816
+ return;
817
+ const now = clock().getTime();
818
+ const at = Math.min(line.at, now);
819
+ if (at + ATTENDED_MS <= now)
820
+ return;
821
+ const account = text(env.SIDEBY_ACCOUNT, 256);
822
+ const cwd = text(v.cwd);
823
+ await markAttended(resolvePaths(env).stateDir, { sessionId, family: 'claude', ...(account ? { account } : {}), ...(cwd ? { cwd } : {}) }, new Date(at));
488
824
  }
489
825
  /**
490
826
  * Turn Retry (spec §3.37 item 6, ADR-0067), Claude's background `StopFailure` hook (`asyncRewake`): Claude Code runs it
@@ -509,7 +845,7 @@ async function retryAfterFailure(env, input, deps) {
509
845
  const said = [text(v.last_assistant_message, 1000), text(v.error_details, 1000)].filter(Boolean).join(' ');
510
846
  // A later failure that is not retried (a used-up Quota, a lasting error) or comes while the mode is off still
511
847
  // takes over the session: the wait an earlier failure left must not wake it.
512
- if (!error || !passingFailure(error, said) || !(await isOn(env, now))) {
848
+ if (!error || !passingFailure(error, said) || !(await isOn(env, now, sessionId))) {
513
849
  await clearRetryStreak(paths.stateDir, sessionId).catch(() => { });
514
850
  return undefined;
515
851
  }
@@ -534,7 +870,7 @@ async function retryAfterFailure(env, input, deps) {
534
870
  return undefined;
535
871
  if ((await readRetryStreak(paths.stateDir, sessionId))?.token !== streak.token)
536
872
  return undefined;
537
- if (!(await isOn(env, clock())))
873
+ if (!(await isOn(env, clock(), sessionId)))
538
874
  return undefined;
539
875
  return retryMessage(error, text(v.last_assistant_message, 1000) ?? '', streak.count, prefersChinese(env));
540
876
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.38.1",
3
+ "version": "0.40.0",
4
4
  "description": "Run work, personal and API-key accounts at the same time, without their configs drifting apart.",
5
5
  "license": "MIT",
6
6
  "author": "Adonis0123 (https://github.com/Adonis0123)",
@@ -500,11 +500,38 @@
500
500
  "additionalProperties": false
501
501
  },
502
502
  "description": "Slots that turn Unattended Mode on and off by themselves, in this computer's time zone. Empty by default."
503
+ },
504
+ "answerWait": {
505
+ "anyOf": [
506
+ {
507
+ "type": "integer",
508
+ "minimum": 1,
509
+ "maximum": 120
510
+ },
511
+ {
512
+ "type": "boolean",
513
+ "const": false
514
+ }
515
+ ],
516
+ "description": "Answer Wait (ADR-0077): how many minutes a question or a permission prompt shown in a Claude session sideby started waits for a person. Once it has waited this long with nobody answering and Unattended Mode is on, the session goes on as Unattended Mode would: the question with the recommended choice where it can be undone, the permission prompt refused (never allowed); each is kept as a Pending Decision. A turn that ended on a question written as text goes on the same way. `false`: never, questions wait for you. Not set: 10 minutes."
503
517
  }
504
518
  },
505
519
  "additionalProperties": false,
506
520
  "description": "Unattended Mode (spec §3.37, ADR-0058): while it is on, sessions sideby starts never stop to wait for a person. Present once the feature is used; from then on sideby adds its hook to every Claude and Codex session it starts, so turning it on later covers sessions already running. `sideby config unset unattended` stops adding it."
507
521
  },
522
+ "progress": {
523
+ "type": "object",
524
+ "properties": {
525
+ "every": {
526
+ "type": "integer",
527
+ "minimum": 1,
528
+ "maximum": 240,
529
+ "description": "Progress Reminders: while a Claude session sideby started waits on background work (subagents, background commands), wake it every this many minutes so the model tells you in one or two sentences what it waits for. Each reminder is one model turn over the whole conversation, so it uses quota. Not set: off (the default). Sessions started afterwards get it; turning it off or changing the interval also reaches running sessions. Not while the session is unattended; Codex is not covered."
530
+ }
531
+ },
532
+ "additionalProperties": false,
533
+ "description": "Progress Reminders (spec §3.42, ADR-0076)."
534
+ },
508
535
  "browser": {
509
536
  "type": "object",
510
537
  "properties": {