🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(console): control plane data (stop, message, redirect), targets registry, send transports (ADR-465 wip)
ruv3f44b13f3e5b
diff --git a/plugins/ruflo-console/hooks/data/wf-control.ts b/plugins/ruflo-console/hooks/data/wf-control.tsnew file mode 100644index 0000000000..e64fb130d6--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-control.ts@@ -0,0 +1,251 @@+/**+ * Stop, Message and Redirect for a running workflow run or agent (ADR-465). Pure: the run, the agent and the bridge in, `ActionSpec`s out.+ * Each spec goes through the page's confirm card, which shows the EXACT engine call; the call itself is `$.tool.call` (through the host's+ * `toolCall`), so the engine's permission check and dialog decide it, never this file. What the spike proved, and no more:+ *+ * TaskStop verified on a real background agent (task_id = the agent's id): "Successfully stopped task", then status "killed".+ * For a workflow run's id, or the id of an agent inside a workflow run, no one has tried it: the engine's own answer is shown.+ * SendMessage verified only to QUEUE a message for a named or id-addressed background agent in this session+ * ("Message queued for delivery ... at its next tool round"). Delivery and being acted on are not verified.+ * Redirect the stop above (same proof), then the resume text prepared in the prompt box (never sent): two halves, said as two.+ *+ * A refusal (`deny`) is shown and nothing else is tried: no other route is used to do what the engine would not. A failed or unreachable+ * call keeps the person's choice: the same words as a prepared prompt are one button away. Everything drawn is masked first.+ */+import type { ActionSpec } from '../actions'+import type { Host, ToolReply } from '../host'+import { cleanText } from './wf-clean'+import { guardText } from './wf-guide'+import { idOf, plain } from './parse'+import type { WfAgent, WfRun } from './workflows'++/** What the control actions need of the host; a test passes fakes. */+export type Bridge = Pick<Host, 'toolCall' | 'toolCheck'>++export type ControlKind = 'stop-agent' | 'stop-run' | 'message' | 'redirect' | 'text'+/** How much of the path is known: what the spike showed, or what nobody has tried. */+export type Proof = 'verified' | 'queued-only' | 'unverified' | 'prefill'++export type ControlAction = {+ id: ControlKind+ label: string+ /** The exact engine call, or the exact prepared text. */+ call: string+ proof: Proof+ /** In words, what is known about this path. */+ proofText: string+ spec: ActionSpec | null+ /** Said on the confirm row when `spec` is null. */+ why: string+}++export type ControlInput = {+ run: WfRun+ agent: WfAgent | null+ /** The sentence typed for Message and Redirect. */+ text: string+ bridge: Bridge & Pick<Host, 'fillPrompt'>+ /** Says the result on the outcome row (and draws again). */+ report: (label: string, ok: boolean, detail: string) => void+ isRunPath: (path: string) => boolean+}++/** An id the engine hands out is letters, digits, dash and underscore; anything else is not passed to a tool. */+export const ENGINE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{5,63}$/++const CAP = 240+const stopCall = (id: string): string => `TaskStop ${JSON.stringify({ task_id: id })}`+const messageCall = (to: string, message: string): string => `SendMessage ${JSON.stringify({ to, message })}`++/** The fields a tool's answer carries, wherever it put them: the structured result first, then JSON in the text. */+function fieldsOf(reply: ToolReply): Record<string, unknown> | null {+ const raw = reply.result ?? (typeof reply.text === 'string' && reply.text.trim().startsWith('{') ? safeParse(reply.text) : undefined)++ return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null+}++function safeParse(text: string): unknown {+ try {+ return JSON.parse(text)+ } catch {+ return undefined+ }+}++export type Outcome = { ok: boolean; kind: 'done' | 'denied' | 'error' | 'not-wired'; text: string }++/** One answer, in the words the outcome row shows: masked, one line, capped. `deny` is a refusal; `isError` and `success:false` are failures. */+export function classifyReply(reply: ToolReply | undefined): Outcome {+ if (reply === undefined) return { ok: false, kind: 'not-wired', text: 'the host does not bind tool calls here' }+ if (typeof reply.deny === 'string') return { ok: false, kind: 'denied', text: `the engine refused it: ${clean(reply.deny)}` }++ const fields = fieldsOf(reply)+ const said = clean(typeof fields?.message === 'string' ? fields.message : (reply.text ?? (reply.result === undefined ? '' : JSON.stringify(reply.result))))++ if (reply.isError === true || fields?.success === false || fields?.isError === true) return { ok: false, kind: 'error', text: said === '' ? 'the engine answered with an error' : said }++ return { ok: true, kind: 'done', text: said === '' ? 'the engine answered ok with no text' : said }+}++const clean = (value: string): string => cleanText(plain(value, 400)).slice(0, CAP)++/** Calls one tool and classifies the answer; a rejection (no such tool, aborted) is an error outcome, never thrown. */+export async function callTool(bridge: Bridge, input: { tool: string } & Record<string, unknown>): Promise<Outcome> {+ if (bridge.toolCall === undefined) return classifyReply(undefined)++ try {+ return classifyReply(await bridge.toolCall(input))+ } catch (error) {+ return { ok: false, kind: 'error', text: clean(error instanceof Error ? error.message : String(error)) || 'the call was rejected' }+ }+}++/** The engine's permission verdict now, in a phrase; a missing check says so rather than guessing "allow". */+export async function permissionOf(bridge: Bridge, tool: string, input: unknown): Promise<{ decision: 'allow' | 'ask' | 'deny' | 'unknown'; text: string }> {+ if (bridge.toolCheck === undefined) return { decision: 'unknown', text: 'the host cannot ask the engine for its permission verdict; the call is still checked when it runs' }++ try {+ const verdict = await bridge.toolCheck(tool, input)++ return { decision: verdict.decision, text: `the engine's permission check: ${verdict.decision}${verdict.reason === undefined ? '' : ` (${clean(verdict.reason)})`}` }+ } catch {+ return { decision: 'unknown', text: 'the permission check could not be asked' }+ }+}++/** Text for the main session after a stop: resume the run with the guidance added. Never sent: the person presses Enter. */+export function resumeText(run: WfRun, agent: WfAgent | null, text: string, isRunPath: (path: string) => boolean): string | null {+ const session = run.dir === undefined || !isRunPath(run.dir) ? null : run.dir.replace(/\/subagents\/workflows\/[^/]+\/?$/, '')+ const where = session === null ? 'its scripts folder (<session>/workflows/scripts)' : `${session}/workflows/scripts/${plain(run.name, 40)}-${plain(run.id, 40)}.js`++ return idOf(run.id) === null ? null : `Claude Code workflow run ${run.id} (${plain(run.name, 40)}${agent === null ? '' : `, agent "${plain(agent.label, 60)}"`}) was stopped from the ruflo console. Resume it with Workflow({ scriptPath: <${where}>, resumeFromRunId: "${run.id}" }) after adding this guidance to the affected agent's prompt: ${text}`+}++/** The prompt that asks the main session to deliver a message to a workflow agent, for where the console cannot. */+export const relayText = (run: WfRun, agent: WfAgent | null, text: string): string => `Send this to ${agent === null ? `the agents of Claude Code workflow run ${run.id}` : `agent "${plain(agent.label, 60)}" (${agent.id}) of workflow run ${run.id}`} with SendMessage, then tell me what the tool answered: ${text}`++const prefillSpec = (input: ControlInput, label: string, prompt: string, note: string): ActionSpec => ({+ label,+ args: [],+ shows: `into the prompt box, not sent: ${prompt.slice(0, 200)}`,+ expect: 'the text in the prompt box (it is not sent)',+ note,+ run: async () => {+ const isFilled = await Promise.resolve(input.bridge.fillPrompt(prompt)).catch(() => false)++ input.report(label, isFilled, isFilled ? 'prepared in the prompt box: press Enter there to send it' : 'there is no prompt box to fill here')+ },+})++/** A TaskStop of `id`: the permission is asked first, a refusal ends it, and the engine's own words are the result. */+function stopSpec(input: ControlInput, id: string, label: string, proofNote: string, after?: () => Promise<string>): ActionSpec {+ return {+ label,+ args: [],+ shows: stopCall(id),+ expect: 'the engine answers that the task was stopped',+ declared: 'write',+ note: `Calls the engine's TaskStop through the session's own permission check and dialog. ${proofNote} Stopped work is not undone by resuming: a resumed run starts its unfinished agents again.`,+ run: async () => {+ const verdict = await permissionOf(input.bridge, 'TaskStop', { task_id: id })++ if (verdict.decision === 'deny') return input.report(label, false, `${verdict.text}: nothing was stopped and no other route is tried`)++ const outcome = await callTool(input.bridge, { tool: 'TaskStop', task_id: id })++ if (!outcome.ok) return input.report(label, false, `${outcome.text}${outcome.kind === 'denied' ? ': nothing was stopped and no other route is tried' : ''}`)++ const tail = after === undefined ? '' : ` ${await after().catch(() => '')}`++ input.report(label, true, `${outcome.text}${tail} (re-read the run to see its state change)`)+ },+ }+}++/**+ * What the control tab offers for the cursor. Message and Redirect need the typed sentence; every action says what it sends, how far its+ * path is proven and what to do where it is not. A ruflo swarm agent is not a Claude task: its stop and notes are the page's own.+ */+export function controlActions(input: ControlInput): ControlAction[] {+ const { run, agent, bridge } = input+ const out: ControlAction[] = []+ const add = (entry: Omit<ControlAction, 'call'> & { call?: string }) => out.push({ ...entry, call: entry.call ?? entry.spec?.shows ?? 'nothing yet' })++ if (run.kind !== 'workflow') {+ out.push({ id: 'text', label: 'ruflo agents', call: 'nothing', proof: 'prefill', proofText: 'A ruflo swarm agent is not a Claude Code task: stop it with the page\'s stop (x); message it with the guide tab (broadcast, task note).', spec: null, why: 'pick a Claude Code workflow run for these' })++ return out+ }++ const runId = ENGINE_ID.test(run.id) ? run.id : null+ const agentId = agent !== null && ENGINE_ID.test(agent.id) ? agent.id : null+ const wired = bridge.toolCall !== undefined+ const typed = guardText(input.text, 300)+ const resume = typed.ok ? resumeText(run, agent, typed.text, input.isRunPath) : null++ add({+ id: 'stop-agent',+ label: agent === null ? 'stop the agent' : `stop agent ${clean(agent.label).slice(0, 30)}`,+ proof: 'verified',+ proofText: 'TaskStop worked on a real background agent (task_id = its id; its status became killed). An agent inside a workflow run has not been tried: the engine says.',+ spec: !wired ? null : agentId === null ? null : stopSpec(input, agentId, `stop agent ${clean(agent?.label ?? agentId).slice(0, 40)}`, 'Proven on a background Agent-tool agent; for an agent of a workflow run the engine\'s answer is the proof.'),+ why: !wired ? 'this host does not bind tool calls: prepare the text instead' : agent === null ? 'pick an agent first (the cursor)' : 'that agent\'s id is not one the engine can be given',+ })++ add({+ id: 'stop-run',+ label: `stop the whole run ${clean(run.name).slice(0, 30)}`,+ proof: 'unverified',+ proofText: 'TaskStop with a workflow run\'s id was not tried in the spike. The call is real and permission-checked; the engine\'s answer, and the run read again, say whether it took.',+ spec: !wired || runId === null ? null : stopSpec(input, runId, `stop workflow run ${clean(run.name).slice(0, 40)}`, 'Not proven for a workflow run id: the engine may answer that no such task exists.'),+ why: !wired ? 'this host does not bind tool calls: stop it in Claude Code\'s Workflows panel' : 'that run\'s id is not one the engine can be given',+ })++ if (!typed.ok) {+ add({ id: 'message', label: 'message the agent', proof: 'queued-only', proofText: 'SendMessage queued a message for a running named agent in this session; whether it was delivered and acted on was not verified.', spec: null, why: typed.why })+ add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'unverified', proofText: 'Half one is the stop (see above); half two is text prepared in your prompt box.', spec: null, why: typed.why })++ return out+ }++ const to = agentId+ const messageSpec: ActionSpec | null =+ !wired || to === null+ ? null+ : {+ label: `message agent ${clean(agent?.label ?? to).slice(0, 40)}`,+ args: [],+ shows: messageCall(to, typed.text),+ expect: 'the engine answers that the message was queued',+ declared: 'write',+ note: 'Calls the engine\'s SendMessage through the session\'s permission check. The spike showed it QUEUES a message at the agent\'s next tool round; it did not show the agent reads or acts on it. An agent that is not a running, reachable one is answered "not reachable" and nothing is sent.',+ run: async () => {+ const verdict = await permissionOf(bridge, 'SendMessage', { to, message: typed.text })++ if (verdict.decision === 'deny') return input.report('message agent', false, `${verdict.text}: nothing was sent and no other route is tried`)++ const outcome = await callTool(bridge, { tool: 'SendMessage', to, message: typed.text, summary: typed.text.slice(0, 40) })++ input.report('message agent', outcome.ok, outcome.ok ? `${outcome.text} (queued is not delivered: the agent may never act on it)` : `${outcome.text}${outcome.kind === 'denied' ? ': nothing was sent and no other route is tried' : ' (use "prepare as text" to ask the main session to relay it)'}`)+ },+ }++ add({ id: 'message', label: agent === null ? 'message the agent' : `message ${clean(agent.label).slice(0, 30)}`, proof: 'queued-only', proofText: 'Queued for delivery at the agent\'s next tool round (verified on a named background agent); delivery and effect are not.', spec: messageSpec, why: !wired ? 'this host does not bind tool calls: prepare the text instead' : agent === null ? 'pick an agent first (the cursor)' : 'that agent\'s id is not one the engine can be given' })++ const redirectSpec: ActionSpec | null =+ !wired || runId === null || resume === null+ ? null+ : stopSpec(input, runId, `redirect run ${clean(run.name).slice(0, 36)}: stop, then prepare the resume`, 'Half one of two: the stop. Half two prepares the resume text in your prompt box, only when the stop worked.', async () => {+ const isFilled = await Promise.resolve(bridge.fillPrompt(resume)).catch(() => false)++ return isFilled ? 'The resume text with your guidance is in the prompt box: press Enter there to resume.' : 'There is no prompt box to put the resume text in.'+ })++ add({ id: 'redirect', label: 'redirect: stop, then resume with guidance', proof: 'unverified', proofText: 'Half one is the stop (TaskStop, proof as the run stop); half two is text prepared in your prompt box and never sent for you.', spec: redirectSpec === null ? null : { ...redirectSpec, shows: `${stopCall(runId ?? '')}, then into the prompt box: ${resume?.slice(0, 120) ?? ''}` }, why: !wired ? 'this host does not bind tool calls: prepare the text instead' : 'this run has no id the engine can be given' })++ const prompt = relayText(run, agent, typed.text)++ add({ id: 'text', label: 'prepare as text instead', proof: 'prefill', proofText: 'Nothing is called: the words wait in your prompt box and Claude (the main session) acts on them when you press Enter, under its own permissions.', spec: prefillSpec(input, 'prepare the message for the main session', prompt, 'Text only: it goes to the main Claude session, which would use SendMessage itself.'), why: 'nothing to prepare' })++ return out+}diff --git a/plugins/ruflo-console/hooks/data/wf-send.ts b/plugins/ruflo-console/hooks/data/wf-send.tsnew file mode 100644index 0000000000..e0058e0157--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-send.ts@@ -0,0 +1,210 @@+/**+ * How one message reaches one target, and how its answer comes back (ADR-465). Every transport is an injected function (`SendDeps`), so a+ * test passes fakes and asserts the exact payload; nothing here touches `$`. `payloadOf` is what the confirm card shows and `sendTo` is+ * what runs after it, built from the same strings: the card can never show something other than what is sent. Secrets: a message that+ * looks like it holds a credential is refused before either; a key is read from the NAMED environment variable at send time, rides one+ * header, and is masked out of anything drawn, logged or saved (including the provider's own reply).+ */+import { exec } from '../actions'+import { OPERATOR, hivePropose } from '../hive'+import type { Host } from '../host'+import { callTool, permissionOf } from './wf-control'+import { cleanText } from './wf-clean'+import { guardText } from './wf-guide'+import { idOf, plain, type HiveInfo } from './parse'+import { endpointsOf, type Config, type Endpoint, type Target } from './wf-targets'++export type SendDeps = Pick<Host, 'toolCall' | 'toolCheck' | 'run' | 'httpSend' | 'submitPrompt'> & {+ /** `ruflo mcp exec` is `[...cli, 'mcp', 'exec', ...]`. */+ cli: readonly string[]+ /** Where the federation helper script is, and whether the peer is trusted (an untrusted one gets the helper's own --confirm, which the person's confirm card stands for). */+ helper: string+ trustedPeers: ReadonlySet<string>+ cwd: string+ hive: HiveInfo | null+ config: Config+}++export type SendState = 'reply' | 'queued' | 'sent' | 'error' | 'refused'++export type SendResult = { ok: boolean; state: SendState; text: string; tokensIn?: number; tokensOut?: number; costUsd?: number; model?: string }++export type Payload = { shows: string; note: string }++const REPLY_CAP = 4000+const WAIT = { peer: 600_000, codex: 300_000, cli: 60_000, http: 120_000 }++const err = (state: SendState, text: string): SendResult => ({ ok: false, state, text: tidy(text, 300) })++/** Text from outside: escapes and control characters out, credentials masked, capped. */+export const tidy = (value: string, max = REPLY_CAP): string => cleanText(value).slice(0, max)++/** The body checked: plain, bounded, no leading dash, nothing that looks like a credential. */+export const bodyOf = (value: string, max = 1500): { ok: true; text: string } | { ok: false; why: string } => guardText(value, max)++const endpointOf = (target: Target, config: Config): Endpoint | undefined => endpointsOf(config).find(held => held.name === target.ref)++/** `task-12 the note`: the first word is the id, the rest the note. */+export function taskNote(body: string): { id: string; note: string } | null {+ const [first = '', ...rest] = body.trim().split(/\s+/)+ const id = idOf(first)+ const note = rest.join(' ').trim()++ return id === null || note === '' ? null : { id, note }+}++/** The exact request body an OpenAI-compatible endpoint is sent; OpenRouter is also asked for the cost it billed (other servers may reject the field). */+export function chatBody(endpoint: Endpoint, body: string): string {+ return JSON.stringify({ model: endpoint.model, messages: [{ role: 'user', content: body }], ...(new URL(endpoint.baseUrl).hostname.endsWith('openrouter.ai') && { usage: { include: true } }) })+}++/** What the confirm card shows for this send, or null where the target cannot take it (with the reason in `why`). */+export function payloadOf(target: Target, raw: string, deps: Pick<SendDeps, 'config' | 'hive' | 'cwd'>): { ok: true; payload: Payload; body: string } | { ok: false; why: string } {+ const typed = bodyOf(raw)++ if (!typed.ok) return typed++ const body = typed.text+ const done = (shows: string, note: string): { ok: true; payload: Payload; body: string } => ({ ok: true, payload: { shows: tidy(shows, 700), note }, body })++ switch (target.transport) {+ case 'prompt':+ return done(`to Claude in this session, as a visible prompt: "${body}"`, 'Starts a turn of this session (billed as any turn is). Its answer is the next turn in the transcript.')+ case 'send-message':+ return done(`SendMessage ${JSON.stringify({ to: target.ref, message: body })}`, 'The engine queues it for the agent\'s next tool round; delivery and effect are not verified.')+ case 'hive': {+ if (deps.hive === null) return { ok: false, why: 'there is no hive-mind to write to' }++ if (target.ref === 'propose') {+ const spec = hivePropose(deps.hive, body)++ return spec === null ? { ok: false, why: 'a proposal is not possible now (raft allows one open proposal per term) or the text cannot be passed' } : done(`ruflo ${spec.args.join(' ')}`, 'Opens a proposal the workers vote on. A pass binds no agent to do anything.')+ }++ return done(`ruflo mcp exec -t hive-mind_broadcast ${JSON.stringify({ message: body.slice(0, 160), priority: 'normal', fromId: OPERATOR })}`, 'Appended to the hive shared memory (the last 100). No worker is interrupted.')+ }+ case 'task': {+ const note = taskNote(body)++ return note === null ? { ok: false, why: 'start with the task id, then the note: @task task-12 what the agent should know' } : done(`ruflo mcp exec -t task_update ${JSON.stringify({ taskId: note.id, result: { guidance: note.note.slice(0, 300) } })}`, 'Writes the task record\'s result; an agent sees it only when it reads the task.')+ }+ case 'bbs':+ return done(`ruflo mcp exec -t federation_bbs_publish ${JSON.stringify({ roomId: target.ref, msgType: 'human-message', payload: { text: body, from: 'ruflo-console' } })}`, 'Appended to the room log; peers get it where the room syncs.')+ case 'x-channel':+ return done(`ruflo mcp exec -t x_federation_channel_publish ${JSON.stringify({ channel: target.ref, msgType: 'Status', payload: { text: body, from: 'ruflo-console' } })}`, `${target.ref.startsWith('prv:') ? 'Encrypted under the channel key' : 'PUBLIC: anyone on the relay can read it'}. Signed with your key. Never put secrets in it.`)+ case 'peer':+ return done(`bash federation.sh dispatch ${target.ref} ${JSON.stringify(body)}${/\(not trusted/.test(target.label) ? ' --confirm' : ''}`, `Runs \`claude -p\` on ${target.ref} with that machine's own permissions and files; the helper blocks destructive prompts and audits the dispatch.`)+ case 'codex':+ return done(`codex exec -s read-only --skip-git-repo-check --ephemeral -C ${deps.cwd} - (prompt on stdin: ${JSON.stringify(body)})`, 'Read-only sandbox: Codex can read files here and cannot write them. Its answer is the final message.')+ case 'http': {+ const endpoint = endpointOf(target, deps.config)++ return endpoint === undefined ? { ok: false, why: `no endpoint named ${target.ref}` } : done(`POST ${endpoint.baseUrl}/chat/completions${endpoint.keyEnv === 'NONE' ? '' : ` Authorization: Bearer ‹from $${endpoint.keyEnv}›`}\n${chatBody(endpoint, body)}`, 'The key is read from the named variable, sent in one header and never shown or stored. Metered by the provider.')+ }+ }+}++async function viaCli(deps: SendDeps, tool: string, params: Record<string, unknown>): Promise<SendResult> {+ const result = await deps.run([...deps.cli, 'mcp', 'exec', '-t', tool, '-p', JSON.stringify(params)], WAIT.cli).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))+ const failed = result.exitCode !== 0 || /"success"\s*:\s*false|"isError"\s*:\s*true|\[ERROR\]/.test(result.stdout)++ return failed ? err('error', result.stderr.trim() !== '' ? result.stderr : result.stdout) : { ok: true, state: 'sent', text: tidy(plain(result.stdout, 300)) || 'ruflo answered ok' }+}++/** The answer of an OpenAI-compatible reply: text, tokens and the cost the provider itself billed (never one this code works out). */+export function parseChat(text: string, secret?: string): SendResult {+ let json: { choices?: { message?: { content?: unknown } }[]; usage?: { prompt_tokens?: unknown; completion_tokens?: unknown; cost?: unknown }; model?: unknown; error?: { message?: unknown } } | undefined++ try {+ json = JSON.parse(text) as typeof json+ } catch {+ return err('error', 'the endpoint did not answer with JSON')+ }++ const content = json?.choices?.[0]?.message?.content++ if (typeof content !== 'string') return err('error', typeof json?.error?.message === 'string' ? `the endpoint refused: ${scrub(json.error.message, secret)}` : 'the endpoint answered without a message')++ const num = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)++ return { ok: true, state: 'reply', text: scrub(content, secret), ...(num(json?.usage?.prompt_tokens) !== undefined && { tokensIn: num(json?.usage?.prompt_tokens) as number }), ...(num(json?.usage?.completion_tokens) !== undefined && { tokensOut: num(json?.usage?.completion_tokens) as number }), ...(num(json?.usage?.cost) !== undefined && { costUsd: num(json?.usage?.cost) as number }), ...(typeof json?.model === 'string' && { model: tidy(json.model, 80) }) }+}++/** Masks the key's own text wherever it appears (a provider may echo a header), then the usual credential shapes. */+export const scrub = (value: string, secret?: string): string => tidy(secret === undefined || secret.length < 6 ? value : value.split(secret).join('‹masked›'))++/** Sends one message. The engine's permission, the confirm card and the person's choice come BEFORE this; nothing here retries by another route. */+export async function sendTo(deps: SendDeps, target: Target, raw: string): Promise<SendResult> {+ const made = payloadOf(target, raw, deps)++ if (!made.ok) return err('refused', made.why)++ const body = made.body++ switch (target.transport) {+ case 'prompt':+ await deps.submitPrompt(body)++ return { ok: true, state: 'sent', text: 'submitted as a visible prompt; the answer is the next turn in the transcript' }+ case 'send-message': {+ if ((await permissionOf(deps, 'SendMessage', { to: target.ref, message: body })).decision === 'deny') return err('refused', 'the engine\'s permission check refused SendMessage: nothing was sent')++ const outcome = await callTool(deps, { tool: 'SendMessage', to: target.ref, message: body, summary: body.slice(0, 40) })++ return outcome.ok ? { ok: true, state: 'queued', text: `${outcome.text} (queued is not delivered)` } : err(outcome.kind === 'denied' ? 'refused' : 'error', outcome.text)+ }+ case 'hive': {+ if (target.ref === 'propose') {+ const spec = deps.hive === null ? null : hivePropose(deps.hive, body)++ if (spec === null) return err('refused', 'a proposal is not possible now')++ const proposed = await deps.run([...deps.cli, ...spec.args], WAIT.cli).catch(() => undefined)++ return proposed !== undefined && proposed.exitCode === 0 ? { ok: true, state: 'sent', text: 'the proposal was opened; the workers vote on it' } : err('error', proposed?.stderr ?? 'refused')+ }++ return viaCli(deps, 'hive-mind_broadcast', { message: body.slice(0, 160), priority: 'normal', fromId: OPERATOR })+ }+ case 'task': {+ const note = taskNote(body)++ return note === null ? err('refused', 'no task id') : viaCli(deps, 'task_update', { taskId: note.id, result: { guidance: note.note.slice(0, 300) } })+ }+ case 'bbs':+ return viaCli(deps, 'federation_bbs_publish', { roomId: target.ref, msgType: 'human-message', payload: { text: body, from: 'ruflo-console' } })+ case 'x-channel':+ return viaCli(deps, 'x_federation_channel_publish', { channel: target.ref, msgType: 'Status', payload: { text: body, from: 'ruflo-console' } })+ case 'peer': {+ const result = await deps.run(['bash', deps.helper, 'dispatch', target.ref, body, ...(deps.trustedPeers.has(target.ref) ? [] : ['--confirm'])], WAIT.peer).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))++ return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout) } : err('error', result.stderr.trim() !== '' ? result.stderr : `the peer answered nothing (exit ${result.exitCode})`)+ }+ case 'codex': {+ const result = await deps.run(['codex', 'exec', '-s', 'read-only', '--skip-git-repo-check', '--ephemeral', '-C', deps.cwd, '-'], WAIT.codex, body).catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : 'refused' }))+ const used = /tokens used\s*[:\n]\s*([\d,]+)/i.exec(result.stderr + result.stdout)?.[1]++ return result.exitCode === 0 && result.stdout.trim() !== '' ? { ok: true, state: 'reply', text: tidy(result.stdout), ...(used !== undefined && { tokensOut: Number(used.replace(/,/g, '')) }) } : err('error', result.stderr.trim() !== '' ? result.stderr : `codex answered nothing (exit ${result.exitCode})`)+ }+ case 'http': {+ const endpoint = endpointOf(target, deps.config)++ if (endpoint === undefined) return err('refused', `no endpoint named ${target.ref}`)+ if (deps.httpSend === undefined) return err('error', 'this host cannot send an HTTP request')++ let key: string | undefined++ if (endpoint.keyEnv !== 'NONE') {+ const read = await deps.run(['printenv', endpoint.keyEnv], 5_000).catch(() => undefined)++ key = read !== undefined && read.exitCode === 0 ? read.stdout.trim() : undefined++ if (key === undefined || key === '') return err('refused', `$${endpoint.keyEnv} is not set in the environment Claude Code runs in: nothing was sent`)+ }++ const response = await deps.httpSend(`${endpoint.baseUrl}/chat/completions`, { method: 'POST', headers: { 'content-type': 'application/json', ...(key !== undefined && { authorization: `Bearer ${key}` }) }, body: chatBody(endpoint, body) }).catch((error: unknown) => ({ ok: false, status: 0, text: error instanceof Error ? error.message : 'refused' }))++ return response.ok ? parseChat(response.text, key) : err('error', `${response.status === 0 ? 'the request failed' : `HTTP ${response.status}`}: ${scrub(response.text, key).slice(0, 160)}`)+ }+ }+}diff --git a/plugins/ruflo-console/hooks/data/wf-targets.ts b/plugins/ruflo-console/hooks/data/wf-targets.tsnew file mode 100644index 0000000000..092ef20704--- /dev/null+++ b/plugins/ruflo-console/hooks/data/wf-targets.ts@@ -0,0 +1,178 @@+/**+ * Who the console can talk to (ADR-465). Pure: what the session and the stores hold, and what the person configured, in; a list of targets+ * out. Every target declares its transport, WHAT LEAVES THE MACHINE, its cost class and HOW A REPLY ARRIVES, so the composer and the confirm+ * card say it before anything is sent. A target that is not configured is not listed as if it were: an absent one is an honest empty state.+ *+ * The configuration is one option string, entries separated by `;` (nothing in it is a secret: a key is named by its environment variable):+ * endpoint:<name>=<base-url>|<KEY_ENV>|<model> an OpenAI-compatible chat endpoint (OpenRouter, the meta-llm gateway, a local server)+ * bbs:<room> an agentbbs room (federation_bbs_publish / federation_bbs_watch)+ * x:<channel> an x-federation channel (pub:<name> or prv:<16 hex>)+ * OpenRouter is always offered as `openrouter` (https://openrouter.ai/api/v1, OPENROUTER_API_KEY) while no entry of that name replaces it.+ */+export type TransportKind = 'prompt' | 'send-message' | 'hive' | 'task' | 'bbs' | 'x-channel' | 'peer' | 'codex' | 'http'+export type Leaves = 'machine' | 'tailnet' | 'internet'+export type CostClass = 'session-turn' | 'free' | 'metered' | 'peer-session' | 'local-cli'+export type Arrival = 'turn' | 'immediate' | 'polled' | 'none'++export type Target = {+ id: string+ label: string+ transport: TransportKind+ /** What leaves this machine, in words. */+ leavesText: string+ leaves: Leaves+ cost: CostClass+ costText: string+ arrival: Arrival+ arrivalText: string+ /** Transport details: an agent id, a peer host, a channel id, an endpoint's name. */+ ref: string+}++export type Endpoint = { name: string; baseUrl: string; keyEnv: string; model: string }++export type Config = { endpoints: Endpoint[]; rooms: string[]; channels: string[]; errors: string[] }++export const OPENROUTER: Endpoint = { name: 'openrouter', baseUrl: 'https://openrouter.ai/api/v1', keyEnv: 'OPENROUTER_API_KEY', model: 'openrouter/auto' }++const NAME = /^[a-z][a-z0-9-]{1,23}$/+const ENV_NAME = /^[A-Z_][A-Z0-9_]{0,63}$/+const ROOM = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/+const CHANNEL = /^(pub:[a-z0-9][a-z0-9._-]{0,63}|prv:[0-9a-f]{16})$/+const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,80}$/+export const HOST = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/++/** True for an http(s) base URL with no credentials, query or fragment in it, and only https unless it is a local or tailnet address. */+export function isBaseUrl(value: string): boolean {+ let url: URL++ try {+ url = new URL(value)+ } catch {+ return false+ }++ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') return false+ if (url.protocol === 'https:') return true++ return url.protocol === 'http:' && /^(localhost|127\.0\.0\.1|\[::1\]|[a-z0-9-]+|100\.\d+\.\d+\.\d+|[a-z0-9.-]+\.ts\.net)$/i.test(url.hostname)+}++/** The option string as targets: each bad entry is dropped with a reason (never thrown), so one typo does not hide the rest. */+export function parseConfig(value: string | undefined): Config {+ const config: Config = { endpoints: [], rooms: [], channels: [], errors: [] }++ for (const entry of (value ?? '').split(';').map(part => part.trim()).filter(part => part !== '').slice(0, 24)) {+ const at = entry.indexOf(':')+ const kind = entry.slice(0, at)+ const rest = entry.slice(at + 1)++ if (kind === 'endpoint') {+ const eq = rest.indexOf('=')+ const [baseUrl = '', keyEnv = '', model = ''] = rest.slice(eq + 1).split('|').map(part => part.trim())+ const name = rest.slice(0, Math.max(eq, 0)).trim()++ if (eq < 0 || !NAME.test(name)) config.errors.push(`endpoint "${entry.slice(0, 30)}": the name is a lowercase word (endpoint:<name>=<base-url>|<KEY_ENV>|<model>)`)+ else if (!isBaseUrl(baseUrl)) config.errors.push(`endpoint ${name}: the base URL must be https (or http to a local or tailnet address), with no credentials, query or fragment`)+ else if (keyEnv !== 'NONE' && !ENV_NAME.test(keyEnv)) config.errors.push(`endpoint ${name}: the key is named by an environment variable (UPPER_SNAKE), or NONE; a key itself is never accepted here`)+ else if (!MODEL.test(model)) config.errors.push(`endpoint ${name}: no model named`)+ else if (config.endpoints.some(held => held.name === name)) config.errors.push(`endpoint ${name}: named twice`)+ else config.endpoints.push({ name, baseUrl: baseUrl.replace(/\/+$/, ''), keyEnv, model })+ } else if (kind === 'bbs' && ROOM.test(rest)) config.rooms.push(rest)+ else if (kind === 'x' && CHANNEL.test(rest)) config.channels.push(rest)+ else config.errors.push(`"${entry.slice(0, 40)}" is not endpoint:, bbs: or x: with a valid value`)+ }++ return config+}++/** The endpoints with OpenRouter defaulted in, unless the person named their own `openrouter`. */+export const endpointsOf = (config: Config): Endpoint[] => (config.endpoints.some(held => held.name === OPENROUTER.name) ? config.endpoints : [...config.endpoints, OPENROUTER])++export type PeerRef = { host: string; trusted: boolean }++/** The peers in the federation helper's `peers.json` (`peers[].host` and `.trusted`); anything else is dropped. */+export function peersOf(text: string | null): PeerRef[] {+ if (text === null) return []++ try {+ const list = (JSON.parse(text) as { peers?: unknown }).peers++ return Array.isArray(list) ? list.flatMap(item => (typeof item === 'object' && item !== null && typeof (item as { host?: unknown }).host === 'string' && HOST.test((item as { host: string }).host) ? [{ host: (item as { host: string }).host, trusted: (item as { trusted?: unknown }).trusted === true }] : [])).slice(0, 40) : []+ } catch {+ return []+ }+}++export type AgentRef = { id: string; name: string }++export type TargetInput = { agents: readonly AgentRef[]; peers: readonly PeerRef[]; config: Config; hasHive: boolean; hasCodex: boolean }++const mention = (value: string): string => value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24)++/** Every target the console can address now, in a stable order: the main session, then agents, the hive, channels, peers, Codex and endpoints. */+export function targetsOf(input: TargetInput): Target[] {+ const out: Target[] = [+ { id: 'claude', label: 'Claude (this session)', transport: 'prompt', leaves: 'machine', leavesText: 'nothing beyond what a turn of this session sends to the model', cost: 'session-turn', costText: 'a visible turn of this session, billed as any turn is', arrival: 'turn', arrivalText: 'its answer is the next turn in the transcript, not captured here', ref: 'main' },+ ]++ for (const agent of input.agents.slice(0, 20)) {+ const id = mention(agent.name)++ if (id !== '' && !out.some(held => held.id === id)) out.push({ id, label: `agent ${agent.name}`, transport: 'send-message', leaves: 'machine', leavesText: 'nothing: queued inside this session', cost: 'session-turn', costText: 'the agent\'s own next turn', arrival: 'none', arrivalText: 'queued for its next tool round; its answer is not routed back here', ref: agent.id })+ }++ if (input.hasHive) out.push({ id: 'hive', label: 'ruflo hive-mind', transport: 'hive', leaves: 'machine', leavesText: 'nothing: written to the hive\'s shared memory', cost: 'free', costText: 'no model call', arrival: 'none', arrivalText: 'appended to the hive memory; a worker sees it only if its own turn reads it (a proposal needs votes)', ref: 'hive' })++ if (input.hasHive) out.push({ id: 'hive-propose', label: 'ruflo hive consensus (a proposal)', transport: 'hive', leaves: 'machine', leavesText: 'nothing: a proposal in the hive state', cost: 'free', costText: 'no model call', arrival: 'none', arrivalText: 'workers vote on it; a pass binds no agent', ref: 'propose' })++ out.push({ id: 'task', label: 'ruflo task note', transport: 'task', leaves: 'machine', leavesText: 'nothing: written to the task store', cost: 'free', costText: 'no model call', arrival: 'none', arrivalText: 'the task record changes; an agent sees it only when it reads the task', ref: 'task' })++ for (const room of input.config.rooms) out.push({ id: `bbs-${mention(room)}`, label: `agentbbs room ${room}`, transport: 'bbs', leaves: 'machine', leavesText: 'a message in the room log on this machine, and to its peers if the room syncs', cost: 'free', costText: 'no model call', arrival: 'polled', arrivalText: 'read back with federation_bbs_watch while the thread is open', ref: room })++ for (const channel of input.config.channels) out.push({ id: `x-${mention(channel.replace(':', '-'))}`, label: `x channel ${channel}`, transport: 'x-channel', leaves: 'internet', leavesText: `a message to the relay (${channel.startsWith('prv:') ? 'encrypted under the channel key' : 'PUBLIC: anyone can read it'}) signed with your key`, cost: 'free', costText: 'no model call', arrival: 'polled', arrivalText: 'read back with x_federation_channel_read while the thread is open', ref: channel })++ for (const peer of input.peers) out.push({ id: `peer-${mention(peer.host)}`, label: `peer ${peer.host}${peer.trusted ? '' : ' (not trusted: needs your confirm)'}`, transport: 'peer', leaves: 'tailnet', leavesText: `the prompt, over ssh to ${peer.host}, run as \`claude -p\` there with that machine's own permissions and files`, cost: 'peer-session', costText: `a headless Claude run on ${peer.host}, billed to that machine's login`, arrival: 'immediate', arrivalText: 'the peer\'s stdout comes back when it finishes (up to 10 minutes)', ref: peer.host })++ if (input.hasCodex) out.push({ id: 'codex', label: 'Codex (codex exec, read-only)', transport: 'codex', leaves: 'internet', leavesText: 'the prompt, to OpenAI via the codex CLI, run in a read-only sandbox here', cost: 'local-cli', costText: 'the codex CLI\'s own login; its usage is not read here', arrival: 'immediate', arrivalText: 'its final message comes back when it finishes (up to 5 minutes)', ref: 'codex' })++ for (const endpoint of endpointsOf(input.config)) out.push({ id: endpoint.name, label: `${endpoint.name} (${endpoint.model})`, transport: 'http', leaves: endpoint.baseUrl.startsWith('https://') ? 'internet' : 'machine', leavesText: `the prompt, to ${new URL(endpoint.baseUrl).host}${endpoint.keyEnv === 'NONE' ? ' with no key' : `, with the key from $${endpoint.keyEnv} (never shown or stored)`}`, cost: 'metered', costText: 'metered by the provider; the tokens it reports are shown, a price is not guessed', arrival: 'immediate', arrivalText: 'the answer comes back in the same request', ref: endpoint.name })++ return out+}++export type Mentions = { targets: Target[]; unknown: string[]; body: string }++/** `@name` words at the start or after a space pick targets (`@all` picks the agents, the hive and the rooms: what stays on this machine; anything that leaves it is named); the rest is the body. */+export function parseMentions(text: string, targets: readonly Target[]): Mentions {+ const picked: Target[] = []+ const unknown: string[] = []+ const kept: string[] = []++ for (const word of text.trim().split(/\s+/)) {+ const match = /^@([A-Za-z0-9][A-Za-z0-9-]{0,31})$/.exec(word)++ if (match === null) {+ kept.push(word)+ continue+ }++ const name = (match[1] ?? '').toLowerCase()+ const found = targets.find(target => target.id === name)++ if (name === 'all') {+ for (const target of targets.filter(held => held.leaves === 'machine' && ['send-message', 'hive', 'bbs'].includes(held.transport))) if (!picked.includes(target)) picked.push(target)++ continue+ }++ if (found !== undefined) {+ if (!picked.includes(found)) picked.push(found)+ } else unknown.push(name)+ }++ return { targets: picked.slice(0, MAX_FANOUT), unknown, body: kept.join(' ').trim() }+}++/** At most this many targets get one question: a longer list is cut, and the composer says so. */+export const MAX_FANOUT = 6diff --git a/plugins/ruflo-console/hooks/host.ts b/plugins/ruflo-console/hooks/host.tsindex dcde03087d..d88d666be4 100644--- a/plugins/ruflo-console/hooks/host.ts+++ b/plugins/ruflo-console/hooks/host.ts@@ -56,4 +56,17 @@ export type Host = {listCommands: () => Promise<string[]>/** Runs a slash command as if typed (built-in, plugin or MCP); queued until the session is idle. */runSlash: (command: string, args: string) => Promise<{ text?: string } | void>+ /**+ * Calls an engine tool as the session would ($.tool.call: every hook, the permission check and its dialog, then the tool), from a clock tick+ * (a tool call waits on the turn). A refusal comes back as `deny`, a failure as `isError`; a missing tool or an aborted call rejects.+ * Optional: a build that does not bind it makes the control actions fall back to a prompt-box prefill (ADR-465).+ */+ toolCall?: (input: { tool: string } & Record<string, unknown>) => Promise<ToolReply>+ /** The engine's permission verdict for a tool call now, with nothing run and no dialog ($.tool.check). */+ toolCheck?: (tool: string, input: unknown) => Promise<{ decision: 'allow' | 'ask' | 'deny'; reason?: string }>+ /** A request with a method, headers and a text body through the host (the OpenAI-compatible targets); the key rides a header and is never logged. */+ httpSend?: (url: string, init: { method: string; headers: Record<string, string>; body: string }) => Promise<{ ok: boolean; status: number; text: string }>}++/** What a tool call answered: the refusal, or the output (text and structure) and whether it was an error. */+export type ToolReply = { deny?: string; text?: string; result?: unknown; isError?: boolean }diff --git a/plugins/ruflo-console/hooks/register.ts b/plugins/ruflo-console/hooks/register.tsindex fd1d69501b..4507b8fede 100644--- a/plugins/ruflo-console/hooks/register.ts+++ b/plugins/ruflo-console/hooks/register.ts@@ -112,6 +112,17 @@ function hostOf($: EngineInterface, cwd: string): Host {$.clock.after(1, () => void $.command.run({ command, args }).then(resolve, reject))}),listCommands: async () => (await $.command.list()).map(command => command.name),+ // ADR-465. A tool call waits on the turn like submitPrompt, so it starts from a clock tick, never inside the hook that asked.+ toolCall: input =>+ new Promise((resolve, reject) => {+ $.clock.after(1, () => void $.tool.call(input as never).then(reply => resolve(reply as never), reject))+ }),+ toolCheck: async (tool, input) => $.tool.check({ tool, input }),+ httpSend: async (url, init) => {+ const response = await $.http.fetch(url, init)++ return { ok: response.ok, status: response.status, text: response.text }+ },}}