@faces-sh/cli 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -33
- package/dist/chat-command.d.ts +2 -0
- package/dist/chat.d.ts +2 -0
- package/dist/choices.d.ts +9 -0
- package/dist/choices.js +17 -1
- package/dist/client.d.ts +8 -0
- package/dist/client.js +37 -0
- package/dist/commands/chat/chat.d.ts +2 -0
- package/dist/commands/chat/messages.d.ts +2 -0
- package/dist/commands/chat/responses.d.ts +2 -0
- package/dist/commands/chat/thread.d.ts +2 -0
- package/dist/commands/choices.d.ts +3 -0
- package/dist/commands/choices.js +36 -0
- package/dist/commands/conversation/add.d.ts +2 -0
- package/dist/commands/conversation/add.js +5 -2
- package/dist/commands/conversation/create.d.ts +2 -0
- package/dist/commands/conversation/create.js +4 -2
- package/dist/commands/decide.d.ts +31 -0
- package/dist/commands/decide.js +84 -4
- package/dist/commands/face/list.d.ts +2 -0
- package/dist/commands/face/list.js +23 -1
- package/dist/commands/premise/add.d.ts +30 -0
- package/dist/commands/premise/add.js +86 -0
- package/dist/commands/premise/choices.d.ts +21 -0
- package/dist/commands/premise/choices.js +68 -0
- package/dist/commands/premise/claim.d.ts +20 -0
- package/dist/commands/premise/claim.js +38 -0
- package/dist/commands/premise/decide.d.ts +18 -0
- package/dist/commands/premise/decide.js +36 -0
- package/dist/commands/premise/delete.d.ts +17 -0
- package/dist/commands/premise/delete.js +17 -0
- package/dist/commands/premise/edit.d.ts +28 -0
- package/dist/commands/premise/edit.js +51 -0
- package/dist/commands/premise/get.d.ts +22 -0
- package/dist/commands/premise/get.js +37 -0
- package/dist/commands/premise/refine.d.ts +20 -0
- package/dist/commands/premise/refine.js +80 -0
- package/dist/commands/state/create.d.ts +13 -2
- package/dist/commands/state/create.js +55 -2
- package/dist/commands/state/get.d.ts +19 -2
- package/dist/commands/state/get.js +30 -2
- package/dist/commands/state/use.d.ts +16 -0
- package/dist/commands/state/use.js +25 -0
- package/dist/conversation.d.ts +30 -3
- package/dist/conversation.js +202 -18
- package/dist/foreman.d.ts +47 -0
- package/dist/foreman.js +115 -0
- package/dist/refine.d.ts +106 -0
- package/dist/refine.js +601 -0
- package/dist/synopsis.d.ts +49 -0
- package/dist/synopsis.js +43 -0
- package/oclif.manifest.json +1415 -109
- package/package.json +5 -2
package/dist/refine.js
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
import { FacesAPIError } from './client.js';
|
|
2
|
+
import { CONVERSATIONS_PATH } from './conversation.js';
|
|
3
|
+
import { seg } from './utils.js';
|
|
4
|
+
export const AND = 'Before anything is done, "{P}" has to be broken into the conditions that together make ' +
|
|
5
|
+
'it true, and the choice here is which conditions to require. Propose each condition as an ' +
|
|
6
|
+
'option, written as "It holds only if: <a statement that is true or false of the finished ' +
|
|
7
|
+
'work>". Each must be needed: if it were false, "{P}" would be false. No two conditions ' +
|
|
8
|
+
'may be the same condition reworded, and none may be "{P}" in other words.';
|
|
9
|
+
export const AND_LEAD = 'It holds only if:';
|
|
10
|
+
export const OR = 'Before anything is done, the words "{P}" have to be pinned to one meaning, and the choice ' +
|
|
11
|
+
'here is which meaning to take them in. Propose each meaning they could be taken in as an ' +
|
|
12
|
+
'option, written as "Take it to mean: <a statement that is true or false of the finished ' +
|
|
13
|
+
'work>". Any two meanings must disagree about some concrete case.';
|
|
14
|
+
export const OR_LEAD = 'Take it to mean:';
|
|
15
|
+
export const NEEDED = 'Is "{k}: {v}" needed for "{P}"? It is needed if "{P}" would be false without it.';
|
|
16
|
+
export const GATE = 'Is "{k}: {v}" a condition on the finished work that covers only part of what "{P}" ' +
|
|
17
|
+
'requires, rather than a step to take or "{P}" in other words?';
|
|
18
|
+
export const GAP_ROUNDS = 3;
|
|
19
|
+
export const GAP_PROPOSE = 'The conditions already listed under "{P}" are required. Before anything is done, ' +
|
|
20
|
+
'the choice here is whether they leave out a condition that "{P}" also needs. ' +
|
|
21
|
+
'Propose each condition they leave out, as an option, written as "It holds only ' +
|
|
22
|
+
'if: <a statement that is true or false of the finished work>". Each must be ' +
|
|
23
|
+
'needed: if it were false, "{P}" would be false even with every listed condition ' +
|
|
24
|
+
'true. None may be a listed condition reworded, and none may be "{P}" in other ' +
|
|
25
|
+
'words.';
|
|
26
|
+
export const GAP_MAX = 4;
|
|
27
|
+
export const KIND = 'Before anything is done, "{P}" has to be settled, and the choice here is how it will be settled.';
|
|
28
|
+
export const KIND_OPTIONS = [
|
|
29
|
+
['and', 'split it into conditions',
|
|
30
|
+
'Its meaning is clear, but it holds only if several separate things are all true of the ' +
|
|
31
|
+
'finished work.'],
|
|
32
|
+
['or', 'pin it to one meaning',
|
|
33
|
+
'Its words leave open what exactly would make it true (which cases count, how it is ' +
|
|
34
|
+
'measured, how much is enough), and the possible meanings would change the finished work; ' +
|
|
35
|
+
'they can be listed and one chosen.'],
|
|
36
|
+
['test', 'one test settles it',
|
|
37
|
+
'It is already precise: one check, true or false of the finished work, settles it.'],
|
|
38
|
+
['human', 'ask the human',
|
|
39
|
+
'It is about a person\'s own response (whether they accept, like, approve or agree), which ' +
|
|
40
|
+
'no meaning of the words and no check of the work can settle.'],
|
|
41
|
+
];
|
|
42
|
+
export const TEST = 'Before anything is done, "{P}" has to be settled by one test run on the finished work. ' +
|
|
43
|
+
'Propose the test as an option, written as "Passes only if: <a statement that is true or ' +
|
|
44
|
+
'false of the finished work>. Reads: <the items or data it checks, by name>."';
|
|
45
|
+
export const TEST_LEAD = 'Passes only if:';
|
|
46
|
+
export const AWAIT_QUESTION = 'Before anything is done, "{P}" has to be settled by asking {who}, because only ' +
|
|
47
|
+
'they, or someone they can ask, know whether it holds. The choice here is which ' +
|
|
48
|
+
'question to put to {who}. Propose each question as an option, written as "Ask ' +
|
|
49
|
+
'{who}: <one question, ending with a question mark, about this case>, because ' +
|
|
50
|
+
'<why their answer is needed>". Each must be a question {who} can answer, and ' +
|
|
51
|
+
'its answer must settle "{P}".';
|
|
52
|
+
export const AWAIT_MAX = 2;
|
|
53
|
+
export const WHO = 'the human';
|
|
54
|
+
export const RECHECK = 'The premise "{P}" was rewritten and now reads: "{new}". Is "{k}: {v}" still a condition ' +
|
|
55
|
+
'it needs, as it now reads?';
|
|
56
|
+
export const NAME_LINE = 'Name each option by what it is, in a few words (e.g. the dishes themselves), and put the full statement in its description.';
|
|
57
|
+
export function named(question) {
|
|
58
|
+
return `${question}\n${NAME_LINE}`;
|
|
59
|
+
}
|
|
60
|
+
export const SAME = 'Is "{a}" the same condition as "{b}"?';
|
|
61
|
+
export const AT = 0.5;
|
|
62
|
+
export const CLEAR_P = 0.6;
|
|
63
|
+
export const CLEAR_MARGIN = 0.2;
|
|
64
|
+
export const SIMILAR_AT = 0.85;
|
|
65
|
+
export const DECISION_MODEL = process.env.FACES_REFINE_DECISION_MODEL?.trim() || 'jev-latest';
|
|
66
|
+
export const CONDITION_MODEL = process.env.FACES_REFINE_CONDITION_MODEL?.trim() || 'clef';
|
|
67
|
+
const MAX_PREDICATES = 10;
|
|
68
|
+
export function fill(t, vars) {
|
|
69
|
+
return t.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? vars[k] : m));
|
|
70
|
+
}
|
|
71
|
+
export function stripLead(text, lead) {
|
|
72
|
+
const esc = lead.replace(/:$/, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
73
|
+
const m = new RegExp(`^\\s*(["“]?)\\s*${esc}(?:\\s*:\\s*|\\s+)`, 'i').exec(text);
|
|
74
|
+
if (!m)
|
|
75
|
+
return text;
|
|
76
|
+
let rest = text.slice(m[0].length);
|
|
77
|
+
if (m[1] && /["”]\s*$/.test(rest))
|
|
78
|
+
rest = rest.trimEnd().slice(0, -1);
|
|
79
|
+
return rest.trim() || text;
|
|
80
|
+
}
|
|
81
|
+
export function plainKey(text, limit = 120) {
|
|
82
|
+
let t = text.replace(/[\u0000-\u001f\u007f--]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
83
|
+
if (t.length > limit) {
|
|
84
|
+
const cut = t.slice(0, limit + 1);
|
|
85
|
+
const at = cut.lastIndexOf(' ');
|
|
86
|
+
t = at > limit / 3 ? cut.slice(0, at) : t.slice(0, limit);
|
|
87
|
+
}
|
|
88
|
+
t = t.replace(/[\s,;:.\-\u2013\u2014]+$/, '').trim();
|
|
89
|
+
while ((t.match(/\(/g) ?? []).length > (t.match(/\)/g) ?? []).length) {
|
|
90
|
+
t = t.slice(0, t.lastIndexOf('(')).replace(/[\s,;:.\-\u2013\u2014]+$/, '').trim();
|
|
91
|
+
}
|
|
92
|
+
return t;
|
|
93
|
+
}
|
|
94
|
+
export function stripOptions(opts, lead = '') {
|
|
95
|
+
const base = (n) => norm(n).replace(/\s+\d+$/, '');
|
|
96
|
+
const count = new Map();
|
|
97
|
+
for (const o of opts)
|
|
98
|
+
count.set(base(o.name ?? ''), (count.get(base(o.name ?? '')) ?? 0) + 1);
|
|
99
|
+
return opts.map((o) => {
|
|
100
|
+
const bare = lead ? stripLead(o.description ?? o.name, lead) : (o.description ?? o.name);
|
|
101
|
+
const name = plainKey(lead ? stripLead(o.name ?? '', lead) : (o.name ?? ''));
|
|
102
|
+
const own = name && count.get(base(o.name ?? '')) === 1;
|
|
103
|
+
return { name: (own ? name : plainKey(String(bare ?? '').replace(/\.$/, ''))) || name, description: bare };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
export function readsOf(definition) {
|
|
107
|
+
const [head, tail] = definition.split(/\bReads:/, 2);
|
|
108
|
+
const statement = head.trim().replace(/\.$/, '').trim();
|
|
109
|
+
if (tail === undefined)
|
|
110
|
+
return { statement, reads: [] };
|
|
111
|
+
const reads = tail.replace(/\.\s*$/, '').split(/\s*[,;]\s*/)
|
|
112
|
+
.map((x) => x.trim().replace(/^and\s+/, '').replace(/^["“]|["”]$/g, '').replace(/\.$/, '').trim())
|
|
113
|
+
.filter(Boolean);
|
|
114
|
+
return { statement, reads };
|
|
115
|
+
}
|
|
116
|
+
export function asked(o) {
|
|
117
|
+
const re = /^\s*(?:Ask [^:,]{1,60}[:,]\s*)?["“‘']?(.+?\?)["”’']?(?:\s*,?\s*because\b[\s\S]*)?\s*$/;
|
|
118
|
+
for (const t of [o.description, o.name]) {
|
|
119
|
+
const m = re.exec(t ?? '');
|
|
120
|
+
if (m)
|
|
121
|
+
return m[1].trim();
|
|
122
|
+
}
|
|
123
|
+
return (o.description || o.name || '').trim();
|
|
124
|
+
}
|
|
125
|
+
export function condition(template, p, o) {
|
|
126
|
+
const same = norm(o.name) === norm(o.description.replace(/[.\s]+$/, ''));
|
|
127
|
+
return same ? fill(template.replace('"{k}: {v}"', '"{v}"'), { P: p, v: o.description })
|
|
128
|
+
: fill(template, { P: p, k: o.name, v: o.description });
|
|
129
|
+
}
|
|
130
|
+
function norm(x) {
|
|
131
|
+
return x.toLowerCase().replace(/\s+/g, ' ').trim();
|
|
132
|
+
}
|
|
133
|
+
export function clearWinner(probs) {
|
|
134
|
+
const order = Object.keys(probs).sort((a, b) => probs[b] - probs[a]);
|
|
135
|
+
if (order.length === 0)
|
|
136
|
+
return undefined;
|
|
137
|
+
const top = probs[order[0]];
|
|
138
|
+
const next = order.length > 1 ? probs[order[1]] : 0;
|
|
139
|
+
return top >= CLEAR_P - 1e-9 && top - next >= CLEAR_MARGIN - 1e-9 ? order[0] : undefined;
|
|
140
|
+
}
|
|
141
|
+
export class Loop {
|
|
142
|
+
client;
|
|
143
|
+
sid;
|
|
144
|
+
face;
|
|
145
|
+
as;
|
|
146
|
+
log;
|
|
147
|
+
calls = 0;
|
|
148
|
+
usage = { input_tokens: 0, output_tokens: 0 };
|
|
149
|
+
constructor(client, sid, face, as, log = () => { }) {
|
|
150
|
+
this.client = client;
|
|
151
|
+
this.sid = sid;
|
|
152
|
+
this.face = face;
|
|
153
|
+
this.as = as;
|
|
154
|
+
this.log = log;
|
|
155
|
+
}
|
|
156
|
+
state(route) {
|
|
157
|
+
return `${CONVERSATIONS_PATH}/${seg(this.sid)}${route}`;
|
|
158
|
+
}
|
|
159
|
+
async send(method, p, opts = {}) {
|
|
160
|
+
const got = await this.client.stateReply(method, p, opts);
|
|
161
|
+
if (!got.ok)
|
|
162
|
+
throw new FacesAPIError(got.status, String(got.data.error ?? got.data.text ?? 'refused'));
|
|
163
|
+
const u = got.data.usage;
|
|
164
|
+
if (u && (p === '/v1/choices' || p === '/v1/decisions')) {
|
|
165
|
+
if ((u.input_tokens ?? 0) + (u.output_tokens ?? 0) > 0)
|
|
166
|
+
this.calls++;
|
|
167
|
+
this.usage.input_tokens += u.input_tokens ?? 0;
|
|
168
|
+
this.usage.output_tokens += u.output_tokens ?? 0;
|
|
169
|
+
}
|
|
170
|
+
return got.data;
|
|
171
|
+
}
|
|
172
|
+
async premises() {
|
|
173
|
+
const d = await this.send('GET', this.state('/proof'), { params: { format: 'json', all: 'true' } });
|
|
174
|
+
const out = {};
|
|
175
|
+
for (const p of d.premises ?? [])
|
|
176
|
+
out[p.key] = p;
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
async propose(key, question, max, see = false) {
|
|
180
|
+
const body = { model: `${this.face}:maestro-1`, state_id: this.sid };
|
|
181
|
+
if (see)
|
|
182
|
+
body.depends_on = [key];
|
|
183
|
+
else
|
|
184
|
+
body.premise = key;
|
|
185
|
+
if (question)
|
|
186
|
+
body.instructions = question;
|
|
187
|
+
if (max)
|
|
188
|
+
body.max_choices = max;
|
|
189
|
+
const d = await this.send('POST', '/v1/choices', { body });
|
|
190
|
+
return (d.choices ?? []).map((c) => ({ name: c.name, description: c.description }));
|
|
191
|
+
}
|
|
192
|
+
async ownQuestion(key) {
|
|
193
|
+
const d = await this.send('POST', '/v1/choices', { body: { model: `${this.face}:maestro-1`, state_id: this.sid, premise: key } });
|
|
194
|
+
return String(d.question ?? '');
|
|
195
|
+
}
|
|
196
|
+
async write(into, kind, options) {
|
|
197
|
+
if (options.length === 0)
|
|
198
|
+
return { new: [], matched: [] };
|
|
199
|
+
const P = await this.premises();
|
|
200
|
+
const said = new Map();
|
|
201
|
+
for (const c of P[into]?.children ?? [])
|
|
202
|
+
if (P[c])
|
|
203
|
+
said.set(norm(String(P[c].value ?? '')).replace(/[.\s]+$/, ''), c);
|
|
204
|
+
const send = [];
|
|
205
|
+
const copies = [];
|
|
206
|
+
for (const o of options) {
|
|
207
|
+
const t = norm(o.description ?? '').replace(/[.\s]+$/, '');
|
|
208
|
+
const was = t ? said.get(t) : undefined;
|
|
209
|
+
if (was !== undefined) {
|
|
210
|
+
copies.push(was);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (t)
|
|
214
|
+
said.set(t, o.name);
|
|
215
|
+
send.push(o);
|
|
216
|
+
}
|
|
217
|
+
if (send.length === 0)
|
|
218
|
+
return { new: [], matched: copies };
|
|
219
|
+
const out = await this.sameElsewhere(into, send, P);
|
|
220
|
+
const d = await this.send('POST', '/v1/choices', { body: { state_id: this.sid, into, kind, options: out, ...(this.as ? { as: this.as } : {}) } });
|
|
221
|
+
for (const k of d.linked ?? []) {
|
|
222
|
+
const p = this.sameP.get(k);
|
|
223
|
+
this.log(`"${k}" already exists; linked it under "${into}"${p === undefined ? '' : ` (the same condition, p ${round(p)})`}.`);
|
|
224
|
+
}
|
|
225
|
+
for (const r of d.refused ?? [])
|
|
226
|
+
this.log(`"${r.key}" already exists, and was not linked under "${into}": ${r.why}.`);
|
|
227
|
+
return { new: d.new ?? [], matched: [...copies, ...(d.matched ?? [])] };
|
|
228
|
+
}
|
|
229
|
+
sameP = new Map();
|
|
230
|
+
async sameElsewhere(into, options, P) {
|
|
231
|
+
const siblings = new Set(P[into]?.children ?? []);
|
|
232
|
+
const above = new Set([into]);
|
|
233
|
+
const todo = [into];
|
|
234
|
+
while (todo.length) {
|
|
235
|
+
const x = todo.pop();
|
|
236
|
+
for (const [k, p] of Object.entries(P))
|
|
237
|
+
if (p.children.includes(x) && !above.has(k)) {
|
|
238
|
+
above.add(k);
|
|
239
|
+
todo.push(k);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const o of options) {
|
|
244
|
+
const hits = (await this.search(`${o.name}: ${o.description}`))
|
|
245
|
+
.filter(([k, s]) => s >= SIMILAR_AT && !siblings.has(k) && !above.has(k) && P[k]);
|
|
246
|
+
let same;
|
|
247
|
+
for (const [k] of hits.slice(0, 3)) {
|
|
248
|
+
const [p] = await this.predicates([fill(SAME, { a: `${o.name}: ${o.description}`, b: `${k}: ${String(P[k].value ?? '')}` })], [into, k], `${this.face}:maestro-1/${CONDITION_MODEL}`);
|
|
249
|
+
if (p >= AT) {
|
|
250
|
+
same = k;
|
|
251
|
+
this.sameP.set(k, p);
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
out.push(same ? { name: same, description: String(P[same].value ?? '') } : o);
|
|
256
|
+
}
|
|
257
|
+
return out;
|
|
258
|
+
}
|
|
259
|
+
async decide(questions, dependsOn, model) {
|
|
260
|
+
const d = await this.send('POST', '/v1/decisions', { body: {
|
|
261
|
+
model: model ?? `${this.face}:maestro-1/${DECISION_MODEL}`, conversation: this.sid, questions, depends_on: dependsOn
|
|
262
|
+
} });
|
|
263
|
+
return d.answers ?? [];
|
|
264
|
+
}
|
|
265
|
+
async predicates(texts, dependsOn, model) {
|
|
266
|
+
const out = [];
|
|
267
|
+
for (let i = 0; i < texts.length; i += MAX_PREDICATES) {
|
|
268
|
+
const part = texts.slice(i, i + MAX_PREDICATES);
|
|
269
|
+
const ans = await this.decide(part.map((t, j) => ({ type: 'predicate', name: `q${i + j}`, instructions: t })), dependsOn, model);
|
|
270
|
+
for (let j = 0; j < part.length; j++) {
|
|
271
|
+
const a = ans.find((x) => x.name === `q${i + j}`);
|
|
272
|
+
if (!a || a.type === 'refusal')
|
|
273
|
+
throw new FacesAPIError(503, `the decision model gave no answer to q${i + j}; retry`);
|
|
274
|
+
out.push(Number(a.probability ?? 0));
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
async choice(name, instructions, values, dependsOn) {
|
|
280
|
+
const ans = await this.decide([{ type: 'choice', name, instructions,
|
|
281
|
+
choices: values.map(([value, description]) => ({ value, description: description.slice(0, 1000) })) }], dependsOn);
|
|
282
|
+
const a = ans.find((x) => x.name === name);
|
|
283
|
+
if (!a || a.type === 'refusal')
|
|
284
|
+
throw new FacesAPIError(503, `the decision model gave no answer to ${name}; retry`);
|
|
285
|
+
const probs = {};
|
|
286
|
+
for (const p of a.probabilities ?? [])
|
|
287
|
+
probs[p.value] = Number(p.probability);
|
|
288
|
+
return probs;
|
|
289
|
+
}
|
|
290
|
+
async kind(key) {
|
|
291
|
+
const probs = await this.choice('kind', fill(KIND, { P: key }), KIND_OPTIONS.map(([, v, d]) => [v, d]), [key]);
|
|
292
|
+
const best = Object.keys(probs).sort((a, b) => probs[b] - probs[a])[0];
|
|
293
|
+
const k = KIND_OPTIONS.find(([, v]) => v === best);
|
|
294
|
+
if (!k)
|
|
295
|
+
throw new FacesAPIError(503, `the decision model chose no refinement for "${key}"; retry`);
|
|
296
|
+
return [k[0], probs[best]];
|
|
297
|
+
}
|
|
298
|
+
async judged(key, opts) {
|
|
299
|
+
if (opts.length === 0)
|
|
300
|
+
return [[], []];
|
|
301
|
+
const texts = opts.flatMap((o) => [condition(NEEDED, key, o), condition(GATE, key, o)]);
|
|
302
|
+
const ps = await this.predicates(texts, [key], `${this.face}:maestro-1/${CONDITION_MODEL}`);
|
|
303
|
+
const kept = opts.filter((_o, i) => Math.min(ps[2 * i], ps[2 * i + 1]) >= AT);
|
|
304
|
+
return [kept, opts.filter((o) => !kept.includes(o)).map((o) => o.name)];
|
|
305
|
+
}
|
|
306
|
+
async question(key, also = []) {
|
|
307
|
+
const q = fill(AWAIT_QUESTION, { P: key, who: WHO });
|
|
308
|
+
const deps = [key, ...also];
|
|
309
|
+
const d = await this.send('POST', '/v1/choices', { body: { model: `${this.face}:maestro-1`, state_id: this.sid,
|
|
310
|
+
depends_on: deps, instructions: q, max_choices: AWAIT_MAX } });
|
|
311
|
+
const opts = (d.choices ?? []);
|
|
312
|
+
if (opts.length === 0)
|
|
313
|
+
throw new FacesAPIError(503, `the face proposed no question about "${key}"; retry`);
|
|
314
|
+
let best = opts[0];
|
|
315
|
+
if (opts.length > 1) {
|
|
316
|
+
const probs = await this.choice('question', q, opts.map((o) => [o.name, o.description ?? '']), deps);
|
|
317
|
+
best = opts.reduce((a, b) => ((probs[b.name] ?? 0) > (probs[a.name] ?? 0) ? b : a));
|
|
318
|
+
}
|
|
319
|
+
return asked(best);
|
|
320
|
+
}
|
|
321
|
+
async edit(key, body) {
|
|
322
|
+
return this.send('PATCH', this.state('/premises'), { body: { key, ...body, ...(this.as ? { as: this.as } : {}) } });
|
|
323
|
+
}
|
|
324
|
+
async add(body) {
|
|
325
|
+
return this.send('POST', this.state('/premises'), { body: { ...body, ...(this.as ? { as: this.as } : {}) } });
|
|
326
|
+
}
|
|
327
|
+
async search(text, within) {
|
|
328
|
+
const d = within
|
|
329
|
+
? await this.send('GET', this.state('/premise'), { params: { key: within, query: text, format: 'json' } })
|
|
330
|
+
: await this.send('GET', this.state('/proof'), { params: { query: text, format: 'json' } });
|
|
331
|
+
return (d.matches ?? []).map((m) => [m.key, m.score]);
|
|
332
|
+
}
|
|
333
|
+
async awaitHuman(key, also = []) {
|
|
334
|
+
const q = await this.question(key, also);
|
|
335
|
+
await this.edit(key, { await: 'human', note: q });
|
|
336
|
+
return q;
|
|
337
|
+
}
|
|
338
|
+
async weigh(key) {
|
|
339
|
+
const d = await this.send('POST', '/v1/decisions', { body: { model: `${this.face}:maestro-1/${DECISION_MODEL}`,
|
|
340
|
+
conversation: this.sid, weigh: { premise: key, kind: 'or', ...(this.as ? { as: this.as } : {}) } } });
|
|
341
|
+
const w = d.weigh ?? {};
|
|
342
|
+
if (!w.written)
|
|
343
|
+
throw new FacesAPIError(503, `the ranking was not written: ${w.reason ?? 'retry'}`);
|
|
344
|
+
return Object.fromEntries((w.edges ?? []).map((e) => [e.id, e.p]));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
export async function refine(L, key) {
|
|
348
|
+
const P = await L.premises();
|
|
349
|
+
const n = P[key];
|
|
350
|
+
if (!n)
|
|
351
|
+
throw new FacesAPIError(404, `no premise "${key}" in this state`);
|
|
352
|
+
if (n.role === 'test')
|
|
353
|
+
throw new FacesAPIError(422, `"${key}" is a test: it is a leaf, settled by its runs (premise:edit --status --tested)`);
|
|
354
|
+
if (n.role === null && n.origin === 'human')
|
|
355
|
+
throw new FacesAPIError(422, `"${key}" is the human's word, an axiom: nothing refines it`);
|
|
356
|
+
if (n.refinement === 'incomplete' && n.op === 'and' && n.children.length > 0)
|
|
357
|
+
return recheck(L, key, P);
|
|
358
|
+
if (n.op === 'and')
|
|
359
|
+
return refineAnd(L, key);
|
|
360
|
+
if (n.op === 'or')
|
|
361
|
+
return refineOr(L, key);
|
|
362
|
+
const [kind, p] = await L.kind(key);
|
|
363
|
+
L.log(`"${key}" needs ${({ and: 'an AND-refinement', or: 'an OR-refinement', test: 'one test', human: 'the human' })[kind]} (p ${round(p)}).`);
|
|
364
|
+
if (kind === 'and')
|
|
365
|
+
return refineAnd(L, key);
|
|
366
|
+
if (kind === 'or')
|
|
367
|
+
return refineOr(L, key);
|
|
368
|
+
if (kind === 'test')
|
|
369
|
+
return refineTest(L, key, P);
|
|
370
|
+
const q = await L.awaitHuman(key);
|
|
371
|
+
return [`Only the human can settle "${key}": it awaits their answer to: ${q}`];
|
|
372
|
+
}
|
|
373
|
+
function round(p) {
|
|
374
|
+
return String(Math.round(p * 100) / 100);
|
|
375
|
+
}
|
|
376
|
+
async function refineAnd(L, key) {
|
|
377
|
+
const out = [];
|
|
378
|
+
const opts = stripOptions(await L.propose(key, named(fill(AND, { P: key }))), AND_LEAD);
|
|
379
|
+
const [kept, dropped] = await L.judged(key, opts);
|
|
380
|
+
const w = await L.write(key, 'and', kept);
|
|
381
|
+
out.push(`The face proposed ${opts.length} condition(s); ${kept.length} passed both judges.` +
|
|
382
|
+
(dropped.length ? ` Not written: ${dropped.map((d) => `"${d}"`).join(', ')}.` : '') +
|
|
383
|
+
(w.matched.length ? ` Matched one already there: ${w.matched.map((d) => `"${d}"`).join(', ')}.` : ''));
|
|
384
|
+
const gap = await gapLoop(L, key);
|
|
385
|
+
out.push(...gap.lines);
|
|
386
|
+
for (const c of [...w.new, ...gap.added]) {
|
|
387
|
+
const [ck, cp] = await L.kind(c);
|
|
388
|
+
if (ck === 'human') {
|
|
389
|
+
const q = await L.awaitHuman(c);
|
|
390
|
+
out.push(`Only the human can settle "${c}" (p ${round(cp)}): it awaits their answer to: ${q}`);
|
|
391
|
+
}
|
|
392
|
+
else if (ck === 'or') {
|
|
393
|
+
out.push(`"${c}" needs alternatives (premise:refine "${c}").`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (gap.empty)
|
|
397
|
+
return out;
|
|
398
|
+
out.push(gap.sufficient ? `Together they are sufficient for "${key}".`
|
|
399
|
+
: `After ${GAP_ROUNDS} rounds the gap check still finds conditions they leave out: its refinement is incomplete.`);
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
async function gapLoop(L, key) {
|
|
403
|
+
const added = [];
|
|
404
|
+
const lines = [];
|
|
405
|
+
let sufficient = false;
|
|
406
|
+
for (let round = 1; round <= GAP_ROUNDS; round++) {
|
|
407
|
+
const gaps = stripOptions(await L.propose(key, named(fill(GAP_PROPOSE, { P: key })), GAP_MAX, true), AND_LEAD);
|
|
408
|
+
const [passing] = await L.judged(key, gaps);
|
|
409
|
+
if (passing.length === 0) {
|
|
410
|
+
sufficient = true;
|
|
411
|
+
break;
|
|
412
|
+
}
|
|
413
|
+
const more = await L.write(key, 'and', passing);
|
|
414
|
+
if (more.new.length === 0) {
|
|
415
|
+
sufficient = true;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
lines.push(`The gap check added ${more.new.map((d) => `"${d}"`).join(', ')}.`);
|
|
419
|
+
added.push(...more.new);
|
|
420
|
+
}
|
|
421
|
+
if ((await L.premises())[key]?.children.length === 0) {
|
|
422
|
+
lines.push(`No condition passed both judges, so "${key}" has no refinement; nothing was recorded.`);
|
|
423
|
+
return { added, sufficient: false, lines, empty: true };
|
|
424
|
+
}
|
|
425
|
+
await L.edit(key, { refinement: sufficient ? 'complete' : 'incomplete', refined_by: 'refine' });
|
|
426
|
+
return { added, sufficient, lines };
|
|
427
|
+
}
|
|
428
|
+
async function refineOr(L, key) {
|
|
429
|
+
const out = [];
|
|
430
|
+
const opts = stripOptions(await L.propose(key, named(fill(OR, { P: key }))), OR_LEAD);
|
|
431
|
+
const w = await L.write(key, 'or', opts);
|
|
432
|
+
out.push(`Wrote ${w.new.length} candidate(s) under "${key}"` + (w.matched.length ? `; ${w.matched.length} matched one already there.` : '.'));
|
|
433
|
+
await L.edit(key, { refinement: 'complete', refined_by: 'refine' });
|
|
434
|
+
const P = await L.premises();
|
|
435
|
+
if (P[key].children.length < 2)
|
|
436
|
+
return out;
|
|
437
|
+
out.push(...(await rank(L, key, true)));
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
440
|
+
export async function rank(L, key, awaitOnTie = false) {
|
|
441
|
+
const probs = await L.weigh(key);
|
|
442
|
+
const order = Object.keys(probs).sort((a, b) => probs[b] - probs[a]);
|
|
443
|
+
const out = [`Ranked: ${order.map((k) => `"${k}" (p ${round(probs[k])})`).join(', ')}.`];
|
|
444
|
+
if (awaitOnTie && !clearWinner(probs)) {
|
|
445
|
+
const q = await L.awaitHuman(key);
|
|
446
|
+
out.push(`No candidate is clearly ahead, so only the human can settle which is meant: "${key}" awaits their answer to: ${q}`);
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
async function refineTest(L, key, P) {
|
|
451
|
+
const opts = await L.propose(key, fill(TEST, { P: key }), 1);
|
|
452
|
+
if (opts.length === 0)
|
|
453
|
+
throw new FacesAPIError(503, `the face proposed no test for "${key}"; retry`);
|
|
454
|
+
const raw = opts[0].description ?? opts[0].name;
|
|
455
|
+
const desc = stripLead(raw, TEST_LEAD);
|
|
456
|
+
const { statement, reads } = readsOf(desc);
|
|
457
|
+
const name = (desc !== raw && plainKey(statement)) || plainKey(opts[0].name);
|
|
458
|
+
const tests = P[key].children.filter((c) => P[c]?.role === 'test');
|
|
459
|
+
if (tests.length > 0) {
|
|
460
|
+
const same = tests.find((t) => norm(t) === norm(statement) || norm(String(P[t].value ?? '')) === norm(statement));
|
|
461
|
+
const hit = same ?? (await L.search(statement, key)).find(([k, s]) => tests.includes(k) && s >= SIMILAR_AT)?.[0];
|
|
462
|
+
if (hit) {
|
|
463
|
+
await L.edit(key, { refinement: 'complete', refined_by: 'refine' });
|
|
464
|
+
return [`"${key}" is settled by one test: the face proposed "${name}", which matches the test already under it, "${hit}". Nothing was written twice.`];
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const below = new Set(descendants(P, key).concat(key));
|
|
468
|
+
const above = new Set(ancestors(P, key).concat(key));
|
|
469
|
+
const ins = [];
|
|
470
|
+
const left = [];
|
|
471
|
+
for (const r of reads) {
|
|
472
|
+
const exact = Object.keys(P).find((k) => norm(k) === norm(r));
|
|
473
|
+
let hit = exact && ok(P, exact, below, above) ? exact : undefined;
|
|
474
|
+
if (!hit)
|
|
475
|
+
hit = (await L.search(r)).find(([k, s]) => s >= SIMILAR_AT && ok(P, k, below, above))?.[0];
|
|
476
|
+
if (hit && !ins.includes(hit))
|
|
477
|
+
ins.push(hit);
|
|
478
|
+
else if (!hit)
|
|
479
|
+
left.push(r);
|
|
480
|
+
}
|
|
481
|
+
let tk = name;
|
|
482
|
+
for (let i = 2; P[tk]; i++)
|
|
483
|
+
tk = `${name} (${i})`;
|
|
484
|
+
await L.add({ key: tk, value: desc, description: `the test of ${key}`, role: 'test', and: key, ...(ins.length ? { on: ins } : {}) });
|
|
485
|
+
await L.edit(key, { refinement: 'complete', refined_by: 'refine' });
|
|
486
|
+
return [`"${key}" is settled by one test, "${tk}": ${desc}`,
|
|
487
|
+
ins.length ? `It reads ${ins.map((x) => `"${x}"`).join(', ')}.` : 'It reads no premise of this state.',
|
|
488
|
+
...(left.length ? [`On its "Reads:" line, ${left.map((x) => `"${x}"`).join(', ')} match no premise of this state.`] : [])];
|
|
489
|
+
}
|
|
490
|
+
function ok(P, k, below, above) {
|
|
491
|
+
const p = P[k];
|
|
492
|
+
return Boolean(p) && !below.has(k) && !above.has(k) && p.role !== 'goal' && p.role !== 'test';
|
|
493
|
+
}
|
|
494
|
+
function descendants(P, k) {
|
|
495
|
+
const out = [];
|
|
496
|
+
const todo = [...(P[k]?.children ?? [])];
|
|
497
|
+
while (todo.length) {
|
|
498
|
+
const x = todo.shift();
|
|
499
|
+
if (!out.includes(x)) {
|
|
500
|
+
out.push(x);
|
|
501
|
+
todo.push(...(P[x]?.children ?? []));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return out;
|
|
505
|
+
}
|
|
506
|
+
function ancestors(P, k) {
|
|
507
|
+
const out = [];
|
|
508
|
+
const todo = Object.keys(P).filter((x) => P[x].children.includes(k));
|
|
509
|
+
while (todo.length) {
|
|
510
|
+
const x = todo.shift();
|
|
511
|
+
if (!out.includes(x)) {
|
|
512
|
+
out.push(x);
|
|
513
|
+
todo.push(...Object.keys(P).filter((y) => P[y].children.includes(x)));
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return out;
|
|
517
|
+
}
|
|
518
|
+
async function recheck(L, key, P) {
|
|
519
|
+
const out = [];
|
|
520
|
+
const now = String(P[key].value ?? '');
|
|
521
|
+
const human = (c) => P[c].origin === 'human' || (P[c].messages ?? []).some((m) => m.author === 'human');
|
|
522
|
+
const kids = P[key].children.filter((c) => P[c] && P[c].role !== 'test' && !human(c) && P[c].children.length === 0);
|
|
523
|
+
if (kids.length) {
|
|
524
|
+
const still = await L.predicates(kids.map((c) => fill(RECHECK, { P: key, new: now, k: c, v: String(P[c].value ?? '') })), [key, ...kids]);
|
|
525
|
+
for (const [i, c] of kids.entries()) {
|
|
526
|
+
if (1 - still[i] < AT)
|
|
527
|
+
continue;
|
|
528
|
+
const shared = Object.values(P).some((p) => p.key !== key && (p.children.includes(c) || p.on.includes(c)));
|
|
529
|
+
if (shared) {
|
|
530
|
+
await L.edit(key, { note: `"${c}" may no longer be needed for "${key}" as it now reads (p ${round(1 - still[i])}); other premises rest on it, so it stays.` });
|
|
531
|
+
out.push(`"${c}" may no longer be needed, but other premises rest on it, so it stays (noted).`);
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
await L.send('DELETE', `${CONVERSATIONS_PATH}/${seg(L.sid)}/premises`, { params: { key: c, ...(L.as ? { as: L.as } : {}) } });
|
|
535
|
+
out.push(`Cut "${c}": "${key}" no longer needs it as it now reads (p ${round(1 - still[i])}).`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const gap = await gapLoop(L, key);
|
|
540
|
+
out.push(...gap.lines);
|
|
541
|
+
out.push(gap.sufficient ? `Its sub-goals make "${key}" true as it now reads: its refinement is complete again.`
|
|
542
|
+
: `After ${GAP_ROUNDS} rounds the gap check still finds conditions they leave out: its refinement is incomplete.`);
|
|
543
|
+
return out;
|
|
544
|
+
}
|
|
545
|
+
export async function refineTree(L, root, depth, log = () => { }) {
|
|
546
|
+
const refined = [];
|
|
547
|
+
const beyond = [];
|
|
548
|
+
const awaits = new Set();
|
|
549
|
+
const seen = new Set();
|
|
550
|
+
let level = [root];
|
|
551
|
+
for (let d = 0; level.length > 0; d++) {
|
|
552
|
+
const next = [];
|
|
553
|
+
for (const key of level) {
|
|
554
|
+
if (seen.has(key))
|
|
555
|
+
continue;
|
|
556
|
+
seen.add(key);
|
|
557
|
+
let P = await L.premises();
|
|
558
|
+
let n = P[key];
|
|
559
|
+
if (!n || stops(n)) {
|
|
560
|
+
if (n?.await)
|
|
561
|
+
awaits.add(key);
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
const done = n.refinement === 'complete' && n.children.length > 0;
|
|
565
|
+
if (!done && d >= depth) {
|
|
566
|
+
beyond.push(key);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (!done) {
|
|
570
|
+
log(`== ${key}`);
|
|
571
|
+
for (const line of await refine(L, key))
|
|
572
|
+
log(line);
|
|
573
|
+
refined.push(key);
|
|
574
|
+
P = await L.premises();
|
|
575
|
+
n = P[key];
|
|
576
|
+
}
|
|
577
|
+
if (!n)
|
|
578
|
+
continue;
|
|
579
|
+
if (n.await) {
|
|
580
|
+
awaits.add(key);
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
if (n.op === 'or') {
|
|
584
|
+
const c = n.next_to_try;
|
|
585
|
+
if (c)
|
|
586
|
+
next.push(c);
|
|
587
|
+
}
|
|
588
|
+
else if (n.op === 'and') {
|
|
589
|
+
next.push(...n.children.filter((c) => P[c] && !stops(P[c])));
|
|
590
|
+
for (const c of n.children)
|
|
591
|
+
if (P[c]?.await)
|
|
592
|
+
awaits.add(c);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
level = next;
|
|
596
|
+
}
|
|
597
|
+
return { refined, awaits: [...awaits], beyond };
|
|
598
|
+
}
|
|
599
|
+
function stops(n) {
|
|
600
|
+
return n.role === 'test' || (n.role === null && n.origin === 'human') || Boolean(n.await);
|
|
601
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface FrontierItem {
|
|
2
|
+
key: string;
|
|
3
|
+
action: string;
|
|
4
|
+
reason?: string;
|
|
5
|
+
weight?: number;
|
|
6
|
+
path?: string[];
|
|
7
|
+
goals?: string[];
|
|
8
|
+
claimed_by?: string;
|
|
9
|
+
side_node?: string;
|
|
10
|
+
alternatives?: Array<string | {
|
|
11
|
+
key: string;
|
|
12
|
+
p: number;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
15
|
+
export interface Claim {
|
|
16
|
+
object?: string;
|
|
17
|
+
id: string;
|
|
18
|
+
key: string;
|
|
19
|
+
agent: string;
|
|
20
|
+
since?: string;
|
|
21
|
+
expires_at?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface Synopsis {
|
|
24
|
+
object?: string;
|
|
25
|
+
done?: boolean;
|
|
26
|
+
next?: string | null;
|
|
27
|
+
goals?: Array<{
|
|
28
|
+
key: string;
|
|
29
|
+
status?: string;
|
|
30
|
+
achieved?: boolean;
|
|
31
|
+
}>;
|
|
32
|
+
frontier?: FrontierItem[];
|
|
33
|
+
ready?: FrontierItem[];
|
|
34
|
+
groups?: Array<{
|
|
35
|
+
weight?: number;
|
|
36
|
+
items: Array<{
|
|
37
|
+
key: string;
|
|
38
|
+
action: string;
|
|
39
|
+
weight?: number;
|
|
40
|
+
}>;
|
|
41
|
+
}>;
|
|
42
|
+
claims?: Claim[];
|
|
43
|
+
outline?: string;
|
|
44
|
+
text?: string;
|
|
45
|
+
changed?: Array<Record<string, unknown>>;
|
|
46
|
+
}
|
|
47
|
+
export declare function synopsisLines(s: Synopsis, outline?: boolean): string[];
|
|
48
|
+
export declare function pickParallel(s: Synopsis, n: number): FrontierItem[];
|
|
49
|
+
export declare function nextLines(s: Synopsis, picked: FrontierItem[], claimed?: Claim[]): string[];
|