@faces-sh/cli 0.0.0-stage → 1.0.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 (290) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -2
  3. package/bin/dev.js +5 -0
  4. package/bin/run.js +5 -0
  5. package/dist/base.d.ts +26 -0
  6. package/dist/base.js +181 -0
  7. package/dist/benchmark.d.ts +21 -0
  8. package/dist/benchmark.js +95 -0
  9. package/dist/billing.d.ts +17 -0
  10. package/dist/billing.js +101 -0
  11. package/dist/catalog.d.ts +35 -0
  12. package/dist/catalog.js +242 -0
  13. package/dist/client.d.ts +98 -0
  14. package/dist/client.js +590 -0
  15. package/dist/commands/account/preferences.d.ts +20 -0
  16. package/dist/commands/account/preferences.js +190 -0
  17. package/dist/commands/account/state.d.ts +11 -0
  18. package/dist/commands/account/state.js +24 -0
  19. package/dist/commands/auth/connect.d.ts +17 -0
  20. package/dist/commands/auth/connect.js +190 -0
  21. package/dist/commands/auth/connections.d.ts +12 -0
  22. package/dist/commands/auth/connections.js +40 -0
  23. package/dist/commands/auth/disconnect.d.ts +15 -0
  24. package/dist/commands/auth/disconnect.js +49 -0
  25. package/dist/commands/auth/login.d.ts +13 -0
  26. package/dist/commands/auth/login.js +42 -0
  27. package/dist/commands/auth/logout.d.ts +11 -0
  28. package/dist/commands/auth/logout.js +14 -0
  29. package/dist/commands/auth/refresh.d.ts +11 -0
  30. package/dist/commands/auth/refresh.js +30 -0
  31. package/dist/commands/auth/register.d.ts +15 -0
  32. package/dist/commands/auth/register.js +98 -0
  33. package/dist/commands/auth/whoami.d.ts +11 -0
  34. package/dist/commands/auth/whoami.js +108 -0
  35. package/dist/commands/benchmark/get.d.ts +16 -0
  36. package/dist/commands/benchmark/get.js +42 -0
  37. package/dist/commands/benchmark/list.d.ts +13 -0
  38. package/dist/commands/benchmark/list.js +47 -0
  39. package/dist/commands/benchmark/start.d.ts +22 -0
  40. package/dist/commands/benchmark/start.js +80 -0
  41. package/dist/commands/billing/balance.d.ts +11 -0
  42. package/dist/commands/billing/balance.js +27 -0
  43. package/dist/commands/billing/card/default.d.ts +15 -0
  44. package/dist/commands/billing/card/default.js +33 -0
  45. package/dist/commands/billing/card/remove.d.ts +16 -0
  46. package/dist/commands/billing/card/remove.js +41 -0
  47. package/dist/commands/billing/card-setup.d.ts +13 -0
  48. package/dist/commands/billing/card-setup.js +41 -0
  49. package/dist/commands/billing/cards.d.ts +11 -0
  50. package/dist/commands/billing/cards.js +34 -0
  51. package/dist/commands/billing/llm-costs.d.ts +14 -0
  52. package/dist/commands/billing/llm-costs.js +95 -0
  53. package/dist/commands/billing/subscription/activate.d.ts +14 -0
  54. package/dist/commands/billing/subscription/activate.js +91 -0
  55. package/dist/commands/billing/subscription/cancel.d.ts +12 -0
  56. package/dist/commands/billing/subscription/cancel.js +54 -0
  57. package/dist/commands/billing/subscription/index.d.ts +11 -0
  58. package/dist/commands/billing/subscription/index.js +46 -0
  59. package/dist/commands/billing/subscription/plan.d.ts +16 -0
  60. package/dist/commands/billing/subscription/plan.js +86 -0
  61. package/dist/commands/billing/topup.d.ts +16 -0
  62. package/dist/commands/billing/topup.js +60 -0
  63. package/dist/commands/billing/usage.d.ts +15 -0
  64. package/dist/commands/billing/usage.js +68 -0
  65. package/dist/commands/catalog/backup.d.ts +11 -0
  66. package/dist/commands/catalog/backup.js +169 -0
  67. package/dist/commands/catalog/doctor.d.ts +14 -0
  68. package/dist/commands/catalog/doctor.js +303 -0
  69. package/dist/commands/catalog/list.d.ts +11 -0
  70. package/dist/commands/catalog/list.js +39 -0
  71. package/dist/commands/catalog/restore.d.ts +17 -0
  72. package/dist/commands/catalog/restore.js +259 -0
  73. package/dist/commands/causes.d.ts +27 -0
  74. package/dist/commands/causes.js +135 -0
  75. package/dist/commands/chat/chat.d.ts +42 -0
  76. package/dist/commands/chat/chat.js +363 -0
  77. package/dist/commands/chat/messages.d.ts +26 -0
  78. package/dist/commands/chat/messages.js +139 -0
  79. package/dist/commands/chat/responses.d.ts +27 -0
  80. package/dist/commands/chat/responses.js +150 -0
  81. package/dist/commands/chat/thread.d.ts +43 -0
  82. package/dist/commands/chat/thread.js +458 -0
  83. package/dist/commands/compile/all.d.ts +14 -0
  84. package/dist/commands/compile/all.js +186 -0
  85. package/dist/commands/compile/doc/create.d.ts +19 -0
  86. package/dist/commands/compile/doc/create.js +58 -0
  87. package/dist/commands/compile/doc/delete.d.ts +15 -0
  88. package/dist/commands/compile/doc/delete.js +33 -0
  89. package/dist/commands/compile/doc/edit.d.ts +19 -0
  90. package/dist/commands/compile/doc/edit.js +59 -0
  91. package/dist/commands/compile/doc/get.d.ts +15 -0
  92. package/dist/commands/compile/doc/get.js +43 -0
  93. package/dist/commands/compile/doc/index.d.ts +24 -0
  94. package/dist/commands/compile/doc/index.js +211 -0
  95. package/dist/commands/compile/doc/list.d.ts +15 -0
  96. package/dist/commands/compile/doc/list.js +46 -0
  97. package/dist/commands/compile/doc/make.d.ts +17 -0
  98. package/dist/commands/compile/doc/make.js +95 -0
  99. package/dist/commands/compile/doc/pause.d.ts +17 -0
  100. package/dist/commands/compile/doc/pause.js +74 -0
  101. package/dist/commands/compile/doc/reset.d.ts +15 -0
  102. package/dist/commands/compile/doc/reset.js +33 -0
  103. package/dist/commands/compile/import.d.ts +20 -0
  104. package/dist/commands/compile/import.js +138 -0
  105. package/dist/commands/compile/stats.d.ts +11 -0
  106. package/dist/commands/compile/stats.js +75 -0
  107. package/dist/commands/compile/status.d.ts +17 -0
  108. package/dist/commands/compile/status.js +110 -0
  109. package/dist/commands/compile/thread/create.d.ts +16 -0
  110. package/dist/commands/compile/thread/create.js +42 -0
  111. package/dist/commands/compile/thread/delete.d.ts +15 -0
  112. package/dist/commands/compile/thread/delete.js +33 -0
  113. package/dist/commands/compile/thread/edit.d.ts +19 -0
  114. package/dist/commands/compile/thread/edit.js +120 -0
  115. package/dist/commands/compile/thread/get.d.ts +15 -0
  116. package/dist/commands/compile/thread/get.js +48 -0
  117. package/dist/commands/compile/thread/list.d.ts +14 -0
  118. package/dist/commands/compile/thread/list.js +38 -0
  119. package/dist/commands/compile/thread/make.d.ts +17 -0
  120. package/dist/commands/compile/thread/make.js +87 -0
  121. package/dist/commands/compile/thread/message.d.ts +16 -0
  122. package/dist/commands/compile/thread/message.js +43 -0
  123. package/dist/commands/compile/thread/pause.d.ts +17 -0
  124. package/dist/commands/compile/thread/pause.js +75 -0
  125. package/dist/commands/compile/thread/replace.d.ts +27 -0
  126. package/dist/commands/compile/thread/replace.js +114 -0
  127. package/dist/commands/compile/thread/reset.d.ts +15 -0
  128. package/dist/commands/compile/thread/reset.js +33 -0
  129. package/dist/commands/compile/upload.d.ts +21 -0
  130. package/dist/commands/compile/upload.js +162 -0
  131. package/dist/commands/config/clear.d.ts +12 -0
  132. package/dist/commands/config/clear.js +17 -0
  133. package/dist/commands/config/set.d.ts +15 -0
  134. package/dist/commands/config/set.js +43 -0
  135. package/dist/commands/config/show.d.ts +11 -0
  136. package/dist/commands/config/show.js +19 -0
  137. package/dist/commands/decide.d.ts +35 -0
  138. package/dist/commands/decide.js +242 -0
  139. package/dist/commands/face/attributes.d.ts +11 -0
  140. package/dist/commands/face/attributes.js +44 -0
  141. package/dist/commands/face/avatar/delete.d.ts +15 -0
  142. package/dist/commands/face/avatar/delete.js +38 -0
  143. package/dist/commands/face/avatar/get.d.ts +20 -0
  144. package/dist/commands/face/avatar/get.js +100 -0
  145. package/dist/commands/face/avatar/list.d.ts +14 -0
  146. package/dist/commands/face/avatar/list.js +56 -0
  147. package/dist/commands/face/avatar/make.d.ts +16 -0
  148. package/dist/commands/face/avatar/make.js +64 -0
  149. package/dist/commands/face/avatar/upload.d.ts +15 -0
  150. package/dist/commands/face/avatar/upload.js +67 -0
  151. package/dist/commands/face/create.d.ts +23 -0
  152. package/dist/commands/face/create.js +122 -0
  153. package/dist/commands/face/delete.d.ts +15 -0
  154. package/dist/commands/face/delete.js +39 -0
  155. package/dist/commands/face/diff.d.ts +12 -0
  156. package/dist/commands/face/diff.js +50 -0
  157. package/dist/commands/face/edit.d.ts +25 -0
  158. package/dist/commands/face/edit.js +155 -0
  159. package/dist/commands/face/get.d.ts +16 -0
  160. package/dist/commands/face/get.js +145 -0
  161. package/dist/commands/face/groups.d.ts +15 -0
  162. package/dist/commands/face/groups.js +34 -0
  163. package/dist/commands/face/list.d.ts +23 -0
  164. package/dist/commands/face/list.js +168 -0
  165. package/dist/commands/face/lock.d.ts +15 -0
  166. package/dist/commands/face/lock.js +35 -0
  167. package/dist/commands/face/neighbors.d.ts +16 -0
  168. package/dist/commands/face/neighbors.js +63 -0
  169. package/dist/commands/face/publish.d.ts +16 -0
  170. package/dist/commands/face/publish.js +42 -0
  171. package/dist/commands/face/share.d.ts +22 -0
  172. package/dist/commands/face/share.js +103 -0
  173. package/dist/commands/face/sources.d.ts +21 -0
  174. package/dist/commands/face/sources.js +169 -0
  175. package/dist/commands/face/stats.d.ts +12 -0
  176. package/dist/commands/face/stats.js +46 -0
  177. package/dist/commands/face/tag/add.d.ts +15 -0
  178. package/dist/commands/face/tag/add.js +40 -0
  179. package/dist/commands/face/tag/all.d.ts +11 -0
  180. package/dist/commands/face/tag/all.js +31 -0
  181. package/dist/commands/face/tag/list.d.ts +14 -0
  182. package/dist/commands/face/tag/list.js +36 -0
  183. package/dist/commands/face/tag/remove.d.ts +16 -0
  184. package/dist/commands/face/tag/remove.js +44 -0
  185. package/dist/commands/face/tag/set.d.ts +15 -0
  186. package/dist/commands/face/tag/set.js +40 -0
  187. package/dist/commands/face/unlock.d.ts +15 -0
  188. package/dist/commands/face/unlock.js +35 -0
  189. package/dist/commands/face/unpublish.d.ts +14 -0
  190. package/dist/commands/face/unpublish.js +31 -0
  191. package/dist/commands/face/unshare.d.ts +18 -0
  192. package/dist/commands/face/unshare.js +66 -0
  193. package/dist/commands/fidelity/get.d.ts +15 -0
  194. package/dist/commands/fidelity/get.js +42 -0
  195. package/dist/commands/fidelity/pick.d.ts +19 -0
  196. package/dist/commands/fidelity/pick.js +70 -0
  197. package/dist/commands/fidelity/run.d.ts +20 -0
  198. package/dist/commands/fidelity/run.js +99 -0
  199. package/dist/commands/fidelity/save-thread.d.ts +15 -0
  200. package/dist/commands/fidelity/save-thread.js +35 -0
  201. package/dist/commands/fidelity/start.d.ts +17 -0
  202. package/dist/commands/fidelity/start.js +56 -0
  203. package/dist/commands/fidelity/turn.d.ts +17 -0
  204. package/dist/commands/fidelity/turn.js +48 -0
  205. package/dist/commands/group/add.d.ts +16 -0
  206. package/dist/commands/group/add.js +83 -0
  207. package/dist/commands/group/create.d.ts +16 -0
  208. package/dist/commands/group/create.js +68 -0
  209. package/dist/commands/group/delete.d.ts +15 -0
  210. package/dist/commands/group/delete.js +39 -0
  211. package/dist/commands/group/edit.d.ts +18 -0
  212. package/dist/commands/group/edit.js +75 -0
  213. package/dist/commands/group/get.d.ts +14 -0
  214. package/dist/commands/group/get.js +29 -0
  215. package/dist/commands/group/list.d.ts +11 -0
  216. package/dist/commands/group/list.js +39 -0
  217. package/dist/commands/group/members.d.ts +15 -0
  218. package/dist/commands/group/members.js +68 -0
  219. package/dist/commands/group/remove.d.ts +15 -0
  220. package/dist/commands/group/remove.js +55 -0
  221. package/dist/commands/group/tag/add.d.ts +15 -0
  222. package/dist/commands/group/tag/add.js +30 -0
  223. package/dist/commands/group/tag/list.d.ts +14 -0
  224. package/dist/commands/group/tag/list.js +36 -0
  225. package/dist/commands/group/tag/remove.d.ts +15 -0
  226. package/dist/commands/group/tag/remove.js +30 -0
  227. package/dist/commands/group/tag/set.d.ts +15 -0
  228. package/dist/commands/group/tag/set.js +30 -0
  229. package/dist/commands/keys/create.d.ts +17 -0
  230. package/dist/commands/keys/create.js +72 -0
  231. package/dist/commands/keys/list.d.ts +11 -0
  232. package/dist/commands/keys/list.js +24 -0
  233. package/dist/commands/keys/revoke.d.ts +15 -0
  234. package/dist/commands/keys/revoke.js +49 -0
  235. package/dist/commands/keys/update.d.ts +17 -0
  236. package/dist/commands/keys/update.js +41 -0
  237. package/dist/commands/models/list.d.ts +15 -0
  238. package/dist/commands/models/list.js +98 -0
  239. package/dist/commands/session/close.d.ts +16 -0
  240. package/dist/commands/session/close.js +36 -0
  241. package/dist/commands/session/compact.d.ts +15 -0
  242. package/dist/commands/session/compact.js +58 -0
  243. package/dist/commands/session/create.d.ts +15 -0
  244. package/dist/commands/session/create.js +45 -0
  245. package/dist/commands/session/get.d.ts +15 -0
  246. package/dist/commands/session/get.js +34 -0
  247. package/dist/commands/style/delete.d.ts +19 -0
  248. package/dist/commands/style/delete.js +92 -0
  249. package/dist/commands/style/make.d.ts +28 -0
  250. package/dist/commands/style/make.js +298 -0
  251. package/dist/commands/style/revert.d.ts +17 -0
  252. package/dist/commands/style/revert.js +66 -0
  253. package/dist/commands/style/status.d.ts +20 -0
  254. package/dist/commands/style/status.js +109 -0
  255. package/dist/commands/style/upload.d.ts +19 -0
  256. package/dist/commands/style/upload.js +100 -0
  257. package/dist/commands/style/versions.d.ts +15 -0
  258. package/dist/commands/style/versions.js +104 -0
  259. package/dist/commands/user/follow.d.ts +14 -0
  260. package/dist/commands/user/follow.js +38 -0
  261. package/dist/commands/user/followers.d.ts +14 -0
  262. package/dist/commands/user/followers.js +50 -0
  263. package/dist/commands/user/following.d.ts +14 -0
  264. package/dist/commands/user/following.js +50 -0
  265. package/dist/commands/user/get.d.ts +14 -0
  266. package/dist/commands/user/get.js +49 -0
  267. package/dist/commands/user/unfollow.d.ts +14 -0
  268. package/dist/commands/user/unfollow.js +38 -0
  269. package/dist/config.d.ts +32 -0
  270. package/dist/config.js +139 -0
  271. package/dist/decisions.d.ts +42 -0
  272. package/dist/decisions.js +262 -0
  273. package/dist/fidelity.d.ts +50 -0
  274. package/dist/fidelity.js +92 -0
  275. package/dist/group-catalog.d.ts +22 -0
  276. package/dist/group-catalog.js +133 -0
  277. package/dist/paths.d.ts +1 -0
  278. package/dist/paths.js +8 -0
  279. package/dist/poll.d.ts +26 -0
  280. package/dist/poll.js +75 -0
  281. package/dist/routing.d.ts +15 -0
  282. package/dist/routing.js +135 -0
  283. package/dist/session.d.ts +14 -0
  284. package/dist/session.js +18 -0
  285. package/dist/style.d.ts +46 -0
  286. package/dist/style.js +285 -0
  287. package/dist/utils.d.ts +149 -0
  288. package/dist/utils.js +865 -0
  289. package/oclif.manifest.json +11070 -0
  290. package/package.json +127 -4
@@ -0,0 +1,262 @@
1
+ import fs from 'node:fs';
2
+ import { FacesAPIError, readableDetail } from './client.js';
3
+ export const DECISION_MODELS = ['jev-latest', 'clef', 'clef-flash'];
4
+ export async function decisionModels(client) {
5
+ try {
6
+ const raw = (await client.get('/v1/models', { params: { kind: 'decision' } }));
7
+ const rows = (Array.isArray(raw) ? raw : (raw.data ?? []));
8
+ const ids = rows.map((m) => m.id).filter((id) => typeof id === 'string');
9
+ if (ids.length > 0)
10
+ return ids;
11
+ }
12
+ catch {
13
+ }
14
+ return [...DECISION_MODELS];
15
+ }
16
+ export const DECISION_FORMATS = ['systemone', 'openai'];
17
+ export function toOpenAIDecision(model, state, questions) {
18
+ const body = { model, input: typeof state === 'string' ? state : JSON.stringify(state) };
19
+ if (!questions)
20
+ return body;
21
+ body.questions = Object.entries(questions).map(([name, raw]) => {
22
+ const q = (raw ?? {});
23
+ if (q.type === 'noul') {
24
+ if (q.criteria && typeof q.criteria === 'object' && Object.keys(q.criteria).length > 0) {
25
+ throw new Error(`The yes and no descriptions on '${name}' have no place in the OpenAI format. Leave them out, or use --format systemone.`);
26
+ }
27
+ return { type: 'predicate', name, instructions: q.instructions };
28
+ }
29
+ if (q.type === 'choice') {
30
+ const c = (q.criteria ?? {});
31
+ return {
32
+ type: 'choice',
33
+ name,
34
+ instructions: q.instructions,
35
+ choices: Object.entries(c).map(([value, description]) => (description ? { value, description: String(description) } : { value })),
36
+ };
37
+ }
38
+ if (q.type === 'score') {
39
+ const levels = Array.isArray(q.criteria) ? q.criteria : [];
40
+ return { type: 'score', name, instructions: q.instructions, levels: levels.map((label) => ({ label: String(label) })) };
41
+ }
42
+ throw new Error(`'${name}' has a type the OpenAI format does not take: ${String(q.type)}.`);
43
+ });
44
+ return body;
45
+ }
46
+ export function fromOpenAIAnswers(answers, questions = {}) {
47
+ if (!Array.isArray(answers))
48
+ return {};
49
+ const out = {};
50
+ for (const raw of answers) {
51
+ const a = (raw ?? {});
52
+ const name = String(a.name ?? `answer ${Object.keys(out).length + 1}`);
53
+ const probs = Array.isArray(a.probabilities) ? a.probabilities : [];
54
+ if (a.type === 'predicate') {
55
+ out[name] = { type: 'noul', noul: a.probability };
56
+ }
57
+ else if (a.type === 'choice') {
58
+ out[name] = { type: 'choice', choice: a.choice, confidence: a.confidence, probabilities: Object.fromEntries(probs.map((p) => [String(p.value), p.probability])) };
59
+ }
60
+ else if (a.type === 'score') {
61
+ const sent = questions[name]?.criteria;
62
+ const labels = Array.isArray(sent) ? sent.map(String) : [];
63
+ out[name] = {
64
+ type: 'score',
65
+ score: a.score,
66
+ confidence: a.confidence,
67
+ probabilities: Object.fromEntries(probs.map((p, i) => [String(typeof p.level === 'number' ? p.level : i), p.probability])),
68
+ legend: Object.fromEntries(labels.map((l, i) => [String(i), l])),
69
+ };
70
+ }
71
+ else {
72
+ out[name] = a;
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ export const MAX_QUESTIONS = { face: 10, baseline: 32, openaiBaseline: 400 };
78
+ export const CHOICE_OPTIONS = { min: 2, max: 255 };
79
+ export function questionsProblem(questions, withFace, openaiModel = false) {
80
+ const n = Object.keys(questions).length;
81
+ const max = withFace ? MAX_QUESTIONS.face : openaiModel ? MAX_QUESTIONS.openaiBaseline : MAX_QUESTIONS.baseline;
82
+ if (n > max)
83
+ return `At most ${max} questions ${withFace ? 'with a face' : 'with --baseline'} (got ${n}). Split them across requests.`;
84
+ for (const [id, q] of Object.entries(questions)) {
85
+ const o = q;
86
+ if (o?.type !== 'choice' || !o.criteria || typeof o.criteria !== 'object')
87
+ continue;
88
+ const k = Array.isArray(o.criteria) ? o.criteria.length : Object.keys(o.criteria).length;
89
+ if (k < CHOICE_OPTIONS.min || k > CHOICE_OPTIONS.max) {
90
+ return `The choice '${id}' has ${k} option(s); a choice takes ${CHOICE_OPTIONS.min} to ${CHOICE_OPTIONS.max}.`;
91
+ }
92
+ }
93
+ return undefined;
94
+ }
95
+ export const QUESTION_TYPES = ['noul', 'choice', 'score'];
96
+ export function parseDecisionOption(raw) {
97
+ const at = raw.indexOf('=');
98
+ const name = (at === -1 ? raw : raw.slice(0, at)).trim();
99
+ if (!name)
100
+ return undefined;
101
+ if (at === -1)
102
+ return { name, definition: null };
103
+ const definition = raw.slice(at + 1).trim();
104
+ return { name, definition: definition || null };
105
+ }
106
+ function bar(p, barWidth) {
107
+ return '#'.repeat(Math.round(Math.min(Math.max(p, 0), 1) * barWidth));
108
+ }
109
+ function pct(p) {
110
+ return `${(p * 100).toFixed(1)}%`.padStart(6);
111
+ }
112
+ function probabilityLines(probabilities, label, barWidth) {
113
+ const entries = Object.entries(probabilities)
114
+ .map(([key, p]) => [label(key), typeof p === 'number' ? p : Number.NaN])
115
+ .sort((a, b) => (Number.isNaN(b[1]) ? -1 : b[1]) - (Number.isNaN(a[1]) ? -1 : a[1]));
116
+ const width = Math.max(...entries.map(([name]) => name.length));
117
+ return entries.map(([name, p]) => Number.isNaN(p) ? ` ${name.padEnd(width)} -` : ` ${name.padEnd(width)} ${pct(p)} ${bar(p, barWidth)}`.trimEnd());
118
+ }
119
+ export function decisionLines(answers, barWidth = 20) {
120
+ const lines = [];
121
+ for (const [id, raw] of Object.entries(answers)) {
122
+ if (lines.length > 0)
123
+ lines.push('');
124
+ const a = (raw && typeof raw === 'object' ? raw : {});
125
+ const confidence = typeof a.confidence === 'number' ? `, confidence ${a.confidence.toFixed(2)}` : '';
126
+ if (a.type === 'noul' && typeof a.noul === 'number') {
127
+ lines.push(`${id}: yes ${(a.noul * 100).toFixed(1)}%`);
128
+ lines.push(...probabilityLines({ yes: a.noul, no: 1 - a.noul }, (k) => k, barWidth));
129
+ continue;
130
+ }
131
+ if (a.type === 'choice') {
132
+ lines.push(`${id}: ${String(a.choice ?? '-')}${confidence}`);
133
+ if (a.probabilities && typeof a.probabilities === 'object') {
134
+ lines.push(...probabilityLines(a.probabilities, (k) => k, barWidth));
135
+ }
136
+ continue;
137
+ }
138
+ if (a.type === 'score') {
139
+ const legend = (a.legend && typeof a.legend === 'object' ? a.legend : {});
140
+ const top = Math.max(-1, ...Object.keys(legend).map(Number).filter((n) => !Number.isNaN(n)));
141
+ const score = typeof a.score === 'number' ? a.score.toFixed(2) : '-';
142
+ lines.push(`${id}: ${score}${top >= 0 ? ` on 0 to ${top}` : ''}${confidence}`);
143
+ if (a.probabilities && typeof a.probabilities === 'object') {
144
+ const label = (k) => (legend[k] === undefined ? k : `${k} ${String(legend[k])}`);
145
+ lines.push(...probabilityLines(a.probabilities, label, barWidth));
146
+ }
147
+ continue;
148
+ }
149
+ lines.push(id, ` ${JSON.stringify(raw)}`);
150
+ }
151
+ return lines;
152
+ }
153
+ export const MAX_WARM_UP_WAIT_S = 300;
154
+ export function warmUpWait(status, retryAfter, waitedS) {
155
+ if (status !== 503 || retryAfter === undefined)
156
+ return undefined;
157
+ if (waitedS + retryAfter > MAX_WARM_UP_WAIT_S)
158
+ return undefined;
159
+ return retryAfter;
160
+ }
161
+ export function causeLines(data, questionIds) {
162
+ const cause = typeof data.cause === 'string' ? data.cause : '';
163
+ const per = questionIds.map((id) => {
164
+ const c = data.causes?.[id];
165
+ return [id, typeof c === 'string' && c !== '' ? c : cause];
166
+ });
167
+ if (per.length === 0 || per.every(([, c]) => c === cause))
168
+ return cause ? [cause] : [];
169
+ const lines = [];
170
+ for (const [id, c] of per) {
171
+ if (!c)
172
+ continue;
173
+ if (lines.length > 0)
174
+ lines.push('');
175
+ lines.push(`${id}:`, c);
176
+ }
177
+ return lines;
178
+ }
179
+ export function heldDecisionError(data) {
180
+ if (!data || typeof data !== 'object')
181
+ return undefined;
182
+ const d = data;
183
+ if (!d.error || typeof d.error !== 'object' || 'answers' in d || 'cause' in d)
184
+ return undefined;
185
+ const e = d.error;
186
+ const n = Number(e.status);
187
+ const status = Number.isInteger(n) && n >= 400 && n < 600 ? n : 502;
188
+ const said = readableDetail(d.detail) ?? (typeof e.message === 'string' && e.message.trim() ? e.message : undefined);
189
+ const code = typeof e.code === 'string' ? e.code : typeof e.type === 'string' ? e.type : undefined;
190
+ return new FacesAPIError(status, said ?? 'The request failed after the server held it open.', {
191
+ errorCode: code,
192
+ });
193
+ }
194
+ export function readStateFlags(flags, fail) {
195
+ let state = flags.state;
196
+ const path = flags['state-file'];
197
+ if (path) {
198
+ if (!fs.existsSync(path))
199
+ fail(`File not found: ${path}`);
200
+ state = fs.readFileSync(path, 'utf8');
201
+ if (path.toLowerCase().endsWith('.json')) {
202
+ try {
203
+ return JSON.parse(state);
204
+ }
205
+ catch (err) {
206
+ fail(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
207
+ }
208
+ }
209
+ }
210
+ if (!state?.trim())
211
+ fail('Describe the situation with --state or --state-file.');
212
+ return state;
213
+ }
214
+ export function readQuestionFlags(flags, fail) {
215
+ if (flags['questions-file']) {
216
+ const path = flags['questions-file'];
217
+ if (!fs.existsSync(path))
218
+ fail(`File not found: ${path}`);
219
+ let parsed;
220
+ try {
221
+ parsed = JSON.parse(fs.readFileSync(path, 'utf8'));
222
+ }
223
+ catch (err) {
224
+ fail(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
225
+ }
226
+ if (parsed && typeof parsed === 'object' && 'questions' in parsed && 'state' in parsed) {
227
+ parsed = parsed.questions;
228
+ }
229
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.keys(parsed).length === 0) {
230
+ fail(`${path} should hold an object of questions: {"<id>": {"type": "...", "instructions": "...", "criteria": ...}}`);
231
+ }
232
+ return parsed;
233
+ }
234
+ if (!flags.question)
235
+ return undefined;
236
+ const options = flags.option ?? [];
237
+ const levels = flags.level ?? [];
238
+ const type = flags.type ?? (options.length > 0 ? 'choice' : levels.length > 0 ? 'score' : 'noul');
239
+ const question = { type, instructions: flags.question };
240
+ if (type === 'choice') {
241
+ const criteria = {};
242
+ for (const raw of options) {
243
+ const parsed = parseDecisionOption(raw);
244
+ if (!parsed)
245
+ fail(`--option '${raw}' names nothing. Use name="description", or a bare name.`);
246
+ criteria[parsed.name] = parsed.definition;
247
+ }
248
+ if (Object.keys(criteria).length < 2)
249
+ fail('A choice needs at least two --option values to choose between.');
250
+ question.criteria = criteria;
251
+ }
252
+ else if (type === 'score') {
253
+ if (levels.length < 2 || levels.length > 10) {
254
+ fail(`A score needs 2 to 10 --level values, lowest first (got ${levels.length}).`);
255
+ }
256
+ question.criteria = levels;
257
+ }
258
+ else if (options.length > 0 || levels.length > 0) {
259
+ fail('A noul is a yes or no and takes no --option or --level. Leave them out, or pick another --type.');
260
+ }
261
+ return { [flags.id ?? 'answer']: question };
262
+ }
@@ -0,0 +1,50 @@
1
+ import { FacesAPIError, FacesClient } from './client.js';
2
+ export declare const FIDELITY_TURNS = 10;
3
+ export interface FidelityTurn {
4
+ n: number;
5
+ message?: string;
6
+ answers?: {
7
+ a?: string;
8
+ b?: string;
9
+ };
10
+ pick?: 'a' | 'b';
11
+ correction?: string | null;
12
+ score?: number | null;
13
+ face?: 'a' | 'b';
14
+ }
15
+ export interface FidelityRun {
16
+ run_id: string;
17
+ alias?: string;
18
+ status?: string;
19
+ competitor?: string;
20
+ competitor_texts?: number;
21
+ turns_total?: number;
22
+ turns_done?: number;
23
+ next?: {
24
+ turn: number;
25
+ awaiting: 'message' | 'choice';
26
+ } | null;
27
+ score?: number | null;
28
+ score_so_far?: number;
29
+ thread_id?: string | null;
30
+ turns?: FidelityTurn[];
31
+ estimated_usd?: number;
32
+ }
33
+ export declare function fidelityPost(client: FacesClient, path: string, body: Record<string, unknown>): Promise<Record<string, unknown>>;
34
+ export declare function getRun(client: FacesClient, runId: string): Promise<FidelityRun>;
35
+ export declare function score10(n: unknown): string;
36
+ export declare function nextStep(run: FidelityRun): string | undefined;
37
+ export declare function runLines(run: FidelityRun): string[];
38
+ export declare function turnLines(run: FidelityRun): string[];
39
+ export declare function answerLines(turn: number, answers: {
40
+ a?: unknown;
41
+ b?: unknown;
42
+ }): string[];
43
+ export declare function fidelityHint(err: FacesAPIError, on?: {
44
+ run?: string;
45
+ alias?: string;
46
+ }): string | undefined;
47
+ export declare function fidelityError(err: FacesAPIError, on?: {
48
+ run?: string;
49
+ alias?: string;
50
+ }): string;
@@ -0,0 +1,92 @@
1
+ import { heldDecisionError } from './decisions.js';
2
+ import { seg } from './utils.js';
3
+ export const FIDELITY_TURNS = 10;
4
+ export async function fidelityPost(client, path, body) {
5
+ const data = (await client.post(path, { body }));
6
+ const held = heldDecisionError(data);
7
+ if (held)
8
+ throw held;
9
+ return data;
10
+ }
11
+ export async function getRun(client, runId) {
12
+ return (await client.get(`/v1/fidelity/${seg(runId)}`));
13
+ }
14
+ export function score10(n) {
15
+ return typeof n === 'number' && Number.isFinite(n) ? n.toFixed(1).replace(/\.0$/, '') : '-';
16
+ }
17
+ export function nextStep(run) {
18
+ const id = run.run_id;
19
+ if (!run.next) {
20
+ return run.thread_id
21
+ ? undefined
22
+ : `Keep the conversation as a thread on the face, to compile: faces fidelity:save-thread ${id}`;
23
+ }
24
+ return run.next.awaiting === 'choice'
25
+ ? `Pick the answer that sounds more like the person: faces fidelity:pick ${id} a|b [--correction "..."]`
26
+ : `Send turn ${run.next.turn}'s message: faces fidelity:turn ${id} -m "..."`;
27
+ }
28
+ export function runLines(run) {
29
+ const total = run.turns_total ?? FIDELITY_TURNS;
30
+ const done = run.status === 'done';
31
+ const lines = [
32
+ `run: ${run.run_id}`,
33
+ `face: ${run.alias ?? '-'}`,
34
+ `status: ${done ? 'finished' : 'in progress'}`,
35
+ ];
36
+ if (run.competitor) {
37
+ const texts = typeof run.competitor_texts === 'number' ? `, shown ${run.competitor_texts} of the face's texts` : '';
38
+ lines.push(`competitor: ${run.competitor}${texts}`);
39
+ }
40
+ lines.push(`turns: ${run.turns_done ?? 0} of ${total}`);
41
+ lines.push(done ? `score: ${score10(run.score)} out of ${total}` : `so far: ${score10(run.score_so_far ?? 0)} out of ${run.turns_done ?? 0}`);
42
+ if (run.thread_id)
43
+ lines.push(`thread: ${run.thread_id}`);
44
+ return lines;
45
+ }
46
+ export function turnLines(run) {
47
+ const out = [];
48
+ for (const t of run.turns ?? []) {
49
+ if (!t.pick) {
50
+ out.push(` turn ${t.n}: waiting for a pick`);
51
+ continue;
52
+ }
53
+ const how = t.correction ? 'corrected' : 'accepted';
54
+ const side = t.face ? (t.face === t.pick ? ', the face' : ', the competitor') : '';
55
+ out.push(` turn ${t.n}: picked ${t.pick}${side}, ${how}, scored ${score10(t.score)}`);
56
+ }
57
+ return out;
58
+ }
59
+ export function answerLines(turn, answers) {
60
+ return [
61
+ `Turn ${turn} of ${FIDELITY_TURNS}. Which sounds more like the person?`,
62
+ '',
63
+ 'a:',
64
+ String(answers.a ?? ''),
65
+ '',
66
+ 'b:',
67
+ String(answers.b ?? ''),
68
+ ];
69
+ }
70
+ export function fidelityHint(err, on = {}) {
71
+ const id = on.run ?? '<run>';
72
+ switch (err.errorCode) {
73
+ case 'fidelity_choice_pending':
74
+ return `Pick one first: faces fidelity:pick ${id} a|b`;
75
+ case 'fidelity_run_finished':
76
+ return `Read the score: faces fidelity:get ${id}. Start another with faces fidelity:start ${on.alias ?? '<alias>'}.`;
77
+ case 'fidelity_run_open':
78
+ return `See where it stands: faces fidelity:get ${id}`;
79
+ case 'fidelity_unknown_model':
80
+ return 'List the chat models with: faces models:list';
81
+ case 'fidelity_nothing_compiled':
82
+ return `Add a source with: faces compile:upload ${on.alias ?? '<alias>'} --file <file>`;
83
+ case 'fidelity_run_not_found':
84
+ return 'Run ids are printed by faces fidelity:start.';
85
+ default:
86
+ return undefined;
87
+ }
88
+ }
89
+ export function fidelityError(err, on = {}) {
90
+ const hint = fidelityHint(err, on);
91
+ return `HTTP ${err.statusCode}: ${err.message}${hint ? `\n${hint}` : ''}`;
92
+ }
@@ -0,0 +1,22 @@
1
+ export declare const GROUPS_DIR: string;
2
+ export declare function slugifyGroupName(name: string): string;
3
+ export interface GroupFrontmatter {
4
+ id?: string;
5
+ name: string;
6
+ description?: string;
7
+ tags?: string[];
8
+ members?: string[];
9
+ extra?: string[];
10
+ }
11
+ export declare function stripFrontmatter(text: string): string;
12
+ export declare class GroupCatalogService {
13
+ writeGroup(name: string, fm: GroupFrontmatter, protocol?: string | null): void;
14
+ readGroup(name: string): {
15
+ frontmatter: GroupFrontmatter;
16
+ body: string;
17
+ } | null;
18
+ listGroups(): string[];
19
+ hasLocalContent(name: string): boolean;
20
+ findById(id: string): string | undefined;
21
+ deleteGroup(name: string): void;
22
+ }
@@ -0,0 +1,133 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { quoteYaml, unquoteYaml } from './utils.js';
5
+ import { childPath } from './paths.js';
6
+ export const GROUPS_DIR = path.join(os.homedir(), '.faces', 'teams');
7
+ export function slugifyGroupName(name) {
8
+ return String(name)
9
+ .toLowerCase()
10
+ .replace(/[^a-z0-9]+/g, '-')
11
+ .replace(/^-|-$/g, '');
12
+ }
13
+ export function stripFrontmatter(text) {
14
+ let out = text;
15
+ while (/^---\r?\n[\s\S]*?\r?\n---\r?\n?/.test(out))
16
+ out = out.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
17
+ return out.replace(/^\s*\n/, '');
18
+ }
19
+ function serializeFrontmatter(fm) {
20
+ const lines = ['---'];
21
+ if (fm.id)
22
+ lines.push(`id: ${fm.id}`);
23
+ lines.push(`name: ${quoteYaml(fm.name)}`);
24
+ if (fm.description)
25
+ lines.push(`description: ${quoteYaml(fm.description)}`);
26
+ if (fm.tags && fm.tags.length > 0) {
27
+ lines.push(`tags: [${fm.tags.join(', ')}]`);
28
+ }
29
+ if (fm.members && fm.members.length > 0) {
30
+ lines.push(`members: [${fm.members.join(', ')}]`);
31
+ }
32
+ for (const line of fm.extra ?? [])
33
+ lines.push(line);
34
+ lines.push('---');
35
+ return lines.join('\n');
36
+ }
37
+ const KNOWN_KEYS = new Set(['id', 'name', 'description', 'tags', 'members']);
38
+ function parseBlock(yamlBlock, fm) {
39
+ for (const line of yamlBlock.split('\n')) {
40
+ const colonIdx = line.indexOf(':');
41
+ const key = colonIdx < 0 ? '' : line.slice(0, colonIdx).trim();
42
+ if (!KNOWN_KEYS.has(key)) {
43
+ if (line.trim() && !(fm.extra ?? []).includes(line))
44
+ fm.extra = [...(fm.extra ?? []), line];
45
+ continue;
46
+ }
47
+ if (fm[key] !== undefined)
48
+ continue;
49
+ const val = line.slice(colonIdx + 1).trim();
50
+ if (key === 'id')
51
+ fm.id = unquoteYaml(val);
52
+ else if (key === 'name')
53
+ fm.name = unquoteYaml(val);
54
+ else if (key === 'description')
55
+ fm.description = unquoteYaml(val);
56
+ else {
57
+ const inner = val.replace(/^\[/, '').replace(/\]$/, '');
58
+ const items = inner ? inner.split(',').map(s => s.trim()).filter(Boolean) : [];
59
+ if (key === 'tags')
60
+ fm.tags = items;
61
+ else
62
+ fm.members = items;
63
+ }
64
+ }
65
+ }
66
+ function parseFrontmatter(content) {
67
+ const block = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
68
+ let match = content.match(block);
69
+ if (!match)
70
+ return { frontmatter: null, body: content };
71
+ const fm = {};
72
+ let rest = content;
73
+ while (match) {
74
+ parseBlock(match[1], fm);
75
+ rest = rest.slice(match[0].length);
76
+ match = rest.match(block);
77
+ }
78
+ if (!fm.name)
79
+ return { frontmatter: null, body: content };
80
+ return { frontmatter: fm, body: rest };
81
+ }
82
+ export class GroupCatalogService {
83
+ writeGroup(name, fm, protocol) {
84
+ try {
85
+ const dir = childPath(GROUPS_DIR, name);
86
+ fs.mkdirSync(dir, { recursive: true });
87
+ const filePath = path.join(dir, 'TEAM.md');
88
+ const existing = fs.existsSync(filePath) ? parseFrontmatter(fs.readFileSync(filePath, 'utf8')).frontmatter : null;
89
+ const merged = { ...fm, extra: fm.extra ?? existing?.extra };
90
+ const body = stripFrontmatter(protocol ?? '');
91
+ const content = serializeFrontmatter(merged) + '\n' + body;
92
+ fs.writeFileSync(filePath, content);
93
+ }
94
+ catch (err) {
95
+ const msg = err instanceof Error ? err.message : String(err);
96
+ process.stderr.write(`warn: group catalog write failed: ${msg}\n`);
97
+ }
98
+ }
99
+ readGroup(name) {
100
+ const filePath = path.join(childPath(GROUPS_DIR, name), 'TEAM.md');
101
+ if (!fs.existsSync(filePath))
102
+ return null;
103
+ const content = fs.readFileSync(filePath, 'utf8');
104
+ const parsed = parseFrontmatter(content);
105
+ if (!parsed.frontmatter)
106
+ return null;
107
+ return { frontmatter: parsed.frontmatter, body: parsed.body };
108
+ }
109
+ listGroups() {
110
+ if (!fs.existsSync(GROUPS_DIR))
111
+ return [];
112
+ return fs.readdirSync(GROUPS_DIR, { withFileTypes: true })
113
+ .filter(d => d.isDirectory() && fs.existsSync(path.join(GROUPS_DIR, d.name, 'TEAM.md')))
114
+ .map(d => d.name);
115
+ }
116
+ hasLocalContent(name) {
117
+ const group = this.readGroup(name);
118
+ return Boolean(group && group.body.trim());
119
+ }
120
+ findById(id) {
121
+ return this.listGroups().find((name) => this.readGroup(name)?.frontmatter.id === id);
122
+ }
123
+ deleteGroup(name) {
124
+ try {
125
+ const dir = childPath(GROUPS_DIR, name);
126
+ fs.rmSync(dir, { recursive: true, force: true });
127
+ }
128
+ catch (err) {
129
+ const msg = err instanceof Error ? err.message : String(err);
130
+ process.stderr.write(`warn: group catalog delete failed: ${msg}\n`);
131
+ }
132
+ }
133
+ }
@@ -0,0 +1 @@
1
+ export declare function childPath(base: string, name: string): string;
package/dist/paths.js ADDED
@@ -0,0 +1,8 @@
1
+ import path from 'node:path';
2
+ export function childPath(base, name) {
3
+ const p = path.resolve(base, name);
4
+ if (!name || path.dirname(p) !== path.resolve(base)) {
5
+ throw new Error(`"${name}" cannot be used as a folder name under ${base}.`);
6
+ }
7
+ return p;
8
+ }
package/dist/poll.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { FacesClient } from './client.js';
2
+ export interface PollProgress {
3
+ status: string | null;
4
+ progress: number | null;
5
+ finishing: boolean | null;
6
+ stall_reason: string | null;
7
+ starts_at?: string | null;
8
+ rush?: boolean | null;
9
+ }
10
+ export interface PollOptions {
11
+ intervalMs?: number;
12
+ timeoutMs?: number;
13
+ startsAt?: string | null;
14
+ onProgress?: (p: PollProgress) => void;
15
+ endpoint?: string;
16
+ fullOnFinish?: boolean;
17
+ }
18
+ export declare function progressLine(p: PollProgress): string;
19
+ export declare function pollCompileProgress(client: FacesClient, id: string, opts?: PollOptions): Promise<unknown>;
20
+ export interface PausePollOptions {
21
+ intervalMs?: number;
22
+ timeoutMs?: number;
23
+ onTick?: () => void;
24
+ endpoint?: string;
25
+ }
26
+ export declare function pollUntilPaused(client: FacesClient, id: string, opts?: PausePollOptions): Promise<string | null | undefined>;
package/dist/poll.js ADDED
@@ -0,0 +1,75 @@
1
+ import { compileProgressLabel, compileStatusOf, msUntilStart, seg } from './utils.js';
2
+ export function progressLine(p) {
3
+ return compileProgressLabel(p);
4
+ }
5
+ export async function pollCompileProgress(client, id, opts = {}) {
6
+ const interval = opts.intervalMs ?? 3000;
7
+ const timeout = opts.timeoutMs ?? 600_000;
8
+ const start = Date.now();
9
+ let deadline = start + timeout + msUntilStart(opts.startsAt, start);
10
+ const base = opts.endpoint ?? `/v1/compile/documents/${seg(id)}`;
11
+ const endpoint = base.includes('?') ? `${base}&status_only=true` : `${base}?status_only=true`;
12
+ let lastLine = '';
13
+ while (true) {
14
+ if (Date.now() > deadline) {
15
+ throw new Error(`Compile timed out after ${Math.round(timeout / 1000)}s`);
16
+ }
17
+ await sleep(interval);
18
+ const data = await client.get(endpoint);
19
+ const progress = {
20
+ status: compileStatusOf(data.status),
21
+ progress: typeof data.progress === 'number' ? data.progress : null,
22
+ finishing: data.finishing ?? null,
23
+ stall_reason: data.stall_reason ?? null,
24
+ starts_at: typeof data.starts_at === 'string' ? data.starts_at : null,
25
+ rush: typeof data.rush === 'boolean' ? data.rush : null,
26
+ };
27
+ if (progress.status === 'queued') {
28
+ const now = Date.now();
29
+ const wait = msUntilStart(progress.starts_at, now);
30
+ if (wait > 0)
31
+ deadline = Math.max(deadline, now + wait + timeout);
32
+ }
33
+ const line = progressLine(progress);
34
+ if (line !== lastLine) {
35
+ lastLine = line;
36
+ opts.onProgress?.(progress);
37
+ }
38
+ if (progress.status === 'compiled') {
39
+ if (opts.fullOnFinish === false)
40
+ return data;
41
+ try {
42
+ return await client.get(base);
43
+ }
44
+ catch {
45
+ return data;
46
+ }
47
+ }
48
+ if (progress.status === 'failed' && progress.finishing !== true) {
49
+ throw new Error(`Compile failed: ${progress.stall_reason ?? data.error_code ?? 'no reason given'}\n` +
50
+ 'It is out of automatic retries, so this needs a decision rather than more waiting.');
51
+ }
52
+ if (progress.status === 'paused') {
53
+ throw new Error('Compile is paused, and nothing moves until it is resumed. Resume it by running make again.');
54
+ }
55
+ }
56
+ }
57
+ function sleep(ms) {
58
+ return new Promise((resolve) => setTimeout(resolve, ms));
59
+ }
60
+ const PAUSE_TERMINAL = new Set(['paused', 'compiled', 'failed', 'not_compiled']);
61
+ export async function pollUntilPaused(client, id, opts = {}) {
62
+ const interval = opts.intervalMs ?? 1000;
63
+ const timeout = opts.timeoutMs ?? 60_000;
64
+ const endpoint = opts.endpoint ?? `/v1/compile/documents/${seg(id)}`;
65
+ const start = Date.now();
66
+ while (Date.now() - start < timeout) {
67
+ await sleep(interval);
68
+ opts.onTick?.();
69
+ const data = await client.get(`${endpoint}?status_only=true`);
70
+ const status = compileStatusOf(data.status);
71
+ if (status === null || PAUSE_TERMINAL.has(status))
72
+ return status;
73
+ }
74
+ return undefined;
75
+ }