@tidegap/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Handoff fields of a task queued from an agent session: the folder a run
3
+ * works in (`cwd`), its tool profile and the result file Tidegap writes when
4
+ * it completes. Pure rules with injected file-system reads, so the MCP
5
+ * server, the CLI and the tick apply the same checks, at enqueue and again
6
+ * before a run or a write.
7
+ *
8
+ * Runs stay read-only: a profile only names one of the existing tool sets,
9
+ * and only Tidegap writes a result file, as a new file, never through a
10
+ * link.
11
+ */
12
+ /** A tool profile: a name for one of the existing tool sets. */
13
+ export type HandoffProfile = "read" | "web" | "none";
14
+ export declare const HANDOFF_PROFILES: readonly HandoffProfile[];
15
+ /** The tools of each profile. `read` is scoped to the run's folder by the adapter. */
16
+ export declare const PROFILE_TOOLS: Readonly<Record<HandoffProfile, readonly string[]>>;
17
+ /** The handoff fields of a task body (`ProviderCallSpec.handoff`). */
18
+ export interface HandoffSpec {
19
+ /** The folder a `claude-code` run works in. */
20
+ cwd?: string;
21
+ /** The tool profile; `read` when only `cwd` is given. */
22
+ profile?: HandoffProfile;
23
+ /** The new file Tidegap writes the result text to when the task completes. */
24
+ resultPath?: string;
25
+ /**
26
+ * Wake the idle Claude Code session that queued the task when it
27
+ * finishes (the plugin's Stop hook). Needs a checked session origin.
28
+ */
29
+ wake?: boolean;
30
+ }
31
+ /** Longest result or output path. */
32
+ export declare const HANDOFF_PATH_MAX_CHARS = 1024;
33
+ /** What the rules need to know about one path; no link is followed. */
34
+ export interface HandoffFsEntry {
35
+ kind: "file" | "dir" | "symlink" | "other";
36
+ uid: number;
37
+ }
38
+ /** The file-system reads of the rules. Tests inject their own. */
39
+ export interface HandoffFs {
40
+ /** The real path (links resolved), or undefined when the path does not resolve. */
41
+ realpath(path: string): string | undefined;
42
+ /** What is at `path` itself (a link is not followed), or undefined when nothing is. */
43
+ lstat(path: string): HandoffFsEntry | undefined;
44
+ /**
45
+ * The identity of the folder or file at `path` (links followed), such as
46
+ * `<dev>:<ino>`, or undefined when nothing is there. Two spellings of one
47
+ * folder (another letter case, a firmlink such as `/System/Volumes/Data`)
48
+ * have the same identity. Optional: without it, only the spelling counts.
49
+ */
50
+ identity?(path: string): string | undefined;
51
+ }
52
+ export declare const nodeHandoffFs: HandoffFs;
53
+ /** Where a result or output file may go, and how the rules read the disk. */
54
+ export interface HandoffPathContext {
55
+ /** The task's own folder (`handoff.cwd`, or the command's `cwd`). */
56
+ cwd?: string;
57
+ /** The origin session's project folder (the `origin_cwd` column). */
58
+ originCwd?: string;
59
+ /** Default: this user's home folder. */
60
+ home?: string;
61
+ /** Default: the system temp folder and `/tmp`. */
62
+ tmpDirs?: readonly string[];
63
+ fs?: HandoffFs;
64
+ /** Default: this process's user id. */
65
+ uid?: number;
66
+ }
67
+ /**
68
+ * Folders under the home folder that no handoff file or `claude-code` folder
69
+ * may be in. The handoff and tools pages list them; docs-drift compares.
70
+ */
71
+ export declare const PROTECTED_HOME_DIRS: readonly string[];
72
+ /**
73
+ * Check a result path: the location rules, and create-only (nothing may be
74
+ * at the path yet, not even a link). Returns the error message, or
75
+ * undefined when the path is allowed.
76
+ */
77
+ export declare function resultPathError(path: unknown, ctx?: HandoffPathContext): string | undefined;
78
+ /**
79
+ * Check an `output_path`: the location rules; a file already there must be
80
+ * a regular file (not a link) that this user owns, which the JSON then
81
+ * replaces. Returns the error message, or undefined when the path is allowed.
82
+ */
83
+ export declare function outputPathError(path: unknown, ctx?: HandoffPathContext): string | undefined;
84
+ /**
85
+ * Check the folder of a handed-off run. Every runner: an absolute path in
86
+ * its `path.resolve` form to an existing folder. `claude-code` also: not
87
+ * `/` or the home folder, owned by this user, and not inside a dot folder
88
+ * of the home folder, `~/Library` or a `.git` folder (links resolved too).
89
+ * Returns the error message, or undefined.
90
+ */
91
+ export declare function handoffCwdError(cwd: unknown, runner: "claude-code" | "command", ctx?: Pick<HandoffPathContext, "home" | "fs" | "uid">): string | undefined;
92
+ /** The profile and tools a handoff asks for, or the reason it is refused. */
93
+ export interface ProfileChoice {
94
+ profile?: HandoffProfile;
95
+ tools?: string[];
96
+ error?: string;
97
+ }
98
+ /**
99
+ * The tool set of a profile. A `cwd` with no profile means `read`; `web`
100
+ * runs in a fresh temporary folder, so it refuses a `cwd`. Neither given:
101
+ * no profile (the runner's default tools apply).
102
+ */
103
+ export declare function profileTools(profile: unknown, cwd: string | undefined): ProfileChoice;
104
+ /** True when two tool lists name the same tools. */
105
+ export declare function sameTools(a: readonly string[], b: readonly string[]): boolean;
106
+ /** What a task runs and where (the handed-off work shape), from its body. */
107
+ export interface TaskWorkShape {
108
+ runner?: string;
109
+ cwd?: string;
110
+ profile?: string;
111
+ tools?: string[];
112
+ resultPath?: string;
113
+ /** True when the task wakes its idle origin session when it finishes. */
114
+ wake?: boolean;
115
+ /** The shell command of a one-off command task. */
116
+ command?: string;
117
+ }
118
+ /** {@link TaskWorkShape} of a task; empty for a closure task or a corrupt body. */
119
+ export declare function taskWorkShape(record: {
120
+ bodyJson?: string;
121
+ }): TaskWorkShape;
122
+ /** The details of a task's newest `result_file` event, or undefined. */
123
+ export declare function latestResultFile(events: ReadonlyArray<{
124
+ kind: string;
125
+ details: Record<string, unknown>;
126
+ }> | undefined): Record<string, unknown> | undefined;
127
+ /** A result file's state in words: `written, 12 bytes`, `not written: <error>`, or `not written yet`. */
128
+ export declare function resultFileText(details: Record<string, unknown> | undefined): string;
129
+ /**
130
+ * Why a task may not ask for a wake, or undefined when it may: a wake is
131
+ * `true` or absent, and `true` needs a checked Claude Code session origin
132
+ * (the body's `origin` and a valid session id), so the right session wakes.
133
+ */
134
+ export declare function wakeError(wake: unknown, origin: {
135
+ agent?: unknown;
136
+ } | undefined, sessionId: unknown): string | undefined;
137
+ /**
138
+ * The default ledger, `~/.tidegap/queue.db`: the one the CLI, the tick
139
+ * and the plugin's hooks read when no path is given. When only the legacy
140
+ * `~/.ebb/queue.sqlite` exists, that file is returned, so its data stays
141
+ * visible. The MCP server's own default is `queue.db` with no legacy
142
+ * fallback; it creates that file at start, so the two agree from then on.
143
+ */
144
+ export declare function defaultDbPath(): string;
145
+ /**
146
+ * True when `dbPath` is the default ledger. The session notice and wake
147
+ * markers under `~/.tidegap/sessions` belong to it: the plugin's hooks
148
+ * read that ledger only, so a pass over another ledger must neither
149
+ * create nor remove them, and a wake for a task in another ledger could
150
+ * never fire. Compares real paths; a missing file compares by
151
+ * its folder's real path and its name.
152
+ */
153
+ export declare function isDefaultLedger(dbPath: string): boolean;
154
+ /** A wake marker with no wake task left to wait for goes this long after its last refresh (the waiter refreshes it at every Stop). */
155
+ export declare const WAKE_MARKER_MAX_AGE_MS: number;
156
+ /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
157
+ export declare function wakeMarkersDir(home?: string): string;
158
+ /** The wake marker of one session, or undefined for an id that fails the id rule. */
159
+ export declare function wakeMarkerPath(sessionId: string, dir?: string): string | undefined;
160
+ /**
161
+ * Create or refresh a session's wake marker (file `0600`, folder `0700`),
162
+ * so the plugin's Stop hook starts its waiter; its time is `now`. Returns
163
+ * the error message, or undefined. Something other than a regular file at
164
+ * the path is left alone and reported. A waiter or the sweep may remove
165
+ * or write the marker at the same moment: a refresh that finds it gone
166
+ * creates it, and a create that finds one there refreshes it.
167
+ */
168
+ export declare function writeWakeMarker(sessionId: string, dir?: string, now?: Date): string | undefined;
169
+ /** Remove a session's wake marker; a missing one is fine. */
170
+ export declare function removeWakeMarker(sessionId: string, dir?: string): void;
171
+ //# sourceMappingURL=handoff.d.ts.map
@@ -0,0 +1,482 @@
1
+ /**
2
+ * Handoff fields of a task queued from an agent session: the folder a run
3
+ * works in (`cwd`), its tool profile and the result file Tidegap writes when
4
+ * it completes. Pure rules with injected file-system reads, so the MCP
5
+ * server, the CLI and the tick apply the same checks, at enqueue and again
6
+ * before a run or a write.
7
+ *
8
+ * Runs stay read-only: a profile only names one of the existing tool sets,
9
+ * and only Tidegap writes a result file, as a new file, never through a
10
+ * link.
11
+ */
12
+ import { chmodSync, existsSync, lstatSync, mkdirSync, realpathSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
13
+ import { homedir, tmpdir } from "node:os";
14
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
15
+ import { isValidSessionId } from "./history.js";
16
+ import { resolveTidegapHome } from "./paths.js";
17
+ export const HANDOFF_PROFILES = ["read", "web", "none"];
18
+ /** The tools of each profile. `read` is scoped to the run's folder by the adapter. */
19
+ export const PROFILE_TOOLS = {
20
+ read: ["Read", "Grep", "Glob"],
21
+ web: ["WebSearch", "WebFetch"],
22
+ none: [],
23
+ };
24
+ /** Longest result or output path. */
25
+ export const HANDOFF_PATH_MAX_CHARS = 1024;
26
+ export const nodeHandoffFs = {
27
+ realpath(path) {
28
+ try {
29
+ // The native call also returns the on-disk letter case (macOS).
30
+ return realpathSync.native(path);
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ },
36
+ identity(path) {
37
+ try {
38
+ const s = statSync(path);
39
+ return `${s.dev}:${s.ino}`;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ },
45
+ lstat(path) {
46
+ try {
47
+ const s = lstatSync(path);
48
+ const kind = s.isSymbolicLink() ? "symlink" : s.isDirectory() ? "dir" : s.isFile() ? "file" : "other";
49
+ return { kind, uid: s.uid };
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ },
55
+ };
56
+ /**
57
+ * Folders under the home folder that no handoff file or `claude-code` folder
58
+ * may be in. The handoff and tools pages list them; docs-drift compares.
59
+ */
60
+ export const PROTECTED_HOME_DIRS = Object.freeze([".tidegap", ".config", ".claude", ".ssh", ".gnupg", ".aws", "Library"]);
61
+ // eslint-disable-next-line no-control-regex
62
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
63
+ /** True when `path` is `dir` or below it. */
64
+ function inside(path, dir) {
65
+ if (path === dir)
66
+ return true;
67
+ return path.startsWith(dir.endsWith("/") ? dir : `${dir}/`);
68
+ }
69
+ function segments(rel) {
70
+ return rel.split("/").filter((s) => s !== "");
71
+ }
72
+ function unique(values) {
73
+ return [...new Set(values.filter((v) => typeof v === "string" && v !== ""))];
74
+ }
75
+ /** The home folder as given and as its real path. */
76
+ function homes(home, fs) {
77
+ return unique([home, fs.realpath(home)]);
78
+ }
79
+ /** True when `path` is `dir` or below it, in any letter case (a case-insensitive disk). */
80
+ function insideAnyCase(path, dir) {
81
+ return inside(path.toLowerCase(), dir.toLowerCase());
82
+ }
83
+ /**
84
+ * Where `path` sits relative to the home folder: `{ first: undefined }` when
85
+ * it is the home folder, `{ first }` with the first name below it, or
86
+ * undefined when it is not inside. Matches the spelling in any letter case,
87
+ * then the identity of each folder above `path`, so another spelling of the
88
+ * home folder (a firmlink, another case) is found too.
89
+ */
90
+ function homeSegment(path, homeDirs, fs) {
91
+ for (const h of homeDirs) {
92
+ if (!insideAnyCase(path, h))
93
+ continue;
94
+ const first = segments(path)[segments(h).length];
95
+ return first === undefined ? { home: h } : { home: h, first };
96
+ }
97
+ const identity = fs.identity?.bind(fs);
98
+ if (!identity)
99
+ return undefined;
100
+ const homeIds = new Set(homeDirs.map((h) => identity(h)).filter((id) => id !== undefined));
101
+ if (homeIds.size === 0)
102
+ return undefined;
103
+ let cur = path;
104
+ let child;
105
+ for (;;) {
106
+ const id = identity(cur);
107
+ if (id !== undefined && homeIds.has(id))
108
+ return child === undefined ? { home: cur } : { home: cur, first: child };
109
+ const up = dirname(cur);
110
+ if (up === cur)
111
+ return undefined;
112
+ child = basename(cur);
113
+ cur = up;
114
+ }
115
+ }
116
+ /** True when `dir` is `/` or the home folder, by spelling or identity. */
117
+ function isRootOrHome(dir, homeDirs, fs) {
118
+ const real = fs.realpath(dir) ?? dir;
119
+ if (dir === "/" || real === "/")
120
+ return true;
121
+ const id = fs.identity?.(real);
122
+ if (id !== undefined && id === fs.identity?.("/"))
123
+ return true;
124
+ const at = homeSegment(real, homeDirs, fs);
125
+ return at !== undefined && at.first === undefined;
126
+ }
127
+ /** True when a name is `.git` in any letter case. */
128
+ function isGitName(name) {
129
+ return name.toLowerCase() === ".git";
130
+ }
131
+ /**
132
+ * The shape rule: an absolute path of at most {@link HANDOFF_PATH_MAX_CHARS}
133
+ * characters, without control characters, equal to its `path.resolve` form
134
+ * (no `.` or `..` segments, no repeated or trailing `/`). Links are not
135
+ * resolved here.
136
+ */
137
+ function shapeError(name, path) {
138
+ if (typeof path !== "string" || path === "")
139
+ return `${name} must be an absolute path`;
140
+ if (CONTROL_CHARS.test(path))
141
+ return `${name} must not contain control characters`;
142
+ if (path.length > HANDOFF_PATH_MAX_CHARS)
143
+ return `${name} is longer than ${HANDOFF_PATH_MAX_CHARS} characters`;
144
+ if (!isAbsolute(path))
145
+ return `${name} must be an absolute path, got ${JSON.stringify(path)}`;
146
+ if (resolve(path) !== path) {
147
+ return `${name} ${JSON.stringify(path)} must have no "." or ".." segments and no repeated or trailing "/"`;
148
+ }
149
+ return undefined;
150
+ }
151
+ /**
152
+ * The protected folder `path` is in, or undefined: a home dot folder of the
153
+ * list, `~/Library`, or any `.git` folder. Names match in any letter case,
154
+ * and the home folder also by identity (see {@link homeSegment}).
155
+ */
156
+ function protectedDir(path, homeDirs, fs) {
157
+ const at = homeSegment(path, homeDirs, fs);
158
+ const first = at?.first?.toLowerCase();
159
+ const match = first === undefined ? undefined : PROTECTED_HOME_DIRS.find((d) => d.toLowerCase() === first);
160
+ if (at && match)
161
+ return join(homeDirs.includes(at.home) ? at.home : (homeDirs[0] ?? at.home), match);
162
+ if (segments(path).some(isGitName))
163
+ return "a .git folder";
164
+ return undefined;
165
+ }
166
+ /**
167
+ * The location rules of a result or output file. 1: the shape rule. 2: the
168
+ * real path of the parent folder is inside the real path of an allowed root
169
+ * (the task's folder, the session's project folder, the temp folders; never
170
+ * `/` or the home folder itself), no folder or file name below that root
171
+ * starts with `.`, and every folder below that root is this user's. 3:
172
+ * neither the path nor the parent's real path is in a protected folder.
173
+ */
174
+ function locationError(name, path, ctx) {
175
+ const shape = shapeError(name, path);
176
+ if (shape)
177
+ return shape;
178
+ const p = path;
179
+ const fs = ctx.fs ?? nodeHandoffFs;
180
+ const homeDirs = homes(ctx.home ?? homedir(), fs);
181
+ // A session started in `/` or the home folder names no project: those are not roots.
182
+ const roots = unique([ctx.cwd, ctx.originCwd, ...(ctx.tmpDirs ?? [tmpdir(), "/tmp"])]).filter((root) => !isRootOrHome(root, homeDirs, fs));
183
+ const allowed = `; allowed folders: ${roots.join(", ") || "none"}`;
184
+ const uid = ctx.uid ?? process.getuid?.();
185
+ const isProtected = (candidate) => {
186
+ const dir = protectedDir(candidate, homeDirs, fs);
187
+ return dir ? `${name} ${p} is inside ${dir}, a protected folder${allowed}` : undefined;
188
+ };
189
+ const given = isProtected(p);
190
+ if (given)
191
+ return given;
192
+ const parent = dirname(p);
193
+ const realParent = fs.realpath(parent);
194
+ if (!realParent)
195
+ return `${name} ${p}: the folder ${parent} does not exist${allowed}`;
196
+ const real = isProtected(join(realParent, basename(p)));
197
+ if (real)
198
+ return real;
199
+ let dotted = false;
200
+ for (const root of roots) {
201
+ const realRoot = fs.realpath(root);
202
+ if (!realRoot || !inside(realParent, realRoot))
203
+ continue;
204
+ const below = [...segments(relative(realRoot, realParent)), basename(p)];
205
+ const lexical = inside(p, root) ? segments(relative(root, p)) : [];
206
+ if ([...below, ...lexical].some((s) => s.startsWith("."))) {
207
+ dotted = true;
208
+ continue;
209
+ }
210
+ // Another user's folder below the root could be swapped for a link after this check.
211
+ for (let dir = realParent; dir !== realRoot && inside(dir, realRoot); dir = dirname(dir)) {
212
+ const entry = fs.lstat(dir);
213
+ if (entry?.kind !== "dir" || (uid !== undefined && entry.uid !== uid)) {
214
+ return `${name} ${p}: the folder ${dir} is not a folder you own${allowed}`;
215
+ }
216
+ }
217
+ return undefined;
218
+ }
219
+ if (dotted)
220
+ return `${name} ${p}: no folder or file name below the allowed folder may start with "."${allowed}`;
221
+ return `${name} ${p} must be inside one of these folders: ${roots.join(", ") || "none"}`;
222
+ }
223
+ /**
224
+ * Check a result path: the location rules, and create-only (nothing may be
225
+ * at the path yet, not even a link). Returns the error message, or
226
+ * undefined when the path is allowed.
227
+ */
228
+ export function resultPathError(path, ctx = {}) {
229
+ const location = locationError("result path", path, ctx);
230
+ if (location)
231
+ return location;
232
+ const fs = ctx.fs ?? nodeHandoffFs;
233
+ if (fs.lstat(path))
234
+ return `result path ${path} already exists; a result file is never replaced`;
235
+ return undefined;
236
+ }
237
+ /**
238
+ * Check an `output_path`: the location rules; a file already there must be
239
+ * a regular file (not a link) that this user owns, which the JSON then
240
+ * replaces. Returns the error message, or undefined when the path is allowed.
241
+ */
242
+ export function outputPathError(path, ctx = {}) {
243
+ const location = locationError("output path", path, ctx);
244
+ if (location)
245
+ return location;
246
+ const fs = ctx.fs ?? nodeHandoffFs;
247
+ const entry = fs.lstat(path);
248
+ if (!entry)
249
+ return undefined;
250
+ const uid = ctx.uid ?? process.getuid?.();
251
+ if (entry.kind !== "file" || (uid !== undefined && entry.uid !== uid)) {
252
+ return `output path ${path} exists and is not a regular file you own`;
253
+ }
254
+ return undefined;
255
+ }
256
+ /**
257
+ * Check the folder of a handed-off run. Every runner: an absolute path in
258
+ * its `path.resolve` form to an existing folder. `claude-code` also: not
259
+ * `/` or the home folder, owned by this user, and not inside a dot folder
260
+ * of the home folder, `~/Library` or a `.git` folder (links resolved too).
261
+ * Returns the error message, or undefined.
262
+ */
263
+ export function handoffCwdError(cwd, runner, ctx = {}) {
264
+ const shape = shapeError("cwd", cwd);
265
+ if (shape)
266
+ return shape;
267
+ const dir = cwd;
268
+ const fs = ctx.fs ?? nodeHandoffFs;
269
+ const real = fs.realpath(dir);
270
+ const entry = real ? fs.lstat(real) : undefined;
271
+ if (!real || entry?.kind !== "dir")
272
+ return `cwd ${dir} is not an existing folder`;
273
+ if (runner === "command")
274
+ return undefined;
275
+ const homeDirs = homes(ctx.home ?? homedir(), fs);
276
+ if (isRootOrHome(dir, homeDirs, fs) || isRootOrHome(real, homeDirs, fs))
277
+ return `cwd ${dir} is the root or home folder`;
278
+ const uid = ctx.uid ?? process.getuid?.();
279
+ if (uid !== undefined && entry.uid !== uid)
280
+ return `cwd ${dir} belongs to another user`;
281
+ for (const candidate of [dir, real]) {
282
+ const at = homeSegment(candidate, homeDirs, fs);
283
+ const first = at?.first;
284
+ if (at && first !== undefined && (first.startsWith(".") || first.toLowerCase() === "library")) {
285
+ return `cwd ${dir} is inside ${join(at.home, first)}, a protected folder`;
286
+ }
287
+ if (segments(candidate).some(isGitName))
288
+ return `cwd ${dir} is inside a .git folder`;
289
+ }
290
+ return undefined;
291
+ }
292
+ /**
293
+ * The tool set of a profile. A `cwd` with no profile means `read`; `web`
294
+ * runs in a fresh temporary folder, so it refuses a `cwd`. Neither given:
295
+ * no profile (the runner's default tools apply).
296
+ */
297
+ export function profileTools(profile, cwd) {
298
+ if (profile === undefined) {
299
+ return cwd === undefined ? {} : { profile: "read", tools: [...PROFILE_TOOLS.read] };
300
+ }
301
+ if (typeof profile !== "string" || !HANDOFF_PROFILES.includes(profile)) {
302
+ return { error: `profile must be one of ${HANDOFF_PROFILES.join(", ")}, got ${JSON.stringify(profile)}` };
303
+ }
304
+ const p = profile;
305
+ if (p === "web" && cwd !== undefined) {
306
+ return { error: "profile web runs in a fresh temporary folder and cannot take a cwd; use profile read with a cwd" };
307
+ }
308
+ return { profile: p, tools: [...PROFILE_TOOLS[p]] };
309
+ }
310
+ /** True when two tool lists name the same tools. */
311
+ export function sameTools(a, b) {
312
+ return a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
313
+ }
314
+ /** {@link TaskWorkShape} of a task; empty for a closure task or a corrupt body. */
315
+ export function taskWorkShape(record) {
316
+ if (!record.bodyJson)
317
+ return {};
318
+ let spec;
319
+ try {
320
+ spec = JSON.parse(record.bodyJson);
321
+ }
322
+ catch {
323
+ return {};
324
+ }
325
+ const str = (v) => (typeof v === "string" && v !== "" ? v : undefined);
326
+ const oneOff = spec?.provider === "command" && spec.command?.origin === "cli";
327
+ const out = {};
328
+ const runner = str(spec?.provider);
329
+ if (runner)
330
+ out.runner = runner;
331
+ const cwd = str(spec?.handoff?.cwd) ?? (oneOff ? str(spec.command?.cwd) : undefined);
332
+ if (cwd)
333
+ out.cwd = cwd;
334
+ const profile = str(spec?.handoff?.profile);
335
+ if (profile)
336
+ out.profile = profile;
337
+ if (Array.isArray(spec?.tools))
338
+ out.tools = spec.tools.filter((t) => typeof t === "string");
339
+ const resultPath = str(spec?.handoff?.resultPath);
340
+ if (resultPath)
341
+ out.resultPath = resultPath;
342
+ if (spec?.handoff?.wake === true)
343
+ out.wake = true;
344
+ const command = oneOff ? str(spec.command?.run) : undefined;
345
+ if (command)
346
+ out.command = command;
347
+ return out;
348
+ }
349
+ /** The details of a task's newest `result_file` event, or undefined. */
350
+ export function latestResultFile(events) {
351
+ return [...(events ?? [])].reverse().find((e) => e.kind === "result_file")?.details;
352
+ }
353
+ /** A result file's state in words: `written, 12 bytes`, `not written: <error>`, or `not written yet`. */
354
+ export function resultFileText(details) {
355
+ if (!details)
356
+ return "not written yet";
357
+ if (details.written === true)
358
+ return typeof details.bytes === "number" ? `written, ${details.bytes} bytes` : "written";
359
+ return `not written: ${typeof details.error === "string" ? details.error : "unknown error"}`;
360
+ }
361
+ /**
362
+ * Why a task may not ask for a wake, or undefined when it may: a wake is
363
+ * `true` or absent, and `true` needs a checked Claude Code session origin
364
+ * (the body's `origin` and a valid session id), so the right session wakes.
365
+ */
366
+ export function wakeError(wake, origin, sessionId) {
367
+ if (wake === undefined || wake === false)
368
+ return undefined;
369
+ if (wake !== true)
370
+ return "wake must be true or false";
371
+ if (origin?.agent !== "claude-code" || !isValidSessionId(sessionId)) {
372
+ return "a wake needs a task queued from a Claude Code session (the session that wakes); queue it from the session, or drop the wake";
373
+ }
374
+ return undefined;
375
+ }
376
+ /**
377
+ * The default ledger, `~/.tidegap/queue.db`: the one the CLI, the tick
378
+ * and the plugin's hooks read when no path is given. When only the legacy
379
+ * `~/.ebb/queue.sqlite` exists, that file is returned, so its data stays
380
+ * visible. The MCP server's own default is `queue.db` with no legacy
381
+ * fallback; it creates that file at start, so the two agree from then on.
382
+ */
383
+ export function defaultDbPath() {
384
+ const newPath = join(resolveTidegapHome(), "queue.db");
385
+ const legacyPath = join(homedir(), ".ebb", "queue.sqlite");
386
+ if (!existsSync(newPath) && existsSync(legacyPath))
387
+ return legacyPath;
388
+ return newPath;
389
+ }
390
+ /**
391
+ * True when `dbPath` is the default ledger. The session notice and wake
392
+ * markers under `~/.tidegap/sessions` belong to it: the plugin's hooks
393
+ * read that ledger only, so a pass over another ledger must neither
394
+ * create nor remove them, and a wake for a task in another ledger could
395
+ * never fire. Compares real paths; a missing file compares by
396
+ * its folder's real path and its name.
397
+ */
398
+ export function isDefaultLedger(dbPath) {
399
+ if (dbPath === ":memory:")
400
+ return false;
401
+ // A missing file resolves through its folder, so a linked home still matches.
402
+ const real = (path) => {
403
+ try {
404
+ return realpathSync.native(path);
405
+ }
406
+ catch {
407
+ try {
408
+ return join(realpathSync.native(dirname(path)), basename(path));
409
+ }
410
+ catch {
411
+ return resolve(path);
412
+ }
413
+ }
414
+ };
415
+ return real(dbPath) === real(defaultDbPath());
416
+ }
417
+ /** A wake marker with no wake task left to wait for goes this long after its last refresh (the waiter refreshes it at every Stop). */
418
+ export const WAKE_MARKER_MAX_AGE_MS = 12 * 3_600_000;
419
+ /** `~/.tidegap/sessions/wake`: one marker per session with a task to wake it for. */
420
+ export function wakeMarkersDir(home = resolveTidegapHome()) {
421
+ return join(home, "sessions", "wake");
422
+ }
423
+ /** The wake marker of one session, or undefined for an id that fails the id rule. */
424
+ export function wakeMarkerPath(sessionId, dir = wakeMarkersDir()) {
425
+ return isValidSessionId(sessionId) ? join(dir, sessionId) : undefined;
426
+ }
427
+ /**
428
+ * Create or refresh a session's wake marker (file `0600`, folder `0700`),
429
+ * so the plugin's Stop hook starts its waiter; its time is `now`. Returns
430
+ * the error message, or undefined. Something other than a regular file at
431
+ * the path is left alone and reported. A waiter or the sweep may remove
432
+ * or write the marker at the same moment: a refresh that finds it gone
433
+ * creates it, and a create that finds one there refreshes it.
434
+ */
435
+ export function writeWakeMarker(sessionId, dir = wakeMarkersDir(), now = new Date()) {
436
+ const path = wakeMarkerPath(sessionId, dir);
437
+ if (!path)
438
+ return "not a session id";
439
+ try {
440
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
441
+ chmodSync(dir, 0o700);
442
+ for (let attempt = 0;; attempt++) {
443
+ let there;
444
+ try {
445
+ there = lstatSync(path);
446
+ }
447
+ catch {
448
+ there = undefined;
449
+ }
450
+ if (there && !there.isFile())
451
+ return `${path} is not a regular file`;
452
+ try {
453
+ if (!there)
454
+ writeFileSync(path, `${now.toISOString()}\n`, { mode: 0o600, flag: "wx" });
455
+ utimesSync(path, now, now);
456
+ return undefined;
457
+ }
458
+ catch (err) {
459
+ // Removed or created by another writer since the look: look once more.
460
+ const code = err.code;
461
+ if (attempt > 0 || (code !== "ENOENT" && code !== "EEXIST"))
462
+ throw err;
463
+ }
464
+ }
465
+ }
466
+ catch (err) {
467
+ return err.message;
468
+ }
469
+ }
470
+ /** Remove a session's wake marker; a missing one is fine. */
471
+ export function removeWakeMarker(sessionId, dir = wakeMarkersDir()) {
472
+ const path = wakeMarkerPath(sessionId, dir);
473
+ if (!path)
474
+ return;
475
+ try {
476
+ unlinkSync(path);
477
+ }
478
+ catch {
479
+ // already gone
480
+ }
481
+ }
482
+ //# sourceMappingURL=handoff.js.map
package/dist/history.d.ts CHANGED
@@ -64,11 +64,28 @@ export interface TaskActions {
64
64
  reschedule: boolean;
65
65
  /** Queued or scheduled provider-call task: mark it due for the next tick. */
66
66
  runNow: boolean;
67
+ /** Queued or scheduled provider-call task: move it later ("Later", same rule as `reschedule`). */
68
+ later: boolean;
67
69
  /** Completed provider-call task: enqueue a reply child. */
68
70
  reply: boolean;
69
71
  /** Finished (completed or failed): mark read or unread. */
70
72
  markRead: boolean;
73
+ /**
74
+ * Failed provider-call one-off task, a `command` task included: retry it
75
+ * by hand (due on the next tick). A run of a job, and a run that stopped
76
+ * during its Batch submit, are refused.
77
+ */
78
+ retry: boolean;
71
79
  }
80
+ /**
81
+ * The error of a row whose Batch submit a forced stop interrupted (batch 25
82
+ * KTD5). The provider may hold a batch for it, so no path runs it again:
83
+ * `retryTask` and the Python `retry_task` refuse it, and the sweep does not
84
+ * retry it. The text is the marker; `test/fixtures/interrupted-batch-submit.json`
85
+ * shares it with the Python core. It lives here, not in `jobs.ts`, so this
86
+ * module imports nothing from `jobs.ts` (which imports `deriveTitle` from here).
87
+ */
88
+ export declare const BATCH_SUBMIT_INTERRUPTED_ERROR = "interrupted: the tick stopped during the Batch submit; the provider may have accepted the batch, so check the provider's batch list before you enqueue the task again";
72
89
  /** True when the task repeats (a stored rule other than `none`). */
73
90
  export declare function isRepeating(record: Pick<TaskRecord<unknown>, "repeat">): boolean;
74
91
  /** Allowed actions for `record`; see {@link TaskActions}. */