create-nisc 0.9.2 → 0.9.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +20 -22
  3. package/dist/{chunk-RUHOVTHF.js → chunk-2W7KLXCO.js} +3 -3
  4. package/dist/{chunk-RUHOVTHF.js.map → chunk-2W7KLXCO.js.map} +1 -1
  5. package/dist/cli.js +1 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +1 -1
  8. package/templates/base/files/src/ui/kit.css +8 -41
  9. package/templates/dom/files/src/ui/kit.ts +2 -8
  10. package/templates/dom/files/src/ui/registry.ts +2 -2
  11. package/templates/model-first/agents-section.md +31 -25
  12. package/templates/model-first/files/src/app/action-catalog.ts +4 -3
  13. package/templates/model-first/files/src/app/actions/answer/turn.action.ts +23 -0
  14. package/templates/model-first/files/src/app/actions/ask/dock.action.ts +10 -33
  15. package/templates/model-first/files/src/app/actions/ask/dock.layout.ts +7 -39
  16. package/templates/model-first/files/src/app/actions/guide/guide.actions.ts +16 -19
  17. package/templates/model-first/files/src/app/app.ts +4 -3
  18. package/templates/model-first/files/src/app/charter/charter.ts +1 -1
  19. package/templates/model-first/files/src/app/screens.ts +27 -48
  20. package/templates/model-first/files/src/app/shell/frame.layout.ts +5 -1
  21. package/templates/model-first/files/src/app/shell/shell.ts +7 -10
  22. package/templates/model-first/files/src/dev/all-checks.ts +3 -3
  23. package/templates/model-first/files/src/dev/artifacts-check.ts +14 -25
  24. package/templates/model-first/files/src/dev/compose-check.ts +87 -136
  25. package/templates/model-first/files/src/dev/guide-check.ts +41 -58
  26. package/templates/model-first/files/src/dev/live-ask.ts +43 -138
  27. package/templates/model-first/files/src/dev/scripted.ts +24 -102
  28. package/templates/model-first/files/src/dev/shape-check.ts +2 -6
  29. package/templates/model-first/files/src/dev/strata.ts +2 -2
  30. package/templates/model-first/files/src/server/boot.ts +2 -2
  31. package/templates/model-first/files/src/server/compose/catalog.ts +10 -28
  32. package/templates/model-first/files/src/server/compose/composer.agent.ts +13 -11
  33. package/templates/model-first/files/src/server/compose/index.ts +55 -132
  34. package/templates/model-first/files/src/server/compose/knowledge.ts +22 -43
  35. package/templates/model-first/files/src/server/compose/turn.schema.ts +55 -0
  36. package/templates/model-first/files/src/server/models/index.ts +5 -23
  37. package/templates/model-first/item.json +28 -38
  38. package/templates/react/files/src/ui/kit.tsx +14 -25
  39. package/templates/react/files/src/ui/registry.ts +2 -2
  40. package/templates/model-first/files/src/app/arrangements.ts +0 -17
  41. package/templates/model-first/files/src/app/shell/areas.ts +0 -3
  42. package/templates/model-first/files/src/server/compose/answer.ts +0 -145
  43. package/templates/model-first/files/src/server/compose/history.ts +0 -45
  44. package/templates/model-first/files/src/server/compose/layout.ts +0 -70
  45. package/templates/model-first/files/src/server/compose/pick.ts +0 -44
  46. package/templates/model-first/files/src/server/compose/plan.ts +0 -45
  47. package/templates/model-first/files/src/server/compose/reply.schema.ts +0 -70
  48. package/templates/model-first/files/src/server/compose/screen.ts +0 -40
@@ -1,170 +1,93 @@
1
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';
2
+ import type { SignalClient } from '@niscorp/cortex';
3
+ import type { FunctionDefinition, FunctionSession, ShellManifest } from '@niscorp/moss';
6
4
  import { SCREENS } from '../../app/screens';
7
- import type { Screen } from '../../app/screens';
8
- import type { AreaId } from '../../app/shell/areas';
5
+ import type { Card } from '../../app/screens';
9
6
  import { recordModelRun } from '../runs';
10
- import { answerOf, answerSoFar, refusalsOf } from './answer';
11
- import type { AnswerContext } from './answer';
12
- import { CATALOG, opened } from './catalog';
7
+ import { CATALOG } from './catalog';
13
8
  import type { Catalog } from './catalog';
14
9
  import { composerAgent } from './composer.agent';
15
- import { createHistory } from './history';
16
10
  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';
11
+ import type { Said } from './knowledge';
12
+ import { cardsOf, turnRefusals } from './turn.schema';
24
13
 
25
- export type { Decide } from './pick';
26
-
27
- export type Jev = { provider: string; model: string; decide: Decide };
28
14
  export type Chat = { provider: string; model: string; llm: SignalClient; timeoutMs: number };
29
15
 
30
- export type Models = { jev?: Jev; chat?: Chat; missing: readonly string[] };
16
+ export type Models = { chat?: Chat; missing: readonly string[] };
31
17
 
32
- const AskSchema = z.looseObject({ text: z.string() });
18
+ const AskSchema = z.looseObject({ asked: z.string() });
33
19
  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
20
 
38
- const NO_USAGE: Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0, reported: false };
21
+ // How many turns the model is told of: enough to follow on from, short enough to stay fast.
22
+ const SAID = 4;
39
23
 
40
- const screenOf = (plan: Plan): string => JSON.stringify([plan.canvases, plan.layout, plan.label]);
24
+ // A shell is built on the first screen: its cards on the screen canvas, one under another.
25
+ export const firstScreen: NonNullable<ShellManifest['seeds']> = () => ({ screen: SCREENS[0].cards.map(({ action, input }) => ({ action, input })) });
41
26
 
42
27
  export const composer =
43
28
  (models: Models): ((session: FunctionSession) => FunctionDefinition[]) =>
44
29
  (session) => {
45
30
  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 };
31
+ const catalog: Catalog = { actions: CATALOG.actions.filter((action) => held.has(action.id)) };
32
+ // The conversation lives as long as this shell: the turns on its `talk` canvas, and what they said, here.
33
+ const said: Said[] = [];
34
+
35
+ // The question goes into the conversation at once, still being answered; nothing on `talk` is a step Back takes.
36
+ const begin = (question: string): ((reply: string, cards?: readonly Card[]) => void) => {
37
+ const turn = session.shell.push('talk', 'answer.turn', { question, reply: '', thinking: true }, undefined, { history: false });
38
+ return (reply, cards = []) => {
39
+ session.shell.getRuntime(turn)?.setData({ question, reply, thinking: false });
40
+ said.push({ question, reply, shown: cards.map((card) => (card.action === 'answer.text' ? 'words' : card.action)) });
41
+ for (const card of cards) session.shell.push('talk', card.action, card.input, undefined, { history: false });
42
+ };
90
43
  };
91
44
 
92
- const ask = async (data: unknown): Promise<ShownPlan> => {
93
- const message = AskSchema.parse(data).text.trim();
94
- if (message === '') return history.current();
45
+ const answer = async (message: string): Promise<void> => {
46
+ const finish = begin(message);
95
47
  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' });
48
+ if (chat === undefined) {
49
+ finish(`Set ${models.missing.join(' and ')} in .env, and start the app again.`);
50
+ return;
112
51
  }
113
-
114
- const current = arrangementOfPlan(before);
115
- const context: AnswerContext = { ...deps, open: canvasesOfPlan(before), current };
116
52
  const agent = composerAgent((envelope) => {
117
- const refused = refusalsOf(envelope.data, context);
53
+ const refused = turnRefusals(envelope.data, catalog);
118
54
  return refused.length === 0 ? { ok: true } : { retry: refused.map((reason) => `- ${reason}`).join('\n') };
119
55
  });
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;
56
+ const result = await agent.run(messageInput(message, said.slice(-SAID)), { llm: chat.llm, deps: { catalog }, signal: AbortSignal.timeout(chat.timeoutMs) }).result;
133
57
  const { usage, steps, elapsedMs } = result.meta;
134
58
  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
59
  if (!result.ok) {
140
60
  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.');
61
+ console.error(`[ask] "${message}" got no answer: ${code}${stop === undefined ? '' : ` (${stop})`}: ${reason}`);
62
+ finish(code === 'aborted' || code === 'model_call_failed' ? 'I could not be reached just now. Ask again in a moment.' : 'I could not answer that one. Ask again, or put it differently.');
63
+ return;
144
64
  }
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));
65
+ finish(result.output.response?.trim() ?? '', cardsOf(result.output.data, catalog));
66
+ };
67
+
68
+ // One message at a time, in the order they were sent: one asked while another is answered waits for it.
69
+ let answering: Promise<void> = Promise.resolve();
70
+ const ask = async (data: unknown): Promise<{ asked: boolean }> => {
71
+ const message = AskSchema.parse(data).asked.trim();
72
+ if (message === '') return { asked: false };
73
+ const answered = answering.then(() => answer(message));
74
+ answering = answered.catch(() => undefined);
75
+ await answered;
76
+ return { asked: true };
155
77
  };
156
78
 
157
- const open = async (data: unknown): Promise<ShownPlan> => {
79
+ // A screen is the cards of it the person's roles reach, one under another: what was on the screen canvas goes, and they are
80
+ // put there in order.
81
+ const open = async (data: unknown): Promise<{ screen: string }> => {
158
82
  const screen = SCREENS.find((candidate) => candidate.id === OpenSchema.parse(data).opening);
159
- return screen === undefined ? history.current() : leave(() => showScreen(screen));
83
+ if (screen === undefined) throw new Error('There is no such screen.');
84
+ for (const shown of session.shell.getState().canvases['screen']?.stack ?? []) session.shell.removeInstance('screen', shown.id);
85
+ for (const card of screen.cards) if (held.has(card.action)) session.shell.push('screen', card.action, card.input, undefined, { history: false });
86
+ return { screen: screen.id };
160
87
  };
161
88
 
162
89
  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() },
90
+ { id: 'ask', description: 'Answers a message with a turn of the conversation: a sentence, and the cards under it. Send { text }.', execute: ask },
91
+ { id: 'screens.open', description: 'Shows one of the screens in the dock: its cards, one under another. Send { opening: <screen id> }; answers { screen }.', execute: open },
169
92
  ];
170
93
  };
@@ -1,57 +1,36 @@
1
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
2
  import type { Catalog } from './catalog';
7
- import { areaRows } from './layout';
8
- import type { Picks } from './pick';
9
3
  import { recordOf } from './record';
10
- import type { OpenCanvas } from './screen';
11
4
 
12
- export type ComposerDeps = { catalog: Catalog; screens: readonly Screen[]; arrangements: readonly Arrangement[] };
5
+ export type ComposerDeps = { catalog: Catalog };
13
6
 
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.`;
7
+ // What a turn said, for the model to follow on from: what was asked, the sentence, and the cards shown.
8
+ export type Said = { question: string; reply: string; shown: string[] };
20
9
 
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>;
10
+ // The app's own paragraph: who the assistant is, and what it answers about. The rest is how a turn is made.
11
+ const ABOUT = 'You are the assistant of this app, a short tour of nisc. You answer questions about nisc and about this tour, with the tour’s cards.';
23
12
 
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>;
13
+ export const INSTRUCTIONS = `${ABOUT}
14
+ Each message gets one turn of a conversation: your response, and under it up to three cards that show the answer.
15
+ Cards are the app's own CARDS, each opened with an input its schema takes. Prefer them to words: when a card shows what was asked, show it. Fill in what the person asked for ("a counter that starts at 100").
16
+ Words, as a card (say), only for what no card shows.
17
+ Your response: one plain sentence of at most 120 characters that answers them. Never name ids.
18
+ What no card shows and you do not know, say so: never make anything up.
19
+ You never save anything and never press anything: a card you open is filled in, and the person does the rest.
20
+ A message may follow on from CONVERSATION SO FAR ("and the next one?"). Do not show again a card the last turn showed, unless the message asks for it changed.
21
+ Answer in the language they write in.`;
26
22
 
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>;
23
+ const json = (value: unknown): string => JSON.stringify(value);
34
24
 
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
- };
25
+ const withoutDialect = (schema: unknown): Record<string, unknown> => Object.fromEntries(Object.entries(recordOf(schema)).filter(([key]) => key !== '$schema'));
40
26
 
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
- };
27
+ export const cardCatalog = (({ deps }) =>
28
+ `CARDS — what each shows, and its input\n${deps.catalog.actions.map((action) => `- ${action.id}: ${action.description} Input: ${json(withoutDialect(action.schema))}`).join('\n') || 'none'}`) satisfies Producer<ComposerDeps>;
47
29
 
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}`]),
30
+ export const messageInput = (message: string, said: readonly Said[]): string =>
31
+ [
32
+ 'CONVERSATION SO FAR',
33
+ ...(said.length === 0 ? ['nothing yet: this is its first message'] : said.map((turn) => `- they asked: ${json(turn.question)} — you said: ${json(turn.reply)} — shown: ${turn.shown.join(', ') || 'nothing'}`)),
54
34
  '',
55
35
  `MESSAGE: ${message}`,
56
36
  ].join('\n');
57
- };
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+ import type { Card } from '../../app/screens';
3
+ import { opened } from './catalog';
4
+ import type { Catalog } from './catalog';
5
+
6
+ // One turn, as the model writes it: the cards under its sentence. The sentence itself is cortex's envelope's `response`.
7
+ export const CardSchema = z
8
+ .object({
9
+ action: z.string().nullish().describe('Shows a card: the id of one of the CARDS.'),
10
+ input: z.record(z.string(), z.unknown()).nullish().describe('What the card is opened with, as its input schema says: what the person asked for, filled in.'),
11
+ say: z
12
+ .object({
13
+ title: z.string().max(60).describe('A few words.'),
14
+ text: z.string().max(240).describe('At most two short sentences.'),
15
+ })
16
+ .strict()
17
+ .nullish()
18
+ .describe('Words, as a card: only for what no card shows.'),
19
+ })
20
+ .strict()
21
+ .describe('One card: exactly one of action with input, or say.');
22
+
23
+ export const TurnSchema = z
24
+ .object({
25
+ cards: z.array(CardSchema).max(3).nullish().describe('Up to three cards under your sentence that show the answer, the most important first; none when the sentence says it all.'),
26
+ })
27
+ .strict();
28
+
29
+ export type Turn = z.infer<typeof TurnSchema>;
30
+
31
+ export const turnRefusals = (turn: Turn, catalog: Catalog): string[] => {
32
+ const seen = new Set<string>();
33
+ return (turn.cards ?? []).flatMap((card, at) => {
34
+ const where = `cards[${String(at)}]`;
35
+ const isAction = card.action !== undefined && card.action !== null;
36
+ const isSay = card.say !== undefined && card.say !== null;
37
+ if (isAction === isSay) return [`${where}: give exactly one of "action" with "input", or "say".`];
38
+ if (!isAction) return [];
39
+ const same = JSON.stringify([card.action, card.input ?? {}]);
40
+ if (seen.has(same)) return [`${where}: shows the same as an earlier card; show it once.`];
41
+ seen.add(same);
42
+ const known = catalog.actions.find((candidate) => candidate.id === card.action);
43
+ if (known === undefined) return [`${where}: there is no card "${String(card.action)}".`];
44
+ const parsed = known.check.safeParse(card.input ?? {});
45
+ return parsed.success ? [] : parsed.error.issues.map((issue) => `${where}: input.${issue.path.join('.')}: ${issue.message}`);
46
+ });
47
+ };
48
+
49
+ // The cards as they are placed: words as the words card, any other as itself, opened with its whole input.
50
+ export const cardsOf = (turn: Turn, catalog: Catalog): Card[] =>
51
+ (turn.cards ?? []).flatMap((card): Card[] => {
52
+ if (card.say) return [{ action: 'answer.text', input: { title: card.say.title.trim(), text: card.say.text.trim() } }];
53
+ if (!card.action) return [];
54
+ return [opened({ action: card.action, input: card.input ?? {} }, catalog)];
55
+ });
@@ -1,35 +1,17 @@
1
- import { z } from 'zod';
2
1
  import { createSignal } from '@niscorp/signal';
3
- import type { Chat, Jev, Models } from '../compose';
2
+ import type { Chat, Models } from '../compose';
4
3
 
5
4
  type Env = Readonly<Record<string, string | undefined>>;
6
5
 
7
- const JEV = { provider: 'typesafe', model: 'jev-latest' };
8
6
  const CHAT = { provider: 'groq', model: 'openai/gpt-oss-120b' };
9
7
 
10
- // Jev answers in about 200 ms and the chat model in about one second, its slowest measured near 4 s. A Jev pass given up
11
- // is answered by the chat model alone; a chat run given up is a line saying the model could not be reached.
12
- const JEV_MS = 2_000;
8
+ // The chat model answers in about one second, its slowest measured near 4 s; a run given up is a turn saying it could not
9
+ // be reached.
13
10
  const CHAT_MS = 8_000;
14
11
 
15
- const DecisionsSchema = z.record(z.string(), z.looseObject({ answer: z.boolean(), noul: z.number().optional() }));
16
-
17
- // Without a TypeSafe key there is no Jev pass: the chat model could answer its questions too, but far slower than its
18
- // budget allows.
19
12
  export const modelsFromEnv = (env: Env): Models & { summary: string } => {
20
13
  const has = (name: string): boolean => (env[name] ?? '').trim() !== '';
21
- const decider = has('TYPESAFE_API_KEY') ? createSignal('typesafe').model(JEV.model) : undefined;
22
-
23
- const jev: Jev | undefined = decider && {
24
- ...JEV,
25
- decide: async (state, questions) => {
26
- const result = await decider.decide({ state, questions, options: { signal: AbortSignal.timeout(JEV_MS) } });
27
- const picked = Object.fromEntries(Object.entries(DecisionsSchema.parse(result.decisions)).map(([name, decision]) => [name, { yes: decision.answer, ...(decision.noul !== undefined ? { probability: decision.noul } : {}) }]));
28
- return { picked, usage: result.meta.usage };
29
- },
30
- };
31
14
  const chat: Chat | undefined = has('GROQ_API_KEY') ? { ...CHAT, llm: createSignal('groq', { options: { reasoningEffort: 'low' } }).model(CHAT.model), timeoutMs: CHAT_MS } : undefined;
32
-
33
- const summary = [jev !== undefined ? 'Jev picks' : 'no Jev pass (no TYPESAFE_API_KEY)', chat !== undefined ? 'gpt-oss-120b composes' : 'nothing composes (no GROQ_API_KEY)'].join(' · ');
34
- return { ...(jev !== undefined ? { jev } : {}), ...(chat !== undefined ? { chat } : {}), missing: has('GROQ_API_KEY') ? [] : ['GROQ_API_KEY'], summary };
15
+ const summary = chat !== undefined ? 'gpt-oss-120b answers' : 'nothing answers (no GROQ_API_KEY)';
16
+ return { ...(chat !== undefined ? { chat } : {}), missing: has('GROQ_API_KEY') ? [] : ['GROQ_API_KEY'], summary };
35
17
  };
@@ -2,8 +2,8 @@
2
2
  "id": "model-first",
3
3
  "answers": "kind",
4
4
  "label": "A model — model-first",
5
- "hint": "every message is answered with a screen composed from the app's actions",
6
- "usage": "a model leads: each message is answered with a screen composed from the app's actions",
5
+ "hint": "every message is answered with a sentence and the app's own cards",
6
+ "usage": "a model leads: each message is answered with a sentence and the app's own cards, in a conversation",
7
7
  "summary": "model-first",
8
8
  "requires": {
9
9
  "shell": "moss"
@@ -18,68 +18,58 @@
18
18
  "env": [
19
19
  {
20
20
  "name": "GROQ_API_KEY",
21
- "message": "Groq API key — gpt-oss-120b composes each answer",
21
+ "message": "Groq API key — gpt-oss-120b answers each message",
22
22
  "required": true
23
- },
24
- {
25
- "name": "TYPESAFE_API_KEY",
26
- "message": "TypeSafe API key — Jev's pass over the message and the open screen, in about 200 ms; without it the chat model answers alone"
27
23
  }
28
24
  ],
29
25
  "docs": {
30
- "is": "led by a model: every message is answered with a screen composed from the app's actions",
26
+ "is": "led by a model: every message is answered with a sentence and the app's own cards",
31
27
  "where": [
32
28
  "src/app/actions/guide/ the tour of nisc the app starts with: cards to read, and a counter, a checklist and a quick check to use — it goes first (below, \"How to proceed from here\")",
33
- "src/app/action-catalog.ts every action, and `placeable`: the ones the model may put on a screen",
34
- "src/app/screens.ts the screens in the dock — the tour's lessons: canvases shown together; the first is the one the app opens on",
35
- "src/app/arrangements.ts how an answer is laid out: layouts for the frame’s `answers` region, and what each is for",
36
- "src/server/compose/ the message loop: the open screen read, Jev's pass, gpt-oss-120b composes, the plan is placed",
37
- " catalog.ts what the model is given to place: the `placeable` actions, the reads, the writes",
38
- " screen.ts the open screen, read",
39
- " pick.ts Jev's pass",
40
- " composer.agent.ts the composer: a cortex agent",
41
- " knowledge.ts what it is told: its instructions, the catalog as producers, the run’s input",
42
- " reply.schema.ts what it replies, each field described",
43
- " answer.ts what refuses a reply, and the answer a reply is turned into",
44
- " layout.ts arrangements and the grids the model writes, as layouts",
45
- " plan.ts, history.ts the answer as a plan, and the stack of them",
46
- " index.ts the functions the dock calls",
47
- "src/server/models/ the models, from .env",
48
- "src/server/runs/ each model's part in a message recorded as a run, and the line the server logs for it",
29
+ "src/app/action-catalog.ts every action, and `placeable`: the ones the model may show",
30
+ "src/app/actions/ask/ the dock: the conversation, the screens, and the line to ask in",
31
+ "src/app/actions/answer/ a turn of the conversation, and words as a card",
32
+ "src/app/screens.ts the screens in the dock — the tour's lessons: cards shown one under another; the first is the one the app opens on",
33
+ "src/server/compose/ the message loop: gpt-oss-120b answers, the answer is checked, the turn goes into the conversation",
34
+ " catalog.ts the cards the model may show: the `placeable` actions, each with its input schema",
35
+ " knowledge.ts what it is told: its instructions (the first paragraph is the app's own), the cards, the conversation so far",
36
+ " turn.schema.ts what it answers with, each field described; what refuses an answer",
37
+ " composer.agent.ts the model, as a cortex agent",
38
+ " index.ts the functions the dock calls: `ask`, `screens.open`",
39
+ "src/server/models/ the model, from .env",
40
+ "src/server/runs/ each message recorded as a run, and the line the server logs for it",
49
41
  "src/app/vex/ your reads and writes, one file of entries per entity — the tour's read, `guide/packages`, until the tour goes",
50
42
  "src/db/ your tables, as a strata sequence — the tour's `packages` until the tour goes"
51
43
  ],
52
44
  "decisions": [
53
45
  "| D3 Reads | answered | **Vex entries**, read by an action by its fingerprint (`/api/vex`), under the person's policy. One so far: the tour's packages card replays `guide/packages`, its rows worded by the entry's Prism mapping (`src/app/vex/guide.entries.ts`). |",
54
46
  "| D4 Writes | answered | **Vex mutation entries**, posted to `/api/vex` by a form the person saves, never by the model. None yet. |",
55
- "| D6 Who answers a message | answered | Jev reads the message and the open screen (`TYPESAFE_API_KEY`), then gpt-oss-120b on Groq composes the screen as a cortex agent (`GROQ_API_KEY`), with what Jev picked as a hint. Without a TypeSafe key there is no Jev pass. Jev may take 2 s and the model 8 s; past that, the model answers alone, or the line says it could not be reached and the screen stays as it is. Measured on the tour's cases (`src/dev/live-ask.ts --runs=2`): 30/32 right with Jev, 31/32 without, and about 200 ms slower with it. |",
56
- "| D7 What a screen is made of | answered | Canvases: an action the model may place (`placeable`, in `src/app/action-catalog.ts`), opened with an input its schema takes, and why it is there; or words. Up to six, on the areas `a`–`f`; the screens in the dock are canvases too (`src/app/screens.ts`). |",
57
- "| D8 History | derived · **open** | The answers one shell was given, kept while it lives; a reload starts again. An answer keeps what the person did on it when it is left — a count, a step ticked, a pick — as a browser keeps a page's form, so going back shows it as they left it. Open: whether a person's answers outlive the shell, and memory beyond that. |",
58
- "| D9 Layout swaps | derived · **open: sign-in** | An answer’s arrangement is swapped into the frame’s `answers` region through moss’s unverified shell (`@niscorp/moss/unverified`, in `src/server/compose/index.ts`), because moss lets a session change a layout only through a draft, and a draft needs a signed-in person. **When the app has sign-in, the swap moves to `session.draft`, where moss checks it.** |",
59
- "| D10 What keeps a canvas in place | answered | **The model answers by area.** It names only the areas that change — a canvas moved from another area, a new one, words, or nothing — and an area it leaves out stays as it is, the same canvas: a card filled in never moves the others. |",
60
- "| D11 Jev's \"still wanted?\" | answered | **Not asked.** On ten follow-ups Jev was right 8 of 14 times, and with its answer the model dropped what was open. |",
61
- "| D12 What a card written onto a screen keeps | derived | **Nothing of what was there.** A canvas the model or a screen writes holds its whole input: what it leaves out is its action's default, so a checklist written where another was shows none of its ticks, and a new quick check opens unpicked. A canvas an answer leaves alone keeps what the person did to it. |"
47
+ "| D6 Who answers a message | answered | **gpt-oss-120b on Groq, as a cortex agent** (`GROQ_API_KEY`), effort low, one run a message — one call, and another for each answer sent back. It has 8 s; past that, the turn says it could not be reached. |",
48
+ "| D7 What an answer is | answered | **A turn of the conversation:** one sentence it is told to keep to 120 characters, and under it up to three cards — one of the app's `placeable` actions the person's roles reach, opened with an input its schema takes, or words. The answer is checked (the card exists, its input fits, nothing shown twice); one that fails is sent back with what is wrong, five tries in all. The screen behind is never changed by an answer. |",
49
+ "| D8 The conversation | derived · **open** | **It lasts as long as the person's shell:** for somebody not signed in, one connection — a reload, or a phone that reconnects, starts it again. The model is told its last four turns. Open: whether it outlives the shell. That needs sign-in, and then the turns are rows the person owns. |",
50
+ "| D9 Screens | derived | **Cards one under another,** opened from the dock or by a card's link, never by the model. A screen opened again is opened fresh: what was pressed on it before is not kept. |"
62
51
  ],
63
52
  "answered": [
64
- "**Who leads:** a model. A message is answered with a screen: Jev reads the message and the open screen, gpt-oss-120b composes the screen from the app's actions, and the dock places it on the six areas. The keys are in `.env`."
53
+ "**Who leads:** a model. A message is answered with a turn of the conversation: gpt-oss-120b writes a sentence and picks up to three of the app's cards, filled in. The key is in `.env`."
65
54
  ],
66
55
  "open": [
67
56
  "The entities, and how they relate — and what a person will ask about them.",
68
57
  "Expected scale.",
69
58
  "Who uses it: one person, or roles. More than one principal sketches its roles and charter now, not later.",
70
- "Memory: what the app keeps of a person between messages.",
59
+ "Memory: what the app keeps of a person between messages (D8).",
71
60
  "Look and feel.",
72
61
  "Where it is deployed.",
73
62
  "What happens to the data long-term."
74
63
  ],
75
64
  "order": [
76
65
  "**The interview** — every open item above, answered or delegated by name. ← here",
77
- "**Scaffold** — done: the frame, the message loop, the dock, a tour of nisc in five screens — cards to read, one of them a read of a table through vex, and a counter, a checklist and a quick check to use, which the model can fill in too — and their checks.",
66
+ "**Scaffold** — done: the frame, the message loop, the dock with the conversation, a tour of nisc in five screens — cards to read, one of them a read of a table through vex, and a counter, a checklist and a quick check to use, which the model can fill in too — and their checks.",
78
67
  "**Data** — the tour goes first (AGENTS.md, \"How to proceed from here\"); then, per D2/D3, your tables in `src/db/schema.ts`, your reads in `src/app/vex/`, each replayed by the action that shows it, its words in the entry's `mapping` — as the tour's packages card does.",
79
- "**Actions** — your own, small: one purpose each, a description that says what it shows, an `input` schema for what the model fills in; the ones the model may place in `placeable`, each granted in the charter.",
80
- "**Screens** — the ones a person will want in the dock, each its canvases; the first the one the app opens on.",
81
- "**Writes** — per D4; a form an answer opens, filled in by the model, saved by the person.",
82
- "**Checks** — a check for each feature in `src/dev/`, beside `compose-check.ts`, which runs the loop offline; and `live-ask` cases for what people will ask, run against the real models before a change to an action's description or to the instructions is kept."
68
+ "**Actions** — your own, small: one purpose each, a description that says what it shows, an `input` schema for what the model fills in; the ones the model may show in `placeable`, each granted in the charter.",
69
+ "**The assistant** — its paragraph in `src/server/compose/knowledge.ts`: who it is, and what it answers about.",
70
+ "**Screens** — the ones a person will want in the dock, each its cards; the first the one the app opens on.",
71
+ "**Writes** — per D4; a form the model opens, filled in, saved by the person.",
72
+ "**Checks** — a check for each feature in `src/dev/`, beside `compose-check.ts`, which runs the loop offline; and `live-ask` cases for what people will ask, run against the real model before a change to an action's description or to the instructions is kept."
83
73
  ]
84
74
  }
85
75
  }
@@ -44,10 +44,10 @@ Text.meta = { description: 'A paragraph.', propsSchema: TextProps };
44
44
  const ButtonProps = z.object({
45
45
  label: z.string().optional().describe('What the button says; falls back to its children.'),
46
46
  tone: z
47
- .enum(['primary', 'suggestion', 'link', 'choice', 'chosen', 'right', 'wrong', 'summary', 'step'])
47
+ .enum(['primary', 'suggestion', 'link', 'choice', 'chosen', 'right', 'wrong', 'step'])
48
48
  .optional()
49
49
  .describe(
50
- 'primary: what the action does | suggestion: a thing to ask | link: opens another screen | choice: one of a set to choose from | chosen: the one of the set that is chosen | right: the right one of a set, once picked | wrong: a wrong one, picked | summary: names what is shown, and opens to more | step: back, forward, or start over',
50
+ 'primary: what the action does | suggestion: a thing to ask | link: opens another screen | choice: one of a set to choose from | chosen: the one of the set that is chosen | right: the right one of a set, once picked | wrong: a wrong one, picked | step: start over, or try again',
51
51
  ),
52
52
  value: z.unknown().optional().describe('Sent with the click as its payload.'),
53
53
  });
@@ -66,19 +66,23 @@ export const Button: NovaComponent = ({ children, novaRef, novaModel: _model, ..
66
66
  };
67
67
  Button.meta = { description: 'A button; dispatches ui:click with its ref, and its value as the payload.', propsSchema: ButtonProps };
68
68
 
69
- const FrameProps = z.object({}).describe('The whole app: the answer, and the dock under it.');
69
+ const FrameProps = z.object({}).describe('The whole app: the screen, and the dock under it.');
70
70
  export const Frame: NovaComponent = ({ children }) => <div className="k-frame">{children}</div>;
71
71
  Frame.meta = { description: 'The whole app, top to bottom.', propsSchema: FrameProps };
72
72
 
73
- const DockProps = z.object({}).describe('What stays at the bottom while the answer scrolls above it.');
73
+ const DockProps = z.object({}).describe('What stays at the bottom while the screen scrolls above it.');
74
74
  export const Dock: NovaComponent = ({ children }) => <footer className="k-dock">{children}</footer>;
75
- Dock.meta = { description: 'What stays at the bottom while the answer scrolls above it.', propsSchema: DockProps };
75
+ Dock.meta = { description: 'What stays at the bottom while the screen scrolls above it.', propsSchema: DockProps };
76
76
 
77
- const MenuProps = z.object({}).describe('A list that opens above the dock: one choice a line.');
78
- export const Menu: NovaComponent = ({ children }) => <nav className="k-menu">{children}</nav>;
79
- Menu.meta = { description: 'A list that opens above the dock.', propsSchema: MenuProps };
77
+ const TalkProps = z.object({}).describe('The conversation, in the dock: it scrolls, and shows its newest turn.');
78
+ export const Talk: NovaComponent = ({ children }) => (
79
+ <section className="k-talk">
80
+ <div>{children}</div>
81
+ </section>
82
+ );
83
+ Talk.meta = { description: 'The conversation, in the dock: it scrolls, and shows its newest turn.', propsSchema: TalkProps };
80
84
 
81
- const GridProps = z.object({ columns: z.number().int().min(1).max(3).optional().describe('How many columns its areas are laid out in: 1 to 3.') });
85
+ const GridProps = z.object({ columns: z.number().int().min(1).max(3).optional().describe('How many columns its cards are laid out in: 1 to 3.') });
82
86
  export const Grid: NovaComponent = ({ children, novaRef: _ref, novaModel: _model, ...props }) => {
83
87
  const { columns } = parsed(GridProps, props, {});
84
88
  return (
@@ -87,22 +91,7 @@ export const Grid: NovaComponent = ({ children, novaRef: _ref, novaModel: _model
87
91
  </main>
88
92
  );
89
93
  };
90
- Grid.meta = { description: 'Areas in columns, row by row.', propsSchema: GridProps };
91
-
92
- const AreaProps = z.object({
93
- name: z.string().describe('Which canvas it holds.'),
94
- span: z.number().int().min(1).max(3).optional().describe('How many columns it takes.'),
95
- changed: z.boolean().optional().describe('Whether the last answer changed what it holds.'),
96
- });
97
- export const Area: NovaComponent = ({ children, novaRef: _ref, novaModel: _model, ...props }) => {
98
- const { span, changed } = parsed(AreaProps, props, { name: '' });
99
- return (
100
- <section className={`k-area k-span-${span ?? 1}${changed === true ? ' k-area-changed' : ''}`}>
101
- {children}
102
- </section>
103
- );
104
- };
105
- Area.meta = { description: 'One area of an answer.', propsSchema: AreaProps };
94
+ Grid.meta = { description: 'Cards in columns, row by row.', propsSchema: GridProps };
106
95
 
107
96
  const CardProps = z.object({
108
97
  title: z.string().optional().describe('What the card shows, in a few words.'),