@wirecat/cli-core 0.641.0 → 0.643.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 (287) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/dist/analysis/provider.d.ts +1 -1
  3. package/dist/analysis/provider.js +2 -1
  4. package/dist/attachments/gateway-ocr.js +13 -8
  5. package/dist/attachments/ocr.js +27 -18
  6. package/dist/attachments/picture-reading.d.ts +51 -0
  7. package/dist/attachments/picture-reading.js +207 -0
  8. package/dist/background/backfill.d.ts +4 -2
  9. package/dist/background/backfill.js +3 -3
  10. package/dist/background/schedules.d.ts +28 -2
  11. package/dist/background/schedules.js +73 -20
  12. package/dist/background/units.d.ts +2 -0
  13. package/dist/background/units.js +8 -9
  14. package/dist/calendar/cli/index.js +10 -2
  15. package/dist/calendar/feeds.js +2 -2
  16. package/dist/calendar/mcp/index.d.ts +12 -12
  17. package/dist/calendar/server-search.js +2 -2
  18. package/dist/calendar/source.d.ts +4 -3
  19. package/dist/calendar/sync.js +12 -10
  20. package/dist/calendar/testing/source-contract.js +5 -4
  21. package/dist/calendar/testing/source.js +3 -2
  22. package/dist/cli/ai-model-command.js +6 -3
  23. package/dist/cli/analysis-choice.js +20 -4
  24. package/dist/cli/complete-command.d.ts +23 -0
  25. package/dist/cli/complete-command.js +80 -0
  26. package/dist/cli/context.js +7 -1
  27. package/dist/cli/effects.d.ts +2 -0
  28. package/dist/cli/effects.js +2 -0
  29. package/dist/cli/enrichment-consents-command.js +2 -0
  30. package/dist/cli/envelope.js +6 -1
  31. package/dist/cli/help/first-screen.js +5 -0
  32. package/dist/cli/index.d.ts +4 -2
  33. package/dist/cli/index.js +2 -1
  34. package/dist/cli/list-query.d.ts +3 -1
  35. package/dist/cli/list-query.js +5 -3
  36. package/dist/cli/local-only-command.d.ts +10 -0
  37. package/dist/cli/local-only-command.js +112 -0
  38. package/dist/cli/messenger/backfill-command.js +1 -1
  39. package/dist/cli/messenger/chat-queries.js +2 -1
  40. package/dist/cli/messenger/complete-command.d.ts +4 -7
  41. package/dist/cli/messenger/complete-command.js +31 -98
  42. package/dist/cli/messenger/contacts-command.js +4 -0
  43. package/dist/cli/messenger/conversations-command.js +1 -1
  44. package/dist/cli/messenger/guard-commands.js +1 -1
  45. package/dist/cli/messenger/images-command.js +32 -0
  46. package/dist/cli/messenger/list-result-queries.d.ts +1 -0
  47. package/dist/cli/messenger/list-result-queries.js +2 -1
  48. package/dist/cli/messenger/mentions-command.js +3 -3
  49. package/dist/cli/messenger/message-items.js +1 -0
  50. package/dist/cli/messenger/messages-command.js +7 -6
  51. package/dist/cli/messenger/people-queries.d.ts +2 -2
  52. package/dist/cli/messenger/people-queries.js +4 -4
  53. package/dist/cli/messenger/replies-consents-command.js +12 -6
  54. package/dist/cli/messenger/search-answers.js +2 -2
  55. package/dist/cli/messenger/search-command.js +3 -3
  56. package/dist/cli/messenger/searches-command.js +1 -1
  57. package/dist/cli/messenger/store-maintenance-command.js +4 -0
  58. package/dist/cli/messenger/tasks-analysis-command.js +1 -1
  59. package/dist/cli/messenger/tasks-command.js +2 -2
  60. package/dist/cli/model-catalogue-command.js +4 -0
  61. package/dist/cli/picture-reading-command.d.ts +12 -0
  62. package/dist/cli/picture-reading-command.js +82 -0
  63. package/dist/cli/program.d.ts +6 -0
  64. package/dist/cli/program.js +28 -2
  65. package/dist/cli/schedule/agent-start.d.ts +23 -0
  66. package/dist/cli/schedule/agent-start.js +115 -0
  67. package/dist/cli/schedule/harnesses.d.ts +203 -0
  68. package/dist/cli/schedule/harnesses.js +278 -0
  69. package/dist/cli/schedule/schedule-command.d.ts +9 -5
  70. package/dist/cli/schedule/schedule-command.js +89 -79
  71. package/dist/cli/search-harder-consents-command.js +16 -1
  72. package/dist/cli/shared-command-exports.d.ts +186 -0
  73. package/dist/cli/shared-command-exports.js +2 -0
  74. package/dist/cli/untrusted-marks.d.ts +25 -0
  75. package/dist/cli/untrusted-marks.js +102 -0
  76. package/dist/crm/cli/index.d.ts +1 -0
  77. package/dist/crm/cli/index.js +6 -5
  78. package/dist/crm/cli/store.d.ts +30 -0
  79. package/dist/crm/cli/store.js +63 -0
  80. package/dist/crm/source.d.ts +6 -4
  81. package/dist/crm/sync.js +10 -6
  82. package/dist/crm/testing/source-contract.js +9 -7
  83. package/dist/crm/testing/source.js +6 -2
  84. package/dist/crm/testing/sync-contract.js +4 -4
  85. package/dist/crm/writes.d.ts +5 -2
  86. package/dist/crm/writes.js +1 -1
  87. package/dist/documents.d.ts +2 -1
  88. package/dist/documents.js +2 -1
  89. package/dist/domain/addresses.d.ts +2 -0
  90. package/dist/domain/addresses.js +7 -0
  91. package/dist/domain/attachments.d.ts +2 -0
  92. package/dist/domain/attachments.js +2 -1
  93. package/dist/domain/models.d.ts +2 -0
  94. package/dist/embeddings/remote.d.ts +2 -1
  95. package/dist/embeddings/remote.js +5 -3
  96. package/dist/entities/attachment-results.d.ts +3 -0
  97. package/dist/entities/attachment-results.js +3 -0
  98. package/dist/entities/attachment.d.ts +2 -0
  99. package/dist/entities/attachment.js +8 -1
  100. package/dist/entities/hit.d.ts +1 -0
  101. package/dist/entities/index.d.ts +21 -4
  102. package/dist/entities/index.js +3 -2
  103. package/dist/entities/list-results.d.ts +33 -5
  104. package/dist/entities/list-results.js +33 -5
  105. package/dist/errors/reasons.js +38 -1
  106. package/dist/mail/cli/index.js +7 -6
  107. package/dist/mcp/agent.d.ts +2 -1
  108. package/dist/mcp/agent.js +5 -0
  109. package/dist/mcp/app-server.js +10 -0
  110. package/dist/mcp/surface.d.ts +7 -2
  111. package/dist/mcp/surface.js +49 -10
  112. package/dist/meetings/cli/index.js +6 -1
  113. package/dist/meetings/mcp/index.js +6 -3
  114. package/dist/meetings/participant-search.d.ts +2 -2
  115. package/dist/meetings/project-discovery.d.ts +1 -1
  116. package/dist/meetings/project-evidence-answer.js +2 -2
  117. package/dist/meetings/reads.d.ts +2 -2
  118. package/dist/meetings/reads.js +6 -6
  119. package/dist/meetings/store.d.ts +2 -1
  120. package/dist/meetings/testing/contract.js +6 -6
  121. package/dist/meetings/testing/memory.js +7 -2
  122. package/dist/models/ai.d.ts +17 -4
  123. package/dist/models/ai.js +22 -14
  124. package/dist/models/anthropic.js +15 -9
  125. package/dist/models/endpoint.d.ts +5 -0
  126. package/dist/models/endpoint.js +13 -0
  127. package/dist/models/index.d.ts +4 -0
  128. package/dist/models/index.js +14 -4
  129. package/dist/models/local-only.d.ts +17 -0
  130. package/dist/models/local-only.js +42 -0
  131. package/dist/models/openai.js +24 -11
  132. package/dist/models/purpose.d.ts +24 -0
  133. package/dist/models/purpose.js +26 -0
  134. package/dist/models/types.d.ts +8 -0
  135. package/dist/models/types.js +11 -1
  136. package/dist/ports/app.d.ts +17 -1
  137. package/dist/ports/app.js +63 -3
  138. package/dist/replies/rendering.js +10 -10
  139. package/dist/search/lucene/plain.js +45 -3
  140. package/dist/search/lucene/registry.d.ts +15 -4
  141. package/dist/search/lucene/registry.js +70 -12
  142. package/dist/search/lucene/types.d.ts +2 -0
  143. package/dist/search/lucene/types.js +12 -0
  144. package/dist/sends/upload.d.ts +8 -1
  145. package/dist/sends/upload.js +35 -14
  146. package/dist/services/account-groups.d.ts +11 -0
  147. package/dist/services/account-groups.js +29 -0
  148. package/dist/services/agenda.js +1 -0
  149. package/dist/services/attachments.d.ts +18 -4
  150. package/dist/services/attachments.js +66 -15
  151. package/dist/services/conversations.d.ts +2 -4
  152. package/dist/services/conversations.js +1 -1
  153. package/dist/services/deal-context.js +5 -5
  154. package/dist/services/documents/ingestion.js +3 -3
  155. package/dist/services/documents/knowledge.d.ts +6 -6
  156. package/dist/services/documents/knowledge.js +1 -2
  157. package/dist/services/embeddings-maintenance.js +4 -1
  158. package/dist/services/enrichment.d.ts +1 -1
  159. package/dist/services/enrichment.js +27 -0
  160. package/dist/services/events-search.d.ts +3 -3
  161. package/dist/services/events-search.js +7 -7
  162. package/dist/services/index.d.ts +1 -1
  163. package/dist/services/index.js +1 -1
  164. package/dist/services/meeting-model.js +1 -1
  165. package/dist/services/meeting-project-discovery.js +1 -1
  166. package/dist/services/message-resolution.js +10 -3
  167. package/dist/services/messages-search.js +6 -4
  168. package/dist/services/metadata.d.ts +1 -1
  169. package/dist/services/notes-search.d.ts +3 -3
  170. package/dist/services/notes-search.js +3 -3
  171. package/dist/services/organization-context.js +12 -9
  172. package/dist/services/people.d.ts +2 -0
  173. package/dist/services/people.js +4 -2
  174. package/dist/services/pictures.d.ts +9 -0
  175. package/dist/services/pictures.js +34 -28
  176. package/dist/services/project-status/index.js +1 -1
  177. package/dist/services/project-status/signals/payments.js +4 -2
  178. package/dist/services/project-status/signals/promises.js +5 -2
  179. package/dist/services/proposals/kinds/action.js +1 -1
  180. package/dist/services/proposals/kinds/fact.js +1 -1
  181. package/dist/services/proposals/kinds/findings.d.ts +2 -1
  182. package/dist/services/proposals/kinds/findings.js +12 -5
  183. package/dist/services/proposals/kinds/identity-link.js +1 -1
  184. package/dist/services/proposals/kinds/identity-split.js +1 -1
  185. package/dist/services/proposals/kinds/key-document.js +1 -1
  186. package/dist/services/proposals/kinds/mail-findings.d.ts +1 -1
  187. package/dist/services/proposals/kinds/mail-findings.js +11 -5
  188. package/dist/services/proposals/kinds/meeting-findings.js +10 -4
  189. package/dist/services/proposals/kinds/memory.js +1 -1
  190. package/dist/services/proposals/kinds/organization.js +1 -1
  191. package/dist/services/proposals/kinds/relationship-update.js +1 -1
  192. package/dist/services/proposals/kinds/relationship.js +1 -1
  193. package/dist/services/proposals/kinds/shared.d.ts +3 -2
  194. package/dist/services/proposals/kinds/shared.js +4 -4
  195. package/dist/services/proposals/kinds/source-review.js +1 -1
  196. package/dist/services/proposals/kinds/task-close.js +2 -2
  197. package/dist/services/proposals/registry.js +1 -1
  198. package/dist/services/proposals/types.d.ts +2 -1
  199. package/dist/services/search-all-business.js +3 -4
  200. package/dist/services/search-all.js +13 -14
  201. package/dist/services/search-harder.d.ts +11 -1
  202. package/dist/services/search-harder.js +38 -5
  203. package/dist/services/searches.d.ts +2 -4
  204. package/dist/services/searches.js +1 -4
  205. package/dist/services/stored-project-gathering.js +6 -1
  206. package/dist/services/tags.d.ts +2 -4
  207. package/dist/services/tags.js +1 -1
  208. package/dist/services/tasks.d.ts +1 -1
  209. package/dist/services/tasks.js +4 -3
  210. package/dist/speech/openai.js +2 -0
  211. package/dist/speech/transcribe.d.ts +5 -2
  212. package/dist/speech/transcribe.js +14 -5
  213. package/dist/store/account-store.d.ts +2 -1
  214. package/dist/store/account-store.js +3 -1
  215. package/dist/store/accounts.d.ts +2 -0
  216. package/dist/store/accounts.js +8 -0
  217. package/dist/store/chats.d.ts +5 -0
  218. package/dist/store/chats.js +4 -0
  219. package/dist/store/evidence-findings.d.ts +9 -0
  220. package/dist/store/exports.d.ts +1 -1
  221. package/dist/store/exports.js +1 -1
  222. package/dist/store/identity-links.d.ts +3 -1
  223. package/dist/store/mail-findings.d.ts +9 -0
  224. package/dist/store/meeting-findings.d.ts +9 -0
  225. package/dist/store/searches.d.ts +3 -2
  226. package/dist/store/sqlite/accounts.js +37 -0
  227. package/dist/store/sqlite/agent-actions.d.ts +2 -1
  228. package/dist/store/sqlite/agent-actions.js +10 -4
  229. package/dist/store/sqlite/business-contracts.d.ts +3 -1
  230. package/dist/store/sqlite/business-contracts.js +7 -3
  231. package/dist/store/sqlite/business-search.d.ts +2 -1
  232. package/dist/store/sqlite/business-search.js +6 -4
  233. package/dist/store/sqlite/deals.d.ts +6 -4
  234. package/dist/store/sqlite/deals.js +12 -7
  235. package/dist/store/sqlite/evidence-findings.js +78 -9
  236. package/dist/store/sqlite/facts.d.ts +2 -1
  237. package/dist/store/sqlite/facts.js +6 -2
  238. package/dist/store/sqlite/finance.d.ts +4 -2
  239. package/dist/store/sqlite/finance.js +13 -6
  240. package/dist/store/sqlite/findings-core.d.ts +56 -2
  241. package/dist/store/sqlite/findings-core.js +109 -22
  242. package/dist/store/sqlite/identities.d.ts +4 -0
  243. package/dist/store/sqlite/identities.js +12 -3
  244. package/dist/store/sqlite/identity-proposals.js +34 -4
  245. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  246. package/dist/store/sqlite/lucene-fields.js +28 -2
  247. package/dist/store/sqlite/lucene.js +21 -10
  248. package/dist/store/sqlite/mail-findings.js +60 -22
  249. package/dist/store/sqlite/meeting-findings.js +53 -7
  250. package/dist/store/sqlite/meeting-participant-search.js +4 -5
  251. package/dist/store/sqlite/meetings.js +7 -3
  252. package/dist/store/sqlite/memories.d.ts +4 -2
  253. package/dist/store/sqlite/memories.js +13 -6
  254. package/dist/store/sqlite/money-transactions.d.ts +3 -1
  255. package/dist/store/sqlite/money-transactions.js +7 -3
  256. package/dist/store/sqlite/name-traces.d.ts +3 -3
  257. package/dist/store/sqlite/name-traces.js +29 -2
  258. package/dist/store/sqlite/orders.d.ts +3 -1
  259. package/dist/store/sqlite/orders.js +5 -2
  260. package/dist/store/sqlite/people-list.js +67 -22
  261. package/dist/store/sqlite/person-match-scan.d.ts +3 -1
  262. package/dist/store/sqlite/person-match-scan.js +97 -7
  263. package/dist/store/sqlite/products.d.ts +3 -1
  264. package/dist/store/sqlite/products.js +5 -2
  265. package/dist/store/sqlite/proposed-actions.d.ts +2 -1
  266. package/dist/store/sqlite/proposed-actions.js +7 -3
  267. package/dist/store/sqlite/query-filter.d.ts +4 -0
  268. package/dist/store/sqlite/query-filter.js +14 -0
  269. package/dist/store/sqlite/reads.d.ts +1 -0
  270. package/dist/store/sqlite/reads.js +14 -0
  271. package/dist/store/sqlite/records.d.ts +3 -1
  272. package/dist/store/sqlite/records.js +7 -5
  273. package/dist/store/sqlite/rows-page.d.ts +3 -0
  274. package/dist/store/sqlite/rows-page.js +4 -0
  275. package/dist/store/sqlite/searches.d.ts +2 -1
  276. package/dist/store/sqlite/searches.js +3 -1
  277. package/dist/store/sqlite/subscriptions.d.ts +5 -2
  278. package/dist/store/sqlite/subscriptions.js +13 -6
  279. package/dist/store/sqlite/task-board.js +27 -0
  280. package/dist/store/sqlite/task-find.d.ts +15 -0
  281. package/dist/store/sqlite/task-find.js +1 -0
  282. package/dist/store/sqlite/wallets.d.ts +3 -1
  283. package/dist/store/sqlite/wallets.js +7 -3
  284. package/dist/store/sqlite/work-tasks.d.ts +3 -11
  285. package/dist/store/sqlite/work-tasks.js +8 -4
  286. package/package.json +2 -2
  287. package/parity.json +24 -0
@@ -2,15 +2,15 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { prepareReport } from "./report/render.js";
5
- import { attemptSchedule, KILL_AFTER_MS, readSchedule, sharedLinks } from "./schedules.js";
5
+ import { attemptSchedule, KILL_AFTER_MS, readSchedule, sharedLinks, } from "./schedules.js";
6
6
  /**
7
7
  * One past day's run of an agent schedule, as its timer would have made it at `at`: the same harness, flags, per-run
8
8
  * cap and input, the report rendered as of `at` and kept in `runs/` under that time, with `"backfill": true` in its
9
9
  * `.report.json`. It sends nothing, shows no notice, and leaves `last.json` and `latest.*` as they are; its cost counts
10
10
  * in today's spend, as any run's does.
11
11
  */
12
- export const backfillSchedule = async (app, system, env, file, { at, input, now = () => new Date(), signal, killAfterMs = KILL_AFTER_MS, agentRuns = [], ownerLanguage = async () => "ru", reportTemplates, }) => {
13
- const schedule = readSchedule(file);
12
+ export const backfillSchedule = async (app, system, env, file, { at, input, now = () => new Date(), signal, killAfterMs = KILL_AFTER_MS, agentRuns = [], ownerLanguage = async () => "ru", reportTemplates, schedule: checked, }) => {
13
+ const schedule = checked ?? readSchedule(file);
14
14
  if (schedule.kind !== "agent")
15
15
  throw new CliError("validation_error", `${schedule.name} runs a command, not an agent; only an agent's report is built for a past day`);
16
16
  const folder = join(file, "..");
@@ -28,7 +28,26 @@ export interface Schedule {
28
28
  to?: string[];
29
29
  /** Kept with no timer: `schedule run` still runs it, and `schedule resume` puts the timer back. */
30
30
  paused?: true;
31
+ /** An agent's: files its harness reads its limits from, by path in the run's work folder; written before each run. */
32
+ files?: Record<string, string>;
33
+ /** An agent's: what its start is rebuilt from before each run, so the saved argv is never what runs. */
34
+ agent?: AgentSpec;
31
35
  }
36
+ /** An agent schedule's harness and what it was asked; the argv, variables and files are built from it. */
37
+ export interface AgentSpec {
38
+ harness: string;
39
+ prompt: string;
40
+ /** An alias or a model id; "" for the harness's own default. */
41
+ model: string;
42
+ leanStart: boolean;
43
+ maxCost?: number;
44
+ /** The owner accepted an agent its own limits cannot hold to the CLIs' commands (`--allow-dangerous`). */
45
+ allowDangerous?: true;
46
+ }
47
+ /** Stands for an agent run's own work folder in its harness's variables and files; the run puts the real path in. */
48
+ export declare const WORK_FOLDER = "{wirecat-work-folder}";
49
+ /** Stands for the run's own mark in an agent's prompt, which the CLIs put around other people's text in that run. */
50
+ export declare const UNTRUSTED_MARK = "{wirecat-untrusted-mark}";
32
51
  export declare const NOTIFY_WHEN: readonly ["always", "failures", "never"];
33
52
  export type Notify = (typeof NOTIFY_WHEN)[number];
34
53
  /** A repeating agent would otherwise notify on every tick; any other schedule runs rarely enough to say each result. */
@@ -69,6 +88,8 @@ export interface LastRun {
69
88
  reason?: string;
70
89
  /** The `code` of the error the run printed, as run records keep it. */
71
90
  errorCode?: string;
91
+ /** How long the CLI asked to wait before it is tried again (`retry.after_ms` of a `rate_limited` error). */
92
+ retryAfterMs?: number;
72
93
  /** The first failure of the failures in a row, so "failing since" survives every retry. */
73
94
  failingSince?: string;
74
95
  /** Failed runs in a row; absent once a run succeeds. */
@@ -94,6 +115,7 @@ export declare const SKIP_REASONS: {
94
115
  readonly mailNone: "mail.none-new";
95
116
  readonly mailBelowThreshold: "mail.below-threshold";
96
117
  readonly mailSameInput: "mail.same-input";
118
+ readonly agentRefused: "agent.refused";
97
119
  };
98
120
  export type SkipReason = (typeof SKIP_REASONS)[keyof typeof SKIP_REASONS];
99
121
  /**
@@ -104,6 +126,7 @@ export type SkipReason = (typeof SKIP_REASONS)[keyof typeof SKIP_REASONS];
104
126
  export declare const failureOf: (stderr: string, exitCode: number) => {
105
127
  reason: string;
106
128
  errorCode?: string;
129
+ retryAfterMs?: number;
107
130
  };
108
131
  /** The one-line reason `failureOf` keeps, for a timer that reads a run's stderr itself. */
109
132
  export declare const reasonOf: (stderr: string, exitCode?: number) => string;
@@ -162,9 +185,10 @@ export declare const CREDENTIALS_UNREACHABLE = "credentials.unreachable";
162
185
  *
163
186
  * `untilUnlocked` is for the timer's run: a timer that catches up at boot runs before the login unlocks the
164
187
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
165
- * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
188
+ * 12 hours. A run the provider asked to wait (`rate_limited` with `retry.after_ms`, up to 6 hours) waits that long
189
+ * and runs once more. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
166
190
  */
167
- export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, ownerLanguage, reportTemplates, skipRepeatedInput, routes: chosen, }?: {
191
+ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, file: string, { now, timer, signal, killAfterMs, untilUnlocked, wait, agentRuns, agentInput, ownerLanguage, reportTemplates, skipRepeatedInput, routes: chosen, schedule: checked, }?: {
168
192
  now?: () => Date;
169
193
  timer?: Timer;
170
194
  signal?: AbortSignal;
@@ -185,6 +209,8 @@ export declare const runSchedule: (app: AppIdentity, system: ServerSystem, env:
185
209
  skipRepeatedInput?: boolean;
186
210
  /** Where this run goes instead of the schedule's own routes; `[]` keeps it here. */
187
211
  routes?: readonly string[];
212
+ /** The schedule as its guard checked and rebuilt it, run as it is: the file is not read again. */
213
+ schedule?: Schedule;
188
214
  }) => Promise<LastRun>;
189
215
  /** One run of the schedule's command or agent: its output in `runs/`, its result in `last.json`. */
190
216
  export declare const attemptSchedule: (app: AppIdentity, system: ServerSystem, env: NodeJS.ProcessEnv, schedule: Schedule, folder: string, { now, signal, killAfterMs, agentRuns, agentInput, skipRepeatedInput, at, }: {
@@ -1,7 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
- import { basename, join } from "node:path";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join, relative } from "node:path";
5
6
  import { CliError, errorCodes, writeSecurely } from "@wirecat/cli-base";
6
7
  import { linkConfigOf, linkFor } from "../domain/links.js";
7
8
  import { mailHolderVariable, readOnlyLockOf } from "../ports/app.js";
@@ -14,6 +15,10 @@ import { causeOf, gapsView, noticeView, weeklyGapsOf } from "./report/messages.j
14
15
  import { prepareMessage, prepareReport, } from "./report/render.js";
15
16
  export { launchdTimer, systemdTimer, timerFor, windowsTimer } from "./timers.js";
16
17
  export { calendarOf, describeWhen, isCalendar, nextRun, previousRun, runsBetween, slotsOf, WEEKDAYS, } from "./when.js";
18
+ /** Stands for an agent run's own work folder in its harness's variables and files; the run puts the real path in. */
19
+ export const WORK_FOLDER = "{wirecat-work-folder}";
20
+ /** Stands for the run's own mark in an agent's prompt, which the CLIs put around other people's text in that run. */
21
+ export const UNTRUSTED_MARK = "{wirecat-untrusted-mark}";
17
22
  export const NOTIFY_WHEN = ["always", "failures", "never"];
18
23
  /** A repeating agent would otherwise notify on every tick; any other schedule runs rarely enough to say each result. */
19
24
  export const notifyOf = (schedule) => schedule.notify ?? (schedule.kind === "agent" && "every" in schedule.when ? "failures" : "always");
@@ -38,7 +43,7 @@ const addSpend = (folder, usd, at) => {
38
43
  };
39
44
  /**
40
45
  * Claude reports a run's cost only in its JSON answer, so a scheduled claude run asks for it; the report kept is the
41
- * answer's text. Codex reports none.
46
+ * answer's text. No other agent reports one.
42
47
  */
43
48
  const priced = (argv) => {
44
49
  const [program = ""] = argv;
@@ -47,6 +52,7 @@ const priced = (argv) => {
47
52
  ? [...argv, "--output-format", "json"]
48
53
  : argv;
49
54
  };
55
+ /** `failed`: claude answered an error, such as no credit left, which it may do with exit 0. */
50
56
  const reportOf = (stdout) => {
51
57
  try {
52
58
  const answer = JSON.parse(stdout.toString("utf8"));
@@ -55,6 +61,7 @@ const reportOf = (stdout) => {
55
61
  return {
56
62
  text: typeof answer.result === "string" ? Buffer.from(answer.result) : stdout,
57
63
  ...(typeof answer.total_cost_usd === "number" ? { costUsd: answer.total_cost_usd } : {}),
64
+ ...(answer.is_error === true ? { failed: true } : {}),
58
65
  };
59
66
  }
60
67
  catch {
@@ -72,6 +79,7 @@ export const SKIP_REASONS = {
72
79
  mailNone: "mail.none-new",
73
80
  mailBelowThreshold: "mail.below-threshold",
74
81
  mailSameInput: "mail.same-input",
82
+ agentRefused: "agent.refused",
75
83
  };
76
84
  const REASON_ID = /^[a-z0-9][a-z0-9.-]{0,79}$/;
77
85
  /**
@@ -82,9 +90,15 @@ const REASON_ID = /^[a-z0-9][a-z0-9.-]{0,79}$/;
82
90
  export const failureOf = (stderr, exitCode) => {
83
91
  for (const line of stderr.split("\n").reverse()) {
84
92
  try {
85
- const { code, reason } = JSON.parse(line).error ?? {};
93
+ const { code, reason, retry } = JSON.parse(line).error ??
94
+ {};
86
95
  if (errorCodes.includes(code) && typeof reason === "string" && REASON_ID.test(reason)) {
87
- return { reason: `${code} (${reason})`, errorCode: code };
96
+ const after = retry?.after_ms;
97
+ return {
98
+ reason: `${code} (${reason})`,
99
+ errorCode: code,
100
+ ...(code === "rate_limited" && typeof after === "number" && after > 0 ? { retryAfterMs: after } : {}),
101
+ };
88
102
  }
89
103
  }
90
104
  catch { }
@@ -282,6 +296,9 @@ const LOCKED_FIRST_WAIT_MS = 60_000;
282
296
  const LOCKED_LONGEST_WAIT_MS = 15 * 60_000;
283
297
  /** A night's catch-up waits for the morning's login; past that the run fails as it is. */
284
298
  const LOCKED_GIVE_UP_MS = 12 * 60 * 60_000;
299
+ /** A wait the provider asked for that a daily run sits out and then runs once more; a longer one fails for the day. */
300
+ const RATE_LIMITED_WAIT_AT_MOST_MS = 6 * 60 * 60_000;
301
+ const RATE_LIMITED_MARGIN_MS = 30_000;
285
302
  const lockedOut = (last) => last.reason?.endsWith(`(${CREDENTIALS_UNREACHABLE})`) === true;
286
303
  const pause = (ms, signal) => new Promise((resolve) => {
287
304
  if (signal?.aborted)
@@ -301,10 +318,11 @@ const pause = (ms, signal) => new Promise((resolve) => {
301
318
  *
302
319
  * `untilUnlocked` is for the timer's run: a timer that catches up at boot runs before the login unlocks the
303
320
  * keyring, so a run that fails for that reason is tried again, a minute then up to 15 minutes apart, for up to
304
- * 12 hours. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
321
+ * 12 hours. A run the provider asked to wait (`rate_limited` with `retry.after_ms`, up to 6 hours) waits that long
322
+ * and runs once more. A schedule that repeats every few minutes is left to its next tick; a run by hand fails at once.
305
323
  */
306
- export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, ownerLanguage = async () => "ru", reportTemplates, skipRepeatedInput = false, routes: chosen, } = {}) => {
307
- const schedule = readSchedule(file);
324
+ export const runSchedule = async (app, system, env, file, { now = () => new Date(), timer, signal, killAfterMs = KILL_AFTER_MS, untilUnlocked = false, wait = pause, agentRuns = [], agentInput, ownerLanguage = async () => "ru", reportTemplates, skipRepeatedInput = false, routes: chosen, schedule: checked, } = {}) => {
325
+ const schedule = checked ?? readSchedule(file);
308
326
  const folder = join(file, "..");
309
327
  const runs = join(folder, "runs");
310
328
  mkdirSync(runs, { recursive: true, mode: 0o700 });
@@ -339,6 +357,21 @@ export const runSchedule = async (app, system, env, file, { now = () => new Date
339
357
  break;
340
358
  last = again;
341
359
  }
360
+ const asked = last.errorCode === "rate_limited" ? last.retryAfterMs : undefined;
361
+ if (retries && asked !== undefined && asked <= RATE_LIMITED_WAIT_AT_MOST_MS && !signal?.aborted) {
362
+ await wait(asked + RATE_LIMITED_MARGIN_MS, signal);
363
+ if (!signal?.aborted) {
364
+ const again = await attemptSchedule(app, system, env, schedule, folder, {
365
+ now,
366
+ signal,
367
+ killAfterMs,
368
+ agentRuns,
369
+ agentInput,
370
+ });
371
+ if (!("repeated" in again))
372
+ last = again;
373
+ }
374
+ }
342
375
  const { exitCode, output } = last;
343
376
  const errors = agent ? output.replace(/\.md$/, ".log") : output;
344
377
  if (agent && exitCode === 0)
@@ -502,22 +535,29 @@ export const attemptSchedule = async (app, system, env, schedule, folder, { now,
502
535
  const agent = schedule.kind === "agent";
503
536
  const output = join(runs, `${stamp}.${agent ? "md" : "log"}`);
504
537
  const errors = agent ? join(runs, `${stamp}.log`) : output;
505
- const [program = "", ...args] = agent ? priced(schedule.argv) : [...system.entry, ...schedule.argv];
506
538
  const trace = childTrace();
539
+ // An agent works in an empty folder of its own: one that could write where it runs never reaches its schedule file.
540
+ const work = agent ? mkdtempSync(join(tmpdir(), "wirecat-agent-")) : folder;
541
+ const mark = randomBytes(8).toString("hex");
542
+ const inWork = (text) => text.replaceAll(WORK_FOLDER, work).replaceAll(UNTRUSTED_MARK, mark);
543
+ const [program = "", ...args] = agent ? priced(schedule.argv).map(inWork) : [...system.entry, ...schedule.argv];
544
+ const agentOnly = (one) => [
545
+ [`${one.envPrefix}_READ_ONLY`, "1"],
546
+ [`${one.envPrefix}_SCHEDULED`, schedule.name],
547
+ [`${one.envPrefix}_WORK_FOLDER`, work],
548
+ [`${one.envPrefix}_UNTRUSTED_MARK`, mark],
549
+ ];
507
550
  const childEnv = {
508
551
  ...env,
509
- ...schedule.environment,
552
+ ...(agent
553
+ ? Object.fromEntries(Object.entries(schedule.environment).map(([name, value]) => [name, inWork(value)]))
554
+ : schedule.environment),
510
555
  TRACEPARENT: trace.traceparent,
511
556
  [`${app.envPrefix}_SCHEDULED`]: schedule.name,
512
557
  ...(schedule.onNewMail ? { [mailHolderVariable(app)]: schedule.onNewMail } : {}),
513
558
  // A run started under the lock stays under it, whatever the schedule file says.
514
559
  ...(agent || readOnlyLockOf(app, env) ? { [`${app.envPrefix}_READ_ONLY`]: "1" } : {}),
515
- ...(agent
516
- ? Object.fromEntries(agentRuns.flatMap((other) => [
517
- [`${other.envPrefix}_READ_ONLY`, "1"],
518
- [`${other.envPrefix}_SCHEDULED`, schedule.name],
519
- ]))
520
- : {}),
560
+ ...(agent ? Object.fromEntries([app, ...agentRuns].flatMap(agentOnly)) : {}),
521
561
  };
522
562
  // The child's output is data, and an agent's is another program's: it is kept as it came. These lines say
523
563
  // only when it ran and how it ended.
@@ -531,11 +571,20 @@ export const attemptSchedule = async (app, system, env, schedule, folder, { now,
531
571
  if (before?.exitCode === 0 && before.inputHash === inputHash) {
532
572
  // A skip every few minutes would otherwise push the kept runs' files out of runs/.
533
573
  rmSync(join(runs, `${stamp}.jsonl`), { force: true });
574
+ if (agent)
575
+ rmSync(work, { recursive: true, force: true });
534
576
  return { repeated: before };
535
577
  }
578
+ for (const [path, body] of Object.entries(agent ? (schedule.files ?? {}) : {})) {
579
+ const file = join(work, path);
580
+ if (relative(work, file).startsWith(".."))
581
+ continue;
582
+ mkdirSync(dirname(file), { recursive: true });
583
+ writeFileSync(file, inWork(body), { mode: 0o600 });
584
+ }
536
585
  let costUsd;
537
586
  const exitCode = await new Promise((resolve) => {
538
- const child = spawn(program, args, { env: childEnv, cwd: folder, stdio: ["pipe", "pipe", "pipe"] });
587
+ const child = spawn(program, args, { env: childEnv, cwd: work, stdio: ["pipe", "pipe", "pipe"] });
539
588
  // An agent that stops reading its stdin may close it first; that is no failure of the run.
540
589
  child.stdin?.on("error", () => { });
541
590
  child.stdin?.end(input);
@@ -564,11 +613,15 @@ export const attemptSchedule = async (app, system, env, schedule, folder, { now,
564
613
  const report = agent ? reportOf(Buffer.concat(out)) : { text: Buffer.concat([...out, ...err]) };
565
614
  costUsd = report.costUsd;
566
615
  writeFileSync(output, report.text, { mode: 0o600 });
616
+ // The error is the agent's answer, so the log keeps it beside its stderr.
567
617
  if (agent)
568
- writeFileSync(errors, Buffer.concat(err), { mode: 0o600 });
569
- resolve(code ?? (killedBy === "SIGKILL" ? 137 : killedBy === "SIGTERM" ? 143 : 1));
618
+ writeFileSync(errors, Buffer.concat([...err, ...("failed" in report ? [report.text] : [])]), { mode: 0o600 });
619
+ const exited = code ?? (killedBy === "SIGKILL" ? 137 : killedBy === "SIGTERM" ? 143 : 1);
620
+ resolve("failed" in report && exited === 0 ? 1 : exited);
570
621
  });
571
622
  });
623
+ if (agent)
624
+ rmSync(work, { recursive: true, force: true });
572
625
  const ended = now();
573
626
  if (costUsd !== undefined)
574
627
  addSpend(folder, costUsd, ended);
@@ -22,6 +22,8 @@ export interface Unit {
22
22
  * development checkout must open that checkout's session and store, never the owner's real ones.
23
23
  * Nothing that could hold a credential is copied.
24
24
  */
25
+ /** The variables that move a CLI's files elsewhere. */
26
+ export declare const locationNames: (app: AppIdentity) => string[];
25
27
  export declare const locationVariables: (app: AppIdentity, env: NodeJS.ProcessEnv) => Record<string, string>;
26
28
  /**
27
29
  * A unit written with location variables runs another installation — a development checkout — so
@@ -7,15 +7,14 @@ import { CliError } from "@wirecat/cli-base";
7
7
  * development checkout must open that checkout's session and store, never the owner's real ones.
8
8
  * Nothing that could hold a credential is copied.
9
9
  */
10
- export const locationVariables = (app, env) => {
11
- const names = [
12
- ...["CONFIG_DIR", "STATE_DIR", "CACHE_DIR"].map((name) => `${app.envPrefix}_${name}`),
13
- "MESSAGING_STORE",
14
- "MESSAGING_STATE_DIR",
15
- "WIRECAT_STATE_DIR",
16
- ];
17
- return Object.fromEntries(names.flatMap((name) => (env[name] === undefined ? [] : [[name, env[name]]])));
18
- };
10
+ /** The variables that move a CLI's files elsewhere. */
11
+ export const locationNames = (app) => [
12
+ ...["CONFIG_DIR", "STATE_DIR", "CACHE_DIR"].map((name) => `${app.envPrefix}_${name}`),
13
+ "MESSAGING_STORE",
14
+ "MESSAGING_STATE_DIR",
15
+ "WIRECAT_STATE_DIR",
16
+ ];
17
+ export const locationVariables = (app, env) => Object.fromEntries(locationNames(app).flatMap((name) => (env[name] === undefined ? [] : [[name, env[name]]])));
19
18
  /**
20
19
  * A unit written with location variables runs another installation — a development checkout — so
21
20
  * its name says which: under the bare name, `server start` there drove the owner's real unit.
@@ -409,8 +409,16 @@ const addCalendarCommandsDefinition = (program, options) => {
409
409
  ...(opts.exact ? { exact: true } : {}),
410
410
  ...(opts.newest ? { newest: true } : {}),
411
411
  });
412
- if (!server)
413
- return hitsBody(command, { ...(await archived()), untrusted: SEARCH_UNTRUSTED });
412
+ if (!server) {
413
+ const { items, hasMore, nextOffset, ...found } = await archived();
414
+ return hitsBody(command, {
415
+ ...found,
416
+ hits: items,
417
+ has_more: hasMore,
418
+ ...(nextOffset === undefined ? {} : { next_offset: nextOffset }),
419
+ untrusted: SEARCH_UNTRUSTED,
420
+ });
421
+ }
414
422
  const served = await serverSearchAnswer(run.source(), run.store, {
415
423
  accountId: run.accountId,
416
424
  account: run.account,
@@ -292,7 +292,7 @@ export const icsFeeds = (options) => {
292
292
  if (got === "unchanged") {
293
293
  const [events, skipped] = [held?.events ?? 0, held?.skipped ?? 0];
294
294
  stats.set(calendar.id, { calendarId: calendar.id, events, skipped, unchanged: true });
295
- return { entries: [], removed: [], cursor, unchanged: true };
295
+ return { items: [], hasMore: false, removed: [], cursor, unchanged: true };
296
296
  }
297
297
  const { text, validators } = got;
298
298
  const found = readFeed(text, calendar.timezone ?? options.zone, window);
@@ -305,7 +305,7 @@ export const icsFeeds = (options) => {
305
305
  const next = validators.etag || validators.lastModified
306
306
  ? { v: 1, validators, window, events: found.events, skipped: found.skipped }
307
307
  : null;
308
- return { entries: found.entries, removed: [], cursor: next && JSON.stringify(next) };
308
+ return { items: found.entries, hasMore: false, removed: [], cursor: next && JSON.stringify(next) };
309
309
  },
310
310
  };
311
311
  return {
@@ -10,13 +10,13 @@ export declare const calendarTools: ({
10
10
  inputSchema: {
11
11
  type: string;
12
12
  properties: {
13
- limit?: undefined;
14
13
  account_id: {
15
14
  type: string;
16
15
  minimum: number;
17
16
  };
18
17
  query?: undefined;
19
18
  timezone?: undefined;
19
+ limit?: undefined;
20
20
  page?: undefined;
21
21
  event?: undefined;
22
22
  } | {
@@ -45,9 +45,9 @@ export declare const calendarTools: ({
45
45
  };
46
46
  event?: undefined;
47
47
  } | {
48
- limit?: undefined;
49
48
  query?: undefined;
50
49
  timezone?: undefined;
50
+ limit?: undefined;
51
51
  page?: undefined;
52
52
  event: {
53
53
  type: string;
@@ -58,9 +58,9 @@ export declare const calendarTools: ({
58
58
  minimum: number;
59
59
  };
60
60
  } | {
61
- limit?: undefined;
62
61
  query?: undefined;
63
62
  timezone?: undefined;
63
+ limit?: undefined;
64
64
  page?: undefined;
65
65
  event?: undefined;
66
66
  account_id?: undefined;
@@ -80,13 +80,13 @@ export declare const calendarTools: ({
80
80
  inputSchema: {
81
81
  type: string;
82
82
  properties: {
83
- limit?: undefined;
84
83
  account_id: {
85
84
  type: string;
86
85
  minimum: number;
87
86
  };
88
87
  query?: undefined;
89
88
  timezone?: undefined;
89
+ limit?: undefined;
90
90
  page?: undefined;
91
91
  event?: undefined;
92
92
  } | {
@@ -115,9 +115,9 @@ export declare const calendarTools: ({
115
115
  };
116
116
  event?: undefined;
117
117
  } | {
118
- limit?: undefined;
119
118
  query?: undefined;
120
119
  timezone?: undefined;
120
+ limit?: undefined;
121
121
  page?: undefined;
122
122
  event: {
123
123
  type: string;
@@ -128,9 +128,9 @@ export declare const calendarTools: ({
128
128
  minimum: number;
129
129
  };
130
130
  } | {
131
- limit?: undefined;
132
131
  query?: undefined;
133
132
  timezone?: undefined;
133
+ limit?: undefined;
134
134
  page?: undefined;
135
135
  event?: undefined;
136
136
  account_id?: undefined;
@@ -150,13 +150,13 @@ export declare const calendarTools: ({
150
150
  inputSchema: {
151
151
  type: string;
152
152
  properties: {
153
- limit?: undefined;
154
153
  account_id: {
155
154
  type: string;
156
155
  minimum: number;
157
156
  };
158
157
  query?: undefined;
159
158
  timezone?: undefined;
159
+ limit?: undefined;
160
160
  page?: undefined;
161
161
  event?: undefined;
162
162
  } | {
@@ -185,9 +185,9 @@ export declare const calendarTools: ({
185
185
  };
186
186
  event?: undefined;
187
187
  } | {
188
- limit?: undefined;
189
188
  query?: undefined;
190
189
  timezone?: undefined;
190
+ limit?: undefined;
191
191
  page?: undefined;
192
192
  event: {
193
193
  type: string;
@@ -198,9 +198,9 @@ export declare const calendarTools: ({
198
198
  minimum: number;
199
199
  };
200
200
  } | {
201
- limit?: undefined;
202
201
  query?: undefined;
203
202
  timezone?: undefined;
203
+ limit?: undefined;
204
204
  page?: undefined;
205
205
  event?: undefined;
206
206
  account_id?: undefined;
@@ -220,13 +220,13 @@ export declare const calendarTools: ({
220
220
  inputSchema: {
221
221
  type: string;
222
222
  properties: {
223
- limit?: undefined;
224
223
  account_id: {
225
224
  type: string;
226
225
  minimum: number;
227
226
  };
228
227
  query?: undefined;
229
228
  timezone?: undefined;
229
+ limit?: undefined;
230
230
  page?: undefined;
231
231
  event?: undefined;
232
232
  } | {
@@ -255,9 +255,9 @@ export declare const calendarTools: ({
255
255
  };
256
256
  event?: undefined;
257
257
  } | {
258
- limit?: undefined;
259
258
  query?: undefined;
260
259
  timezone?: undefined;
260
+ limit?: undefined;
261
261
  page?: undefined;
262
262
  event: {
263
263
  type: string;
@@ -268,9 +268,9 @@ export declare const calendarTools: ({
268
268
  minimum: number;
269
269
  };
270
270
  } | {
271
- limit?: undefined;
272
271
  query?: undefined;
273
272
  timezone?: undefined;
273
+ limit?: undefined;
274
274
  page?: undefined;
275
275
  event?: undefined;
276
276
  account_id?: undefined;
@@ -51,7 +51,7 @@ const groupOf = (eventId, eventSeriesId) => eventSeriesId !== null ? `s${eventSe
51
51
  */
52
52
  export const bothSearchAnswer = async (store, accountId, archived, served, limit) => {
53
53
  const calendars = new Map((await store.calendars(accountId)).map((calendar) => [calendar.externalId, calendar]));
54
- const hits = archived.hits.map((hit) => ({ ...hit }));
54
+ const hits = archived.items.map((hit) => ({ ...hit }));
55
55
  const byGroup = new Map();
56
56
  for (const hit of hits) {
57
57
  const details = await store.event(Number(hit.ref.slice("event:".length)));
@@ -76,6 +76,6 @@ export const bothSearchAnswer = async (store, accountId, archived, served, limit
76
76
  by: "both",
77
77
  ...(archived.meaning_skipped === undefined ? {} : { meaning_skipped: archived.meaning_skipped }),
78
78
  hits: merged.slice(0, limit),
79
- has_more: archived.has_more || served.has_more || merged.length > limit,
79
+ has_more: archived.hasMore || served.has_more || merged.length > limit,
80
80
  };
81
81
  };
@@ -20,14 +20,15 @@ export interface CalendarSourceTraits {
20
20
  fullListOnly: boolean;
21
21
  }
22
22
  export interface ChangePage {
23
- entries: EntryInput[];
23
+ items: EntryInput[];
24
24
  /**
25
25
  * Entries the provider confirmed deleted, known only by `externalId` (CalDAV 404; Graph `@removed` that a GET by id
26
26
  * answered 404). Never an entry that only left the window.
27
27
  */
28
28
  removed: string[];
29
- /** More pages in this round. */
30
- nextPage?: string;
29
+ /** More pages in this round, read from `nextCursor`. */
30
+ hasMore: boolean;
31
+ nextCursor?: string;
31
32
  /** On the last page: the cursor for the next run; `null` when the source has none. */
32
33
  cursor?: string | null;
33
34
  /**
@@ -198,16 +198,16 @@ const syncOne = async ({ source, store, calendar, window, now, expand, budget, s
198
198
  if (signal?.aborted)
199
199
  return "cancelled";
200
200
  const groups = [];
201
- const listed = page.entries.filter((entry) => entry.kind === "series" && entry.status !== "cancelled");
201
+ const listed = page.items.filter((entry) => entry.kind === "series" && entry.status !== "cancelled");
202
202
  const kept = new Set();
203
203
  if (source.traits.expands === "on-request")
204
204
  for (const entry of listed)
205
205
  if (await unchanged(entry))
206
206
  kept.add(entry.externalId);
207
- if (page.entries.length) {
208
- await store.saveEntries(calendar.id, page.entries, now);
209
- result.saved += page.entries.length;
210
- cursor = { ...cursor, done: cursor.done + page.entries.length };
207
+ if (page.items.length) {
208
+ await store.saveEntries(calendar.id, page.items, now);
209
+ result.saved += page.items.length;
210
+ cursor = { ...cursor, done: cursor.done + page.items.length };
211
211
  for (const entry of listed) {
212
212
  if (source.traits.expands === "local")
213
213
  groups.push({ series: entry.externalId, slots: await expand(entry, round.window) });
@@ -219,15 +219,17 @@ const syncOne = async ({ source, store, calendar, window, now, expand, budget, s
219
219
  }
220
220
  if (page.removed.length)
221
221
  result.removed += await store.removeEntries(calendar.id, page.removed, now);
222
- if (page.unchanged && source.traits.fullListOnly && page.entries.length === 0 && page.nextPage === undefined)
222
+ if (page.unchanged && source.traits.fullListOnly && page.items.length === 0 && !page.hasMore)
223
223
  round = { ...round, page: null, listed: true, next: page.cursor ?? null, unchanged: true };
224
- else if (page.nextPage === undefined)
224
+ else if (!page.hasMore)
225
225
  round = { ...round, page: null, listed: true, next: page.cursor ?? null };
226
226
  else {
227
- if (seen.has(page.nextPage))
227
+ if (page.nextCursor === undefined)
228
+ throw new CliError("invalid_response", `${source.provider} said there are more pages but gave no cursor`);
229
+ if (seen.has(page.nextCursor))
228
230
  throw new CliError("invalid_response", `${source.provider} returned the same page twice`);
229
- seen.add(page.nextPage);
230
- round = { ...round, page: page.nextPage };
231
+ seen.add(page.nextCursor);
232
+ round = { ...round, page: page.nextCursor };
231
233
  }
232
234
  await commit(groups);
233
235
  moved();
@@ -36,14 +36,15 @@ const round = async (source, calendar, cursor, window) => {
36
36
  const result = await source.changes(calendar, { cursor, window, ...(page === undefined ? {} : { page }) });
37
37
  if ("reset" in result)
38
38
  return "reset";
39
- const { entries, removed, nextPage, cursor: next } = result;
40
- listed.entries.push(...entries);
39
+ const { items, removed, hasMore, nextCursor, cursor: next } = result;
40
+ listed.entries.push(...items);
41
41
  listed.removed.push(...removed);
42
- if (nextPage === undefined) {
42
+ assert.equal(hasMore, nextCursor !== undefined, "a page names its next cursor exactly when it has more");
43
+ if (!hasMore) {
43
44
  listed.cursor = next ?? null;
44
45
  return listed;
45
46
  }
46
- page = nextPage;
47
+ page = nextCursor;
47
48
  }
48
49
  throw new assert.AssertionError({ message: "the source never stopped paging" });
49
50
  };
@@ -71,9 +71,10 @@ export const fakeCalendarSource = (options = {}) => {
71
71
  const slice = entries.slice(from, from + pageSize);
72
72
  const more = from + pageSize < entries.length;
73
73
  return {
74
- entries: slice.map((entry) => structuredClone(entry)),
74
+ items: slice.map((entry) => structuredClone(entry)),
75
+ hasMore: more,
75
76
  removed: from === 0 ? removed : [],
76
- ...(more ? { nextPage: `p${pages}:${from + pageSize}` } : { cursor: token(window) }),
77
+ ...(more ? { nextCursor: `p${pages}:${from + pageSize}` } : { cursor: token(window) }),
77
78
  };
78
79
  },
79
80
  ...(traits.expands === "on-request"