@figs-so/cli 0.1.7 → 0.1.8

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 (3) hide show
  1. package/README.md +1 -1
  2. package/figs.mjs +135 -50
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -33,6 +33,6 @@ The full, always-current guide + `agent.json` schema is served at **`<endpoint>/
33
33
  | `figs version` | print version + check for updates |
34
34
  | `figs help [<command>]` | usage (bare `figs` shows it too) |
35
35
 
36
- Global: `-h` / `--help` on any command (or `figs help <command>`), `-v` / `--version` for the version. Unknown commands exit non-zero.
36
+ Global: `-h` / `--help` on any command (or `figs help <command>`), `-v` / `--version` for the version. Unknown commands **and unknown flags** exit non-zero (no silent no-ops). Flags accept `--name value` or `--name=value`. Network calls time out after 30s.
37
37
 
38
38
  Override the endpoint with `FIGS_ENDPOINT` (e.g. `http://localhost:3000` for local dev).
package/figs.mjs CHANGED
@@ -16,7 +16,9 @@
16
16
  *
17
17
  * Designed to be driven by an agent: non-interactive, clear output, `--json`
18
18
  * on read commands, `-h`/`--help`/`help` everywhere, and errors that say what to
19
- * do next. Bare `figs` prints help; unknown commands exit non-zero.
19
+ * do next. Bare `figs` prints help; unknown commands AND unknown flags exit
20
+ * non-zero (no silent no-ops). Flags accept `--name value` or `--name=value`.
21
+ * Network calls time out (30s) instead of hanging the agent.
20
22
  *
21
23
  * Auth is the *user* (a token, configured once per machine). Identity is the
22
24
  * *agent* — a UUID generated by `init`, stored in the committed, non-secret
@@ -35,7 +37,7 @@ import { homedir } from "node:os"
35
37
  import { join } from "node:path"
36
38
  import { randomUUID } from "node:crypto"
37
39
 
38
- const VERSION = "0.1.7"
40
+ const VERSION = "0.1.8"
39
41
  // Going-forward default; override with FIGS_ENDPOINT or .figs/config.json endpoint
40
42
  // (e.g. FIGS_ENDPOINT=http://localhost:3000 for local dev).
41
43
  const DEFAULT_ENDPOINT = "https://app.figs.so"
@@ -47,34 +49,67 @@ const cmd = process.argv[2] ?? "help"
47
49
  const JSON_OUT = process.argv.includes("--json")
48
50
  const WANTS_HELP = process.argv.slice(2).some((a) => a === "-h" || a === "--help")
49
51
 
50
- /** Command registry — single source for dispatch + `figs help`. */
52
+ /**
53
+ * Command registry — single source for dispatch, `figs help`, and per-command
54
+ * flag validation. `flags` lists the flags a command accepts (beyond the global
55
+ * `-h`/`--help`); an unrecognized flag is rejected rather than silently ignored.
56
+ */
51
57
  const COMMANDS = {
52
- status: { args: "[--json]", desc: "show login / workspace / agent state" },
58
+ status: {
59
+ args: "[--json]",
60
+ flags: ["--json"],
61
+ desc: "show login / workspace / agent state",
62
+ eg: "figs status --json",
63
+ },
53
64
  login: {
54
65
  args: "[<token>]",
66
+ flags: [],
55
67
  desc: "log in — browser device-flow, or save a pasted token",
56
68
  more: [
57
69
  "no arg → device flow: a human approves in a browser (you never see the token).",
58
70
  "<token> → save a token you already have to ~/.figs/credentials.json.",
59
71
  ],
72
+ eg: "figs login",
73
+ },
74
+ logout: { args: "", flags: [], desc: "remove the locally-saved token (~/.figs/credentials.json)" },
75
+ workspaces: {
76
+ args: "[--json]",
77
+ flags: ["--json"],
78
+ desc: "list your workspaces (read-only; shows the slug)",
79
+ eg: "figs workspaces",
60
80
  },
61
- logout: { args: "", desc: "remove the locally-saved token (~/.figs/credentials.json)" },
62
- workspaces: { args: "[--json]", desc: "list your workspaces (read-only; shows the slug)" },
63
81
  init: {
64
82
  args: "--workspace <slug-or-id> [--endpoint <url>]",
83
+ flags: ["--workspace", "--endpoint"],
65
84
  desc: "set up .figs/ here (identity UUID + config + pointer GUIDE.md)",
66
85
  more: [
67
86
  "--workspace takes a slug (resolved to its UUID) or a raw UUID — get it from `figs workspaces`.",
68
87
  ],
88
+ eg: "figs init --workspace acme-corp",
69
89
  },
70
- doctor: { args: "", desc: "validate .figs/ against the live contract before pushing" },
90
+ doctor: { args: "", flags: ["--json"], desc: "validate .figs/ against the live contract before pushing" },
71
91
  push: {
72
92
  args: "",
93
+ flags: [],
73
94
  desc: "publish .figs/ — spine to /api/ingest, artifacts to /api/artifacts",
74
95
  more: ["Idempotent (records fold by id). Exits non-zero if an artifact upload is rejected."],
96
+ eg: "figs push",
75
97
  },
76
- version: { args: "", desc: "print the CLI version and check for updates" },
77
- help: { args: "[<command>]", desc: "show this help, or detailed help for one command" },
98
+ version: { args: "", flags: [], desc: "print the CLI version and check for updates" },
99
+ help: { args: "[<command>]", flags: [], desc: "show this help, or detailed help for one command" },
100
+ }
101
+
102
+ /** Reject unknown flags for a command (don't silently ignore an agent's typo). */
103
+ function checkFlags(name) {
104
+ const allowed = new Set([...(COMMANDS[name].flags ?? []), "-h", "--help"])
105
+ for (const tok of process.argv.slice(3)) {
106
+ if (tok.startsWith("-") && tok !== "-" && tok !== "--") {
107
+ const f = tok.split("=")[0]
108
+ if (!allowed.has(f)) {
109
+ die(`unknown flag "${f}" for \`figs ${name}\` — run \`figs ${name} --help\``)
110
+ }
111
+ }
112
+ }
78
113
  }
79
114
 
80
115
  function die(msg) {
@@ -84,9 +119,14 @@ function die(msg) {
84
119
  function readJson(path, fallback) {
85
120
  return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : fallback
86
121
  }
122
+ /** Read a flag value — supports both `--name value` and `--name=value`. */
87
123
  function flag(name) {
88
- const i = process.argv.indexOf(name)
89
- return i >= 0 ? process.argv[i + 1] : undefined
124
+ const args = process.argv.slice(2)
125
+ for (let i = 0; i < args.length; i++) {
126
+ if (args[i] === name) return args[i + 1]
127
+ if (args[i].startsWith(`${name}=`)) return args[i].slice(name.length + 1)
128
+ }
129
+ return undefined
90
130
  }
91
131
  function getToken() {
92
132
  return process.env.FIGS_TOKEN || readJson(globalCreds, {}).token
@@ -98,12 +138,28 @@ function resolveEndpoint() {
98
138
  "",
99
139
  )
100
140
  }
141
+ const REQUEST_TIMEOUT_MS = 30000
142
+ /** `fetch` with a hard timeout so a hung server never stalls the agent. */
143
+ async function fetchT(url, opts = {}) {
144
+ const ctrl = new AbortController()
145
+ const t = setTimeout(() => ctrl.abort(), REQUEST_TIMEOUT_MS)
146
+ try {
147
+ return await fetch(url, { ...opts, signal: ctrl.signal })
148
+ } finally {
149
+ clearTimeout(t)
150
+ }
151
+ }
152
+ /** Human reason for a thrown fetch error (timeout vs. network). */
153
+ function netReason(e) {
154
+ if (e?.name === "AbortError") return `timed out after ${REQUEST_TIMEOUT_MS / 1000}s`
155
+ return e?.cause?.code || e?.code || e?.message || "network error"
156
+ }
101
157
  /** Low-level request — returns { ok, status, data }, never throws/exits. */
102
158
  async function request(method, path, body, token = getToken()) {
103
159
  const base = resolveEndpoint()
104
160
  let res
105
161
  try {
106
- res = await fetch(`${base}${path}`, {
162
+ res = await fetchT(`${base}${path}`, {
107
163
  method,
108
164
  headers: {
109
165
  "content-type": "application/json",
@@ -112,12 +168,8 @@ async function request(method, path, body, token = getToken()) {
112
168
  body: body ? JSON.stringify(body) : undefined,
113
169
  })
114
170
  } catch (e) {
115
- // Network error (unreachable host, DNS, timeout) — degrade, don't crash.
116
- return {
117
- ok: false,
118
- status: 0,
119
- data: { error: `cannot reach ${base} (${e?.cause?.code || e?.code || e?.message || "network error"})` },
120
- }
171
+ // Unreachable host / DNS / timeout — degrade, don't crash.
172
+ return { ok: false, status: 0, data: { error: `cannot reach ${base} (${netReason(e)})` } }
121
173
  }
122
174
  const text = await res.text()
123
175
  let data
@@ -136,12 +188,20 @@ async function api(method, path, body) {
136
188
  return r.data
137
189
  }
138
190
 
191
+ /**
192
+ * Compare two semver strings → -1 | 0 | 1, or **null** if either is unparseable.
193
+ * Returning null (rather than guessing) lets the caller skip the check instead of
194
+ * failing closed on a malformed server-provided version — a bad `min` must never
195
+ * lock an agent out of pushing.
196
+ */
139
197
  function cmpSemver(a, b) {
140
- const pa = String(a).split(".").map(Number)
141
- const pb = String(b).split(".").map(Number)
198
+ const pa = String(a).split(".").map((n) => parseInt(n, 10))
199
+ const pb = String(b).split(".").map((n) => parseInt(n, 10))
142
200
  for (let i = 0; i < 3; i++) {
143
- const d = (pa[i] || 0) - (pb[i] || 0)
144
- if (d) return d < 0 ? -1 : 1
201
+ const x = pa[i] ?? 0
202
+ const y = pb[i] ?? 0
203
+ if (Number.isNaN(x) || Number.isNaN(y)) return null
204
+ if (x !== y) return x < y ? -1 : 1
145
205
  }
146
206
  return 0
147
207
  }
@@ -168,11 +228,12 @@ async function checkVersion({ force = false, hardFail = false } = {}) {
168
228
  }
169
229
  const min = info?.cli?.min
170
230
  const latest = info?.cli?.latest
171
- if (min && cmpSemver(VERSION, min) < 0) {
231
+ // cmpSemver returns null on an unparseable version → skip (never fail closed).
232
+ if (min && cmpSemver(VERSION, min) === -1) {
172
233
  const msg = `figs CLI ${VERSION} is below the minimum ${min} — upgrade: npx @figs-so/cli@latest`
173
234
  if (hardFail) die(msg)
174
235
  console.warn(`figs: ! ${msg}`)
175
- } else if (latest && cmpSemver(VERSION, latest) < 0) {
236
+ } else if (latest && cmpSemver(VERSION, latest) === -1) {
176
237
  console.warn(`figs: a newer CLI is available (${latest}) — npx @figs-so/cli@latest`)
177
238
  }
178
239
  }
@@ -189,6 +250,7 @@ function printHelp(name) {
189
250
  console.log(`Usage: figs ${name}${c.args ? " " + c.args : ""}\n`)
190
251
  console.log(` ${c.desc}`)
191
252
  if (c.more) for (const line of c.more) console.log(` ${line}`)
253
+ if (c.eg) console.log(`\n e.g. ${c.eg}`)
192
254
  return
193
255
  }
194
256
  console.log("figs — publish your AI agent's state to Figs (https://figs.so)\n")
@@ -212,14 +274,16 @@ else if (cmd === "version" || cmd === "--version" || cmd === "-v" || cmd === "-V
212
274
  console.log(VERSION)
213
275
  await checkVersion({ force: true })
214
276
  } else if (WANTS_HELP) printHelp(cmd)
215
- else if (cmd === "login") await login(process.argv[3])
216
- else if (cmd === "logout") logout()
217
- else if (cmd === "status") await status()
218
- else if (cmd === "workspaces") await workspaces()
219
- else if (cmd === "init") await init()
220
- else if (cmd === "doctor") await doctor()
221
- else if (cmd === "push") await push()
222
- else {
277
+ else if (COMMANDS[cmd]) {
278
+ checkFlags(cmd) // reject unknown flags before running
279
+ if (cmd === "login") await login(process.argv[3])
280
+ else if (cmd === "logout") logout()
281
+ else if (cmd === "status") await status()
282
+ else if (cmd === "workspaces") await workspaces()
283
+ else if (cmd === "init") await init()
284
+ else if (cmd === "doctor") await doctor()
285
+ else if (cmd === "push") await push()
286
+ } else {
223
287
  console.error(`figs: unknown command "${cmd}" — run \`figs help\` for usage`)
224
288
  process.exit(1)
225
289
  }
@@ -532,11 +596,16 @@ async function push() {
532
596
  const asks = foldById(readJsonl("asks.jsonl"))
533
597
 
534
598
  const base = endpoint.replace(/\/+$/, "")
535
- const res = await fetch(`${base}/api/ingest`, {
536
- method: "POST",
537
- headers: { "content-type": "application/json", "x-figs-token": token },
538
- body: JSON.stringify({ workspaceId: config.workspaceId, agent, runs, asks }),
539
- })
599
+ let res
600
+ try {
601
+ res = await fetchT(`${base}/api/ingest`, {
602
+ method: "POST",
603
+ headers: { "content-type": "application/json", "x-figs-token": token },
604
+ body: JSON.stringify({ workspaceId: config.workspaceId, agent, runs, asks }),
605
+ })
606
+ } catch (e) {
607
+ die(`push failed — cannot reach ${base} (${netReason(e)})`)
608
+ }
540
609
  const text = await res.text()
541
610
  if (!res.ok) die(`push failed (${res.status}): ${text}`)
542
611
  console.log(
@@ -577,16 +646,23 @@ async function pushArtifacts(base, token, config, runs, asks) {
577
646
  continue
578
647
  }
579
648
  const content = readFileSync(p).toString("base64")
580
- const res = await fetch(`${base}/api/artifacts/upload`, {
581
- method: "POST",
582
- headers: { "content-type": "application/json", "x-figs-token": token },
583
- body: JSON.stringify({
584
- workspaceId: config.workspaceId,
585
- agentId: config.agentId,
586
- name,
587
- content,
588
- }),
589
- })
649
+ let res
650
+ try {
651
+ res = await fetchT(`${base}/api/artifacts/upload`, {
652
+ method: "POST",
653
+ headers: { "content-type": "application/json", "x-figs-token": token },
654
+ body: JSON.stringify({
655
+ workspaceId: config.workspaceId,
656
+ agentId: config.agentId,
657
+ name,
658
+ content,
659
+ }),
660
+ })
661
+ } catch (e) {
662
+ console.error(`figs: ✗ artifact upload failed ${name}: ${netReason(e)}`)
663
+ failed++
664
+ continue
665
+ }
590
666
  if (!res.ok) {
591
667
  const t = await res.text().catch(() => "")
592
668
  const hint =
@@ -614,10 +690,19 @@ async function pushArtifacts(base, token, config, runs, asks) {
614
690
  function readJsonl(name) {
615
691
  const p = join(repoDir, name)
616
692
  if (!existsSync(p)) return []
617
- return readFileSync(p, "utf8")
693
+ const out = []
694
+ readFileSync(p, "utf8")
618
695
  .split("\n")
619
- .filter((l) => l.trim())
620
- .map((l) => JSON.parse(l))
696
+ .forEach((line, i) => {
697
+ const s = line.trim()
698
+ if (!s) return
699
+ try {
700
+ out.push(JSON.parse(s))
701
+ } catch {
702
+ die(`malformed JSON in .figs/${name} line ${i + 1}: ${s.slice(0, 80)}`)
703
+ }
704
+ })
705
+ return out
621
706
  }
622
707
 
623
708
  /** Fold append-only records by id — latest line wins. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@figs-so/cli",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Figs CLI — publish your AI agent's state to Figs (figs.so). Run by the agent.",
5
5
  "type": "module",
6
6
  "bin": {