create-nisc 0.8.1 → 0.8.4
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/CHANGELOG.md +26 -0
- package/README.md +89 -13
- package/dist/chunk-7APNWIDD.js +316 -0
- package/dist/chunk-7APNWIDD.js.map +1 -0
- package/dist/cli.js +86 -42
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +61 -6
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/templates/base/files/src/ui/kit.css +232 -0
- package/templates/base/item.json +31 -0
- package/templates/{moss-dom → classic/files}/src/app/actions/surfaces/welcome.action.ts +1 -1
- package/templates/classic/item.json +32 -0
- package/templates/{moss-dom → dom/files}/index.html +1 -1
- package/templates/dom/files/src/ui/kit.ts +109 -0
- package/templates/{shell-dom → dom/files}/src/ui/registry.ts +2 -2
- package/templates/{shell-dom → dom/files}/tsconfig.json +3 -14
- package/templates/dom/item.json +24 -0
- package/templates/model-first/agents-section.md +42 -0
- package/templates/model-first/files/src/app/action-catalog.ts +10 -0
- package/templates/model-first/files/src/app/actions/answer/text.action.ts +17 -0
- package/templates/model-first/files/src/app/actions/answer/text.layout.ts +3 -0
- package/templates/model-first/files/src/app/actions/ask/dock.action.ts +58 -0
- package/templates/model-first/files/src/app/actions/ask/dock.layout.ts +59 -0
- package/templates/model-first/files/src/app/actions/guide/checklist.action.ts +24 -0
- package/templates/model-first/files/src/app/actions/guide/checklist.layout.ts +17 -0
- package/templates/model-first/files/src/app/actions/guide/counter.action.ts +22 -0
- package/templates/model-first/files/src/app/actions/guide/counter.layout.ts +19 -0
- package/templates/model-first/files/src/app/actions/guide/guide.actions.ts +144 -0
- package/templates/model-first/files/src/app/actions/guide/guide.layouts.ts +31 -0
- package/templates/model-first/files/src/app/actions/guide/quiz.action.ts +25 -0
- package/templates/model-first/files/src/app/actions/guide/quiz.layout.ts +33 -0
- package/templates/model-first/files/src/app/app.ts +11 -0
- package/templates/model-first/files/src/app/arrangements.ts +17 -0
- package/templates/model-first/files/src/app/charter/assignments.ts +1 -0
- package/templates/model-first/files/src/app/charter/charter.ts +10 -0
- package/templates/model-first/files/src/app/screens.ts +87 -0
- package/templates/model-first/files/src/app/shell/areas.ts +3 -0
- package/templates/model-first/files/src/app/shell/frame.layout.ts +6 -0
- package/templates/model-first/files/src/app/shell/shell.ts +20 -0
- package/templates/model-first/files/src/app/vex/index.ts +3 -0
- package/templates/model-first/files/src/db/schema.ts +3 -0
- package/templates/{moss-react → model-first/files}/src/dev/all-checks.ts +3 -2
- package/templates/model-first/files/src/dev/artifacts-check.ts +95 -0
- package/templates/model-first/files/src/dev/checks.ts +13 -0
- package/templates/model-first/files/src/dev/compose-check.ts +191 -0
- package/templates/model-first/files/src/dev/guide-check.ts +90 -0
- package/templates/model-first/files/src/dev/live-ask.ts +185 -0
- package/templates/model-first/files/src/dev/scripted.ts +208 -0
- package/templates/{shell-dom → model-first/files}/src/dev/strata.ts +7 -1
- package/templates/model-first/files/src/server/boot.ts +24 -0
- package/templates/model-first/files/src/server/compose/answer.ts +145 -0
- package/templates/model-first/files/src/server/compose/catalog.ts +46 -0
- package/templates/model-first/files/src/server/compose/composer.agent.ts +18 -0
- package/templates/model-first/files/src/server/compose/history.ts +45 -0
- package/templates/model-first/files/src/server/compose/index.ts +170 -0
- package/templates/model-first/files/src/server/compose/knowledge.ts +57 -0
- package/templates/model-first/files/src/server/compose/layout.ts +70 -0
- package/templates/model-first/files/src/server/compose/pick.ts +44 -0
- package/templates/model-first/files/src/server/compose/plan.ts +45 -0
- package/templates/model-first/files/src/server/compose/record.ts +3 -0
- package/templates/model-first/files/src/server/compose/reply.schema.ts +70 -0
- package/templates/model-first/files/src/server/compose/screen.ts +40 -0
- package/templates/model-first/files/src/server/models/index.ts +35 -0
- package/templates/model-first/files/src/server/runs/index.ts +20 -0
- package/templates/model-first/item.json +84 -0
- package/templates/{moss-dom → moss/files}/README.md +1 -1
- package/templates/moss/item.json +40 -0
- package/templates/{shell-dom → page/files}/README.md +1 -1
- package/templates/page/item.json +37 -0
- package/templates/questions.json +5 -0
- package/templates/{moss-react → react/files}/index.html +1 -1
- package/templates/react/files/src/ui/kit.tsx +221 -0
- package/templates/{moss-react → react/files}/src/ui/registry.ts +2 -2
- package/templates/react/item.json +31 -0
- package/dist/chunk-6FL5A3LS.js +0 -174
- package/dist/chunk-6FL5A3LS.js.map +0 -1
- package/templates/moss-dom/package.json +0 -39
- package/templates/moss-dom/src/app/actions/surfaces/welcome.layout.ts +0 -25
- package/templates/moss-dom/src/ui/kit.css +0 -42
- package/templates/moss-dom/src/ui/kit.ts +0 -35
- package/templates/moss-dom/src/ui/registry.ts +0 -15
- package/templates/moss-dom/tsconfig.json +0 -27
- package/templates/moss-react/README.md +0 -15
- package/templates/moss-react/nisc.config.ts +0 -11
- package/templates/moss-react/package.json +0 -42
- package/templates/moss-react/src/app/action-catalog.ts +0 -6
- package/templates/moss-react/src/app/actions/surfaces/welcome.action.ts +0 -10
- package/templates/moss-react/src/app/app.ts +0 -7
- package/templates/moss-react/src/app/charter/assignments.ts +0 -2
- package/templates/moss-react/src/app/charter/charter.ts +0 -5
- package/templates/moss-react/src/app/shell/frame.layout.ts +0 -3
- package/templates/moss-react/src/app/shell/shell.ts +0 -7
- package/templates/moss-react/src/dev/artifacts-check.ts +0 -49
- package/templates/moss-react/src/dev/strata.ts +0 -21
- package/templates/moss-react/src/dev/welcome-check.ts +0 -38
- package/templates/moss-react/src/server/boot.ts +0 -6
- package/templates/moss-react/src/server/runtime.ts +0 -13
- package/templates/moss-react/src/ui/kit.css +0 -42
- package/templates/moss-react/src/ui/kit.tsx +0 -39
- package/templates/moss-react/strata.lock.json +0 -6
- package/templates/shell-dom/index.html +0 -12
- package/templates/shell-dom/package.json +0 -35
- package/templates/shell-dom/src/app/action-catalog.ts +0 -6
- package/templates/shell-dom/src/app/actions/surfaces/welcome.action.ts +0 -10
- package/templates/shell-dom/src/app/actions/surfaces/welcome.layout.ts +0 -32
- package/templates/shell-dom/src/app/shell/frame.layout.ts +0 -3
- package/templates/shell-dom/src/ui/kit.css +0 -42
- package/templates/shell-dom/src/ui/kit.ts +0 -35
- package/templates/shell-dom/strata.lock.json +0 -6
- package/templates/shell-dom/vite.config.ts +0 -5
- package/templates/shell-react/README.md +0 -16
- package/templates/shell-react/index.html +0 -12
- package/templates/shell-react/package.json +0 -40
- package/templates/shell-react/src/app/action-catalog.ts +0 -6
- package/templates/shell-react/src/app/actions/surfaces/welcome.action.ts +0 -10
- package/templates/shell-react/src/app/shell/frame.layout.ts +0 -3
- package/templates/shell-react/src/app/shell/shell.ts +0 -7
- package/templates/shell-react/src/boot.ts +0 -13
- package/templates/shell-react/src/dev/all-checks.ts +0 -17
- package/templates/shell-react/src/dev/artifacts-check.ts +0 -45
- package/templates/shell-react/src/dev/strata.ts +0 -21
- package/templates/shell-react/src/dev/welcome-check.ts +0 -21
- package/templates/shell-react/src/ui/kit.css +0 -42
- package/templates/shell-react/src/ui/kit.tsx +0 -39
- package/templates/shell-react/src/ui/registry.ts +0 -12
- package/templates/shell-react/strata.lock.json +0 -6
- package/templates/shell-react/tsconfig.json +0 -28
- package/templates/shell-react/vite.config.ts +0 -8
- /package/templates/{moss-dom → base/files}/strata.lock.json +0 -0
- /package/templates/{moss-dom → classic/files}/src/app/action-catalog.ts +0 -0
- /package/templates/{moss-dom → classic/files}/src/app/shell/frame.layout.ts +0 -0
- /package/templates/{moss-dom → classic/files}/src/dev/strata.ts +0 -0
- /package/templates/{moss-react → classic/with/moss}/src/app/actions/surfaces/welcome.layout.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/app/app.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/app/charter/assignments.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/app/charter/charter.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/app/shell/shell.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/dev/all-checks.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/dev/artifacts-check.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/dev/welcome-check.ts +0 -0
- /package/templates/{moss-dom → classic/with/moss}/src/server/boot.ts +0 -0
- /package/templates/{shell-react → classic/with/page}/src/app/actions/surfaces/welcome.layout.ts +0 -0
- /package/templates/{shell-dom → classic/with/page}/src/app/shell/shell.ts +0 -0
- /package/templates/{shell-dom → classic/with/page}/src/boot.ts +0 -0
- /package/templates/{shell-dom → classic/with/page}/src/dev/all-checks.ts +0 -0
- /package/templates/{shell-dom → classic/with/page}/src/dev/artifacts-check.ts +0 -0
- /package/templates/{shell-dom → classic/with/page}/src/dev/welcome-check.ts +0 -0
- /package/templates/{moss-dom → dom/files}/vite.config.ts +0 -0
- /package/templates/{moss-dom → dom/with/moss}/src/main.ts +0 -0
- /package/templates/{moss-dom → dom/with/moss}/src/server/document.ts +0 -0
- /package/templates/{shell-dom → dom/with/page}/nisc.config.ts +0 -0
- /package/templates/{shell-dom → dom/with/page}/src/main.ts +0 -0
- /package/templates/{shell-dom → dom/with/page}/src/ui/screen.ts +0 -0
- /package/templates/{moss-dom → moss/files}/nisc.config.ts +0 -0
- /package/templates/{moss-dom → moss/files}/src/server/runtime.ts +0 -0
- /package/templates/{moss-react → react/files}/tsconfig.json +0 -0
- /package/templates/{moss-react → react/files}/vite.config.ts +0 -0
- /package/templates/{moss-react → react/with/moss}/src/main.tsx +0 -0
- /package/templates/{moss-react → react/with/moss}/src/server/document.ts +0 -0
- /package/templates/{shell-react → react/with/page}/nisc.config.ts +0 -0
- /package/templates/{shell-react → react/with/page}/src/main.tsx +0 -0
- /package/templates/{shell-react → react/with/page}/src/ui/screen.tsx +0 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type { Arrangement } from '../../app/arrangements';
|
|
2
|
+
import { AREAS } from '../../app/shell/areas';
|
|
3
|
+
import type { AreaId } from '../../app/shell/areas';
|
|
4
|
+
import { opened } from './catalog';
|
|
5
|
+
import type { Catalog } from './catalog';
|
|
6
|
+
import type { ComposerDeps } from './knowledge';
|
|
7
|
+
import { areasOfArrangement, gridLayout } from './layout';
|
|
8
|
+
import type { WrittenLayout } from './layout';
|
|
9
|
+
import { wordsCanvas } from './plan';
|
|
10
|
+
import type { AreaCanvases } from './plan';
|
|
11
|
+
import { isRecord, recordOf } from './record';
|
|
12
|
+
import { entriesOf, EntrySchema, entryOf } from './reply.schema';
|
|
13
|
+
import type { Entry, Reply } from './reply.schema';
|
|
14
|
+
|
|
15
|
+
// No arrangement keeps the one on screen.
|
|
16
|
+
export type Answer = { title: string; screen?: string; canvases: AreaCanvases; arrangement?: string | WrittenLayout };
|
|
17
|
+
|
|
18
|
+
export type AnswerContext = ComposerDeps & { open: AreaCanvases; current: string | WrittenLayout };
|
|
19
|
+
|
|
20
|
+
const arrangementOfReply = (reply: Reply, arrangements: readonly Arrangement[]): string | WrittenLayout | undefined => {
|
|
21
|
+
if (reply.grid) return gridLayout(reply.grid);
|
|
22
|
+
return arrangements.find((arrangement) => arrangement.id === reply.arrangement)?.id;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const canvasRefusals = (entry: Entry, where: string, catalog: Catalog): string[] => {
|
|
26
|
+
const action = catalog.actions.find((candidate) => candidate.id === entry.action);
|
|
27
|
+
if (action === undefined) return [`${where}: there is no action "${String(entry.action)}".`];
|
|
28
|
+
const input = entry.input ?? {};
|
|
29
|
+
const parsed = action.check.safeParse(input);
|
|
30
|
+
if (!parsed.success) return parsed.error.issues.map((issue) => `${where}: input.${issue.path.join('.')}: ${issue.message}`);
|
|
31
|
+
const refusals: string[] = [];
|
|
32
|
+
const read = input['read'];
|
|
33
|
+
if (typeof read === 'string') {
|
|
34
|
+
const known = catalog.reads.find((candidate) => candidate.fingerprint === read);
|
|
35
|
+
const params = isRecord(input['params']) ? input['params'] : {};
|
|
36
|
+
if (known === undefined) refusals.push(`${where}: there is no read "${read}".`);
|
|
37
|
+
else {
|
|
38
|
+
for (const key of known.contextKeys) if (params[key] === undefined || params[key] === '') refusals.push(`${where}: the read "${read}" is asked with params.${key}, and it is missing.`);
|
|
39
|
+
for (const key of Object.keys(params)) if (!known.contextKeys.includes(key)) refusals.push(`${where}: the read "${read}" takes no params.${key}; it takes ${known.contextKeys.length > 0 ? known.contextKeys.join(', ') : 'none'}.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const write = input['write'];
|
|
43
|
+
if (typeof write === 'string') {
|
|
44
|
+
const known = catalog.writes.find((candidate) => candidate.fingerprint === write);
|
|
45
|
+
const keys = (Array.isArray(input['fields']) ? input['fields'] : []).map((field: unknown) => (isRecord(field) ? field['key'] : undefined));
|
|
46
|
+
if (known === undefined) refusals.push(`${where}: there is no write "${write}".`);
|
|
47
|
+
else for (const key of known.contextKeys) if (!keys.includes(key)) refusals.push(`${where}: the write "${write}" saves a field "${key}", and the form has none.`);
|
|
48
|
+
}
|
|
49
|
+
return refusals;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const entryRefusals = (entry: Entry, where: string, room: readonly AreaId[], named: string, open: AreaCanvases, catalog: Catalog): string[] => {
|
|
53
|
+
const refusals = room.includes(entry.area) ? [] : [`${where}: the arrangement ${named} has no area ${entry.area}; its areas are ${room.join(', ')}.`];
|
|
54
|
+
const kinds = [entry.keep !== undefined, entry.action !== undefined || entry.input !== undefined, entry.say !== undefined, entry.drop].filter(Boolean).length;
|
|
55
|
+
if (kinds !== 1) return [...refusals, `${where}: give exactly one of "keep", "action" with "input", "say", or "drop".`];
|
|
56
|
+
if (entry.keep !== undefined) return open[entry.keep] === undefined ? [...refusals, `${where}: there is nothing in area ${entry.keep} to keep.`] : refusals;
|
|
57
|
+
if (entry.action !== undefined || entry.input !== undefined) return [...refusals, ...canvasRefusals(entry, where, catalog)];
|
|
58
|
+
return refusals;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const nameOf = (arrangement: string | WrittenLayout): string => (typeof arrangement === 'object' ? 'you wrote' : `"${arrangement}"`);
|
|
62
|
+
|
|
63
|
+
// What was there stays, in the areas the arrangement has, unless an entry drops it, moves it (an area another entry
|
|
64
|
+
// keeps from is empty unless it is given something), or puts another canvas or words there.
|
|
65
|
+
const applyEntries = (entries: readonly Entry[], open: AreaCanvases, room: readonly AreaId[], catalog: Catalog): AreaCanvases => {
|
|
66
|
+
const canvases: AreaCanvases = Object.fromEntries(room.flatMap((area) => (open[area] !== undefined ? [[area, open[area]]] : [])));
|
|
67
|
+
for (const entry of entries) if (entry.keep !== undefined && entry.keep !== entry.area && !entries.some((other) => other.area === entry.keep)) delete canvases[entry.keep];
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
delete canvases[entry.area];
|
|
70
|
+
if (entry.keep !== undefined) {
|
|
71
|
+
const kept = open[entry.keep];
|
|
72
|
+
if (kept !== undefined) canvases[entry.area] = kept;
|
|
73
|
+
} else if (entry.say !== undefined) canvases[entry.area] = wordsCanvas(entry.say);
|
|
74
|
+
else if (entry.action !== undefined) {
|
|
75
|
+
const intent = entry.intent?.trim() ?? '';
|
|
76
|
+
canvases[entry.area] = opened({ action: entry.action, input: entry.input ?? {}, intent: intent !== '' ? intent : (catalog.actions.find((action) => action.id === entry.action)?.description ?? '') }, catalog);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return canvases;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// A read shown again with the same values is the same thing under another heading; so is a second form for one write.
|
|
83
|
+
const sameThingKey = (canvas: { action: string; input: Record<string, unknown> }): string => {
|
|
84
|
+
const { read, params, write } = canvas.input;
|
|
85
|
+
return JSON.stringify(read !== undefined ? [canvas.action, read, params] : write !== undefined ? [canvas.action, write] : [canvas.action, canvas.input]);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export const refusalsOf = (reply: Reply, context: AnswerContext): string[] => {
|
|
89
|
+
const { open, current, catalog, screens, arrangements } = context;
|
|
90
|
+
if (reply.screen) return screens.some((screen) => screen.id === reply.screen) ? [] : [`"${reply.screen}" is not one of the app's screens.`];
|
|
91
|
+
const refusals: string[] = [];
|
|
92
|
+
if (reply.arrangement && !reply.grid && !arrangements.some((arrangement) => arrangement.id === reply.arrangement)) refusals.push(`there is no arrangement "${reply.arrangement}".`);
|
|
93
|
+
if (reply.grid && new Set(reply.grid.areas.map(({ name }) => name)).size !== reply.grid.areas.length) refusals.push('the grid names an area twice.');
|
|
94
|
+
const arrangement = arrangementOfReply(reply, arrangements) ?? current;
|
|
95
|
+
const room = areasOfArrangement(arrangement, arrangements);
|
|
96
|
+
const entries = entriesOf(reply);
|
|
97
|
+
const seen = new Set<AreaId>();
|
|
98
|
+
entries.forEach((entry, at) => {
|
|
99
|
+
const where = `areas[${at}] (area ${entry.area})`;
|
|
100
|
+
if (seen.has(entry.area)) refusals.push(`${where}: area ${entry.area} is given twice.`);
|
|
101
|
+
seen.add(entry.area);
|
|
102
|
+
refusals.push(...entryRefusals(entry, where, room, nameOf(arrangement), open, catalog));
|
|
103
|
+
});
|
|
104
|
+
const shown = new Map<string, AreaId>();
|
|
105
|
+
const canvases = applyEntries(entries, open, room, catalog);
|
|
106
|
+
for (const area of AREAS) {
|
|
107
|
+
const canvas = canvases[area];
|
|
108
|
+
if (canvas === undefined) continue;
|
|
109
|
+
const there = shown.get(sameThingKey(canvas));
|
|
110
|
+
if (there !== undefined) refusals.push(`areas ${there} and ${area} would show the same thing; show it once.`);
|
|
111
|
+
else shown.set(sameThingKey(canvas), area);
|
|
112
|
+
}
|
|
113
|
+
return refusals;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export const answerOf = (reply: Reply, context: AnswerContext): Answer => {
|
|
117
|
+
const title = reply.title.trim();
|
|
118
|
+
if (reply.screen) return { title, screen: reply.screen, canvases: {} };
|
|
119
|
+
const arrangement = arrangementOfReply(reply, context.arrangements);
|
|
120
|
+
const canvases = applyEntries(entriesOf(reply), context.open, areasOfArrangement(arrangement ?? context.current, context.arrangements), context.catalog);
|
|
121
|
+
return { title, canvases, ...(arrangement !== undefined ? { arrangement } : {}) };
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// While the reply streams, solid writes it left to right: an entry is finished once the next one has begun, or once the
|
|
125
|
+
// reply has gone past the areas to its room (solid holds every key from the start; a key the model has reached has a
|
|
126
|
+
// value, null included). A finished entry is placed in the room on screen if its own checks pass;
|
|
127
|
+
// another room, or a screen, comes with the whole reply, which is the run's to check when it ends.
|
|
128
|
+
export const answerSoFar = (output: unknown, context: AnswerContext): Answer | undefined => {
|
|
129
|
+
const data = recordOf(recordOf(output)['data']);
|
|
130
|
+
const written = data['areas'];
|
|
131
|
+
if (!Array.isArray(written) || typeof data['screen'] === 'string') return undefined;
|
|
132
|
+
const pastTheAreas = ['arrangement', 'grid', 'screen'].some((key) => data[key] !== undefined);
|
|
133
|
+
const room = areasOfArrangement(context.current, context.arrangements);
|
|
134
|
+
const seen = new Set<AreaId>();
|
|
135
|
+
const entries = (pastTheAreas ? written : written.slice(0, -1)).flatMap((raw: unknown) => {
|
|
136
|
+
const parsed = EntrySchema.safeParse(raw);
|
|
137
|
+
if (!parsed.success) return [];
|
|
138
|
+
const entry = entryOf(parsed.data);
|
|
139
|
+
if (seen.has(entry.area) || entryRefusals(entry, '', room, nameOf(context.current), context.open, context.catalog).length > 0) return [];
|
|
140
|
+
seen.add(entry.area);
|
|
141
|
+
return [entry];
|
|
142
|
+
});
|
|
143
|
+
const title = typeof data['title'] === 'string' ? data['title'].trim() : '';
|
|
144
|
+
return { title, canvases: applyEntries(entries, context.open, room, context.catalog) };
|
|
145
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { ActionDefinition } from '@niscorp/nova';
|
|
3
|
+
import type { SeedEntry, SeedMutation } from '@niscorp/vex';
|
|
4
|
+
import { placeable } from '../../app/action-catalog';
|
|
5
|
+
import type { Canvas } from '../../app/screens';
|
|
6
|
+
import { ENTRIES } from '../../app/vex';
|
|
7
|
+
import { isRecord, recordOf } from './record';
|
|
8
|
+
|
|
9
|
+
type Placeable = { id: string; description: string; schema: Record<string, unknown>; check: z.ZodType; defaults: Record<string, unknown> };
|
|
10
|
+
type Read = { fingerprint: string; intent: string; shape: unknown; contextKeys: string[] };
|
|
11
|
+
type Write = { fingerprint: string; intent: string; contextKeys: string[] };
|
|
12
|
+
export type Catalog = { actions: Placeable[]; reads: Read[]; writes: Write[] };
|
|
13
|
+
|
|
14
|
+
// An action that declares no input is opened with none.
|
|
15
|
+
const NO_INPUT = z.toJSONSchema(z.object({}).strict());
|
|
16
|
+
|
|
17
|
+
export const inputKeysOf = (schema: unknown): string[] => Object.keys(recordOf(recordOf(schema)['properties']));
|
|
18
|
+
|
|
19
|
+
const contextOf = (node: unknown): string[] => {
|
|
20
|
+
if (Array.isArray(node)) return node.flatMap(contextOf);
|
|
21
|
+
if (!isRecord(node)) return [];
|
|
22
|
+
const named = node['$context'];
|
|
23
|
+
return typeof named === 'string' ? [named] : Object.values(node).flatMap(contextOf);
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const placeableOf = (action: ActionDefinition): Placeable => {
|
|
27
|
+
const schema = action.input ?? NO_INPUT;
|
|
28
|
+
const carried = inputKeysOf(schema);
|
|
29
|
+
const defaults = Object.fromEntries(Object.entries(action.data ?? {}).filter(([key]) => carried.includes(key)));
|
|
30
|
+
return { id: action.id, description: action.description ?? '', schema, check: z.fromJSONSchema(schema), defaults };
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// A canvas written onto a screen holds its whole input: what it leaves out, or says is null, is its action's default, so
|
|
34
|
+
// a card already there is written into exactly as a new one would open, and keeps nothing of what it showed before.
|
|
35
|
+
export const opened = (canvas: Canvas, catalog: Catalog): Canvas => ({
|
|
36
|
+
...canvas,
|
|
37
|
+
input: { ...catalog.actions.find((action) => action.id === canvas.action)?.defaults, ...Object.fromEntries(Object.entries(canvas.input).filter(([, value]) => value !== null)) },
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const catalogOf = (actions: readonly ActionDefinition[], entries: readonly (SeedEntry | SeedMutation)[]): Catalog => ({
|
|
41
|
+
actions: actions.map(placeableOf),
|
|
42
|
+
reads: entries.flatMap((entry) => ('dsl' in entry ? [{ fingerprint: entry.fingerprint, intent: entry.intent ?? '', shape: entry.shape, contextKeys: [...new Set(contextOf(entry.dsl))] }] : [])),
|
|
43
|
+
writes: entries.flatMap((entry) => ('mutation' in entry ? [{ fingerprint: entry.fingerprint, intent: entry.intent ?? '', contextKeys: [...new Set(contextOf(entry.mutation))] }] : [])),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export const CATALOG: Catalog = catalogOf(placeable, ENTRIES);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { defineAgent } from '@niscorp/cortex';
|
|
2
|
+
import type { AgentDefinition, OutputValidator } from '@niscorp/cortex';
|
|
3
|
+
import { actionCatalog, arrangementCatalog, INSTRUCTIONS, readCatalog, screenCatalog, writeCatalog } from './knowledge';
|
|
4
|
+
import type { ComposerDeps } from './knowledge';
|
|
5
|
+
import { ReplySchema } from './reply.schema';
|
|
6
|
+
import type { Reply } from './reply.schema';
|
|
7
|
+
|
|
8
|
+
// Defined for each message: what refuses an answer depends on the screen the message was asked on.
|
|
9
|
+
export const composerAgent = (validate: OutputValidator<Reply>): AgentDefinition<Reply, ComposerDeps> =>
|
|
10
|
+
defineAgent<Reply, ComposerDeps>({
|
|
11
|
+
id: 'nisc-template-app.compose',
|
|
12
|
+
description: 'Answers a message with a screen composed from the app’s actions.',
|
|
13
|
+
instructions: INSTRUCTIONS,
|
|
14
|
+
context: [actionCatalog, readCatalog, writeCatalog, screenCatalog, arrangementCatalog],
|
|
15
|
+
// An agent with no tools on Groq would be sent the envelope as Groq's loose JSON schema, and gpt-oss answers this one
|
|
16
|
+
// worse there: emit carries the contract in the prompt, as every Groq agent with tools gets it.
|
|
17
|
+
output: { schema: ReplySchema, response: 'required', strategy: 'emit', validate },
|
|
18
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Plan, ShownPlan } from './plan';
|
|
2
|
+
|
|
3
|
+
export type History = {
|
|
4
|
+
current: () => ShownPlan;
|
|
5
|
+
add: (plan: Plan) => ShownPlan;
|
|
6
|
+
next: (plan: Plan) => ShownPlan;
|
|
7
|
+
indexOf: (test: (plan: Plan) => boolean) => number;
|
|
8
|
+
go: (position: number) => ShownPlan;
|
|
9
|
+
back: () => ShownPlan;
|
|
10
|
+
forward: () => ShownPlan;
|
|
11
|
+
keep: (canvases: Plan['canvases']) => void;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const NOTHING: ShownPlan = { question: '', label: '', position: 0, total: 0, stack: [], canvases: {}, arrangement: '', layout: { component: 'Grid' } };
|
|
15
|
+
|
|
16
|
+
const stackOf = (plans: readonly Plan[]): ShownPlan['stack'] => plans.map((plan, offset) => ({ position: offset + 1, label: plan.label }));
|
|
17
|
+
|
|
18
|
+
export const createHistory = (first: Plan | undefined): History => {
|
|
19
|
+
const plans: Plan[] = first === undefined ? [] : [first];
|
|
20
|
+
let at = plans.length - 1;
|
|
21
|
+
const shown = (index: number): ShownPlan => {
|
|
22
|
+
const plan = plans[index];
|
|
23
|
+
return plan === undefined ? NOTHING : { ...plan, position: index + 1, total: plans.length, stack: stackOf(plans) };
|
|
24
|
+
};
|
|
25
|
+
const showAt = (index: number): ShownPlan => {
|
|
26
|
+
at = index;
|
|
27
|
+
return shown(at);
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
current: () => shown(at),
|
|
31
|
+
add: (plan) => {
|
|
32
|
+
plans.push(plan);
|
|
33
|
+
return showAt(plans.length - 1);
|
|
34
|
+
},
|
|
35
|
+
next: (plan) => ({ ...plan, position: plans.length + 1, total: plans.length + 1, stack: stackOf([...plans, plan]) }),
|
|
36
|
+
indexOf: (test) => plans.findIndex(test),
|
|
37
|
+
go: (position) => showAt(position >= 1 && position <= plans.length ? position - 1 : at),
|
|
38
|
+
back: () => showAt(Math.max(0, at - 1)),
|
|
39
|
+
forward: () => showAt(Math.min(plans.length - 1, at + 1)),
|
|
40
|
+
keep: (canvases) => {
|
|
41
|
+
const plan = plans[at];
|
|
42
|
+
if (plan !== undefined) plans[at] = { ...plan, canvases };
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
};
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { CortexEvent, SignalClient, Usage } from '@niscorp/cortex';
|
|
3
|
+
import type { FunctionDefinition, FunctionSession } from '@niscorp/moss';
|
|
4
|
+
import { unverifiedShell } from '@niscorp/moss/unverified';
|
|
5
|
+
import { ARRANGEMENTS } from '../../app/arrangements';
|
|
6
|
+
import { SCREENS } from '../../app/screens';
|
|
7
|
+
import type { Screen } from '../../app/screens';
|
|
8
|
+
import type { AreaId } from '../../app/shell/areas';
|
|
9
|
+
import { recordModelRun } from '../runs';
|
|
10
|
+
import { answerOf, answerSoFar, refusalsOf } from './answer';
|
|
11
|
+
import type { AnswerContext } from './answer';
|
|
12
|
+
import { CATALOG, opened } from './catalog';
|
|
13
|
+
import type { Catalog } from './catalog';
|
|
14
|
+
import { composerAgent } from './composer.agent';
|
|
15
|
+
import { createHistory } from './history';
|
|
16
|
+
import { messageInput } from './knowledge';
|
|
17
|
+
import { markChanged } from './layout';
|
|
18
|
+
import { pick } from './pick';
|
|
19
|
+
import type { Decide } from './pick';
|
|
20
|
+
import { arrangementOfPlan, canvasesInAreas, canvasesOfPlan, changedAreas, planOf } from './plan';
|
|
21
|
+
import type { Plan, ShownPlan } from './plan';
|
|
22
|
+
import { canvasesStanding, readOpenScreen } from './screen';
|
|
23
|
+
import type { OpenCanvas } from './screen';
|
|
24
|
+
|
|
25
|
+
export type { Decide } from './pick';
|
|
26
|
+
|
|
27
|
+
export type Jev = { provider: string; model: string; decide: Decide };
|
|
28
|
+
export type Chat = { provider: string; model: string; llm: SignalClient; timeoutMs: number };
|
|
29
|
+
|
|
30
|
+
export type Models = { jev?: Jev; chat?: Chat; missing: readonly string[] };
|
|
31
|
+
|
|
32
|
+
const AskSchema = z.looseObject({ text: z.string() });
|
|
33
|
+
const OpenSchema = z.looseObject({ opening: z.string() });
|
|
34
|
+
const GoSchema = z.looseObject({ going: z.coerce.number() });
|
|
35
|
+
|
|
36
|
+
const reasonOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
37
|
+
|
|
38
|
+
const NO_USAGE: Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, reported: false };
|
|
39
|
+
|
|
40
|
+
const screenOf = (plan: Plan): string => JSON.stringify([plan.canvases, plan.layout, plan.label]);
|
|
41
|
+
|
|
42
|
+
export const composer =
|
|
43
|
+
(models: Models): ((session: FunctionSession) => FunctionDefinition[]) =>
|
|
44
|
+
(session) => {
|
|
45
|
+
const held = new Set(session.actions);
|
|
46
|
+
const catalog: Catalog = { ...CATALOG, actions: CATALOG.actions.filter((action) => held.has(action.id)) };
|
|
47
|
+
const deps = { catalog, screens: SCREENS, arrangements: ARRANGEMENTS };
|
|
48
|
+
// What the person did last: an answer for anything earlier is no longer shown.
|
|
49
|
+
let turn = 0;
|
|
50
|
+
|
|
51
|
+
const screenPlan = (screen: Screen): Plan => planOf('', canvasesInAreas(screen.canvases.map((canvas) => opened(canvas, catalog))), { arrangements: ARRANGEMENTS, screen, arrangement: screen.arrangement });
|
|
52
|
+
const history = createHistory(screenPlan(SCREENS[0]));
|
|
53
|
+
|
|
54
|
+
// The swap goes around moss (`unverifiedShell`): moss lets a session change a layout only through a draft, and a
|
|
55
|
+
// draft needs a signed-in person. When the app has sign-in, this moves to `session.draft`, where moss checks it.
|
|
56
|
+
const show = (plan: ShownPlan, changed: readonly AreaId[] = []): ShownPlan => {
|
|
57
|
+
unverifiedShell(session).setLayout('answers', changed.length > 0 ? markChanged(plan.layout, changed) : plan.layout);
|
|
58
|
+
return plan;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// The answer being written, while it streams: the dock re-reads it whenever the message `answer-moved` says it moved.
|
|
62
|
+
let soFar: ShownPlan | undefined;
|
|
63
|
+
const moveTo = (plan: ShownPlan | undefined, changed: readonly AreaId[] = []): void => {
|
|
64
|
+
soFar = plan;
|
|
65
|
+
show(plan ?? history.current(), changed);
|
|
66
|
+
session.shell.publish('answer-moved');
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// Before anything else is shown, the screen as the person left it is kept with the answer it is on — unless an answer
|
|
70
|
+
// is streaming in over it.
|
|
71
|
+
const standing = (): OpenCanvas[] => {
|
|
72
|
+
const open = readOpenScreen(session.shell, history.current());
|
|
73
|
+
if (soFar === undefined) history.keep(canvasesStanding(open));
|
|
74
|
+
return open;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const leave = (to: () => ShownPlan): ShownPlan => {
|
|
78
|
+
standing();
|
|
79
|
+
turn += 1;
|
|
80
|
+
soFar = undefined;
|
|
81
|
+
return show(to());
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// A screen already in the stack is gone back to, not stacked again. What the model said when it answered with the
|
|
85
|
+
// screen is shown with it, and not kept.
|
|
86
|
+
const showScreen = (screen: Screen, response?: string): ShownPlan => {
|
|
87
|
+
const there = history.indexOf((plan) => plan.screen === screen.id);
|
|
88
|
+
const plan = there >= 0 ? history.go(there + 1) : history.add(screenPlan(screen));
|
|
89
|
+
return response === undefined ? plan : { ...plan, response };
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const ask = async (data: unknown): Promise<ShownPlan> => {
|
|
93
|
+
const message = AskSchema.parse(data).text.trim();
|
|
94
|
+
if (message === '') return history.current();
|
|
95
|
+
const chat = models.chat;
|
|
96
|
+
if (chat === undefined) throw new Error(`Set ${models.missing.join(' and ')} in .env, and start the app again.`);
|
|
97
|
+
const open = standing();
|
|
98
|
+
const asked = (turn += 1);
|
|
99
|
+
const before = history.current();
|
|
100
|
+
const jev = models.jev;
|
|
101
|
+
const picking = performance.now();
|
|
102
|
+
const picked =
|
|
103
|
+
jev === undefined
|
|
104
|
+
? undefined
|
|
105
|
+
: await pick(message, open, catalog, SCREENS, jev.decide).catch((error: unknown) => {
|
|
106
|
+
console.error(`[ask] Jev could not answer "${message}": ${reasonOf(error)}`);
|
|
107
|
+
return undefined;
|
|
108
|
+
});
|
|
109
|
+
if (jev !== undefined) {
|
|
110
|
+
const usage = picked?.usage ?? NO_USAGE;
|
|
111
|
+
recordModelRun(session, { agentId: 'nisc-template-app.jev', label: message, provider: jev.provider, model: jev.model, usage, steps: picked === undefined ? 0 : 1, elapsedMs: performance.now() - picking, outcome: picked === undefined ? 'failed' : 'ok' });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const current = arrangementOfPlan(before);
|
|
115
|
+
const context: AnswerContext = { ...deps, open: canvasesOfPlan(before), current };
|
|
116
|
+
const agent = composerAgent((envelope) => {
|
|
117
|
+
const refused = refusalsOf(envelope.data, context);
|
|
118
|
+
return refused.length === 0 ? { ok: true } : { retry: refused.map((reason) => `- ${reason}`).join('\n') };
|
|
119
|
+
});
|
|
120
|
+
const input = messageInput(message, open, { id: before.arrangement, layout: before.layout }, picked?.picks);
|
|
121
|
+
// A correction starts the answer again from the screen the message was asked on.
|
|
122
|
+
const streamed = (event: CortexEvent): void => {
|
|
123
|
+
if (asked !== turn) return;
|
|
124
|
+
if (event.type === 'retry' && soFar !== undefined) moveTo(undefined);
|
|
125
|
+
if (event.type !== 'output-partial') return;
|
|
126
|
+
const answer = answerSoFar(event.output, context);
|
|
127
|
+
if (answer === undefined) return;
|
|
128
|
+
const plan = history.next(planOf(message, answer.canvases, { arrangements: ARRANGEMENTS, arrangement: answer.arrangement ?? current, label: answer.title }));
|
|
129
|
+
if (screenOf(plan) === screenOf(soFar ?? before)) return;
|
|
130
|
+
moveTo(plan, changedAreas(plan, before));
|
|
131
|
+
};
|
|
132
|
+
const result = await agent.run(input, { llm: chat.llm, deps, signal: AbortSignal.timeout(chat.timeoutMs), onEvent: streamed }).result;
|
|
133
|
+
const { usage, steps, elapsedMs } = result.meta;
|
|
134
|
+
recordModelRun(session, { agentId: agent.agentId, label: message, provider: chat.provider, model: chat.model, usage, steps, elapsedMs, outcome: result.ok ? 'ok' : 'failed' });
|
|
135
|
+
if (asked !== turn) return history.current();
|
|
136
|
+
const placed = soFar !== undefined;
|
|
137
|
+
soFar = undefined;
|
|
138
|
+
|
|
139
|
+
if (!result.ok) {
|
|
140
|
+
const { code, stop, message: reason } = result.error;
|
|
141
|
+
console.error(`[ask] "${message}" got no screen: ${code}${stop === undefined ? '' : ` (${stop})`}: ${reason}`);
|
|
142
|
+
if (placed) moveTo(undefined);
|
|
143
|
+
throw new Error(code === 'aborted' || code === 'model_call_failed' ? 'The model could not be reached. Ask again in a moment.' : 'That answer did not fit this app’s actions. Ask again, or put it differently.');
|
|
144
|
+
}
|
|
145
|
+
const answer = answerOf(result.output.data, context);
|
|
146
|
+
const response = result.output.response?.trim() ?? '';
|
|
147
|
+
const screen = answer.screen === undefined ? undefined : SCREENS.find((candidate) => candidate.id === answer.screen);
|
|
148
|
+
if (screen !== undefined) return show(showScreen(screen, response));
|
|
149
|
+
if (Object.keys(answer.canvases).length === 0) throw new Error('Nothing here answers that yet.');
|
|
150
|
+
const plan = { ...planOf(message, answer.canvases, { arrangements: ARRANGEMENTS, arrangement: answer.arrangement ?? current, label: answer.title }), response };
|
|
151
|
+
// An answer that leaves the screen as it is adds nothing to the stack; the dock still names what was asked, and why
|
|
152
|
+
// nothing changed.
|
|
153
|
+
if (screenOf({ ...plan, label: before.label }) === screenOf(before)) return show({ ...before, question: message, label: answer.title, response });
|
|
154
|
+
return show(history.add(plan), changedAreas(plan, before));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const open = async (data: unknown): Promise<ShownPlan> => {
|
|
158
|
+
const screen = SCREENS.find((candidate) => candidate.id === OpenSchema.parse(data).opening);
|
|
159
|
+
return screen === undefined ? history.current() : leave(() => showScreen(screen));
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
return [
|
|
163
|
+
{ id: 'ask', description: 'Answers a message with a screen. Send { text }; answers the plan shown: { question, response, label, canvases, position, total, stack }.', execute: ask },
|
|
164
|
+
{ id: 'screens.open', description: 'Shows one of the screens in the dock: its canvases together. Send { opening: <screen id> }; answers its plan.', execute: open },
|
|
165
|
+
{ id: 'answers.back', description: 'Shows the answer before the one shown, and answers its plan.', execute: async () => leave(history.back) },
|
|
166
|
+
{ id: 'answers.forward', description: 'Shows the answer after the one shown, and answers its plan.', execute: async () => leave(history.forward) },
|
|
167
|
+
{ id: 'answers.go', description: 'Shows one answer from the stack. Send { going: <its position> }; answers its plan.', execute: async (data) => leave(() => history.go(GoSchema.parse(data).going)) },
|
|
168
|
+
{ id: 'answers.current', description: 'Answers the plan shown, or, while an answer streams, the answer so far.', execute: async () => soFar ?? history.current() },
|
|
169
|
+
];
|
|
170
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Producer } from '@niscorp/cortex';
|
|
2
|
+
import type { LayoutNode } from '@niscorp/nova';
|
|
3
|
+
import type { Arrangement } from '../../app/arrangements';
|
|
4
|
+
import type { Screen } from '../../app/screens';
|
|
5
|
+
import { AREAS } from '../../app/shell/areas';
|
|
6
|
+
import type { Catalog } from './catalog';
|
|
7
|
+
import { areaRows } from './layout';
|
|
8
|
+
import type { Picks } from './pick';
|
|
9
|
+
import { recordOf } from './record';
|
|
10
|
+
import type { OpenCanvas } from './screen';
|
|
11
|
+
|
|
12
|
+
export type ComposerDeps = { catalog: Catalog; screens: readonly Screen[]; arrangements: readonly Arrangement[] };
|
|
13
|
+
|
|
14
|
+
const json = (value: unknown): string => JSON.stringify(value);
|
|
15
|
+
|
|
16
|
+
const withoutDialect = (schema: unknown): Record<string, unknown> => Object.fromEntries(Object.entries(recordOf(schema)).filter(([key]) => key !== '$schema'));
|
|
17
|
+
|
|
18
|
+
export const INSTRUCTIONS = `You answer a person's message with a screen: up to ${AREAS.length} canvases, each an action opened with an input, on the areas ${AREAS.join(', ')} of an arrangement. The screen is the answer: prefer actions to words, always. There is no chat history: the screen open when the message arrives is the conversation, and the message is about it. Change only what the message asks to change; keep everything else exactly where it is.
|
|
19
|
+
Your \`response\` is one plain sentence for the person, at most 120 characters: what you change and why, or why nothing changes. Whatever a person reads — the response, and every word you put on a card — names what they see, never ids, area letters, arrangement names or fingerprints.`;
|
|
20
|
+
|
|
21
|
+
export const actionCatalog = (({ deps }) =>
|
|
22
|
+
`ACTIONS — what a person sees, and the input schema\n${deps.catalog.actions.map((action) => `- ${action.id}: ${action.description} Input: ${json(withoutDialect(action.schema))}`).join('\n') || 'none'}`) satisfies Producer<ComposerDeps>;
|
|
23
|
+
|
|
24
|
+
export const readCatalog = (({ deps }) =>
|
|
25
|
+
`READS — what it answers, its rows, and the params it is asked with\n${deps.catalog.reads.map((read) => `- ${read.fingerprint}: ${read.intent}. Rows: ${json(read.shape)}. Params: ${json(read.contextKeys)}`).join('\n') || 'none'}`) satisfies Producer<ComposerDeps>;
|
|
26
|
+
|
|
27
|
+
export const writeCatalog = (({ deps }) =>
|
|
28
|
+
`WRITES — what it does, and the keys of the fields a form saves through it\n${deps.catalog.writes.map((write) => `- ${write.fingerprint}: ${write.intent}. Fields: ${json(write.contextKeys)}`).join('\n') || 'none'}`) satisfies Producer<ComposerDeps>;
|
|
29
|
+
|
|
30
|
+
export const screenCatalog = (({ deps }) => `SCREENS\n${deps.screens.map((screen) => `- ${screen.id}: ${screen.description}`).join('\n')}`) satisfies Producer<ComposerDeps>;
|
|
31
|
+
|
|
32
|
+
export const arrangementCatalog = (({ deps }) =>
|
|
33
|
+
`ARRANGEMENTS — and their areas, row by row\n${deps.arrangements.map((arrangement) => `- ${arrangement.id}: ${arrangement.description} Areas: ${areaRows(arrangement.layout)}`).join('\n')}`) satisfies Producer<ComposerDeps>;
|
|
34
|
+
|
|
35
|
+
const canvasLine = (canvas: OpenCanvas): string => {
|
|
36
|
+
const what = canvas.action === 'answer.text' ? `words ${json({ title: canvas.input['title'], text: canvas.input['text'] })}` : `input ${json(canvas.input)}`;
|
|
37
|
+
const shows = Object.keys(canvas.shows).length > 0 ? ` — shows ${json(canvas.shows)}` : '';
|
|
38
|
+
return `- ${canvas.area}: ${canvas.action} — ${canvas.intent} — ${what}${shows}`;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// A hint that finds nothing likely reads as "nothing belongs in the answer", so the model is not given one.
|
|
42
|
+
const picksLine = (picks: Picks): string | undefined => {
|
|
43
|
+
const kinds = Object.entries(picks).map(([kind, scored]) => ({ kind, likely: scored.filter((item) => item.probability >= 0.5).map((item) => `${item.name} ${item.probability.toFixed(2)}`) }));
|
|
44
|
+
if (kinds.every(({ likely }) => likely.length === 0)) return undefined;
|
|
45
|
+
return kinds.map(({ kind, likely }) => `${kind} ${likely.length > 0 ? likely.join(', ') : 'none'}`).join('; ');
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const messageInput = (message: string, open: readonly OpenCanvas[], arrangement: { id: string; layout: LayoutNode }, picks: Picks | undefined): string => {
|
|
49
|
+
const hint = picks === undefined ? undefined : picksLine(picks);
|
|
50
|
+
return [
|
|
51
|
+
`OPEN SCREEN — arrangement ${arrangement.id}: ${areaRows(arrangement.layout)}`,
|
|
52
|
+
...(open.length === 0 ? ['nothing'] : open.map(canvasLine)),
|
|
53
|
+
...(hint === undefined ? [] : ['', `A FAST PICKER THINKS (a hint; how likely each belongs in the answer): ${hint}`]),
|
|
54
|
+
'',
|
|
55
|
+
`MESSAGE: ${message}`,
|
|
56
|
+
].join('\n');
|
|
57
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { LayoutNodeSchema } from '@niscorp/nova';
|
|
3
|
+
import type { LayoutNode } from '@niscorp/nova';
|
|
4
|
+
import type { Arrangement } from '../../app/arrangements';
|
|
5
|
+
import { AREAS } from '../../app/shell/areas';
|
|
6
|
+
import type { AreaId } from '../../app/shell/areas';
|
|
7
|
+
import { isRecord, recordOf } from './record';
|
|
8
|
+
|
|
9
|
+
export const AreaIdSchema = z.enum(AREAS);
|
|
10
|
+
|
|
11
|
+
export type WrittenLayout = { layout: LayoutNode; areas: AreaId[] };
|
|
12
|
+
|
|
13
|
+
type Grid = { columns: number; areas: readonly { name: AreaId; span?: number | null | undefined }[] };
|
|
14
|
+
|
|
15
|
+
export const areasInLayout = (layout: unknown): AreaId[] => {
|
|
16
|
+
if (Array.isArray(layout)) return layout.flatMap(areasInLayout);
|
|
17
|
+
if (!isRecord(layout)) return [];
|
|
18
|
+
const name = AreaIdSchema.safeParse(recordOf(layout['props'])['name']);
|
|
19
|
+
return [...(layout['component'] === 'Area' && name.success ? [name.data] : []), ...areasInLayout(layout['children'])];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// "a (the whole width); b c; d e"
|
|
23
|
+
export const areaRows = (layout: unknown): string => {
|
|
24
|
+
const node = recordOf(layout);
|
|
25
|
+
const columnsProp = recordOf(node['props'])['columns'];
|
|
26
|
+
const columns = typeof columnsProp === 'number' ? columnsProp : 1;
|
|
27
|
+
const rows: string[][] = [[]];
|
|
28
|
+
let used = 0;
|
|
29
|
+
for (const area of Array.isArray(node['children']) ? node['children'] : []) {
|
|
30
|
+
const props = recordOf(recordOf(area)['props']);
|
|
31
|
+
const span = Math.min(typeof props['span'] === 'number' ? props['span'] : 1, columns);
|
|
32
|
+
if (used + span > columns) {
|
|
33
|
+
rows.push([]);
|
|
34
|
+
used = 0;
|
|
35
|
+
}
|
|
36
|
+
rows[rows.length - 1]?.push(`${String(props['name'])}${span === columns && columns > 1 ? ' (the whole width)' : span > 1 ? ` (${span} columns)` : ''}`);
|
|
37
|
+
used += span;
|
|
38
|
+
}
|
|
39
|
+
return rows.map((row) => row.join(' ')).join('; ');
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const areasOfArrangement = (arrangement: string | WrittenLayout, arrangements: readonly Arrangement[]): AreaId[] =>
|
|
43
|
+
typeof arrangement === 'object' ? arrangement.areas : AREAS.slice(0, arrangements.find((candidate) => candidate.id === arrangement)?.areaCount ?? 0);
|
|
44
|
+
|
|
45
|
+
export const arrangementFor = (asked: string | WrittenLayout, arrangements: readonly Arrangement[]): { arrangement: string; layout: LayoutNode } => {
|
|
46
|
+
if (typeof asked === 'object') return { arrangement: 'written', layout: asked.layout };
|
|
47
|
+
const named = arrangements.find((arrangement) => arrangement.id === asked) ?? arrangements[0];
|
|
48
|
+
return { arrangement: named?.id ?? '', layout: named?.layout ?? { component: 'Grid' } };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const gridLayout = (grid: Grid): WrittenLayout => ({
|
|
52
|
+
layout: {
|
|
53
|
+
component: 'Grid',
|
|
54
|
+
props: { columns: grid.columns },
|
|
55
|
+
children: grid.areas.map(({ name, span }) => ({ component: 'Area', props: { name, span: span ?? 1 }, children: [{ component: 'CanvasSlot', props: { canvasId: name } }] })),
|
|
56
|
+
},
|
|
57
|
+
areas: grid.areas.map(({ name }) => name),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// The areas an answer changed are marked for the kit to outline; parsed back, so what is swapped in is a layout.
|
|
61
|
+
export const markChanged = (layout: LayoutNode, changed: readonly AreaId[]): LayoutNode => {
|
|
62
|
+
const mark = (node: unknown): unknown => {
|
|
63
|
+
if (Array.isArray(node)) return node.map(mark);
|
|
64
|
+
if (!isRecord(node)) return node;
|
|
65
|
+
const props = recordOf(node['props']);
|
|
66
|
+
const marked = node['component'] === 'Area' && changed.some((area) => area === props['name']) ? { ...node, props: { ...props, changed: true } } : node;
|
|
67
|
+
return 'children' in marked ? { ...marked, children: mark(marked['children']) } : marked;
|
|
68
|
+
};
|
|
69
|
+
return LayoutNodeSchema.parse(mark(layout));
|
|
70
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Usage } from '@niscorp/cortex';
|
|
2
|
+
import type { Screen } from '../../app/screens';
|
|
3
|
+
import type { Catalog } from './catalog';
|
|
4
|
+
import type { OpenCanvas } from './screen';
|
|
5
|
+
|
|
6
|
+
type Question = { type: 'noul'; instructions: string };
|
|
7
|
+
type Picked = { yes: boolean; probability?: number };
|
|
8
|
+
|
|
9
|
+
export type Decide = (state: Record<string, unknown>, questions: Record<string, Question>) => Promise<{ picked: Record<string, Picked>; usage: Usage }>;
|
|
10
|
+
|
|
11
|
+
const KINDS = ['actions', 'reads', 'writes', 'screens'] as const;
|
|
12
|
+
type Kind = (typeof KINDS)[number];
|
|
13
|
+
type Candidate = { name: string; says: string };
|
|
14
|
+
|
|
15
|
+
export type Picks = Record<Kind, { name: string; probability: number }[]>;
|
|
16
|
+
|
|
17
|
+
const ASK: Record<Kind, (name: string) => string> = {
|
|
18
|
+
actions: (name) => `Does the answer to the message need actions["${name}"]?`,
|
|
19
|
+
reads: (name) => `Does the message ask for what reads["${name}"] answers?`,
|
|
20
|
+
writes: (name) => `Does the message ask to do what writes["${name}"] does?`,
|
|
21
|
+
screens: (name) => `Does the message ask to see screens["${name}"] as it is?`,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const probabilityOf = (picked: Picked | undefined): number => picked?.probability ?? (picked?.yes === true ? 1 : 0);
|
|
25
|
+
|
|
26
|
+
// The state carries what each candidate is, in words; each question names its candidate by key.
|
|
27
|
+
export const pick = async (message: string, open: readonly OpenCanvas[], catalog: Catalog, screens: readonly Screen[], decide: Decide): Promise<{ picks: Picks; usage: Usage }> => {
|
|
28
|
+
const candidates: Record<Kind, Candidate[]> = {
|
|
29
|
+
actions: catalog.actions.map((action) => ({ name: action.id, says: action.description })),
|
|
30
|
+
reads: catalog.reads.map((read) => ({ name: read.fingerprint, says: read.intent })),
|
|
31
|
+
writes: catalog.writes.map((write) => ({ name: write.fingerprint, says: write.intent })),
|
|
32
|
+
screens: screens.map((screen) => ({ name: screen.id, says: screen.description })),
|
|
33
|
+
};
|
|
34
|
+
const state = {
|
|
35
|
+
message,
|
|
36
|
+
open_screen: Object.fromEntries(open.map((canvas) => [canvas.area, canvas.intent])),
|
|
37
|
+
...Object.fromEntries(KINDS.map((kind) => [kind, Object.fromEntries(candidates[kind].map(({ name, says }) => [name, says]))])),
|
|
38
|
+
};
|
|
39
|
+
const questions = Object.fromEntries(KINDS.flatMap((kind) => candidates[kind].map(({ name }, at): [string, Question] => [`${kind}${at}`, { type: 'noul', instructions: ASK[kind](name) }])));
|
|
40
|
+
|
|
41
|
+
const { picked, usage } = await decide(state, questions);
|
|
42
|
+
const scored = (kind: Kind): Picks[Kind] => candidates[kind].map(({ name }, at) => ({ name, probability: probabilityOf(picked[`${kind}${at}`]) }));
|
|
43
|
+
return { picks: { actions: scored('actions'), reads: scored('reads'), writes: scored('writes'), screens: scored('screens') }, usage };
|
|
44
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { LayoutNode } from '@niscorp/nova';
|
|
2
|
+
import type { Arrangement } from '../../app/arrangements';
|
|
3
|
+
import type { Canvas } from '../../app/screens';
|
|
4
|
+
import { AREAS } from '../../app/shell/areas';
|
|
5
|
+
import type { AreaId } from '../../app/shell/areas';
|
|
6
|
+
import { areasInLayout, arrangementFor } from './layout';
|
|
7
|
+
import type { WrittenLayout } from './layout';
|
|
8
|
+
|
|
9
|
+
export type AreaCanvases = Partial<Record<AreaId, Canvas>>;
|
|
10
|
+
|
|
11
|
+
export type Said = { title: string; text: string };
|
|
12
|
+
|
|
13
|
+
// Each area's canvas sits in an array, as nova's `reconcile` takes it.
|
|
14
|
+
export type Plan = {
|
|
15
|
+
question: string;
|
|
16
|
+
response?: string;
|
|
17
|
+
label: string;
|
|
18
|
+
screen?: string;
|
|
19
|
+
canvases: Partial<Record<AreaId, Canvas[]>>;
|
|
20
|
+
arrangement: string;
|
|
21
|
+
layout: LayoutNode;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type ShownPlan = Plan & { position: number; total: number; stack: { position: number; label: string }[] };
|
|
25
|
+
|
|
26
|
+
export const wordsCanvas = (said: Said): Canvas => ({ action: 'answer.text', input: { title: said.title, text: said.text }, intent: `the words "${said.title}"` });
|
|
27
|
+
|
|
28
|
+
export const canvasesInAreas = (canvases: readonly Canvas[]): AreaCanvases => Object.fromEntries(canvases.slice(0, AREAS.length).map((canvas, at) => [AREAS[at], canvas]));
|
|
29
|
+
|
|
30
|
+
export const canvasesOfPlan = (plan: Plan): AreaCanvases => Object.fromEntries(AREAS.flatMap((area) => plan.canvases[area]?.slice(0, 1).map((canvas) => [area, canvas]) ?? []));
|
|
31
|
+
|
|
32
|
+
export const changedAreas = (now: Plan, before: Plan): AreaId[] =>
|
|
33
|
+
AREAS.filter((area) => now.canvases[area] !== undefined && JSON.stringify(now.canvases[area]) !== JSON.stringify(before.canvases[area]));
|
|
34
|
+
|
|
35
|
+
export const arrangementOfPlan = (plan: Plan): string | WrittenLayout => (plan.arrangement === 'written' ? { layout: plan.layout, areas: areasInLayout(plan.layout) } : plan.arrangement);
|
|
36
|
+
|
|
37
|
+
type PlanOptions = { arrangements: readonly Arrangement[]; arrangement: string | WrittenLayout; label?: string; screen?: { id: string; label: string } };
|
|
38
|
+
|
|
39
|
+
export const planOf = (question: string, canvases: AreaCanvases, options: PlanOptions): Plan => ({
|
|
40
|
+
question,
|
|
41
|
+
label: options.screen?.label ?? options.label ?? question,
|
|
42
|
+
...(options.screen !== undefined ? { screen: options.screen.id } : {}),
|
|
43
|
+
canvases: Object.fromEntries(AREAS.flatMap((area) => (canvases[area] !== undefined ? [[area, [canvases[area]]]] : []))),
|
|
44
|
+
...arrangementFor(options.arrangement, options.arrangements),
|
|
45
|
+
});
|