create-pmos 0.795.0 → 0.797.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.
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+ /* a2ui.js — PMOS cards as A2UI v1.0 messages, and A2UI actions read back as card-catalog commands (bet A459a, job #1751). The A2UI v1.0
3
+ * schemas are vendored in lib/a2ui-v1/ (Apache-2.0, google/A2UI, specification/v1_0/json and catalogs/basic/v1; see lib/a2ui-v1/NOTICE).
4
+ *
5
+ * validate(schema, msg) → [error] 'agent_to_renderer' | 'renderer_to_agent' | 'catalog' (a component); [] when msg is valid. A small
6
+ * JSON Schema 2020-12 reader for the keywords these schemas use, with no dependency.
7
+ * surfaceOf(kind, rows, { catalog, surfaceId }) → [message] one createSurface with its components and data model, in the basic catalog
8
+ * so a stock A2UI renderer draws it: a Card per row (title, who · due, its buttons), "<id> was not found" for a
9
+ * missing one. Buttons: the catalog's own, only those PMOS runs from here (`pmos task …`, who: you).
10
+ * readAction(msg, catalog) → { ok, kind, id, action, argv, args } | { ok: false, refused | error }
11
+ * an A2UI action (renderer_to_agent) as the `pmos` command its catalog button runs; a "waits" button refuses
12
+ * ("asks first"), an "agent" button refuses (PMOS does it itself)
13
+ * CATALOG_ID the basic catalog's id: the surfaces use only its parts */
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const DIR = path.join(__dirname, 'a2ui-v1');
18
+ const CATALOG_ID = 'https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json';
19
+ const FILES = { 'agent_to_renderer.json': 'agent_to_renderer.json', 'renderer_to_agent.json': 'renderer_to_agent.json', 'common_types.json': 'common_types.json', 'catalog.json': 'catalog.json' };
20
+ const DOCS = {};
21
+ const doc = (f) => DOCS[f] || (DOCS[f] = JSON.parse(fs.readFileSync(path.join(DIR, FILES[f]), 'utf8')));
22
+
23
+ /* ---- the schema reader ---------------------------------------------------------------------------------------------------- */
24
+ function resolve(ref, file) {
25
+ const [f, frag] = ref.split('#');
26
+ const target = f ? f : file;
27
+ if (!FILES[target]) throw new Error('unknown schema file ' + target);
28
+ let node = doc(target);
29
+ for (const p of String(frag || '').split('/').filter(Boolean)) node = node == null ? undefined : node[p.replace(/~1/g, '/').replace(/~0/g, '~')];
30
+ if (node === undefined) throw new Error('unresolved $ref ' + ref);
31
+ return { schema: node, file: target };
32
+ }
33
+ const typeOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);
34
+ const isType = (v, t) => (t === 'number' ? typeof v === 'number' : t === 'integer' ? Number.isInteger(v) : typeOf(v) === t);
35
+ const FORMATS = { date: /^\d{4}-\d{2}-\d{2}$/, time: /^\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?$/, 'date-time': /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/ };
36
+
37
+ /** → { errors: [string], seen: Set of the property names this schema evaluated (for unevaluatedProperties) } */
38
+ function check(v, s, file, at) {
39
+ const errors = [], seen = new Set();
40
+ if (s === true || s === undefined) return { errors, seen };
41
+ if (s === false) return { errors: [at + ': not allowed'], seen };
42
+ const sub = (sch, val, where, f = file) => check(val, sch, f, where);
43
+ const merge = (r) => { for (const k of r.seen) seen.add(k); };
44
+ if (s.$ref) {
45
+ const r = resolve(s.$ref, file);
46
+ const out = sub(r.schema, v, at, r.file);
47
+ errors.push(...out.errors); merge(out);
48
+ }
49
+ if (s.type) { const ts = Array.isArray(s.type) ? s.type : [s.type]; if (!ts.some((t) => isType(v, t))) errors.push(`${at}: expected ${ts.join('|')}, got ${typeOf(v)}`); }
50
+ if ('const' in s && JSON.stringify(v) !== JSON.stringify(s.const)) errors.push(`${at}: expected ${JSON.stringify(s.const)}`);
51
+ if (s.enum && !s.enum.some((e) => JSON.stringify(e) === JSON.stringify(v))) errors.push(`${at}: not one of ${s.enum.join(', ')}`);
52
+ if (typeof v === 'string') {
53
+ if (s.pattern && !new RegExp(s.pattern, 'u').test(v)) errors.push(`${at}: does not match ${s.pattern}`);
54
+ if (s.format && FORMATS[s.format] && !FORMATS[s.format].test(v)) errors.push(`${at}: not a ${s.format}`);
55
+ }
56
+ if (Array.isArray(v)) {
57
+ if (s.minItems !== undefined && v.length < s.minItems) errors.push(`${at}: fewer than ${s.minItems} items`);
58
+ if (s.items && typeof s.items === 'object') v.forEach((x, i) => errors.push(...sub(s.items, x, `${at}[${i}]`).errors));
59
+ }
60
+ const obj = typeOf(v) === 'object';
61
+ if (obj) {
62
+ const keys = Object.keys(v);
63
+ if (s.minProperties !== undefined && keys.length < s.minProperties) errors.push(`${at}: fewer than ${s.minProperties} properties`);
64
+ if (s.maxProperties !== undefined && keys.length > s.maxProperties) errors.push(`${at}: more than ${s.maxProperties} properties`);
65
+ for (const r of s.required || []) if (!(r in v)) errors.push(`${at}: missing ${r}`);
66
+ const props = s.properties || {};
67
+ for (const k of keys) {
68
+ let hit = false;
69
+ if (k in props) { hit = true; errors.push(...sub(props[k], v[k], `${at}.${k}`).errors); }
70
+ for (const [p, ps] of Object.entries(s.patternProperties || {})) if (new RegExp(p, 'u').test(k)) { hit = true; errors.push(...sub(ps, v[k], `${at}.${k}`).errors); }
71
+ if (s.propertyNames) errors.push(...sub(s.propertyNames, k, `${at}{${k}}`).errors);
72
+ if (hit) seen.add(k);
73
+ else if (s.additionalProperties !== undefined) {
74
+ seen.add(k);
75
+ if (s.additionalProperties === false) errors.push(`${at}: unexpected property ${k}`);
76
+ else errors.push(...sub(s.additionalProperties, v[k], `${at}.${k}`).errors);
77
+ }
78
+ }
79
+ }
80
+ if (s.allOf) for (const x of s.allOf) { const r = sub(x, v, at); errors.push(...r.errors); merge(r); }
81
+ if (s.anyOf) {
82
+ const rs = s.anyOf.map((x) => sub(x, v, at)), good = rs.filter((r) => !r.errors.length);
83
+ if (!good.length) errors.push(`${at}: matches none of anyOf (${rs.map((r) => r.errors[0]).join(' / ')})`); else good.forEach(merge);
84
+ }
85
+ if (s.oneOf) {
86
+ const rs = s.oneOf.map((x) => sub(x, v, at)), good = rs.filter((r) => !r.errors.length);
87
+ if (good.length !== 1) errors.push(`${at}: matches ${good.length} of oneOf${good.length ? '' : ' (' + rs.map((r) => r.errors[0]).slice(0, 4).join(' / ') + ')'}`); else merge(good[0]);
88
+ }
89
+ if (s.not && !sub(s.not, v, at).errors.length) errors.push(`${at}: matches a "not" schema`);
90
+ if (s.if) {
91
+ const ok = !sub(s.if, v, at).errors.length;
92
+ const branch = ok ? s.then : s.else;
93
+ if (branch) { const r = sub(branch, v, at); errors.push(...r.errors); merge(r); }
94
+ }
95
+ if (obj && s.unevaluatedProperties === false) for (const k of Object.keys(v)) if (!seen.has(k)) errors.push(`${at}: unevaluated property ${k}`);
96
+ if (obj && s.unevaluatedProperties === false) for (const k of Object.keys(v)) seen.add(k);
97
+ return { errors, seen };
98
+ }
99
+
100
+ function validate(name, msg) {
101
+ const file = name === 'catalog' ? 'catalog.json' : name + '.json';
102
+ const root = name === 'catalog' ? { $ref: 'agent_to_renderer.json#/$defs/Component' } : doc(file);
103
+ try { return check(msg, root, name === 'catalog' ? 'agent_to_renderer.json' : file, '$').errors; } catch (e) { return ['schema: ' + e.message]; }
104
+ }
105
+
106
+ /* ---- PMOS rows as a surface ----------------------------------------------------------------------------------------------- */
107
+ const DOW = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
108
+ const dayText = (d) => { if (!/^\d{4}-\d{2}-\d{2}$/.test(String(d || ''))) return ''; const t = new Date(d + 'T00:00:00Z'); return `${DOW[t.getUTCDay()]} ${t.getUTCDate()} ${MON[t.getUTCMonth()]}`; };
109
+ const metaOf = (r) => [r.who || (r.kind === 'initiative' ? '' : 'No owner'), r.due ? 'due ' + dayText(r.due) : '', r.state && r.state !== 'To do' ? r.state : '', r.stage || ''].filter(Boolean).join(' · ');
110
+
111
+ const actionsOf = (catalog, kind) => { for (const g of (catalog && catalog.groups) || []) for (const k of g.kinds || []) if (k.id === kind) return k.actions || []; return []; };
112
+ const cmdOf = (run) => { const w = String(run || '').trim().split(/\s+/); return w[0] === 'pmos' && w[1] ? { verb: w[1], sub: w[2] && !w[2].startsWith('<') && !w[2].startsWith('-') ? w[2] : '' } : null; };
113
+ /** The buttons a surface carries: the kind's catalog buttons PMOS runs itself from here (`pmos task …`), with no value or one date. */
114
+ function buttonsOf(catalog, kind) {
115
+ return actionsOf(catalog, kind).filter((a) => a.who === 'you' && (!a.field || a.field === 'date') && cmdOf(a.run) && cmdOf(a.run).verb === 'task' && !/<text>/.test(a.run));
116
+ }
117
+
118
+ let seq = 0;
119
+ function surfaceOf(kind, rows, { catalog, surfaceId } = {}) {
120
+ const sid = surfaceId || `pmos-${kind}-${Date.now().toString(36)}-${(++seq).toString(36)}`;
121
+ const comps = [], cards = [], data = { rows: [] };
122
+ const text = (id, t, variant) => { comps.push({ id, component: 'Text', text: t, ...(variant ? { variant } : {}) }); return id; };
123
+ const btns = buttonsOf(catalog, kind);
124
+ rows.forEach((r, i) => {
125
+ if (!r || r.found === false) { cards.push(text(`miss_${i}`, `${(r && r.id) || 'This id'} was not found. It may have been closed.`, 'caption')); return; }
126
+ data.rows.push({ id: r.id, title: r.title, meta: metaOf(r), due: r.due || '' });
127
+ const at = data.rows.length - 1, p = `/rows/${at}`;
128
+ const kids = [text(`title_${i}`, { '@path': p + '/title' }), text(`meta_${i}`, { '@path': p + '/meta' }, 'caption')];
129
+ const acts = [];
130
+ for (const [k, a] of btns.entries()) {
131
+ if (a.field === 'date') {
132
+ comps.push({ id: `date_${i}_${k}`, component: 'DateTimeInput', value: { '@path': p + '/due' }, enableDate: true, label: 'New due' });
133
+ acts.push(`date_${i}_${k}`);
134
+ }
135
+ text(`btn_${i}_${k}_l`, a.label);
136
+ comps.push({ id: `btn_${i}_${k}`, component: 'Button', child: `btn_${i}_${k}_l`, ...(k === 0 ? { variant: 'primary' } : {}),
137
+ action: { event: { name: a.label, context: { kind, id: r.id, ...(a.field === 'date' ? { date: { '@path': p + '/due' } } : {}) } } } });
138
+ acts.push(`btn_${i}_${k}`);
139
+ }
140
+ if (acts.length) { comps.push({ id: `acts_${i}`, component: 'Row', children: acts, align: 'center' }); kids.push(`acts_${i}`); }
141
+ comps.push({ id: `col_${i}`, component: 'Column', children: kids });
142
+ comps.push({ id: `card_${i}`, component: 'Card', child: `col_${i}` });
143
+ cards.push(`card_${i}`);
144
+ });
145
+ comps.unshift({ id: 'root', component: 'Column', children: cards.length ? cards : [text('empty', 'Nothing to show.', 'caption')] });
146
+ return [{ version: '1.0', createSurface: { surfaceId: sid, catalogId: CATALOG_ID, components: comps, dataModel: data } }];
147
+ }
148
+
149
+ /** An A2UI action back as the catalog command it names. Only a button surfaceOf drew can come back: its label on that kind. */
150
+ function readAction(msg, catalog) {
151
+ const errs = validate('renderer_to_agent', msg);
152
+ if (errs.length) return { ok: false, error: 'Not an A2UI v1.0 action: ' + errs[0] };
153
+ if (!msg.action) return { ok: false, error: 'Only an action is taken here.' };
154
+ const c = msg.action.context || {};
155
+ const kind = typeof c.kind === 'string' ? c.kind : '', id = typeof c.id === 'string' ? c.id.trim() : '';
156
+ if (!kind || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$/.test(id)) return { ok: false, error: 'The action names no card (context.kind and context.id).' };
157
+ const act = actionsOf(catalog, kind).find((a) => a.label === msg.action.name);
158
+ if (!act) return { ok: false, error: `"${msg.action.name}" is not a button of a ${kind} card.` };
159
+ if (act.who === 'waits') return { ok: false, refused: true, error: `"${act.label}" asks first: the PM says yes on the PMOS page. Nothing changed.` };
160
+ if (act.who === 'agent') return { ok: false, refused: true, error: `"${act.label}" is done by PMOS itself. Nothing changed.` };
161
+ if (!buttonsOf(catalog, kind).includes(act)) return { ok: false, refused: true, error: `"${act.label}" is not run from here yet. Nothing changed.` };
162
+ const date = typeof c.date === 'string' ? c.date.slice(0, 10) : '';
163
+ const words = String(act.run).trim().match(/"[^"]*"|<[^>]*>|\S+/g).slice(1);
164
+ const argv = [];
165
+ for (const w of words) {
166
+ if (w === '<id>' || w === '<task>') argv.push(id);
167
+ else if (w === '<date>') { if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return { ok: false, error: `"${act.label}" needs a day (context.date, YYYY-MM-DD).` }; argv.push(date); }
168
+ else if (/^<.*>$/.test(w)) return { ok: false, error: `"${act.label}" needs ${w}.` };
169
+ else argv.push(w);
170
+ }
171
+ return { ok: true, kind, id, action: act, argv, args: { date } };
172
+ }
173
+
174
+ module.exports = { CATALOG_ID, validate, surfaceOf, readAction, buttonsOf, metaOf };
@@ -193,6 +193,8 @@ function chatSessionOf(runtimeDir, key) {
193
193
  const ASK_RULES = [
194
194
  // ask-cards-and-pickers (canvas A2Cards, A2Ask): the page draws the named rows live with the card catalog's buttons, and a picker that runs one catalog command (public/pm/chat-cards.js)
195
195
  'When your answer names tasks or initiatives the PM may act on, add one fenced code block with the language tag pmos-card holding one JSON object: {"kind":"task","ids":["<task id>","<task id>"],"title":"This sprint · ends Sat 6 Dec","total":7} (kind: task, subtask, milestone or initiative; the real ids from pmos task list or the records, the most important first; total: how many the whole list holds). The page draws those rows live with their buttons, so do not repeat each row in your words: say what matters in one or two sentences. When one change would help and the PM must choose a value, add one fenced pmos-pick block instead of asking in words: {"kind":"task","id":"<task id>","action":"Move the date","question":"Move Payment API so the launch holds?","why":"4 days late","fields":[{"flag":"due","options":[{"value":"2026-12-03","label":"Wed 3 Dec"},{"value":"2026-12-05","label":"Fri 5 Dec"}],"recommended":0},{"flag":"owner","options":[{"value":"Dana Lee"},{"value":"Priya Shah"}],"recommended":0}],"after":"The launch moves to Fri 5 Dec"} (action: a button label of the card catalog for that kind; at most 2 fields, each a flag that command takes; 2 to 4 options, the one you recommend in recommended). One press runs it with Undo; nothing else is needed from you.',
196
+ // a2ui-inbound-render: another agent's A2UI v1.0 surface (public/pm/a2ui-view.js) is drawn only from an a2ui block, never from a tool result's words
197
+ 'When a tool you call returns A2UI v1.0 messages (JSON lines with "version":"1.0" and createSurface, updateComponents or updateDataModel) for the PM to see, put them unchanged in one fenced code block with the language tag a2ui, after your words. Do not write A2UI yourself and do not change the lines. When the PM presses a button on it, their next message holds the A2UI action as JSON: pass that action to the same tool (for pmos mcp, pmos_action) and say what it answered.',
196
198
  'When you need the PM to judge a done point you cannot check yourself, or you cannot reach something you need (a sign-in expired, a file), end your message with one fenced code block with the language tag pmos-ask holding one JSON object: {"kind":"judge","point":"the done point","question":"Is the draft ready for Dita?"} or {"kind":"reach","what":"Jira","why":"sign-in expired","need":"signin"} (need: signin, file or both). The page draws it as a card with the PM\'s answers.',
197
199
  'When the PM asks you to chase people for a reply, end each message about it with one fenced pmos-chase block: {"state":"chasing","what":"Sign-off on the PRD","next":"ISO 8601 time of the next nudge","people":[{"name":"Dita","status":"signed off","note":"Fri 16:40, in Slack","replied":true},{"name":"Raj","status":"asked twice","note":"last nudge Fri 10:00, no reply"}]}. Set state to done when everyone replied, and to stopped when the PM says stop.',
198
200
  ];
@@ -3,8 +3,10 @@
3
3
  * routes-slash.js beside #1746's routes, so it is not named routes-*.js (d86-seams 7: every routes-*.js is a route-modules entry).
4
4
  *
5
5
  * GET /api/card-rows?ws=<id>&kind=task|subtask|milestone|initiative&ids=a,b,c
6
- * → { ok, rows: [{ id, kind, found, title, who, due, start, state, board, initiative, stage }] } at most 5 ids; an id that is not
7
- * on a board of the workspace comes back { id, found: false }
6
+ * → { ok, rows: [{ id, kind, found, title, who, due, start, state, board, initiative, stage, rank? }] } at most 5 ids; an id that is
7
+ * not on a board of the workspace comes back { id, found: false }
8
+ * rank (initiative rows on the Roadmap, job #1818): { up?, down?, back } — the initiative each move ranks it right after (null = the
9
+ * top), as `pmos initiative up|down` computes it; `up` is left out at the top and `down` at the end; `back` is where it is now (Undo)
8
10
  *
9
11
  * Read only. The chat draws these rows with the card catalog's buttons (public/pm/chat-cards.js); a button writes through the page's own
10
12
  * routes (public/pm/action-run.js), never this one. */
@@ -24,13 +26,35 @@ function taskRows(ctx, w, ids) {
24
26
  return ids.map((id) => {
25
27
  const t = B.taskOf(folded, id);
26
28
  if (!t) return { id, found: false };
27
- return { id, kind: t.milestone ? 'milestone' : t.parent ? 'subtask' : 'task', found: true, title: t.title || id, who: whoOf(t.owner), due: day(t.due),
29
+ // the PM's milestone flag is a ledger line of its own (scripts/boards.js task-milestone), folded into `milestones`, not a task field
30
+ const ms = (folded.milestones && folded.milestones.get(id) === true) || t.milestone === true;
31
+ return { id, kind: ms ? 'milestone' : t.parent ? 'subtask' : 'task', found: true, title: t.title || id, who: whoOf(t.owner), due: day(t.due),
28
32
  start: day(t.start), state: t.state || 'To do', board: t.board || null, initiative: t.initiative || null };
29
33
  });
30
34
  }
31
35
 
36
+ /** The one Roadmap order (D105), read as `pmos initiative up|down` reads it. [] when it cannot be read: the rows then draw no move. */
37
+ function rankedOf(root) {
38
+ try {
39
+ const d = require('./initiative-rows.js').deriveSync(root);
40
+ if (!d.ok) return [];
41
+ const placed = require('./placements.js').readPlacements(root, { now: Date.now(), rules: require('./plan-rules.js').readRules(root), records: d.rows });
42
+ return Array.isArray(placed.ranked) ? placed.ranked : [];
43
+ } catch { return []; }
44
+ }
45
+ /** Where Move up and Move down put an initiative: the id it then comes right after (null = the top). PURE */
46
+ function rankOf(list, id) {
47
+ const i = list.indexOf(id);
48
+ if (i < 0) return null;
49
+ const r = { back: i > 0 ? list[i - 1] : null };
50
+ if (i > 0) r.up = i === 1 ? null : list[i - 2];
51
+ if (i < list.length - 1) r.down = list[i + 1];
52
+ return r;
53
+ }
54
+
32
55
  function initiativeRows(ctx, w, ids) {
33
56
  const boards = require('./routes-boards.js');
57
+ let list = null;
34
58
  return ids.map((id) => {
35
59
  let r = boards.initiativeWorkflow(ctx, w, id);
36
60
  // the rows are still being derived (a fresh process): derive them now, as `pmos task` does
@@ -39,7 +63,8 @@ function initiativeRows(ctx, w, ids) {
39
63
  const row = r.row;
40
64
  const stage = row.stageName || (row.wf && row.wf.stage && row.wf.stage.name) || row.stage || '';
41
65
  return { id, kind: 'initiative', found: true, title: row.title || id, who: row.owner || '', due: day(row.due || row.target || ''), state: row.state || '',
42
- stage: typeof stage === 'string' ? stage : '', board: (r.board && r.board.id) || null, initiative: id };
66
+ stage: typeof stage === 'string' ? stage : '', board: (r.board && r.board.id) || null, initiative: id,
67
+ ...(() => { if (!list) list = rankedOf(w.root); const k = rankOf(list, id); return k ? { rank: k } : {}; })() };
43
68
  });
44
69
  }
45
70
 
@@ -60,5 +85,6 @@ module.exports = {
60
85
  return true;
61
86
  },
62
87
  taskRows,
88
+ rankOf,
63
89
  initiativeRows,
64
90
  };
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+ /* mcp-cli.js — `pmos mcp`: PMOS cards for another agent, as A2UI v1.0 over MCP (bet A459a, job #1751). WAITS FOR WAWAN'S FINAL YES:
3
+ * a new public API, so its pull request stays out of auto-merge until he says yes.
4
+ *
5
+ * pmos mcp [--root <repo>] an MCP server on stdin and stdout (JSON-RPC 2.0, one message per line; no dependency). Tools:
6
+ * pmos_catalog the card catalog as an A2UI catalog: its catalogId, and per kind the part and the functions (its buttons)
7
+ * pmos_card { kind, ids } the rows of those ids (task, subtask, milestone or initiative; at most 5) as A2UI JSONL: one createSurface
8
+ * in the basic catalog, so a stock A2UI renderer draws it (lib/a2ui.js surfaceOf)
9
+ * pmos_action { action } an A2UI v1.0 action message (renderer_to_agent) from a surface pmos_card drew: runs the `pmos task …`
10
+ * command its button names, and answers what changed and the Undo line. A button that asks first, or one
11
+ * PMOS does itself, refuses and changes nothing.
12
+ *
13
+ * A write is attributed from the call path, like every `pmos task` call (lib/actor.js). Nothing is sent anywhere: the server answers the
14
+ * agent that started it, on its own stdout. Exit codes: 0 when stdin closes, 2 usage. */
15
+ const path = require('path');
16
+ const readline = require('readline');
17
+ const { execFileSync } = require('child_process');
18
+ const driver = require('./driver.js');
19
+ const A = require('./a2ui.js');
20
+ const CC = require('./card-catalog.js');
21
+
22
+ const COMMANDS = { mcp: [] };
23
+ const USAGE = 'pmos mcp [--root <repo>] — PMOS cards for another agent, as A2UI v1.0 over MCP (stdio)';
24
+ const PROTOCOL = '2025-06-18';
25
+ const KINDS = ['task', 'subtask', 'milestone', 'initiative'];
26
+
27
+ const TOOLS = [
28
+ { name: 'pmos_catalog', description: 'The PMOS card catalog as an A2UI v1.0 catalog: the catalogId the cards use, and for each kind of card its part and its buttons (functions), with who acts: you (runs at once, with Undo), agent (PMOS does it) or waits (asks the PM first).',
29
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false } },
30
+ { name: 'pmos_card', description: 'Live PMOS rows as an A2UI v1.0 surface (JSONL, one message per line, basic catalog): a card per row with its title, owner and due day, and the catalog buttons that run from here. Example: {"kind":"task","ids":["task-1a2b3c4d5e"]}. An id that is not on a board comes back as "<id> was not found".',
31
+ inputSchema: { type: 'object', properties: { kind: { type: 'string', enum: KINDS }, ids: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 5 } }, required: ['kind', 'ids'], additionalProperties: false } },
32
+ { name: 'pmos_action', description: 'Run the button a user pressed on a surface from pmos_card: pass the A2UI v1.0 action message the renderer sent ({"version":"1.0","action":{name, surfaceId, sourceComponentId, timestamp, context}}). It runs the pmos command that button names and answers the Undo line. A button that asks first refuses and changes nothing.',
33
+ inputSchema: { type: 'object', properties: { action: { type: 'object' } }, required: ['action'], additionalProperties: false } },
34
+ ];
35
+
36
+ function repoRoot(cwd) {
37
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || cwd; } catch { return cwd; }
38
+ }
39
+
40
+ /** The tools, given a repository root; the server below only moves JSON-RPC lines to and from these. */
41
+ function tools(root, { env = process.env } = {}) {
42
+ const catalog = CC.load();
43
+ const ctxOf = () => {
44
+ const stateDir = driver.stateDirOf(root, { create: false });
45
+ const w = { id: driver.wsIdOf(root), name: path.basename(root), root };
46
+ return { w, ctx: { getWs: () => w, workspaceList: () => [w], stateDirFor: () => stateDir, selfRoot: path.resolve(__dirname, '..', '..') }, stateDir };
47
+ };
48
+ const rowsOf = (kind, ids) => {
49
+ const { w, ctx, stateDir } = ctxOf();
50
+ if (!stateDir) return ids.map((id) => ({ id, found: false }));
51
+ const R = require('./card-rows-route.js');
52
+ return kind === 'initiative' ? R.initiativeRows(ctx, w, ids) : R.taskRows(ctx, w, ids);
53
+ };
54
+ return {
55
+ pmos_catalog() {
56
+ const kinds = {};
57
+ for (const g of catalog.groups || []) for (const k of g.kinds || []) {
58
+ kinds[k.id] = { group: g.id, name: k.name, part: k.part, functions: (k.actions || []).filter((a) => /^pmos /.test(a.run || '')).map((a) => ({ name: a.label, run: a.run, field: a.field || null, who: a.who || 'you' })) };
59
+ }
60
+ return { ok: true, text: JSON.stringify({ catalogId: A.CATALOG_ID, pmosCatalogVersion: catalog.version, kinds }) };
61
+ },
62
+ pmos_card(args) {
63
+ const kind = args && args.kind, ids = Array.isArray(args && args.ids) ? args.ids.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()).slice(0, 5) : [];
64
+ if (!KINDS.includes(kind) || !ids.length) return { ok: false, text: 'kind is one of ' + KINDS.join(', ') + ', and ids names 1 to 5 ids.' };
65
+ const msgs = A.surfaceOf(kind, rowsOf(kind, ids), { catalog });
66
+ return { ok: true, text: msgs.map((m) => JSON.stringify(m)).join('\n') };
67
+ },
68
+ async pmos_action(args) {
69
+ const r = A.readAction(args && args.action, catalog);
70
+ if (!r.ok) return { ok: false, text: r.error };
71
+ const [before] = rowsOf(r.kind, [r.id]);
72
+ if (!before || before.found === false) return { ok: false, text: `${r.id} was not found. Nothing changed.` };
73
+ const out = [];
74
+ const code = await require('./task-cli.js').run([...r.argv, '--root', root], { say: (x) => out.push(String(x)), isTTY: false, env });
75
+ if (code !== 0) return { ok: false, text: out.join('\n') || 'The command was refused. Nothing changed.' };
76
+ const sub = r.argv[1];
77
+ const undo = sub === 'state' ? `pmos task state ${r.id} --to "${before.state || 'To do'}"`
78
+ : r.argv.includes('--due') ? `pmos task set ${r.id} --due ${before.due || 'none'}`
79
+ : r.argv.includes('--milestone') ? `pmos task set ${r.id} --no-milestone`
80
+ : r.argv.includes('--pin') ? `pmos task set ${r.id} --pin-default` : '';
81
+ const [after] = rowsOf(r.kind, [r.id]);
82
+ return { ok: true, text: [`✓ ${r.action.label}: ${before.title}.`, ...(undo ? [`Undo: ${undo}`] : []), JSON.stringify({ row: after })].join('\n') };
83
+ },
84
+ };
85
+ }
86
+
87
+ /** One JSON-RPC request → its answer (null for a notification). */
88
+ async function answer(T, msg) {
89
+ const id = msg && msg.id !== undefined ? msg.id : null;
90
+ const reply = (result) => (id === null ? null : { jsonrpc: '2.0', id, result });
91
+ const fail = (code, message) => (id === null ? null : { jsonrpc: '2.0', id, error: { code, message } });
92
+ if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') return fail(-32600, 'Invalid request');
93
+ switch (msg.method) {
94
+ case 'initialize': return reply({ protocolVersion: (msg.params && msg.params.protocolVersion) || PROTOCOL, capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'pmos', version: '1.0.0' },
95
+ instructions: 'PMOS cards as A2UI v1.0. Call pmos_card with a kind and ids to get a surface; pass a user\'s button press back to pmos_action. Buttons that ask first never run from here.' });
96
+ case 'notifications/initialized': case 'notifications/cancelled': return null;
97
+ case 'ping': return reply({});
98
+ case 'tools/list': return reply({ tools: TOOLS });
99
+ case 'tools/call': {
100
+ const name = msg.params && msg.params.name;
101
+ if (!T[name]) return fail(-32602, 'Unknown tool ' + name);
102
+ let r;
103
+ try { r = await T[name]((msg.params && msg.params.arguments) || {}); } catch (e) { r = { ok: false, text: 'The tool failed: ' + String((e && e.message) || e).slice(0, 200) }; }
104
+ return reply({ content: [{ type: 'text', text: r.text }], isError: !r.ok });
105
+ }
106
+ default: return fail(-32601, 'Method not found: ' + msg.method);
107
+ }
108
+ }
109
+
110
+ async function run(argv, { say = (s) => process.stdout.write(s + '\n'), cwd = process.cwd(), input = process.stdin, env = process.env } = {}) {
111
+ const args = argv[0] === 'mcp' ? argv.slice(1) : argv.slice();
112
+ if (args[0] === 'help' || args[0] === '--help') { say(USAGE); return 0; }
113
+ let root = null;
114
+ for (let i = 0; i < args.length; i++) {
115
+ if (args[i] === '--root' && args[i + 1]) { root = path.resolve(cwd, args[++i]); continue; }
116
+ say(`usage: ${USAGE}`); return 2;
117
+ }
118
+ const T = tools(root || repoRoot(cwd), { env });
119
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
120
+ for await (const line of rl) {
121
+ if (!line.trim()) continue;
122
+ let msg; try { msg = JSON.parse(line); } catch { say(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })); continue; }
123
+ const out = await answer(T, msg);
124
+ if (out) say(JSON.stringify(out));
125
+ }
126
+ return 0;
127
+ }
128
+
129
+ module.exports = { run, COMMANDS, USAGE, TOOLS, tools, answer };
@@ -224,6 +224,9 @@ const VERBS = Object.freeze({
224
224
  help: 'pmos signal add|remove|list|count — the customer signals behind each roadmap item; Work shows the count (pmos signal help)' }),
225
225
  launcher: Object.freeze({ module: 'launcher-cli.js', run: null, guide: 'cli.md',
226
226
  help: 'pmos launcher on|off|status — a PMOS app and a login item, so the workspace starts without a terminal' }),
227
+ // bet A459a (job #1751): a new public API, held out of auto-merge until Wawan's final yes
228
+ mcp: Object.freeze({ module: 'mcp-cli.js', run: null, guide: 'cli.md',
229
+ help: 'pmos mcp [--root <repo>] — PMOS cards for another agent, as A2UI v1.0 over MCP (stdio)' }),
227
230
  });
228
231
 
229
232
  const has = (verb) => typeof verb === 'string' && Object.prototype.hasOwnProperty.call(VERBS, verb);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.795.0",
3
+ "version": "0.797.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.795.0",
9
+ "version": "0.797.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.795.0",
3
+ "version": "0.797.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",