clavarium-docket 0.0.2 → 0.1.0-next.2
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.
- package/README.md +14 -1
- package/bin/docket.mjs +62 -0
- package/docs/protocol.md +97 -0
- package/host/docket-host.mjs +90 -0
- package/package.json +38 -7
- package/server/docket.mjs +237 -0
- package/server/time.mjs +127 -0
- package/keep.mjs +0 -7
package/README.md
CHANGED
|
@@ -17,6 +17,19 @@ acknowledged is delivered again.
|
|
|
17
17
|
A sibling of [Clavarium Parley](https://github.com/clavarium/clavarium-parley),
|
|
18
18
|
built the same way, universal (nothing in it is specific to Clavarium).
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
A worker may also set itself reminders, which come as events when due:
|
|
21
|
+
|
|
22
|
+
docket remind --at "2026-10-23 09:00" "call the client back"
|
|
23
|
+
docket remind --in 2h "check the build"
|
|
24
|
+
docket remind --cron "0 9 * * 1" "Monday review"
|
|
25
|
+
|
|
26
|
+
The application's side (`clavarium-docket/host`) posts events, turns the
|
|
27
|
+
reminders that came due into events (`tick`), and is told what the worker
|
|
28
|
+
did. When to tell the worker, and how often again, is the application's
|
|
29
|
+
business. See [docs/protocol.md](docs/protocol.md).
|
|
30
|
+
|
|
31
|
+
No dependency; Node 22 or later.
|
|
32
|
+
|
|
33
|
+
**Status:** first version (0.1), tested here; not tried with a real agent yet.
|
|
21
34
|
|
|
22
35
|
License: MIT.
|
package/bin/docket.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* THE COMMAND: Docket's verbs for any worker that can run a command. It writes
|
|
3
|
+
* the same files as the MCP server (server/docket.mjs).
|
|
4
|
+
*
|
|
5
|
+
* docket | done | failed | remind | cancel | tick | --help | --version
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { verbs, findFolder, FOLDER, VERSION } from '../server/docket.mjs';
|
|
10
|
+
|
|
11
|
+
export const HELP = `docket: the events an application posted for you, and what you did of each.
|
|
12
|
+
|
|
13
|
+
docket what waits, oldest first, each with its id; then your reminders
|
|
14
|
+
docket done ID ["note"] handled
|
|
15
|
+
docket failed ID "why" could not be handled: say why; the person is told
|
|
16
|
+
docket remind --at "2026-10-23 09:00" "text"
|
|
17
|
+
docket remind --in 2h "text" also 45m, 3d
|
|
18
|
+
docket remind --cron "0 9 * * 1" "text"
|
|
19
|
+
set yourself a reminder: it comes as an event when due
|
|
20
|
+
docket cancel ID take back a reminder you set
|
|
21
|
+
docket tick post the reminders due (for a machine with no application)
|
|
22
|
+
|
|
23
|
+
ID: whole, or its first 8 characters. Times are in $DOCKET_TZ, else the machine's time zone.
|
|
24
|
+
An event waits until you say done or failed: one never acknowledged is given to you again.
|
|
25
|
+
The folder used is --dir FOLDER, else $DOCKET_DIR, else the nearest ${FOLDER} folder from here up.
|
|
26
|
+
docket ${VERSION}`;
|
|
27
|
+
|
|
28
|
+
/* Runs one command line. Resolves with { code, out, err }: nothing is printed here. */
|
|
29
|
+
export function run(argv, { env = process.env, cwd = process.cwd(), now } = {}) {
|
|
30
|
+
const args = [...argv];
|
|
31
|
+
let dir;
|
|
32
|
+
const at = args.indexOf('--dir');
|
|
33
|
+
if (at >= 0) { dir = args[at + 1]; if (!dir) return { code: 64, out: '', err: '--dir needs a folder.\n' }; args.splice(at, 2); }
|
|
34
|
+
const [verb = 'list', ...rest] = args;
|
|
35
|
+
if (verb === '--help' || verb === '-h' || verb === 'help') return { code: 0, out: `${HELP}\n`, err: '' };
|
|
36
|
+
if (verb === '--version') return { code: 0, out: `${VERSION}\n`, err: '' };
|
|
37
|
+
if (!['list', 'done', 'failed', 'remind', 'cancel', 'tick'].includes(verb)) return { code: 64, out: '', err: `Unknown: ${verb}. Run "docket --help".\n` };
|
|
38
|
+
const folder = findFolder({ dir, env, from: cwd });
|
|
39
|
+
if (!folder) return { code: 2, out: '', err: `No ${FOLDER} folder here or above. Run it from your work folder, or give --dir FOLDER.\n` };
|
|
40
|
+
const v = verbs(folder, { env, ...(now ? { now } : {}) });
|
|
41
|
+
const flag = (name) => { const i = rest.indexOf(name); if (i < 0) return undefined; const value = rest[i + 1]; rest.splice(i, 2); return value ?? ''; };
|
|
42
|
+
try {
|
|
43
|
+
let said;
|
|
44
|
+
if (verb === 'list') { if (rest.length) return { code: 64, out: '', err: 'docket alone lists; it takes nothing else.\n' }; said = v.list(); }
|
|
45
|
+
else if (verb === 'done') said = v.done(rest[0], rest.slice(1).join(' '));
|
|
46
|
+
else if (verb === 'failed') said = v.failed(rest[0], rest.slice(1).join(' '));
|
|
47
|
+
else if (verb === 'remind') { const when = { at: flag('--at'), in: flag('--in'), cron: flag('--cron') }; said = v.remind({ ...when, text: rest.join(' ') }); }
|
|
48
|
+
else if (verb === 'cancel') said = v.cancel(rest[0]);
|
|
49
|
+
else { const n = v.tick(); said = n === 0 ? 'Nothing came due.' : `${n} reminder${n === 1 ? '' : 's'} came due.`; }
|
|
50
|
+
return { code: 0, out: `${said}\n`, err: '' };
|
|
51
|
+
} catch (error) {
|
|
52
|
+
return { code: 1, out: '', err: `Not done: ${error.message}. Run "docket --help".\n` };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const main = (() => { try { return realpathSync(process.argv[1] ?? '') === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } })();
|
|
57
|
+
if (main) {
|
|
58
|
+
const r = run(process.argv.slice(2));
|
|
59
|
+
if (r.out) process.stdout.write(r.out);
|
|
60
|
+
if (r.err) process.stderr.write(r.err);
|
|
61
|
+
process.exitCode = r.code;
|
|
62
|
+
}
|
package/docs/protocol.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# The protocol
|
|
2
|
+
|
|
3
|
+
Docket is three small things that agree on one folder, as Parley does: a
|
|
4
|
+
command and an MCP server for whoever does the work (an agent, a script), and
|
|
5
|
+
a library for the application that posts events.
|
|
6
|
+
|
|
7
|
+
## The folder
|
|
8
|
+
|
|
9
|
+
| File | Written by | What it holds |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `events.jsonl` | the application | what happened, one event per line |
|
|
12
|
+
| `acks.jsonl` | the worker | what it did of each event: done, or failed and why |
|
|
13
|
+
| `plans.jsonl` | the worker | the reminders it set itself, and those it took back |
|
|
14
|
+
| `plans-off.jsonl` | the application | the reminders the person took back |
|
|
15
|
+
| `zone` | the application | the person's time zone, one IANA name (optional) |
|
|
16
|
+
|
|
17
|
+
Every `.jsonl` file only grows: nothing is edited, nothing is deleted. Each has one
|
|
18
|
+
writer. There is no address, no port and no key: whoever can read and write
|
|
19
|
+
the folder is a side.
|
|
20
|
+
|
|
21
|
+
The command finds the folder as git finds a repository: `--dir`, else
|
|
22
|
+
`$DOCKET_DIR`, else the nearest `.docket` from where it stands.
|
|
23
|
+
|
|
24
|
+
## An event
|
|
25
|
+
|
|
26
|
+
{id, at, from, kind, text, data?, plan?, due?}
|
|
27
|
+
|
|
28
|
+
`from` names who posted it (`clavarium`, `mail`, `docket` for a reminder),
|
|
29
|
+
`kind` what it is (`arrival`, `call`, `clock`, `reminder`, any word), `text`
|
|
30
|
+
one line a person would write (500 characters), `data` a small object for a
|
|
31
|
+
program (4 KB once written). A reminder carries the `plan` it came from and
|
|
32
|
+
the time it was `due`.
|
|
33
|
+
|
|
34
|
+
An event WAITS until the worker says what it did of it. Nothing else takes it
|
|
35
|
+
out: an event told and never acknowledged is told again (when, and how
|
|
36
|
+
often, is the application's business).
|
|
37
|
+
|
|
38
|
+
## What the worker can do
|
|
39
|
+
|
|
40
|
+
| Command | MCP tool | It writes | It says |
|
|
41
|
+
|---|---|---|---|
|
|
42
|
+
| `docket` | `list()` | nothing | the events that wait, oldest first, each with its id; then the reminders set |
|
|
43
|
+
| `docket done ID [NOTE]` | `done(id, note?)` | `{kind:"done", event, note}` | at once |
|
|
44
|
+
| `docket failed ID WHY` | `failed(id, why)` | `{kind:"failed", event, note}` | at once; the application tells the person |
|
|
45
|
+
| `docket remind --at WHEN TEXT` | `remind({at, text})` | `{kind:"plan", id, at: WHEN, text}` | the time it is due, as understood |
|
|
46
|
+
| `docket remind --in 2h TEXT` | `remind({in, text})` | the same, `at` reckoned now | the same |
|
|
47
|
+
| `docket remind --cron "M H D M W" TEXT` | `remind({cron, text})` | `{kind:"plan", id, cron, tz, text}` | the next time it is due |
|
|
48
|
+
| `docket cancel PLAN` | `cancel(plan)` | `{kind:"cancel", plan}` | at once |
|
|
49
|
+
| `docket tick` | none | events, for the reminders due | how many; for a machine with no application, from its own cron |
|
|
50
|
+
|
|
51
|
+
ID and PLAN are given whole, or by their first 8 characters or more. WHEN is
|
|
52
|
+
a date and a time, `2026-10-23 09:00`, in the time zone of the folder (below),
|
|
53
|
+
or with its own offset. `--in` takes minutes, hours or days: `45m`, `2h`,
|
|
54
|
+
`3d`. A cron line is five fields (minute, hour, day of the month, month, day of
|
|
55
|
+
the week; `*`, lists, ranges and steps). A reminder is at most a year away; a
|
|
56
|
+
plan by cron says its next time each time it is listed.
|
|
57
|
+
|
|
58
|
+
`acks.jsonl` and `plans.jsonl` lines also carry `id` and `at` (the time,
|
|
59
|
+
ISO 8601). An event acknowledged twice keeps the first. Exit codes of the
|
|
60
|
+
command: 0 done, 1 refused, 2 no folder, 64 not understood.
|
|
61
|
+
|
|
62
|
+
## Time
|
|
63
|
+
|
|
64
|
+
A folder's time zone is `$DOCKET_TZ` (an IANA name, `Europe/Paris`), else
|
|
65
|
+
the one the application wrote in its `zone` file (`zone(tz)`: the person's,
|
|
66
|
+
since a machine often runs in UTC), else the machine's. It is written into each plan, so that a cron line keeps meaning
|
|
67
|
+
what it meant where it was set.
|
|
68
|
+
|
|
69
|
+
## Reminders become events
|
|
70
|
+
|
|
71
|
+
`tick(now)` (the application's, every few seconds; `docket tick` without one)
|
|
72
|
+
posts an event for each reminder that came due and was not posted yet: once
|
|
73
|
+
per time it is due (its id says which), `from: "docket"`, `kind: "reminder"`,
|
|
74
|
+
the plan's text. One missed while nothing ran is posted late, once, saying
|
|
75
|
+
so; a cron plan missed more than once is posted once, for the last time it
|
|
76
|
+
was due.
|
|
77
|
+
|
|
78
|
+
## The application's side
|
|
79
|
+
|
|
80
|
+
| Action | Gives |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `post({from, kind, text, data?})` | the event, written |
|
|
83
|
+
| `read()` | `events` (each with `state`: `waiting`, `done` or `failed`, and its `ack`), `plans` (each with `next`, or `off`), `waiting` (how many) |
|
|
84
|
+
| `tick(now?)` | the events it posted |
|
|
85
|
+
| `cancel(plan)` | the plan taken back, by the person |
|
|
86
|
+
| `zone(tz)` | the folder's time zone written |
|
|
87
|
+
| `listen({every})` | events of its own: `acked` (`{event, ack}`), `planned` (`{plan}`), `cancelled` (`{plan}`) |
|
|
88
|
+
|
|
89
|
+
`WAKE` is one line the application may type to a worker that waits at a
|
|
90
|
+
prompt: `You have something to handle: run "docket".` What an event says is
|
|
91
|
+
never on that line.
|
|
92
|
+
|
|
93
|
+
## What each side must not trust
|
|
94
|
+
|
|
95
|
+
What the worker wrote (its notes, its reminders' text) is text chosen by a
|
|
96
|
+
program: bounded, cleaned of what a screen obeys, given as text. A line that
|
|
97
|
+
does not parse is skipped. A link where a file should be is not followed.
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/* THE APPLICATION'S SIDE OF DOCKET: it posts what happened, turns the
|
|
2
|
+
* reminders that came due into events, and is told what the worker did.
|
|
3
|
+
*
|
|
4
|
+
* DOCKET ANNOUNCES, THE APPLICATION DECIDES. When to tell the worker that
|
|
5
|
+
* something waits, how often to tell it again, whom to tell of a failure: the
|
|
6
|
+
* application's business. WAKE is a line it may type.
|
|
7
|
+
*
|
|
8
|
+
* events, to `on(event)` actions, called by the application
|
|
9
|
+
* acked {event, ack} post({from, kind, text, data})
|
|
10
|
+
* planned {plan} read()
|
|
11
|
+
* cancelled {plan} tick(now)
|
|
12
|
+
* cancel(plan) (by the person)
|
|
13
|
+
*
|
|
14
|
+
* WHAT IS READ HERE WAS WRITTEN BY A WORKER: its notes and its reminders are
|
|
15
|
+
* text chosen by a program, bounded and cleaned, handed over as text.
|
|
16
|
+
*/
|
|
17
|
+
import { appendFileSync, mkdirSync, statSync, lstatSync, writeFileSync, renameSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { randomUUID } from 'node:crypto';
|
|
20
|
+
import { state, tick, oneLine, TEXT_MAX, DATA_MAX, WAKE, VERSION, FOLDER } from '../server/docket.mjs';
|
|
21
|
+
import { isZone } from '../server/time.mjs';
|
|
22
|
+
|
|
23
|
+
export { WAKE, VERSION, FOLDER };
|
|
24
|
+
|
|
25
|
+
export class Docket {
|
|
26
|
+
#dir; #on; #now;
|
|
27
|
+
/* `on(event)`: told what the worker did (acked), set (planned) or took back (cancelled). `now()`: milliseconds. */
|
|
28
|
+
constructor(dir, { on, now = () => Date.now() } = {}) { this.#dir = dir; this.#on = on; this.#now = now; }
|
|
29
|
+
|
|
30
|
+
#tell(event) { try { this.#on?.(event); } catch { /* a hook that fails stops nothing */ } }
|
|
31
|
+
#append(file, entry) { mkdirSync(this.#dir, { recursive: true }); appendFileSync(join(this.#dir, file), `${JSON.stringify(entry)}\n`); }
|
|
32
|
+
|
|
33
|
+
/* Something happened: one event, waiting until the worker says what it did of it. */
|
|
34
|
+
post({ from, kind, text, data } = {}) {
|
|
35
|
+
const said = oneLine(text, TEXT_MAX);
|
|
36
|
+
if (!said) throw new RangeError('An event says what happened.');
|
|
37
|
+
const extra = data === undefined ? undefined : JSON.stringify(data);
|
|
38
|
+
if (extra !== undefined && (typeof data !== 'object' || data === null || Array.isArray(data) || extra.length > DATA_MAX)) throw new RangeError(`An event's data is an object of ${DATA_MAX} characters at most.`);
|
|
39
|
+
const event = { id: randomUUID(), at: new Date(this.#now()).toISOString(), from: oneLine(from, 40) || 'app', kind: oneLine(kind, 40) || 'event', text: said, ...(extra === undefined ? {} : { data }) };
|
|
40
|
+
this.#append('events.jsonl', event);
|
|
41
|
+
return event;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/* Everything: the events (each with its state and ack), the reminders (each with when it is next due), how many wait. */
|
|
45
|
+
read() { return state(this.#dir, { now: this.#now() }); }
|
|
46
|
+
|
|
47
|
+
/* The reminders that came due, posted as events: once each time each is due. */
|
|
48
|
+
tick(now = this.#now()) { return tick(this.#dir, { now }); }
|
|
49
|
+
|
|
50
|
+
/* The person's time zone (an IANA name), written for the worker: the times it gives are read in it. */
|
|
51
|
+
zone(tz) {
|
|
52
|
+
if (!isZone(tz)) throw new RangeError('Not a time zone.');
|
|
53
|
+
mkdirSync(this.#dir, { recursive: true });
|
|
54
|
+
writeFileSync(join(this.#dir, 'zone.new'), `${tz}\n`);
|
|
55
|
+
renameSync(join(this.#dir, 'zone.new'), join(this.#dir, 'zone'));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/* The person takes a reminder back. */
|
|
59
|
+
cancel(plan) {
|
|
60
|
+
const found = this.read().plans.find((p) => p.id === plan);
|
|
61
|
+
if (!found) throw new RangeError('No such reminder.');
|
|
62
|
+
if (found.off) return this.read();
|
|
63
|
+
this.#append('plans-off.jsonl', { id: randomUUID(), at: new Date(this.#now()).toISOString(), plan: found.id });
|
|
64
|
+
return this.read();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/* Starts announcing, FROM NOW ON, what the worker writes: acked, planned, cancelled. The files are
|
|
68
|
+
looked at, nothing is pushed. Resolves with a function that stops it. */
|
|
69
|
+
listen({ every = 2000 } = {}) {
|
|
70
|
+
const size = (f) => { try { return lstatSync(join(this.#dir, f)).isSymbolicLink() ? 0 : statSync(join(this.#dir, f)).size; } catch { return 0; } };
|
|
71
|
+
const known = () => { const s = this.read(); return { acks: new Set(s.events.filter((e) => e.ack).map((e) => e.id)), plans: new Set(s.plans.map((p) => p.id)), off: new Set(s.plans.filter((p) => p.off).map((p) => p.id)) }; };
|
|
72
|
+
let was = known();
|
|
73
|
+
let sizes = ['acks.jsonl', 'plans.jsonl', 'plans-off.jsonl'].map(size).join();
|
|
74
|
+
const look = () => {
|
|
75
|
+
const now = ['acks.jsonl', 'plans.jsonl', 'plans-off.jsonl'].map(size).join();
|
|
76
|
+
if (now === sizes) return;
|
|
77
|
+
sizes = now;
|
|
78
|
+
const s = this.read();
|
|
79
|
+
for (const e of s.events) if (e.ack && !was.acks.has(e.id)) this.#tell({ type: 'acked', event: e, ack: e.ack });
|
|
80
|
+
for (const p of s.plans) {
|
|
81
|
+
if (!was.plans.has(p.id)) this.#tell({ type: 'planned', plan: p });
|
|
82
|
+
else if (p.off && !was.off.has(p.id)) this.#tell({ type: 'cancelled', plan: p });
|
|
83
|
+
}
|
|
84
|
+
was = known();
|
|
85
|
+
};
|
|
86
|
+
const timer = setInterval(look, every);
|
|
87
|
+
timer.unref?.();
|
|
88
|
+
return () => clearInterval(timer);
|
|
89
|
+
}
|
|
90
|
+
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium-docket",
|
|
3
|
-
"version": "0.0.2",
|
|
4
|
-
"description": "Clavarium Docket: events an AI agent or a script sees and acknowledges (
|
|
3
|
+
"version": "0.1.0-next.2",
|
|
4
|
+
"description": "Clavarium Docket: events an AI agent or a script sees and acknowledges, and reminders it sets itself (a command and an MCP server, and a library for the application). No dependency.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/clavarium/clavarium-docket#readme",
|
|
7
|
-
"repository": {
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/clavarium/clavarium-docket.git"
|
|
10
|
+
},
|
|
8
11
|
"type": "module",
|
|
9
|
-
"bin": {
|
|
10
|
-
|
|
12
|
+
"bin": {
|
|
13
|
+
"docket": "bin/docket.mjs",
|
|
14
|
+
"docket-mcp": "server/docket.mjs"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"bin/",
|
|
18
|
+
"server/",
|
|
19
|
+
"host/",
|
|
20
|
+
"docs/",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
11
24
|
"dependencies": {},
|
|
12
|
-
"engines": {
|
|
13
|
-
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"check": "npm run check:hooks && npm run check:shapes && npm run check:names && npm run check:shell && npm test",
|
|
33
|
+
"check:shapes": "node tools/check-shapes.mjs",
|
|
34
|
+
"check:names": "node tools/check-ai-names.mjs",
|
|
35
|
+
"check:shell": "node tools/check-shell.mjs",
|
|
36
|
+
"check:hooks": "node tools/check-hooks.mjs",
|
|
37
|
+
"hooks": "git config core.hooksPath hooks",
|
|
38
|
+
"test": "node --test \"test/*.test.mjs\""
|
|
39
|
+
},
|
|
40
|
+
"exports": {
|
|
41
|
+
"./host": "./host/docket-host.mjs",
|
|
42
|
+
"./server": "./server/docket.mjs",
|
|
43
|
+
"./time": "./server/time.mjs"
|
|
44
|
+
}
|
|
14
45
|
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* THE WORKER'S SIDE OF DOCKET: what an agent, or a script, sees of the events
|
|
3
|
+
* an application posted, and how it says what it did of each. One file, no
|
|
4
|
+
* dependency but time.mjs beside it.
|
|
5
|
+
*
|
|
6
|
+
* a command `docket`, `docket done ID` (bin/docket.mjs imports this file)
|
|
7
|
+
* MCP `node docket.mjs [--dir FOLDER]`: the same verbs as tools, over
|
|
8
|
+
* standard input and output (JSON-RPC 2.0, one message per line)
|
|
9
|
+
*
|
|
10
|
+
* An event waits until the worker says what it did of it: done, or failed and
|
|
11
|
+
* why. Nothing else takes it out. The worker may also set itself reminders
|
|
12
|
+
* (at a time, in a while, by a cron line), which the application's tick turns
|
|
13
|
+
* into events when they come due.
|
|
14
|
+
*
|
|
15
|
+
* THE FOLDER (docs/protocol.md):
|
|
16
|
+
* events.jsonl the application's: what happened
|
|
17
|
+
* acks.jsonl the worker's: what it did of each event
|
|
18
|
+
* plans.jsonl the worker's: the reminders it set, and took back
|
|
19
|
+
* plans-off.jsonl the application's: the reminders the person took back
|
|
20
|
+
*/
|
|
21
|
+
import { appendFileSync, readFileSync, mkdirSync, statSync, lstatSync, realpathSync } from 'node:fs';
|
|
22
|
+
import { dirname, join, resolve } from 'node:path';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
25
|
+
import { createInterface } from 'node:readline';
|
|
26
|
+
import { zoneOf, isZone, parseWhen, parseIn, parseCron, nextCron, lastCron, wall } from './time.mjs';
|
|
27
|
+
|
|
28
|
+
export const VERSION = '0.1.0-next.2';
|
|
29
|
+
export const FOLDER = '.docket';
|
|
30
|
+
export const TEXT_MAX = 500;
|
|
31
|
+
export const NOTE_MAX = 1000;
|
|
32
|
+
export const DATA_MAX = 4096;
|
|
33
|
+
export const ID_SHOWN = 8;
|
|
34
|
+
/* A reminder is at most this far away. */
|
|
35
|
+
export const AHEAD_MAX_MS = 366 * 86_400_000;
|
|
36
|
+
export const PLANS_MAX = 100;
|
|
37
|
+
export const LISTED_MAX = 50;
|
|
38
|
+
export const WAKE = 'You have something to handle: run "docket".';
|
|
39
|
+
|
|
40
|
+
const NOT_SHOWN = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F----]/gu;
|
|
41
|
+
export const oneLine = (text, max) => String(text ?? '').replace(/\r/g, '').replace(NOT_SHOWN, '').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
42
|
+
const parsed = (line) => { try { const j = JSON.parse(line); return j && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; } };
|
|
43
|
+
/* The lines of one file of the folder: never through a link; one that does not parse is skipped. */
|
|
44
|
+
export function lines(file) {
|
|
45
|
+
try { if (lstatSync(file).isSymbolicLink()) return []; return readFileSync(file, 'utf8').split('\n').filter(Boolean).map(parsed).filter(Boolean); } catch { return []; }
|
|
46
|
+
}
|
|
47
|
+
const isFolder = (path) => { try { return statSync(path).isDirectory(); } catch { return false; } };
|
|
48
|
+
|
|
49
|
+
/* The folder: `dir`, else $DOCKET_DIR, else the nearest .docket from `from` up. */
|
|
50
|
+
export function findFolder({ dir, env = process.env, from = process.cwd() } = {}) {
|
|
51
|
+
if (dir) return resolve(dir);
|
|
52
|
+
if (env.DOCKET_DIR) return resolve(env.DOCKET_DIR);
|
|
53
|
+
for (let at = resolve(from); ; at = dirname(at)) {
|
|
54
|
+
if (isFolder(join(at, FOLDER))) return join(at, FOLDER);
|
|
55
|
+
if (dirname(at) === at) return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/* The id of the event a plan gives for the time it is due: the same every time it is reckoned. */
|
|
60
|
+
export const eventIdOf = (plan, due) => createHash('sha256').update(`${plan}\n${due}`).digest('hex').slice(0, 32);
|
|
61
|
+
|
|
62
|
+
/* EVERYTHING IN THE FOLDER, as both sides see it. `now`: milliseconds. */
|
|
63
|
+
export function state(dir, { now = Date.now() } = {}) {
|
|
64
|
+
/* An event posted twice (two sides ticked at once) is one: the first. */
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
const events = lines(join(dir, 'events.jsonl')).filter((e) => typeof e.id === 'string' && e.id && !seen.has(e.id) && seen.add(e.id));
|
|
67
|
+
const acks = new Map();
|
|
68
|
+
for (const a of lines(join(dir, 'acks.jsonl'))) {
|
|
69
|
+
if ((a.kind === 'done' || a.kind === 'failed') && typeof a.event === 'string' && !acks.has(a.event)) acks.set(a.event, { kind: a.kind, note: oneLine(a.note, NOTE_MAX), at: String(a.at ?? '') });
|
|
70
|
+
}
|
|
71
|
+
const off = new Map();
|
|
72
|
+
for (const o of [...lines(join(dir, 'plans.jsonl')).filter((x) => x.kind === 'cancel').map((x) => ({ ...x, by: 'worker' })), ...lines(join(dir, 'plans-off.jsonl')).map((x) => ({ ...x, by: 'person' }))]) {
|
|
73
|
+
if (typeof o.plan === 'string' && !off.has(o.plan)) off.set(o.plan, { at: String(o.at ?? ''), by: o.by });
|
|
74
|
+
}
|
|
75
|
+
const plans = lines(join(dir, 'plans.jsonl')).filter((p) => p.kind === 'plan' && typeof p.id === 'string').map((p) => {
|
|
76
|
+
const tz = isZone(p.tz) ? p.tz : 'UTC';
|
|
77
|
+
const plan = { id: p.id, set: String(p.at ?? ''), text: oneLine(p.text, TEXT_MAX), tz, ...(off.has(p.id) ? { off: off.get(p.id) } : {}) };
|
|
78
|
+
if (typeof p.cron === 'string') { const c = parseCron(p.cron); if (!c) return null; plan.cron = p.cron; plan.next = off.has(p.id) ? null : nextCron(c, now - 1, tz); }
|
|
79
|
+
else { const due = Date.parse(p.due); if (!Number.isFinite(due)) return null; plan.due = due; plan.next = off.has(p.id) ? null : due; }
|
|
80
|
+
return plan;
|
|
81
|
+
}).filter(Boolean);
|
|
82
|
+
const all = events.map((e) => ({ id: e.id, at: String(e.at ?? ''), from: oneLine(e.from, 40), kind: oneLine(e.kind, 40), text: oneLine(e.text, TEXT_MAX),
|
|
83
|
+
...(e.data && typeof e.data === 'object' && !Array.isArray(e.data) ? { data: e.data } : {}), ...(typeof e.plan === 'string' ? { plan: e.plan, due: String(e.due ?? '') } : {}),
|
|
84
|
+
...(e.late ? { late: true } : {}), state: acks.get(e.id)?.kind ?? 'waiting', ...(acks.has(e.id) ? { ack: acks.get(e.id) } : {}) }));
|
|
85
|
+
return { events: all, plans, waiting: all.filter((e) => e.state === 'waiting').length };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/* An id given whole or by its first characters: the one it names, or why not. */
|
|
89
|
+
function pick(list, given, what) {
|
|
90
|
+
const id = oneLine(given, 100).replace(/^\[|\]$/g, '');
|
|
91
|
+
if (id.length < ID_SHOWN) throw new Error(`give the id of the ${what}, as "docket" shows it (${ID_SHOWN} characters at least)`);
|
|
92
|
+
const found = list.filter((x) => x.id.startsWith(id));
|
|
93
|
+
if (found.length === 0) throw new Error(`no ${what} has the id ${id}`);
|
|
94
|
+
if (found.length > 1) throw new Error(`several ${what}s start with ${id}: give more of it`);
|
|
95
|
+
return found[0];
|
|
96
|
+
}
|
|
97
|
+
const stamp = (t, tz) => { const w = wall(t, tz); const p = (n) => String(n).padStart(2, '0'); return `${w.year}-${p(w.month)}-${p(w.day)} ${p(w.hour)}:${p(w.minute)} (${tz})`; };
|
|
98
|
+
|
|
99
|
+
/* THE VERBS, on one folder. */
|
|
100
|
+
export function verbs(dir, { env = process.env, now = () => Date.now() } = {}) {
|
|
101
|
+
const write = (file, entry) => { mkdirSync(dir, { recursive: true }); const id = randomUUID(); appendFileSync(join(dir, file), `${JSON.stringify({ id, at: new Date(now()).toISOString(), ...entry })}\n`); return id; };
|
|
102
|
+
const ack = (kind, given, note) => {
|
|
103
|
+
const s = state(dir, { now: now() });
|
|
104
|
+
const event = pick(s.events, given, 'event');
|
|
105
|
+
if (event.state !== 'waiting') throw new Error(`that event was said ${event.state} already`);
|
|
106
|
+
write('acks.jsonl', { kind, event: event.id, note: oneLine(note, NOTE_MAX) });
|
|
107
|
+
return event;
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
list() {
|
|
111
|
+
const s = state(dir, { now: now() });
|
|
112
|
+
const waiting = s.events.filter((e) => e.state === 'waiting');
|
|
113
|
+
const plans = s.plans.filter((p) => !p.off && p.next !== null && !(p.due !== undefined && s.events.some((e) => e.plan === p.id)));
|
|
114
|
+
const said = [];
|
|
115
|
+
if (waiting.length === 0) said.push('Nothing waits.');
|
|
116
|
+
else {
|
|
117
|
+
said.push(`Waiting (${waiting.length}), oldest first; say what you did of each: docket done ID, or docket failed ID "why".`);
|
|
118
|
+
const tz = zoneOf(env, dir);
|
|
119
|
+
const when = (e) => (Number.isFinite(Date.parse(e.at)) ? stamp(Date.parse(e.at), tz).replace(/ \(.*\)$/, '') : '?');
|
|
120
|
+
for (const e of waiting.slice(0, LISTED_MAX)) said.push(` [${e.id.slice(0, ID_SHOWN)}] ${when(e)} ${e.from}/${e.kind}${e.late ? ' (late)' : ''}: ${e.text}${e.data ? `\n data: ${JSON.stringify(e.data).slice(0, 500)}` : ''}`);
|
|
121
|
+
if (waiting.length > LISTED_MAX) said.push(` ... and ${waiting.length - LISTED_MAX} more`);
|
|
122
|
+
}
|
|
123
|
+
if (plans.length) {
|
|
124
|
+
said.push(`Your reminders (${plans.length}); take one back with docket cancel ID:`);
|
|
125
|
+
for (const p of plans) said.push(` [${p.id.slice(0, ID_SHOWN)}] ${p.cron ? `"${p.cron}", next ${stamp(p.next, p.tz)}` : stamp(p.next, p.tz)}: ${p.text}`);
|
|
126
|
+
}
|
|
127
|
+
return said.join('\n');
|
|
128
|
+
},
|
|
129
|
+
done(id, note) { const e = ack('done', id, note); return `Done: ${e.text}`; },
|
|
130
|
+
failed(id, why) {
|
|
131
|
+
if (!oneLine(why, NOTE_MAX)) throw new Error('say why it could not be done');
|
|
132
|
+
const e = ack('failed', id, why);
|
|
133
|
+
return `Said failed: ${e.text}. The person is told.`;
|
|
134
|
+
},
|
|
135
|
+
/* { at } or { in } or { cron }, and the text the reminder will say. */
|
|
136
|
+
remind({ at, in: after, cron, text } = {}) {
|
|
137
|
+
const said = oneLine(text, TEXT_MAX);
|
|
138
|
+
if (!said) throw new Error('say what the reminder is for');
|
|
139
|
+
const given = [at, after, cron].filter((x) => x !== undefined && x !== null && x !== '').length;
|
|
140
|
+
if (given !== 1) throw new Error('give one of: --at "2026-10-23 09:00", --in 2h, --cron "0 9 * * 1"');
|
|
141
|
+
const s = state(dir, { now: now() });
|
|
142
|
+
if (s.plans.filter((p) => !p.off && p.next !== null).length >= PLANS_MAX) throw new Error(`${PLANS_MAX} reminders at most: take one back first`);
|
|
143
|
+
const tz = zoneOf(env, dir);
|
|
144
|
+
if (cron) {
|
|
145
|
+
const c = parseCron(cron);
|
|
146
|
+
if (!c) throw new Error('a cron line is five fields: minute hour day month weekday ("0 9 * * 1": Mondays at 9:00)');
|
|
147
|
+
const next = nextCron(c, now(), tz);
|
|
148
|
+
if (next === null) throw new Error('that cron line never comes within a year');
|
|
149
|
+
const id = write('plans.jsonl', { kind: 'plan', cron: String(cron).trim().split(/\s+/).join(' '), tz, text: said });
|
|
150
|
+
return `Set [${id.slice(0, ID_SHOWN)}]: "${String(cron).trim()}", next ${stamp(next, tz)}.`;
|
|
151
|
+
}
|
|
152
|
+
const due = at ? parseWhen(at, tz) : (() => { const ms = parseIn(after); return ms === null ? null : now() + ms; })();
|
|
153
|
+
if (due === null) throw new Error(at ? 'a time is "2026-10-23 09:00" (date, then hour)' : 'a delay is a number then m, h or d: 45m, 2h, 3d');
|
|
154
|
+
if (due <= now()) throw new Error(`that time has passed: it is ${stamp(now(), tz)} now`);
|
|
155
|
+
if (due - now() > AHEAD_MAX_MS) throw new Error('a reminder is at most a year away');
|
|
156
|
+
const id = write('plans.jsonl', { kind: 'plan', due: new Date(due).toISOString(), tz, text: said });
|
|
157
|
+
return `Set [${id.slice(0, ID_SHOWN)}]: ${stamp(due, tz)}.`;
|
|
158
|
+
},
|
|
159
|
+
cancel(id) {
|
|
160
|
+
const s = state(dir, { now: now() });
|
|
161
|
+
const plan = pick(s.plans, id, 'reminder');
|
|
162
|
+
if (plan.off) return 'It was taken back already.';
|
|
163
|
+
write('plans.jsonl', { kind: 'cancel', plan: plan.id });
|
|
164
|
+
return `Taken back: ${plan.text}`;
|
|
165
|
+
},
|
|
166
|
+
/* Posts an event for each reminder that came due and was not posted yet. */
|
|
167
|
+
tick() { return tick(dir, { now: now() }).length; },
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/* REMINDERS BECOME EVENTS: once per time each is due. Written to events.jsonl, as the application posts:
|
|
172
|
+
whichever side ticks, an event already there (by its id) is not posted again. */
|
|
173
|
+
export function tick(dir, { now = Date.now() } = {}) {
|
|
174
|
+
const s = state(dir, { now });
|
|
175
|
+
const have = new Set(s.events.map((e) => e.id));
|
|
176
|
+
const posted = [];
|
|
177
|
+
for (const p of s.plans) {
|
|
178
|
+
if (p.off) continue;
|
|
179
|
+
let due = null;
|
|
180
|
+
if (p.cron) {
|
|
181
|
+
const c = parseCron(p.cron);
|
|
182
|
+
const last = s.events.filter((e) => e.plan === p.id).map((e) => Date.parse(e.due)).filter(Number.isFinite).sort((a, b) => a - b).at(-1);
|
|
183
|
+
/* Since the last one posted, or since it was set: the last time it was due (one missed more than once is posted once). */
|
|
184
|
+
const since = last ?? (Date.parse(p.set) || now) - 1;
|
|
185
|
+
due = lastCron(c, since, now, p.tz);
|
|
186
|
+
} else if (p.due <= now) due = p.due;
|
|
187
|
+
if (due === null) continue;
|
|
188
|
+
const id = eventIdOf(p.id, new Date(due).toISOString());
|
|
189
|
+
if (have.has(id)) continue;
|
|
190
|
+
const event = { id, at: new Date(now).toISOString(), from: 'docket', kind: 'reminder', text: p.text, plan: p.id, due: new Date(due).toISOString(), ...(now - due > 5 * 60_000 ? { late: true } : {}) };
|
|
191
|
+
mkdirSync(dir, { recursive: true });
|
|
192
|
+
appendFileSync(join(dir, 'events.jsonl'), `${JSON.stringify(event)}\n`);
|
|
193
|
+
have.add(id); posted.push(event);
|
|
194
|
+
}
|
|
195
|
+
return posted;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/* ---- MCP ---- */
|
|
199
|
+
export const TOOLS = [
|
|
200
|
+
{ name: 'list', description: 'What waits for you, oldest first, each with its id; then the reminders you set. Say what you did of each event with done or failed.', inputSchema: { type: 'object', properties: {} } },
|
|
201
|
+
{ name: 'done', description: 'Say an event is handled.', inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'the id, or its first 8 characters' }, note: { type: 'string' } }, required: ['id'] } },
|
|
202
|
+
{ name: 'failed', description: 'Say an event could not be handled, and why: the person is told.', inputSchema: { type: 'object', properties: { id: { type: 'string' }, why: { type: 'string' } }, required: ['id', 'why'] } },
|
|
203
|
+
{ name: 'remind', description: 'Set yourself a reminder: at a time ("2026-10-23 09:00"), in a while ("2h", "3d"), or by a cron line ("0 9 * * 1"). It comes as an event when due.', inputSchema: { type: 'object', properties: { at: { type: 'string' }, in: { type: 'string' }, cron: { type: 'string' }, text: { type: 'string' } }, required: ['text'] } },
|
|
204
|
+
{ name: 'cancel', description: 'Take back a reminder you set.', inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } },
|
|
205
|
+
];
|
|
206
|
+
export function serve(dir, { input = process.stdin, output = process.stdout, env = process.env } = {}) {
|
|
207
|
+
const v = verbs(dir, { env });
|
|
208
|
+
const reply = (id, result, error) => output.write(`${JSON.stringify({ jsonrpc: '2.0', id, ...(error ? { error } : { result }) })}\n`);
|
|
209
|
+
const rl = createInterface({ input });
|
|
210
|
+
rl.on('line', (line) => {
|
|
211
|
+
const m = parsed(line);
|
|
212
|
+
if (!m || m.id === undefined) return;
|
|
213
|
+
if (m.method === 'initialize') return reply(m.id, { protocolVersion: m.params?.protocolVersion ?? '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'docket', version: VERSION } });
|
|
214
|
+
if (m.method === 'tools/list') return reply(m.id, { tools: TOOLS });
|
|
215
|
+
if (m.method === 'tools/call') {
|
|
216
|
+
const { name, arguments: a = {} } = m.params ?? {};
|
|
217
|
+
try {
|
|
218
|
+
const text = name === 'list' ? v.list() : name === 'done' ? v.done(a.id, a.note) : name === 'failed' ? v.failed(a.id, a.why)
|
|
219
|
+
: name === 'remind' ? v.remind({ at: a.at, in: a.in, cron: a.cron, text: a.text }) : name === 'cancel' ? v.cancel(a.id) : null;
|
|
220
|
+
if (text === null) return reply(m.id, undefined, { code: -32601, message: `no tool ${name}` });
|
|
221
|
+
return reply(m.id, { content: [{ type: 'text', text }] });
|
|
222
|
+
} catch (error) { return reply(m.id, { content: [{ type: 'text', text: `Not done: ${error.message}.` }], isError: true }); }
|
|
223
|
+
}
|
|
224
|
+
if (m.method === 'ping') return reply(m.id, {});
|
|
225
|
+
return reply(m.id, undefined, { code: -32601, message: `no method ${m.method}` });
|
|
226
|
+
});
|
|
227
|
+
return rl;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const HERE = fileURLToPath(import.meta.url);
|
|
231
|
+
const main = (() => { try { return realpathSync(process.argv[1] ?? '') === realpathSync(HERE); } catch { return false; } })();
|
|
232
|
+
if (main) {
|
|
233
|
+
const at = process.argv.indexOf('--dir');
|
|
234
|
+
const dir = findFolder({ dir: at >= 0 ? process.argv[at + 1] : undefined });
|
|
235
|
+
if (!dir) { process.stderr.write(`No ${FOLDER} folder: give --dir FOLDER.\n`); process.exit(2); }
|
|
236
|
+
serve(dir);
|
|
237
|
+
}
|
package/server/time.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { lstatSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/* TIME, for reminders: a wall-clock time in a time zone, a cron line, and when
|
|
5
|
+
* it is next due. No dependency: the time zones are the platform's (Intl).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/* The time zone a folder works in: $DOCKET_TZ, else what the application wrote in its `zone` file
|
|
9
|
+
(the person's: a machine often runs in UTC), else the machine's. */
|
|
10
|
+
export function zoneOf(env = process.env, dir) {
|
|
11
|
+
const given = String(env.DOCKET_TZ ?? '').trim();
|
|
12
|
+
if (given && isZone(given)) return given;
|
|
13
|
+
if (dir) {
|
|
14
|
+
try {
|
|
15
|
+
const file = join(dir, 'zone');
|
|
16
|
+
if (lstatSync(file).isFile() && lstatSync(file).size <= 64) { const written = readFileSync(file, 'utf8').trim(); if (isZone(written)) return written; }
|
|
17
|
+
} catch { /* none written */ }
|
|
18
|
+
}
|
|
19
|
+
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; }
|
|
20
|
+
}
|
|
21
|
+
export function isZone(tz) { try { new Intl.DateTimeFormat('en-US', { timeZone: tz }); return /^[A-Za-z0-9_+\-/]{1,64}$/.test(tz); } catch { return false; } }
|
|
22
|
+
|
|
23
|
+
const formats = new Map();
|
|
24
|
+
const format = (tz) => {
|
|
25
|
+
if (!formats.has(tz)) formats.set(tz, new Intl.DateTimeFormat('en-US', { timeZone: tz, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', weekday: 'short' }));
|
|
26
|
+
return formats.get(tz);
|
|
27
|
+
};
|
|
28
|
+
const DAYS = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
29
|
+
/* What a clock on the wall shows at `t` (milliseconds) in `tz`. */
|
|
30
|
+
export function wall(t, tz) {
|
|
31
|
+
const p = Object.fromEntries(format(tz).formatToParts(new Date(t)).map((x) => [x.type, x.value]));
|
|
32
|
+
return { year: +p.year, month: +p.month, day: +p.day, hour: +p.hour % 24, minute: +p.minute, weekday: DAYS[p.weekday] };
|
|
33
|
+
}
|
|
34
|
+
/* The moment a wall clock in `tz` shows that time; one near it, for a time a clock skips or shows twice. */
|
|
35
|
+
export function moment({ year, month, day, hour = 0, minute = 0 }, tz) {
|
|
36
|
+
const asUtc = Date.UTC(year, month - 1, day, hour, minute);
|
|
37
|
+
let t = asUtc;
|
|
38
|
+
for (let i = 0; i < 3; i++) {
|
|
39
|
+
const w = wall(t, tz);
|
|
40
|
+
const shown = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute);
|
|
41
|
+
if (shown === asUtc) return t;
|
|
42
|
+
t += asUtc - shown;
|
|
43
|
+
}
|
|
44
|
+
return t;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/* "2026-10-23 09:00", "2026-10-23T09:00", with seconds or an offset ("+02:00", "Z"), or a date alone (00:00). */
|
|
48
|
+
const WHEN = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?\s*(Z|[+-]\d{2}:?\d{2})?$/;
|
|
49
|
+
export function parseWhen(text, tz) {
|
|
50
|
+
const m = WHEN.exec(String(text ?? '').trim());
|
|
51
|
+
if (!m) return null;
|
|
52
|
+
const [, y, mo, d, h = '0', mi = '0', , off] = m;
|
|
53
|
+
const parts = { year: +y, month: +mo, day: +d, hour: +h, minute: +mi };
|
|
54
|
+
if (parts.month < 1 || parts.month > 12 || parts.day < 1 || parts.day > 31 || parts.hour > 23 || parts.minute > 59) return null;
|
|
55
|
+
if (new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDate() !== parts.day) return null;
|
|
56
|
+
if (off) {
|
|
57
|
+
const sign = off === 'Z' ? 0 : off[0] === '-' ? -1 : 1;
|
|
58
|
+
const [oh, om] = off === 'Z' ? [0, 0] : [+off.slice(1, 3), +off.slice(-2)];
|
|
59
|
+
return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute) - sign * (oh * 60 + om) * 60_000;
|
|
60
|
+
}
|
|
61
|
+
return moment(parts, tz);
|
|
62
|
+
}
|
|
63
|
+
/* "45m", "2h", "3d": from now. */
|
|
64
|
+
export function parseIn(text) {
|
|
65
|
+
const m = /^(\d{1,4})\s*(m|min|h|d)$/i.exec(String(text ?? '').trim());
|
|
66
|
+
if (!m) return null;
|
|
67
|
+
const unit = { m: 60_000, min: 60_000, h: 3_600_000, d: 86_400_000 }[m[2].toLowerCase()];
|
|
68
|
+
const ms = +m[1] * unit;
|
|
69
|
+
return ms > 0 ? ms : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/* A CRON LINE: minute hour day-of-month month day-of-week; *, lists, ranges, steps.
|
|
73
|
+
Day of the week 0-7 (0 and 7 Sunday). As cron does: when both days are given, either one matches. */
|
|
74
|
+
const FIELDS = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
|
|
75
|
+
export function parseCron(line) {
|
|
76
|
+
const parts = String(line ?? '').trim().split(/\s+/);
|
|
77
|
+
if (parts.length !== 5) return null;
|
|
78
|
+
const sets = [];
|
|
79
|
+
for (let i = 0; i < 5; i++) {
|
|
80
|
+
const [lo, hi] = FIELDS[i];
|
|
81
|
+
const set = new Set();
|
|
82
|
+
for (const piece of parts[i].split(',')) {
|
|
83
|
+
const m = /^(\*|(\d{1,2})(?:-(\d{1,2}))?)(?:\/(\d{1,2}))?$/.exec(piece);
|
|
84
|
+
if (!m) return null;
|
|
85
|
+
const step = m[4] === undefined ? 1 : +m[4];
|
|
86
|
+
if (step < 1) return null;
|
|
87
|
+
let from = lo; let to = hi;
|
|
88
|
+
if (m[1] !== '*') { from = +m[2]; to = m[3] === undefined ? (m[4] === undefined ? from : hi) : +m[3]; }
|
|
89
|
+
if (from < lo || to > hi || from > to) return null;
|
|
90
|
+
for (let v = from; v <= to; v += step) set.add(i === 4 && v === 7 ? 0 : v);
|
|
91
|
+
}
|
|
92
|
+
sets.push(set);
|
|
93
|
+
}
|
|
94
|
+
return { minutes: sets[0], hours: sets[1], days: sets[2], months: sets[3], weekdays: sets[4], anyDay: parts[2] === '*', anyWeekday: parts[4] === '*' };
|
|
95
|
+
}
|
|
96
|
+
const dayMatches = (c, w) => {
|
|
97
|
+
if (c.anyDay && c.anyWeekday) return true;
|
|
98
|
+
if (c.anyDay) return c.weekdays.has(w.weekday);
|
|
99
|
+
if (c.anyWeekday) return c.days.has(w.day);
|
|
100
|
+
return c.days.has(w.day) || c.weekdays.has(w.weekday);
|
|
101
|
+
};
|
|
102
|
+
export const cronMatches = (c, t, tz) => { const w = wall(t, tz); return c.minutes.has(w.minute) && c.hours.has(w.hour) && c.months.has(w.month) && dayMatches(c, w); };
|
|
103
|
+
/* The first minute strictly after `after` that the line matches, within a year and a day; null if none. */
|
|
104
|
+
export function nextCron(c, after, tz) {
|
|
105
|
+
let t = Math.floor(after / 60_000) * 60_000 + 60_000;
|
|
106
|
+
const end = after + 367 * 86_400_000;
|
|
107
|
+
while (t <= end) {
|
|
108
|
+
const w = wall(t, tz);
|
|
109
|
+
if (!c.months.has(w.month) || !dayMatches(c, w)) {
|
|
110
|
+
/* The next day, from its first minute (a day may be 23 or 25 hours long). */
|
|
111
|
+
const n = wall(t + (24 * 60 - w.hour * 60 - w.minute) * 60_000 + 3_600_000, tz);
|
|
112
|
+
const next = moment({ year: n.year, month: n.month, day: n.day }, tz);
|
|
113
|
+
t = next > t ? next : t + 3_600_000;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (!c.hours.has(w.hour)) { t += (60 - w.minute) * 60_000; continue; }
|
|
117
|
+
if (c.minutes.has(w.minute)) return t;
|
|
118
|
+
t += 60_000;
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
/* The last minute after `since` and at or before `upTo` that the line matches; null if none. */
|
|
123
|
+
export function lastCron(c, since, upTo, tz) {
|
|
124
|
+
let found = null;
|
|
125
|
+
for (let t = nextCron(c, since, tz); t !== null && t <= upTo; t = nextCron(c, t, tz)) found = t;
|
|
126
|
+
return found;
|
|
127
|
+
}
|
package/keep.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/* Clavarium Docket is not built yet: this version only keeps the name. It runs
|
|
3
|
-
* nothing else, installs nothing and reaches no network. */
|
|
4
|
-
process.stderr.write('Clavarium Docket is not built yet.\n'
|
|
5
|
-
+ 'Events an AI agent or a script sees and acknowledges: list, done, failed.\n'
|
|
6
|
-
+ 'https://github.com/clavarium/clavarium-docket\n');
|
|
7
|
-
process.exitCode = 1;
|