shipmates 0.0.0 → 0.2.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.
- package/LICENSE +661 -0
- package/dist/cli-run.d.ts +9 -0
- package/dist/cli-run.d.ts.map +1 -0
- package/dist/cli-run.js +237 -0
- package/dist/cli-run.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +11 -0
- package/dist/cli.js.map +1 -0
- package/dist/delivery.d.ts +37 -0
- package/dist/delivery.d.ts.map +1 -0
- package/dist/delivery.js +13 -0
- package/dist/delivery.js.map +1 -0
- package/dist/host.d.ts +132 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +66 -0
- package/dist/host.js.map +1 -0
- package/dist/ids.d.ts +3 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +6 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/liveness.d.ts +25 -0
- package/dist/liveness.d.ts.map +1 -0
- package/dist/liveness.js +75 -0
- package/dist/liveness.js.map +1 -0
- package/dist/quiet.d.ts +7 -0
- package/dist/quiet.d.ts.map +1 -0
- package/dist/quiet.js +19 -0
- package/dist/quiet.js.map +1 -0
- package/dist/shipmates.d.ts +401 -0
- package/dist/shipmates.d.ts.map +1 -0
- package/dist/shipmates.js +1112 -0
- package/dist/shipmates.js.map +1 -0
- package/dist/store.d.ts +19 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +236 -0
- package/dist/store.js.map +1 -0
- package/dist/tail.d.ts +27 -0
- package/dist/tail.d.ts.map +1 -0
- package/dist/tail.js +127 -0
- package/dist/tail.js.map +1 -0
- package/dist/types.d.ts +129 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +11 -0
- package/dist/types.js.map +1 -0
- package/dist/watch.d.ts +13 -0
- package/dist/watch.d.ts.map +1 -0
- package/dist/watch.js +30 -0
- package/dist/watch.js.map +1 -0
- package/package.json +50 -13
- package/src/cli-run.ts +263 -0
- package/src/cli.ts +11 -0
- package/src/delivery.ts +49 -0
- package/src/host.ts +161 -0
- package/src/ids.ts +6 -0
- package/src/index.ts +44 -0
- package/src/liveness.ts +86 -0
- package/src/quiet.ts +22 -0
- package/src/shipmates.ts +1634 -0
- package/src/store.ts +252 -0
- package/src/tail.ts +143 -0
- package/src/types.ts +138 -0
- package/src/watch.ts +32 -0
- package/.npm-publish.log +0 -0
- package/README.md +0 -5
package/src/store.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
5
|
+
|
|
6
|
+
export type DB = DatabaseSync;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Several pi processes, the CLI and wherever write this file at once. Without a
|
|
10
|
+
* busy timeout SQLite answers SQLITE_BUSY on the first contended write, which an
|
|
11
|
+
* agent would see as a failed send. Every write here is a few rows (well under a
|
|
12
|
+
* millisecond), so 5 s only ever matters when something is badly wrong.
|
|
13
|
+
*/
|
|
14
|
+
const BUSY_TIMEOUT_MS = 5_000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Forward migrations, applied in order and recorded in meta.schema_version.
|
|
18
|
+
* Unlike memonaut's index, this database is NOT a derived cache: a pending
|
|
19
|
+
* message or an open question exists nowhere else, so it is never dropped and
|
|
20
|
+
* rebuilt (ADR 0001). Append a migration; never edit one that shipped.
|
|
21
|
+
*/
|
|
22
|
+
export const MIGRATIONS: string[] = [
|
|
23
|
+
`
|
|
24
|
+
CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
25
|
+
|
|
26
|
+
-- One live (or recently live) session. Liveness is (pid, start_time, boot_id):
|
|
27
|
+
-- a crashed process stops being live at once, with no heartbeat.
|
|
28
|
+
CREATE TABLE presence(
|
|
29
|
+
session_file TEXT PRIMARY KEY,
|
|
30
|
+
session_id TEXT,
|
|
31
|
+
cwd TEXT,
|
|
32
|
+
branch TEXT,
|
|
33
|
+
state TEXT NOT NULL DEFAULT 'idle',
|
|
34
|
+
status TEXT,
|
|
35
|
+
refs TEXT,
|
|
36
|
+
waiting_on TEXT,
|
|
37
|
+
wake INTEGER NOT NULL DEFAULT 1,
|
|
38
|
+
settled_at INTEGER, -- last time it became idle or waiting-for-human
|
|
39
|
+
pid INTEGER NOT NULL,
|
|
40
|
+
start_time TEXT,
|
|
41
|
+
boot_id TEXT,
|
|
42
|
+
host TEXT,
|
|
43
|
+
registered_at INTEGER NOT NULL,
|
|
44
|
+
updated_at INTEGER NOT NULL
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
-- A role points at whichever session does a job (ADR 0004).
|
|
48
|
+
CREATE TABLE role(
|
|
49
|
+
role TEXT PRIMARY KEY,
|
|
50
|
+
session_file TEXT NOT NULL,
|
|
51
|
+
claimed_at INTEGER NOT NULL
|
|
52
|
+
);
|
|
53
|
+
CREATE INDEX role_session ON role(session_file);
|
|
54
|
+
|
|
55
|
+
CREATE TABLE message(
|
|
56
|
+
id TEXT PRIMARY KEY,
|
|
57
|
+
from_session TEXT,
|
|
58
|
+
from_label TEXT NOT NULL,
|
|
59
|
+
to_kind TEXT NOT NULL, -- 'session' | 'role'
|
|
60
|
+
to_target TEXT NOT NULL, -- a session file or a role
|
|
61
|
+
kind TEXT NOT NULL, -- 'tell' | 'ask' | 'answer' | 'notice'
|
|
62
|
+
question_id TEXT,
|
|
63
|
+
item_id TEXT,
|
|
64
|
+
text TEXT NOT NULL,
|
|
65
|
+
origin TEXT NOT NULL, -- 'human' | 'agent' | 'human-relayed'
|
|
66
|
+
relay TEXT, -- JSON: the human words carried, and where they come from
|
|
67
|
+
request_id TEXT,
|
|
68
|
+
urgent INTEGER NOT NULL DEFAULT 0,
|
|
69
|
+
state TEXT NOT NULL DEFAULT 'pending', -- pending | delivered | superseded | withdrawn
|
|
70
|
+
superseded_by TEXT,
|
|
71
|
+
claim_pid INTEGER,
|
|
72
|
+
claim_start TEXT,
|
|
73
|
+
claim_until INTEGER,
|
|
74
|
+
delivered_to TEXT,
|
|
75
|
+
created_at INTEGER NOT NULL,
|
|
76
|
+
finished_at INTEGER
|
|
77
|
+
);
|
|
78
|
+
CREATE UNIQUE INDEX message_request ON message(from_label, request_id) WHERE request_id IS NOT NULL;
|
|
79
|
+
CREATE INDEX message_pending ON message(state, to_kind, to_target);
|
|
80
|
+
|
|
81
|
+
CREATE TABLE question(
|
|
82
|
+
id TEXT PRIMARY KEY,
|
|
83
|
+
asker_session TEXT,
|
|
84
|
+
asker_label TEXT NOT NULL,
|
|
85
|
+
message_id TEXT NOT NULL,
|
|
86
|
+
to_kind TEXT NOT NULL,
|
|
87
|
+
to_target TEXT NOT NULL,
|
|
88
|
+
text TEXT NOT NULL,
|
|
89
|
+
state TEXT NOT NULL DEFAULT 'open', -- open | answered | withdrawn
|
|
90
|
+
answer TEXT,
|
|
91
|
+
answer_origin TEXT,
|
|
92
|
+
answer_relay TEXT,
|
|
93
|
+
answered_by TEXT,
|
|
94
|
+
created_at INTEGER NOT NULL,
|
|
95
|
+
finished_at INTEGER
|
|
96
|
+
);
|
|
97
|
+
CREATE INDEX question_open ON question(state);
|
|
98
|
+
|
|
99
|
+
-- An attention item: a question addressed to the human.
|
|
100
|
+
CREATE TABLE item(
|
|
101
|
+
id TEXT PRIMARY KEY,
|
|
102
|
+
session_file TEXT NOT NULL,
|
|
103
|
+
question TEXT NOT NULL,
|
|
104
|
+
options TEXT,
|
|
105
|
+
blocking INTEGER NOT NULL DEFAULT 0,
|
|
106
|
+
on_behalf_of TEXT,
|
|
107
|
+
state TEXT NOT NULL DEFAULT 'open', -- open | answered | withdrawn
|
|
108
|
+
answer TEXT,
|
|
109
|
+
answer_channel TEXT,
|
|
110
|
+
created_at INTEGER NOT NULL,
|
|
111
|
+
finished_at INTEGER
|
|
112
|
+
);
|
|
113
|
+
CREATE INDEX item_open ON item(state);
|
|
114
|
+
|
|
115
|
+
-- Turns a human really typed (ADR 0003): what human-relayed must point at.
|
|
116
|
+
CREATE TABLE human_turn(
|
|
117
|
+
id TEXT PRIMARY KEY,
|
|
118
|
+
session_file TEXT NOT NULL,
|
|
119
|
+
text TEXT NOT NULL,
|
|
120
|
+
channel TEXT NOT NULL,
|
|
121
|
+
at INTEGER NOT NULL
|
|
122
|
+
);
|
|
123
|
+
CREATE INDEX human_turn_session ON human_turn(session_file, at);
|
|
124
|
+
`,
|
|
125
|
+
// 2: ownership, archive markers and stop requests (D23, D24, D30).
|
|
126
|
+
`
|
|
127
|
+
-- Who spawned a session (D23). A row is created when the spawn starts, before
|
|
128
|
+
-- the new session exists; session_file is set once, when it does, and the owner
|
|
129
|
+
-- never changes. It outlives presence and is pruned only as D25 says.
|
|
130
|
+
CREATE TABLE ownership(
|
|
131
|
+
id TEXT PRIMARY KEY, -- the spawn, sp_...
|
|
132
|
+
session_file TEXT UNIQUE, -- NULL until the new session exists
|
|
133
|
+
owner TEXT NOT NULL,
|
|
134
|
+
folder TEXT NOT NULL,
|
|
135
|
+
role TEXT,
|
|
136
|
+
via TEXT NOT NULL, -- 'host' | 'zellij' | 'headless' | 'recorded'
|
|
137
|
+
detail TEXT, -- JSON: fork, worktree, host
|
|
138
|
+
prompt TEXT, -- the first prompt, delivered once at bind
|
|
139
|
+
created_at INTEGER NOT NULL,
|
|
140
|
+
bound_at INTEGER,
|
|
141
|
+
wake_until INTEGER -- a headless wake in flight (D29)
|
|
142
|
+
);
|
|
143
|
+
CREATE INDEX ownership_owner ON ownership(owner);
|
|
144
|
+
|
|
145
|
+
-- A host archived or deleted a session and its owned ones (D24).
|
|
146
|
+
CREATE TABLE archive(
|
|
147
|
+
session_file TEXT PRIMARY KEY,
|
|
148
|
+
kind TEXT NOT NULL, -- 'archived' | 'deleted'
|
|
149
|
+
batch TEXT NOT NULL,
|
|
150
|
+
by_label TEXT NOT NULL,
|
|
151
|
+
at INTEGER NOT NULL
|
|
152
|
+
);
|
|
153
|
+
CREATE INDEX archive_batch ON archive(batch);
|
|
154
|
+
|
|
155
|
+
-- Stop the current turn of a session (D30): its own extension acts on it.
|
|
156
|
+
CREATE TABLE stop_request(
|
|
157
|
+
id TEXT PRIMARY KEY,
|
|
158
|
+
session_file TEXT NOT NULL,
|
|
159
|
+
by_session TEXT,
|
|
160
|
+
by_label TEXT NOT NULL,
|
|
161
|
+
at INTEGER NOT NULL,
|
|
162
|
+
handled_at INTEGER,
|
|
163
|
+
outcome TEXT -- 'stopped' | 'not-running'
|
|
164
|
+
);
|
|
165
|
+
CREATE INDEX stop_open ON stop_request(session_file, handled_at);
|
|
166
|
+
`,
|
|
167
|
+
];
|
|
168
|
+
|
|
169
|
+
export function defaultStateDir(): string {
|
|
170
|
+
if (process.env.SHIPMATES_STATE_DIR) return process.env.SHIPMATES_STATE_DIR;
|
|
171
|
+
const base =
|
|
172
|
+
process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state');
|
|
173
|
+
return path.join(base, 'shipmates');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function openDb(stateDir: string): DB {
|
|
177
|
+
fs.mkdirSync(stateDir, {recursive: true});
|
|
178
|
+
const db = new DatabaseSync(path.join(stateDir, 'shipmates.db'));
|
|
179
|
+
db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
|
|
180
|
+
// Measured (test/multiprocess.test.ts): when several processes open a NEW
|
|
181
|
+
// database together, the switch to WAL and the first migration can answer
|
|
182
|
+
// SQLITE_BUSY at once, without the busy handler, while another connection is
|
|
183
|
+
// changing the journal mode. It only happens during setup, so setup alone is
|
|
184
|
+
// retried; steady-state writes rely on busy_timeout.
|
|
185
|
+
retryBusy(() => {
|
|
186
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
187
|
+
db.exec('PRAGMA synchronous = NORMAL');
|
|
188
|
+
migrate(db);
|
|
189
|
+
});
|
|
190
|
+
return db;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function retryBusy(fn: () => void): void {
|
|
194
|
+
const deadline = Date.now() + BUSY_TIMEOUT_MS;
|
|
195
|
+
for (let attempt = 0; ; attempt++) {
|
|
196
|
+
try {
|
|
197
|
+
return fn();
|
|
198
|
+
} catch (e) {
|
|
199
|
+
if ((e as {errcode?: number}).errcode !== 5 || Date.now() > deadline)
|
|
200
|
+
throw e;
|
|
201
|
+
Atomics.wait(
|
|
202
|
+
new Int32Array(new SharedArrayBuffer(4)),
|
|
203
|
+
0,
|
|
204
|
+
0,
|
|
205
|
+
5 + Math.random() * 20 * Math.min(attempt + 1, 5),
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function migrate(db: DB): void {
|
|
212
|
+
write(db, () => {
|
|
213
|
+
const hasMeta = db
|
|
214
|
+
.prepare(
|
|
215
|
+
`SELECT 1 AS x FROM sqlite_master WHERE type='table' AND name='meta'`,
|
|
216
|
+
)
|
|
217
|
+
.get();
|
|
218
|
+
let version = 0;
|
|
219
|
+
if (hasMeta) {
|
|
220
|
+
const row = db
|
|
221
|
+
.prepare(`SELECT value FROM meta WHERE key='schema_version'`)
|
|
222
|
+
.get() as {value: string} | undefined;
|
|
223
|
+
version = row ? Number(row.value) : 0;
|
|
224
|
+
}
|
|
225
|
+
if (version > MIGRATIONS.length)
|
|
226
|
+
throw new Error(
|
|
227
|
+
`shipmates: database schema ${version} is newer than this version of shipmates (${MIGRATIONS.length}); upgrade shipmates`,
|
|
228
|
+
);
|
|
229
|
+
for (let v = version; v < MIGRATIONS.length; v++) db.exec(MIGRATIONS[v]);
|
|
230
|
+
db.prepare(
|
|
231
|
+
`INSERT OR REPLACE INTO meta(key, value) VALUES('schema_version', ?)`,
|
|
232
|
+
).run(String(MIGRATIONS.length));
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Run fn in a write transaction. BEGIN IMMEDIATE takes the write lock up front:
|
|
238
|
+
* a deferred transaction that reads then writes can fail with SQLITE_BUSY on the
|
|
239
|
+
* lock upgrade without ever honouring busy_timeout, which is exactly the case
|
|
240
|
+
* several concurrent pi processes would hit.
|
|
241
|
+
*/
|
|
242
|
+
export function write<T>(db: DB, fn: () => T): T {
|
|
243
|
+
db.exec('BEGIN IMMEDIATE');
|
|
244
|
+
try {
|
|
245
|
+
const out = fn();
|
|
246
|
+
db.exec('COMMIT');
|
|
247
|
+
return out;
|
|
248
|
+
} catch (e) {
|
|
249
|
+
db.exec('ROLLBACK');
|
|
250
|
+
throw e;
|
|
251
|
+
}
|
|
252
|
+
}
|
package/src/tail.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
|
|
3
|
+
export interface TailMessage {
|
|
4
|
+
role: 'user' | 'assistant';
|
|
5
|
+
text: string;
|
|
6
|
+
timestamp: string | null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface Tail {
|
|
10
|
+
messages: TailMessage[];
|
|
11
|
+
/** True when a message was cut, or the total cap or the scan bound dropped older ones. */
|
|
12
|
+
truncated: boolean;
|
|
13
|
+
scannedBytes: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface TailOptions {
|
|
17
|
+
messages?: number;
|
|
18
|
+
perMessageBytes?: number;
|
|
19
|
+
totalBytes?: number;
|
|
20
|
+
/** Stop scanning backwards after this many bytes (tool results can be most of a file). */
|
|
21
|
+
maxScanBytes?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const CHUNK = 64 * 1024;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The last user and assistant texts of a pi transcript, read BACKWARDS from the
|
|
28
|
+
* end in chunks, never materialising the file: transcripts reach 62 MB (wherever
|
|
29
|
+
* CONTEXT.md, "Reading transcripts"), and most of their bytes are tool results we
|
|
30
|
+
* skip. Lines are recognised by their head before being parsed, so a 500 KB tool
|
|
31
|
+
* result is never turned into an object.
|
|
32
|
+
*/
|
|
33
|
+
export function readTail(file: string, opts: TailOptions = {}): Tail {
|
|
34
|
+
const want = opts.messages ?? 6;
|
|
35
|
+
const perMessage = opts.perMessageBytes ?? 2048;
|
|
36
|
+
const total = opts.totalBytes ?? 12 * 1024;
|
|
37
|
+
const maxScan = opts.maxScanBytes ?? 8 * 1024 * 1024;
|
|
38
|
+
let fd: number;
|
|
39
|
+
try {
|
|
40
|
+
fd = fs.openSync(file, 'r');
|
|
41
|
+
} catch {
|
|
42
|
+
return {messages: [], truncated: false, scannedBytes: 0};
|
|
43
|
+
}
|
|
44
|
+
const found: TailMessage[] = [];
|
|
45
|
+
let truncated = false;
|
|
46
|
+
let scanned = 0;
|
|
47
|
+
try {
|
|
48
|
+
let pos = fs.fstatSync(fd).size;
|
|
49
|
+
let carry: Buffer = Buffer.alloc(0);
|
|
50
|
+
while (pos > 0 && found.length < want) {
|
|
51
|
+
if (scanned >= maxScan) {
|
|
52
|
+
truncated = true;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
const len = Math.min(CHUNK, pos);
|
|
56
|
+
pos -= len;
|
|
57
|
+
const buf = Buffer.alloc(len);
|
|
58
|
+
fs.readSync(fd, buf, 0, len, pos);
|
|
59
|
+
scanned += len;
|
|
60
|
+
let data = Buffer.concat([buf, carry]);
|
|
61
|
+
// Every complete line is after the first newline (or the file start).
|
|
62
|
+
let end = data.length;
|
|
63
|
+
for (let i = data.length - 1; i >= -1 && found.length < want; i--) {
|
|
64
|
+
if (i >= 0 && data[i] !== 0x0a) continue;
|
|
65
|
+
if (i < 0 && pos > 0) break; // the first line of this chunk may be partial
|
|
66
|
+
const lineBuf = data.subarray(i + 1, end);
|
|
67
|
+
end = i;
|
|
68
|
+
const m = parseLine(lineBuf);
|
|
69
|
+
if (m) found.push(m);
|
|
70
|
+
}
|
|
71
|
+
carry = data.subarray(0, Math.max(end, 0));
|
|
72
|
+
if (carry.length > maxScan) {
|
|
73
|
+
truncated = true;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} finally {
|
|
78
|
+
fs.closeSync(fd);
|
|
79
|
+
}
|
|
80
|
+
const out: TailMessage[] = [];
|
|
81
|
+
let used = 0;
|
|
82
|
+
for (const m of found) {
|
|
83
|
+
let text = m.text;
|
|
84
|
+
if (Buffer.byteLength(text) > perMessage) {
|
|
85
|
+
text = cut(text, perMessage) + '...';
|
|
86
|
+
truncated = true;
|
|
87
|
+
}
|
|
88
|
+
const size = Buffer.byteLength(text);
|
|
89
|
+
if (used + size > total) {
|
|
90
|
+
truncated = true;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
used += size;
|
|
94
|
+
out.push({...m, text});
|
|
95
|
+
}
|
|
96
|
+
return {messages: out.reverse(), truncated, scannedBytes: scanned};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const HEAD = 512;
|
|
100
|
+
|
|
101
|
+
function parseLine(line: Buffer): TailMessage | null {
|
|
102
|
+
if (line.length === 0) return null;
|
|
103
|
+
// pi writes `type` and the fixed keys before `message`, so the first
|
|
104
|
+
// occurrence of the role marker in the head is the structural one.
|
|
105
|
+
const head = line.subarray(0, HEAD).toString('utf8');
|
|
106
|
+
if (!head.startsWith('{"type":"message"')) return null;
|
|
107
|
+
const roleMatch = /"message":\{"role":"(\w+)"/.exec(head);
|
|
108
|
+
if (!roleMatch || (roleMatch[1] !== 'user' && roleMatch[1] !== 'assistant'))
|
|
109
|
+
return null;
|
|
110
|
+
let entry: {timestamp?: string; message?: {role: string; content: unknown}};
|
|
111
|
+
try {
|
|
112
|
+
entry = JSON.parse(line.toString('utf8'));
|
|
113
|
+
} catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
const content = entry.message?.content;
|
|
117
|
+
let text = '';
|
|
118
|
+
if (typeof content === 'string') text = content;
|
|
119
|
+
else if (Array.isArray(content))
|
|
120
|
+
text = content
|
|
121
|
+
.filter(
|
|
122
|
+
(b): b is {type: 'text'; text: string} =>
|
|
123
|
+
!!b && (b as {type?: string}).type === 'text',
|
|
124
|
+
)
|
|
125
|
+
.map((b) => b.text)
|
|
126
|
+
.join('\n');
|
|
127
|
+
text = text.trim();
|
|
128
|
+
if (!text) return null;
|
|
129
|
+
return {
|
|
130
|
+
role: roleMatch[1] as 'user' | 'assistant',
|
|
131
|
+
text,
|
|
132
|
+
timestamp: entry.timestamp ?? null,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function cut(s: string, bytes: number): string {
|
|
137
|
+
const b = Buffer.from(s);
|
|
138
|
+
if (b.length <= bytes) return s;
|
|
139
|
+
// Do not split a multi-byte character.
|
|
140
|
+
let end = bytes;
|
|
141
|
+
while (end > 0 && (b[end] & 0xc0) === 0x80) end--;
|
|
142
|
+
return b.subarray(0, end).toString('utf8');
|
|
143
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export type SessionState =
|
|
2
|
+
'running' | 'waiting-for-human' | 'waiting-for-session' | 'idle';
|
|
3
|
+
export type Origin = 'human' | 'agent' | 'human-relayed';
|
|
4
|
+
/** `spawn`: the first prompt of a session another session spawned, from its owner (D28). */
|
|
5
|
+
export type MessageKind = 'tell' | 'ask' | 'answer' | 'notice' | 'spawn';
|
|
6
|
+
export type MessageState = 'pending' | 'delivered' | 'superseded' | 'withdrawn';
|
|
7
|
+
|
|
8
|
+
export interface Presence {
|
|
9
|
+
sessionFile: string;
|
|
10
|
+
sessionId: string | null;
|
|
11
|
+
cwd: string | null;
|
|
12
|
+
branch: string | null;
|
|
13
|
+
roles: string[];
|
|
14
|
+
state: SessionState;
|
|
15
|
+
status: string | null;
|
|
16
|
+
refs: string[];
|
|
17
|
+
waitingOn: string | null;
|
|
18
|
+
/** Whether a message may start a turn here (`/shipmates wake off` clears it). */
|
|
19
|
+
wake: boolean;
|
|
20
|
+
/** False once the process that registered it is gone. */
|
|
21
|
+
live: boolean;
|
|
22
|
+
pid: number;
|
|
23
|
+
updatedAt: number;
|
|
24
|
+
/** Last time it became idle or waiting for the human. */
|
|
25
|
+
settledAt: number | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The human words a human-relayed message carries, verbatim, and where they were said. */
|
|
29
|
+
export interface Relay {
|
|
30
|
+
text: string;
|
|
31
|
+
channel: string;
|
|
32
|
+
session: string | null;
|
|
33
|
+
turnId?: string;
|
|
34
|
+
itemId?: string;
|
|
35
|
+
at: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface Message {
|
|
39
|
+
id: string;
|
|
40
|
+
from: string | null;
|
|
41
|
+
fromLabel: string;
|
|
42
|
+
to: {kind: 'session' | 'role'; target: string};
|
|
43
|
+
kind: MessageKind;
|
|
44
|
+
questionId: string | null;
|
|
45
|
+
itemId: string | null;
|
|
46
|
+
text: string;
|
|
47
|
+
origin: Origin;
|
|
48
|
+
relay: Relay | null;
|
|
49
|
+
urgent: boolean;
|
|
50
|
+
state: MessageState;
|
|
51
|
+
supersededBy: string | null;
|
|
52
|
+
deliveredTo: string | null;
|
|
53
|
+
createdAt: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface Question {
|
|
57
|
+
id: string;
|
|
58
|
+
asker: string | null;
|
|
59
|
+
askerLabel: string;
|
|
60
|
+
messageId: string;
|
|
61
|
+
to: {kind: 'session' | 'role'; target: string};
|
|
62
|
+
text: string;
|
|
63
|
+
state: 'open' | 'answered' | 'withdrawn';
|
|
64
|
+
answer: string | null;
|
|
65
|
+
answerOrigin: Origin | null;
|
|
66
|
+
answerRelay: Relay | null;
|
|
67
|
+
answeredBy: string | null;
|
|
68
|
+
createdAt: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface AttentionItem {
|
|
72
|
+
id: string;
|
|
73
|
+
session: string;
|
|
74
|
+
question: string;
|
|
75
|
+
options: string[] | null;
|
|
76
|
+
blocking: boolean;
|
|
77
|
+
onBehalfOf: string[];
|
|
78
|
+
state: 'open' | 'answered' | 'withdrawn';
|
|
79
|
+
answer: string | null;
|
|
80
|
+
answerChannel: string | null;
|
|
81
|
+
createdAt: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** How a session came to be owned (D23): through a host, or the terminal default (D19). */
|
|
85
|
+
export type SpawnVia = 'host' | 'zellij' | 'headless' | 'recorded';
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Who spawned a session (D23). Set once, when the spawned session exists, and
|
|
89
|
+
* never changed; it outlives presence, so a child that is not live is still owned.
|
|
90
|
+
*/
|
|
91
|
+
export interface Ownership {
|
|
92
|
+
/** The spawn (`sp_...`), known before the session exists. */
|
|
93
|
+
id: string;
|
|
94
|
+
/** Null until the new session exists and is bound to this spawn. */
|
|
95
|
+
session: string | null;
|
|
96
|
+
owner: string;
|
|
97
|
+
folder: string;
|
|
98
|
+
role: string | null;
|
|
99
|
+
via: SpawnVia;
|
|
100
|
+
/** How it was spawned beyond `via`: fork, worktree, host name. */
|
|
101
|
+
detail: Record<string, unknown>;
|
|
102
|
+
createdAt: number;
|
|
103
|
+
boundAt: number | null;
|
|
104
|
+
archived: ArchiveMark | null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A host archived or deleted a session (D24); undoable until `undoUntil`. */
|
|
108
|
+
export interface ArchiveMark {
|
|
109
|
+
session: string;
|
|
110
|
+
kind: 'archived' | 'deleted';
|
|
111
|
+
/** One archive call and its whole cascade; the unit of undo. */
|
|
112
|
+
batch: string;
|
|
113
|
+
by: string;
|
|
114
|
+
at: number;
|
|
115
|
+
undoUntil: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A request to stop a session's current turn (D30). */
|
|
119
|
+
export interface StopRequest {
|
|
120
|
+
id: string;
|
|
121
|
+
session: string;
|
|
122
|
+
by: string | null;
|
|
123
|
+
byLabel: string;
|
|
124
|
+
at: number;
|
|
125
|
+
handledAt: number | null;
|
|
126
|
+
outcome: 'stopped' | 'not-running' | null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export class ShipmatesError extends Error {
|
|
130
|
+
constructor(
|
|
131
|
+
message: string,
|
|
132
|
+
readonly code: string,
|
|
133
|
+
readonly details?: unknown,
|
|
134
|
+
) {
|
|
135
|
+
super(message);
|
|
136
|
+
this.name = 'ShipmatesError';
|
|
137
|
+
}
|
|
138
|
+
}
|
package/src/watch.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type {Shipmates} from './shipmates.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Call `onChange` whenever anything in the database changed (D6). It polls
|
|
5
|
+
* `PRAGMA data_version`, which changes only when another connection commits and
|
|
6
|
+
* reads no table pages, plus this connection's own write count. One watcher per
|
|
7
|
+
* process is enough; the timer is unref'd so it never keeps a process alive.
|
|
8
|
+
*/
|
|
9
|
+
export function watchChanges(
|
|
10
|
+
shipmates: Shipmates,
|
|
11
|
+
onChange: () => void,
|
|
12
|
+
opts: {intervalMs?: number} = {},
|
|
13
|
+
): {stop(): void} {
|
|
14
|
+
let last = shipmates.changeToken();
|
|
15
|
+
const timer = setInterval(() => {
|
|
16
|
+
let token: string;
|
|
17
|
+
try {
|
|
18
|
+
token = shipmates.changeToken();
|
|
19
|
+
} catch {
|
|
20
|
+
return; // closed underneath us; stop() is on its way
|
|
21
|
+
}
|
|
22
|
+
if (token === last) return;
|
|
23
|
+
last = token;
|
|
24
|
+
try {
|
|
25
|
+
onChange();
|
|
26
|
+
} catch (e) {
|
|
27
|
+
console.error('[shipmates] change handler failed:', e);
|
|
28
|
+
}
|
|
29
|
+
}, opts.intervalMs ?? 1000);
|
|
30
|
+
timer.unref();
|
|
31
|
+
return {stop: () => clearInterval(timer)};
|
|
32
|
+
}
|
package/.npm-publish.log
DELETED
|
File without changes
|