granttap-mcp 0.8.179 → 0.8.181

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 (35) hide show
  1. package/README.md +14 -0
  2. package/apps/bridge/src/helper-runs/README.md +27 -13
  3. package/apps/bridge/src/helper-runs/capture.ts +16 -4
  4. package/apps/bridge/src/helper-runs/index.ts +1 -0
  5. package/apps/bridge/src/helper-runs/kinds.ts +81 -11
  6. package/apps/bridge/src/helper-runs/links.ts +14 -4
  7. package/apps/bridge/src/helper-runs/recognition.ts +56 -0
  8. package/apps/bridge/src/host/session-keys.ts +4 -1
  9. package/apps/bridge/src/limit-continuation/README.md +12 -1
  10. package/apps/bridge/src/limit-continuation/index.ts +74 -18
  11. package/apps/bridge/src/limit-continuation/lift.ts +52 -0
  12. package/apps/bridge/src/limit-continuation/store.ts +10 -2
  13. package/apps/bridge/src/mesh/README.md +8 -0
  14. package/apps/bridge/src/mesh/catalog/binding-state.ts +3 -1
  15. package/apps/bridge/src/mesh/catalog/index.ts +40 -28
  16. package/apps/bridge/src/mesh/repositories/candidates.ts +99 -0
  17. package/apps/bridge/src/mesh/repositories/checkout.ts +43 -0
  18. package/apps/bridge/src/mesh/repositories/edit.ts +118 -0
  19. package/apps/bridge/src/mesh/repositories/index.ts +161 -0
  20. package/apps/bridge/src/mesh/repositories/requests.ts +49 -0
  21. package/apps/bridge/src/mesh/store/index.ts +2 -2
  22. package/apps/bridge/src/mesh/store/repositories/index.ts +90 -0
  23. package/apps/bridge/src/mesh/store/state.ts +30 -1
  24. package/apps/bridge/src/mesh/store/sync.ts +4 -3
  25. package/apps/bridge/src/monitor/handlers/inbound.ts +4 -0
  26. package/apps/bridge/src/monitor/support/runtime.ts +2 -1
  27. package/apps/bridge/src/sessions/scan/grok.ts +13 -3
  28. package/cursor-plugin/README.md +1 -1
  29. package/cursor-plugin/mcp.json +1 -1
  30. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  31. package/package.json +1 -1
  32. package/packages/protocol/messages/README.md +6 -0
  33. package/packages/protocol/messages/mesh/index.ts +1 -0
  34. package/packages/protocol/messages/mesh/repositories/index.ts +131 -0
  35. package/packages/protocol/schema.ts +8 -0
package/README.md CHANGED
@@ -425,6 +425,20 @@ shows is what the mesh holds. A release is written to the store as a
425
425
  tombstone, so a snapshot or a late event from a computer that was away cannot
426
426
  bring the claim back.
427
427
 
428
+ ### Repositories of a Mesh
429
+
430
+ The repositories a Mesh holds are changed from the phone, one computer at a
431
+ time. The phone asks a computer which checkouts it knows: the ones it binds
432
+ to any Mesh and the ones its chats work in, each repository once, with where
433
+ it is bound. Adding a checkout binds its Git work tree to the Mesh on that
434
+ computer; a repository already in another Mesh on the same computer stays
435
+ where it is. Removing takes out one of that computer's own bindings, never
436
+ another computer's, and never the Mesh's last repository — delete the Mesh
437
+ instead. A removed repository stays out: chats that keep working in it, and
438
+ snapshots that still list it, do not bind it again until it is added back.
439
+ Only a controller paired with the computer is answered, and the answer goes
440
+ to that controller alone.
441
+
428
442
  ### Task reports
429
443
 
430
444
  <p align="center">
@@ -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
+ }
@@ -9,6 +9,8 @@ import type {
9
9
  MeshEvent,
10
10
  MeshSnapshot,
11
11
  MeshInvocationPage,
12
+ MeshRepositoryEditResult,
13
+ MeshRepositoryList,
12
14
  ProjectKnowledgePage,
13
15
  Payload,
14
16
  ProjectPolicyPayload,
@@ -56,7 +58,8 @@ export async function sendMeshPayload(
56
58
 
57
59
  export async function sendProjectPayload(
58
60
  client: RelayClient,
59
- payload: ProjectPolicyPayload | MeshClaimReleaseResult | MeshInvocationPage | ProjectKnowledgePage,
61
+ payload: ProjectPolicyPayload | MeshClaimReleaseResult | MeshInvocationPage | ProjectKnowledgePage
62
+ | MeshRepositoryList | MeshRepositoryEditResult,
60
63
  to: Role | "all" = "phone",
61
64
  options: SendOptions = {},
62
65
  ): Promise<void> {
@@ -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
+ }