@journoid/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Journoid contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # Journoid CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use your terminal or an agent to read and change your Journoid data.
4
+ Requires Node.js 22.14 or later.
5
+
6
+ ```sh
7
+ pnpm add -g @journoid/cli
8
+ journoid login
9
+ journoid blocks
10
+ journoid actions
11
+ journoid actions create-todo
12
+ journoid call create-todo --input '{"title":"Try Journoid from my terminal"}'
13
+ ```
14
+
15
+ Data commands return JSON. `--json` is accepted for agent scripts. Discover an
16
+ action's exact schema before calling it. Custom block schemas come from `blocks`.
17
+ Use `--input-file path.json`, or `--input-file -` to read JSON from stdin.
18
+
19
+ Full access includes permanent deletion. The connected agent supplies its own
20
+ reasoning; ordinary data operations make no extra model request. If a write loses
21
+ its response, inspect saved data before retrying. Writes are not automatically
22
+ retried after network failures.
23
+
24
+ Credentials stay in a private file under your user configuration directory.
25
+ Use `journoid logout` to revoke the CLI session. Settings > Your agents can
26
+ disconnect access immediately, or allow access again after disconnecting.
27
+ Expired sessions refresh automatically when possible; otherwise run `login`.
28
+
29
+ For remote MCP clients, use `https://journoid.app/mcp` with OAuth instead of
30
+ installing the CLI. Settings provides setup commands for supported clients.
31
+
32
+ For an isolated local backend, use `--url http://localhost:<app-port>` on each
33
+ command. Credentials are kept separately for each server origin.
@@ -0,0 +1,449 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ readFile,
4
+ writeFile,
5
+ mkdir,
6
+ rename,
7
+ chmod,
8
+ unlink,
9
+ realpath,
10
+ } from 'node:fs/promises'
11
+ import { homedir } from 'node:os'
12
+ import { join, dirname } from 'node:path'
13
+ import { randomUUID } from 'node:crypto'
14
+ import { spawn } from 'node:child_process'
15
+ import { pathToFileURL } from 'node:url'
16
+ import lockfile from 'proper-lockfile'
17
+
18
+ function secureUrl(value) {
19
+ const url = new URL(value)
20
+ if (
21
+ url.protocol !== 'https:' &&
22
+ !(
23
+ url.protocol === 'http:' &&
24
+ ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
25
+ )
26
+ )
27
+ throw new Error('Use HTTPS, or a loopback URL for local development.')
28
+ if (url.username || url.password)
29
+ throw new Error('URLs must not contain credentials.')
30
+ return url
31
+ }
32
+
33
+ export class JournoidClient {
34
+ constructor({
35
+ origin = process.env.JOURNOID_URL || 'https://journoid.app',
36
+ file,
37
+ fetcher = fetch,
38
+ now = Date.now,
39
+ wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
40
+ } = {}) {
41
+ this.origin = secureUrl(origin).origin
42
+ this.file =
43
+ file ??
44
+ join(
45
+ process.env.XDG_CONFIG_HOME || join(homedir(), '.config'),
46
+ 'journoid',
47
+ 'credentials.json'
48
+ )
49
+ this.fetcher = fetcher
50
+ this.now = now
51
+ this.wait = wait
52
+ }
53
+
54
+ async readStore() {
55
+ try {
56
+ const value = JSON.parse(await readFile(this.file, 'utf8'))
57
+ if (!value || typeof value !== 'object' || Array.isArray(value))
58
+ throw new Error('Invalid credentials file. Run journoid login again.')
59
+ return value
60
+ } catch (error) {
61
+ if (error.code === 'ENOENT') return {}
62
+ throw error
63
+ }
64
+ }
65
+
66
+ async save(account, options = {}) {
67
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 })
68
+ await chmod(dirname(this.file), 0o700)
69
+ // Rename keeps readers safe; the lock also serializes read-check-write
70
+ // transactions across CLI processes, including different server origins.
71
+ const release = await lockfile.lock(this.file, {
72
+ realpath: false,
73
+ retries: { retries: 30, minTimeout: 25, maxTimeout: 500 },
74
+ })
75
+ try {
76
+ const store = await this.readStore()
77
+ if (
78
+ Object.hasOwn(options, 'expected') &&
79
+ JSON.stringify(store[this.origin]) !== JSON.stringify(options.expected)
80
+ )
81
+ throw new Error('Your CLI session changed. Run the command again.')
82
+ if (account) store[this.origin] = account
83
+ else delete store[this.origin]
84
+ const temporary = `${this.file}.${randomUUID()}.tmp`
85
+ try {
86
+ await writeFile(temporary, JSON.stringify(store), {
87
+ flag: 'wx',
88
+ mode: 0o600,
89
+ })
90
+ await rename(temporary, this.file)
91
+ } finally {
92
+ await unlink(temporary).catch((error) => {
93
+ if (error.code !== 'ENOENT') throw error
94
+ })
95
+ }
96
+ } finally {
97
+ await release()
98
+ }
99
+ }
100
+
101
+ async json(url, options = {}, { ignoreBody = false } = {}) {
102
+ const response = await this.fetcher(secureUrl(url), {
103
+ ...options,
104
+ redirect: 'error',
105
+ signal: AbortSignal.timeout(30_000),
106
+ })
107
+ // Revocation is status-only. Data and token responses must be readable JSON.
108
+ if (ignoreBody) {
109
+ if (response.body) await response.body.cancel().catch(() => {})
110
+ return { response }
111
+ }
112
+ const value = await response.json()
113
+ return { response, value }
114
+ }
115
+
116
+ async discover() {
117
+ const { response, value } = await this.json(
118
+ `${this.origin}/.well-known/journoid`
119
+ )
120
+ if (
121
+ !response.ok ||
122
+ !value.configured ||
123
+ typeof value.clientId !== 'string' ||
124
+ !value.clientId ||
125
+ typeof value.authorizationServer !== 'string' ||
126
+ value.resource !== `${this.origin}/mcp` ||
127
+ !Array.isArray(value.scopes) ||
128
+ !value.scopes.every((scope) => typeof scope === 'string') ||
129
+ !value.scopes.includes('journoid:full')
130
+ )
131
+ throw new Error(
132
+ 'CLI sign-in is not configured on this Journoid server yet.'
133
+ )
134
+ const issuer = secureUrl(value.authorizationServer).origin
135
+ const metadata = await this.json(
136
+ `${issuer}/.well-known/oauth-authorization-server`
137
+ )
138
+ if (
139
+ !metadata.response.ok ||
140
+ metadata.value.issuer !== issuer ||
141
+ !metadata.value.device_authorization_endpoint ||
142
+ !metadata.value.token_endpoint ||
143
+ !metadata.value.revocation_endpoint
144
+ )
145
+ throw new Error('This server does not support device sign-in.')
146
+ const endpoints = metadata.value
147
+ for (const key of [
148
+ 'device_authorization_endpoint',
149
+ 'token_endpoint',
150
+ 'revocation_endpoint',
151
+ ]) {
152
+ if (endpoints[key] && secureUrl(endpoints[key]).origin !== issuer)
153
+ throw new Error(
154
+ 'The authorization server returned an unexpected endpoint.'
155
+ )
156
+ }
157
+ return {
158
+ clientId: value.clientId,
159
+ issuer,
160
+ endpoints,
161
+ scopes: value.scopes,
162
+ resource: value.resource,
163
+ }
164
+ }
165
+
166
+ async form(url, values, options) {
167
+ return this.json(
168
+ url,
169
+ {
170
+ method: 'POST',
171
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
172
+ body: new URLSearchParams(values),
173
+ },
174
+ options
175
+ )
176
+ }
177
+
178
+ accountFromTokens(tokens, config, previous) {
179
+ if (
180
+ typeof tokens.access_token !== 'string' ||
181
+ !Number.isFinite(tokens.expires_in) ||
182
+ tokens.expires_in <= 0
183
+ )
184
+ throw new Error('The sign-in server returned an invalid token response.')
185
+ return {
186
+ accessToken: tokens.access_token,
187
+ refreshToken: tokens.refresh_token ?? previous?.refreshToken,
188
+ expiresAt: this.now() + tokens.expires_in * 1000,
189
+ clientId: config.clientId,
190
+ tokenEndpoint: config.endpoints.token_endpoint,
191
+ revocationEndpoint: config.endpoints.revocation_endpoint,
192
+ resource: config.resource ?? previous?.resource,
193
+ }
194
+ }
195
+
196
+ async login(onDevice) {
197
+ const config = await this.discover()
198
+ const { response, value } = await this.form(
199
+ config.endpoints.device_authorization_endpoint,
200
+ {
201
+ client_id: config.clientId,
202
+ scope: config.scopes.join(' '),
203
+ ...(config.resource ? { resource: config.resource } : {}),
204
+ }
205
+ )
206
+ if (
207
+ !response.ok ||
208
+ typeof value.device_code !== 'string' ||
209
+ typeof value.user_code !== 'string' ||
210
+ !Number.isFinite(value.expires_in) ||
211
+ value.expires_in <= 0
212
+ )
213
+ throw new Error('Could not start sign-in. Try again.')
214
+ const verificationUrl = secureUrl(
215
+ value.verification_uri_complete || value.verification_uri
216
+ ).href
217
+ onDevice({ url: verificationUrl, code: value.user_code })
218
+ const expires = this.now() + value.expires_in * 1000
219
+ let interval = Math.max(5, Number(value.interval) || 5) * 1000
220
+ while (this.now() < expires) {
221
+ await this.wait(Math.min(interval, expires - this.now()))
222
+ if (this.now() >= expires) break
223
+ const token = await this.form(config.endpoints.token_endpoint, {
224
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
225
+ client_id: config.clientId,
226
+ device_code: value.device_code,
227
+ ...(config.resource ? { resource: config.resource } : {}),
228
+ })
229
+ if (token.response.ok && token.value.access_token) {
230
+ await this.save(this.accountFromTokens(token.value, config))
231
+ // Verify scope, audience, and connection access before reporting success.
232
+ // A device token without an audience gets one resource-bound refresh.
233
+ return this.request('GET')
234
+ }
235
+ if (token.value.error === 'authorization_pending') continue
236
+ if (token.value.error === 'slow_down') {
237
+ interval += 5000
238
+ continue
239
+ }
240
+ if (token.value.error === 'access_denied')
241
+ throw new Error('Sign-in was declined.')
242
+ if (token.value.error === 'expired_token') break
243
+ throw new Error('Sign-in failed. Run journoid login again.')
244
+ }
245
+ throw new Error('The sign-in code expired. Run journoid login again.')
246
+ }
247
+
248
+ async refresh(account) {
249
+ if (!account.refreshToken)
250
+ throw new Error('Sign in again with journoid login.')
251
+ const { response, value } = await this.form(account.tokenEndpoint, {
252
+ grant_type: 'refresh_token',
253
+ client_id: account.clientId,
254
+ refresh_token: account.refreshToken,
255
+ ...(account.resource ? { resource: account.resource } : {}),
256
+ })
257
+ if (!response.ok)
258
+ throw new Error('Your session expired. Run journoid login again.')
259
+ const updated = this.accountFromTokens(
260
+ value,
261
+ {
262
+ clientId: account.clientId,
263
+ endpoints: {
264
+ token_endpoint: account.tokenEndpoint,
265
+ revocation_endpoint: account.revocationEndpoint,
266
+ },
267
+ },
268
+ account
269
+ )
270
+ await this.save(updated, { expected: account })
271
+ return updated
272
+ }
273
+
274
+ async request(method, { view, body } = {}) {
275
+ let account = (await this.readStore())[this.origin]
276
+ if (!account?.accessToken)
277
+ throw new Error('Sign in first with journoid login.')
278
+ if (account.expiresAt <= this.now() + 30_000)
279
+ account = await this.refresh(account)
280
+ const url = new URL('/api/agents', this.origin)
281
+ if (view) url.searchParams.set('view', view)
282
+ const send = async () => {
283
+ try {
284
+ return await this.json(url, {
285
+ method,
286
+ headers: {
287
+ Authorization: `Bearer ${account.accessToken}`,
288
+ 'Content-Type': 'application/json',
289
+ },
290
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
291
+ })
292
+ } catch {
293
+ throw new Error(
294
+ method === 'POST'
295
+ ? 'Connection lost. Check Journoid before retrying this change; it may have completed.'
296
+ : 'Could not reach Journoid. Try again.'
297
+ )
298
+ }
299
+ }
300
+ let result = await send()
301
+ if (result.response.status === 401) {
302
+ account = await this.refresh(account)
303
+ result = await send()
304
+ }
305
+ if (!result.response.ok)
306
+ throw new Error(
307
+ typeof result.value.error === 'string'
308
+ ? result.value.error
309
+ : `Journoid returned ${result.response.status}.`
310
+ )
311
+ return result.value
312
+ }
313
+
314
+ async logout() {
315
+ const account = (await this.readStore())[this.origin]
316
+ if (account?.refreshToken) {
317
+ if (!account.revocationEndpoint)
318
+ throw new Error(
319
+ 'Disconnect the CLI in Journoid Settings before removing these credentials.'
320
+ )
321
+ const { response } = await this.form(
322
+ account.revocationEndpoint,
323
+ {
324
+ token: account.refreshToken,
325
+ token_type_hint: 'refresh_token',
326
+ client_id: account.clientId,
327
+ },
328
+ { ignoreBody: true }
329
+ )
330
+ if (!response.ok)
331
+ throw new Error(
332
+ 'Could not revoke the session. Try again, or disconnect the CLI in Journoid Settings.'
333
+ )
334
+ }
335
+ await this.save(undefined, { expected: account })
336
+ }
337
+ }
338
+
339
+ const help = `Journoid CLI
340
+
341
+ journoid login [--no-browser]
342
+ journoid status
343
+ journoid blocks
344
+ journoid actions [action]
345
+ journoid call <action> --input '<JSON>'
346
+ journoid call <action> --input-file <path|->
347
+ journoid logout
348
+
349
+ Data commands print JSON. --json is accepted for agent scripts.
350
+ Use --url <origin> to select another server. Full access includes deletion.
351
+ Writes are not automatically retried after a lost response.
352
+ `
353
+
354
+ export async function main(args = process.argv.slice(2)) {
355
+ const take = (flag) => {
356
+ const index = args.indexOf(flag)
357
+ if (index < 0) return undefined
358
+ const value = args[index + 1]
359
+ if (!value || value.startsWith('--'))
360
+ throw new Error(`Missing value for ${flag}.`)
361
+ args.splice(index, 2)
362
+ return value
363
+ }
364
+ const origin = take('--url')
365
+ const inputText = take('--input')
366
+ const inputFile = take('--input-file')
367
+ const noBrowser = args.includes('--no-browser')
368
+ args = args.filter((arg) => !['--json', '--no-browser'].includes(arg))
369
+ const [command, action, ...rest] = args
370
+ if (!command || ['help', '--help', '-h'].includes(command)) {
371
+ console.log(help)
372
+ return
373
+ }
374
+ if (
375
+ rest.length ||
376
+ args.some((arg) => arg.startsWith('--')) ||
377
+ (action !== undefined && !['actions', 'call'].includes(command)) ||
378
+ (noBrowser && command !== 'login') ||
379
+ ((inputText !== undefined || inputFile !== undefined) && command !== 'call')
380
+ )
381
+ throw new Error('Unknown argument. Run journoid --help.')
382
+ const client = new JournoidClient({ origin })
383
+ let result
384
+ if (command === 'login') {
385
+ result = await client.login(({ url, code }) => {
386
+ console.error(`Open ${url}\nYour code: ${code}`)
387
+ if (!noBrowser) {
388
+ const program =
389
+ process.platform === 'darwin'
390
+ ? 'open'
391
+ : process.platform === 'win32'
392
+ ? 'rundll32'
393
+ : 'xdg-open'
394
+ const browserArgs =
395
+ process.platform === 'win32'
396
+ ? ['url.dll,FileProtocolHandler', url]
397
+ : [url]
398
+ const browser = spawn(program, browserArgs, { stdio: 'ignore' })
399
+ browser.on('error', () => {})
400
+ browser.unref()
401
+ }
402
+ })
403
+ } else if (command === 'logout') {
404
+ await client.logout()
405
+ result = { signedOut: true }
406
+ } else if (command === 'status') result = await client.request('GET')
407
+ else if (command === 'blocks')
408
+ result = await client.request('GET', { view: 'blocks' })
409
+ else if (command === 'actions') {
410
+ const actions = await client.request('GET', { view: 'actions' })
411
+ result = action ? actions.find((item) => item.name === action) : actions
412
+ if (!result) throw new Error('Unknown action. Run journoid actions.')
413
+ } else if (command === 'call') {
414
+ if (!action) throw new Error('Choose an action. Run journoid actions.')
415
+ if (inputText !== undefined && inputFile !== undefined)
416
+ throw new Error('Choose --input or --input-file.')
417
+ let text = inputText ?? '{}'
418
+ if (inputFile === '-') {
419
+ const chunks = []
420
+ let size = 0
421
+ for await (const chunk of process.stdin) {
422
+ size += Buffer.byteLength(chunk)
423
+ if (size > 60_000) throw new Error('Action input is too large.')
424
+ chunks.push(Buffer.from(chunk))
425
+ }
426
+ text = Buffer.concat(chunks).toString('utf8')
427
+ } else if (inputFile !== undefined) text = await readFile(inputFile, 'utf8')
428
+ if (Buffer.byteLength(text) > 60_000)
429
+ throw new Error('Action input is too large.')
430
+ const input = JSON.parse(text)
431
+ if (!input || typeof input !== 'object' || Array.isArray(input))
432
+ throw new Error('Input must be a JSON object.')
433
+ result = await client.request('POST', { body: { action, input } })
434
+ } else throw new Error('Unknown command. Run journoid --help.')
435
+ console.log(JSON.stringify(result, null, 2))
436
+ if (result && typeof result === 'object' && result.success === false)
437
+ process.exitCode = 1
438
+ }
439
+
440
+ // npm exposes the executable through a symlink on Unix.
441
+ const entryFile = process.argv[1]
442
+ ? await realpath(process.argv[1]).catch(() => undefined)
443
+ : undefined
444
+ if (entryFile && import.meta.url === pathToFileURL(entryFile).href) {
445
+ main().catch((error) => {
446
+ console.error(error.message)
447
+ process.exitCode = 1
448
+ })
449
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@journoid/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Connect your agents and terminal to Journoid",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=22.14.0"
9
+ },
10
+ "bin": {
11
+ "journoid": "./bin/journoid.mjs"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/expl0r3rgu1/journoid.git",
24
+ "directory": "packages/cli"
25
+ },
26
+ "homepage": "https://journoid.app",
27
+ "dependencies": {
28
+ "proper-lockfile": "4.1.2"
29
+ },
30
+ "scripts": {
31
+ "test": "node --test test/*.test.mjs"
32
+ }
6
33
  }