@astrosheep/square 0.3.84 → 0.3.86

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 (41) hide show
  1. package/dist/cli/express-presentation.js +1 -2
  2. package/dist/cli/observation-commands.js +1 -1
  3. package/dist/help.js +5 -4
  4. package/dist/hints.js +2 -3
  5. package/dist/index.d.ts +1 -0
  6. package/dist/open-square.d.ts +2 -0
  7. package/dist/open-square.js +1 -1
  8. package/dist/operation-presentation.js +9 -10
  9. package/dist/participant-host.d.ts +1 -0
  10. package/dist/participant-host.js +1 -1
  11. package/dist/presentation.d.ts +0 -1
  12. package/dist/presentation.js +10 -10
  13. package/dist/sqlite-square.d.ts +42 -0
  14. package/dist/sqlite-square.js +470 -0
  15. package/dist/square-api.d.ts +11 -41
  16. package/dist/square-api.js +27 -474
  17. package/dist/square-backend.d.ts +13 -0
  18. package/dist/square-backend.js +1 -0
  19. package/dist/square-facade.d.ts +2 -0
  20. package/dist/square-location.d.ts +15 -0
  21. package/dist/square-location.js +76 -0
  22. package/dist/square-stdio.d.ts +22 -0
  23. package/dist/square-stdio.js +217 -0
  24. package/dist/square-tools.js +1 -1
  25. package/dist/stdio-server.d.ts +3 -0
  26. package/dist/stdio-server.js +190 -0
  27. package/guides/backends.md +180 -0
  28. package/guides/claude-native.md +11 -10
  29. package/guides/square-api.md +13 -7
  30. package/package.json +1 -1
  31. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  32. package/plugins/claude/skills/square/SKILL.md +6 -6
  33. package/plugins/codex/.codex-plugin/plugin.json +1 -1
  34. package/plugins/paseo/OVERVIEW.md +4 -7
  35. package/plugins/paseo/README.md +6 -30
  36. package/plugins/paseo/package.json +3 -3
  37. package/plugins/paseo/paseo-plugin.json +1 -1
  38. package/plugins/pi/square-pi.js +4 -4
  39. package/skills/square/SKILL.md +6 -6
  40. package/plugins/paseo/index.server.ts +0 -10
  41. package/plugins/paseo/server/record-delivery.ts +0 -28
@@ -0,0 +1,22 @@
1
+ import { type SquareErrorCode, type SquareErrorFacts } from './model.js';
2
+ import type { SquareBackends, SquareBackend } from './square-backend.js';
3
+ import type { ParsedSquareLocation } from './square-location.js';
4
+ import type { OperationControl, OperationFailureDetail, SquareAtInput, SquareBuildInput } from './square-facade.js';
5
+ export declare const STDIO_PROTOCOL_VERSION = 1;
6
+ export declare const STDIO_MAX_FRAME_BYTES: number;
7
+ export declare const identityVariables: string[];
8
+ export declare function wireIdentity(env: NodeJS.ProcessEnv): Record<string, string>;
9
+ export interface WireError {
10
+ readonly code: number;
11
+ readonly message: string;
12
+ readonly data?: {
13
+ readonly code?: SquareErrorCode;
14
+ readonly facts?: SquareErrorFacts;
15
+ readonly operation?: OperationFailureDetail;
16
+ };
17
+ }
18
+ export declare function encodeError(error: unknown): WireError;
19
+ export declare function unsupported(feature: string): never;
20
+ export declare function openStdioSquare(location: string, selected: Extract<ParsedSquareLocation, {
21
+ kind: 'stdio';
22
+ }>, input: SquareAtInput, backends: SquareBackends, build?: Pick<SquareBuildInput, 'markdown' | 'hardCap' | 'throttlePerMinute' | 'template' | 'force'>, control?: OperationControl): Promise<SquareBackend>;
@@ -0,0 +1,217 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { createInterface } from 'node:readline';
4
+ import { SquareError } from './model.js';
5
+ import { harnessSessionSources } from './participant-identity.js';
6
+ export const STDIO_PROTOCOL_VERSION = 1;
7
+ export const STDIO_MAX_FRAME_BYTES = 8 * 1024 * 1024;
8
+ export const identityVariables = [...harnessSessionSources.flatMap(source => [source.variable, ...(source.childVariable ? [source.childVariable] : [])]), 'SQUARE_PARTICIPANT_NAME'];
9
+ export function wireIdentity(env) {
10
+ return Object.fromEntries(identityVariables.map(key => [key, env[key] ?? '']));
11
+ }
12
+ export function encodeError(error) {
13
+ const e = error;
14
+ return { code: -32000, message: e.message ?? 'Backend request failed', data: { code: e.code, facts: e.facts, operation: e.operation } };
15
+ }
16
+ function decodeError(error) {
17
+ return Object.assign(error.data?.code ? new SquareError(error.data.code, error.message, error.data.facts) : new Error(error.message), error.data?.operation ? { operation: error.data.operation } : {});
18
+ }
19
+ export function unsupported(feature) {
20
+ throw new SquareError('invalid_args', `The stdio backend does not support ${feature}; use explicit catch/history or a local resource`);
21
+ }
22
+ /** One process per opened Square. No replay, pooling, or operation policy. */
23
+ class Connection {
24
+ nextId = 0;
25
+ closed = false;
26
+ closing;
27
+ pending = new Map();
28
+ child;
29
+ exited;
30
+ constructor(command, args, cwd, env) {
31
+ this.child = spawn(command, [...args], { cwd, env, shell: false, stdio: 'pipe' });
32
+ this.exited = new Promise(resolve => this.child.once('close', () => resolve()));
33
+ // Diagnostic bytes are deliberately not included in errors (they can contain credentials).
34
+ this.child.stderr.resume();
35
+ const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
36
+ let frameBytes = 0;
37
+ this.child.stdout.on('data', chunk => {
38
+ for (const byte of chunk) {
39
+ if (byte === 10)
40
+ frameBytes = 0;
41
+ else if (++frameBytes > STDIO_MAX_FRAME_BYTES) {
42
+ this.fail('Backend frame exceeds the protocol limit');
43
+ break;
44
+ }
45
+ }
46
+ });
47
+ lines.on('line', line => {
48
+ try {
49
+ const message = JSON.parse(line);
50
+ if (message.jsonrpc !== '2.0')
51
+ throw new Error();
52
+ if (message.method === 'square/progress') {
53
+ const pending = this.pending.get(message.params?.id);
54
+ if (pending && message.params?.progress) {
55
+ try {
56
+ pending.control?.onProgress?.(message.params.progress);
57
+ }
58
+ catch { /* progress observers cannot corrupt framing */ }
59
+ }
60
+ return;
61
+ }
62
+ if (!Number.isSafeInteger(message.id) || (Object.hasOwn(message, 'result') === Object.hasOwn(message, 'error')))
63
+ throw new Error();
64
+ const pending = this.pending.get(message.id);
65
+ if (!pending)
66
+ throw new Error();
67
+ this.pending.delete(message.id);
68
+ pending.dispose();
69
+ if (message.error)
70
+ pending.reject(decodeError(message.error));
71
+ else
72
+ pending.resolve(message.result);
73
+ }
74
+ catch {
75
+ this.fail('Malformed backend protocol response');
76
+ }
77
+ });
78
+ lines.once('close', () => this.fail('Backend stdout ended'));
79
+ this.child.once('error', () => this.fail('Cannot start configured backend; check command and cwd'));
80
+ this.child.once('exit', () => this.fail('Backend process exited'));
81
+ this.child.stdin.on('error', () => this.fail('Backend stdin closed'));
82
+ }
83
+ fail(message) {
84
+ if (this.closed)
85
+ return;
86
+ this.closed = true;
87
+ for (const pending of this.pending.values()) {
88
+ pending.dispose();
89
+ const error = new SquareError('unavailable', message);
90
+ if (pending.method === 'express')
91
+ Object.assign(error, { operation: { operation: 'express', expressEffect: 'unknown' } });
92
+ pending.reject(error);
93
+ }
94
+ this.pending.clear();
95
+ this.child.stdin.destroy();
96
+ this.child.kill();
97
+ const timer = setTimeout(() => this.child.kill('SIGKILL'), 500);
98
+ timer.unref();
99
+ void this.exited.then(() => clearTimeout(timer));
100
+ }
101
+ request(method, params, control) {
102
+ if (control?.signal?.aborted)
103
+ return Promise.reject(control.signal.reason ?? new Error('Operation cancelled'));
104
+ if (this.closed)
105
+ return Promise.reject(new SquareError('unavailable', 'Backend connection is closed'));
106
+ const id = ++this.nextId;
107
+ let frame;
108
+ try {
109
+ frame = JSON.stringify({ jsonrpc: '2.0', id, method, params }, (_key, value) => {
110
+ if (typeof value === 'number' && !Number.isFinite(value))
111
+ throw new Error('Non-finite number');
112
+ return value;
113
+ }) + '\n';
114
+ if (Buffer.byteLength(frame) > STDIO_MAX_FRAME_BYTES)
115
+ throw new Error('Frame too large');
116
+ }
117
+ catch {
118
+ const error = new SquareError('invalid_args', 'Backend request must be JSON-serializable with finite numbers and fit the protocol frame limit');
119
+ if (method === 'express')
120
+ Object.assign(error, { operation: { operation: 'express', expressEffect: 'unsent' } });
121
+ return Promise.reject(error);
122
+ }
123
+ return new Promise((resolve, reject) => {
124
+ const abort = () => {
125
+ // Wait for the response: server cleanup (including catch lease release) must finish first.
126
+ if (!this.closed)
127
+ this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }) + '\n');
128
+ };
129
+ this.pending.set(id, { resolve, reject, method, control, dispose: () => control?.signal?.removeEventListener('abort', abort) });
130
+ control?.signal?.addEventListener('abort', abort, { once: true });
131
+ this.child.stdin.write(frame);
132
+ });
133
+ }
134
+ close() {
135
+ return this.closing ??= (async () => {
136
+ const timer = setTimeout(() => this.fail('Backend close timed out'), 1000);
137
+ try {
138
+ if (!this.closed)
139
+ await this.request('square/close', {});
140
+ }
141
+ catch { /* disconnect already rejects outstanding work */ }
142
+ finally {
143
+ clearTimeout(timer);
144
+ this.fail('Backend connection closed');
145
+ await this.exited;
146
+ }
147
+ })();
148
+ }
149
+ }
150
+ class StdioSquare {
151
+ location;
152
+ connection;
153
+ handle;
154
+ constructor(location, connection, handle) {
155
+ this.location = location;
156
+ this.connection = connection;
157
+ this.handle = handle;
158
+ }
159
+ call(method, args, control, participant) {
160
+ return this.connection.request(method, { handle: this.handle, args, ...(participant === undefined ? {} : { participant }) }, control);
161
+ }
162
+ participantHandle(name) {
163
+ return {
164
+ name,
165
+ express: (body, options, control) => this.call('express', [body, options], control, name),
166
+ catch: (options, control) => this.call('catch', [options], control, name),
167
+ listen: (target, options, control) => this.call('listen', [target, options], control, name),
168
+ ignore: (target, options, control) => this.call('ignore', [target, options], control, name),
169
+ unlisten: (target, options, control) => this.call('unlisten', [target, options], control, name),
170
+ listening: (options, control) => this.call('listening', [options], control, name),
171
+ hold: (reason, options, control) => this.call('hold', [reason, options], control, name),
172
+ resume: (options, control) => this.call('resume', [options], control, name),
173
+ done: (body, options, control) => this.call('done', [body, options], control, name),
174
+ history: (query, control) => this.history(query, control),
175
+ };
176
+ }
177
+ async participant(name) { return this.participantHandle(await this.call('participant', [name])); }
178
+ async join(...[name, options, control]) {
179
+ const result = await this.call('join', [name, options], control);
180
+ return { ...result, participant: this.participantHandle(result.participant) };
181
+ }
182
+ history(...[query, control]) { return this.call('history', [query], control); }
183
+ status(...[options, control]) { return this.call('status', [options], control); }
184
+ participants(...[options, control]) { return this.call('participants', [options], control); }
185
+ recovery(...[name, control]) { return this.call('recovery', [name], control); }
186
+ snapshot() { return Promise.reject(new SquareError('invalid_args', 'stdio does not support function-valued snapshot; use status/participants/history')); }
187
+ stream() { unsupported('stream'); }
188
+ recognize() { return Promise.reject(new SquareError('invalid_args', 'stdio does not support host recognition; select a participant explicitly')); }
189
+ implicitJoin() { unsupported('host implicit join'); }
190
+ doneOwnedSession() { unsupported('host session cleanup'); }
191
+ endOwnedSession() { unsupported('host session cleanup'); }
192
+ retireEndedSessionRoutes() { unsupported('host wake routes'); }
193
+ close() { return this.connection.close(); }
194
+ }
195
+ export async function openStdioSquare(location, selected, input, backends, build, control) {
196
+ if (input.clock || input.hostLedger || input.wakeTransport)
197
+ unsupported('client clock, hostLedger or wakeTransport injection');
198
+ if (control?.signal?.aborted)
199
+ throw control.signal.reason ?? new Error('Operation cancelled');
200
+ const backend = Object.hasOwn(backends, selected.backend) ? backends[selected.backend] : undefined;
201
+ if (!backend)
202
+ throw new SquareError('invalid_args', `Backend ${selected.backend} is not configured; set backends or SQUARE_BACKENDS_CONFIG`);
203
+ const cwd = input.cwd ?? process.cwd();
204
+ const command = backend.command.includes('/') || backend.command.includes('\\') ? path.resolve(cwd, backend.command) : backend.command;
205
+ const connection = new Connection(command, backend.args ?? [], path.resolve(cwd, backend.cwd ?? '.'), { ...(input.env ?? process.env), ...backend.env });
206
+ try {
207
+ const result = await connection.request('square/open', { version: STDIO_PROTOCOL_VERSION, key: selected.key, location,
208
+ identity: wireIdentity(input.env ?? process.env), participant: input.participant, build }, control);
209
+ if (result.version !== STDIO_PROTOCOL_VERSION || typeof result.handle !== 'string')
210
+ throw new SquareError('unavailable', 'Backend protocol version mismatch');
211
+ return new StdioSquare(location, connection, result.handle);
212
+ }
213
+ catch (error) {
214
+ await connection.close();
215
+ throw error;
216
+ }
217
+ }
@@ -2,7 +2,7 @@ import { z } from 'zod/v4';
2
2
  import { isSquareError } from './model.js';
3
3
  import { CATCH_DEFAULT_LIMIT } from './square-api.js';
4
4
  import { renderCatchOutcome, renderExpression, renderFailureLines, renderHistoryResult, renderJoinResult, renderLifecycleResult, renderListenerChange, renderListeningResult, renderParticipantsResult, renderStatusResult, } from './operation-presentation.js';
5
- const location = z.string().optional().describe('Path to the .square artifact, relative to the current working directory. Defaults to the configured square.');
5
+ const location = z.string().optional().describe('Local .square artifact path or configured backend URI (stdio://name/key). Relative paths use the current working directory. Defaults to the configured square.');
6
6
  const participant = z.string().optional().describe('Participant name. Defaults to the configured participant or the current session’s unambiguous participant.');
7
7
  const activityId = z.string().regex(/^act\/(0|[1-9][0-9]*)$/);
8
8
  const stringArray = z.array(z.string());
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** Serve the existing resource API. This adapter contains no activity policy. */
3
+ export declare function runSquareStdioServer(root: string): Promise<void>;
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import fs from 'node:fs/promises';
4
+ import { createInterface } from 'node:readline';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { SqliteSquare } from './sqlite-square.js';
7
+ import { SquareError } from './model.js';
8
+ import { canonicalPath } from './canonical-path.js';
9
+ import { STDIO_PROTOCOL_VERSION, STDIO_MAX_FRAME_BYTES, encodeError, identityVariables } from './square-stdio.js';
10
+ import { parseSquareLocation } from './square-location.js';
11
+ /** Serve the existing resource API. This adapter contains no activity policy. */
12
+ export async function runSquareStdioServer(root) {
13
+ await fs.mkdir(root, { recursive: true });
14
+ root = await canonicalPath(root);
15
+ const baseEnv = { ...process.env };
16
+ let square;
17
+ let location;
18
+ let opening = false, closing = false;
19
+ const running = new Map();
20
+ const write = (message) => { if (!process.stdout.destroyed)
21
+ process.stdout.write(JSON.stringify(message) + '\n'); };
22
+ const response = (id, result) => write({ jsonrpc: '2.0', id, result });
23
+ const fail = (id, error) => write({ jsonrpc: '2.0', id, error: encodeError(error) });
24
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
25
+ let shutdown;
26
+ const close = () => shutdown ??= (async () => {
27
+ closing = true;
28
+ for (const request of running.values())
29
+ request.controller.abort();
30
+ await Promise.allSettled([...running.values()].map(request => request.work));
31
+ await square?.close();
32
+ lines.close();
33
+ process.stdin.pause();
34
+ })();
35
+ const fatal = () => { void close().finally(() => { process.exitCode = 1; }); };
36
+ let frameBytes = 0;
37
+ process.stdin.on('data', chunk => {
38
+ for (const byte of Buffer.from(chunk)) {
39
+ if (byte === 10)
40
+ frameBytes = 0;
41
+ else if (++frameBytes > STDIO_MAX_FRAME_BYTES) {
42
+ fatal();
43
+ break;
44
+ }
45
+ }
46
+ });
47
+ process.stdout.on('error', fatal);
48
+ process.once('SIGTERM', fatal);
49
+ process.once('SIGINT', fatal);
50
+ lines.on('close', () => { if (!closing)
51
+ void close(); });
52
+ async function invoke(method, params, control) {
53
+ if (method === 'square/open') {
54
+ if (square || opening)
55
+ throw new SquareError('invalid_args', 'One logical open is allowed per connection');
56
+ opening = true;
57
+ try {
58
+ if (params.version !== STDIO_PROTOCOL_VERSION)
59
+ throw new SquareError('invalid_args', 'Unsupported Square stdio protocol version');
60
+ const parsed = parseSquareLocation(params.location);
61
+ if (parsed.kind !== 'stdio' || parsed.key !== params.key)
62
+ throw new SquareError('invalid_args', 'Open requires a matching stdio location and key');
63
+ const target = path.join(root, `${parsed.key}.square`);
64
+ const canonical = await canonicalPath(target);
65
+ if (path.dirname(canonical) !== root)
66
+ throw new SquareError('invalid_args', 'Square key escapes the configured backend root');
67
+ const env = { ...baseEnv };
68
+ for (const key of identityVariables) {
69
+ const value = params.identity?.[key];
70
+ if (value !== undefined && typeof value !== 'string')
71
+ throw new SquareError('invalid_args', 'Invalid operation identity');
72
+ env[key] = value ?? '';
73
+ }
74
+ const input = { path: target, env, participant: params.participant };
75
+ square = params.build === undefined ? await SqliteSquare.at(input, control, false)
76
+ : await SqliteSquare.build({ ...params.build, ...input }, control, false);
77
+ location = parsed.uri;
78
+ return { version: STDIO_PROTOCOL_VERSION, handle: 'square' };
79
+ }
80
+ finally {
81
+ opening = false;
82
+ }
83
+ }
84
+ if (!square || params.handle !== 'square')
85
+ throw new SquareError('invalid_args', 'Open a logical square first');
86
+ if (!Array.isArray(params.args))
87
+ throw new SquareError('invalid_args', 'Operation args must be an array');
88
+ // JSON null represents omitted optional arguments, never the meaningful history limit:null inside an options object.
89
+ const args = params.args.map((arg) => arg === null ? undefined : arg);
90
+ let result;
91
+ switch (method) {
92
+ case 'participant': return (await square.participant(args[0])).name;
93
+ case 'join': {
94
+ const joined = await square.join(args[0], args[1], control);
95
+ result = { ...joined, participant: joined.participant.name };
96
+ break;
97
+ }
98
+ case 'history':
99
+ result = await square.history(args[0], control);
100
+ break;
101
+ case 'status':
102
+ result = await square.status(args[0], control);
103
+ break;
104
+ case 'participants':
105
+ result = await square.participants(args[0], control);
106
+ break;
107
+ case 'recovery':
108
+ result = await square.recovery(args[0], control);
109
+ break;
110
+ default: {
111
+ if (typeof params.participant !== 'string')
112
+ throw new SquareError('invalid_args', 'Participant operation requires a name');
113
+ const participant = await square.participant(params.participant);
114
+ switch (method) {
115
+ case 'express':
116
+ result = await participant.express(args[0], args[1], control);
117
+ break;
118
+ case 'catch':
119
+ result = await participant.catch(args[0], control);
120
+ break;
121
+ case 'listen':
122
+ result = await participant.listen(args[0], args[1], control);
123
+ break;
124
+ case 'ignore':
125
+ result = await participant.ignore(args[0], args[1], control);
126
+ break;
127
+ case 'unlisten':
128
+ result = await participant.unlisten(args[0], args[1], control);
129
+ break;
130
+ case 'listening':
131
+ result = await participant.listening(args[0], control);
132
+ break;
133
+ case 'hold':
134
+ result = await participant.hold(args[0], args[1], control);
135
+ break;
136
+ case 'resume':
137
+ result = await participant.resume(args[0], control);
138
+ break;
139
+ case 'done':
140
+ result = await participant.done(args[0], args[1], control);
141
+ break;
142
+ default: throw new SquareError('invalid_args', 'Unsupported stdio operation');
143
+ }
144
+ }
145
+ }
146
+ if (result?.observation)
147
+ result = { ...result, observation: { ...result.observation, location, automaticDeliveryAvailable: false } };
148
+ return result;
149
+ }
150
+ lines.on('line', line => {
151
+ if (closing)
152
+ return;
153
+ let message;
154
+ try {
155
+ message = JSON.parse(line);
156
+ if (message.jsonrpc !== '2.0' || typeof message.method !== 'string' || !message.params || typeof message.params !== 'object')
157
+ throw new Error();
158
+ if (message.method === '$/cancelRequest') {
159
+ running.get(message.params.id)?.controller.abort();
160
+ return;
161
+ }
162
+ if (!Number.isSafeInteger(message.id) || running.has(message.id))
163
+ throw new Error();
164
+ }
165
+ catch {
166
+ fatal();
167
+ return;
168
+ }
169
+ if (message.method === 'square/close') {
170
+ void close().then(() => { response(message.id, null); process.stdout.end(); });
171
+ return;
172
+ }
173
+ const controller = new AbortController();
174
+ // Start on a microtask so the request is tracked before progress/cleanup can run.
175
+ const work = Promise.resolve().then(() => invoke(message.method, message.params, {
176
+ signal: controller.signal,
177
+ onProgress: progress => write({ jsonrpc: '2.0', method: 'square/progress', params: { id: message.id, progress } }),
178
+ })).then(result => response(message.id, result), error => fail(message.id, error)).finally(() => { running.delete(message.id); });
179
+ running.set(message.id, { controller, work });
180
+ });
181
+ }
182
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
183
+ if (process.argv.length !== 4 || process.argv[2] !== '--root') {
184
+ process.stderr.write('usage: node dist/stdio-server.js --root <backend-artifact-directory>\n');
185
+ process.exitCode = 2;
186
+ }
187
+ else {
188
+ await runSquareStdioServer(path.resolve(process.argv[3]));
189
+ }
190
+ }
@@ -0,0 +1,180 @@
1
+ # Locations and the stdio backend
2
+
3
+ Square and Participant are the same public resource API for local SQLite, local in-memory,
4
+ and stdio-backed squares. There is no separate participant policy or caller-specific dispatch.
5
+ `Square.at` / `Square.build` choose the backend before opening storage. CLI, MCP and Pi tools use
6
+ that same boundary. No Slack backend or external messaging integration is included.
7
+
8
+ ## Runnable setup
9
+
10
+ From a built source checkout (`npm run build`), create a JSON configuration file, substituting
11
+ absolute paths for this machine:
12
+
13
+ ```json
14
+ {
15
+ "backends": {
16
+ "local": {
17
+ "command": "/absolute/path/to/node",
18
+ "args": ["/absolute/path/to/square/dist/stdio-server.js", "--root", "/absolute/path/to/squares"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ The bundled backend's standalone startup command is:
25
+
26
+ ```sh
27
+ node /absolute/path/to/square/dist/stdio-server.js --root /absolute/path/to/squares
28
+ ```
29
+
30
+ Normally Square spawns it automatically, without a shell, using the configured command. Its
31
+ stdin/stdout are the protocol, not an interactive terminal. Stderr is diagnostics. The client
32
+ drains stderr without inserting it into participant output or error messages.
33
+
34
+ ```sh
35
+ export SQUARE_BACKENDS_CONFIG=/absolute/path/to/backends.json
36
+ export SQUARE_LOCATION=stdio://local/design
37
+ printf '# Design\nA place to compare ideas.\n' | node dist/square.js build -
38
+ node dist/square.js --as Alice join
39
+ node dist/square.js --as Bob join
40
+ node dist/square.js --as Alice express --force 'What do you think @Bob?'
41
+ node dist/square.js --as Bob history
42
+ node dist/square.js --as Bob catch --now
43
+ ```
44
+
45
+ History does not consume. Catch consumes eligible directed activity once. A reply uses the usual
46
+ `--reply act/N`; mentions, replies, listening, ownership, hold/throttle, reentry and receipt semantics
47
+ are the existing SQLite implementation. Independent processes address the same `design.square`
48
+ inside the backend root. They do **not** share an in-memory resource.
49
+
50
+ SDK callers may provide typed configuration directly:
51
+
52
+ ```ts
53
+ import { Square, type SquareBackends } from '@astrosheep/square';
54
+
55
+ const backends: SquareBackends = {
56
+ local: { command: process.execPath, args: ['/absolute/path/to/square/dist/stdio-server.js', '--root', '/tmp/squares'] },
57
+ };
58
+ const square = await Square.at({ path: 'stdio://local/design', backends, participant: 'Bob' });
59
+ try {
60
+ const bob = (await square.join()).participant;
61
+ const caught = await bob.catch();
62
+ console.log(caught.activities);
63
+ } finally {
64
+ await square.close();
65
+ }
66
+ ```
67
+
68
+ Use the same `path` and `backends` in `createSquareMcpServer` options. Tool calls can override
69
+ `location: "stdio://local/design"`; the override owns its process rather than borrowing the
70
+ configured local SQLite connection. Pi tools accept the identical location and read the captured
71
+ `SQUARE_BACKENDS_CONFIG`. Native session identity is still chosen by each adapter on each call.
72
+
73
+ ## Locations and configuration
74
+
75
+ - Plain locations are filesystem paths, resolved against captured input `cwd`. `inMemory` is always
76
+ local. Remote `build` creates a square through the backend; it never writes a URI-named local file.
77
+ - Stdio URI grammar is `stdio://<alias>/<encoded-key>`. Aliases are case-sensitive ASCII letters,
78
+ digits, `_` and `-`. The key is one nonempty Unicode name, **not** a hierarchy: encode it with
79
+ `encodeURIComponent`, decoded exactly once. Encoded slashes/backslashes, controls, `.` and `..`
80
+ are refused. Canonical URIs re-encode the decoded key, so `hello%20world` is unambiguous.
81
+ Credentials, ports, query strings, fragments, extra path segments and unknown schemes are refused.
82
+ - A key `design` maps to `design.square` in the bundled server root. The root is created if needed;
83
+ resolved artifact targets outside it (including existing escaping symlinks) are refused. Use a root
84
+ managed by the backend owner, not an attacker-writable directory. Different aliases need not refer
85
+ to different servers, but ownership is established by backend persistence, not by the alias.
86
+ - An alias is explicit configuration, never an executable in a URI. An entry is
87
+ `{command: string, args?: string[], cwd?: string, env?: Record<string,string>}`. `command` is a
88
+ program name on PATH or a path. Relative command paths, entry `cwd`, and the config-file path are
89
+ resolved against captured input `cwd`, **not** relative to the config file. Commands spawn with
90
+ no shell and inherit captured caller environment plus only the entry's explicit env overrides.
91
+ - SDK `backends` (including `{}`) wins over file configuration. Otherwise Square reads
92
+ `SQUARE_BACKENDS_CONFIG`, default `~/.config/square/backends.json` (`HOME` from captured env).
93
+ A missing default file is harmless for local resources. Explicit missing/invalid files, malformed
94
+ configuration and missing selected aliases refuse with `invalid_args`. Error text never dumps
95
+ configuration values or environment secrets.
96
+ - Each remote open owns one child process/connection, reused across its operations. There is no
97
+ global pool. A supplied SQLite `resources` owner is not used for remote opens; close still closes
98
+ that remote process. Separate opens share state only through the backend's persistence.
99
+ - CLI failed-expression drafts stay in local `./drafts` for backend locations; recovery commands and
100
+ display labels retain the URI. Local-artifact draft placement is unchanged.
101
+
102
+ ## Protocol version 1
103
+
104
+ Newline-delimited JSON-RPC 2.0 over UTF-8 stdin/stdout, one object per line, at most 8 MiB per frame.
105
+ Stdout is protocol only. No batch requests. The initial versioned handshake opens one logical square
106
+ per connection and returns an opaque handle. IDs are unique positive integers on the client;
107
+ requests may overlap and responses may arrive out of order.
108
+
109
+ ```json
110
+ {"jsonrpc":"2.0","id":1,"method":"square/open","params":{"version":1,"key":"design","location":"stdio://local/design","identity":{"PI_SESSION_ID":"session-id"},"participant":"Bob"}}
111
+ {"jsonrpc":"2.0","id":1,"result":{"version":1,"handle":"square"}}
112
+ {"jsonrpc":"2.0","id":2,"method":"join","params":{"handle":"square","args":["Bob",{"observe":true}]}}
113
+ ```
114
+
115
+ Open may include `build: {markdown, hardCap?, throttlePerMinute?, template?, force?}` instead of
116
+ opening an existing artifact. The client transmits only recognized harness session coordinates,
117
+ the Claude child flag and configured participant name as identity facts, **not the whole environment
118
+ in the protocol**. The backend captures its own process environment, clears **all** these startup
119
+ coordinates (including PASEO_AGENT_ID), then overlays explicit call-local facts without mutating
120
+ `process.env`. Participant defaults remain separate from square keys. Each new tool open therefore
121
+ uses that call's identity, not MCP/Pi/backend startup identity.
122
+
123
+ After open, methods take `{handle, args, participant?}`. `args` is the public operation's positional
124
+ arguments excluding `OperationControl`; trailing JSON nulls represent omitted optional arguments.
125
+ Nested nulls such as `history({limit:null})` retain their public meaning.
126
+
127
+ | Methods | args | participant field |
128
+ | --- | --- | --- |
129
+ | `participant` | `[name?]` | no; selection only, not joining |
130
+ | `join` | `[name?, options?]` | no |
131
+ | `history`, `status`, `participants` | `[options?]` | no |
132
+ | `recovery` | `[name?]` | no |
133
+ | `express` | `[body, options?]` | required |
134
+ | `catch`, `listening`, `resume` | `[options?]` | required |
135
+ | `listen`, `ignore`, `unlisten` | `[target, options?]` | required |
136
+ | `hold`, `done` | `[body?, options?]` | required |
137
+
138
+ Results are the concrete public operation results, including requested observations. Participant
139
+ handles serialize as names for `participant` and `join.participant` and become real local handles
140
+ on the client. Observation locations are canonical remote URIs and automatic delivery is false.
141
+ Errors are JSON-RPC `{code:-32000,message,data:{code?,facts?,operation?}}`; Square codes, structured
142
+ facts, history bounds and express certainty survive the boundary. The client does not infer
143
+ `unsent` from a connection failure. There is no mutation retry or replay.
144
+
145
+ Progress is a notification
146
+ `{jsonrpc:"2.0",method:"square/progress",params:{id,progress}}` where progress is the typed public
147
+ `OperationProgress`. Request abort sends `$/cancelRequest` with `{id}`; the server aborts only that
148
+ request and returns its response **after** cleanup, including releasing a catch lease. Another
149
+ request on the same handle continues normally. Cancellation never undoes an explicitly committed
150
+ receipt. `square/close` with `{}` aborts/drains outstanding requests, closes SQLite and acknowledges
151
+ with a null result. Client close is idempotent, waits briefly for graceful cleanup, then terminates
152
+ an unresponsive process. EOF, malformed framing, version mismatch and process exit reject pending
153
+ requests and release the connection. A lost express response after dispatch has unknown effect;
154
+ inspect history before deciding whether to send again.
155
+
156
+ ## Explicit limitations
157
+
158
+ - No automatic wake, route registration, native notification delivery or cross-host inbox for stdio.
159
+ The server disables wake dispatch and route publication explicitly, while retaining backend-local
160
+ session ownership. A harness identity does not imply wake capability. Use explicit `catch`
161
+ (including cancellable positive-idle catch) or history.
162
+ - `snapshot` (which contains a function), `stream`, host recognition/implicit join, owner-session
163
+ cleanup and route-retirement operations refuse explicitly. No partial JSON snapshot or fake stream
164
+ is offered. Use status/participants/history and explicit participant lifecycle methods.
165
+ - Client clock functions, host-ledger objects and wake transport objects cannot cross the process
166
+ boundary and are refused. Backend process configuration owns its environment, clock and ledger.
167
+ - File doctor, migrate and discovery are local-only and refuse a selected backend URI. Run file
168
+ diagnostics/migration locally on the backend host with the artifact path while clients are stopped.
169
+ Local harness discovery/inbox do not enumerate remote backends; remote membership is not registered
170
+ into the client's host ledger or notification watchers.
171
+ - No process pooling, reconnection, automatic retries, server daemon, Slack IDs, credentials, live
172
+ external sends, installation or release management is introduced.
173
+
174
+ ## Slack is a bridge, not a backend
175
+
176
+ Slack never becomes a Square location and does not change the backend grammar. To bring Slack humans
177
+ into a square, run `packages/slack-bridge` (`square-slack-bridge`) against one channel and one local
178
+ artifact: Slack messages land as ordinary activities from `slack/<name>` participants, and Square
179
+ `say` activities appear in the channel. The artifact stays authoritative, so mentions, replies, catch,
180
+ notifications and previews are the existing native behavior; no core, CLI, MCP or Pi code changes.
@@ -37,19 +37,20 @@ changes `crossSessionInbound`. After bytes may have been sent, `unknown` remains
37
37
  attention-wide and prevents another send through Paseo, even if routes later change.
38
38
 
39
39
  Each native send persists a message ID before writing; the wire `uuid` and
40
- `msg_id` carry that ID. On a matching Paseo build, the Square server plugin records
41
- `held`, `released` and `dropped` observations from `agent.delivery_status` on the
42
- original host-ledger wake attempt. The event ID is deduplicated and the native
43
- reason and observation time remain diagnostic only. Neither a release nor a drop
44
- is a queue receipt, proof of consumption or retry authorization. Unknown IDs do
45
- not create evidence; older attempts without message IDs cannot be backfilled.
40
+ `msg_id` carry that ID. Square records no native custody telemetry from Paseo:
41
+ official Paseo exposes no delivery-status lifecycle event, so a held message stays
42
+ `unknown` with `native_admission_unconfirmed`. Recording a `held`, `released` or
43
+ `dropped` observation would require a Paseo-provided event; Square does not patch
44
+ Paseo to invent one. Even when such an observation exists, the event ID is
45
+ deduplicated and the native reason and observation time remain diagnostic only.
46
+ Neither a release nor a drop is a queue receipt, proof of consumption or retry
47
+ authorization.
46
48
 
47
49
  `square harness doctor delivery` shows native custody separately from pending
48
50
  attention, including after the activity is seen or the participant leaves. Paseo
49
- also presents the native state in its timeline. This integration requires the
50
- matching local Paseo 0.12.1-square.1 lifecycle API and plugin SDK; see
51
- [the Paseo plugin](../plugins/paseo/README.md). Acceptance means normal delivery
52
- when policy allows it, or a visible reason without bypass/replay when policy holds it.
51
+ presents the `peer_message_hold` state in its own timeline. Acceptance means normal
52
+ delivery when the receiver allows it, or a visible reason without bypass/replay when
53
+ policy holds it.
53
54
 
54
55
  ## MCP tools and call identity
55
56