@faces-sh/cli 1.0.3 → 1.2.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 (70) hide show
  1. package/README.md +107 -53
  2. package/dist/billing.js +11 -8
  3. package/dist/{commands/causes.d.ts → chat-command.d.ts} +13 -13
  4. package/dist/chat-command.js +110 -0
  5. package/dist/chat.d.ts +47 -0
  6. package/dist/chat.js +157 -0
  7. package/dist/choices.d.ts +20 -0
  8. package/dist/choices.js +49 -0
  9. package/dist/commands/auth/connect.js +2 -2
  10. package/dist/commands/billing/llm-costs.js +9 -5
  11. package/dist/commands/billing/subscription/index.js +1 -1
  12. package/dist/commands/catalog/doctor.js +9 -68
  13. package/dist/commands/chat/chat.d.ts +10 -26
  14. package/dist/commands/chat/chat.js +21 -366
  15. package/dist/commands/chat/messages.d.ts +13 -13
  16. package/dist/commands/chat/messages.js +15 -142
  17. package/dist/commands/chat/responses.d.ts +13 -14
  18. package/dist/commands/chat/responses.js +16 -153
  19. package/dist/commands/chat/thread.d.ts +3 -15
  20. package/dist/commands/chat/thread.js +128 -362
  21. package/dist/commands/choices.d.ts +20 -0
  22. package/dist/commands/choices.js +91 -0
  23. package/dist/commands/conversation/add.d.ts +2 -0
  24. package/dist/commands/conversation/add.js +21 -10
  25. package/dist/commands/conversation/close.js +5 -5
  26. package/dist/commands/conversation/compact.js +15 -18
  27. package/dist/commands/conversation/create.d.ts +2 -0
  28. package/dist/commands/conversation/create.js +20 -17
  29. package/dist/commands/conversation/get.js +4 -4
  30. package/dist/commands/conversation/items.js +5 -5
  31. package/dist/commands/decide.d.ts +4 -4
  32. package/dist/commands/decide.js +70 -81
  33. package/dist/commands/face/get.js +2 -2
  34. package/dist/commands/group/add.js +1 -1
  35. package/dist/commands/media/list.d.ts +12 -0
  36. package/dist/commands/media/list.js +35 -0
  37. package/dist/commands/models/list.js +16 -5
  38. package/dist/commands/session/close.js +1 -1
  39. package/dist/commands/session/compact.js +6 -9
  40. package/dist/commands/session/create.js +10 -9
  41. package/dist/commands/session/get.js +1 -1
  42. package/dist/commands/state/add.d.ts +3 -0
  43. package/dist/commands/state/add.js +3 -0
  44. package/dist/commands/state/close.d.ts +3 -0
  45. package/dist/commands/state/close.js +3 -0
  46. package/dist/commands/state/compact.d.ts +3 -0
  47. package/dist/commands/state/compact.js +3 -0
  48. package/dist/commands/state/create.d.ts +3 -0
  49. package/dist/commands/state/create.js +3 -0
  50. package/dist/commands/state/get.d.ts +3 -0
  51. package/dist/commands/state/get.js +3 -0
  52. package/dist/commands/state/items.d.ts +3 -0
  53. package/dist/commands/state/items.js +3 -0
  54. package/dist/commands/style/make.js +2 -6
  55. package/dist/commands/style/upload.js +1 -1
  56. package/dist/conversation.d.ts +27 -2
  57. package/dist/conversation.js +91 -16
  58. package/dist/decisions.d.ts +0 -5
  59. package/dist/decisions.js +0 -18
  60. package/dist/media.d.ts +8 -0
  61. package/dist/media.js +12 -0
  62. package/dist/model.d.ts +11 -0
  63. package/dist/model.js +53 -0
  64. package/dist/routing.d.ts +1 -4
  65. package/dist/routing.js +4 -40
  66. package/dist/utils.d.ts +1 -25
  67. package/dist/utils.js +10 -108
  68. package/oclif.manifest.json +2054 -1649
  69. package/package.json +10 -7
  70. package/dist/commands/causes.js +0 -146
@@ -4,64 +4,14 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { BaseCommand } from '../../base.js';
7
- import { conversationFields, conversationTurnFlags } from '../../conversation.js';
8
7
  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';
8
+ import { conversationFields, conversationTurnFlags } from '../../conversation.js';
9
+ import { MODEL_ARG_DESCRIPTION, chatModelProblem, chatPayload, sendChat } from '../../chat.js';
10
+ import { parseModel } from '../../model.js';
11
+ import { resolveEndpoint } from '../../routing.js';
12
+ import { COMPACTION_FLAG_DESCRIPTION, SESSION_FLAG_DESCRIPTION, STREAM_FLAG_DESCRIPTION, parseTemperature } from '../../utils.js';
13
+ import { chatRefusal } from '../../chat-command.js';
11
14
  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
15
  function newThreadId() {
66
16
  return 't_' + crypto.randomBytes(6).toString('hex');
67
17
  }
@@ -70,10 +20,6 @@ function threadPath(id) {
70
20
  throw new Error(`"${id}" is not a thread id. List them with: faces chat:thread --list`);
71
21
  return path.join(THREADS_DIR, `${id}.json`);
72
22
  }
73
- function ensureThreadsDir() {
74
- if (!fs.existsSync(THREADS_DIR))
75
- fs.mkdirSync(THREADS_DIR, { recursive: true, mode: 0o700 });
76
- }
77
23
  function loadThread(id) {
78
24
  const p = threadPath(id);
79
25
  if (!fs.existsSync(p))
@@ -81,7 +27,8 @@ function loadThread(id) {
81
27
  return JSON.parse(fs.readFileSync(p, 'utf8'));
82
28
  }
83
29
  function saveThread(t) {
84
- ensureThreadsDir();
30
+ if (!fs.existsSync(THREADS_DIR))
31
+ fs.mkdirSync(THREADS_DIR, { recursive: true, mode: 0o700 });
85
32
  t.updated_at = new Date().toISOString();
86
33
  fs.writeFileSync(threadPath(t.id), JSON.stringify(t, null, 2), { mode: 0o600 });
87
34
  }
@@ -101,11 +48,11 @@ function listThreads() {
101
48
  return out;
102
49
  }
103
50
  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.';
51
+ static description = 'A multi-turn chat with a face, kept under ~/.faces/threads/<id>.json. Start one with the model ' +
52
+ '(@alice:maestro-1/gpt-5.4) and a message, then go on with --id. The whole thread is sent each turn, ' +
53
+ 'unless the turn is in a state (--conversation), which holds the history: then only the new message goes.';
107
54
  static examples = [
108
- '<%= config.bin %> <%= command.id %> socrates -m "What is justice?"',
55
+ '<%= config.bin %> <%= command.id %> @socrates:maestro-1/gpt-5.4 -m "What is justice?"',
109
56
  '<%= config.bin %> <%= command.id %> --id t_abc123 -m "Say more about that"',
110
57
  '<%= config.bin %> <%= command.id %> --list',
111
58
  '<%= config.bin %> <%= command.id %> --id t_abc123 --show',
@@ -113,33 +60,24 @@ export default class ChatThread extends BaseCommand {
113
60
  ];
114
61
  static flags = {
115
62
  ...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)' }),
63
+ id: Flags.string({ description: 'Go on with a saved thread, by id.' }),
64
+ message: Flags.string({ char: 'm', description: 'Your message.' }),
65
+ file: Flags.string({ description: 'Read the message from a file.' }),
66
+ system: Flags.string({ description: 'System prompt (only when starting a thread).' }),
67
+ 'max-tokens': Flags.integer({ description: 'The most tokens the reply may take (at least 1).', min: 1 }),
68
+ temperature: Flags.string({ description: 'Temperature (0.0-2.0).' }),
123
69
  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.' }),
70
+ ...conversationTurnFlags({ suffix: 'For this turn only. Only the new message is sent: the state holds the rest.' }),
127
71
  session: Flags.string({ description: `${SESSION_FLAG_DESCRIPTION} For this turn only.` }),
128
72
  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 }),
73
+ 'oauth-only': Flags.boolean({ description: 'On a linked ChatGPT plan, run there or fail: never fall back to credits.', default: false }),
74
+ list: Flags.boolean({ description: 'List saved threads.', default: false }),
75
+ show: Flags.boolean({ description: 'Show a thread (needs --id).', default: false }),
76
+ delete: Flags.boolean({ description: 'Delete a thread (needs --id).', default: false }),
77
+ yes: Flags.boolean({ description: 'Skip the confirmation for --delete.', default: false }),
137
78
  };
138
79
  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
- }),
80
+ model: Args.string({ description: `${MODEL_ARG_DESCRIPTION} Needed to start a thread; a saved thread keeps its own.`, required: false }),
143
81
  };
144
82
  async run() {
145
83
  const { args, flags } = await this.parse(ChatThread);
@@ -149,324 +87,152 @@ export default class ChatThread extends BaseCommand {
149
87
  return this.handleDelete(flags.id, flags.yes);
150
88
  if (flags.show)
151
89
  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;
90
+ let message;
218
91
  if (flags.file) {
219
92
  if (!fs.existsSync(flags.file))
220
93
  this.error(`File not found: ${flags.file}`);
221
- userMessage = fs.readFileSync(flags.file, 'utf8');
94
+ message = fs.readFileSync(flags.file, 'utf8');
222
95
  }
223
96
  else if (flags.message) {
224
- userMessage = flags.message;
97
+ message = flags.message;
225
98
  }
226
99
  else {
227
- this.error('Provide --message/-m or --file');
100
+ this.error('Provide --message/-m or --file.');
228
101
  }
102
+ let turn;
229
103
  try {
230
- this.conversationBody = conversationFields(flags);
104
+ turn = conversationFields(flags);
231
105
  }
232
106
  catch (err) {
233
107
  this.error(err instanceof Error ? err.message : String(err));
234
108
  }
235
- this.newOnly = Boolean(flags.conversation || flags.session);
236
- const client = this.makeClient(flags);
109
+ const newOnly = Boolean(flags.conversation || flags.session);
237
110
  let thread;
238
111
  if (flags.id) {
239
- const existing = loadThread(flags.id);
112
+ let existing;
113
+ try {
114
+ existing = loadThread(flags.id);
115
+ }
116
+ catch (err) {
117
+ this.error(err instanceof Error ? err.message : String(err));
118
+ }
240
119
  if (!existing)
241
120
  this.error(`Thread not found: ${flags.id}`);
242
121
  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
- }
122
+ if (args.model && args.model.trim() !== thread.model)
123
+ this.warn(`A thread keeps its model; going on with ${thread.model}.`);
124
+ if (flags.system)
125
+ this.warn('--system is ignored when going on with a thread.');
246
126
  }
247
127
  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;
128
+ if (!args.model)
129
+ this.error('Name the model to start a thread (e.g. faces chat:thread @socrates:maestro-1/gpt-5.4 -m "..."), or --id to go on with one.');
253
130
  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';
131
+ thread = { id: newThreadId(), model: args.model.trim(), system: flags.system, created_at: now, updated_at: now, messages: [] };
279
132
  }
280
- let cause;
133
+ const problem = chatModelProblem(thread.model);
134
+ if (problem)
135
+ this.error(`${problem}\nThis thread was saved with the old form; start a new one with the new model.`);
136
+ const client = this.makeClient(flags);
137
+ if (!thread.endpoint)
138
+ thread.endpoint = (await resolveEndpoint(client, parseModel(thread.model).downstream)).endpoint;
139
+ const endpoint = thread.endpoint;
140
+ thread.messages.push({ role: 'user', content: message, ts: new Date().toISOString() });
141
+ const sent = newOnly ? thread.messages.slice(-1) : thread.messages;
142
+ const json = this.jsonEnabled();
143
+ let payload;
281
144
  try {
282
- cause = resolveCause(flags.cause, flags['cause-file']);
145
+ payload = chatPayload(endpoint, thread.model, sent.map((m) => ({ role: m.role, content: m.content })), {
146
+ system: thread.system,
147
+ maxTokens: flags['max-tokens'],
148
+ temperature: flags.temperature === undefined ? undefined : parseTemperature(flags.temperature, (m) => this.error(m)),
149
+ stream: flags.stream && !json,
150
+ oauthOnly: flags['oauth-only'],
151
+ session: flags.session,
152
+ compaction: flags.compaction,
153
+ turn,
154
+ });
283
155
  }
284
156
  catch (err) {
285
157
  this.error(err instanceof Error ? err.message : String(err));
286
158
  }
287
- flags = { ...flags, cause, stream: flags.stream && !this.jsonEnabled() };
288
159
  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);
160
+ const res = await sendChat(client, endpoint, payload, (d) => process.stdout.write(d), json);
161
+ if (!res.text)
162
+ this.error('No answer came back. Run it again with --no-stream to see what the server said.');
163
+ thread.messages.push({ role: 'assistant', content: res.text, ts: new Date().toISOString() });
311
164
  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);
165
+ if (json)
166
+ return { thread_id: thread.id, model: thread.model, endpoint, assistant: res.text, turns: thread.messages.length };
167
+ if (payload.stream)
168
+ process.stdout.write('\n');
169
+ else
170
+ this.log(res.text);
324
171
  this.log(`\n[thread ${thread.id} · ${thread.messages.length} turns]`);
325
- return { thread_id: thread.id, assistant: assistantText };
172
+ return { thread_id: thread.id, assistant: res.text };
326
173
  }
327
174
  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
- }
175
+ if (err instanceof FacesAPIError)
176
+ this.error(await chatRefusal(err, thread.model, endpoint, false, client));
342
177
  throw err;
343
178
  }
344
179
  }
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);
180
+ handleList() {
181
+ const threads = listThreads();
182
+ if (this.jsonEnabled()) {
183
+ return threads.map((t) => ({ id: t.id, model: t.model, turns: t.messages.length, created_at: t.created_at, updated_at: t.updated_at }));
368
184
  }
369
- let data;
370
- try {
371
- ;
372
- ({ data } = await retryOnceOnWarmUp(() => postChat(client, CHAT_COMPLETIONS_ENDPOINT, payload), sayWarmUp));
185
+ if (threads.length === 0) {
186
+ this.log('(no threads)');
187
+ return {};
373
188
  }
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
- }
189
+ for (const t of threads) {
190
+ const last = t.messages.at(-1);
191
+ this.log(`${t.id} ${t.model} (${t.messages.length} turns, updated ${t.updated_at})`);
192
+ if (last)
193
+ this.log(` ${last.role}: ${last.content.slice(0, 60).replace(/\s+/g, ' ')}${last.content.length > 60 ? '…' : ''}`);
383
194
  }
384
- return replyOf(data, CHAT_COMPLETIONS_ENDPOINT);
195
+ return {};
385
196
  }
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'];
197
+ async handleDelete(id, yes) {
198
+ if (!id)
199
+ this.error('--delete needs --id <thread-id>');
200
+ let p;
201
+ try {
202
+ p = threadPath(id);
397
203
  }
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);
204
+ catch (err) {
205
+ this.error(err instanceof Error ? err.message : String(err));
407
206
  }
408
- const { data } = await retryOnceOnWarmUp(() => postChat(client, RESPONSES_ENDPOINT, payload), sayWarmUp);
409
- return replyOf(data, RESPONSES_ENDPOINT);
207
+ if (!fs.existsSync(p))
208
+ this.error(`Thread not found: ${id}`);
209
+ await this.confirmOrRefuse(`Delete thread ${id} and its history?`, yes);
210
+ fs.unlinkSync(p);
211
+ if (!this.jsonEnabled())
212
+ this.log(`Deleted thread ${id}`);
213
+ return { deleted: id };
410
214
  }
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);
215
+ handleShow(id) {
216
+ if (!id)
217
+ this.error('--show needs --id <thread-id>');
218
+ let t;
219
+ try {
220
+ t = loadThread(id);
428
221
  }
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 { }
222
+ catch (err) {
223
+ this.error(err instanceof Error ? err.message : String(err));
468
224
  }
469
- process.stdout.write('\n');
470
- return { text: accum, reasoning, causeId, modelReasoning: modelReasoning || undefined };
225
+ if (!t)
226
+ this.error(`Thread not found: ${id}`);
227
+ if (this.jsonEnabled())
228
+ return t;
229
+ this.log(`Thread ${t.id} (${t.model})`);
230
+ this.log(`Created: ${t.created_at}`);
231
+ this.log(`Updated: ${t.updated_at}`);
232
+ if (t.system)
233
+ this.log(`---\nsystem: ${t.system}`);
234
+ for (const m of t.messages)
235
+ this.log(`---\n${m.role} [${m.ts}]:\n${m.content}`);
236
+ return t;
471
237
  }
472
238
  }
@@ -0,0 +1,20 @@
1
+ import { BaseCommand } from '../base.js';
2
+ export default class Choices extends BaseCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ question: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ state: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ 'state-file': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'state-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'max-choices': import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ 'base-url': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ token: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ 'api-key': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ toon: import("@oclif/core/interfaces").BooleanFlag<boolean>;
15
+ };
16
+ static args: {
17
+ model: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
18
+ };
19
+ run(): Promise<unknown>;
20
+ }