granttap-mcp 0.8.180 → 0.8.182

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.
@@ -1,23 +1,34 @@
1
1
  # Helper runs
2
2
 
3
3
  A chat that asks for a picture runs a script, and the script starts its own
4
- headless provider session in a throwaway folder inside the system temp
5
- directory. That session is the chat's work. It is shown as one of the chat's
6
- nested conversations, labelled for what it is, and never as a chat or a Mesh
7
- of its own.
4
+ headless provider session in a folder it makes for that one request. That
5
+ session is the chat's work. It is shown as one of the chat's nested
6
+ conversations, labelled for what it is, and never as a chat or a Mesh of its
7
+ own.
8
8
 
9
- **Recognised** (`kinds.ts`). A run is a headless session whose working folder
10
- sits directly inside a temp directory and carries a generator's prefix.
11
- `GENERATORS` is the one place a generator is listed: its folder prefix, the
12
- kind its runs are, and the label a phone that does not know the kind shows.
13
- A session in a temp folder is not a run unless a generator claims the folder.
9
+ **Recognised** (`kinds.ts`, `recognition.ts`). A run is a headless Grok
10
+ session in a folder that was made for it. Two things say a folder was:
11
+
12
+ - its name: it sits directly inside a temp directory and carries a generator's
13
+ prefix. `GENERATORS` is the one place a generator is listed: its folder
14
+ prefix, the kind its runs are, and the label a phone that does not know the
15
+ kind shows;
16
+ - what became of it, whatever a script called it: the session was given one
17
+ request, the folder is not a checkout of its own, and it is gone again from
18
+ inside a Git checkout or the temp directory, or was made in the last
19
+ fifteen minutes. A folder that a live run was linked from counts as well.
20
+
21
+ A run that made a picture is an image generation; any other is a helper run.
22
+ A headless session in a workspace that stays, in a checkout of its own such as
23
+ a worktree, or one given a second request, is a chat.
14
24
 
15
25
  **Linked** (`capture.ts`, `links.ts`). Nothing recorded after the fact names
16
26
  the chat that started a run. The run's live process does: Claude Code and
17
27
  Codex give every command a chat runs that chat's id, and the run inherits it.
18
28
  Each process sample (`machine-load`) passes its provider processes here. A
19
29
  process is looked at once: its working folder is read, and only when that is a
20
- generator's folder is its environment read, for the chat's id alone. Nothing
30
+ run's folder (a generator's, or for Grok one made minutes ago that is not a
31
+ checkout of its own) is its environment read, for the chat's id alone. Nothing
21
32
  read from a process is logged or kept beyond that id. The link is written to
22
33
  `helper-runs.json` in the config directory, keyed by the run's folder, and
23
34
  outlives the process. The first capture of a run stands.
@@ -43,9 +54,12 @@ in place of the path line that names them. A phone reads one with
43
54
  picture's content, never a path, and only the chat that started the run is
44
55
  answered.
45
56
 
46
- **Meshes.** A generator's folder never registers a Mesh. Meshes registered for
47
- such folders before runs were recognised stay in the Mesh store and are left
48
- out of every list of this computer's Projects.
57
+ **Meshes.** A run is not passed to the Mesh, and a generator's folder never
58
+ registers one. A Mesh without a remote whose folder is a generator's, or is
59
+ gone from inside a Git checkout or the temp directory, was registered for a
60
+ run before the run was recognised: it stays in the Mesh store and is left out
61
+ of every list of this computer's Projects. A workspace of its own is kept
62
+ whether its folder is there or not.
49
63
 
50
64
  Tests live in `tests/`; the Mesh behaviour is covered in
51
65
  `../mesh/runtime/tests/helper-run-meshes.test.ts`.
@@ -6,12 +6,15 @@
6
6
  * to everything its shell starts, and the run's process inherits it. Only a
7
7
  * process already known to be a helper run has its environment read, only the
8
8
  * chat's id is kept from it, and nothing read here is ever logged.
9
+ *
10
+ * A run is known by its folder: a generator's, or, for Grok, one a script made
11
+ * minutes ago that is not a checkout of its own.
9
12
  */
10
13
  import { execFile } from "node:child_process";
11
14
  import { existsSync, readlinkSync } from "node:fs";
12
15
  import { promisify } from "node:util";
13
16
  import type { ProcessRow } from "../machine-load/host/process-sampler";
14
- import { helperRunFolder, helperRunFoldersNamed, type HelperRunFolder } from "./kinds";
17
+ import { freshRunFolder, helperRunFolder, helperRunFoldersNamed, helperRunLabel, plainFolder, type HelperRunFolder } from "./kinds";
15
18
  import { rememberHelperRunLinks, type HelperRunLink, type HelperRunParentAgent } from "./links";
16
19
  import { followHelperRunPictures } from "./pictures/capture";
17
20
 
@@ -20,7 +23,9 @@ const run = promisify(execFile);
20
23
  export type HelperRunParent = { agent: HelperRunParentAgent; sessionId: string };
21
24
 
22
25
  /** One provider process the listing shows. Its command line is searched for a generator's folder and never kept. */
23
- export type HelperRunProcess = { pid: number; command: string; ancestor?: HelperRunParent };
26
+ export type HelperRunProcess = { pid: number; command: string; ancestor?: HelperRunParent;
27
+ /** The provider the process is, as the listing knows it. */
28
+ agent?: string };
24
29
 
25
30
  export type HelperRunReaders = {
26
31
  directories: (pids: readonly number[]) => Promise<Map<number, string>>;
@@ -102,8 +107,9 @@ export function helperRunProcesses(
102
107
  const above = row.ppid != null ? ownership.roots.get(row.ppid) : undefined;
103
108
  const agent = above != null ? ownership.agents.get(above) : undefined;
104
109
  const sessionId = above != null ? sessions.get(above) : undefined;
110
+ const own = ownership.agents.get(row.pid);
105
111
  return {
106
- pid: row.pid, command: row.command,
112
+ pid: row.pid, command: row.command, ...(own ? { agent: own } : {}),
107
113
  ...(agent && sessionId && PARENT_AGENTS.has(agent)
108
114
  ? { ancestor: { agent: agent as HelperRunParentAgent, sessionId } } : {}),
109
115
  };
@@ -115,6 +121,8 @@ type CaptureOptions = {
115
121
  remember?: (links: HelperRunLink[]) => number;
116
122
  /** Told, at every sample, the folders of the linked runs still alive, so their pictures are caught. */
117
123
  follow?: (folders: readonly string[]) => void;
124
+ /** Whether a folder was made for the run in it; the disk answers unless a test does. */
125
+ madeForRun?: (folder: string, now: number) => boolean;
118
126
  now?: () => number;
119
127
  };
120
128
 
@@ -124,6 +132,7 @@ export function createHelperRunCapture(options: CaptureOptions = {}) {
124
132
  const remember = options.remember ?? rememberHelperRunLinks;
125
133
  const follow = options.follow ?? followHelperRunPictures;
126
134
  const now = options.now ?? Date.now;
135
+ const madeForRun = options.madeForRun ?? freshRunFolder;
127
136
  const settled = new Set<number>();
128
137
  const folderReads = new Map<number, number>();
129
138
  /** The folder of each live linked run, by its process. */
@@ -133,7 +142,10 @@ export function createHelperRunCapture(options: CaptureOptions = {}) {
133
142
  const working = helperRunFolder(directory);
134
143
  if (working) return working;
135
144
  const named = helperRunFoldersNamed(item.command);
136
- return named.length === 1 ? named[0] : undefined;
145
+ if (named.length === 1) return named[0];
146
+ // A headless Grok run in a folder a script has just made for it is that script's chat's work.
147
+ if (item.agent !== "grok" || !directory || !madeForRun(directory, now())) return undefined;
148
+ return { kind: "helper-run", label: helperRunLabel("helper-run"), folder: plainFolder(directory) };
137
149
  };
138
150
 
139
151
  const examine = async (processes: readonly HelperRunProcess[]): Promise<number> => {
@@ -1,5 +1,6 @@
1
1
  /** Short helper runs a chat starts, such as image generation: recognised, linked to their chat, shown under it. */
2
2
  export { helperRunFolder, helperRunLabel, helperRunProject, type HelperRunFolder, type HelperRunKind } from "./kinds";
3
+ export { recognizeHelperRun } from "./recognition";
3
4
  export { helperRunLink, rememberHelperRunLinks, type HelperRunLink } from "./links";
4
5
  export { attachHelperRuns, helperRunEntries, helperRunThread, type HelperRunSession } from "./attach";
5
6
  export { captureHelperRuns, helperRunProcesses } from "./capture";
@@ -7,10 +7,11 @@
7
7
  * about the run says what it is. A session in a temp folder is not a helper
8
8
  * run by itself: only a generator listed here makes it one.
9
9
  */
10
- import { realpathSync } from "node:fs";
10
+ import { existsSync, realpathSync, statSync } from "node:fs";
11
11
  import { tmpdir } from "node:os";
12
12
 
13
- export type HelperRunKind = "image-generation";
13
+ /** `helper-run` is a run no generator claims: its folder alone says it was made for one run. */
14
+ export type HelperRunKind = "image-generation" | "helper-run";
14
15
 
15
16
  type Generator = {
16
17
  /** How the generator names its throwaway folder. */
@@ -36,7 +37,8 @@ export type HelperRunFolder = {
36
37
  folder: string;
37
38
  };
38
39
 
39
- function plain(path: string): string {
40
+ /** A folder in one spelling: forward slashes, no trailing slash, and macOS `/private/var` as `/var`. */
41
+ export function plainFolder(path: string): string {
40
42
  const trimmed = path.trim().replace(/\\/g, "/").replace(/\/+$/, "");
41
43
  return /^\/private\/(var|tmp)(\/|$)/.test(trimmed) ? trimmed.slice("/private".length) : trimmed;
42
44
  }
@@ -53,8 +55,9 @@ function systemTempRoots(): readonly string[] {
53
55
  return ownTemp;
54
56
  }
55
57
 
56
- function isTempRoot(directory: string, roots: readonly string[]): boolean {
57
- return PER_USER_TEMP.test(directory) || roots.some((root) => plain(root) === directory);
58
+ /** Whether a folder, in its plain spelling, is a temp directory of this computer. */
59
+ export function isTempRoot(directory: string, roots: readonly string[] = systemTempRoots()): boolean {
60
+ return PER_USER_TEMP.test(directory) || roots.some((root) => plainFolder(root) === directory);
58
61
  }
59
62
 
60
63
  /** The generator a working folder belongs to, when it is one's throwaway folder directly inside a temp directory. */
@@ -63,7 +66,7 @@ export function helperRunFolder(
63
66
  tempRoots: readonly string[] = systemTempRoots(),
64
67
  ): HelperRunFolder | undefined {
65
68
  if (!path) return undefined;
66
- const folder = plain(path);
69
+ const folder = plainFolder(path);
67
70
  const cut = folder.lastIndexOf("/");
68
71
  if (cut <= 0 || !isTempRoot(folder.slice(0, cut), tempRoots)) return undefined;
69
72
  const name = folder.slice(cut + 1);
@@ -90,12 +93,79 @@ export function helperRunLabel(kind: string): string {
90
93
  }
91
94
 
92
95
  /**
93
- * A Mesh that was registered for a helper run's folder before helper runs were recognised.
94
- * A repository with a remote is a real Project wherever it was cloned.
96
+ * A Mesh that was registered for a helper run's folder before the run was recognised: a generator's
97
+ * folder, or a folder made for one run that is gone again. A repository with a remote is a real
98
+ * Project wherever it was cloned.
95
99
  */
96
- export function helperRunProject(project: { repositoryRoot?: string; canonicalRepositoryId: string }): boolean {
100
+ export function helperRunProject(
101
+ project: { repositoryRoot?: string; canonicalRepositoryId: string },
102
+ vanished: (folder: string | undefined) => boolean = vanishedRunFolder,
103
+ ): boolean {
97
104
  const identity = project.canonicalRepositoryId;
98
105
  if (!identity.startsWith("local:")) return false;
99
- return helperRunFolder(project.repositoryRoot) !== undefined
100
- || helperRunFolder(identity.slice("local:".length)) !== undefined;
106
+ const folders = [project.repositoryRoot, identity.slice("local:".length)];
107
+ return folders.some((folder) => helperRunFolder(folder) !== undefined) || folders.some((folder) => vanished(folder));
108
+ }
109
+
110
+ /** A folder made this recently was made for the run found in it, when nothing else is there to work on. */
111
+ export const FRESH_FOLDER_MS = 15 * 60_000;
112
+ const CHECK_AGAIN_MS = 60_000;
113
+ const MAX_REMEMBERED = 4_096;
114
+ const vanishedChecks = new Map<string, { at: number; vanished: boolean }>();
115
+
116
+ function absolute(folder: string): boolean {
117
+ return folder.startsWith("/") || /^[A-Za-z]:\//.test(folder);
118
+ }
119
+
120
+ function parentOf(folder: string): string | undefined {
121
+ const cut = folder.lastIndexOf("/");
122
+ if (cut < 0) return undefined;
123
+ const parent = cut === 0 ? "/" : folder.slice(0, cut);
124
+ return parent === folder || /^[A-Za-z]:$/.test(parent) ? undefined : parent;
125
+ }
126
+
127
+ /**
128
+ * A folder that was made for one run and removed after it: it is gone, and it lay directly inside a
129
+ * temp directory or anywhere inside a Git checkout. Had it been a workspace of its own it would have
130
+ * been that checkout's. The answer is kept for a minute; a Mesh list asks about every Project.
131
+ */
132
+ export function vanishedRunFolder(path: string | undefined, now = Date.now()): boolean {
133
+ if (!path) return false;
134
+ const folder = plainFolder(path);
135
+ if (!absolute(folder)) return false;
136
+ const known = vanishedChecks.get(folder);
137
+ if (known && now - known.at < CHECK_AGAIN_MS && now >= known.at) return known.vanished;
138
+ let vanished = false;
139
+ try {
140
+ if (!existsSync(folder)) {
141
+ let above = parentOf(folder);
142
+ vanished = above !== undefined && isTempRoot(above);
143
+ for (let depth = 0; !vanished && above !== undefined && depth < 48; depth += 1) {
144
+ vanished = existsSync(`${above === "/" ? "" : above}/.git`);
145
+ above = parentOf(above);
146
+ }
147
+ }
148
+ } catch { /* A folder that cannot be looked at is not called gone. */ }
149
+ if (vanishedChecks.size >= MAX_REMEMBERED) vanishedChecks.clear();
150
+ vanishedChecks.set(folder, { at: now, vanished });
151
+ return vanished;
152
+ }
153
+
154
+ /** For tests: look at every folder again. */
155
+ export function forgetRunFolderChecks(): void {
156
+ vanishedChecks.clear();
157
+ }
158
+
159
+ /** A folder made within the last minutes that is not a checkout of its own: a script made it for the run in it. */
160
+ export function freshRunFolder(path: string | undefined, now = Date.now()): boolean {
161
+ if (!path) return false;
162
+ const folder = plainFolder(path);
163
+ if (!absolute(folder) || isTempRoot(folder)) return false;
164
+ try {
165
+ const stat = statSync(folder);
166
+ if (!stat.isDirectory() || !(stat.birthtimeMs > 0) || now - stat.birthtimeMs > FRESH_FOLDER_MS) return false;
167
+ return !existsSync(`${folder}/.git`);
168
+ } catch {
169
+ return false;
170
+ }
101
171
  }
@@ -11,7 +11,7 @@ import { join } from "node:path";
11
11
  import { writePrivateFile } from "../config/access/write-private";
12
12
  import { configDir } from "../config/runtime/paths";
13
13
  import { HISTORY_RETENTION_MS } from "../sessions/support/common";
14
- import { helperRunFolder } from "./kinds";
14
+ import { helperRunFolder, plainFolder } from "./kinds";
15
15
 
16
16
  export type HelperRunParentAgent = "claude" | "codex";
17
17
 
@@ -30,10 +30,20 @@ export function helperRunLinksPath(): string {
30
30
  return join(configDir(), "helper-runs.json");
31
31
  }
32
32
 
33
+ /** A generator's folder for a generator's run; any full path for a run known by its folder alone. */
34
+ function linkFolder(folder: unknown, kind: unknown): string | undefined {
35
+ if (typeof folder !== "string") return undefined;
36
+ const generator = helperRunFolder(folder);
37
+ if (generator) return generator.folder;
38
+ if (kind !== "helper-run" || folder.length > 1_024) return undefined;
39
+ const plain = plainFolder(folder);
40
+ return plain.startsWith("/") || /^[A-Za-z]:\//.test(plain) ? plain : undefined;
41
+ }
42
+
33
43
  function valid(value: unknown): HelperRunLink | undefined {
34
44
  if (!value || typeof value !== "object") return undefined;
35
45
  const item = value as Record<string, unknown>;
36
- const folder = typeof item.folder === "string" ? helperRunFolder(item.folder)?.folder : undefined;
46
+ const folder = linkFolder(item.folder, item.kind);
37
47
  if (!folder || typeof item.kind !== "string" || !item.kind || item.kind.length > 40) return undefined;
38
48
  if (item.parentAgent !== "claude" && item.parentAgent !== "codex") return undefined;
39
49
  if (typeof item.parentSessionId !== "string" || !SESSION_ID.test(item.parentSessionId)) return undefined;
@@ -74,8 +84,8 @@ function readLinks(): Map<string, HelperRunLink> {
74
84
 
75
85
  /** The chat that started the run in this folder, when it was captured. */
76
86
  export function helperRunLink(folder: string | undefined): HelperRunLink | undefined {
77
- const key = helperRunFolder(folder)?.folder;
78
- return key ? readLinks().get(key) : undefined;
87
+ if (!folder) return undefined;
88
+ return readLinks().get(helperRunFolder(folder)?.folder ?? plainFolder(folder));
79
89
  }
80
90
 
81
91
  /** Write newly captured parents down. The first capture of a run stands. Returns how many were new. */
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Whether a provider's headless session was a helper run.
3
+ *
4
+ * A generator's folder says so by its name. Any other run is known by what its
5
+ * folder was: one linked to a chat while the run's process lived, or one a
6
+ * script made for a single request, which is gone again or was made minutes
7
+ * ago and is not a checkout of its own. A headless session in a workspace that
8
+ * stays, or one that was given a second request, is a chat.
9
+ */
10
+ import {
11
+ freshRunFolder,
12
+ helperRunFolder,
13
+ helperRunLabel,
14
+ plainFolder,
15
+ vanishedRunFolder,
16
+ type HelperRunFolder,
17
+ type HelperRunKind,
18
+ } from "./kinds";
19
+ import { helperRunLink, type HelperRunLink } from "./links";
20
+
21
+ export type HeadlessSession = {
22
+ cwd?: string;
23
+ startedAt: number;
24
+ /** How many requests the session was given; a run is given one. */
25
+ requests: number;
26
+ /** The checkout the provider recorded for the session, when it recorded one. */
27
+ checkoutRoot?: string;
28
+ /** Whether the session made a picture. */
29
+ madePictures?: boolean;
30
+ };
31
+
32
+ export type RunFolderChecks = {
33
+ link?: (folder: string) => HelperRunLink | undefined;
34
+ vanished?: (folder: string, now: number) => boolean;
35
+ fresh?: (folder: string, now: number) => boolean;
36
+ now?: number;
37
+ };
38
+
39
+ /** A link names the run that was alive when it was captured, not a later session in a folder of the same name. */
40
+ const LINK_SLACK_MS = 60_000;
41
+
42
+ export function recognizeHelperRun(session: HeadlessSession, checks: RunFolderChecks = {}): HelperRunFolder | undefined {
43
+ const generator = helperRunFolder(session.cwd);
44
+ if (generator) return generator;
45
+ if (!session.cwd) return undefined;
46
+ const folder = plainFolder(session.cwd);
47
+ const kind: HelperRunKind = session.madePictures ? "image-generation" : "helper-run";
48
+ const run: HelperRunFolder = { kind, label: helperRunLabel(kind), folder };
49
+ const link = (checks.link ?? helperRunLink)(folder);
50
+ if (link && session.startedAt <= link.capturedAt + LINK_SLACK_MS) return run;
51
+ if (session.requests > 1) return undefined;
52
+ if (session.checkoutRoot && plainFolder(session.checkoutRoot) === folder) return undefined;
53
+ const now = checks.now ?? Date.now();
54
+ return (checks.vanished ?? vanishedRunFolder)(folder, now) || (checks.fresh ?? freshRunFolder)(folder, now)
55
+ ? run : undefined;
56
+ }
@@ -6,8 +6,19 @@ persistent monitor then queues one "continue" for that chat on the relay's durab
6
6
  due a minute after the reset. The relay holds it while this computer sleeps or the phone is away,
7
7
  and offers it back like any queued phone message: the chat receives it when it is idle.
8
8
 
9
+ The window often has room before the time the refusal stated. While a continuation waits, the
10
+ monitor looks at Claude's account readings (`lift.ts`). It queues one more continuation, due at once,
11
+ when a reading of the same window, taken after the continuation was queued and less than ten
12
+ minutes old, shows it below 98 % used, or ending more than five minutes before the refusal's reset
13
+ (it already rolled over). `five_hour` is read from the five-hour window, `seven_day` from the weekly
14
+ one, and a weekly limit named after one model (`seven_day_<model>`) from that model's weekly limit
15
+ when exactly one reading names it. `seven_day_overage_included`, other kinds, a signed-out account
16
+ and missing readings never go early. The early continuation is tried once per chat and reset time.
17
+ The one due at the reset stays queued until the chat goes on; a chat refused again for the same
18
+ reset keeps it and gets no second early try.
19
+
9
20
  The phone turns it off or on per chat with `session.autocontinue.set`. It is on by default.
10
- Turning it off takes the queued copy back from the relay. A copy the relay still offers afterwards
21
+ Turning it off takes the queued copies back from the relay. A copy the relay still offers afterwards
11
22
  is refused at delivery. The same happens when the chat went on by itself first. A limit that reset
12
23
  more than an hour ago is treated as abandoned and is never woken by an update.
13
24
 
@@ -1,21 +1,31 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { CodingAgent, UserMessage, type SessionInfo } from '../../../../packages/protocol/schema';
2
+ import { CodingAgent, UserMessage, type ProviderAccountUsage, type SessionInfo } from '../../../../packages/protocol/schema';
3
3
  import type { NativeQueueScope } from '../task-dispatch/sender/store';
4
- import { readLimitContinuationState, writeLimitContinuationState, type ScheduledContinuation } from './store';
4
+ import { limitLifted } from './lift';
5
+ import { readLimitContinuationState, writeLimitContinuationState, type LimitContinuationState,
6
+ type ScheduledContinuation } from './store';
7
+
8
+ export { LIFT_BELOW_PERCENT, LIFT_READING_MAX_AGE_MS } from './lift';
5
9
 
6
10
  /** What the agent reads when the computer continues a chat its subscription had stopped. */
7
11
  export const LIMIT_CONTINUE_PROMPT =
8
12
  'GrantTap: the subscription limit that stopped this chat has reset. Continue the work from where you stopped.';
13
+ /** What the agent reads when the account's readings show the limit has room again before its reset. */
14
+ export const LIMIT_ROOM_PROMPT =
15
+ 'GrantTap: the subscription limit that stopped this chat has room again. Continue the work from where you stopped.';
9
16
  /** The provider's clock and ours differ a little; arriving just before the reset would hit the limit again. */
10
17
  export const LIMIT_CONTINUE_GRACE_MS = 60_000;
11
18
  /** A chat left at a limit that reset longer ago than this was abandoned, not waiting; an update must not wake it. */
12
19
  const STALE_AFTER_RESET_MS = 3_600_000;
13
20
  const PREFIX = 'limit-continue-';
21
+ const EARLY_PREFIX = `${PREFIX}early-`;
14
22
 
15
23
  export type ContinuationQueue = {
16
24
  submit: (scope: NativeQueueScope, message: UserMessage, notBefore: number, createdAt: number) => Promise<unknown>;
17
25
  cancel: (scope: NativeQueueScope, id: string) => Promise<unknown>;
18
26
  };
27
+ /** The account's limit readings; asked only while a queued continuation could still go early. */
28
+ export type UsageReadings = () => ProviderAccountUsage[];
19
29
 
20
30
  let registered: ContinuationQueue | undefined;
21
31
  /** Only the persistent monitor owns the durable relay queue; session MCPs never schedule. */
@@ -41,48 +51,94 @@ function wanted(session: SessionInfo, off: Set<string>, now: number): boolean {
41
51
  && limit.resetsAt > now - STALE_AFTER_RESET_MS;
42
52
  }
43
53
 
44
- function continuation(session: SessionInfo, now: number): { job: ScheduledContinuation; message: UserMessage } {
54
+ function continuation(session: SessionInfo, now: number, early = false): { job: ScheduledContinuation; message: UserMessage } {
45
55
  const resetsAt = session.usageLimit!.resetsAt;
46
- const messageId = PREFIX + createHash('sha256').update(`${session.sessionId}:${resetsAt}`).digest('hex').slice(0, 40);
56
+ const messageId = (early ? EARLY_PREFIX : PREFIX) + createHash('sha256')
57
+ .update(`${session.sessionId}:${resetsAt}${early ? ':early' : ''}`).digest('hex').slice(0, 40);
47
58
  const scope: NativeQueueScope = { sessionId: session.sessionId, provider: CodingAgent.parse(session.agent),
48
59
  ...(session.projectId ? { projectId: session.projectId } : {}), ...(session.taskId ? { taskId: session.taskId } : {}) };
49
60
  const cwd = session.worktree ?? session.cwd;
50
61
  const message = UserMessage.parse({ type: 'user.message', messageId, sessionId: session.sessionId, agent: session.agent,
51
- text: LIMIT_CONTINUE_PROMPT, createdAt: now, ...(cwd ? { cwd } : {}),
62
+ text: early ? LIMIT_ROOM_PROMPT : LIMIT_CONTINUE_PROMPT, createdAt: now, ...(cwd ? { cwd } : {}),
52
63
  ...(session.projectId ? { projectId: session.projectId } : {}) });
53
- return { job: { resetsAt, messageId, scope }, message };
64
+ return { job: { resetsAt, messageId, scope, scheduledAt: now }, message };
54
65
  }
55
66
 
56
- /**
57
- * Puts one "continue" on the relay for every chat its subscription stopped, due when the limit resets,
58
- * and takes it back when the chat went on by itself or the person turned it off. The relay holds it
59
- * while this computer sleeps or the phone is away.
60
- */
61
- export async function scheduleLimitContinuations(sessions: SessionInfo[], queue = registered, now = Date.now()): Promise<void> {
62
- if (!queue) return;
63
- const state = readLimitContinuationState(), off = new Set(state.off);
64
- const byId = new Map(sessions.map(session => [session.sessionId, session]));
67
+ /** Takes back what the relay holds for chats that went on, were turned off or left the catalog long ago. */
68
+ async function withdraw(state: LimitContinuationState, byId: Map<string, SessionInfo>, off: Set<string>,
69
+ queue: ContinuationQueue, now: number): Promise<boolean> {
65
70
  let changed = false;
66
71
  for (const [sessionId, job] of Object.entries(state.scheduled)) {
67
72
  const session = byId.get(sessionId);
68
73
  const current = session?.usageLimit?.resetsAt === job.resetsAt && wanted(session, off, now);
69
74
  const missing = !session && job.resetsAt > now - 7 * 86_400_000 && !off.has(sessionId);
75
+ // A job queued before its time was recorded counts from now, so no older reading speaks for it.
76
+ if (current && job.scheduledAt === undefined) { job.scheduledAt = now; changed = true; }
70
77
  if (current || missing) continue;
71
- await queue.cancel(job.scope, job.messageId).catch(() => {});
78
+ for (const id of [job.messageId, ...(job.early ? [job.early] : [])]) await queue.cancel(job.scope, id).catch(() => {});
72
79
  delete state.scheduled[sessionId]; changed = true;
73
80
  }
81
+ for (const [sessionId, resetsAt] of Object.entries(state.tried ?? {})) {
82
+ if (resetsAt > now - STALE_AFTER_RESET_MS) continue;
83
+ delete state.tried![sessionId]; changed = true;
84
+ }
85
+ return changed;
86
+ }
87
+
88
+ /**
89
+ * Queues a second continuation, due at once, for a limited chat whose window the account's readings
90
+ * show has room again before its reset. It is tried once per limit; the one due at the reset stays.
91
+ */
92
+ async function continueEarly(state: LimitContinuationState, byId: Map<string, SessionInfo>, queue: ContinuationQueue,
93
+ now: number, readings: UsageReadings): Promise<boolean> {
94
+ const waiting = Object.entries(state.scheduled).flatMap(([sessionId, job]) => {
95
+ const session = byId.get(sessionId);
96
+ // A job queued this moment has no reading taken after it yet.
97
+ return session?.usageLimit?.resetsAt === job.resetsAt && job.scheduledAt !== undefined && job.scheduledAt < now
98
+ && !job.early && state.tried?.[sessionId] !== job.resetsAt && now < job.resetsAt
99
+ ? [{ session, job, at: job.scheduledAt }] : [];
100
+ });
101
+ if (!waiting.length) return false;
102
+ let usage: ProviderAccountUsage[] = [], changed = false;
103
+ // Unreadable limits only mean nothing goes early; what this pass queued must still be recorded.
104
+ try { usage = readings(); } catch { /* No readings. */ }
105
+ for (const { session, job, at } of waiting) {
106
+ if (!limitLifted(session.usageLimit!, at, usage, now)) continue;
107
+ const { message } = continuation(session, now, true), tried = state.tried ??= {};
108
+ // It is due at once, so delivery must already find it wanted.
109
+ job.early = message.messageId; tried[session.sessionId] = job.resetsAt; changed = true;
110
+ writeLimitContinuationState(state);
111
+ try { await queue.submit(job.scope, message, now, now); }
112
+ catch (error) { delete job.early; delete tried[session.sessionId]; writeLimitContinuationState(state); throw error; }
113
+ }
114
+ return changed;
115
+ }
116
+
117
+ /**
118
+ * Puts one "continue" on the relay for every chat its subscription stopped, due when the limit resets,
119
+ * and takes it back when the chat went on by itself or the person turned it off. The relay holds it
120
+ * while this computer sleeps or the phone is away. When the account's readings show the window has
121
+ * room again sooner, one more goes at once.
122
+ */
123
+ export async function scheduleLimitContinuations(sessions: SessionInfo[], queue = registered, now = Date.now(),
124
+ readings: UsageReadings = () => []): Promise<void> {
125
+ if (!queue) return;
126
+ const state = readLimitContinuationState(), off = new Set(state.off);
127
+ const byId = new Map(sessions.map(session => [session.sessionId, session]));
128
+ let changed = await withdraw(state, byId, off, queue, now);
74
129
  for (const session of sessions) {
75
130
  if (!wanted(session, off, now) || state.scheduled[session.sessionId]) continue;
76
131
  const { job, message } = continuation(session, now);
77
132
  await queue.submit(job.scope, message, Math.max(now, job.resetsAt + LIMIT_CONTINUE_GRACE_MS), now);
78
133
  state.scheduled[session.sessionId] = job; changed = true;
79
134
  }
135
+ if (await continueEarly(state, byId, queue, now, readings)) changed = true;
80
136
  if (changed) writeLimitContinuationState(state);
81
137
  }
82
138
 
83
139
  /** A continuation the relay hands back after the person turned it off, or for a limit since lifted, is not delivered. */
84
140
  export function limitContinuationUnwanted(message: UserMessage): boolean {
85
141
  if (!message.messageId?.startsWith(PREFIX) || !message.sessionId) return false;
86
- const state = readLimitContinuationState();
87
- return state.off.includes(message.sessionId) || state.scheduled[message.sessionId]?.messageId !== message.messageId;
142
+ const state = readLimitContinuationState(), job = state.scheduled[message.sessionId];
143
+ return state.off.includes(message.sessionId) || (job?.messageId !== message.messageId && job?.early !== message.messageId);
88
144
  }
@@ -0,0 +1,52 @@
1
+ import type { ProviderAccountUsage } from '../../../../packages/protocol/schema';
2
+ import { isSignedOutUsage } from '../provider-account-status/native-usage/memory';
3
+
4
+ type UsageWindow = ProviderAccountUsage['windows'][number];
5
+
6
+ /** A reading older than this says nothing about the window now. */
7
+ export const LIFT_READING_MAX_AGE_MS = 600_000;
8
+ /** Readings lag and round, so a window just under full is still treated as full. */
9
+ export const LIFT_BELOW_PERCENT = 98;
10
+ /** Two reports of one window's end differ by rounding; a window that rolled over ends hours apart. */
11
+ const SAME_WINDOW_MS = 300_000;
12
+ const MODEL_PREFIX = 'claude:model:';
13
+ /** A weekly limit named after one model, such as `seven_day_opus`. */
14
+ const MODEL_WEEKLY = /^seven_day_([a-z0-9]+)$/;
15
+ /** Weekly limits that are not one model's; no reading shows them. */
16
+ const NOT_A_MODEL = new Set(['overage']);
17
+
18
+ /** The one reading that covers the model a weekly limit names, when exactly one does. */
19
+ function modelReading(model: string, claude: ProviderAccountUsage[]): ProviderAccountUsage | undefined {
20
+ const matches = claude.filter(report => {
21
+ const slug = report.limitId.startsWith(MODEL_PREFIX) ? report.limitId.slice(MODEL_PREFIX.length) : '';
22
+ return slug === model || slug.startsWith(`${model}-`);
23
+ });
24
+ return matches.length === 1 ? matches[0] : undefined;
25
+ }
26
+
27
+ /** The reading of the window that refused the chat; none for a refusal no reading covers. */
28
+ function refusingWindow(rateLimitType: string | undefined, claude: ProviderAccountUsage[])
29
+ : { report: ProviderAccountUsage; window: UsageWindow } | undefined {
30
+ const account = claude.find(report => report.limitId === 'claude' && !report.label);
31
+ const model = MODEL_WEEKLY.exec(rateLimitType ?? '')?.[1];
32
+ const [report, id] = rateLimitType === 'five_hour' ? [account, 'primary']
33
+ : rateLimitType === 'seven_day' ? [account, 'secondary']
34
+ : model && !NOT_A_MODEL.has(model) ? [modelReading(model, claude), 'secondary'] : [undefined, undefined];
35
+ const window = report?.windows.find(row => row.id === id);
36
+ return report && window ? { report, window } : undefined;
37
+ }
38
+
39
+ /**
40
+ * Whether the subscription window that refused a chat has room again before its stated reset: a reading
41
+ * of that same window, taken after the continuation was queued and recently, shows it below full or
42
+ * already rolled over to a window that ends sooner. A refusal by a window no reading covers, or no
43
+ * signed-in reading at all, is never lifted early.
44
+ */
45
+ export function limitLifted(limit: { resetsAt: number; window?: string }, scheduledAt: number,
46
+ usage: ProviderAccountUsage[], now: number): boolean {
47
+ const claude = usage.filter(report => report.provider === 'claude');
48
+ if (claude.some(isSignedOutUsage)) return false;
49
+ const found = refusingWindow(limit.window, claude);
50
+ if (!found || found.report.observedAt <= scheduledAt || now - found.report.observedAt > LIFT_READING_MAX_AGE_MS) return false;
51
+ return found.window.usedPercent < LIFT_BELOW_PERCENT || found.window.resetsAt < limit.resetsAt - SAME_WINDOW_MS;
52
+ }
@@ -4,13 +4,20 @@ import { z } from 'zod';
4
4
  import { configDir, writePrivateFile } from '../config';
5
5
  import { NativeQueueScope } from '../task-dispatch/sender/store';
6
6
 
7
- const Scheduled = z.object({ resetsAt: z.number().int(), messageId: z.string().min(1).max(180), scope: NativeQueueScope }).strict();
7
+ const MessageId = z.string().min(1).max(180);
8
+ const Scheduled = z.object({ resetsAt: z.number().int(), messageId: MessageId, scope: NativeQueueScope,
9
+ /** When this computer queued it; only an account reading taken later speaks for the refusal. */
10
+ scheduledAt: z.number().int().nonnegative().optional(),
11
+ /** The continuation queued at once because a reading showed the window had room before its reset. */
12
+ early: MessageId.optional() }).strict();
8
13
  export type ScheduledContinuation = z.infer<typeof Scheduled>;
9
14
  const State = z.object({
10
15
  /** Chats the person told not to continue by themselves. */
11
16
  off: z.array(z.string().min(1).max(180)).max(4_096),
12
17
  /** Continuations this computer put on the relay, by chat. */
13
18
  scheduled: z.record(z.string(), Scheduled),
19
+ /** The limit, by chat, an early continuation was already tried for; it is tried once per limit. */
20
+ tried: z.record(z.string(), z.number().int()).optional(),
14
21
  }).strict();
15
22
  export type LimitContinuationState = z.infer<typeof State>;
16
23
 
@@ -22,6 +29,7 @@ export function readLimitContinuationState(): LimitContinuationState {
22
29
  }
23
30
 
24
31
  export function writeLimitContinuationState(state: LimitContinuationState): void {
32
+ const tried = Object.entries(state.tried ?? {}).slice(-4_096);
25
33
  writePrivateFile(path(), JSON.stringify(State.parse({ off: [...new Set(state.off)].sort().slice(-4_096),
26
- scheduled: state.scheduled })));
34
+ scheduled: state.scheduled, ...(tried.length ? { tried: Object.fromEntries(tried) } : {}) })));
27
35
  }
@@ -21,6 +21,7 @@ import { queueProjectBindingSync } from "../../engine/runtime/engine-projects";
21
21
  import { isCursorTaskCloneId } from "../../sessions/cursor/catalog";
22
22
  import { localTaskTransfers } from '../../task-transfer';
23
23
  import { helperRunFolder } from '../../helper-runs';
24
+ import { presentableTitle } from '../../sessions/support/activity-helpers';
24
25
  export { inspectRepositoryAsync, inspectWorkingTreeAsync, readRepositoryGit } from "./repository-inspection";
25
26
  export { prepareMonitorInspection } from "./monitor-inspection";
26
27
  import type { CatalogInspection } from "./monitor-inspection";
@@ -105,8 +106,8 @@ function provider(value: string): MeshProvider | undefined {
105
106
  * even that is the fallback.
106
107
  */
107
108
  export function meshTaskTitle(session: SessionInfo, agent: string): string {
108
- const named = session.title?.trim();
109
- if (named) return named.slice(0, 160);
109
+ const named = presentableTitle(session.title);
110
+ if (named) return named;
110
111
  const opening = session.summary
111
112
  ?.split("\n")
112
113
  .map((line) => line.trim())
@@ -1,6 +1,7 @@
1
1
  import type { MeshEvent, SessionInfo, TaskCapsule } from '../../../../../../packages/protocol/schema';
2
2
  import type { MeshRuntimeDependencies } from '../dependencies';
3
3
  import { captureTransferContext } from '../../../task-transfer';
4
+ import { presentableTitle } from '../../../sessions/support/activity-helpers';
4
5
 
5
6
  /** The private computer transport owns context; phone notifications are observations only. */
6
7
  export function preparedHandoffMetadata(event: MeshEvent): MeshEvent {
@@ -15,7 +16,7 @@ export async function capturePreparedHandoff(deps: MeshRuntimeDependencies, sess
15
16
  const captured = await capture(session, facts);
16
17
  const task = deps.store().task(facts.taskId);
17
18
  return { transferContext: captured.context,
18
- capsule: { ...facts, title: task?.title ?? session.title ?? facts.goal.slice(0, 160),
19
+ capsule: { ...facts, title: presentableTitle(task?.title) ?? presentableTitle(session.title) ?? facts.goal.slice(0, 160),
19
20
  launch: 'on_message' as const, contextHash: captured.hash },
20
21
  confirm: async () => {
21
22
  const current = deps.sessions().find(row => row.sessionId === session.sessionId);
@@ -46,6 +46,7 @@ const resumedHeads = new WeakSet<RelayClient>();
46
46
  import { publishMonitorMeshes, stopMonitorMeshes } from "../mesh-publication";
47
47
  import { publishMonitorCapabilities, stopMonitorCapabilities } from "../capability-publication";
48
48
  import { annotateLimitContinuations, scheduleLimitContinuations } from "../../limit-continuation";
49
+ import { cachedNativeAccountUsage } from "../../provider-account-status";
49
50
 
50
51
  export type SessionMonitor = {
51
52
  publish: () => Promise<void>;
@@ -172,7 +173,7 @@ async function publishMonitorTick(input: {
172
173
  if (includeHistory || initial) lastHistoryPublishedAt = Date.now();
173
174
  loadLoop.updateStatus(status);
174
175
  void refreshMcpLoad(status.sessions).catch(() => {});
175
- void scheduleLimitContinuations(status.sessions).catch(() => {});
176
+ void scheduleLimitContinuations(status.sessions, undefined, Date.now(), cachedNativeAccountUsage).catch(() => {});
176
177
  publishCatalogHeads(client, status, subscriptions, publishSessionEvents);
177
178
  if (loadRuntimeConfig().meshEnabled) publishMonitorMeshes(client, status);
178
179
  publishMonitorCapabilities(client, status, () => history(false));
@@ -22,7 +22,7 @@ import { grokTimeline } from '../../providers/grok-timeline';
22
22
  import { grokToolCalls, grokToolCompletions, grokToolSummary, grokRecordedChanges } from '../../providers/grok-tools';
23
23
  import { captureGrokConversation, readGrokConversation } from '../../providers/grok-conversation';
24
24
  import { GrokCatalogCache, type GrokParsedContext } from '../../providers/grok-catalog-cache';
25
- import { helperRunFolder, type HelperRunSession } from '../../helper-runs';
25
+ import { recognizeHelperRun, type HelperRunSession } from '../../helper-runs';
26
26
 
27
27
  type Summary = {
28
28
  info?: { id?: unknown; cwd?: unknown };
@@ -32,6 +32,7 @@ type Summary = {
32
32
  updated_at?: unknown;
33
33
  current_model_id?: unknown;
34
34
  session_kind?: unknown;
35
+ git_root_dir?: unknown;
35
36
  };
36
37
 
37
38
  const catalogCache = new GrokCatalogCache();
@@ -168,6 +169,11 @@ function parseLog(path: string, sessionId: string, fallbackTime: number, fullTex
168
169
  return { entries, usage, firstUser, lastMessageAt: lastMessageAt || undefined, tokens, lastTurn, cacheable };
169
170
  }
170
171
 
172
+ /** Grok keeps the pictures a session generated beside its history. */
173
+ function madePictures(directory: string): boolean {
174
+ try { return readdirSync(join(directory, "images")).length > 0; } catch { return false; }
175
+ }
176
+
171
177
  function parseSummary(path: string): Summary | null {
172
178
  try { return JSON.parse(readFileSync(path, "utf8")) as Summary; } catch { return null; }
173
179
  }
@@ -205,8 +211,12 @@ export function scanGrok(maxFiles = MAX_FILES): Scan {
205
211
  .find((value): value is string => typeof value === "string" && value.trim().length > 0);
206
212
  const cwd = typeof summary.info?.cwd === "string" ? summary.info.cwd : undefined;
207
213
  const live = grokNativeActivity(sessionId, directory);
208
- // A generator's headless run in its throwaway folder is its chat's work, not a chat.
209
- const helper = summary.session_kind === "headless" ? helperRunFolder(cwd) : undefined;
214
+ // A headless run in a folder made for it is the work of the chat that started it, not a chat.
215
+ const helper = summary.session_kind === "headless" ? recognizeHelperRun({
216
+ cwd, startedAt, requests: parsed.entries.filter(entry => entry.kind === "user").length,
217
+ checkoutRoot: typeof summary.git_root_dir === "string" ? summary.git_root_dir : undefined,
218
+ madePictures: madePictures(directory),
219
+ }) : undefined;
210
220
  const session: SessionInfo = {
211
221
  sessionId, agent: "grok", title: title?.trim().slice(0, 120), cwd,
212
222
  model: typeof summary.current_model_id === "string" ? summary.current_model_id : undefined,
@@ -46,7 +46,8 @@ export function stripTranscriptMarkup(value: unknown): string {
46
46
  text = text.replace(/<\/?user_query\b[^>]*>/gi, "");
47
47
  text = text.replace(/<\/?timestamp\b[^>]*>/gi, "");
48
48
  // Claude Code wraps text the person pasted; the words are theirs, the tags are not.
49
- text = text.replace(/<pasted_content\b[^>]*>[ \t]*\n?|\n?[ \t]*<\/pasted_content\s*>/gi, "");
49
+ // A name cut short can end inside the opening tag.
50
+ text = text.replace(/<pasted_content\b[^>]*>[ \t]*\n?|\n?[ \t]*<\/pasted_content\s*>|<pasted_content\b[^>]*$/gi, "");
50
51
  return text.replace(/^\s+|\s+$/g, "");
51
52
  }
52
53
 
@@ -86,6 +87,16 @@ export function stripAttachmentNote(text: string): string {
86
87
  ).trim();
87
88
  }
88
89
 
90
+ /**
91
+ * A chat's or Task's name as a person reads it: without the host's wrappers and on one line.
92
+ * A name saved before a wrapper was recognised is cleaned the same way wherever it is shown.
93
+ */
94
+ export function presentableTitle(value: unknown, max = 160): string | undefined {
95
+ if (typeof value !== "string") return undefined;
96
+ const clean = visibleUserText(value).replace(/\s+/g, " ").trim();
97
+ return clean ? clean.slice(0, max) : undefined;
98
+ }
99
+
89
100
  export function visibleUserText(value: unknown): string {
90
101
  const heartbeat = heartbeatDisplayText(value, 'user');
91
102
  if (heartbeat !== undefined) return heartbeat;
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import type { SessionsStatus } from '../../../../packages/protocol/schema';
3
+ import { presentableTitle } from '../sessions/support/activity-helpers';
3
4
 
4
5
  export type TaskActivitySnapshot = {version: 1; keyId: string; machine: string; taskCount: number;
5
6
  generatedAt: number; rows: {id: string; title: string; preview: string; state: string; lastActivityAt: number}[]};
@@ -28,7 +29,7 @@ export function taskActivitySnapshot(catalog: SessionsStatus,
28
29
  taskCount: tasks.size, generatedAt: catalog.generatedAt,
29
30
  rows: options.previews ? sorted.slice(0, 2).map(([id, item]) => ({
30
31
  id: createHash('sha256').update(id).digest('hex').slice(0, 24),
31
- title: text(item.title, 128) || 'GrantTap', preview: text(item.summary, 256),
32
+ title: text(presentableTitle(item.title), 128) || 'GrantTap', preview: text(item.summary, 256),
32
33
  state: item.state, lastActivityAt: item.lastActivityAt,
33
34
  })) : []};
34
35
  }
@@ -1,5 +1,6 @@
1
1
  import type { CodingAgent, SessionInfo, UserAttachment } from '../../../../packages/protocol/schema';
2
2
  import type { DeliveryOptions, ReplyResult } from '../reply';
3
+ import { presentableTitle } from '../sessions/support/activity-helpers';
3
4
  import { TransferPersistence } from './persistence';
4
5
  import type { PreparedTransfer } from './records';
5
6
  import type { MeshStore } from '../mesh/store';
@@ -36,7 +37,8 @@ export class PreparedTaskTransfers extends TransferPersistence {
36
37
  && !rows.some(prepared => prepared.sessionId === row.sessionId));
37
38
  return [...ordinary, ...rows.map(row => {
38
39
  const actual = native.find(session => session.sessionId === row.nativeSessionId);
39
- return { ...this.session(row), ...actual, sessionId: row.sessionId, title: row.title,
40
+ // The Task's name, saved when it moved; one saved with a host's wrapper reads without it.
41
+ return { ...this.session(row), ...actual, sessionId: row.sessionId, title: presentableTitle(row.title),
40
42
  projectId: row.projectId, taskId: row.capsule.taskId, computerId: row.capsule.targetComputer,
41
43
  cwd: row.workspace, worktree: row.capsule.workspaceMode ? undefined : row.workspace, branch: row.branch };
42
44
  })];
@@ -113,7 +115,8 @@ export class PreparedTaskTransfers extends TransferPersistence {
113
115
  private session(row: PreparedTransfer): SessionInfo {
114
116
  return { sessionId: row.sessionId, agent: row.capsule.targetProvider as CodingAgent,
115
117
  projectId: row.projectId, taskId: row.capsule.taskId, computerId: row.capsule.targetComputer,
116
- title: row.title, cwd: row.workspace, worktree: row.capsule.workspaceMode ? undefined : row.workspace, branch: row.branch,
118
+ title: presentableTitle(row.title), cwd: row.workspace,
119
+ worktree: row.capsule.workspaceMode ? undefined : row.workspace, branch: row.branch,
117
120
  model: row.capsule.targetModel, summary: row.capsule.currentStatus,
118
121
  state: row.phase === 'starting' ? 'working' : row.phase === 'uncertain' ? 'waiting' : 'idle',
119
122
  startedAt: row.acceptedAt, lastActivityAt: row.updatedAt, tokensSession: 0, tokensLastTurn: 0 };
@@ -122,7 +125,7 @@ export class PreparedTaskTransfers extends TransferPersistence {
122
125
  private prompt(row: PreparedTransfer, context: string, message: string): string {
123
126
  const location = this.providerContextPath(row.sessionId);
124
127
  const inline = !context.startsWith('{') && Buffer.byteLength(context) <= 32_000 ? `\n<prior-visible-context>\n${context}\n</prior-visible-context>` : '';
125
- return `Continue the existing GrantTap Task ${row.capsule.taskId}: ${row.title}.\n`
128
+ return `Continue the existing GrantTap Task ${row.capsule.taskId}: ${presentableTitle(row.title) ?? row.capsule.taskId}.\n`
126
129
  + (row.capsule.workspaceMode ? 'Continue in the same working folder on this computer. Its files are shared with the source chat.\n'
127
130
  : `Repository revision: ${row.capsule.latestCommit ?? row.capsule.baseSha}.\n`)
128
131
  + `The complete visible conversation and project facts are saved at ${JSON.stringify(location)}. `
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.180
13
+ npm install -g granttap-mcp@0.8.182
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.180\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.182\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.180";
10
+ const PACKAGE = "granttap-mcp@0.8.182";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.180",
3
+ "version": "0.8.182",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {