@faces-sh/cli 1.0.3 → 1.1.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.
Files changed (57) hide show
  1. package/README.md +71 -51
  2. package/dist/choices.d.ts +23 -0
  3. package/dist/choices.js +48 -0
  4. package/dist/commands/auth/connect.js +2 -2
  5. package/dist/commands/catalog/doctor.js +9 -68
  6. package/dist/commands/causes.d.ts +2 -0
  7. package/dist/commands/causes.js +2 -2
  8. package/dist/commands/{fidelity/run.d.ts → choices.d.ts} +9 -8
  9. package/dist/commands/choices.js +86 -0
  10. package/dist/commands/conversation/add.d.ts +2 -0
  11. package/dist/commands/conversation/add.js +21 -10
  12. package/dist/commands/conversation/close.js +5 -5
  13. package/dist/commands/conversation/compact.js +9 -9
  14. package/dist/commands/conversation/create.d.ts +2 -0
  15. package/dist/commands/conversation/create.js +14 -12
  16. package/dist/commands/conversation/get.js +4 -4
  17. package/dist/commands/conversation/items.js +5 -5
  18. package/dist/commands/decide.d.ts +3 -0
  19. package/dist/commands/decide.js +20 -3
  20. package/dist/commands/face/get.js +1 -1
  21. package/dist/commands/fidelity/pick.js +2 -2
  22. package/dist/commands/models/list.js +7 -3
  23. package/dist/commands/session/close.js +1 -1
  24. package/dist/commands/session/compact.js +2 -2
  25. package/dist/commands/session/create.js +2 -2
  26. package/dist/commands/session/get.js +1 -1
  27. package/dist/commands/state/add.d.ts +3 -0
  28. package/dist/commands/state/add.js +3 -0
  29. package/dist/commands/state/close.d.ts +3 -0
  30. package/dist/commands/state/close.js +3 -0
  31. package/dist/commands/state/compact.d.ts +3 -0
  32. package/dist/commands/state/compact.js +3 -0
  33. package/dist/commands/state/create.d.ts +3 -0
  34. package/dist/commands/state/create.js +3 -0
  35. package/dist/commands/state/get.d.ts +3 -0
  36. package/dist/commands/state/get.js +3 -0
  37. package/dist/commands/state/items.d.ts +3 -0
  38. package/dist/commands/state/items.js +3 -0
  39. package/dist/commands/style/make.js +2 -6
  40. package/dist/conversation.d.ts +27 -2
  41. package/dist/conversation.js +91 -16
  42. package/dist/fidelity.js +3 -3
  43. package/oclif.manifest.json +1794 -2187
  44. package/package.json +9 -9
  45. package/dist/commands/chat/chat.d.ts +0 -47
  46. package/dist/commands/chat/chat.js +0 -376
  47. package/dist/commands/chat/messages.d.ts +0 -30
  48. package/dist/commands/chat/messages.js +0 -148
  49. package/dist/commands/chat/responses.d.ts +0 -31
  50. package/dist/commands/chat/responses.js +0 -159
  51. package/dist/commands/chat/thread.d.ts +0 -50
  52. package/dist/commands/chat/thread.js +0 -472
  53. package/dist/commands/fidelity/run.js +0 -99
  54. package/dist/commands/fidelity/start.d.ts +0 -17
  55. package/dist/commands/fidelity/start.js +0 -56
  56. package/dist/commands/fidelity/turn.d.ts +0 -17
  57. package/dist/commands/fidelity/turn.js +0 -48
@@ -1,472 +0,0 @@
1
- import { Args, Flags } from '@oclif/core';
2
- import crypto from 'node:crypto';
3
- import fs from 'node:fs';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import { BaseCommand } from '../../base.js';
7
- import { conversationFields, conversationTurnFlags } from '../../conversation.js';
8
- import { FacesAPIError } from '../../client.js';
9
- import { postChat, streamChat, resolveCause, CAUSE_FLAG_DESCRIPTION, CAUSE_FILE_FLAG_DESCRIPTION, retryOnceOnWarmUp, sayWarmUp, faceRefusalHint, STREAM_FLAG_DESCRIPTION, extractCause, extractStreamDelta, FACES_REASONING_ITEM_PREFIX, FACES_THINKING_SIGNATURE, extractStreamReasoning, isMaxTokensRenameError, MIN_MAX_OUTPUT_TOKENS, STYLE_FLAG_DESCRIPTION, MEDIUM_FLAG_DESCRIPTION, SESSION_FLAG_DESCRIPTION, COMPACTION_FLAG_DESCRIPTION, chatExtras, reasoningHeading, REASONING_FLAG_DESCRIPTION, parseTemperature } from '../../utils.js';
10
- import { resolveEndpoint, isCompositeFormula, llmFromArg, MESSAGES_ENDPOINT, RESPONSES_ENDPOINT, CHAT_COMPLETIONS_ENDPOINT } from '../../routing.js';
11
- const THREADS_DIR = path.join(os.homedir(), '.faces', 'threads');
12
- function extractAssistantText(body, endpoint) {
13
- if (endpoint === MESSAGES_ENDPOINT) {
14
- let text = '';
15
- for (const block of body.content ?? []) {
16
- if (block.type === 'text')
17
- text += String(block.text ?? '');
18
- }
19
- return text;
20
- }
21
- if (endpoint === RESPONSES_ENDPOINT) {
22
- let text = '';
23
- for (const item of body.output ?? []) {
24
- for (const block of item.content ?? []) {
25
- if (block.type === 'output_text')
26
- text += String(block.text ?? '');
27
- }
28
- }
29
- return text;
30
- }
31
- const choices = body.choices;
32
- return String(choices?.[0]?.message?.content ?? '');
33
- }
34
- function replyOf(body, endpoint) {
35
- const cause = extractCause(body, endpoint);
36
- const message = body.choices?.[0]?.message;
37
- const modelReasoning = endpoint === CHAT_COMPLETIONS_ENDPOINT && message?.reasoning_content ? String(message.reasoning_content) : undefined;
38
- return { text: extractAssistantText(body, endpoint), reasoning: cause.text, causeId: cause.id, modelReasoning };
39
- }
40
- function chatTurn(m) {
41
- const turn = { role: m.role, content: m.content };
42
- if (m.role === 'assistant' && m.cause)
43
- turn.cause = m.cause;
44
- if (m.role === 'assistant' && m.reasoning_content)
45
- turn.reasoning_content = m.reasoning_content;
46
- return turn;
47
- }
48
- function responsesTurns(m) {
49
- const turn = { role: m.role, content: m.content };
50
- if (m.role !== 'assistant' || !m.cause || !m.cause_id)
51
- return [turn];
52
- return [{ type: 'reasoning', id: m.cause_id, summary: [{ type: 'summary_text', text: m.cause }] }, turn];
53
- }
54
- function messagesTurn(m) {
55
- if (m.role !== 'assistant' || !m.cause)
56
- return { role: m.role, content: m.content };
57
- return {
58
- role: m.role,
59
- content: [
60
- { type: 'thinking', thinking: m.cause, signature: FACES_THINKING_SIGNATURE },
61
- { type: 'text', text: m.content },
62
- ],
63
- };
64
- }
65
- function newThreadId() {
66
- return 't_' + crypto.randomBytes(6).toString('hex');
67
- }
68
- function threadPath(id) {
69
- if (!/^[A-Za-z0-9_-]+$/.test(id))
70
- throw new Error(`"${id}" is not a thread id. List them with: faces chat:thread --list`);
71
- return path.join(THREADS_DIR, `${id}.json`);
72
- }
73
- function ensureThreadsDir() {
74
- if (!fs.existsSync(THREADS_DIR))
75
- fs.mkdirSync(THREADS_DIR, { recursive: true, mode: 0o700 });
76
- }
77
- function loadThread(id) {
78
- const p = threadPath(id);
79
- if (!fs.existsSync(p))
80
- return null;
81
- return JSON.parse(fs.readFileSync(p, 'utf8'));
82
- }
83
- function saveThread(t) {
84
- ensureThreadsDir();
85
- t.updated_at = new Date().toISOString();
86
- fs.writeFileSync(threadPath(t.id), JSON.stringify(t, null, 2), { mode: 0o600 });
87
- }
88
- function listThreads() {
89
- if (!fs.existsSync(THREADS_DIR))
90
- return [];
91
- const out = [];
92
- for (const f of fs.readdirSync(THREADS_DIR)) {
93
- if (!f.endsWith('.json'))
94
- continue;
95
- try {
96
- out.push(JSON.parse(fs.readFileSync(path.join(THREADS_DIR, f), 'utf8')));
97
- }
98
- catch { }
99
- }
100
- out.sort((a, b) => (b.updated_at ?? '').localeCompare(a.updated_at ?? ''));
101
- return out;
102
- }
103
- export default class ChatThread extends BaseCommand {
104
- static description = 'Multi-turn chat thread. Conversation history is stored under ~/.faces/threads/<id>.json. Resume any thread later with --id. ' +
105
- 'A face named without a model answers on its default model, which is fixed on the thread when it starts. ' +
106
- 'Each turn keeps the face\'s cause and sends it back with the transcript.';
107
- static examples = [
108
- '<%= config.bin %> <%= command.id %> socrates -m "What is justice?"',
109
- '<%= config.bin %> <%= command.id %> --id t_abc123 -m "Say more about that"',
110
- '<%= config.bin %> <%= command.id %> --list',
111
- '<%= config.bin %> <%= command.id %> --id t_abc123 --show',
112
- '<%= config.bin %> <%= command.id %> --id t_abc123 --delete',
113
- ];
114
- static flags = {
115
- ...BaseCommand.baseFlags,
116
- id: Flags.string({ description: 'Resume an existing thread by id' }),
117
- message: Flags.string({ char: 'm', description: 'User message' }),
118
- file: Flags.string({ description: 'Read message from file' }),
119
- llm: Flags.string({ description: 'LLM override (only honored when starting a new thread)' }),
120
- system: Flags.string({ description: 'System prompt (only honored when starting a new thread)' }),
121
- 'max-tokens': Flags.integer({ description: 'Max tokens (at least 1)', min: 1 }),
122
- temperature: Flags.string({ description: 'Temperature (0.0-2.0)' }),
123
- stream: Flags.boolean({ description: STREAM_FLAG_DESCRIPTION, default: true, allowNo: true }),
124
- style: Flags.string({ description: `${STYLE_FLAG_DESCRIPTION} For this turn only.` }),
125
- medium: Flags.string({ description: `${MEDIUM_FLAG_DESCRIPTION} For this turn only.` }),
126
- ...conversationTurnFlags({ suffix: 'For this turn only. Only the new message is sent: the conversation holds the rest.' }),
127
- session: Flags.string({ description: `${SESSION_FLAG_DESCRIPTION} For this turn only.` }),
128
- compaction: Flags.string({ description: `${COMPACTION_FLAG_DESCRIPTION} For this turn only.` }),
129
- 'oauth-only': Flags.boolean({ description: 'On a linked ChatGPT plan, run there or fail: never fall back to credits', default: false }),
130
- 'show-cause': Flags.boolean({ description: REASONING_FLAG_DESCRIPTION, default: false }),
131
- cause: Flags.string({ description: `${CAUSE_FLAG_DESCRIPTION} For this turn only; it is kept on the thread like any.` }),
132
- 'cause-file': Flags.string({ description: CAUSE_FILE_FLAG_DESCRIPTION, exclusive: ['cause'] }),
133
- list: Flags.boolean({ description: 'List saved threads', default: false }),
134
- show: Flags.boolean({ description: 'Show the thread transcript (requires --id)', default: false }),
135
- delete: Flags.boolean({ description: 'Delete the thread (requires --id)', default: false }),
136
- yes: Flags.boolean({ description: 'Skip confirmation for --delete', default: false }),
137
- };
138
- static args = {
139
- face_username: Args.string({
140
- description: 'Face alias (alias@model, or owner:alias@model for a published face). Required when starting a new thread',
141
- required: false,
142
- }),
143
- };
144
- async run() {
145
- const { args, flags } = await this.parse(ChatThread);
146
- if (flags.list)
147
- return this.handleList();
148
- if (flags.delete)
149
- return this.handleDelete(flags.id, flags.yes);
150
- if (flags.show)
151
- return this.handleShow(flags.id);
152
- return this.handleMessage(args.face_username, flags);
153
- }
154
- handleList() {
155
- const threads = listThreads();
156
- if (this.jsonEnabled()) {
157
- return threads.map((t) => ({
158
- id: t.id,
159
- face: t.face_username,
160
- model: t.model,
161
- turns: t.messages.length,
162
- created_at: t.created_at,
163
- updated_at: t.updated_at,
164
- }));
165
- }
166
- if (threads.length === 0) {
167
- this.log('(no threads)');
168
- return {};
169
- }
170
- for (const t of threads) {
171
- const last = t.messages[t.messages.length - 1];
172
- const preview = last
173
- ? last.content.slice(0, 60).replace(/\s+/g, ' ') + (last.content.length > 60 ? '…' : '')
174
- : '';
175
- this.log(`${t.id} ${t.model} (${t.messages.length} turns, updated ${t.updated_at})`);
176
- if (preview)
177
- this.log(` ${last.role}: ${preview}`);
178
- }
179
- return {};
180
- }
181
- async handleDelete(id, yes) {
182
- if (!id)
183
- this.error('--delete requires --id <thread-id>');
184
- const p = threadPath(id);
185
- if (!fs.existsSync(p))
186
- this.error(`Thread not found: ${id}`);
187
- await this.confirmOrRefuse(`Delete thread ${id} and its history?`, yes);
188
- fs.unlinkSync(p);
189
- if (this.jsonEnabled())
190
- return { deleted: id };
191
- this.log(`Deleted thread ${id}`);
192
- return { deleted: id };
193
- }
194
- handleShow(id) {
195
- if (!id)
196
- this.error('--show requires --id <thread-id>');
197
- const t = loadThread(id);
198
- if (!t)
199
- this.error(`Thread not found: ${id}`);
200
- if (this.jsonEnabled())
201
- return t;
202
- this.log(`Thread ${t.id} (${t.model}, provider=${t.provider})`);
203
- this.log(`Created: ${t.created_at}`);
204
- this.log(`Updated: ${t.updated_at}`);
205
- if (t.system) {
206
- this.log('---');
207
- this.log(`system: ${t.system}`);
208
- }
209
- for (const m of t.messages) {
210
- this.log('---');
211
- this.log(`${m.role} [${m.ts}]:`);
212
- this.log(m.content);
213
- }
214
- return t;
215
- }
216
- async handleMessage(face_username, flags) {
217
- let userMessage;
218
- if (flags.file) {
219
- if (!fs.existsSync(flags.file))
220
- this.error(`File not found: ${flags.file}`);
221
- userMessage = fs.readFileSync(flags.file, 'utf8');
222
- }
223
- else if (flags.message) {
224
- userMessage = flags.message;
225
- }
226
- else {
227
- this.error('Provide --message/-m or --file');
228
- }
229
- try {
230
- this.conversationBody = conversationFields(flags);
231
- }
232
- catch (err) {
233
- this.error(err instanceof Error ? err.message : String(err));
234
- }
235
- this.newOnly = Boolean(flags.conversation || flags.session);
236
- const client = this.makeClient(flags);
237
- let thread;
238
- if (flags.id) {
239
- const existing = loadThread(flags.id);
240
- if (!existing)
241
- this.error(`Thread not found: ${flags.id}`);
242
- thread = existing;
243
- if (flags.llm || flags.system) {
244
- this.warn('--llm and --system are ignored when resuming a thread; using values stored on the thread');
245
- }
246
- }
247
- else {
248
- if (!face_username) {
249
- this.error('Provide a face (e.g. `faces chat:thread socrates -m "…"`) or --id <thread-id> to resume');
250
- }
251
- const baseAlias = face_username.split('@')[0];
252
- const model = flags.llm ? `${baseAlias}@${flags.llm}` : face_username;
253
- const now = new Date().toISOString();
254
- thread = {
255
- id: newThreadId(),
256
- face_username: baseAlias,
257
- model,
258
- provider: 'openai',
259
- system: flags.system,
260
- created_at: now,
261
- updated_at: now,
262
- messages: [],
263
- };
264
- }
265
- thread.messages.push({ role: 'user', content: userMessage, ts: new Date().toISOString() });
266
- const bare = !llmFromArg(thread.model) && !isCompositeFormula(thread.model);
267
- let endpoint = thread.endpoint;
268
- if (!endpoint || bare) {
269
- const route = await resolveEndpoint(client, thread.model);
270
- if (bare) {
271
- if (!route.llm) {
272
- this.error(`${thread.model} has no default model to answer on, so name one: ${thread.model}@<model>, or add --llm <model>.`);
273
- }
274
- thread.model = `${thread.model}@${route.llm}`;
275
- }
276
- endpoint = route.endpoint;
277
- thread.endpoint = endpoint;
278
- thread.provider = endpoint === MESSAGES_ENDPOINT ? 'anthropic' : 'openai';
279
- }
280
- let cause;
281
- try {
282
- cause = resolveCause(flags.cause, flags['cause-file']);
283
- }
284
- catch (err) {
285
- this.error(err instanceof Error ? err.message : String(err));
286
- }
287
- flags = { ...flags, cause, stream: flags.stream && !this.jsonEnabled() };
288
- try {
289
- let reply;
290
- if (endpoint === MESSAGES_ENDPOINT) {
291
- reply = await this.sendAnthropic(client, thread, flags);
292
- }
293
- else if (endpoint === RESPONSES_ENDPOINT) {
294
- reply = await this.sendResponses(client, thread, flags);
295
- }
296
- else {
297
- reply = await this.sendChatCompletions(client, thread, flags);
298
- }
299
- const assistantText = reply.text;
300
- if (!flags.stream && flags['show-cause'] && reply.reasoning && !this.jsonEnabled()) {
301
- process.stderr.write(`${reasoningHeading(thread.model)}\n${reply.reasoning}\n\n`);
302
- }
303
- const turn = { role: 'assistant', content: assistantText, ts: new Date().toISOString() };
304
- if (reply.reasoning)
305
- turn.cause = reply.reasoning;
306
- if (reply.causeId)
307
- turn.cause_id = reply.causeId;
308
- if (reply.modelReasoning)
309
- turn.reasoning_content = reply.modelReasoning;
310
- thread.messages.push(turn);
311
- saveThread(thread);
312
- if (this.jsonEnabled()) {
313
- return {
314
- thread_id: thread.id,
315
- model: thread.model,
316
- provider: thread.provider,
317
- assistant: assistantText,
318
- ...(reply.reasoning ? { cause: reply.reasoning } : {}),
319
- turns: thread.messages.length,
320
- };
321
- }
322
- if (!flags.stream)
323
- this.log(assistantText);
324
- this.log(`\n[thread ${thread.id} · ${thread.messages.length} turns]`);
325
- return { thread_id: thread.id, assistant: assistantText };
326
- }
327
- catch (err) {
328
- if (err instanceof FacesAPIError) {
329
- if (err.errorCode === 'oauth_rejected') {
330
- const hints = [];
331
- if (endpoint === RESPONSES_ENDPOINT) {
332
- hints.push('This model is free when you link your ChatGPT account: faces auth:connect openai');
333
- }
334
- hints.push(err.fallbackAvailable
335
- ? 'Run `faces account:preferences api_fallback true` to allow paid fallback.'
336
- : 'Run `faces billing:topup` to add credits, then enable fallback with `faces account:preferences api_fallback true`.');
337
- this.error(`OAuth failed: ${err.message}\n${hints.join('\n')}`);
338
- }
339
- const hint = faceRefusalHint(err, thread.model, flags.style);
340
- this.error(`HTTP ${err.statusCode}: ${err.message}${hint ? `\n${hint}` : ''}`);
341
- }
342
- throw err;
343
- }
344
- }
345
- conversationBody = {};
346
- newOnly = false;
347
- sent(thread) {
348
- return this.newOnly ? thread.messages.slice(-1) : thread.messages;
349
- }
350
- async sendChatCompletions(client, thread, flags) {
351
- const messages = [];
352
- if (thread.system)
353
- messages.push({ role: 'system', content: thread.system });
354
- for (const m of this.sent(thread))
355
- messages.push(chatTurn(m));
356
- const payload = { model: thread.model, messages, stream: flags.stream };
357
- if (flags['max-tokens'])
358
- payload.max_tokens = flags['max-tokens'];
359
- if (flags.temperature !== undefined)
360
- payload.temperature = parseTemperature(flags.temperature, (m) => this.error(m));
361
- Object.assign(payload, chatExtras(flags), this.conversationBody);
362
- if (flags['oauth-only'])
363
- payload.oauth_only = true;
364
- if (flags.cause)
365
- payload.cause = flags.cause;
366
- if (flags.stream) {
367
- return this.streamAndAccumulate(client, CHAT_COMPLETIONS_ENDPOINT, payload, flags['show-cause'] ? thread.model : undefined);
368
- }
369
- let data;
370
- try {
371
- ;
372
- ({ data } = await retryOnceOnWarmUp(() => postChat(client, CHAT_COMPLETIONS_ENDPOINT, payload), sayWarmUp));
373
- }
374
- catch (err) {
375
- if (err instanceof FacesAPIError && isMaxTokensRenameError(err.message) && payload.max_tokens !== undefined) {
376
- payload.max_completion_tokens = payload.max_tokens;
377
- delete payload.max_tokens;
378
- ({ data } = await retryOnceOnWarmUp(() => postChat(client, CHAT_COMPLETIONS_ENDPOINT, payload), sayWarmUp));
379
- }
380
- else {
381
- throw err;
382
- }
383
- }
384
- return replyOf(data, CHAT_COMPLETIONS_ENDPOINT);
385
- }
386
- async sendResponses(client, thread, flags) {
387
- const input = this.sent(thread).flatMap((m) => responsesTurns(m));
388
- const payload = { model: thread.model, input, stream: flags.stream };
389
- if (thread.system)
390
- payload.instructions = thread.system;
391
- if (flags['max-tokens'] !== undefined) {
392
- if (flags['max-tokens'] < MIN_MAX_OUTPUT_TOKENS) {
393
- throw new Error(`--max-tokens must be at least ${MIN_MAX_OUTPUT_TOKENS} for this model (got ${flags['max-tokens']}). ` +
394
- 'The Responses API rejects a smaller output cap.');
395
- }
396
- payload.max_output_tokens = flags['max-tokens'];
397
- }
398
- if (flags.temperature !== undefined)
399
- payload.temperature = parseTemperature(flags.temperature, (m) => this.error(m));
400
- Object.assign(payload, chatExtras(flags), this.conversationBody);
401
- if (flags['oauth-only'])
402
- payload.oauth_only = true;
403
- if (flags.cause)
404
- payload.cause = flags.cause;
405
- if (flags.stream) {
406
- return this.streamAndAccumulate(client, RESPONSES_ENDPOINT, payload, flags['show-cause'] ? thread.model : undefined);
407
- }
408
- const { data } = await retryOnceOnWarmUp(() => postChat(client, RESPONSES_ENDPOINT, payload), sayWarmUp);
409
- return replyOf(data, RESPONSES_ENDPOINT);
410
- }
411
- async sendAnthropic(client, thread, flags) {
412
- const msgs = this.sent(thread).map((m) => messagesTurn(m));
413
- const payload = {
414
- model: thread.model,
415
- messages: msgs,
416
- max_tokens: flags['max-tokens'] ?? 1024,
417
- stream: flags.stream,
418
- };
419
- if (thread.system)
420
- payload.system = thread.system;
421
- Object.assign(payload, chatExtras(flags), this.conversationBody);
422
- if (flags['oauth-only'])
423
- payload.oauth_only = true;
424
- if (flags.cause)
425
- payload.cause = flags.cause;
426
- if (flags.stream) {
427
- return this.streamAndAccumulate(client, MESSAGES_ENDPOINT, payload, flags['show-cause'] ? thread.model : undefined);
428
- }
429
- const { data } = await retryOnceOnWarmUp(() => postChat(client, MESSAGES_ENDPOINT, payload), sayWarmUp);
430
- return replyOf(data, MESSAGES_ENDPOINT);
431
- }
432
- async streamAndAccumulate(client, endpoint, payload, showReasoningAs) {
433
- let accum = '';
434
- let reasoning = '';
435
- let causeId;
436
- let modelReasoning = '';
437
- for await (const line of streamChat(client, endpoint, payload)) {
438
- if (!line.startsWith('data: '))
439
- continue;
440
- const chunk = line.slice(6);
441
- if (chunk.trim() === '[DONE]' || chunk.trim() === '')
442
- continue;
443
- try {
444
- const parsed = JSON.parse(chunk);
445
- const item = parsed.item_id;
446
- if (typeof item === 'string' && item.startsWith(FACES_REASONING_ITEM_PREFIX))
447
- causeId = item;
448
- const own = parsed.choices?.[0]?.delta;
449
- if (own?.reasoning_content)
450
- modelReasoning += String(own.reasoning_content);
451
- const thought = extractStreamReasoning(parsed);
452
- if (thought) {
453
- if (showReasoningAs && !reasoning)
454
- process.stderr.write(`${reasoningHeading(showReasoningAs)}\n`);
455
- if (showReasoningAs)
456
- process.stderr.write(thought);
457
- reasoning += thought;
458
- }
459
- const delta = extractStreamDelta(parsed);
460
- if (delta) {
461
- if (showReasoningAs && reasoning && !accum)
462
- process.stderr.write('\n\n');
463
- accum += delta;
464
- process.stdout.write(delta);
465
- }
466
- }
467
- catch { }
468
- }
469
- process.stdout.write('\n');
470
- return { text: accum, reasoning, causeId, modelReasoning: modelReasoning || undefined };
471
- }
472
- }
@@ -1,99 +0,0 @@
1
- import { Args, Flags } from '@oclif/core';
2
- import { createInterface } from 'node:readline';
3
- import { BaseCommand } from '../../base.js';
4
- import { FacesAPIError } from '../../client.js';
5
- import { FIDELITY_TURNS, answerLines, fidelityError, fidelityPost, getRun, runLines, score10, turnLines } from '../../fidelity.js';
6
- import { seg, usd } from '../../utils.js';
7
- export default class FidelityRunCommand extends BaseCommand {
8
- static description = 'Play a fidelity run in the terminal: ten turns of writing a message, reading answers a and b, and ' +
9
- 'picking the one that sounds more like the person, with an optional correction. Needs a person at ' +
10
- 'the keyboard; without a terminal, use fidelity:start, fidelity:turn and fidelity:pick. Resume a run ' +
11
- 'with --run.';
12
- static examples = [
13
- '<%= config.bin %> <%= command.id %> alice',
14
- '<%= config.bin %> <%= command.id %> alice --run <run>',
15
- ];
16
- static flags = {
17
- ...BaseCommand.baseFlags,
18
- competitor: Flags.string({ description: 'The chat model the face is compared with (default: the cheapest Codex-eligible chat model)' }),
19
- model: Flags.string({ description: 'The model the face answers on (default: its own default model)' }),
20
- run: Flags.string({ description: 'Resume this run instead of starting one', exclusive: ['competitor', 'model'] }),
21
- };
22
- static args = {
23
- alias: Args.string({ description: 'Alias of a face you own', required: true }),
24
- };
25
- rl;
26
- async run() {
27
- const { args, flags } = await this.parse(FidelityRunCommand);
28
- if (this.jsonEnabled() || !process.stdin.isTTY) {
29
- this.error('fidelity:run needs a person at a terminal. Without one, use fidelity:start, fidelity:turn and fidelity:pick.');
30
- }
31
- const client = this.makeClient(flags);
32
- this.rl = createInterface({ input: process.stdin, output: process.stderr });
33
- try {
34
- let run;
35
- if (flags.run) {
36
- run = await getRun(client, flags.run);
37
- }
38
- else {
39
- const body = {};
40
- if (flags.competitor)
41
- body.competitor = flags.competitor;
42
- if (flags.model)
43
- body.model = flags.model;
44
- run = (await fidelityPost(client, `/v1/faces/${seg(args.alias)}/fidelity`, body));
45
- this.log(`Run ${run.run_id} against ${run.competitor ?? 'the competitor'}, up to ${usd(run.estimated_usd)} from credits.`);
46
- }
47
- const id = run.run_id;
48
- this.log('Each turn, pick the answer that sounds more like the person. Ctrl-C stops; --run resumes.\n');
49
- while (run.next) {
50
- const n = run.next.turn;
51
- if (run.next.awaiting === 'message') {
52
- const message = await this.ask(`Turn ${n} of ${FIDELITY_TURNS}, your message: `);
53
- if (!message.trim())
54
- continue;
55
- process.stderr.write('Waiting for both answers...\n');
56
- const t = await fidelityPost(client, `/v1/fidelity/${seg(id)}/turns`, { message });
57
- this.log('');
58
- for (const line of answerLines(n, (t.answers ?? {})))
59
- this.log(line);
60
- this.log('');
61
- }
62
- let pick = '';
63
- while (pick !== 'a' && pick !== 'b')
64
- pick = (await this.ask('Which sounds more like them, a or b? ')).trim().toLowerCase();
65
- const correction = await this.ask('What would they actually have said? (Enter to accept it as it is) ');
66
- const body = { pick };
67
- if (correction.trim())
68
- body.correction = correction;
69
- const c = await fidelityPost(client, `/v1/fidelity/${seg(id)}/turns/${n}/choice`, body);
70
- this.log(`Turn ${n} scored ${score10(c.score)}, ${score10(c.score_so_far)} so far.\n`);
71
- run = await getRun(client, id);
72
- }
73
- for (const line of runLines(run))
74
- this.log(line);
75
- this.log('');
76
- for (const line of turnLines(run))
77
- this.log(line);
78
- if (!run.thread_id) {
79
- const save = await this.ask('\nSave the conversation as a thread on the face, to compile? [y/N] ');
80
- if (save.trim().toLowerCase() === 'y') {
81
- const s = await fidelityPost(client, `/v1/fidelity/${seg(id)}/save-thread`, {});
82
- this.log(`Saved as thread ${s.thread_id}. Compile it: faces compile:thread:make ${s.thread_id}`);
83
- }
84
- }
85
- return run;
86
- }
87
- catch (err) {
88
- if (err instanceof FacesAPIError)
89
- this.error(fidelityError(err, { run: flags.run, alias: args.alias }));
90
- throw err;
91
- }
92
- finally {
93
- this.rl.close();
94
- }
95
- }
96
- ask(question) {
97
- return new Promise((resolve) => this.rl.question(question, resolve));
98
- }
99
- }
@@ -1,17 +0,0 @@
1
- import { BaseCommand } from '../../base.js';
2
- export default class FidelityStart extends BaseCommand {
3
- static description: string;
4
- static examples: string[];
5
- static flags: {
6
- competitor: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
- model: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
- 'base-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
- token: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
- 'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
- toon: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
- };
13
- static args: {
14
- alias: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
15
- };
16
- run(): Promise<unknown>;
17
- }
@@ -1,56 +0,0 @@
1
- import { Args, Flags } from '@oclif/core';
2
- import { BaseCommand } from '../../base.js';
3
- import { FacesAPIError } from '../../client.js';
4
- import { fidelityError, fidelityPost, nextStep } from '../../fidelity.js';
5
- import { seg, usd } from '../../utils.js';
6
- export default class FidelityStart extends BaseCommand {
7
- static description = 'Start a fidelity run on a face you own: ten blind turns, scored out of 10. Each turn you send a ' +
8
- 'message, read two answers labelled a and b (one is the face, one a competitor model given the ' +
9
- 'face\'s own writing), and pick the one that sounds more like the person, accepting it or correcting ' +
10
- 'it. The picks must be the person\'s own: an agent shows both answers and passes on the choice it is ' +
11
- 'given, never its own. The score is saved on the face, and a new run replaces it. On Connect or Pro ' +
12
- 'with ChatGPT linked, answers from Codex-eligible models run on the ChatGPT plan; the rest, and grading ' +
13
- 'a correction, is paid from credits. To play it in the terminal, use faces fidelity:run.';
14
- static examples = [
15
- '<%= config.bin %> <%= command.id %> alice',
16
- '<%= config.bin %> <%= command.id %> alice --competitor <model>',
17
- ];
18
- static flags = {
19
- ...BaseCommand.baseFlags,
20
- competitor: Flags.string({
21
- description: 'The chat model the face is compared with (default: the cheapest Codex-eligible chat model)',
22
- }),
23
- model: Flags.string({ description: 'The model the face answers on (default: its own default model)' }),
24
- };
25
- static args = {
26
- alias: Args.string({ description: 'Alias of a face you own', required: true }),
27
- };
28
- async run() {
29
- const { args, flags } = await this.parse(FidelityStart);
30
- const client = this.makeClient(flags);
31
- const body = {};
32
- if (flags.competitor)
33
- body.competitor = flags.competitor;
34
- if (flags.model)
35
- body.model = flags.model;
36
- let run;
37
- try {
38
- run = (await fidelityPost(client, `/v1/faces/${seg(args.alias)}/fidelity`, body));
39
- }
40
- catch (err) {
41
- if (err instanceof FacesAPIError)
42
- this.error(fidelityError(err, { alias: args.alias }));
43
- throw err;
44
- }
45
- if (this.jsonEnabled())
46
- return run;
47
- this.log(`run: ${run.run_id}`);
48
- this.log(`face: ${run.alias ?? args.alias}`);
49
- this.log(`competitor: ${run.competitor ?? '-'}`);
50
- if (run.estimated_usd !== undefined)
51
- this.log(`up to: ${usd(run.estimated_usd)} from credits`);
52
- this.log('');
53
- this.log(nextStep(run) ?? '');
54
- return run;
55
- }
56
- }
@@ -1,17 +0,0 @@
1
- import { BaseCommand } from '../../base.js';
2
- export default class FidelityTurn extends BaseCommand {
3
- static description: string;
4
- static examples: string[];
5
- static flags: {
6
- message: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
- file: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
- 'base-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
- token: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
- 'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
- toon: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
- };
13
- static args: {
14
- run_id: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
15
- };
16
- run(): Promise<unknown>;
17
- }