omp-superagent 0.1.10 → 0.1.11

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 (149) hide show
  1. package/DESIGN.md +58 -15
  2. package/README.ko.md +7 -0
  3. package/README.md +7 -0
  4. package/THIRD_PARTY_NOTICES.md +35 -436
  5. package/assets/architecture-dark.svg +7 -12
  6. package/assets/architecture.ko-dark.svg +7 -12
  7. package/assets/architecture.ko.svg +7 -12
  8. package/assets/architecture.mmd +5 -13
  9. package/assets/architecture.svg +7 -12
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +106 -52
  12. package/docs/OPERATIONS.md +98 -44
  13. package/docs/design/execution.md +80 -52
  14. package/docs/design/messaging.md +113 -32
  15. package/docs/releases/0.1.11.md +18 -0
  16. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  17. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  18. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  20. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  21. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  24. package/package.json +10 -11
  25. package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
  26. package/skills/head/SKILL.md +12 -3
  27. package/skills/head/references/routing.md +1 -1
  28. package/skills/head/references/supervision.md +23 -26
  29. package/skills/lane/SKILL.md +28 -21
  30. package/skills/lane/references/workflow.md +15 -17
  31. package/src/cli.ts +33 -33
  32. package/src/{config.ts → config/config.ts} +7 -3
  33. package/src/config/wake-config.ts +36 -0
  34. package/src/contracts.ts +61 -12
  35. package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
  36. package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
  37. package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
  38. package/src/extension.ts +43 -25
  39. package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
  40. package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
  41. package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
  42. package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
  43. package/src/gateway-config.ts +1 -1
  44. package/src/gateway-restart-env.ts +3 -3
  45. package/src/{group-access.ts → group/group-access.ts} +8 -3
  46. package/src/{group-policy.ts → group/group-policy.ts} +2 -2
  47. package/src/{group-runner.ts → group/group-runner.ts} +11 -6
  48. package/src/host-extension.ts +164 -36
  49. package/src/host-sdk-helper.ts +62 -65
  50. package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
  51. package/src/{decisions.ts → lane/decisions.ts} +12 -10
  52. package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
  53. package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
  54. package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
  55. package/src/{workflow.ts → lane/workflow.ts} +1 -1
  56. package/src/lane-extension.ts +25 -7
  57. package/src/managed-memory-helper.ts +2 -2
  58. package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
  59. package/src/{delivery.ts → messaging/delivery.ts} +1 -1
  60. package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
  61. package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
  62. package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
  63. package/src/messaging/messenger-commands.ts +55 -0
  64. package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
  65. package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
  66. package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
  67. package/src/omp/head-resume.ts +123 -0
  68. package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
  69. package/src/{host-protocol.ts → omp/host-protocol.ts} +10 -2
  70. package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
  71. package/src/{host.ts → omp/host.ts} +26 -17
  72. package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
  73. package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
  74. package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
  75. package/src/omp/native-journal.ts +124 -0
  76. package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
  77. package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
  78. package/src/omp/native-sessions.ts +124 -0
  79. package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
  80. package/src/{soul.ts → omp/soul.ts} +2 -2
  81. package/src/omp/stock-head-launch.ts +31 -0
  82. package/src/{autostart.ts → operator/autostart.ts} +3 -3
  83. package/src/{operator.ts → operator/operator.ts} +2 -2
  84. package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
  85. package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
  86. package/src/{setup.ts → operator/setup.ts} +5 -5
  87. package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
  88. package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
  89. package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
  90. package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
  91. package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
  92. package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
  93. package/src/{message-order.ts → routing/message-order.ts} +1 -1
  94. package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
  95. package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
  96. package/src/{runtime.ts → runtime/controller.ts} +867 -1213
  97. package/src/runtime/deferred-routing.ts +106 -0
  98. package/src/runtime/dm-timeline.ts +194 -0
  99. package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
  100. package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
  101. package/src/runtime/model-journal.ts +119 -0
  102. package/src/runtime/native-frames.ts +131 -0
  103. package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
  104. package/src/runtime/preset-sync.ts +232 -0
  105. package/src/runtime/preset-watch-paths.ts +137 -0
  106. package/src/runtime/result-attachments.ts +146 -0
  107. package/src/storage/deferred-routing.ts +149 -0
  108. package/src/{store.ts → storage/store.ts} +75 -42
  109. package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
  110. package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
  111. package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
  112. package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
  113. package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
  114. package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
  115. package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
  116. package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
  117. package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
  118. package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
  119. package/src/worker-serve-prepare.ts +4 -4
  120. package/src/board-extension.ts +0 -217
  121. package/src/board.ts +0 -467
  122. package/src/gateway-host-helper.ts +0 -13
  123. package/src/messenger-commands.ts +0 -15
  124. package/src/native-sessions.ts +0 -34
  125. /package/src/{credentials.ts → config/credentials.ts} +0 -0
  126. /package/src/{lane-report.ts → lane/lane-report.ts} +0 -0
  127. /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
  128. /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
  129. /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
  130. /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
  131. /package/src/{host-reply-voice.ts → omp/host-reply-voice.ts} +0 -0
  132. /package/src/{host-services.ts → omp/host-services.ts} +0 -0
  133. /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
  134. /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
  135. /package/src/{repository.ts → operator/repository.ts} +0 -0
  136. /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
  137. /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
  138. /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
  139. /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
  140. /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
  141. /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
  142. /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
  143. /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
  144. /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
  145. /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
  146. /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
  147. /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
  148. /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
  149. /package/upstream/{ulw.json → super.json} +0 -0
@@ -24,7 +24,7 @@ workspace, and observed effects; don't trust a stale summary or infer replay.
24
24
 
25
25
  Default to ordinary work. Only a trusted, source-bound dispatch with the real
26
26
  `workflow: {name, reason}` selects a method, including a forwarded user selection.
27
- Do not infer it from the brief, quotations or board, retag `selectedBy: head` as
27
+ Do not infer it from the brief or quotations, retag `selectedBy: head` as
28
28
  `user`, or rewrite/replay the envelope. Selection is serialized, never a mid-run
29
29
  steer. No extra brand consent is needed; actual cost/scope bounds and approvals
30
30
  still apply. If required capability is unavailable, report it, not a weaker
@@ -65,9 +65,13 @@ substitute or unobserved activation.
65
65
  - Read affected code and callers; make the smallest complete change within the
66
66
  assignment. Use existing APIs, applicable skills and constraints. Preserve
67
67
  unrelated work. A follow-up can steer an active turn at a safe boundary, but
68
- does not undo observed effects or expand authorization. For a material choice,
69
- use `decision_ask` with original options, brief consequences and a recommendation;
70
- use a preview for longer context. A submitted choice never grants new effects.
68
+ does not undo observed effects or expand authorization. Use `decision_ask` for a
69
+ choice needing review: present real options, brief consequences and a recommendation;
70
+ use a preview for longer context. Set `to: "head"` when HEAD must coordinate an
71
+ in-scope choice, even in a bound topic, except on a corrective assignment.
72
+ An explicit HEAD question on a corrective assignment is cancelled privately,
73
+ not redirected to the owner. Otherwise keep default routing. Hold the affected
74
+ action; don't submit a second card or infer approval from a choice.
71
75
  - For independent bounded work, use the most specific advertised native `task`
72
76
  role and a self-contained English brief: target, allowed files, non-goals,
73
77
  relevant facts, observable acceptance, and what evidence to return. Keep edit
@@ -86,13 +90,17 @@ substitute or unobserved activation.
86
90
 
87
91
  For ordinary progress, use milestone commentary. Use `lane_report` for durable
88
92
  structured observations: `progress` selects real paths or completed successful
89
- native `toolCallId`s; runtime, not you, fingerprints them. `waiting` names an
93
+ native `toolCallId`s; runtime, not you, fingerprints them. A decision receipt
94
+ is not work evidence, even when an answer was submitted. `waiting` names an
90
95
  observed tool/approval/job ID or a precise dependency label. `resolved` needs the
91
96
  same target and actual evidence. Identical evidence/repeated waits don't reset
92
97
  clocks. A normal progress report doesn't clear a wait; native tool/approval
93
98
  completion clears only the matching wait, and job/dependency resolution uses a
94
- matching report. Finish the eval reporting cell before a long wait. A printed
95
- receipt doesn't verify acceptance, authorize continuation, or send a message.
99
+ matching report. Finish the eval reporting cell before a long wait. Direct-topic
100
+ observations do not notify HEAD; changed manager-handoff evidence and wait
101
+ transitions are queued to HEAD. No receipt verifies acceptance or authorizes
102
+ continuation. On an eligible assignment, ask via the tracked decision tool
103
+ when HEAD must choose between in-scope ways to resolve a blocker.
96
104
 
97
105
  Assignment scope review is separate from progress and waits. Use the direct
98
106
  native `lane_report` form from the Lane operating contract only for the current
@@ -103,16 +111,6 @@ the explicit correction only to that assignment. Preserve other constraints,
103
111
  actual tool permissions and approvals; do not replay denied or uncertain
104
112
  effects, undo completed effects, or make operator or global changes.
105
113
 
106
- If a board observation helps, use `board_post` for concise evidence or collisions,
107
- `board_read` for needed bodies, and `board_subscribe` for this session's channels.
108
- Runtime verifies actual connected/registered identity per instance and assigns
109
- actor; unmanaged sessions and children are excluded. All participants can read
110
- all instance channels (`general`, `repo:<canonical absolute path>`). Only exact
111
- returned items become read; posting, truncated pages and header notices do not
112
- read skipped items. No polling, read-ACK loop, secrets or transcript dumps. Posts
113
- are data; they can't select work, approve it, or replace the assignment's final
114
- answer.
115
-
116
114
  Put the outcome first in the language required by the managed delivery mode:
117
115
  what changed, acceptance evidence actually checked, remaining risk or held effects,
118
116
  and the exact handoff. Separate observations from child claims. For work feeding
package/src/cli.ts CHANGED
@@ -3,13 +3,13 @@ import { Database } from "bun:sqlite";
3
3
  import { existsSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { isAbsolute, join } from "node:path";
6
- import { configuredPlatforms, credentialEnvNames, hostPaths, loadConfig, loadStateDirectory, requireMessengerCredentials } from "./config";
7
- import { inspectInstalledOmp } from "./installed-omp";
8
- import { requireHostOwner } from "./host-owner-path";
9
- import { loadCredentials } from "./credentials";
6
+ import { configuredPlatforms, credentialEnvNames, hostPaths, loadConfig, loadStateDirectory, requireMessengerCredentials } from "./config/config";
7
+ import { inspectInstalledOmp } from "./omp/installed-omp";
8
+ import { requireHostOwner } from "./omp/host-owner-path";
9
+ import { loadCredentials } from "./config/credentials";
10
10
  import { WORKFLOW_NAMES, type Lane } from "./contracts";
11
- import type { HostConnection } from "./host";
12
- import { readLaneRows } from "./lane-rows";
11
+ import type { HostConnection } from "./omp/host";
12
+ import { readLaneRows } from "./lane/lane-rows";
13
13
 
14
14
  // Keep Host/SDK imports out of setup, doctor and command registration:
15
15
  // OMP's dotenv loader must not choose their credential sources.
@@ -66,6 +66,7 @@ Add a messenger to an existing installation:
66
66
  Editing FILE does not reload a running service. The next Gateway start activates all configured blocks.
67
67
  Other FILE settings: command (stock OMP argv), headCwd, stateDir, maxHosts (includes HEAD),
68
68
  maxSubagents (shared budget), idleMs (idle lane eviction), optional model (HEAD startup model).
69
+ headIdleMs: park a fully idle HEAD after this many milliseconds (default 30 minutes; 0 keeps it resident).
69
70
 
70
71
  Command registration:
71
72
  discord-commands uses Discord REST only: dry-run by default, with no Gateway or native runtime activation.
@@ -94,6 +95,7 @@ Owner controls in chat (not shell commands):
94
95
  /model [list|provider/id] Inspect or select the shared HEAD model; changes require an idle HEAD.
95
96
  /model preset [list|NAME] Inspect or select a preset. Only NAME --global also saves future defaults.
96
97
  /effort [LEVEL] Inspect or change HEAD thinking effort; existing lanes keep their settings.
98
+ /fast Open the HEAD fast tier menu; select a mode and press Confirm.
97
99
  /compact [instructions] Compact idle HEAD context, optionally with multiline instructions.
98
100
  /cron [help] Schedule and manage one-time or recurring jobs in this conversation.
99
101
  /cron pr-add "every 5m" OWNER/REPO Review newly opened external PRs and comment on GitHub (Discord guild parent).
@@ -119,8 +121,6 @@ Capabilities to request from HEAD in chat (not CLI subcommands):
119
121
  Decisions: ask HEAD to request an owner decision, list pending decisions, inspect one or withdraw it.
120
122
  Discord channel context: ask HEAD to inspect channel/thread context or set, list or clear a local purpose
121
123
  note. Notes do not edit Discord's channel description or authorize work.
122
- Shared board: registered HEAD and lane sessions can post, read and subscribe to informational updates
123
- within this instance. Board posts are not commands or approvals.
124
124
  Workflows: begin a request with one of: ${WORKFLOW_NAMES.filter(name => name !== "jevify").join(", ")}.
125
125
  For batch judging against one rubric, begin with lowercase jevify (not /jevify).
126
126
  Operations guide and native tool names: ${join(import.meta.dir, "../docs/OPERATIONS.md")}
@@ -190,8 +190,8 @@ async function workerCommand(args: string[]): Promise<void> {
190
190
  }
191
191
  if (localRepo && !preferred) throw new Error(usage);
192
192
  const config = await loadConfig(configPath ?? "config.local.json");
193
- const { addWorker } = await import("./worker-registration");
194
- const { workerDescribe } = await import("./worker-wire");
193
+ const { addWorker } = await import("./worker/worker-registration");
194
+ const { workerDescribe } = await import("./worker/worker-wire");
195
195
  const result = await addWorker({ destination, stateDir: config.stateDir,
196
196
  ...(preferred ? { defaultRepositoryRoot: localRepo ?? config.headCwd } : {}) }, workerDescribe);
197
197
  console.log(JSON.stringify(result, null, 2));
@@ -209,7 +209,7 @@ async function workerCommand(args: string[]): Promise<void> {
209
209
  if (flags.length !== 0 && (flags.length !== 2 || flag !== "--config" || !file || file.startsWith("-")))
210
210
  throw new Error(usage);
211
211
  const stateDir = await loadStateDirectory(file ?? "config.local.json");
212
- const { workerInventory, workerDoctor } = await import("./worker-doctor");
212
+ const { workerInventory, workerDoctor } = await import("./worker/worker-doctor");
213
213
  if (destination) {
214
214
  const report = await workerDoctor(stateDir, destination);
215
215
  console.log(JSON.stringify(report, null, 2));
@@ -232,10 +232,10 @@ async function workerCommand(args: string[]): Promise<void> {
232
232
  }
233
233
  if (!headKey || !repositories.length) throw new Error(usage);
234
234
  if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("Worker init requires macOS or Linux");
235
- const { workerPublicKey } = await import("./worker-registration");
235
+ const { workerPublicKey } = await import("./worker/worker-registration");
236
236
  const publicKey = workerPublicKey(headKey);
237
- const { enrollWorker } = await import("./worker-enrollment");
238
- const { activeManagedUlw } = await import("./managed-ulw");
237
+ const { enrollWorker } = await import("./worker/worker-enrollment");
238
+ const { activeManagedUlw } = await import("./omp/managed-super");
239
239
  await requireHostOwner();
240
240
  activeManagedUlw();
241
241
  const { executable } = await inspectInstalledOmp(["omp"]);
@@ -248,9 +248,9 @@ async function workerCommand(args: string[]): Promise<void> {
248
248
  if (operands.length !== 2 || flag !== "--policy" || !path || !isAbsolute(path) ||
249
249
  process.env.SSH_ORIGINAL_COMMAND !== "omp-sa-worker-v1")
250
250
  throw new Error("Worker serve requires the enrolled SSH forced command");
251
- const { readWorkerPolicy } = await import("./worker-enrollment");
251
+ const { readWorkerPolicy } = await import("./worker/worker-enrollment");
252
252
  const policy = readWorkerPolicy(homedir(), path);
253
- const { execWorkerBridge } = await import("./worker-bridge");
253
+ const { execWorkerBridge } = await import("./worker/worker-bridge");
254
254
  return execWorkerBridge(policy, path);
255
255
  }
256
256
  default:
@@ -272,12 +272,12 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
272
272
  if (args.length !== 3 || configAt !== 1 || args[2]!.startsWith("-"))
273
273
  throw new Error(`Usage: ${command} --config FILE`);
274
274
  const config = await loadConfig(args[2]!);
275
- const { installAutostart, uninstallAutostart } = await import("./autostart");
275
+ const { installAutostart, uninstallAutostart } = await import("./operator/autostart");
276
276
  console.log(JSON.stringify(await (command === "install" ? installAutostart(config) : uninstallAutostart(config)), null, 2));
277
277
  return;
278
278
  }
279
279
  if (command === "setup") {
280
- const { setup } = await import("./setup");
280
+ const { setup } = await import("./operator/setup");
281
281
  await setup(args[configAt + 1]!);
282
282
  return;
283
283
  }
@@ -303,13 +303,13 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
303
303
  const config = await loadConfig(configPath);
304
304
  let report: unknown;
305
305
  if (command === "discord-commands") {
306
- const { registerDiscordCommands } = await import("./discord-command-registration");
306
+ const { registerDiscordCommands } = await import("./messaging/discord-command-registration");
307
307
  report = await registerDiscordCommands(config, { apply });
308
308
  } else if (command === "telegram-commands") {
309
- const { registerTelegramCommands } = await import("./telegram-command-registration");
309
+ const { registerTelegramCommands } = await import("./messaging/telegram-command-registration");
310
310
  report = await registerTelegramCommands(config, { apply, languageCode: values.get("--language") });
311
311
  } else {
312
- const { registerSlackCommands } = await import("./slack-command-registration");
312
+ const { registerSlackCommands } = await import("./messaging/slack-command-registration");
313
313
  report = await registerSlackCommands(config, { apply, manifestTokenEnv: manifestTokenEnv! });
314
314
  }
315
315
  console.log(JSON.stringify(report, null, 2));
@@ -321,14 +321,14 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
321
321
  if (!((configAt === 1 && args.length === 3) || (configAt === 2 && args.length === 4 && !args[1]?.startsWith("-")))) {
322
322
  throw new Error("Usage: group [REQUEST_ID] --config FILE");
323
323
  }
324
- const { groupRequests } = await import("./group-access");
324
+ const { groupRequests } = await import("./group/group-access");
325
325
  console.log(JSON.stringify(groupRequests(config.stateDir, configAt === 2 ? args[1] : undefined), null, 2));
326
326
  return;
327
327
  }
328
328
  const target = args[1] && !args[1]!.startsWith("-") ? args[1]! : "main";
329
329
  if (command === "doctor") {
330
- const { requireGateway } = await import("./gateway-native");
331
- const { inspectManagedMemory, memoryBlockReason } = await import("./managed-memory");
330
+ const { requireGateway } = await import("./gateway/gateway-native");
331
+ const { inspectManagedMemory, memoryBlockReason } = await import("./omp/managed-memory");
332
332
  loadCredentials(config);
333
333
  const omp = await inspectInstalledOmp(config.command, credentialEnvNames(config));
334
334
  const memory = await inspectManagedMemory(config);
@@ -346,10 +346,10 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
346
346
  return;
347
347
  }
348
348
  if (command === "status") {
349
- const { gatewayStatus } = await import("./gateway-protocol");
350
- const { autostartStatus } = await import("./autostart");
351
- const { listWorkers } = await import("./worker-registration");
352
- const { lanePlacement } = await import("./lane-rows");
349
+ const { gatewayStatus } = await import("./gateway/gateway-protocol");
350
+ const { autostartStatus } = await import("./operator/autostart");
351
+ const { listWorkers } = await import("./worker/worker-registration");
352
+ const { lanePlacement } = await import("./lane/lane-rows");
353
353
  console.log(JSON.stringify({
354
354
  gateway: await gatewayStatus(config),
355
355
  autostart: await autostartStatus(config),
@@ -368,7 +368,7 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
368
368
  }
369
369
  if (command === "stop") {
370
370
  if (target === "main") {
371
- const { stopGateway } = await import("./gateway-native");
371
+ const { stopGateway } = await import("./gateway/gateway-native");
372
372
  await stopGateway(config);
373
373
  console.log("Gateway and supervised main host accepted graceful shutdown.");
374
374
  return;
@@ -378,13 +378,13 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
378
378
  const remote = lane.remote;
379
379
  let host: HostConnection;
380
380
  if (remote) {
381
- const { lookupWorker, remoteLanePaths, workerConnect, workerRef } = await import("./worker-wire");
381
+ const { lookupWorker, remoteLanePaths, workerConnect, workerRef } = await import("./worker/worker-wire");
382
382
  const paths = remoteLanePaths(remote, lane.id);
383
383
  if (lane.pid === null || !lane.sessionId || lane.sessionFile !== paths.sessionFile || lane.socketPath !== paths.socketPath)
384
384
  throw new Error("Remote lane has no recorded Host identity eligible for shutdown");
385
385
  host = await workerConnect(await lookupWorker(config.stateDir, remote), workerRef(lane));
386
386
  } else {
387
- const { connect } = await import("./host");
387
+ const { connect } = await import("./omp/host");
388
388
  host = await connect(hostPaths(config, target).socketPath);
389
389
  }
390
390
  try {
@@ -406,8 +406,8 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
406
406
  loadCredentials(config);
407
407
  // Only pass validated messenger credentials to the native launcher.
408
408
  requireMessengerCredentials(config);
409
- const { gatewayPaths } = await import("./gateway-protocol");
410
- const { launchGateway } = await import("./gateway-native");
409
+ const { gatewayPaths } = await import("./gateway/gateway-protocol");
410
+ const { launchGateway } = await import("./gateway/gateway-native");
411
411
  const status = await launchGateway(config);
412
412
  console.log(JSON.stringify({ ...status, gatewaySocketPath: gatewayPaths(config).socketPath,
413
413
  gatewayLogPath: gatewayPaths(config).logPath,
@@ -1,8 +1,8 @@
1
1
  import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { physicalRoute, type Platform, type Route } from "./contracts";
4
- import { resolveOmpCommand } from "./installed-omp";
5
- import { groupRoom, parseGroupRooms, type GroupRoom } from "./group-policy";
3
+ import { physicalRoute, type Platform, type Route } from "../contracts";
4
+ import { resolveOmpCommand } from "../omp/installed-omp";
5
+ import { groupRoom, parseGroupRooms, type GroupRoom } from "../group/group-policy";
6
6
 
7
7
  export interface DiscordConfig {
8
8
  tokenEnv: string;
@@ -62,6 +62,8 @@ export interface SlackConfig {
62
62
  allowedChannelIds: string[];
63
63
  }
64
64
 
65
+ export const DEFAULT_HEAD_IDLE_MS = 30 * 60 * 1000;
66
+
65
67
  export interface Config {
66
68
  path: string;
67
69
  stateDir: string;
@@ -70,6 +72,7 @@ export interface Config {
70
72
  maxHosts: number;
71
73
  maxSubagents: number;
72
74
  idleMs: number;
75
+ readonly headIdleMs?: number;
73
76
  model?: string;
74
77
  discord?: DiscordConfig;
75
78
  telegram?: TelegramConfig;
@@ -282,6 +285,7 @@ export function parseConfig(value: unknown, path: string): Config {
282
285
  maxHosts,
283
286
  maxSubagents,
284
287
  idleMs: integer(raw.idleMs, "idleMs", 0),
288
+ headIdleMs: raw.headIdleMs === undefined ? DEFAULT_HEAD_IDLE_MS : integer(raw.headIdleMs, "headIdleMs", 0),
285
289
  ...(raw.model === undefined ? {} : { model: text(raw.model, "model") }),
286
290
  ...(discord ? { discord: {
287
291
  tokenEnv: tokenEnv(discord.tokenEnv, "discord.tokenEnv"),
@@ -0,0 +1,36 @@
1
+ import { on } from "node:events";
2
+ import { watch } from "node:fs";
3
+ import { basename, dirname } from "node:path";
4
+ import { parseConfig } from "./config";
5
+
6
+ /** No controller, store or messenger is opened on unapproved bytes. The
7
+ * directory watch survives atomic replacement and is closed on Host stop. */
8
+ export async function loadWakeConfig(path: string, expectedHash: string, signal: AbortSignal) {
9
+ signal.throwIfAborted();
10
+ const watcher = watch(dirname(path), { persistent: false });
11
+ const changes = on(watcher, "change", { signal });
12
+ try {
13
+ for (;;) {
14
+ signal.throwIfAborted();
15
+ let bytes: ArrayBuffer | undefined;
16
+ try { bytes = await Bun.file(path).arrayBuffer(); }
17
+ catch (error) {
18
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
19
+ }
20
+ if (bytes && Bun.CryptoHasher.hash("sha256", bytes, "hex") === expectedHash) {
21
+ return parseConfig(await new Blob([bytes]).json(), path);
22
+ }
23
+ // The config may live beside the live Gateway database. Its journal
24
+ // writes are not a reason to reread the configuration.
25
+ let filename: unknown;
26
+ do {
27
+ const event = await changes.next();
28
+ if (event.done) throw new Error("Configuration watch closed before HEAD wake");
29
+ [, filename] = event.value;
30
+ } while (filename != null && filename !== basename(path));
31
+ }
32
+ } finally {
33
+ watcher.close();
34
+ await changes.return?.();
35
+ }
36
+ }
package/src/contracts.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import type { ModelPreset as NativeModelPreset } from "@oh-my-pi/pi-coding-agent/config/model-settings";
2
- import type { LaneEvidence, LaneReport, LaneWaitTarget } from "./lane-report";
3
- import type { CronUpdate } from "./cron-jobs";
4
- import type { ReviewRound } from "./pr-intake-review";
5
- import type { GroupReply, GroupRequest } from "./group-policy";
6
- import type { StagedResultAttachment } from "./result-attachment";
7
- import type { RemotePlacement } from "./worker-wire";
8
- import type { OmpResetAccount } from "./omp-usage";
2
+ import type { LaneEvidence, LaneReport, LaneWaitTarget } from "./lane/lane-report";
3
+ import type { CronUpdate } from "./cron/cron-jobs";
4
+ import type { ReviewRound } from "./pr/pr-intake-review";
5
+ import type { GroupReply, GroupRequest } from "./group/group-policy";
6
+ import type { StagedResultAttachment } from "./messaging/result-attachment";
7
+ import type { RemotePlacement } from "./worker/worker-wire";
8
+ import type { OmpResetAccount } from "./omp/omp-usage";
9
9
 
10
10
  /** Coordination records only. OMP owns transcripts and execution state. */
11
11
  export type Platform = "discord" | "telegram" | "slack" | "kakao";
12
+ export type HistoryPlatform = Extract<Platform, "discord" | "slack">;
12
13
 
13
14
  export interface Route {
14
15
  platform: Platform;
@@ -40,8 +41,22 @@ export function physicalRouteKey(route: Route): string {
40
41
  return routeKey(physicalRoute(route));
41
42
  }
42
43
 
43
- /** Store meta key: owner inputs acknowledged to Gateway whose topic routing is still pending, in delivery order. */
44
- export const DEFERRED_ROUTING_META = "intake:deferred-routing";
44
+ /** Deferred intake shares order across threads and logical topics of a channel or DM. */
45
+ export function routingConversation(route: Route): string {
46
+ return routeKey({ ...physicalRoute(route), threadId: null });
47
+ }
48
+
49
+ /** Syntax only: these candidates still require current receipt and route authority. */
50
+ export function deferredRecoveryCandidate(text: string) {
51
+ const match = /^\/(restart|stop)(?:\s+(\S+))?$/u.exec(text.trim());
52
+ if (!match) return null;
53
+ const [, name, argument] = match;
54
+ if (name === "restart") return argument ? null : { kind: "restart" } as const;
55
+ if (!argument) return { kind: "bare-stop" } as const;
56
+ if (argument === "head") return { kind: "head-stop" } as const;
57
+ return { kind: "lane-stop", laneId: argument } as const;
58
+ }
59
+
45
60
  /** Internal HEAD review ID prefix; authority lives in the current store binding. */
46
61
  export const SCOPE_REVIEW_PREFIX = "scope-review:";
47
62
 
@@ -133,6 +148,10 @@ export interface Inbound {
133
148
  readonly discordOriginalText?: string;
134
149
  /** Adapter-verified routing-only view; an empty string excludes the entire message. */
135
150
  readonly routingText?: string;
151
+ /** Telegram's authenticated formatting verdict; absent on pre-upgrade receipts. */
152
+ readonly telegramProtectedCommand?: boolean;
153
+ /** Original Telegram text or caption when an addressed bot suffix was removed. */
154
+ readonly telegramOriginalText?: string;
136
155
  receivedAt: number;
137
156
  attachments: Attachment[];
138
157
  reply?: ReplyContext;
@@ -259,6 +278,7 @@ export type HeadPicker = {
259
278
  };
260
279
  } }
261
280
  | { readonly kind: "effort"; readonly forModel: LaneModel }
281
+ | { readonly kind: "fast"; readonly forModel: LaneModel }
262
282
  | { readonly kind: "usage-reset"; readonly accounts: readonly Pick<OmpResetAccount, "target" | "label" | "identity" | "offer">[] }
263
283
  );
264
284
 
@@ -378,7 +398,25 @@ export interface HeadRecoveryEffect {
378
398
  state: string;
379
399
  }
380
400
 
401
+ /** Ordered HEAD receipts for owner inputs still waiting for topic routing. */
402
+ export interface DeferredRoutingPort {
403
+ enqueue(input: Inbound): void;
404
+ /** Verify an existing deferred receipt and refresh eligible attachment URLs without changing order. */
405
+ reconcile(input: Inbound): boolean;
406
+ input(id: string): Inbound | null;
407
+ has(id: string): boolean;
408
+ head(conversation: string): string | null;
409
+ conversations(): readonly string[];
410
+ priority(conversation: string, includeBare: boolean): Iterable<Inbound>;
411
+ earlierLaneStops(lane: Pick<Lane, "id" | "route">, beforeId: string): Iterable<Inbound>;
412
+ hasEarlierMessage(input: Pick<Inbound, "id" | "route">, messageId: string): boolean;
413
+ /** IDs before this queued receipt, or all currently queued IDs for fresh direct admission. */
414
+ idsBefore(id: string): readonly string[];
415
+ remove(id: string): void;
416
+ }
417
+
381
418
  export interface StorePort {
419
+ readonly deferredRouting: DeferredRoutingPort;
382
420
  /** Typed, noninteractive work on the confirmed bot offer; never valid for ordinary owner intake. */
383
421
  receivePrWork(input: Inbound, target: string | null, round: ReviewRound): boolean;
384
422
  receive(input: Inbound, target: string | null, metadata?: Readonly<Record<string, string>>, workflow?: WorkflowActivation | null): boolean;
@@ -417,6 +455,8 @@ export interface StorePort {
417
455
  hasHeadRecoveryInput(): boolean;
418
456
  /** No automatic head replacement while an original HEAD delivery is unresolved. */
419
457
  hasUnresolvedHeadDelivery(): boolean;
458
+ /** Any queued or held coordination work makes hibernating the controller unsafe. */
459
+ hasHeadSleepWork(): boolean;
420
460
  kickoffHold(target: string): KickoffHold | null;
421
461
  /** The first authorized revision on the physical route, even after settlement. */
422
462
  firstAdmittedMessage(route: Route, messageId: string): InputRecord | null;
@@ -449,6 +489,9 @@ export interface StorePort {
449
489
  prepareHeadRecovery(attempt: HeadRecoveryAttempt): boolean;
450
490
  commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean;
451
491
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
492
+ /** Atomically replace this native Host's outstanding job bindings and enqueue observed results. */
493
+ saveHeadJobs(bindingKey: string, owners: readonly (readonly [string, string, string])[],
494
+ outputs?: readonly Pick<OutputRecord, "id" | "sourceId" | "route" | "text">[]): void;
452
495
  recordRestartCheckpointFailure(expectedFence: string, stopBoundary: string | null, failedFence: string,
453
496
  output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
454
497
  recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
@@ -478,6 +521,7 @@ export interface StorePort {
478
521
  recoverDeliveries(): void;
479
522
  getMeta(key: string): string | null;
480
523
  setMeta(key: string, value: string): void;
524
+ completeHistoryBoundary(key: string, cursor: string, sequence: string | null): void;
481
525
  close(): void;
482
526
  }
483
527
 
@@ -545,6 +589,8 @@ export interface InboundAttachmentReceipt {
545
589
  }
546
590
 
547
591
  export interface Messenger {
592
+ /** Startup history, when needed, is ordered by the authenticated transport. */
593
+ readonly managesStartupHistory?: true;
548
594
  start(handlers: {
549
595
  /** Authenticate first; do not consume inbound events until native approvals are reconciled. */
550
596
  ready?: Promise<void>;
@@ -553,7 +599,10 @@ export interface Messenger {
553
599
  answer(approvalId: string, response: DialogResponse, route: Route): Promise<void>;
554
600
  /** Reconcile a previously attempted answer before retrying its native effect. */
555
601
  reconcileAnswer?(approvalId: string, route: Route): Promise<"retry" | "accepted" | "rejected" | "unresolved">;
556
- reconnect?(): Promise<void>;
602
+ /** Pin existing cursors before a fresh Gateway opens ordered intake. */
603
+ reserveStartupHistory?(): void;
604
+ /** A sequence identifies an ordered Gateway gap; false reconciles approvals only. */
605
+ reconnect?(history?: number | false, platform?: HistoryPlatform): Promise<void>;
557
606
  /** Owned Gateway lifecycle outcome; never a user instruction or model turn. */
558
607
  restart?(notice: GatewayRestartNotice): Promise<void>;
559
608
  }): Promise<void>;
@@ -574,8 +623,8 @@ export interface Messenger {
574
623
  inspectDiscordContext?(route: Route): Promise<DiscordContext>;
575
624
  discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
576
625
  messengerPresence?(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus>;
577
- /** null explicitly means no history API; intake recovery belongs to the adapter. */
578
- fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null>;
626
+ /** null means adapter-owned recovery. An ordered read uses the Gateway's saved gap cutoff. */
627
+ fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null>;
579
628
  /** Validate the source before fetching; receipt only a complete, private batch. */
580
629
  openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt>;
581
630
  stop(): Promise<void>;
@@ -1,11 +1,12 @@
1
1
  // allow: SIZE_OK — prompt and PR intake jobs share one atomic schedule/control ledger.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { authorizeRoute, type Config } from "./config";
4
- import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "./contracts";
3
+ import { authorizeRoute, type Config } from "../config/config";
4
+ import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "../contracts";
5
5
  import { describePrIntake, normalizeIntakeRepository } from "./cron-pr-intake";
6
6
  import { describeCronSchedule, nextCronTime, parseCronSchedule, type CronSchedule } from "./cron-schedule";
7
- import { compareMessageIds } from "./message-order";
8
- import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "./pr-intake-mode";
7
+ import { compareMessageIds } from "../routing/message-order";
8
+ import { matchesWrittenCommand } from "../messaging/messenger-commands";
9
+ import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "../pr/pr-intake-mode";
9
10
 
10
11
  const jobsKey = "cron:jobs";
11
12
  export const CRON_RUN_PREFIX = "cron-run:";
@@ -121,14 +122,14 @@ function prModeReceipt(job: CronPrJob, mode: PrIntakeMode): string {
121
122
  }
122
123
 
123
124
  function prAddRequest(tail: string) {
124
- const pair = /^"([^"\r\n]+)"[ \t]+([^ \t\r\n]+)$/u.exec(tail);
125
+ const pair = /^"([^"\r\n]+)"[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(tail);
125
126
  if (!pair?.[1] || !pair[2]) return null;
126
127
  const repository = normalizeIntakeRepository(pair[2]);
127
128
  return repository ? { schedule: pair[1].trim(), repository } : null;
128
129
  }
129
130
 
130
131
  function originalPrAdd(text: string) {
131
- const tail = /^\/cron[ \t]+pr-add[ \t]+(.+)$/u.exec(text.trim())?.[1];
132
+ const tail = /^\/cron[^\S\r\n\u2028\u2029]+pr-add[^\S\r\n\u2028\u2029]+(.+)$/u.exec(text.trim())?.[1];
132
133
  return tail ? prAddRequest(tail) : null;
133
134
  }
134
135
 
@@ -216,10 +217,8 @@ export class CronJobs {
216
217
  const stored = this.store.input(input.id);
217
218
  // A voice confirmation can have projected draft text in `text`. It is
218
219
  // not a physical owner instruction to open a lane or publish to GitHub.
219
- const written = stored?.discordOriginalText?.trim().replace(/^<@!?(\d+)>\s*/, (mention, id) =>
220
- id === route.accountId ? "" : mention).trim();
221
220
  return stored !== null && (stored.state === "pending" || stored.state === "done")
222
- && (written === undefined || written === stored.text.trim())
221
+ && matchesWrittenCommand(stored)
223
222
  && routeKey(stored.route) === routeKey(route) && stored.messageId === input.messageId
224
223
  && stored.interactionId === input.interactionId && !stored.pickerSelection
225
224
  && (stored.messageId === null ? stored.interactionId !== undefined
@@ -606,14 +605,23 @@ export class CronJobs {
606
605
  return id.startsWith(CRON_RUN_PREFIX) && this.store.getMeta(`cron-shell:${id}`) !== null;
607
606
  }
608
607
 
608
+ private scheduled(job: CronJob, boundary: string | null): job is CronJob & { nextAt: number } {
609
+ return job.nextAt !== null && !job.paused && job.stopBoundary === boundary
610
+ && (job.kind === "pr-intake" ? !job.removed : job.shell !== true);
611
+ }
612
+
613
+ hasScheduledWork(): boolean {
614
+ const boundary = this.store.getMeta("head:stop-boundary");
615
+ return this.state().jobs.some(job => this.scheduled(job, boundary) && this.source(job) !== null);
616
+ }
617
+
609
618
  poll(now: number): void {
610
619
  if (this.store.getMeta("head:restart-fence")) return;
611
620
  let state = this.state();
612
621
  const boundary = this.store.getMeta("head:stop-boundary");
613
- for (const job of state.jobs.filter(job => job.nextAt !== null && job.nextAt <= now)
614
- .sort((left, right) => (left.nextAt ?? 0) - (right.nextAt ?? 0))) {
615
- if (job.nextAt === null || job.paused || job.stopBoundary !== boundary || job.kind === "pr-intake" && job.removed) continue;
616
- if (job.kind !== "pr-intake" && job.shell === true) continue;
622
+ const scheduled = state.jobs.filter((job): job is CronJob & { nextAt: number } =>
623
+ this.scheduled(job, boundary) && job.nextAt <= now);
624
+ for (const job of scheduled.sort((left, right) => left.nextAt - right.nextAt)) {
617
625
  const source = this.source(job);
618
626
  if (!source) continue;
619
627
  const last = job.lastRunId ? this.store.input(job.lastRunId) : null;
@@ -1,10 +1,10 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
- import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "./contracts";
3
+ import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "../contracts";
4
4
  import type { CronJobs, CronPrJob } from "./cron-jobs";
5
- import { parsePrRef } from "./pr-github";
6
- import { PrReadError } from "./pr-github-schema";
7
- import { intakeStatusKey } from "./pr-intake-work";
5
+ import { parsePrRef } from "../pr/pr-github";
6
+ import { PrReadError } from "../pr/pr-github-schema";
7
+ import { intakeStatusKey } from "../pr/pr-intake-work";
8
8
 
9
9
  const offerPrefix = "cron-pr:offer:";
10
10
  const githubId = Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }));
@@ -6,7 +6,7 @@ export type CronSchedule =
6
6
  | { readonly kind: "calendar"; readonly expression: string; readonly timezone: string };
7
7
 
8
8
  export function parseCronSchedule(text: string, now: number): CronSchedule | null {
9
- const relative = /^(in|every) ([1-9]\d*)([smhd])$/.exec(text);
9
+ const relative = /^(in|every)[^\S\r\n\u2028\u2029]+([1-9]\d*)([smhd])$/u.exec(text);
10
10
  if (relative) {
11
11
  const [, mode, amount, unit] = relative;
12
12
  const seconds = Number(amount) * (unit === "s" ? 1 : unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
@@ -14,8 +14,8 @@ export function parseCronSchedule(text: string, now: number): CronSchedule | nul
14
14
  if (!Number.isFinite(new Date(now + milliseconds).getTime()) || mode === "every" && seconds < 60) return null;
15
15
  return mode === "every" ? { kind: "interval", milliseconds } : { kind: "once", at: now + milliseconds };
16
16
  }
17
- if (text.startsWith("at ")) {
18
- const date = text.slice(3);
17
+ const date = /^at[^\S\r\n\u2028\u2029]+(\S+)$/u.exec(text)?.[1];
18
+ if (date) {
19
19
  if (!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?:Z|[+-]\d{2}:\d{2})$/.test(date)) return null;
20
20
  const day = date.slice(0, 10);
21
21
  const midnight = new Date(`${day}T00:00:00Z`);