dsh-hive-panel 0.1.6 → 0.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.
package/lib/index.js CHANGED
@@ -67,6 +67,61 @@ export const DEFAULT_BINS = Object.freeze({
67
67
  moc: 'moc',
68
68
  })
69
69
 
70
+ /**
71
+ * npm packages that publish the executable behind each default bin. When a
72
+ * default PATH name is not resolvable in the shell that runs the command, the
73
+ * host retries once through `npx -y -p <package> ... <bin>` before reporting an
74
+ * actionable error. `hive` is the umbrella router, so the whole toolchain is
75
+ * installed into the npx cache and the router can resolve its cores.
76
+ */
77
+ export const BIN_PACKAGES = Object.freeze({
78
+ hive: Object.freeze(['@d86e/hive', 'hive-consensus', 'hive-tasks', 'hive-runner', 'merge-on-commit']),
79
+ tasks: Object.freeze(['hive-tasks']),
80
+ run: Object.freeze(['hive-runner']),
81
+ moc: Object.freeze(['merge-on-commit']),
82
+ })
83
+
84
+ /** The executable name inside each npx package set (the package's declared bin). */
85
+ const BIN_EXECUTABLES = Object.freeze({
86
+ hive: 'hive',
87
+ tasks: 'hive-tasks',
88
+ run: 'hive-run',
89
+ moc: 'moc',
90
+ })
91
+
92
+ /**
93
+ * Build the `npx` argv that runs one bin from its published package(s).
94
+ * @param {string} key - one of the DEFAULT_BINS keys.
95
+ * @param {string[]} [argv] - arguments for the bin, always appended after its name.
96
+ * @returns {string[] | null}
97
+ */
98
+ export function npxInvocation(key, argv = []) {
99
+ const packages = BIN_PACKAGES[key]
100
+ const executable = BIN_EXECUTABLES[key]
101
+ if (packages === undefined || executable === undefined) return null
102
+ const tokens = ['-y']
103
+ for (const name of packages) tokens.push('-p', name)
104
+ tokens.push(executable, ...argv.map(token => String(token)))
105
+ return tokens
106
+ }
107
+
108
+ /**
109
+ * The npx fallback command for one configured bin. A configured absolute (or
110
+ * relative) path is the operator's explicit choice and is never replaced; only
111
+ * the default PATH name gets the package fallback.
112
+ * @param {string} key - one of the DEFAULT_BINS keys.
113
+ * @param {string[]} [argv] - arguments for the executable.
114
+ * @param {object} [bins] - trusted executable overrides.
115
+ * @returns {string | null}
116
+ */
117
+ export function fallbackCommandForBin(key, argv = [], bins = DEFAULT_BINS) {
118
+ const executable = bins[key]
119
+ if (typeof executable !== 'string' || executable === '') return null
120
+ if (executable.includes('/') || executable.includes('\\')) return null
121
+ const tokens = npxInvocation(key, argv)
122
+ return tokens === null ? null : buildCommand('npx', tokens)
123
+ }
124
+
70
125
  /** Read-only commands emitted for one snapshot (all fixed; no browser input). */
71
126
  export const SNAPSHOT_COMMANDS = Object.freeze({
72
127
  board: ['board', '--json'],
@@ -102,6 +157,13 @@ export const ROLE_MODEL_RE = /^[A-Za-z0-9._:-]{1,64}$/
102
157
  const ROLE_LIMITS_FILE = path.join('.hive', 'limits.json')
103
158
  const ROLE_LIMIT_MAX = 999
104
159
 
160
+ /** Last-run records written by hive-runner: one file per card id. */
161
+ export const RUNS_DIR = path.join('.hive', 'runs')
162
+ /** Defensive read cap; hive-runner already truncates to this size. */
163
+ const MAX_RUN_OUTPUT_BYTES = 32 * 1024
164
+ /** Record statuses the panel understands. */
165
+ const RUN_STATUSES = Object.freeze(['done', 'failed', 'running'])
166
+
105
167
  /** One typed failure with the HTTP status and JSON code returned to the browser. */
106
168
  export class HiveRequestError extends Error {
107
169
  /**
@@ -176,6 +238,14 @@ export function parseJson(text, fallback) {
176
238
  }
177
239
  }
178
240
 
241
+ /** The bin key behind each snapshot command. */
242
+ export const SNAPSHOT_BINS = Object.freeze({
243
+ board: 'hive',
244
+ tasks: 'tasks',
245
+ stats: 'tasks',
246
+ roles: 'hive',
247
+ })
248
+
179
249
  /** The read-only commands one snapshot fans out to (fixed argv, validated bins). */
180
250
  export function snapshotCliCommands(bins = DEFAULT_BINS) {
181
251
  return {
@@ -186,6 +256,46 @@ export function snapshotCliCommands(bins = DEFAULT_BINS) {
186
256
  }
187
257
  }
188
258
 
259
+ /** npx fallback command per snapshot read; null for an explicit absolute bin. */
260
+ export function snapshotFallbackCommands(bins = DEFAULT_BINS) {
261
+ return {
262
+ board: fallbackCommandForBin('hive', SNAPSHOT_COMMANDS.board, bins),
263
+ tasks: fallbackCommandForBin('tasks', SNAPSHOT_COMMANDS.tasks, bins),
264
+ stats: fallbackCommandForBin('tasks', SNAPSHOT_COMMANDS.stats, bins),
265
+ roles: fallbackCommandForBin('hive', SNAPSHOT_COMMANDS.roles, bins),
266
+ }
267
+ }
268
+
269
+ /** Bash exit status for "command not found". */
270
+ const COMMAND_NOT_FOUND = 127
271
+
272
+ /**
273
+ * True when a shell result means the executable itself was missing (not when a
274
+ * CLI ran and reported its own failure). bash/yash/zsh all use 127 for this, and
275
+ * some sandbox wrappers only leave the message.
276
+ * @param {object|undefined} result - ctx.shell execute result.
277
+ * @returns {boolean}
278
+ */
279
+ export function missingBinary(result) {
280
+ if (result === undefined || result === null) return false
281
+ if (result.exitCode === COMMAND_NOT_FOUND) return true
282
+ const stderr = String(result.stderr?.text ?? '')
283
+ return /command not found|: not found|No such file or directory/i.test(stderr)
284
+ }
285
+
286
+ /**
287
+ * Append an actionable line to a failed shell result, keeping the CLI output.
288
+ * @param {object} result - ctx.shell execute result.
289
+ * @param {string} line - diagnostic appended to stderr.
290
+ * @returns {object} a shallow copy with stderr.text extended.
291
+ */
292
+ export function appendStderr(result, line) {
293
+ const stderr = result.stderr ?? {}
294
+ const text = String(stderr.text ?? '')
295
+ const joined = text === '' ? line : text.replace(/\s+$/, '') + '\n' + line
296
+ return { ...result, stderr: { ...stderr, text: joined } }
297
+ }
298
+
189
299
  /**
190
300
  * Normalize `hive roles list --json` rows into the snapshot contract.
191
301
  * Unknown/malformed rows are dropped; adapter/model/prompt are nullable.
@@ -249,6 +359,83 @@ export function readRoleLimits(cwd) {
249
359
  return { limits, error: null }
250
360
  }
251
361
 
362
+ /**
363
+ * Resolve one last-run record path, validating the id and containment.
364
+ * The card id is never trusted: anything that is not a single safe token
365
+ * (separators, dots-only ids) resolves to null before touching the filesystem.
366
+ * @param {string} cwd - repository root.
367
+ * @param {unknown} cardId - card id from the task list.
368
+ * @returns {string|null}
369
+ */
370
+ export function lastRunPath(cwd, cardId) {
371
+ if (typeof cwd !== 'string' || cwd === '') return null
372
+ if (typeof cardId !== 'string' || !ID_RE.test(cardId)) return null
373
+ const dir = path.resolve(cwd, RUNS_DIR)
374
+ const file = path.resolve(dir, cardId + '.json')
375
+ if (!file.startsWith(dir + path.sep)) return null
376
+ return file
377
+ }
378
+
379
+ /**
380
+ * Read one card's last-run record. Missing, unreadable, invalid or
381
+ * out-of-contract files all degrade to null: a broken record never breaks the
382
+ * snapshot. A record written by a worker activation also carries that worker's
383
+ * `sessionId` (and its `agentName`); both are forwarded only when present so a
384
+ * legacy record keeps its exact previous shape.
385
+ * @param {string} cwd - repository root.
386
+ * @param {unknown} cardId - card id from the task list.
387
+ * @returns {null|{ cardId: string, agent: string, startedAt: string|null, endedAt: string|null, status: 'done'|'failed'|'running', exitCode?: number, commit?: string, sessionId?: string, agentName?: string, output: string }}
388
+ */
389
+ export function readLastRun(cwd, cardId) {
390
+ const file = lastRunPath(cwd, cardId)
391
+ if (file === null) return null
392
+ let text
393
+ try {
394
+ text = fs.readFileSync(file, 'utf8')
395
+ } catch {
396
+ return null
397
+ }
398
+ let parsed
399
+ try {
400
+ parsed = JSON.parse(text)
401
+ } catch {
402
+ return null
403
+ }
404
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
405
+ if (!RUN_STATUSES.includes(parsed.status)) return null
406
+ const record = {
407
+ cardId: typeof parsed.cardId === 'string' && parsed.cardId !== '' ? parsed.cardId : cardId,
408
+ agent: typeof parsed.agent === 'string' ? parsed.agent : '',
409
+ startedAt: typeof parsed.startedAt === 'string' ? parsed.startedAt : null,
410
+ endedAt: typeof parsed.endedAt === 'string' ? parsed.endedAt : null,
411
+ status: parsed.status,
412
+ output: typeof parsed.output === 'string' ? parsed.output.slice(0, MAX_RUN_OUTPUT_BYTES) : '',
413
+ }
414
+ if (Number.isInteger(parsed.exitCode)) record.exitCode = parsed.exitCode
415
+ if (typeof parsed.commit === 'string' && parsed.commit !== '') record.commit = parsed.commit
416
+ // Worker chat identity: forwarded verbatim, omitted on pre-0.6.4 records.
417
+ if (typeof parsed.sessionId === 'string' && parsed.sessionId !== '') record.sessionId = parsed.sessionId
418
+ if (typeof parsed.agentName === 'string' && parsed.agentName !== '') record.agentName = parsed.agentName
419
+ return record
420
+ }
421
+
422
+ /**
423
+ * Attach `lastRun` to every card of the current repository's task list.
424
+ * Non-array input is returned untouched so the snapshot contract cannot change
425
+ * shape because of a malformed CLI payload.
426
+ * @param {string} cwd - repository root.
427
+ * @param {unknown} tasks - parsed `hive-tasks list --json`.
428
+ * @returns {unknown}
429
+ */
430
+ export function attachLastRuns(cwd, tasks) {
431
+ if (!Array.isArray(tasks)) return tasks
432
+ return tasks.map(task => (
433
+ task !== null && typeof task === 'object' && !Array.isArray(task)
434
+ ? { ...task, lastRun: readLastRun(cwd, task.id) }
435
+ : task
436
+ ))
437
+ }
438
+
252
439
  // ── action argument validation ──────────────────────────────────────────────
253
440
 
254
441
  function invalid(field, rule) {
@@ -404,10 +591,6 @@ const ACTION_BUILDERS = Object.freeze({
404
591
  argv: ['fail', idArg(payload.id), '--reason', optionalString(payload.reason, 'reason', 2000) ?? 'failed from panel'],
405
592
  }),
406
593
  retry: payload => ({ bin: 'tasks', argv: ['retry', idArg(payload.id)] }),
407
- block: payload => ({
408
- bin: 'tasks',
409
- argv: ['block', idArg(payload.id), '--reason', optionalString(payload.reason, 'reason', 2000) ?? 'blocked from panel'],
410
- }),
411
594
  renew: payload => {
412
595
  const argv = ['renew', idArg(payload.id), '--ttl', ttlArg(payload.ttl)]
413
596
  const agent = optionalString(payload.agent, 'agent', 64)
@@ -465,6 +648,15 @@ const ACTION_BUILDERS = Object.freeze({
465
648
  if (description !== undefined) argv.push('--description', description)
466
649
  return { bin: 'hive', argv }
467
650
  },
651
+ // 'hive roles rm <name>': drops the role from .hive/roles.yaml. Neither
652
+ // --force nor --keep-file is ever sent, so the CLI itself decides every
653
+ // refusal (e.g. "role ... not found") and its stderr reaches the panel
654
+ // unchanged. The host does not inspect cards/limits: hive roles rm does not
655
+ // check in-flight work, and the contract file is kept by the CLI.
656
+ 'roles-remove': payload => ({
657
+ bin: 'hive',
658
+ argv: ['roles', 'rm', roleNameArg(payload.name)],
659
+ }),
468
660
  // 'hive tasks rm <id>' goes through the hive router to hive-tasks. No --force
469
661
  // is ever sent: a claimed card is refused by the CLI, and that refusal (like
470
662
  // a second delete's "not found") reaches the panel in stderr unchanged.
@@ -651,6 +843,43 @@ export function createBridge(ctx, config = {}) {
651
843
  }
652
844
  }
653
845
 
846
+ /** Actionable diagnostic for a bin whose PATH name and npx fallback both failed. */
847
+ function missingBinHint(key) {
848
+ const executable = typeof bins[key] === 'string' ? bins[key] : String(DEFAULT_BINS[key])
849
+ const packages = BIN_PACKAGES[key] ?? []
850
+ const install = packages.length === 0 ? 'npm i -g <package>' : 'npm i -g ' + packages.join(' ')
851
+ return '[hive-panel] ' + String(key) + ' CLI ' + JSON.stringify(executable)
852
+ + ' was not found on the PATH of the DSH shell and the npx fallback did not run it; install it once with "'
853
+ + install + '" or set config.bins.' + String(key) + ' to an absolute path.'
854
+ }
855
+
856
+ /**
857
+ * Execute one fixed command; when the bare PATH executable is missing, retry
858
+ * the same argv once through `npx -y -p <package> ... <bin>`. An explicit
859
+ * absolute bin (no npx fallback) fails with the same install hint.
860
+ */
861
+ async function executeWithFallback(command, fallback, options, key) {
862
+ const first = await execute(command, options)
863
+ if (!missingBinary(first)) return first
864
+ if (typeof fallback === 'string') {
865
+ log('bin ' + String(key) + ' is not on the shell PATH; retrying through npx')
866
+ const retried = await execute(fallback, options)
867
+ if (!missingBinary(retried)) return retried
868
+ return appendStderr(retried, missingBinHint(key))
869
+ }
870
+ return appendStderr(first, missingBinHint(key))
871
+ }
872
+
873
+ /** tryExecute + npx fallback (snapshot fan-out and per-command probes). */
874
+ async function tryExecuteWithFallback(command, fallback, options, key) {
875
+ try {
876
+ return await executeWithFallback(command, fallback, options, key)
877
+ } catch (error) {
878
+ log('probe failed: ' + command, error)
879
+ return undefined
880
+ }
881
+ }
882
+
654
883
  function readMode(result) {
655
884
  const parsed = result === undefined ? null : parseJson(result.stdout?.text, null)
656
885
  if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
@@ -743,19 +972,20 @@ export function createBridge(ctx, config = {}) {
743
972
  return payload
744
973
  }
745
974
  const commands = snapshotCliCommands(bins)
975
+ const fallbacks = snapshotFallbackCommands(bins)
746
976
  const [board, tasks, stats, mode, roles] = await Promise.all([
747
- tryExecute(commands.board, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }),
748
- tryExecute(commands.tasks, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }),
749
- tryExecute(commands.stats, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }),
977
+ tryExecuteWithFallback(commands.board, fallbacks.board, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }, 'hive'),
978
+ tryExecuteWithFallback(commands.tasks, fallbacks.tasks, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }, 'tasks'),
979
+ tryExecuteWithFallback(commands.stats, fallbacks.stats, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }, 'tasks'),
750
980
  tryExecute(SNAPSHOT_READS.mode, { cwd, session, timeoutMs: PROBE_TIMEOUT_MS, signal }),
751
- tryExecute(commands.roles, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }),
981
+ tryExecuteWithFallback(commands.roles, fallbacks.roles, { cwd, session, timeoutMs: snapshotTimeoutMs, signal }, 'hive'),
752
982
  ])
753
983
  return {
754
984
  ...payload,
755
985
  initialised: true,
756
986
  mode: readMode(mode),
757
987
  board: parseJson(board?.stdout?.text, []),
758
- tasks: parseJson(tasks?.stdout?.text, []),
988
+ tasks: attachLastRuns(cwd, parseJson(tasks?.stdout?.text, [])),
759
989
  stats: parseJson(stats?.stdout?.text, null),
760
990
  events: readEvents(cwd),
761
991
  roles: rolesSnapshot(cwd, roles),
@@ -834,8 +1064,10 @@ export function createBridge(ctx, config = {}) {
834
1064
  body: { ok: false, code: 2, stdout: '', stderr: 'read-only: hive-panel writable=false' },
835
1065
  }
836
1066
  }
837
- const command = commandForAction(actionName, payload, bins)
838
- const result = await execute(command, { cwd, session, timeoutMs: actionTimeoutMs, signal })
1067
+ const invocation = actionInvocation(actionName, payload)
1068
+ const command = buildCommand(bins[invocation.bin], invocation.argv)
1069
+ const fallback = fallbackCommandForBin(invocation.bin, invocation.argv, bins)
1070
+ const result = await executeWithFallback(command, fallback, { cwd, session, timeoutMs: actionTimeoutMs, signal }, invocation.bin)
839
1071
  const body = actionBody(result)
840
1072
  if (actionName === 'init' && body.ok) {
841
1073
  await activateQueen(sessionId, cwd, session, signal)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hive-panel",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Hive board and queen mode inside DSH Web: a conversation view scoped to the Session's repository, with allowlisted task-card actions over DSH's shell seam.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -53,6 +53,9 @@ const moduleCode = [
53
53
  " onError: function (error) { console.warn('[hive-panel]', error) },",
54
54
  " t: params.hiveTranslate,",
55
55
  " subscribeLocale: params.hiveLocaleSubscribe,",
56
+ " // Optional: the client half only supplies this when the host",
57
+ " // exposes workspace navigation (ctx.uiWorkspace.openSession).",
58
+ " openSession: typeof params.hiveOpenSession === 'function' ? params.hiveOpenSession : undefined,",
56
59
  " })",
57
60
  " return function () { instance.destroy() }",
58
61
  " }, [sessionId])",
@@ -15,6 +15,8 @@
15
15
  import assert from 'node:assert/strict'
16
16
  import { execFile } from 'node:child_process'
17
17
  import { existsSync } from 'node:fs'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
18
20
  import { promisify } from 'node:util'
19
21
  import { commandFor, inject, FETCH_PATH, RPC_CHANNEL, apply } from './hive-exec-demo.mjs'
20
22
 
@@ -23,11 +25,15 @@ let checks = 0
23
25
  const ok = (message) => { checks += 1; console.log('ok ' + checks + ' - ' + message) }
24
26
  const skip = (message) => { console.log('# skip - ' + message) }
25
27
 
26
- // Real Hive CLIs installed on this machine; the panel itself only needs PATH names.
27
- const HIVE_BIN = '/Users/admin/Codes/hive-consensus/bin/hive.js'
28
- const HIVE_TASKS_BIN = '/Users/admin/Codes/hive-tasks/bin/hive-tasks.js'
29
- const DEMO_REPO = '/tmp/hive-demo' // a repo with Hive state
30
- const EMPTY_REPO = '/Users/admin/Codes/hive-panel' // a dir without Hive state
28
+ // Optional real-CLI evidence (check 10). Nothing here is required for the shim
29
+ // checks: point the env vars at your checkouts, or keep the sibling/PATH
30
+ // defaults. The demo repository must already contain Hive cards; without it the
31
+ // real-CLI check skips with a message instead of failing on an author path.
32
+ const SIBLINGS = path.resolve(import.meta.dirname, '..', '..')
33
+ const HIVE_BIN = process.env.HIVE_BIN || path.join(SIBLINGS, 'hive-consensus', 'bin', 'hive.js')
34
+ const HIVE_TASKS_BIN = process.env.HIVE_TASKS_BIN || path.join(SIBLINGS, 'hive-tasks', 'bin', 'hive-tasks.js')
35
+ const DEMO_REPO = process.env.HIVE_DEMO_REPO || path.join(os.tmpdir(), 'hive-demo')
36
+ const EMPTY_REPO = process.env.HIVE_EMPTY_REPO || process.cwd()
31
37
 
32
38
  /**
33
39
  * Build the shim Context. `real: true` actually spawns bash; otherwise the