pi-cue 0.1.0 → 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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # pi-cue
2
2
 
3
- **A tap on your wrist when pi is done, or needs you.**
3
+ **A notification on your iPhone when pi is done, or needs you.**
4
4
 
5
- Pushes to your iPhone and Apple Watch through [Bark](https://github.com/Finb/Bark), but only when you are away. If you are at the keyboard, nothing happens.
5
+ Sent through [Bark](https://github.com/Finb/Bark), and only when you are away: if you are at the keyboard, nothing happens. While the iPhone is locked, it reaches your Apple Watch too.
6
6
 
7
7
  ## Setup
8
8
 
@@ -14,7 +14,7 @@ The key is stored in `~/.pi/agent/cue.json` (mode 600). `PI_CUE_KEY` and `PI_CUE
14
14
 
15
15
  ## Use
16
16
 
17
- Cues are **off** in every session until you turn them on, so parallel sessions don't all tap you.
17
+ Cues are **off** in every session until you turn them on, so parallel sessions don't all notify you.
18
18
 
19
19
  | | |
20
20
  |---|---|
@@ -29,12 +29,18 @@ While on, `cue` shows in the status line.
29
29
 
30
30
  | | When | Level |
31
31
  |---|---|---|
32
- | `● repo` · Needs you | pi waits on a confirm / select / input for 8s | time-sensitive |
32
+ | `● repo` · Needs you | pi waits on a confirm / select / input for 8s, or the reply ends on a question | time-sensitive |
33
33
  | `● repo` · Still waiting | the same decision is still open after 10 min (once) | time-sensitive |
34
34
  | `✗ repo` · Failed | a run failed | time-sensitive |
35
- | `✓ repo` · Done · 3m12s | a run of 30s or more finished, 15s ago | normal |
35
+ | `✓ repo` · Done · 3m12s | pi stopped 15s ago, and you had been away 30s or more | normal |
36
36
 
37
- The body is the question, the error, or the first line of the answer.
37
+ The body is the question, the error, or the first line of the answer. The time is how long since you last touched pi.
38
+
39
+ ## Background subagents
40
+
41
+ When a background subagent wakes the agent for a quick wrap-up, that still cues: away time counts from your last key press, not from the start of the run. A subagent's question, relayed by the agent as a reply ending in `?`, cues as *Needs you*.
42
+
43
+ pi does not tell extensions about background work, so the turn that dispatches subagents cues once as *Done* (the body usually says what was dispatched), and each subagent that wakes the agent replaces that notification and alerts again.
38
44
 
39
45
  ## Quiet by design
40
46
 
@@ -43,8 +49,6 @@ The body is the question, the error, or the first line of the answer.
43
49
  - **Cleans up.** Answering, typing, starting a new run, or quitting removes the notification from the phone and watch. Removal needs Bark's *Background App Refresh*.
44
50
  - **Never in the way.** Network errors are swallowed. Nested and headless sessions never cue.
45
51
 
46
- The Watch only gets iPhone notifications while the iPhone is locked.
47
-
48
52
  ## Config
49
53
 
50
54
  `~/.pi/agent/cue.json`, all optional except `key`:
@@ -62,7 +66,7 @@ The Watch only gets iPhone notifications while the iPhone is locked.
62
66
  }
63
67
  ```
64
68
 
65
- `"default": "on"` (or `PI_CUE=1`) starts new sessions with cues on. `"detail": false` sends only the project and state, never text from the session; worth it on the public Bark server. `remindMs: 0` disables the reminder.
69
+ `"default": "on"` (or `PI_CUE=1`) starts new sessions with cues on. `"detail": false` sends only the project and state, never text from the session; worth it on the public Bark server. `remindMs: 0` disables the reminder. `minRunMs` is the away time needed before *Done* or a question cues.
66
70
 
67
71
  ## Development
68
72
 
package/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * pi-cue: a tap on the wrist when pi is done, or needs you.
2
+ * pi-cue: a phone notification when pi is done, or needs you.
3
3
  *
4
4
  * Off by default per session; `/cue` turns it on for the current one.
5
5
  * All logic lives in src/core.ts; this file only wires pi events to it.
@@ -7,7 +7,7 @@
7
7
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
8
  import { type Config, loadConfig, parseKey, push, remove, saveKey } from "./src/bark.ts";
9
9
  import { type Cue, createCue, isHumanKey, type Note } from "./src/core.ts";
10
- import { isChinese, render, repoName } from "./src/text.ts";
10
+ import { isChinese, question, render, repoName } from "./src/text.ts";
11
11
 
12
12
  const ENTRY = "pi-cue";
13
13
  const STATUS = "cue";
@@ -42,7 +42,7 @@ export default function piCue(pi: ExtensionAPI): void {
42
42
  now: Date.now,
43
43
  after(ms, fn) {
44
44
  const t = setTimeout(fn, ms);
45
- t.unref?.(); // never keep pi alive for a tap
45
+ t.unref?.(); // never keep pi alive for a notification
46
46
  return () => clearTimeout(t);
47
47
  },
48
48
  send(note: Note) {
@@ -77,7 +77,7 @@ export default function piCue(pi: ExtensionAPI): void {
77
77
  cwd = ctx.cwd;
78
78
  sessionId = ctx.sessionManager.getSessionId().slice(0, 8);
79
79
  last = { failed: false, text: "" };
80
- if (!ctx.hasUI) return; // nested and headless sessions never tap
80
+ if (!ctx.hasUI) return; // nested and headless sessions never notify
81
81
  unlisten = ctx.ui.onTerminalInput((data) => {
82
82
  if (isHumanKey(data)) cue.input();
83
83
  return undefined;
@@ -103,7 +103,12 @@ export default function piCue(pi: ExtensionAPI): void {
103
103
 
104
104
  pi.on("agent_settled", (e, ctx) => {
105
105
  cwd = ctx.cwd;
106
- cue.settled({ aborted: e.aborted, failed: last.failed, text: last.text });
106
+ cue.settled({
107
+ aborted: e.aborted,
108
+ failed: last.failed,
109
+ text: last.text,
110
+ question: last.failed ? undefined : question(last.text),
111
+ });
107
112
  });
108
113
 
109
114
  pi.on("ui_prompt_start", (e) => cue.promptStart(e.title));
@@ -130,11 +135,11 @@ export default function piCue(pi: ExtensionAPI): void {
130
135
  cue.setEnabled(on);
131
136
  pi.appendEntry(ENTRY, { on });
132
137
  showStatus(ctx);
133
- say(ctx, on ? (zh ? "cue 已开启:完成或需要你时会推送" : "cue on: you will be tapped when pi is done or needs you") : zh ? "cue 已关闭" : "cue off");
138
+ say(ctx, on ? (zh ? "cue 已开启:完成或需要你时会推送" : "cue on: you will be notified when pi is done or needs you") : zh ? "cue 已关闭" : "cue off");
134
139
  };
135
140
 
136
141
  pi.registerCommand("cue", {
137
- description: "Tap on the wrist when pi is done or needs you (on | off | test | key <key>)",
142
+ description: "Notify your phone when pi is done or needs you (on | off | test | key <key>)",
138
143
  getArgumentCompletions: (prefix) =>
139
144
  ["on", "off", "test", "key", "status"].filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s })),
140
145
  handler: async (args, ctx) => {
@@ -155,7 +160,8 @@ export default function piCue(pi: ExtensionAPI): void {
155
160
  }
156
161
  case "test": {
157
162
  if (!cfg.key) return say(ctx, zh ? "还没有 key,先运行 /cue key" : "No key yet. Run /cue key first.", "warning");
158
- const m = render({ kind: "done", elapsedMs: 83_000, text: zh ? "这是一条测试" : "This is a test" }, cwd, { zh, detail: true });
163
+ // Always English: a test is often sent to show someone else what a cue looks like.
164
+ const m = render({ kind: "done", elapsedMs: 83_000, text: "Test notification from pi-cue. You are all set." }, cwd, { zh: false, detail: true });
159
165
  const ok = await push(cfg, { id: `${id()}-test`, group: repoName(cwd), ...m });
160
166
  return say(ctx, ok ? (zh ? "已发送" : "Sent") : zh ? "发送失败,检查 key 和网络" : "Send failed; check the key and network", ok ? "info" : "error");
161
167
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-cue",
3
- "version": "0.1.0",
4
- "description": "A tap on your wrist when pi is done, or needs you. Bark push to iPhone and Apple Watch, only when you are away.",
3
+ "version": "0.1.2",
4
+ "description": "Get a notification on your iPhone (and Apple Watch) when pi is done or needs you, only when you are away. Uses Bark.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "purboo",
package/src/bark.ts CHANGED
@@ -98,7 +98,7 @@ async function post(cfg: Config, payload: Record<string, unknown>, fetcher: type
98
98
  });
99
99
  return res.ok;
100
100
  } catch {
101
- return false; // best effort: a missed tap must never disturb pi
101
+ return false; // best effort: a missed notification must never disturb pi
102
102
  }
103
103
  }
104
104
 
package/src/core.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * The decision logic, free of pi and the network. Everything time-related and
3
3
  * every side effect is injected, so it can be tested with a fake clock.
4
4
  *
5
- * The rule of thumb: a cue is a tap on the wrist, so it must only fire when
5
+ * The rule of thumb: a cue interrupts you, so it must only fire when
6
6
  * you are away. Every cue therefore waits a grace period, and is dropped if
7
7
  * you touched the keyboard around that time or the situation resolved itself.
8
8
  */
@@ -11,7 +11,7 @@ export type Kind = "done" | "fail" | "ask";
11
11
 
12
12
  export interface Note {
13
13
  kind: Kind;
14
- /** Run duration (done/fail) or time spent waiting (reminder). */
14
+ /** Time since you last touched pi (done/fail/ask), or time spent waiting (reminder). */
15
15
  elapsedMs?: number;
16
16
  /** One-line detail: result summary, error, or the question being asked. */
17
17
  text?: string;
@@ -24,7 +24,10 @@ export interface Timing {
24
24
  graceMs: number;
25
25
  /** Wait before announcing a decision; shorter, because the agent is blocked. */
26
26
  askGraceMs: number;
27
- /** Runs shorter than this are not worth a cue (failures always are). */
27
+ /**
28
+ * Only cue once you have been away this long, counted from your last key press,
29
+ * so a quick wrap-up run woken by a background subagent still counts. Failures always cue.
30
+ */
28
31
  minRunMs: number;
29
32
  /** Nudge once more if a decision is still open after this long. 0 = never. */
30
33
  remindMs: number;
@@ -58,8 +61,11 @@ export interface Cue {
58
61
  input(): void;
59
62
  /** `agent_start`. */
60
63
  runStart(): void;
61
- /** `agent_settled`. */
62
- settled(run: { aborted: boolean; failed: boolean; text?: string }): void;
64
+ /**
65
+ * `agent_settled`. `question` is set when the reply ends by asking you something:
66
+ * the ball is in your court, so it cues like a dialog does.
67
+ */
68
+ settled(run: { aborted: boolean; failed: boolean; text?: string; question?: string }): void;
63
69
  promptStart(title?: string): void;
64
70
  promptEnd(): void;
65
71
  /** New session in the same process: forget everything, touch nothing remote. */
@@ -72,7 +78,8 @@ export function createCue(deps: Deps, timing: Timing = DEFAULT_TIMING): Cue {
72
78
  let startedAt: number | null = null;
73
79
  let depth = 0;
74
80
  let live = false;
75
- let pending: { kind: Kind; cancel: () => void } | null = null;
81
+ /** `prompt`: waits on a dialog, so only the dialog closing resolves it, not a run boundary. */
82
+ let pending: { prompt: boolean; cancel: () => void } | null = null;
76
83
  let cancelRemind: (() => void) | null = null;
77
84
 
78
85
  const drop = () => {
@@ -88,7 +95,11 @@ export function createCue(deps: Deps, timing: Timing = DEFAULT_TIMING): Cue {
88
95
  deps.withdraw();
89
96
  };
90
97
 
91
- const schedule = (graceMs: number, note: Note) => {
98
+ const dropRun = () => {
99
+ if (pending && !pending.prompt) drop();
100
+ };
101
+
102
+ const schedule = (graceMs: number, note: Note, prompt = false) => {
92
103
  drop();
93
104
  const at = deps.now();
94
105
  const cancel = deps.after(graceMs, () => {
@@ -103,7 +114,7 @@ export function createCue(deps: Deps, timing: Timing = DEFAULT_TIMING): Cue {
103
114
  });
104
115
  }
105
116
  });
106
- pending = { kind: note.kind, cancel };
117
+ pending = { prompt, cancel };
107
118
  };
108
119
 
109
120
  return {
@@ -126,30 +137,34 @@ export function createCue(deps: Deps, timing: Timing = DEFAULT_TIMING): Cue {
126
137
  runStart() {
127
138
  // Runs can restart on retry; keep the first start so the duration is the whole run.
128
139
  if (startedAt === null) startedAt = deps.now();
129
- if (pending && pending.kind !== "ask") drop();
140
+ dropRun();
130
141
  withdraw();
131
142
  },
132
143
 
133
- settled({ aborted, failed, text }) {
144
+ settled({ aborted, failed, text, question }) {
134
145
  const started = startedAt;
135
146
  startedAt = null;
136
- if (pending && pending.kind !== "ask") drop();
147
+ dropRun();
137
148
  if (!enabled || aborted) return;
138
- const elapsedMs = started === null ? 0 : deps.now() - started;
139
- if (!failed && elapsedMs < timing.minRunMs) return;
140
- schedule(timing.graceMs, { kind: failed ? "fail" : "done", elapsedMs, text });
149
+ const now = deps.now();
150
+ const since = Number.isFinite(lastInput) ? lastInput : (started ?? now);
151
+ const elapsedMs = now - since;
152
+ if (failed) return schedule(timing.graceMs, { kind: "fail", elapsedMs, text });
153
+ if (elapsedMs < timing.minRunMs) return;
154
+ if (question) return schedule(timing.askGraceMs, { kind: "ask", elapsedMs, text: question });
155
+ schedule(timing.graceMs, { kind: "done", elapsedMs, text });
141
156
  },
142
157
 
143
158
  promptStart(title) {
144
159
  depth += 1;
145
160
  if (!enabled || depth > 1) return;
146
- schedule(timing.askGraceMs, { kind: "ask", text: title });
161
+ schedule(timing.askGraceMs, { kind: "ask", text: title }, true);
147
162
  },
148
163
 
149
164
  promptEnd() {
150
165
  depth = Math.max(0, depth - 1);
151
166
  if (depth > 0) return;
152
- if (pending?.kind === "ask") drop();
167
+ if (pending?.prompt) drop();
153
168
  withdraw();
154
169
  },
155
170
 
package/src/text.ts CHANGED
@@ -34,21 +34,41 @@ export function duration(ms: number): string {
34
34
  }
35
35
 
36
36
  /** First meaningful line, stripped of markdown noise, cut to `max` characters. */
37
+ const clean = (raw: string) =>
38
+ raw
39
+ .replace(/^\s*(?:#{1,6}|>|[-*+]|\d+[.)])\s+/, "")
40
+ .replace(/[`*_~]/g, "")
41
+ .replace(/\s+/g, " ")
42
+ .trim();
43
+
44
+ const clip = (line: string, max: number) => {
45
+ const chars = Array.from(line);
46
+ return chars.length <= max ? line : `${chars.slice(0, max - 1).join("").trimEnd()}…`;
47
+ };
48
+
37
49
  export function oneLine(text: string | undefined, max = 90): string {
38
50
  if (!text) return "";
39
51
  for (const raw of text.split(/\r?\n/)) {
40
- const line = raw
41
- .replace(/^\s*(?:#{1,6}|>|[-*+]|\d+[.)])\s+/, "")
42
- .replace(/[`*_~]/g, "")
43
- .replace(/\s+/g, " ")
44
- .trim();
45
- if (!line) continue;
46
- const chars = Array.from(line);
47
- return chars.length <= max ? line : `${chars.slice(0, max - 1).join("").trimEnd()}…`;
52
+ const line = clean(raw);
53
+ if (line) return clip(line, max);
48
54
  }
49
55
  return "";
50
56
  }
51
57
 
58
+ /**
59
+ * The question a reply ends on, if it ends on one: "Merge it now?" at the end means
60
+ * the agent is waiting for you even though no dialog opened. Heuristic by design.
61
+ */
62
+ export function question(text: string | undefined, max = 90): string | undefined {
63
+ if (!text) return undefined;
64
+ const lines = text.split(/\r?\n/).map(clean).filter(Boolean);
65
+ const last = lines.at(-1)?.replace(/[\s))"'”’]+$/, "");
66
+ if (!last || !/[??]$/.test(last)) return undefined;
67
+ // Keep only the final sentence of a long line.
68
+ const sentence = last.split(/(?<=[.!。!??])\s*/).filter(Boolean).at(-1) ?? last;
69
+ return clip(sentence, max);
70
+ }
71
+
52
72
  export function repoName(cwd: string): string {
53
73
  return basename(cwd) || cwd;
54
74
  }