@anhlp/alp-protocol 0.0.0-beta.1

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/src/session.ts ADDED
@@ -0,0 +1,94 @@
1
+ import type { RuntimeKind } from './dto.js';
2
+ import type { SessionSnapshot } from './events.js';
3
+ /** MCP servers a client adds to the agent's own; the agent's names win no collisions. */
4
+ export type HostMcpServer =
5
+ | { type: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }
6
+ | { type: 'http' | 'sse'; url: string; headers?: Record<string, string> };
7
+
8
+ /** What a client asks for; resolveSession turns it into a launchable session. */
9
+ export type SessionSpec = {
10
+ cwd: string;
11
+ agent?: string;
12
+ /** Workflow selected for a new session; omitted uses settings or the restored snapshot. */
13
+ workflow?: string;
14
+ /** Native model, or runtime-prefixed (`codex:`/`claude:`, or `acp:<provider>[/<model>]`) to also choose the runtime. */
15
+ model?: string;
16
+ mode?: string;
17
+ thinking?: string;
18
+ systemPrompt?: string;
19
+ env?: Record<string, string>;
20
+ mcpServers?: Record<string, HostMcpServer>;
21
+ /** Keep the native thread so the session can be resumed. */
22
+ persist?: boolean;
23
+ /** Keep the native thread on disk though the session cannot be resumed: an assignment, which alp_recall may question later. */
24
+ keepThread?: boolean;
25
+ restore?: { agent: string; threadId: string; runtime?: string; model?: string; workflow?: { mode: string; maxPeers: number; supervisor?: boolean } };
26
+ /** Where the native harness works, when not the project root: an assignment's git worktree. ALP files are still read from cwd. */
27
+ workdir?: string;
28
+ /** Explicit shared-assignment write scope; workdir points here while ALP uses cwd for its project. */
29
+ writeRoot?: string;
30
+ /** The workdir is a disposable copy the session may write, though its mode is read-only for the requester's tree. */
31
+ copy?: boolean;
32
+ /** The requester's directory the copy mirrors. */
33
+ copyOf?: string;
34
+ };
35
+
36
+ export type OpenOptions = {
37
+ history?: 'replay' | 'skip';
38
+ /** False when the client cannot show child sessions; delegation is then refused in this tree. */
39
+ delegation?: boolean;
40
+ };
41
+
42
+ export type PromptContent = Array<{ type: string; text?: string }>;
43
+
44
+ export type PromptInput = {
45
+ clientMessageId: string;
46
+ /** auto starts a turn; steer adds to the running one. */
47
+ delivery: 'auto' | 'steer';
48
+ content: PromptContent;
49
+ };
50
+
51
+ /** A root before it opens: the team and main it would run with, for viewers that let the user choose first (ALPD §60). */
52
+ export type SessionPreview = {
53
+ teams: Array<{ id: string; label: string; description?: string }>;
54
+ /** The team the spec selects, else settings' workflow.mode, else Phở. */
55
+ team: string;
56
+ teamLabel?: string;
57
+ agent: string;
58
+ runtime: RuntimeKind;
59
+ model: string;
60
+ mode: string;
61
+ thinking: string;
62
+ };
63
+
64
+ /** What became of one assignment an earlier alpd left running. */
65
+ export type RecoveryOutcome = { assignmentId: string; agent: string; outcome: 'resumed' | 'parked' | 'failed'; error?: string };
66
+
67
+ export type Pause = { since: string; by: string; reason: string; resetsAt?: string; /** When alpd last asked the runtime about the limit (ALPD §58). */ checkedAt?: string };
68
+ export type PauseState = {
69
+ all?: Pause;
70
+ runtimes: Partial<Record<RuntimeKind, Pause>>;
71
+ parked: Array<{ assignmentId: string; agent: string; runtime: RuntimeKind; rootId: string; reason: string; since: string }>;
72
+ };
73
+
74
+ export type RecallAnswer = { assignmentId: string; agent: string; taskId?: string; finishedAt: string; answer: string };
75
+
76
+ /** A session's lifecycle as alpd records it; neutral, so viewers and integrations share one union. */
77
+ export type SessionStatus = 'initializing' | 'idle' | 'running' | 'error' | 'closed';
78
+
79
+ /** The last failure recorded for a session (daemon store `SessionRecord.lastError`). */
80
+ export type SessionError = { code?: string; message: string };
81
+
82
+ /**
83
+ * A session as clients list it: its last snapshot plus lifecycle (ALPD §18). This is the portable
84
+ * shape served by `session.list`; the daemon and every viewer agree on it, so it is the same type
85
+ * the daemon's store and server use rather than a lossy summary.
86
+ */
87
+ export type SessionSummary = SessionSnapshot & {
88
+ status: SessionStatus;
89
+ title?: string;
90
+ archived?: boolean;
91
+ lastError?: SessionError;
92
+ createdAt?: string;
93
+ updatedAt?: string;
94
+ };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * A dependency-free checker for the JSON Schema subset the protocol schemas use (draft-07:
3
+ * type, const, enum, properties, required, additionalProperties, items, minimum, maximum,
4
+ * minLength, maxLength, pattern, oneOf, anyOf, not and local `#/$defs/...` references).
5
+ * Lengths count Unicode code points, as JSON Schema does. A property whose value is
6
+ * `undefined` counts as absent, so in-process callers behave as their JSON would.
7
+ */
8
+
9
+ /** @typedef {{ path: string, message: string }} SchemaIssue */
10
+
11
+ const MAX_ISSUES = 8;
12
+
13
+ /** @param {unknown} value */
14
+ function typeOf(value) {
15
+ if (value === null) return 'null';
16
+ if (Array.isArray(value)) return 'array';
17
+ if (typeof value === 'number') return !Number.isFinite(value) ? 'non-finite number' : Number.isInteger(value) ? 'integer' : 'number';
18
+ return typeof value;
19
+ }
20
+
21
+ /** @param {string} want @param {string} have */
22
+ const typeMatches = (want, have) => want === have || (want === 'number' && have === 'integer');
23
+
24
+ /** @param {unknown} a @param {unknown} b @returns {boolean} */
25
+ function equal(a, b) {
26
+ if (a === b) return true;
27
+ if (typeOf(a) !== typeOf(b) || a === null || typeof a !== 'object') return false;
28
+ if (Array.isArray(a)) return a.length === /** @type {unknown[]} */ (b).length && a.every((item, index) => equal(item, /** @type {unknown[]} */ (b)[index]));
29
+ const left = Object.keys(a).filter(key => /** @type {any} */ (a)[key] !== undefined);
30
+ const right = Object.keys(/** @type {object} */ (b)).filter(key => /** @type {any} */ (b)[key] !== undefined);
31
+ return left.length === right.length && left.every(key => equal(/** @type {any} */ (a)[key], /** @type {any} */ (b)[key]));
32
+ }
33
+
34
+ /** @param {any} root @param {string} ref */
35
+ function resolve(root, ref) {
36
+ if (!ref.startsWith('#/')) throw new Error(`Unsupported schema reference ${ref}`);
37
+ let target = root;
38
+ for (const part of ref.slice(2).split('/')) target = target?.[part.replaceAll('~1', '/').replaceAll('~0', '~')];
39
+ if (target === undefined) throw new Error(`Unresolved schema reference ${ref}`);
40
+ return target;
41
+ }
42
+
43
+ /**
44
+ * @param {any} schema
45
+ * @param {unknown} value
46
+ * @param {string} at
47
+ * @param {any} root
48
+ * @param {SchemaIssue[]} issues
49
+ */
50
+ function check(schema, value, at, root, issues) {
51
+ if (issues.length >= MAX_ISSUES || schema === true || schema === undefined) return;
52
+ if (schema === false) { issues.push({ path: at, message: 'is not allowed' }); return; }
53
+ if (schema.$ref) { check(resolve(root, schema.$ref), value, at, root, issues); if (Object.keys(schema).length === 1) return; }
54
+ const kind = typeOf(value);
55
+ if (schema.type !== undefined) {
56
+ const wanted = Array.isArray(schema.type) ? schema.type : [schema.type];
57
+ if (!wanted.some(/** @param {string} want */ want => typeMatches(want, kind))) { issues.push({ path: at, message: `must be ${wanted.join(' or ')}` }); return; }
58
+ }
59
+ if ('const' in schema && !equal(schema.const, value)) { issues.push({ path: at, message: `must be ${JSON.stringify(schema.const)}` }); return; }
60
+ if (schema.enum && !schema.enum.some(/** @param {unknown} option */ option => equal(option, value))) { issues.push({ path: at, message: `must be one of ${schema.enum.map(/** @param {unknown} option */ option => JSON.stringify(option)).join(', ')}` }); return; }
61
+ if (kind === 'integer' || kind === 'number') {
62
+ const number = /** @type {number} */ (value);
63
+ if (schema.minimum !== undefined && number < schema.minimum) issues.push({ path: at, message: `must be at least ${schema.minimum}` });
64
+ if (schema.maximum !== undefined && number > schema.maximum) issues.push({ path: at, message: `must be at most ${schema.maximum}` });
65
+ }
66
+ if (kind === 'string') {
67
+ const text = /** @type {string} */ (value);
68
+ let length = 0;
69
+ if (schema.minLength !== undefined || schema.maxLength !== undefined) for (const _point of text) length++;
70
+ if (schema.minLength !== undefined && length < schema.minLength) issues.push({ path: at, message: `must have at least ${schema.minLength} characters` });
71
+ if (schema.maxLength !== undefined && length > schema.maxLength) issues.push({ path: at, message: `must have at most ${schema.maxLength} characters` });
72
+ if (schema.pattern !== undefined && !new RegExp(schema.pattern, 'u').test(text)) issues.push({ path: at, message: `must match ${schema.pattern}` });
73
+ }
74
+ if (kind === 'array' && schema.items !== undefined) {
75
+ const array = /** @type {unknown[]} */ (value);
76
+ for (let index = 0; index < array.length && issues.length < MAX_ISSUES; index++) check(schema.items, array[index] === undefined ? null : array[index], `${at}/${index}`, root, issues);
77
+ }
78
+ if (kind === 'object') {
79
+ const object = /** @type {Record<string, unknown>} */ (value);
80
+ const properties = schema.properties ?? {};
81
+ for (const name of schema.required ?? []) if (object[name] === undefined) issues.push({ path: `${at}/${name}`, message: 'is required' });
82
+ for (const [name, child] of Object.entries(object)) {
83
+ if (child === undefined) continue;
84
+ if (Object.hasOwn(properties, name)) check(properties[name], child, `${at}/${name}`, root, issues);
85
+ else if (schema.additionalProperties !== undefined) check(schema.additionalProperties, child, `${at}/${name}`, root, issues);
86
+ }
87
+ }
88
+ if (schema.not !== undefined) {
89
+ /** @type {SchemaIssue[]} */
90
+ const inner = [];
91
+ check(schema.not, value, at, root, inner);
92
+ if (!inner.length) issues.push({ path: at, message: 'matches a schema it must not match' });
93
+ }
94
+ for (const [keyword, exactlyOne] of /** @type {const} */ ([['anyOf', false], ['oneOf', true]])) {
95
+ if (!schema[keyword]) continue;
96
+ const passing = schema[keyword].filter(/** @param {any} option */ option => { /** @type {SchemaIssue[]} */ const inner = []; check(option, value, at, root, inner); return !inner.length; }).length;
97
+ if (exactlyOne ? passing !== 1 : passing === 0) issues.push({ path: at, message: exactlyOne && passing > 1 ? 'matches more than one allowed shape' : 'matches none of the allowed shapes' });
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Checks `value` against `schema`, resolving `#/$defs/...` against `root`.
103
+ * @param {any} schema
104
+ * @param {unknown} value
105
+ * @param {any} [root]
106
+ * @returns {SchemaIssue[]} empty when the value conforms
107
+ */
108
+ export function validateSchema(schema, value, root = schema) {
109
+ /** @type {SchemaIssue[]} */
110
+ const issues = [];
111
+ check(schema, value, '', root, issues);
112
+ return issues;
113
+ }
package/src/wire.js ADDED
@@ -0,0 +1,26 @@
1
+ /** Wire protocol of alpd (plans/reference/ALPD.md §3). Bump only for incompatible changes. */
2
+ export const PROTOCOL_VERSION = 1;
3
+ export const MAX_FRAME = 16 * 1024 * 1024;
4
+
5
+ export class AlpRpcError extends Error {
6
+ constructor(error) {
7
+ super(error?.message ?? 'ALP daemon request failed');
8
+ this.code = error?.code;
9
+ this.data = error?.data;
10
+ }
11
+ }
12
+
13
+ export const ERROR = Object.freeze({ failed: 1000, notFound: 1001, forbidden: 1003, conflict: 1004, unavailable: 1005, protocol: 1006 });
14
+ /** The JSON-RPC 2.0 codes alpd answers with (docs/protocol/alp-json-rpc-v1.md §5). */
15
+ export const RPC_ERROR = Object.freeze({ parseError: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602 });
16
+ /**
17
+ * Features a daemon lists in its daemon.hello result. A client uses a feature only when listed;
18
+ * a daemon that lists none (one older than this list) has none of them. Unknown names are ignored.
19
+ */
20
+ export const CAPABILITY = Object.freeze({ attachAfter: 'attach.after', promptReceipts: 'prompt.receipts', extensionMethods: 'extension.methods', team: 'team', task: 'task', library: 'library', settingsLanguage: 'settings.language' });
21
+ export const RPC_METHODS = Object.freeze(["assignment.recall", "board.list", "catalog.get", "daemon.hello", "daemon.pause", "daemon.pauses", "daemon.resume", "daemon.shutdown", "daemon.status", "daemon.usage", "extension.register", "extension.unregister", "library.delete", "library.duplicate", "library.get", "library.list", "library.models", "library.rename", "library.save", "library.skills.set", "question.answer", "question.list", "session.archive", "session.attach", "session.close", "session.configure", "session.create", "session.get", "session.interrupt", "session.list", "session.log", "session.message", "session.preview", "session.prompt", "session.release", "session.rename", "session.status", "settings.language.get", "settings.language.set", "task.create", "task.gate.resolve", "task.list", "task.update", "team.list"]);
22
+
23
+ /** UTF-8 socket writers use one newline-terminated JSON value per frame. @param {unknown} value */
24
+ export function encodeFrame(value) { return `${JSON.stringify(value)}\n`; }
25
+ /** Parse one complete frame. Buffering and failure handling belong to the socket owner. @param {string} line @returns {unknown} */
26
+ export function decodeFrame(line) { return JSON.parse(line); }