shipmates 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +661 -0
  2. package/dist/cli-run.d.ts +9 -0
  3. package/dist/cli-run.d.ts.map +1 -0
  4. package/dist/cli-run.js +237 -0
  5. package/dist/cli-run.js.map +1 -0
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +11 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/delivery.d.ts +37 -0
  11. package/dist/delivery.d.ts.map +1 -0
  12. package/dist/delivery.js +13 -0
  13. package/dist/delivery.js.map +1 -0
  14. package/dist/host.d.ts +132 -0
  15. package/dist/host.d.ts.map +1 -0
  16. package/dist/host.js +66 -0
  17. package/dist/host.js.map +1 -0
  18. package/dist/ids.d.ts +3 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +6 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +17 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +11 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/liveness.d.ts +25 -0
  27. package/dist/liveness.d.ts.map +1 -0
  28. package/dist/liveness.js +75 -0
  29. package/dist/liveness.js.map +1 -0
  30. package/dist/quiet.d.ts +7 -0
  31. package/dist/quiet.d.ts.map +1 -0
  32. package/dist/quiet.js +19 -0
  33. package/dist/quiet.js.map +1 -0
  34. package/dist/shipmates.d.ts +440 -0
  35. package/dist/shipmates.d.ts.map +1 -0
  36. package/dist/shipmates.js +1177 -0
  37. package/dist/shipmates.js.map +1 -0
  38. package/dist/store.d.ts +19 -0
  39. package/dist/store.d.ts.map +1 -0
  40. package/dist/store.js +236 -0
  41. package/dist/store.js.map +1 -0
  42. package/dist/tail.d.ts +27 -0
  43. package/dist/tail.d.ts.map +1 -0
  44. package/dist/tail.js +127 -0
  45. package/dist/tail.js.map +1 -0
  46. package/dist/types.d.ts +141 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +16 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/watch.d.ts +13 -0
  51. package/dist/watch.d.ts.map +1 -0
  52. package/dist/watch.js +30 -0
  53. package/dist/watch.js.map +1 -0
  54. package/package.json +50 -13
  55. package/src/cli-run.ts +263 -0
  56. package/src/cli.ts +11 -0
  57. package/src/delivery.ts +49 -0
  58. package/src/host.ts +161 -0
  59. package/src/ids.ts +6 -0
  60. package/src/index.ts +44 -0
  61. package/src/liveness.ts +86 -0
  62. package/src/quiet.ts +22 -0
  63. package/src/shipmates.ts +1745 -0
  64. package/src/store.ts +252 -0
  65. package/src/tail.ts +143 -0
  66. package/src/types.ts +151 -0
  67. package/src/watch.ts +32 -0
  68. package/.npm-publish.log +0 -0
  69. package/README.md +0 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GACvB,SAAS,GAAG,mBAAmB,GAAG,qBAAqB,GAAG,MAAM,CAAC;AAClE,MAAM,MAAM,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,eAAe,CAAC;AACzD,4FAA4F;AAC5F,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAC;AACzE,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,WAAW,GAAG,YAAY,GAAG,WAAW,CAAC;AAEhF,MAAM,WAAW,QAAQ;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,EAAE,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AAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,EAAE,QAAQ,CAAC;IACd,kEAAkE;IAClE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;CAC7B;AAED,8EAA8E;AAC9E,MAAM,WAAW,WAAW;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,UAAU,GAAG,SAAS,CAAC;IAC7B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;CAClB;AAED,wDAAwD;AACxD,MAAM,WAAW,WAAW;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,OAAO,EAAE,SAAS,GAAG,aAAa,GAAG,IAAI,CAAC;CAC1C;AAED,qBAAa,cAAe,SAAQ,KAAK;IAGvC,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO;gBAF1B,OAAO,EAAE,MAAM,EACN,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,OAAO,YAAA;CAK3B"}
package/dist/types.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The `answerChannel` of an item the human answered by replying in the asking
3
+ * session's own conversation rather than in an inbox (D39).
4
+ */
5
+ export const SESSION_ANSWER_CHANNEL = 'session';
6
+ export class ShipmatesError extends Error {
7
+ code;
8
+ details;
9
+ constructor(message, code, details) {
10
+ super(message);
11
+ this.code = code;
12
+ this.details = details;
13
+ this.name = 'ShipmatesError';
14
+ }
15
+ }
16
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAsEA;;;GAGG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AAmEhD,MAAM,OAAO,cAAe,SAAQ,KAAK;IAG9B;IACA;IAHV,YACC,OAAe,EACN,IAAY,EACZ,OAAiB;QAE1B,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,SAAI,GAAJ,IAAI,CAAQ;QACZ,YAAO,GAAP,OAAO,CAAU;QAG1B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC9B,CAAC;CACD"}
@@ -0,0 +1,13 @@
1
+ import type { Shipmates } from './shipmates.js';
2
+ /**
3
+ * Call `onChange` whenever anything in the database changed (D6). It polls
4
+ * `PRAGMA data_version`, which changes only when another connection commits and
5
+ * reads no table pages, plus this connection's own write count. One watcher per
6
+ * process is enough; the timer is unref'd so it never keeps a process alive.
7
+ */
8
+ export declare function watchChanges(shipmates: Shipmates, onChange: () => void, opts?: {
9
+ intervalMs?: number;
10
+ }): {
11
+ stop(): void;
12
+ };
13
+ //# sourceMappingURL=watch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../src/watch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AAE9C;;;;;GAKG;AACH,wBAAgB,YAAY,CAC3B,SAAS,EAAE,SAAS,EACpB,QAAQ,EAAE,MAAM,IAAI,EACpB,IAAI,GAAE;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAM,GAC9B;IAAC,IAAI,IAAI,IAAI,CAAA;CAAC,CAmBhB"}
package/dist/watch.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Call `onChange` whenever anything in the database changed (D6). It polls
3
+ * `PRAGMA data_version`, which changes only when another connection commits and
4
+ * reads no table pages, plus this connection's own write count. One watcher per
5
+ * process is enough; the timer is unref'd so it never keeps a process alive.
6
+ */
7
+ export function watchChanges(shipmates, onChange, opts = {}) {
8
+ let last = shipmates.changeToken();
9
+ const timer = setInterval(() => {
10
+ let token;
11
+ try {
12
+ token = shipmates.changeToken();
13
+ }
14
+ catch {
15
+ return; // closed underneath us; stop() is on its way
16
+ }
17
+ if (token === last)
18
+ return;
19
+ last = token;
20
+ try {
21
+ onChange();
22
+ }
23
+ catch (e) {
24
+ console.error('[shipmates] change handler failed:', e);
25
+ }
26
+ }, opts.intervalMs ?? 1000);
27
+ timer.unref();
28
+ return { stop: () => clearInterval(timer) };
29
+ }
30
+ //# sourceMappingURL=watch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watch.js","sourceRoot":"","sources":["../src/watch.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAC3B,SAAoB,EACpB,QAAoB,EACpB,OAA8B,EAAE;IAEhC,IAAI,IAAI,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;IACnC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC9B,IAAI,KAAa,CAAC;QAClB,IAAI,CAAC;YACJ,KAAK,GAAG,SAAS,CAAC,WAAW,EAAE,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,CAAC,6CAA6C;QACtD,CAAC;QACD,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO;QAC3B,IAAI,GAAG,KAAK,CAAC;QACb,IAAI,CAAC;YACJ,QAAQ,EAAE,CAAC;QACZ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,CAAC,CAAC,CAAC;QACxD,CAAC;IACF,CAAC,EAAE,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;IACd,OAAO,EAAC,IAAI,EAAE,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,EAAC,CAAC;AAC3C,CAAC"}
package/package.json CHANGED
@@ -1,14 +1,51 @@
1
1
  {
2
- "name": "shipmates",
3
- "version": "0.0.0",
4
- "description": "Name reservation for shipmates. A real release follows; this 0.0.0 holds the name and contains no code.",
5
- "license": "AGPL-3.0-only",
6
- "private": false,
7
- "publishConfig": {
8
- "access": "public"
9
- },
10
- "repository": {
11
- "type": "git",
12
- "url": "https://github.com/wighawag/shipmates"
13
- }
14
- }
2
+ "name": "shipmates",
3
+ "version": "0.3.0",
4
+ "description": "Sessions that know about each other: presence, roles, messages with provenance, questions and an attention inbox for agent sessions (pi and friends), on SQLite",
5
+ "license": "AGPL-3.0-only",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/wighawag/shipmates.git",
9
+ "directory": "packages/shipmates"
10
+ },
11
+ "keywords": [
12
+ "agents",
13
+ "sessions",
14
+ "messaging",
15
+ "coordination",
16
+ "pi",
17
+ "sqlite",
18
+ "cli"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ }
29
+ },
30
+ "bin": {
31
+ "shipmates": "./dist/cli.js"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src"
36
+ ],
37
+ "engines": {
38
+ "node": ">=22.5.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^25.2.0",
42
+ "tsx": "^4.23.15",
43
+ "typescript": "^5.3.3",
44
+ "vitest": "^4.0.18"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc",
48
+ "test": "vitest run",
49
+ "test:watch": "vitest"
50
+ }
51
+ }
package/src/cli-run.ts ADDED
@@ -0,0 +1,263 @@
1
+ import {Shipmates} from './shipmates.js';
2
+ import {readTail} from './tail.js';
3
+ import {ShipmatesError, type AttentionItem, type Presence} from './types.js';
4
+
5
+ export interface CliIo {
6
+ env: Record<string, string | undefined>;
7
+ /** Whether stdin and stdout are a terminal: a precondition for acting as the human. */
8
+ isTTY: boolean;
9
+ stdout(s: string): void;
10
+ stderr(s: string): void;
11
+ }
12
+
13
+ const USAGE = `shipmates: sessions that know about each other
14
+
15
+ shipmates list [--cwd DIR] [--role ROLE] [--json] live sessions
16
+ shipmates read TARGET presence, open questions, recent transcript
17
+ shipmates tell TARGET TEXT... [--urgent] send a message
18
+ shipmates ask TARGET QUESTION... ask a question
19
+ shipmates inbox [--json] the human's open attention items
20
+ shipmates answer ID TEXT... answer an inbox item (h_...) or a question (q_...)
21
+ shipmates owned TARGET [--json] the sessions TARGET spawned (live or not), and its owner
22
+ shipmates stop TARGET stop the current turn of a session (the human only)
23
+
24
+ TARGET is a role (template-tree/push), a session file (.jsonl) or a session-id prefix.
25
+ Run by a human at a terminal, tell, ask and answer are origin "human". Run from an
26
+ agent's bash (PI_SESSION_FILE is set) they come from that session, origin "agent",
27
+ and answer and stop are refused: only the human answers the human's inbox, and
28
+ an agent stops only the sessions it owns, with its session_stop tool.
29
+ State: $SHIPMATES_STATE_DIR, else $XDG_STATE_HOME/shipmates.
30
+ `;
31
+
32
+ function flags(args: string[]) {
33
+ const rest: string[] = [];
34
+ const opts: Record<string, string | true> = {};
35
+ for (let i = 0; i < args.length; i++) {
36
+ const a = args[i];
37
+ if (a.startsWith('--')) {
38
+ const key = a.slice(2);
39
+ if (['cwd', 'role'].includes(key)) opts[key] = args[++i] ?? '';
40
+ else opts[key] = true;
41
+ } else rest.push(a);
42
+ }
43
+ return {rest, opts};
44
+ }
45
+
46
+ /**
47
+ * Who is speaking (ADR 0003). Inside an agent session the bash tool sets
48
+ * PI_SESSION_FILE, so the CLI speaks as that session; a human is a terminal
49
+ * with no session around it. Neither is proof against a determined agent on the
50
+ * same user, which is the stated limit.
51
+ */
52
+ function speaker(
53
+ io: CliIo,
54
+ ): {kind: 'agent'; session: string} | {kind: 'human'} | {kind: 'script'} {
55
+ const session = io.env.PI_SESSION_FILE;
56
+ if (session) return {kind: 'agent', session};
57
+ if (io.isTTY) return {kind: 'human'};
58
+ return {kind: 'script'};
59
+ }
60
+
61
+ function presenceLine(p: Presence): string {
62
+ const bits = [
63
+ p.roles.join(',') || '(no role)',
64
+ p.state,
65
+ p.cwd ?? '?',
66
+ p.branch,
67
+ p.status ? `status: ${p.status}` : null,
68
+ ].filter(Boolean);
69
+ return `${p.sessionFile}\n ${bits.join(' · ')}`;
70
+ }
71
+
72
+ function itemLine(i: AttentionItem): string {
73
+ return `${i.id}${i.blocking ? ' BLOCKING' : ''} ${i.question}${i.options?.length ? ` [${i.options.join(' / ')}]` : ''}\n from ${i.session}`;
74
+ }
75
+
76
+ export function runCli(argv: string[], io: CliIo): number {
77
+ const [cmd, ...args] = argv;
78
+ if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
79
+ io.stdout(USAGE);
80
+ return cmd ? 0 : 2;
81
+ }
82
+ const known = [
83
+ 'list',
84
+ 'read',
85
+ 'tell',
86
+ 'ask',
87
+ 'inbox',
88
+ 'answer',
89
+ 'owned',
90
+ 'stop',
91
+ ];
92
+ if (!known.includes(cmd)) {
93
+ io.stderr(`shipmates: unknown command ${cmd}\n\n${USAGE}`);
94
+ return 2;
95
+ }
96
+ let k: Shipmates | undefined;
97
+ try {
98
+ k = new Shipmates({stateDir: io.env.SHIPMATES_STATE_DIR || undefined});
99
+ const {rest, opts} = flags(args);
100
+ const who = speaker(io);
101
+ const from = who.kind === 'agent' ? who.session : null;
102
+ const origin = who.kind === 'human' ? 'human' : 'agent';
103
+ switch (cmd) {
104
+ case 'list': {
105
+ const list = k.list({
106
+ cwd: opts.cwd as string | undefined,
107
+ role: opts.role as string | undefined,
108
+ });
109
+ if (opts.json) io.stdout(JSON.stringify(list, null, 2) + '\n');
110
+ else
111
+ io.stdout(
112
+ list.length
113
+ ? list.map(presenceLine).join('\n') + '\n'
114
+ : 'No live sessions.\n',
115
+ );
116
+ return 0;
117
+ }
118
+ case 'read': {
119
+ const r = k.resolve(need(rest[0], 'TARGET'));
120
+ if (!r.session) {
121
+ io.stdout(`${r.target}: nobody holds this role right now.\n`);
122
+ return 0;
123
+ }
124
+ const p = k.presence(r.session);
125
+ const qs = k.openQuestionsTo(r.session);
126
+ const tail = readTail(r.session);
127
+ io.stdout(
128
+ [
129
+ p ? presenceLine(p) + (p.live ? '' : ' (GONE)') : r.session,
130
+ qs.length
131
+ ? 'open questions:\n' +
132
+ qs
133
+ .map((q) => ` ${q.id} from ${q.askerLabel}: ${q.text}`)
134
+ .join('\n')
135
+ : null,
136
+ tail.messages.map((m) => `[${m.role}] ${m.text}`).join('\n\n'),
137
+ ]
138
+ .filter(Boolean)
139
+ .join('\n\n') + '\n',
140
+ );
141
+ return 0;
142
+ }
143
+ case 'tell':
144
+ case 'ask': {
145
+ const target = need(rest[0], 'TARGET');
146
+ const text = need(
147
+ rest.slice(1).join(' '),
148
+ cmd === 'ask' ? 'QUESTION' : 'TEXT',
149
+ );
150
+ const sent = k.send({
151
+ from,
152
+ fromLabel: who.kind === 'script' ? 'script' : undefined,
153
+ to: target,
154
+ text,
155
+ kind: cmd,
156
+ origin,
157
+ urgent: opts.urgent === true,
158
+ });
159
+ io.stdout(
160
+ `${cmd === 'ask' ? `asked ${sent.question!.id}` : 'sent'} as ${sent.message.id} (origin ${sent.message.origin})\n`,
161
+ );
162
+ return 0;
163
+ }
164
+ case 'inbox': {
165
+ const items = k.inbox();
166
+ if (opts.json) io.stdout(JSON.stringify(items, null, 2) + '\n');
167
+ else
168
+ io.stdout(
169
+ items.length
170
+ ? items.map(itemLine).join('\n') + '\n'
171
+ : 'The inbox is empty.\n',
172
+ );
173
+ return 0;
174
+ }
175
+ case 'owned': {
176
+ const r = k.resolve(need(rest[0], 'TARGET'));
177
+ if (!r.session) {
178
+ io.stdout(`${r.target}: nobody holds this role right now.\n`);
179
+ return 0;
180
+ }
181
+ const owned = k.ownedBy(r.session, {transitive: true});
182
+ const owner = k.ownerOf(r.session);
183
+ if (opts.json) {
184
+ io.stdout(
185
+ JSON.stringify({session: r.session, owner, owned}, null, 2) + '\n',
186
+ );
187
+ return 0;
188
+ }
189
+ const lines = [
190
+ `${r.session}${owner ? `\n owner: ${owner}` : ''}`,
191
+ ...owned.map((o) => {
192
+ const p = k!.presence(o.session!);
193
+ const bits = [
194
+ o.role ?? '(no role)',
195
+ p?.live ? p.state : 'not live',
196
+ o.folder,
197
+ `via ${o.via}`,
198
+ o.owner === r.session ? null : `owned by ${o.owner}`,
199
+ o.archived ? o.archived.kind : null,
200
+ ].filter(Boolean);
201
+ return ` ${o.session}\n ${bits.join(' · ')}`;
202
+ }),
203
+ ];
204
+ if (!owned.length) lines.push(' owns no sessions');
205
+ io.stdout(lines.join('\n') + '\n');
206
+ return 0;
207
+ }
208
+ case 'stop': {
209
+ // D31: the human may stop any session's current turn; an agent stops
210
+ // only what it owns, through session_stop, where ownership is checked.
211
+ asHuman(who, 'stop');
212
+ const r = k.resolve(need(rest[0], 'TARGET'));
213
+ if (!r.session || !k.isLive(r.session)) {
214
+ io.stdout(
215
+ `${r.session ?? r.target} is not running: nothing to stop.\n`,
216
+ );
217
+ return 0;
218
+ }
219
+ const req = k.requestStop(r.session, {by: null});
220
+ io.stdout(
221
+ `stop requested (${req.id}): ${r.session} aborts its current turn within a second, if it is running. Sessions it owns are not stopped.\n`,
222
+ );
223
+ return 0;
224
+ }
225
+ case 'answer': {
226
+ asHuman(who, 'answer');
227
+ const id = need(rest[0], 'ID');
228
+ const text = need(rest.slice(1).join(' '), 'TEXT');
229
+ if (id.startsWith('h_')) k.answerItem(id, text, {channel: 'cli'});
230
+ else k.answer({from: null, questionId: id, text, origin: 'human'});
231
+ io.stdout(`answered ${id}\n`);
232
+ return 0;
233
+ }
234
+ }
235
+ return 2;
236
+ } catch (e) {
237
+ if (e instanceof ShipmatesError) {
238
+ io.stderr(`shipmates: ${e.message}\n`);
239
+ return 1;
240
+ }
241
+ throw e;
242
+ } finally {
243
+ k?.close();
244
+ }
245
+ }
246
+
247
+ function asHuman(who: ReturnType<typeof speaker>, verb: string): void {
248
+ if (who.kind === 'agent')
249
+ throw new ShipmatesError(
250
+ `${verb} is refused from inside an agent session (PI_SESSION_FILE is set): only the human ${verb === 'stop' ? 'stops any session' : 'answers as the human'}`,
251
+ 'not-human',
252
+ );
253
+ if (who.kind !== 'human')
254
+ throw new ShipmatesError(
255
+ `${verb} needs a terminal: only the human, at their terminal, ${verb === 'stop' ? 'stops any session' : 'answers as the human'}`,
256
+ 'not-human',
257
+ );
258
+ }
259
+
260
+ function need(v: string | undefined, what: string): string {
261
+ if (!v || !v.trim()) throw new ShipmatesError(`missing ${what}`, 'usage');
262
+ return v;
263
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {runCli} from './cli-run.js';
3
+ import {silenceSqliteWarning} from './quiet.js';
4
+
5
+ silenceSqliteWarning();
6
+ process.exitCode = runCli(process.argv.slice(2), {
7
+ env: process.env,
8
+ isTTY: !!(process.stdin.isTTY && process.stdout.isTTY),
9
+ stdout: (s) => process.stdout.write(s),
10
+ stderr: (s) => process.stderr.write(s),
11
+ });
@@ -0,0 +1,49 @@
1
+ import type {SessionState} from './types.js';
2
+
3
+ /** What a host knows about a session at the moment a message could be delivered. */
4
+ export interface SessionView {
5
+ /** pi's view: a run is in progress, or the session has settled. */
6
+ phase: 'running' | 'settled';
7
+ /** What the session declared (ADR 0006); only `waiting-for-human` changes the plan. */
8
+ declared: SessionState;
9
+ /** A blocking dialog with the human is open (`ui_prompt_start`). */
10
+ uiPrompt: boolean;
11
+ /** The human has text in the editor: they are typing into this session. */
12
+ editorBusy: boolean;
13
+ /** `/shipmates wake off` turns waking off for this session. */
14
+ wake: boolean;
15
+ }
16
+
17
+ /**
18
+ * When a message enters a session (ADR 0002). Nothing goes into pi's own
19
+ * queues, so every plan except `wake` keeps the message in shipmates until the
20
+ * boundary, where it can still be superseded or withdrawn:
21
+ * - `at-settle`: returned from `agent_before_settle` with a continuation;
22
+ * - `at-turn-end`: returned from `turn_end` (urgent, or after a dialog);
23
+ * - `wake`: start a turn now (`sendMessage` with `triggerTurn`);
24
+ * - `hold-for-human`: attached to the human's next run by `before_agent_start`.
25
+ *
26
+ * `fromHuman`: a pending message has origin `human` (an inbox answer, the
27
+ * human's `shipmates tell`), which only a human act can produce (ADR 0003). A
28
+ * session that declared `waiting-for-human` is waiting for exactly that, so it
29
+ * wakes for it: holding it for "the human's next turn" meant an answer given
30
+ * from the inbox (or a host such as wherever) sat there until the human also
31
+ * typed into the session, which they had no reason to do. Still held while the
32
+ * human types into the session (it joins that run) or with waking off.
33
+ */
34
+ export type DeliveryPlan =
35
+ 'at-settle' | 'at-turn-end' | 'wake' | 'hold-for-human';
36
+
37
+ export function planDelivery(
38
+ view: SessionView,
39
+ message: {urgent: boolean; fromHuman?: boolean},
40
+ ): DeliveryPlan {
41
+ if (view.phase === 'running') {
42
+ if (view.uiPrompt) return 'at-turn-end';
43
+ return message.urgent ? 'at-turn-end' : 'at-settle';
44
+ }
45
+ if (view.editorBusy || !view.wake) return 'hold-for-human';
46
+ if (view.declared === 'waiting-for-human' && !message.fromHuman)
47
+ return 'hold-for-human';
48
+ return 'wake';
49
+ }
package/src/host.ts ADDED
@@ -0,0 +1,161 @@
1
+ import type {DeliveryPlan} from './delivery.js';
2
+ import type {AttentionItem, Message} from './types.js';
3
+
4
+ /**
5
+ * The event a host emits on a pi session's event bus (`pi.events`) right before
6
+ * it sends a human's text into that session, so shipmates records the turn as a
7
+ * human act (ADR 0003, D22). Only extension code can reach the bus; the model
8
+ * cannot. Emit it for web, Telegram or any authenticated human channel; never
9
+ * for scheduled or agent-originated sends.
10
+ */
11
+ export const HUMAN_INPUT_EVENT = 'shipmates:human-input';
12
+
13
+ export interface HumanInputMark {
14
+ text: string;
15
+ /** Where the human typed it: `web`, `telegram`, ... */
16
+ channel: string;
17
+ /** Optional: names this mark, so its end event closes exactly this one. */
18
+ id?: string;
19
+ }
20
+
21
+ /**
22
+ * The event a host emits once its marked send attempt has SETTLED: the awaited
23
+ * `prompt()` resolved or threw (D35). shipmates then drops the mark if no input
24
+ * consumed it, so a send that never reached the `input` handlers (another
25
+ * extension returned `handled`, pi refused it while compacting) leaves nothing
26
+ * behind, with no window. Give the mark's `id` to close exactly that mark;
27
+ * without one, the oldest open mark with this text and no id is closed (a mark
28
+ * that has an id is closed only by it).
29
+ *
30
+ * Emit it ONLY after awaiting the send. Never after `pi.sendUserMessage()`
31
+ * from an extension: that call is fire-and-forget in pi 1.4 (it returns before
32
+ * the `input` handlers run and reports failures only as `extension_error`), so
33
+ * an end emitted after it can drop a mark that was about to match. Such a host
34
+ * emits no end event and relies on the mark's 5 s expiry. Also wrong, though
35
+ * safe: a `prompt()` called while pi is emitting `agent_settled` is deferred
36
+ * and resolves before its input runs, so the end drops the mark and that send
37
+ * is not recorded as the human's (it fails toward "not human").
38
+ */
39
+ export const HUMAN_INPUT_END_EVENT = 'shipmates:human-input-end';
40
+
41
+ export interface HumanInputEnd {
42
+ text: string;
43
+ id?: string;
44
+ }
45
+
46
+ /**
47
+ * A session asks its host for a new session it will own (D23, D28). shipmates has
48
+ * already recorded the spawn (`spawnId`) and created the worktree, if any.
49
+ */
50
+ export interface SpawnRequest {
51
+ /** The ownership record shipmates made for this spawn (`sp_...`). */
52
+ spawnId: string;
53
+ /** The owner's session file. One host serves many sessions, so this says whose child it is. */
54
+ owner: string;
55
+ /** Absolute folder the new session runs in (the worktree, when one was asked for). */
56
+ folder: string;
57
+ /**
58
+ * A short label for the new session (the role, else the prompt's first line,
59
+ * at most 80 characters), for a sidebar. The prompt itself is NOT the host's
60
+ * to send: shipmates delivers it as a message from the owner, origin agent, once
61
+ * the session exists (D28). A host must send nothing into the new session and
62
+ * must never emit a human-input mark for it.
63
+ */
64
+ title: string;
65
+ /** The role shipmates will claim for the new session. */
66
+ role?: string;
67
+ /** Start from this transcript (up to `entryId`, else all of it) instead of an empty one. */
68
+ fork?: {sessionFile: string; entryId?: string};
69
+ /** Informational: the worktree shipmates created for `folder`. */
70
+ worktree?: {repo: string; branch: string; path: string};
71
+ }
72
+
73
+ export interface SpawnResult {
74
+ /** The new session's transcript path, which shipmates binds to the spawn. */
75
+ sessionFile: string;
76
+ }
77
+
78
+ /**
79
+ * What a host did with a stop. `not-mine`: this host does not run that session;
80
+ * shipmates then asks the session's own extension to stop (D30).
81
+ */
82
+ export type StopOutcome = 'stopped' | 'not-running' | 'not-mine';
83
+
84
+ /**
85
+ * How a host delivers, notifies, spawns and stops (D20). The pi extension is the
86
+ * default host for a terminal pi; wherever implements its own through its
87
+ * session pool. Every member is optional: a host provides what it can.
88
+ */
89
+ export interface ShipmatesHost {
90
+ /** Deliver messages into a session the host runs. 'held' leaves them pending. */
91
+ deliver?(
92
+ sessionFile: string,
93
+ messages: Message[],
94
+ plan: DeliveryPlan,
95
+ ): Promise<'done' | 'held'>;
96
+ /** Tell the human about a new attention item (push, Telegram). */
97
+ notifyHuman?(item: AttentionItem): Promise<void>;
98
+ /**
99
+ * Create a session owned by `req.owner` in `req.folder` and resolve as soon
100
+ * as it exists and is addressable (its transcript path is final and its
101
+ * shipmates extension will start in it), NOT when a first turn ends: the new
102
+ * session starts with no prompt and shipmates wakes it with the owner's message.
103
+ * Reject to refuse; the agent sees the error.
104
+ */
105
+ spawn?(req: SpawnRequest): Promise<SpawnResult>;
106
+ /**
107
+ * Stop the CURRENT TURN of `sessionFile` (abort its running agent), leaving
108
+ * the session itself alive, and nothing else: stopping never cascades to the
109
+ * sessions it owns. `by` is the session asking (shipmates already checked that
110
+ * it owns the target). Null is reserved for the human; today `shipmates stop`
111
+ * does not call the host, it records a stop request that the session's own
112
+ * extension acts on (D30).
113
+ */
114
+ stop?(sessionFile: string, opts: {by: string | null}): Promise<StopOutcome>;
115
+ }
116
+
117
+ /**
118
+ * The per-process host registry (D26). It lives on `globalThis` under a
119
+ * `Symbol.for` key, not in this module, so a host that loaded ANOTHER copy of
120
+ * shipmates (wherever's server, the @wherever-dev/pi bridge, a jiti-loaded
121
+ * extension) fills the same registry @shipmates/pi reads. The same pattern as
122
+ * wherever's `Symbol.for('wherever-dev.server-process')` marker; the key string
123
+ * is a contract between packages, so it changes only with a release that says
124
+ * so (once so far: `kenning.host` became `shipmates.host` in the D38 rename).
125
+ * The shape is versioned for the same reason.
126
+ */
127
+ export const HOST_REGISTRY_KEY = Symbol.for('shipmates.host');
128
+
129
+ interface HostRegistry {
130
+ version: 1;
131
+ entries: {host: ShipmatesHost}[];
132
+ }
133
+
134
+ function registry(): HostRegistry {
135
+ const g = globalThis as unknown as Record<symbol, HostRegistry | undefined>;
136
+ let r = g[HOST_REGISTRY_KEY];
137
+ if (!r || !Array.isArray(r.entries))
138
+ r = g[HOST_REGISTRY_KEY] = {version: 1, entries: []};
139
+ return r;
140
+ }
141
+
142
+ /**
143
+ * Register this process's host. The most recently registered host wins; the
144
+ * returned function unregisters it and restores the previous one (registering
145
+ * the same object twice gives two entries, each removed by its own call).
146
+ */
147
+ export function registerHost(host: ShipmatesHost): () => void {
148
+ const entry = {host};
149
+ registry().entries.push(entry);
150
+ return () => {
151
+ const entries = registry().entries;
152
+ const i = entries.indexOf(entry);
153
+ if (i >= 0) entries.splice(i, 1);
154
+ };
155
+ }
156
+
157
+ /** The host registered last in this process, or undefined for the terminal default. */
158
+ export function currentHost(): ShipmatesHost | undefined {
159
+ const entries = registry().entries;
160
+ return entries[entries.length - 1]?.host;
161
+ }
package/src/ids.ts ADDED
@@ -0,0 +1,6 @@
1
+ import {randomBytes} from 'node:crypto';
2
+
3
+ /** Short, typed, unguessable ids: `m_` messages, `q_` questions, `h_` attention items, `t_` human turns. */
4
+ export function newId(prefix: string): string {
5
+ return `${prefix}_${randomBytes(6).toString('base64url')}`;
6
+ }