create-pmos 0.796.0 → 0.798.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +40 -57
- package/payload/KIT-VERSION +1 -1
- package/payload/planning/evals/eval-calibration.md +1 -1
- package/payload/planning/okrs/health-budgets.md +1 -1
- package/payload/scripts/factory-guardrail.js +65 -4
- package/payload/state/discoveries.md +1 -1
- package/workspace/changelog.json +39 -10
- package/workspace/guide/cli.md +11 -0
- package/workspace/guide/home.md +1 -0
- package/workspace/guide/layout.md +1 -1
- package/workspace/lib/a2ui-v1/NOTICE +4 -0
- package/workspace/lib/a2ui-v1/agent_to_renderer.json +220 -0
- package/workspace/lib/a2ui-v1/catalog.json +1206 -0
- package/workspace/lib/a2ui-v1/common_types.json +391 -0
- package/workspace/lib/a2ui-v1/renderer_to_agent.json +161 -0
- package/workspace/lib/a2ui.js +174 -0
- package/workspace/lib/briefing-premium-agent.js +2 -0
- package/workspace/lib/mcp-cli.js +129 -0
- package/workspace/lib/pmos-verbs.js +3 -0
- package/workspace/package-lock.json +2 -2
- package/workspace/package.json +1 -1
- package/workspace/public/pm/a2ui-view.js +230 -0
- package/workspace/public/pm/cozy-home.css +13 -0
- package/workspace/public/pm/cozy-pop-work.js +14 -15
- package/workspace/public/pm/home-chat.js +10 -4
- package/workspace/public/pm/status-edit.js +30 -0
- package/workspace/test-lists/a2ui-inbound-render.json +9 -0
- package/workspace/test-lists/a2ui-mcp-outbound.json +9 -0
|
@@ -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
|
];
|
|
@@ -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.
|
|
3
|
+
"version": "0.798.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pmos-workspace",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.798.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@anthropic-ai/sdk": "^1.3.0",
|
package/workspace/package.json
CHANGED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/* pm/a2ui-view.js — another agent's A2UI v1.0 surface, drawn in the chat with PMOS's own parts (bet A459b, job #1752). WAITS FOR WAWAN'S
|
|
2
|
+
* FINAL YES: a new agent path that draws untrusted input, so its pull request stays out of auto-merge until he says yes.
|
|
3
|
+
*
|
|
4
|
+
* A connected agent's answer carries A2UI messages (JSONL) in one fenced `a2ui` block. The page builds the surface from them and draws
|
|
5
|
+
* the basic catalog's parts with the chat's own classes: never the sender's styles, markup or code. A press on a Button goes back to
|
|
6
|
+
* that same chat session as the A2UI action message, in words; it writes no PMOS record.
|
|
7
|
+
*
|
|
8
|
+
* split(text) → { text, blocks: [jsonl] } the words without the a2ui blocks PURE
|
|
9
|
+
* build(jsonl) → { ok, surfaces: [{ id, components: Map, data }] } | { ok: false, why } the messages applied in order PURE
|
|
10
|
+
* viewHtml(surface, o) → the surface as HTML, or the one plain line when it cannot be shown PURE
|
|
11
|
+
* actionOf(surface, componentId, at) → the A2UI v1.0 renderer_to_agent action message for a press PURE
|
|
12
|
+
* a2uiUi({ send, redraw }) → { split, html(blocks, key, o), owns(button), press(button) → boolean, input(el) → boolean }
|
|
13
|
+
*
|
|
14
|
+
* WHAT IS REFUSED (the whole surface shows one line, "PMOS can't show this surface"): a component outside the basic catalog, a property
|
|
15
|
+
* the catalog does not define, a function call (code that runs in the renderer), a local action (such as openUrl), an Image from an
|
|
16
|
+
* outside address (only the image bytes the agent sent, as a data address, are drawn), text that holds markup or a script, and more than MAX_COMPONENTS parts. Video, AudioPlayer and Modal show as one
|
|
17
|
+
* plain line each that names them, never as a player or an outside link. */
|
|
18
|
+
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
19
|
+
|
|
20
|
+
export const MAX_COMPONENTS = 200;
|
|
21
|
+
export const CANT = "PMOS can't show this surface. The agent's words stay above.";
|
|
22
|
+
const COMMON = ['id', 'component', '@catalogId', '@accessibility', 'weight'];
|
|
23
|
+
// the basic catalog's parts and the properties each one may carry (lib/a2ui-v1/catalog.json)
|
|
24
|
+
export const PARTS = {
|
|
25
|
+
Text: ['text', 'variant'], Image: ['url', 'description', 'fit', 'variant'], Icon: ['name'], Video: ['url', 'posterUrl'], AudioPlayer: ['url', 'description'],
|
|
26
|
+
Row: ['children', 'justify', 'align'], Column: ['children', 'justify', 'align'], List: ['children', 'direction', 'align'], Card: ['child'],
|
|
27
|
+
Tabs: ['tabs'], Modal: ['trigger', 'content'], Divider: ['axis'], Button: ['child', 'variant', 'action', '@checks'],
|
|
28
|
+
TextField: ['label', 'value', 'placeholder', 'variant', '@checks'], CheckBox: ['label', 'value', '@checks'],
|
|
29
|
+
ChoicePicker: ['label', 'options', 'value', 'variant', 'displayStyle', 'filterable', '@checks'], Slider: ['label', 'value', 'min', 'max', 'steps', '@checks'],
|
|
30
|
+
DateTimeInput: ['value', 'enableDate', 'enableTime', 'min', 'max', 'label', '@checks'],
|
|
31
|
+
};
|
|
32
|
+
const MARKUP = /<\s*\/?\s*[a-z!]|javascript:|data:text\/html|(^|[\s"'])on[a-z]+\s*=/i;
|
|
33
|
+
const BLOCK = /```a2ui[ \t]*\n?([\s\S]*?)```/g;
|
|
34
|
+
|
|
35
|
+
export function split(text) {
|
|
36
|
+
const blocks = [];
|
|
37
|
+
const rest = String(text == null ? '' : text).replace(BLOCK, (all, body) => { blocks.push(body); return ''; });
|
|
38
|
+
return { text: blocks.length ? rest.replace(/\n{3,}/g, '\n\n').trim() : rest, blocks };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Why a value cannot be shown, or '' when it can: markup or a script in any string, or a function call anywhere. */
|
|
42
|
+
function badValue(v, depth = 0) {
|
|
43
|
+
if (depth > 12) return 'too deep';
|
|
44
|
+
if (typeof v === 'string') return MARKUP.test(v) ? 'markup in text' : '';
|
|
45
|
+
if (Array.isArray(v)) { for (const x of v) { const b = badValue(x, depth + 1); if (b) return b; } return ''; }
|
|
46
|
+
if (v && typeof v === 'object') {
|
|
47
|
+
if ('call' in v || '@call' in v) return 'a function call';
|
|
48
|
+
for (const [k, x] of Object.entries(v)) { if (MARKUP.test(k)) return 'markup in a key'; const b = badValue(x, depth + 1); if (b) return b; }
|
|
49
|
+
}
|
|
50
|
+
return '';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function checkComponent(c) {
|
|
54
|
+
if (!c || typeof c !== 'object' || typeof c.id !== 'string' || !c.id) return 'a part with no id';
|
|
55
|
+
const allowed = PARTS[c.component];
|
|
56
|
+
if (!allowed) return `an unknown part (${String(c.component).slice(0, 40)})`;
|
|
57
|
+
for (const k of Object.keys(c)) if (!COMMON.includes(k) && !allowed.includes(k)) return `an unknown property ${k} on ${c.component}`;
|
|
58
|
+
const b = badValue(c); if (b) return b;
|
|
59
|
+
// an image is drawn only from the bytes the agent sent (a PNG, JPEG, GIF or WebP data address): never fetched from an address, not even
|
|
60
|
+
// this server's own, so a surface can make no request
|
|
61
|
+
if (c.component === 'Image' && !(typeof c.url === 'string' && /^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/=]+$/.test(c.url))) return 'an image from an outside address';
|
|
62
|
+
if (c.component === 'Button') {
|
|
63
|
+
const a = c.action;
|
|
64
|
+
if (!a || typeof a !== 'object' || !a.event || typeof a.event.name !== 'string') return 'a button that runs something in the page';
|
|
65
|
+
for (const k of Object.keys(a)) if (k !== 'event') return 'a button that runs something in the page';
|
|
66
|
+
}
|
|
67
|
+
return '';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The messages applied in order. A message that is not A2UI v1.0, or a part that is refused, refuses the whole surface. */
|
|
71
|
+
export function build(jsonl) {
|
|
72
|
+
const lines = String(jsonl || '').split('\n').map((l) => l.trim()).filter(Boolean);
|
|
73
|
+
if (!lines.length) return { ok: false, why: 'no messages' };
|
|
74
|
+
const surfaces = new Map(), refused = new Map();
|
|
75
|
+
for (const line of lines) {
|
|
76
|
+
let m; try { m = JSON.parse(line); } catch { return { ok: false, why: 'a line that is not JSON' }; }
|
|
77
|
+
if (!m || m.version !== '1.0') return { ok: false, why: 'not A2UI v1.0' };
|
|
78
|
+
const keys = Object.keys(m).filter((k) => k !== 'version');
|
|
79
|
+
if (keys.length !== 1) return { ok: false, why: 'a message with ' + keys.length + ' parts' };
|
|
80
|
+
const kind = keys[0], body = m[kind] || {};
|
|
81
|
+
const sid = typeof body.surfaceId === 'string' ? body.surfaceId : '';
|
|
82
|
+
if (!sid) return { ok: false, why: 'a message with no surfaceId' };
|
|
83
|
+
if (kind === 'createSurface') {
|
|
84
|
+
if (surfaces.has(sid)) return { ok: false, why: 'a surface created twice' };
|
|
85
|
+
surfaces.set(sid, { id: sid, catalogId: body.catalogId || '', components: new Map(), data: {} });
|
|
86
|
+
if (body.components) { const r = addComponents(surfaces.get(sid), body.components); if (r) refused.set(sid, r); }
|
|
87
|
+
if (body.dataModel !== undefined) { const b = badValue(body.dataModel); if (b) refused.set(sid, b); else surfaces.get(sid).data = clone(body.dataModel); }
|
|
88
|
+
} else if (kind === 'updateComponents') {
|
|
89
|
+
const s = surfaces.get(sid); if (!s) return { ok: false, why: 'an update before its surface' };
|
|
90
|
+
const r = addComponents(s, body.components); if (r) refused.set(sid, r);
|
|
91
|
+
} else if (kind === 'updateDataModel') {
|
|
92
|
+
const s = surfaces.get(sid); if (!s) return { ok: false, why: 'an update before its surface' };
|
|
93
|
+
const b = badValue(body.value); if (b) { refused.set(sid, b); continue; }
|
|
94
|
+
setPath(s.data, body.path || '/', clone(body.value));
|
|
95
|
+
} else if (kind === 'deleteSurface') { surfaces.delete(sid); refused.delete(sid); }
|
|
96
|
+
else return { ok: false, why: 'a message PMOS does not take (' + kind + ')' };
|
|
97
|
+
}
|
|
98
|
+
const out = [...surfaces.values()].map((s) => (refused.has(s.id) ? { ...s, refused: refused.get(s.id) } : s));
|
|
99
|
+
return { ok: true, surfaces: out };
|
|
100
|
+
}
|
|
101
|
+
const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
102
|
+
function addComponents(s, list) {
|
|
103
|
+
if (!Array.isArray(list) || !list.length) return 'a components list that is empty';
|
|
104
|
+
for (const c of list) { const r = checkComponent(c); if (r) return r; s.components.set(c.id, c); }
|
|
105
|
+
if (s.components.size > MAX_COMPONENTS) return 'more than ' + MAX_COMPONENTS + ' parts';
|
|
106
|
+
return '';
|
|
107
|
+
}
|
|
108
|
+
const parts = (p) => String(p || '').split('/').filter(Boolean).map((x) => x.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
109
|
+
function getPath(data, p) { let o = data; for (const k of parts(p)) { if (o == null) return undefined; o = o[k]; } return o; }
|
|
110
|
+
function setPath(data, p, v) {
|
|
111
|
+
const ks = parts(p); if (!ks.length) { if (v && typeof v === 'object') { for (const k of Object.keys(data)) delete data[k]; Object.assign(data, v); } return; }
|
|
112
|
+
let o = data; for (const k of ks.slice(0, -1)) { if (o[k] == null || typeof o[k] !== 'object') o[k] = {}; o = o[k]; }
|
|
113
|
+
if (v === null) delete o[ks.at(-1)]; else o[ks.at(-1)] = v;
|
|
114
|
+
}
|
|
115
|
+
/** A path inside a template child is read against the item it was made for. */
|
|
116
|
+
const abs = (p, scope) => (String(p).startsWith('/') ? p : (scope || '') + '/' + p);
|
|
117
|
+
const val = (v, s, scope) => (v && typeof v === 'object' && typeof v['@path'] === 'string' ? getPath(s.data, abs(v['@path'], scope)) : v);
|
|
118
|
+
const str = (v, s, scope) => { const x = val(v, s, scope); return x == null ? '' : typeof x === 'object' ? '' : String(x); };
|
|
119
|
+
|
|
120
|
+
function childIds(c, s, scope) {
|
|
121
|
+
const ch = c.children;
|
|
122
|
+
if (Array.isArray(ch)) return ch.map((id) => [id, scope]);
|
|
123
|
+
if (ch && typeof ch === 'object' && ch.componentId && ch.path) {
|
|
124
|
+
const list = getPath(s.data, abs(ch.path, scope));
|
|
125
|
+
return Array.isArray(list) ? list.slice(0, 50).map((x, i) => [ch.componentId, abs(ch.path, scope) + '/' + i]) : [];
|
|
126
|
+
}
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function partHtml(id, s, scope, o, seen) {
|
|
131
|
+
const c = s.components.get(id);
|
|
132
|
+
if (!c || seen.size > MAX_COMPONENTS * 2) return '';
|
|
133
|
+
const key = id + '@' + (scope || '');
|
|
134
|
+
if (seen.has(key)) return '';
|
|
135
|
+
seen.add(key);
|
|
136
|
+
const live = o.live !== false;
|
|
137
|
+
const kid = (cid, sc = scope) => partHtml(cid, s, sc, o, seen);
|
|
138
|
+
const attr = (extra) => `data-a2-s="${esc(s.id)}" data-a2-c="${esc(c.id)}" data-a2-scope="${esc(scope || '')}"${extra || ''}`;
|
|
139
|
+
const label = (v) => (v !== undefined ? `<span class="a2-l">${esc(str(v, s, scope))}</span>` : '');
|
|
140
|
+
switch (c.component) {
|
|
141
|
+
case 'Text': return `<p class="${c.variant === 'caption' ? 'a2-cap' : 'a2-t'}">${esc(str(c.text, s, scope))}</p>`;
|
|
142
|
+
case 'Icon': return `<span class="a2-icon">${esc(str(c.name, s, scope))}</span>`;
|
|
143
|
+
case 'Image': return `<img class="a2-img" alt="${esc(str(c.description, s, scope))}" src="${esc(str(c.url, s, scope))}">`;
|
|
144
|
+
case 'Video': case 'AudioPlayer': return `<p class="a2-cap">${c.component === 'Video' ? 'A video' : 'A sound file'} the agent sent: ${esc(str(c.url, s, scope))}</p>`;
|
|
145
|
+
case 'Modal': return `<div class="a2-col">${kid(c.trigger)}<p class="a2-cap">It opens more in the agent's own app.</p></div>`;
|
|
146
|
+
case 'Divider': return '<hr class="a2-hr">';
|
|
147
|
+
case 'Row': return `<div class="a2-row">${childIds(c, s, scope).map(([x, sc]) => kid(x, sc)).join('')}</div>`;
|
|
148
|
+
case 'Column': case 'List': return `<div class="a2-col">${childIds(c, s, scope).map(([x, sc]) => kid(x, sc)).join('')}</div>`;
|
|
149
|
+
case 'Card': return `<div class="cc-card a2-card">${kid(c.child)}</div>`;
|
|
150
|
+
case 'Tabs': return `<div class="a2-col">${(Array.isArray(c.tabs) ? c.tabs : []).map((t) => `<p class="cc-h">${esc(str(t.title, s, scope))}</p>${kid(t.child)}`).join('')}</div>`;
|
|
151
|
+
case 'Button': return `<button type="button" class="pm-btn${c.variant === 'primary' ? ' primary' : ''}" ${attr(' data-a2-press')}${live ? '' : ' disabled'}>${kid(c.child) || esc(c.action.event.name)}</button>`;
|
|
152
|
+
case 'TextField': return `<label class="a2-f">${label(c.label)}<input type="text" ${attr(' data-a2-in')} value="${esc(str(c.value, s, scope))}" placeholder="${esc(str(c.placeholder, s, scope))}"${live ? '' : ' disabled'}></label>`;
|
|
153
|
+
case 'CheckBox': return `<label class="a2-f a2-row"><input type="checkbox" ${attr(' data-a2-in')}${val(c.value, s, scope) === true ? ' checked' : ''}${live ? '' : ' disabled'}>${label(c.label)}</label>`;
|
|
154
|
+
case 'Slider': return `<label class="a2-f">${label(c.label)}<input type="range" ${attr(' data-a2-in')} min="${esc(Number(val(c.min, s, scope)) || 0)}" max="${esc(Number(val(c.max, s, scope)) || 0)}" value="${esc(Number(val(c.value, s, scope)) || 0)}"${live ? '' : ' disabled'}></label>`;
|
|
155
|
+
case 'DateTimeInput': return `<label class="a2-f">${label(c.label)}<input type="${c.enableTime && !c.enableDate ? 'time' : c.enableTime ? 'datetime-local' : 'date'}" ${attr(' data-a2-in')} value="${esc(str(c.value, s, scope).slice(0, c.enableTime ? 16 : 10))}"${live ? '' : ' disabled'}></label>`;
|
|
156
|
+
case 'ChoicePicker': {
|
|
157
|
+
const on = val(c.value, s, scope), sel = Array.isArray(on) ? on : [];
|
|
158
|
+
return `<div class="a2-f">${label(c.label)}<div class="chips2">${(Array.isArray(c.options) ? c.options : []).map((op) => `<button type="button" class="chip chip2${sel.includes(op.value) ? ' on' : ''}" aria-pressed="${sel.includes(op.value)}" ${attr(` data-a2-opt="${esc(op.value)}"`)}${live ? '' : ' disabled'}>${esc(str(op.label, s, scope))}</button>`).join('')}</div></div>`;
|
|
159
|
+
}
|
|
160
|
+
default: return '';
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function viewHtml(s, o = {}) {
|
|
165
|
+
if (!s || s.refused || !s.components.has('root')) return `<p class="cc-miss" role="note">${esc(CANT)}</p>`;
|
|
166
|
+
return `<div class="a2-surface" role="group" aria-label="${esc('From the agent: ' + s.id)}">${partHtml('root', s, '', o, new Set())}</div>`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The A2UI v1.0 renderer_to_agent action for a press: the Button's event, its context bindings read from the data model. */
|
|
170
|
+
export function actionOf(s, componentId, at = new Date().toISOString(), scope = '') {
|
|
171
|
+
const c = s && s.components.get(componentId);
|
|
172
|
+
if (!c || c.component !== 'Button') return null;
|
|
173
|
+
const ev = c.action.event, context = {};
|
|
174
|
+
for (const [k, v] of Object.entries(ev.context || {})) context[k] = val(v, s, scope) === undefined ? null : val(v, s, scope);
|
|
175
|
+
const msg = { version: '1.0', action: { name: ev.name, surfaceId: s.id, sourceComponentId: c.id, timestamp: at, context } };
|
|
176
|
+
if (ev.userMessage !== undefined) msg.action.userMessage = str(ev.userMessage, s, scope);
|
|
177
|
+
return msg;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** What goes back to the agent: one message in the chat, to the same session that drew the surface. */
|
|
181
|
+
export const sayOf = (msg) => `I pressed "${msg.action.name}" on your surface ${msg.action.surfaceId}. The A2UI action:\n\`\`\`json\n${JSON.stringify(msg)}\n\`\`\``;
|
|
182
|
+
|
|
183
|
+
export function a2uiUi(host) {
|
|
184
|
+
const S = new Map(); // key → { surfaces }
|
|
185
|
+
const find = (sid) => { for (const v of S.values()) for (const s of v.surfaces || []) if (s.id === sid) return s; return null; };
|
|
186
|
+
return {
|
|
187
|
+
split,
|
|
188
|
+
html(blocks, key, o = {}) {
|
|
189
|
+
if (!blocks || !blocks.length) return '';
|
|
190
|
+
return blocks.map((b, i) => {
|
|
191
|
+
const k = key + ':' + i;
|
|
192
|
+
if (!S.has(k)) { const r = build(b); S.set(k, r.ok ? { surfaces: r.surfaces } : { why: r.why, surfaces: [] }); }
|
|
193
|
+
const v = S.get(k);
|
|
194
|
+
if (!v.surfaces.length) return `<p class="cc-miss" role="note">${esc(CANT)}</p>`;
|
|
195
|
+
return v.surfaces.map((s) => viewHtml(s, o)).join('');
|
|
196
|
+
}).join('');
|
|
197
|
+
},
|
|
198
|
+
/** True when the button is part of a surface: the chat checks this first, so its other buttons stay synchronous. */
|
|
199
|
+
owns: (b) => !!(b && b.dataset && b.dataset.a2S),
|
|
200
|
+
async press(b) {
|
|
201
|
+
const d = (b && b.dataset) || {};
|
|
202
|
+
if (!d.a2S) return false;
|
|
203
|
+
const s = find(d.a2S); if (!s) return true;
|
|
204
|
+
const c = s.components.get(d.a2C);
|
|
205
|
+
if (d.a2Opt !== undefined && c && c.component === 'ChoicePicker' && c.value && c.value['@path']) {
|
|
206
|
+
const p = abs(c.value['@path'], d.a2Scope), cur = getPath(s.data, p), list = Array.isArray(cur) ? cur.slice() : [];
|
|
207
|
+
const i = list.indexOf(d.a2Opt);
|
|
208
|
+
const next = c.variant === 'multipleSelection' ? (i >= 0 ? list.filter((x) => x !== d.a2Opt) : [...list, d.a2Opt]) : [d.a2Opt];
|
|
209
|
+
setPath(s.data, p, next); host.redraw(); return true;
|
|
210
|
+
}
|
|
211
|
+
if ('a2Press' in d) {
|
|
212
|
+
const msg = actionOf(s, d.a2C, undefined, d.a2Scope);
|
|
213
|
+
if (msg) { b.disabled = true; await host.send(sayOf(msg)); }
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
return true;
|
|
217
|
+
},
|
|
218
|
+
/** An input changed: its bound value in the surface's data model follows (two-way binding), so the next press sends it. */
|
|
219
|
+
input(el) {
|
|
220
|
+
const d = (el && el.dataset) || {};
|
|
221
|
+
if (!d.a2S || !('a2In' in d)) return false;
|
|
222
|
+
const s = find(d.a2S), c = s && s.components.get(d.a2C);
|
|
223
|
+
if (!c || !c.value || typeof c.value['@path'] !== 'string') return true;
|
|
224
|
+
const v = el.type === 'checkbox' ? !!el.checked : el.type === 'range' ? Number(el.value) : String(el.value);
|
|
225
|
+
setPath(s.data, abs(c.value['@path'], d.a2Scope), v);
|
|
226
|
+
return true;
|
|
227
|
+
},
|
|
228
|
+
state: S,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
@@ -1073,3 +1073,16 @@ body.pm-ds :is(form#hmForm.hm-box, form.hm-box, .hm-box-rich):focus-within { box
|
|
|
1073
1073
|
body.pm-ds form.hm-box :is(textarea, input):focus-visible { outline: none; box-shadow: none; }
|
|
1074
1074
|
body.pm-ds form.hm-box button:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--composer-focus-line); }
|
|
1075
1075
|
body.pm-ds .hm-send { width: 32px; height: 32px; border-radius: 50%; background: var(--blue); color: var(--on-blue); }
|
|
1076
|
+
/* a2ui-inbound-render: another agent's A2UI surface, drawn with the chat's own parts (pm/a2ui-view.js) */
|
|
1077
|
+
.a2-surface { display: flex; flex-direction: column; gap: var(--space-8); margin-top: var(--space-8); }
|
|
1078
|
+
.a2-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-8); }
|
|
1079
|
+
.a2-col { display: flex; flex-direction: column; gap: var(--space-8); }
|
|
1080
|
+
.a2-card { display: flex; flex-direction: column; gap: var(--space-8); }
|
|
1081
|
+
.a2-t { margin: 0; font-size: var(--fs-row); line-height: var(--lh-row); color: var(--cz-ink); overflow-wrap: anywhere; }
|
|
1082
|
+
.a2-cap, .a2-l { margin: 0; font-size: var(--fs-meta); line-height: var(--lh-meta); color: var(--cz-ink2); overflow-wrap: anywhere; }
|
|
1083
|
+
.a2-icon { font-size: var(--fs-meta); color: var(--cz-ink2); }
|
|
1084
|
+
.a2-img { max-width: 100%; max-height: 240px; border-radius: var(--radius-md, 14px); object-fit: contain; }
|
|
1085
|
+
.a2-hr { width: 100%; border: 0; border-top: 1px solid var(--cz-hair); margin: 0; }
|
|
1086
|
+
.a2-f { display: flex; flex-direction: column; gap: var(--space-4); }
|
|
1087
|
+
.a2-f.a2-row { flex-direction: row; }
|
|
1088
|
+
.a2-f input[type="text"], .a2-f input[type="date"], .a2-f input[type="time"], .a2-f input[type="datetime-local"] { min-height: 44px; padding: 0 var(--space-12); border-radius: var(--radius-md, 14px); border: 1px solid var(--cz-hair); background: var(--cz-card); color: var(--cz-ink); font: var(--fs-label)/1.25 var(--cz-sans); }
|