SLOPSHOPPER

hub-link-commands

Runs its kndl's commands in a Claude Code Session: prompts, stops, and messages to subagents.

panebandguardprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · hub-link-commands
│ ┃ kndl-question ✕ › fix the failing auth test and add an audit log call │ ┃ No question is open. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · kndl-question
No question is open.
README

<img src="brand/lockup-light.svg" alt="kndl" width="180">

kndl

Multiplayer agentic sessions.

[!NOTE] Issues and pull requests are open to maintainers only for now, while we set the baseline kndl grows from. Please use Discussions for bugs, ideas and questions in the meantime.

kndl (said "kindle") is a self-hosted Hub where a team runs coding-agent Sessions in Sandboxes on any number of Runners, on the Models of any Provider they connect, and watches them together from the web. Each Session is driven by the person who started it.

Documentation: <https://kddige.github.io/kndl/>

kndl is early: v1 is being built, and things change quickly.

How it works

  • The Hub keeps the Sessions, signs people in with GitHub, and serves the web UI. It is invite-only: its Owner invites everyone else.
  • A Runner, on each machine that runs Sessions, starts each Session's agent in its own Sandbox, a microVM built from its Repo's Environment, so nothing the agent runs touches the host. The agent is pi or Claude Code, whichever runs the Session's model, and a Session switches between them when its model does, handing the other what it hasn't seen.
  • Each Session runs on its Creator's own accounts: the Providers they connected on the Hub, with a subscription sign-in or an API key, and their Claude setup token for Claude's Models. The Hub keeps the Providers' credentials and adds them to model calls on the way out, so they never enter a Sandbox. Claude's token is the exception: Claude Code holds it in the Sandbox and talks to Anthropic directly.
  • Only the Creator drives a Session: prompts it, answers it, stops it, controls it and uses its terminal. Everyone else with access to its Repo watches it live, subagents included.

Terms are defined in GLOSSARY.md, and design decisions are in docs/adr/.

Quick start

To install a Hub, a Runner or both as services, on macOS or Linux with git:

curl -fsSL https://raw.githubusercontent.com/kddige/kndl/main/install.sh | sh

It installs into ~/.kndl. Then run kndl onboard to set up a Hub, a Runner, or both. See Install kndl. To get only the kndl command from a Hub, see Install the CLI from a Hub.

To run it from this checkout on one machine, without GitHub, you need Bun 1.4 or newer, git, an account at a Provider (a subscription or an API key, or a Claude subscription for a claude setup-token token), which you connect on your Account page, and a Mac with Apple Silicon or Linux with KVM.

bun install
bun run web:build
HUB_PUBLIC_URL=http://127.0.0.1:7777 KNDL_DEV_LOGIN=1 bun run hub

In a second terminal:

bun run runner-token "$(hostname -s)"   # prints a Runner token, chr_…
RUNNER_TOKEN=chr_… bun run runner

Open <http://127.0.0.1:7777>, sign in with dev login, give a Repo its Environment, and start a Session on it. The tutorial walks through it.

Development

One Bun workspace in TypeScript, with Effect.

PackageWhat it is
packages/protocolThe messages the Hub, Runners, the mod and the web UI exchange, as Effect Schemas.
packages/hubThe Hub: an Effect HTTP server on Bun, with SQLite.
packages/runnerA Runner: pi or Claude Code in tmux in a microsandbox Sandbox, and the mod relay to the Hub.
packages/cliThe kndl command: installs, runs and looks after a Hub and Runner as services.
packages/modThe mod each Session loads: a pi extension, with the Claude bridge, and for Claude Code two plugins, hub-link, which reports to the Hub, and hub-link-commands, which runs its commands.
packages/webThe web UI: React on Vite, Base UI and StyleX.
packages/docsThe documentation site: Astro Starlight.
brand/The logo's sources. bun run --filter @kndl/docs brand makes the PNG and ICO files from them.

From the repo root:

CommandWhat it does
bun testRuns every package's tests.
bun run typecheckTypechecks every package.
bun run lintLints with oxlint.
bun run format:checkChecks formatting with oxfmt; bun run format applies it.
bun run webThe web UI's Vite dev server on <http://localhost:5173>, beside bun run hub.
bun run mod:checkBuilds the mod and validates its plugins with Claude Code.
bun run docs:devThe documentation site on <http://localhost:4321/kndl/>.
bun run docs:buildBuilds the site into packages/docs/dist.

See Develop kndl and the commands reference.

Not affiliated with Anthropic

kndl is an independent project, not affiliated with, endorsed by or sponsored by Anthropic. Claude and Claude Code are Anthropic's trademarks; kndl runs Claude Code as Anthropic publishes it, on your own Claude account.

License

kndl is released under the MIT License. The skills vendored in .agents/skills are MIT-licensed by their author; see THIRD_PARTY_NOTICES.md.

Source 3 files
hooks/register.ts 692 lines
1// hub-link-commands: the plugin that runs the Hub's commands in a Session's Claude Code, beside
2// hub-link, which reports (ADR 0014). They are two because a plugin's hooks don't see the work it
3// causes: an agent this plugin resumes with a message runs past its own hooks, but not past
4// hub-link's (spike #148).
5//
6// - The Hub: says hello and long-polls for commands (see HubLink.ts): prompts from the Prompt
7//   queue, prompts steered into the running Turn, stopping the Turn, messages to subagents and
8//   stopping one, and presence.
9// - hub-link: reads which prompt it delivered last, and who sent it, to report the Turn it starts
10//   and tell Claude of its files; and which it is steering, to report it joining the Turn.
11// - The person at the terminal, the Session's Creator: a band above the prompt shows the link and
12//   the Participants watching (ADR 0026).
13// - Claude: a tool that opens the files the Creator attaches to prompts (#276, ADR 0024), which the
14//   plugin API's prompts can't carry: it fetches each from the Hub, and answers with the image or
15//   PDF (#277). After the Session switched to Claude Code from another Harness, a context handoff
16//   of what happened meanwhile, and a tool that reads further back in its history (ADR 0030).
17//
18// The rest of the plugin, with Effect and the protocol, is bundled from the mod package's src/
19// into hooks/hub-link-lib.js (`bun run build`).
20
21import { atom, read, update } from "claude-code"
22import type { EngineInterface, On } from "claude-code"
23import type { HubLinkBand } from "../types"
24import {
25  askedAsyncText,
26  askedQuestions,
27  attachmentContext,
28  attachmentToolName,
29  attachmentToolSpec,
30  deliveredPrompt,
31  handoffNote,
32  historyAnswer,
33  historyPath,
34  historyRequest,
35  historyToolName,
36  historyToolSpec,
37  HubLink,
38  openAttachment,
39  questionResultText,
40  questionToolName,
41  questionToolSpec,
42  steeredPrompt,
43  stillOpenText,
44} from "./hub-link-lib.js"
45import type {
46  Command,
47  LinkStatus,
48  ModCommand,
49  Participant,
50  Question,
51  QuestionAnswer,
52} from "./hub-link-lib.js"
53import { dialogs, PANE, registerQuestionDialog, rowsFor } from "./question-dialog.ts"
54import type { Submit } from "./question-dialog.ts"
55
56const band = atom(
57  { plugin: "hub-link-commands", key: "band" } as const,
58  {
59    status: "Unlinked",
60    detail: "",
61    participants: [],
62  } as HubLinkBand,
63)
64
65const delivered = { plugin: "hub-link-commands", key: "delivered" } as const
66const steering = { plugin: "hub-link-commands", key: "steering" } as const
67/** The question dialog's state, which question-dialog.ts draws from. */
68const question = { plugin: "hub-link-commands", key: "question" } as const
69
70/** The module's own state; a reload starts it over, and fires `session.start` again. */
71const state = {
72  link: undefined as HubLink | undefined,
73  /** Where the Hub is, and the mod token, for the attachment tool's fetches. */
74  hub: undefined as { readonly url: string; readonly modToken: string } | undefined,
75
76  /** The Turn running on the main loop, which StopTurn stops. */
77  mainTurn: undefined as string | undefined,
78  /**
79   * The question tool's calls waiting for an answer, by id (#193): each takes an answer, from the
80   * web UI with its sender, or from the terminal's dialog with none, and says whether it came
81   * first.
82   */
83  asking: new Map<string, (answer: QuestionAnswer, sender: Participant | undefined) => boolean>(),
84  /** The call of the question asked `async` that is still waiting for an answer, if one is. */
85  asyncOpen: undefined as string | undefined,
86  /**
87   * A context handoff Claude Code wouldn't append as a note (ADR 0030): it goes, out of sight,
88   * with the next prompt instead.
89   */
90  handoff: undefined as string | undefined,
91}
92
93/** The handoff waiting for the next prompt, if one is: taken, so it goes once. */
94const takeHandoff = () => {
95  const note = state.handoff
96  state.handoff = undefined
97  return note
98}
99
100/** A handoff taken for a prompt that never went: it waits for the next, unless a later one does. */
101const putBackHandoff = (note: string | undefined) => {
102  state.handoff ??= note
103}
104
105const report = (event: Record<string, unknown>) => state.link?.report(event)
106
107/**
108 * The prompts given Claude Code, by id, so one delivered again isn't run twice (#323): the Hub
109 * delivers the head of its queue again when it restarts, or when the TurnStarted that takes a
110 * prompt out of it was lost. Kept here for this process, and in the store, which is in the
111 * Session's own Claude configuration, for the next: the last `SubmittedKept` of them.
112 */
113const submitted = {
114  ids: new Set<string>(),
115  /** The store's list is read, changed and written back one change at a time. */
116  writing: Promise.resolve(),
117}
118const SubmittedKept = 200
119
120const storeSubmitted = (
121  $: EngineInterface,
122  change: (ids: ReadonlyArray<string>) => Array<string>,
123) => {
124  submitted.writing = submitted.writing
125    .then(async () => {
126      const kept = await $.store.get("submitted")
127      const ids = Array.isArray(kept) ? kept.filter((id) => typeof id === "string") : []
128      await $.store.set("submitted", change(ids).slice(-SubmittedKept))
129    })
130    .catch(() => undefined)
131  return submitted.writing
132}
133
134/** Whether `promptId` was given Claude Code already; if not, it is now said to be. */
135const submittedBefore = async ($: EngineInterface, promptId: string) => {
136  // Checked and taken before anything is awaited, so a prompt delivered twice at once runs once.
137  if (submitted.ids.has(promptId)) return true
138  submitted.ids.add(promptId)
139  const kept = await $.store.get("submitted").catch(() => undefined)
140  if (Array.isArray(kept) && kept.includes(promptId)) return true
141  await storeSubmitted($, (ids) => [...ids, promptId])
142  return false
143}
144
145/** `promptId` wasn't given Claude Code after all, so it may be delivered again. */
146const notSubmitted = ($: EngineInterface, promptId: string) => {
147  submitted.ids.delete(promptId)
148  void storeSubmitted($, (ids) => ids.filter((id) => id !== promptId))
149}
150
151const setBand = ($: EngineInterface, change: Partial<HubLinkBand>) =>
152  update($, band, (value) => ({ ...value, ...change })).catch(() => undefined)
153
154const bandStatus = (status: LinkStatus): Partial<HubLinkBand> =>
155  status._tag === "Rejected"
156    ? { status: "Rejected", detail: status.reason }
157    : { status: status._tag, detail: "" }
158
159const deliverPrompt = async ($: EngineInterface, command: Command<"DeliverPrompt">) => {
160  if (await submittedBefore($, command.promptId)) {
161    // A Hub from before #323 would refuse the event, so it keeps the prompt queued: still run once.
162    if (state.link?.takesAlreadySubmitted) {
163      report({ _tag: "PromptAlreadySubmitted", promptId: command.promptId })
164    }
165    return
166  }
167  const handoff = takeHandoff()
168  const failed = (message: string) => {
169    // No Turn starts with it, nor with its handoff, which waits for the next prompt.
170    putBackHandoff(handoff)
171    void $.state.set(delivered, null).catch(() => undefined)
172    notSubmitted($, command.promptId)
173    report({ _tag: "PromptFailed", promptId: command.promptId, message })
174  }
175  const attachments = command.attachments ?? []
176  const text = deliveredPrompt(command.sender, command.text, attachments)
177  const context = [
178    handoff,
179    attachments.length > 0 ? attachmentContext(attachments) : undefined,
180  ].filter((part) => part !== undefined)
181  try {
182    // Said before it is submitted, so hub-link reads it when the Turn starts, and adds what Claude
183    // is told of its files, and a handoff that waits: a plugin's own hooks don't see the prompt it
184    // submits.
185    await $.state.set(delivered, {
186      promptId: command.promptId,
187      sender: command.sender,
188      text,
189      ...(context.length > 0 && { context: context.join("\n\n") }),
190    })
191    const entered = await $.prompt.submit({ text, asUser: true })
192    if (entered.drop !== undefined) failed(`a hook dropped the prompt: ${entered.drop}`)
193  } catch (error) {
194    failed(String(error))
195  }
196}
197
198/**
199 * A queued prompt the Creator steered into the running Turn (#195, ADR 0018): a row of the
200 * Turn's conversation, which Claude reads at its next step, as Claude Code adds a prompt typed
201 * while it works. hub-link sees it join, and reports it. Once the Turn has ended it can't join:
202 * the Hub keeps it queued.
203 */
204const deliverIntoTurn = async ($: EngineInterface, command: Command<"DeliverIntoTurn">) => {
205  const failed = (message: string) =>
206    report({ _tag: "PromptFailed", promptId: command.promptId, message })
207  if (state.mainTurn === undefined) return failed("no Turn is running")
208  const { promptId, sender, text } = command
209  const attachments = command.attachments ?? []
210  // Its files are marked in the row (#278): Claude opens them by the markers alone.
211  const row = steeredPrompt(sender, text, attachments)
212  try {
213    // Said before it is appended, so hub-link knows the row.
214    await $.state.set(steering, {
215      promptId,
216      sender,
217      text,
218      ...(attachments.length > 0 && { attachments: [...attachments] }),
219      appended: row,
220    })
221    const appended = await $.session.append({
222      message: { type: "user", content: [{ type: "text", text: row }] },
223    })
224    if (appended.deny !== undefined) failed(appended.deny)
225  } catch (error) {
226    failed(String(error))
227  } finally {
228    await $.state.set(steering, null).catch(() => undefined)
229  }
230}
231
232/**
233 * What happened in the Session while another Harness ran it (ADR 0030), as a note in the
234 * conversation, appended as a steered prompt is: Claude reads it with the next prompt, ahead of it,
235 * and no Turn starts with it (spike #195; in a new conversation too, checked against Claude Code
236 * 2.1.296 with a stub API). It comes once Claude Code has started, before the next
237 * prompt, so while Claude is idle; if it comes during a Turn, Claude reads it at the Turn's next
238 * step. One Claude Code won't append goes with the next prompt instead, unless a later one is
239 * appended first, which takes its place.
240 */
241const deliverHandoff = async ($: EngineInterface, command: Command<"DeliverHandoff">) => {
242  const note = handoffNote(command, historyToolName)
243  if (note === undefined) return
244  const held = (why: string) => {
245    $.ui.log(`hub-link-commands: the handoff waits for the next prompt: ${why}`, { to: "debug" })
246    state.handoff = note
247  }
248  try {
249    const appended = await $.session.append({
250      message: { type: "user", content: [{ type: "text", text: note }] },
251    })
252    if (appended.deny !== undefined) held(appended.deny)
253    else state.handoff = undefined
254  } catch (error) {
255    held(String(error))
256  }
257}
258
259/**
260 * The Creator's message to an agent (ADR 0014), with their name and a marker for each file
261 * (#278), as a prompt is: a running agent reads it at its next tool call; one that has stopped
262 * resumes with it. A subagent type that lists its own tools can't open the files.
263 */
264const messageAgent = async ($: EngineInterface, command: Command<"DeliverAgentMessage">) => {
265  const failed = (message: string) =>
266    report({
267      _tag: "AgentCommandFailed",
268      agentId: command.agentId,
269      command: "MessageAgent",
270      senderId: command.sender.id,
271      message,
272    })
273  try {
274    const sent = await $.session.send({
275      to: { agentId: command.agentId },
276      text: deliveredPrompt(command.sender, command.text, command.attachments ?? []),
277    })
278    if (!sent.isDelivered) failed(sent.reason)
279  } catch (error) {
280    failed(String(error))
281  }
282}
283
284/** Stops an agent with Claude Code's TaskStop, by its id; hub-link sees the call, and reports it. */
285const stopAgent = async ($: EngineInterface, command: Command<"StopAgent">) => {
286  const failed = (message: string) =>
287    report({
288      _tag: "AgentCommandFailed",
289      agentId: command.agentId,
290      command: "StopAgent",
291      message,
292    })
293  try {
294    const stopped = await $.tool.call({ tool: "TaskStop", task_id: command.agentId })
295    if (stopped.deny !== undefined) failed(stopped.deny)
296    else if (stopped.isError) failed(String(stopped.result))
297  } catch (error) {
298    failed(String(error))
299  }
300}
301
302/** A tool's result that is text alone. */
303const textResult = (text: string) => ({ result: [{ type: "text" as const, text }] })
304
305/**
306 * The answer to the question Claude asked `async` (#193), as a note in its conversation if a Turn
307 * runs, as a steered prompt is: it reads it at its next step. With none, or once it has ended, a
308 * Turn of its own starts with it, from whoever answered: the person at the terminal, who has no
309 * `sender`, answers it from the dialog.
310 */
311const giveAnswer = async (
312  $: EngineInterface,
313  toolCallId: string,
314  sender: Participant | undefined,
315  text: string,
316) => {
317  const lost = (why: string) =>
318    $.ui.log(`hub-link-commands: couldn't give Claude the answer to a question: ${why}`, {
319      to: "debug",
320    })
321  try {
322    if (state.mainTurn !== undefined) {
323      const appended = await $.session.append({
324        message: { type: "user", content: [{ type: "text", text }] },
325      })
326      if (appended.deny === undefined) return
327    }
328    // Said before it is submitted, so hub-link reports the Turn as the answerer's. Without one it
329    // is the terminal's, as a prompt typed there is.
330    if (sender !== undefined)
331      await $.state.set(delivered, { promptId: `answer-${toolCallId}`, sender, text })
332    const entered = await $.prompt.submit({ text, asUser: true })
333    if (entered.drop !== undefined) lost(`a hook dropped the prompt: ${entered.drop}`)
334  } catch (error) {
335    lost(String(error))
336  }
337}
338
339/**
340 * Opens the question's pane, and says if it is drawn. One the person's command opens is placed at
341 * any width; one a tool opens waits undrawn below 144 columns.
342 */
343const showPane = async ($: EngineInterface, questions: ReadonlyArray<Question>) => {
344  try {
345    const opened = await $.ui.open({
346      id: PANE,
347      title: "Question",
348      focus: true,
349      rows: rowsFor(questions),
350    })
351    return opened.isPlaced
352  } catch (error) {
353    $.ui.log(`hub-link-commands: couldn't open the question pane: ${error}`, { to: "debug" })
354    return false
355  }
356}
357
358/**
359 * Shows the questions of `toolCallId` in the terminal's pane (#193), until the question closes
360 * (`closeDialog`) or the pane answers it: `submit` takes the answer, and tells the question's call.
361 * Never rejects: a pane that can't be drawn leaves the web UI to answer.
362 */
363const openDialog = async (
364  $: EngineInterface,
365  opened: { toolCallId: string; async: boolean; questions: ReadonlyArray<Question> },
366  submit: Submit,
367) => {
368  const { toolCallId, questions } = opened
369  dialogs.submitters.set(toolCallId, submit)
370  dialogs.current = toolCallId
371  try {
372    await $.state.set(question, {
373      toolCallId,
374      async: opened.async,
375      questions: [...questions],
376      index: 0,
377      answers: {},
378      picked: [],
379    })
380    // Closed already, by an answer from the web UI or a Stop, while the state was written.
381    if (dialogs.current !== toolCallId) return
382    const isPlaced = await showPane($, questions)
383    if (dialogs.current !== toolCallId) {
384      // Closed while the pane opened: it goes, unless another question has it by now.
385      if (dialogs.current === undefined) await $.ui.close({ id: PANE })
386      return
387    }
388    if (!isPlaced) $.ui.toast("The agent has a question: type /question, or widen the terminal.")
389  } catch (error) {
390    $.ui.log(`hub-link-commands: couldn't show the question: ${error}`, { to: "debug" })
391  }
392}
393
394/** The question of `toolCallId` is answered or closed: its pane goes, if it is the one shown. */
395const closeDialog = async ($: EngineInterface, toolCallId: string) => {
396  dialogs.submitters.delete(toolCallId)
397  if (dialogs.current !== toolCallId) return
398  dialogs.current = undefined
399  try {
400    await $.state.set(question, null)
401    // Another question opened meanwhile, and has the pane.
402    if (dialogs.current !== undefined) return
403    // Our own close, which `ui.close` hears as the plugin's: it dismisses nothing.
404    await $.ui.close({ id: PANE })
405  } catch (error) {
406    $.ui.log(`hub-link-commands: couldn't close the question pane: ${error}`, { to: "debug" })
407  }
408}
409
410const runCommand = async ($: EngineInterface, command: ModCommand) => {
411  switch (command._tag) {
412    // Neither waits: a prompt waits for the session to be idle, and a resumed agent runs on, while
413    // the poll goes on.
414    case "DeliverPrompt":
415      void deliverPrompt($, command)
416      return
417    case "DeliverAgentMessage":
418      void messageAgent($, command)
419      return
420    // Appended at once, so one steered prompt is told from the next.
421    case "DeliverIntoTurn":
422      await deliverIntoTurn($, command)
423      return
424    // Appended before the prompt that follows it is submitted.
425    case "DeliverHandoff":
426      await deliverHandoff($, command)
427      return
428    case "StopAgent":
429      await stopAgent($, command)
430      return
431    case "StopTurn":
432      if (state.mainTurn === undefined) return
433      await $.turn.abort({ turnId: state.mainTurn })
434      return
435    case "DeliverAnswer":
436      // Too late: answered at the terminal or by someone else first, or cancelled. The Hub tells
437      // the sender which.
438      if (state.asking.get(command.toolCallId)?.(command.answer, command.sender) !== true)
439        report({
440          _tag: "AnswerFailed",
441          toolCallId: command.toolCallId,
442          senderId: command.sender.id,
443          message: "The question was answered or closed already.",
444        })
445      return
446    case "PresenceChanged":
447      // Someone forwarding a port is here too, from a machine (#180).
448      await setBand($, {
449        participants: command.participants.map((person) =>
450          person.forwardingFrom === undefined
451            ? person.name
452            : `${person.name} (forwarding from ${person.forwardingFrom.join(", ")})`,
453        ),
454      })
455      return
456  }
457}
458
459const startLink = async ($: EngineInterface) => {
460  const [hubUrl, sessionId, modToken, kind, launched] = await Promise.all([
461    $.env.get("KNDL_URL"),
462    $.env.get("KNDL_SESSION_ID"),
463    $.env.get("KNDL_MOD_TOKEN"),
464    $.env.get("CLAUDE_CODE_SESSION_KIND"),
465    $.env.get("KNDL_CONVERSATION_ID"),
466  ])
467  // hub-link says so in the debug log. A background job or daemon of Claude Code's isn't the
468  // Session's Claude Code, and runs none of its commands (#191); nor does a `claude` run inside
469  // the Session as another conversation than the one the Runner launched (#321).
470  if (!hubUrl || !sessionId || !modToken || kind) return false
471  const conversation = await $.session.id()
472  if (launched && conversation !== launched) return false
473  state.hub = { url: hubUrl.replace(/\/+$/, ""), modToken }
474  state.link?.stop()
475  state.link = new HubLink({
476    hubUrl,
477    modToken,
478    hello: { sessionId, conversationId: conversation, model: await $.session.model() },
479    fetch: (url, init) => $.http.fetch(url, init),
480    // Its own timers, so a Stop can't cut what it does short (#165).
481    after: (ms, fn) => void $.clock.after(ms, fn),
482    onCommand: (command) => runCommand($, command),
483    onStatus: (status) => void setBand($, bandStatus(status)),
484    log: (text) => $.ui.log(text, { to: "debug" }),
485  })
486  state.link.start()
487  return true
488}
489
490export function register(on: On) {
491  on("session.start", async ($, e, next) => {
492    const started = await next(e)
493    const linked = await startLink($).catch((error) => {
494      $.ui.log(`hub-link-commands: ${error}`, { to: "debug" })
495      return false
496    })
497    // In the tool list from the first request on, beside the Hub link they fetch through.
498    if (linked) {
499      for (const tool of [attachmentToolSpec, historyToolSpec, questionToolSpec])
500        await $.tool
501          .register(tool)
502          .catch((error) => $.ui.log(`hub-link-commands: ${error}`, { to: "debug" }))
503      // The way to the pane where the terminal is too narrow for a tool to open it.
504      await $.command
505        .register({
506          name: "question",
507          description: "Show the agent's open question",
508          // The agent may be waiting for the answer, with its Turn running.
509          immediate: true,
510        })
511        .catch((error) => $.ui.log(`hub-link-commands: ${error}`, { to: "debug" }))
512    }
513    return started
514  })
515
516  // A handoff that waits goes with a prompt typed at the terminal, if that comes first, out of
517  // sight. This plugin's own prompts don't pass here: they carry it themselves.
518  on("prompt.submit", async ($, e, next) => {
519    const note = takeHandoff()
520    return next(note === undefined ? e : { ...e, context: [...(e.context ?? []), note] })
521  })
522
523  // The Session's earlier Turns (ADR 0030), as the handoff or the tool's last answer says where
524  // they start: fetched from the Hub, through the Runner's relay, and handed Claude as text.
525  on("tool.call", { tool: historyToolName }, async ($, e) => {
526    const hub = state.hub
527    if (hub === undefined) return { deny: "This session is not linked to a kndl Hub." }
528    const request = historyRequest(e)
529    if ("error" in request) return { deny: request.error }
530    try {
531      const response = await $.http.fetch(`${hub.url}${historyPath(request)}`, {
532        headers: { authorization: `Bearer ${hub.modToken}` },
533      })
534      const answer = historyAnswer(response.status, response.text, request, historyToolName)
535      return "error" in answer
536        ? { deny: answer.error }
537        : { result: [{ type: "text" as const, text: answer.text }] }
538    } catch (error) {
539      return { deny: `Could not read the session's history: ${String(error)}` }
540    }
541  })
542
543  // A file the Creator attached (#276, ADR 0024), by the id its marker gives: fetched from the
544  // Hub, through the Runner's relay, in parts the runtime's fetch can read, and handed to Claude as
545  // an image block, or a document block for a PDF (#277).
546  on("tool.call", { tool: attachmentToolName }, async ($, e) => {
547    const hub = state.hub
548    if (hub === undefined) return { deny: "This session is not linked to a kndl Hub." }
549    return openAttachment(typeof e.id === "string" ? e.id : "", (path) =>
550      $.http.fetch(`${hub.url}${path}`, { headers: { authorization: `Bearer ${hub.modToken}` } }),
551    )
552  })
553
554  on("session.end", async ($, e, next) => {
555    const ended = await next(e)
556    await state.link?.flushNow()
557    return ended
558  })
559
560  // A Turn from a prompt this plugin submitted reaches these hooks too: only an agent it resumes
561  // runs past them.
562  on("turn.start", async ($, e, next) => {
563    state.mainTurn = e.turnId
564    return next(e)
565  })
566
567  on("turn.complete", async ($, e, next) => {
568    if (e.agentId === undefined && e.turnId === state.mainTurn) state.mainTurn = undefined
569    return next(e)
570  })
571
572  // Claude's question on the main loop is the Session's Open question (#193). The tool replaces
573  // Claude Code's AskUserQuestion, which the Runner turns off: it takes the same questions, and an
574  // `async` option, with which Claude goes on while they are answered. Claude Code's own dialog
575  // can't be opened with its tool off, so a pane of this plugin's asks at the terminal, beside the
576  // web UI: whichever answers first wins. A question Claude waits for holds the call until the
577  // answer, or a Stop; one asked `async` returns at once, and its answer reaches Claude as a note,
578  // or as a Turn of its own. A subagent's questions are refused.
579  on("tool.call", { tool: questionToolName }, async ($, e, next) => {
580    const turnId = state.mainTurn
581    const toolCallId = e.tool_use_id
582    if (e.agentId !== undefined)
583      return { deny: "Subagents can't ask the people in this session questions." }
584    const questions = askedQuestions(e.questions)
585    if (questions.length === 0) return { deny: "Ask one to four questions: none came." }
586    if (state.link === undefined || turnId === undefined || !toolCallId)
587      return { deny: "There is no one to ask now: this session isn't linked to a kndl Hub." }
588    if (state.asyncOpen !== undefined) return textResult(stillOpenText)
589    const isAsync = e.async === true
590    report({
591      _tag: "QuestionAsked",
592      turnId,
593      toolCallId,
594      questions,
595      ...(isAsync && { async: true }),
596    })
597    const closed = (outcome: Record<string, unknown>, by?: Participant) =>
598      report({
599        _tag: "QuestionClosed",
600        turnId,
601        toolCallId,
602        outcome,
603        ...(by === undefined ? {} : { by }),
604      })
605    let settled = false
606    const settle = () => {
607      if (settled) return false
608      settled = true
609      state.asking.delete(toolCallId)
610      if (state.asyncOpen === toolCallId) state.asyncOpen = undefined
611      // The pane goes, whoever answered, or if the Turn was stopped.
612      void closeDialog($, toolCallId)
613      return true
614    }
615    const dialog = { toolCallId, async: isAsync, questions }
616    // The terminal's dialog answers as the web UI does, with no one to name.
617    const answerFromTerminal = (answer: QuestionAnswer) =>
618      state.asking.get(toolCallId)?.(answer, undefined)
619    if (isAsync) {
620      state.asyncOpen = toolCallId
621      state.asking.set(toolCallId, (answer, sender) => {
622        if (!settle()) return false
623        closed(answer, sender)
624        void giveAnswer(
625          $,
626          toolCallId,
627          sender,
628          questionResultText(questions, { outcome: answer, by: sender }, true),
629        )
630        return true
631      })
632      await openDialog($, dialog, answerFromTerminal)
633      return textResult(askedAsyncText)
634    }
635    const answered = new Promise<Awaited<ReturnType<typeof next>>>((resolve) => {
636      // Stopped, from the web UI or at the terminal: Claude reads no answer, and the Hub
637      // hears so now.
638      next.signal.addEventListener("abort", () => {
639        if (!settle()) return
640        closed({ _tag: "Cancelled" })
641        resolve({ deny: "The questions were closed without an answer: the Turn was stopped." })
642      })
643      state.asking.set(toolCallId, (answer, sender) => {
644        if (!settle()) return false
645        closed(answer, sender)
646        resolve(textResult(questionResultText(questions, { outcome: answer, by: sender })) as never)
647        return true
648      })
649    })
650    await openDialog($, dialog, answerFromTerminal)
651    return answered
652  })
653
654  registerQuestionDialog(on)
655
656  on("command.run", { command: "question" }, async ($) => {
657    if (dialogs.current === undefined) return { text: "No question is open." }
658    const shown = await read($, question)
659    const isPlaced = await showPane($, shown?.questions ?? [])
660    return {
661      text: isPlaced
662        ? "The question is open in a pane."
663        : "The question's pane couldn't be drawn; answer it in the web UI.",
664    }
665  })
666
667  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
668    if (e.props.hasSurvey) return next(e)
669    const value = await read($, band)
670    if (value.status === "Unlinked") return next(e)
671    const { Box, Text } = $.ui.resolve(e)
672    const isLinked = value.status === "Linked"
673    const label =
674      value.status === "Rejected"
675        ? `Hub refused the link: ${value.detail}`
676        : value.status === "Linking"
677          ? "linking to the Hub"
678          : value.status === "Offline"
679            ? "Hub offline"
680            : "Hub"
681    const people =
682      value.participants.length === 0 ? " · nobody watching" : ` · ${value.participants.join(", ")}`
683    return Box({
684      flexDirection: "row",
685      children: [
686        Text({ color: isLinked ? "green" : "red", children: isLinked ? "● " : "○ " }),
687        Text({ dimColor: true, children: isLinked ? `${label}${people}` : label }),
688      ],
689    })
690  })
691}
692
hooks/question-dialog.ts 216 lines
1// The question dialog in Claude Code's terminal (#193, ADR 0031): a pane the plugin draws, since the
2// native AskUserQuestion dialog can't be opened with the tool turned off. The terminal and the web
3// UI both answer a question, and the first answer wins: this module only offers the questions, and
4// hands the answer to the callback it was opened with (register.ts), which says whether it came
5// first. A pane a tool opens is "unasked", and waits undrawn below 144 columns (the Session's tmux
6// is 120 wide), so the person is told to type /question, a command being "asked", placed at any
7// width.
8//
9// This is the pane: what it draws, and what closing it does. Opening and closing it are register.ts's,
10// since a hooks module's `$` goes into no function across an import.
11
12import { atom, read, update } from "claude-code"
13import type { EngineInterface, On } from "claude-code"
14import type { QuestionDialog } from "../types"
15import { joinAnswers } from "./hub-link-lib.js"
16import type { Question, QuestionAnswer } from "./hub-link-lib.js"
17
18export const PANE = "kndl-question"
19
20export const dialog = atom(
21  { plugin: "hub-link-commands", key: "question" } as const,
22  null as QuestionDialog | null,
23)
24
25/** What gives a dialog's answer to the question's call; it says whether the answer came first. */
26export type Submit = (answer: QuestionAnswer) => unknown
27
28/** The dialogs open, and which of them is in the pane. */
29export const dialogs = {
30  /** Each one's callback, by the call it asks for. */
31  submitters: new Map<string, Submit>(),
32  /** The call whose dialog is the one in the pane, if one is. */
33  current: undefined as string | undefined,
34}
35
36const debug = ($: EngineInterface, text: string) => {
37  try {
38    $.ui.log(`hub-link-commands: ${text}`, { to: "debug" })
39  } catch {
40    // A log that fails is not worth failing for.
41  }
42}
43
44/** The rows the dialog wants: its options, a header, the field, the buttons, a footer. */
45export const rowsFor = (questions: ReadonlyArray<Question>) =>
46  Math.max(0, ...questions.map((question) => question.options.length)) * 2 + 6
47
48/**
49 * `answer` to question `index` (none: it is skipped), and on to the next; the last one's answer
50 * sends them all.
51 */
52const answerQuestion = async (
53  $: EngineInterface,
54  toolCallId: string,
55  index: number,
56  answer: string | undefined,
57) => {
58  const state = await update($, dialog, (shown) => {
59    const question = shown?.questions[index]
60    if (shown === null || shown.toolCallId !== toolCallId || shown.index !== index || !question)
61      return shown
62    return {
63      ...shown,
64      index: index + 1,
65      picked: [],
66      answers:
67        answer === undefined ? shown.answers : { ...shown.answers, [question.question]: answer },
68    }
69  })
70  if (state?.toolCallId === toolCallId && state.index >= state.questions.length)
71    dialogs.submitters.get(toolCallId)?.({ _tag: "Answered", answers: state.answers })
72}
73
74const togglePick = ($: EngineInterface, toolCallId: string, index: number, label: string) =>
75  update($, dialog, (shown) =>
76    shown === null || shown.toolCallId !== toolCallId || shown.index !== index
77      ? shown
78      : {
79          ...shown,
80          picked: shown.picked.includes(label)
81            ? shown.picked.filter((each) => each !== label)
82            : [...shown.picked, label],
83        },
84  )
85
86export function registerQuestionDialog(on: On) {
87  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
88    const shown = await read($, dialog)
89    const elements = $.ui.resolve(e)
90    const { Box, Text, Button } = elements
91    // The mobile app draws no field: it picks an option, or skips.
92    const Input = "Input" in elements ? elements.Input : undefined
93    const question = shown?.questions[shown.index]
94    if (shown === null || question === undefined)
95      return Box({ children: [Text({ dimColor: true, children: "No question is open." })] })
96
97    const { toolCallId, index } = shown
98    const many = shown.questions.length
99    const isLast = index === many - 1
100    const run = (work: Promise<unknown>) =>
101      void work.catch((error) => debug($, `the question pane: ${error}`))
102    const typed = (value: string) => {
103      const text = value.trim()
104      if (text === "") return
105      run(
106        answerQuestion(
107          $,
108          toolCallId,
109          index,
110          question.multiSelect ? joinAnswers([...shown.picked, text]) : text,
111        ),
112      )
113    }
114
115    return Box({
116      flexDirection: "column",
117      children: [
118        Text({
119          bold: true,
120          children: `${question.header}: ${question.question}${many > 1 ? ` (${index + 1} of ${many})` : ""}`,
121        }),
122        ...question.options.slice(0, 9).map((option, position) =>
123          Box({
124            flexDirection: "column",
125            children: [
126              Button({
127                key: `option-${position}`,
128                hotkey: String(position + 1),
129                label: `${
130                  question.multiSelect
131                    ? shown.picked.includes(option.label)
132                      ? "[x] "
133                      : "[ ] "
134                    : ""
135                }${position + 1}. ${option.label}`,
136                onPress: () =>
137                  run(
138                    question.multiSelect
139                      ? togglePick($, toolCallId, index, option.label)
140                      : answerQuestion($, toolCallId, index, option.label),
141                  ),
142              }),
143              ...(option.description === undefined
144                ? []
145                : [
146                    Box({
147                      paddingLeft: 4,
148                      children: [Text({ dimColor: true, children: option.description })],
149                    }),
150                  ]),
151            ],
152          }),
153        ),
154        ...(Input === undefined
155          ? []
156          : [Input({ key: "other", placeholder: "Something else", onSubmit: typed })]),
157        Box({
158          flexDirection: "row",
159          gap: 2,
160          children: [
161            Button({
162              key: "skip",
163              label: "Skip",
164              onPress: () => run(answerQuestion($, toolCallId, index, undefined)),
165            }),
166            Button({
167              key: "dismiss",
168              label: "Dismiss",
169              hotkey: "d",
170              role: "dismiss",
171              dimColor: true,
172              onPress: () => dialogs.submitters.get(toolCallId)?.({ _tag: "Dismissed" }),
173            }),
174            ...(question.multiSelect
175              ? [
176                  Button({
177                    key: "next",
178                    label: isLast ? "Submit" : "Next",
179                    variant: "primary",
180                    onPress: () =>
181                      run(
182                        answerQuestion(
183                          $,
184                          toolCallId,
185                          index,
186                          shown.picked.length === 0 ? undefined : joinAnswers(shown.picked),
187                        ),
188                      ),
189                  }),
190                ]
191              : []),
192          ],
193        }),
194        Text({
195          dimColor: true,
196          children: shown.async
197            ? "The agent works on meanwhile and reads your answer when it comes."
198            : "The agent waits for your answer, here or in the web UI.",
199        }),
200      ],
201    })
202  })
203
204  // The pane's close mark, a deliberate close: the person at the terminal dismisses the question. The plugin's
205  // own close, once the question is answered or closed elsewhere, dismisses nothing.
206  on("ui.close", { id: PANE }, async ($, e, next) => {
207    const toolCallId = dialogs.current
208    if (e.origin.kind === "person" && toolCallId !== undefined) {
209      dialogs.current = undefined
210      await update($, dialog, () => null).catch(() => undefined)
211      dialogs.submitters.get(toolCallId)?.({ _tag: "Dismissed" })
212    }
213    return next(e)
214  })
215}
216
types/index.d.ts 90 lines
1// hub-link-commands' contract: the state its band draws from, and the prompts it delivered and
2// steered last, which hub-link reads.
3
4/** What the band above the prompt shows. */
5export type HubLinkBand = {
6  /** Where the link to the Hub stands. */
7  status: "Linking" | "Linked" | "Offline" | "Rejected" | "Unlinked"
8  /** Why the Hub refused the link, when `status` is `Rejected`. */
9  detail: string
10  /** The names of the Participants connected to the Session now. */
11  participants: string[]
12}
13
14/** A Participant, as the protocol has them. */
15export type HubLinkParticipant = {
16  id: string
17  login: string
18  name: string
19  avatarUrl?: string
20}
21
22/** The prompt from the Prompt queue submitted last: the Turn it starts is reported as theirs. */
23export type HubLinkDelivered = {
24  promptId: string
25  sender: HubLinkParticipant
26  /** As submitted, led by the sender's name, with a marker for each file it carries. */
27  text: string
28  /**
29   * What Claude is told beside it, out of sight, when it carries files (#276): hub-link adds it
30   * as the prompt is submitted, since a plugin's hooks don't see the prompt it submits itself.
31   */
32  context?: string
33}
34
35/**
36 * The prompt from the Prompt queue being steered into the running Turn (#195): hub-link reports it
37 * joined when its row is appended.
38 */
39export type HubLinkSteering = {
40  promptId: string
41  sender: HubLinkParticipant
42  /** As its sender wrote it; empty for a prompt of attachments alone. */
43  text: string
44  /** The files it carries (#278), as the Hub sent them. */
45  attachments?: HubLinkAttachment[]
46  /** The row's text as appended: framed, with the sender's name and a marker for each file. */
47  appended: string
48}
49
50/** A file a prompt carries, as the protocol has it. */
51export type HubLinkAttachment = {
52  id: string
53  name: string
54  mediaType: string
55  size: number
56}
57
58/** One question of the dialog, as the protocol has it. */
59export type HubLinkQuestion = {
60  question: string
61  header: string
62  options: readonly { label: string; description?: string }[]
63  multiSelect: boolean
64}
65
66/**
67 * The question dialog in Claude Code's terminal (#193): the questions the agent asked, which one
68 * is shown, what was answered so far, and the options picked for a multi-select question.
69 */
70export type QuestionDialog = {
71  toolCallId: string
72  /** Asked `async`: the agent works on while it is answered. */
73  async: boolean
74  questions: readonly HubLinkQuestion[]
75  index: number
76  answers: Record<string, string>
77  picked: string[]
78}
79
80declare module "claude-code" {
81  interface PluginState {
82    "hub-link-commands": {
83      band: HubLinkBand
84      delivered: HubLinkDelivered | null
85      steering: HubLinkSteering | null
86      question: QuestionDialog | null
87    }
88  }
89}
90