Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion catalog.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"fr": "Lire, modifier et vérifier la scène Houdini ouverte depuis toute conversation OpenCode, avec un panneau facultatif dans Houdini."
},
"app": { "name": "Houdini", "versions": ">=21.0" },
"host": { "protocol": 1, "range": "^0.3.0" },
"host": { "protocol": 1, "range": "^0.3.1" },
"docs": "https://github.com/NeuralNomadsAI/opencode-integrations/blob/main/integrations/houdini/plugin/README.md",
"status": "preview",
"sources": { "git": ["github:NeuralNomadsAI/opencode-integrations#main::path:integrations/houdini/plugin"] }
Expand Down
2 changes: 1 addition & 1 deletion integrations/houdini/host/manifest.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "name": "OpenCode Link", "version": "0.3.0", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" }
{ "name": "OpenCode Link", "version": "0.3.1", "protocol": 1, "license": "MIT", "appVersions": ">=21.0" }
2 changes: 1 addition & 1 deletion integrations/houdini/plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ A call that outlasts its wait says whether Houdini still runs it (OpenCode Link

## The OpenCode Link panel

The **OpenCode Link** Python panel is a conversation inside Houdini. **Connect** attaches the panel's conversation to this Houdini's own offer, taking back the conversation it had for this file; **New** starts another. Closing the panel releases its conversation only: Houdini stays offered and other conversations attached to it keep it. Both write to the same scene, each change checked against its revision. Node.js is found on `PATH`; `NEURALNOMADS_HOUDINI_NODE` names another one.
The **OpenCode Link** Python panel is a conversation inside Houdini. **Connect** attaches the panel's conversation to this Houdini's own offer, taking back the conversation it had for this file; **New** starts another. Closing the panel releases its conversation only: Houdini stays offered and other conversations attached to it keep it. The panel and other conversations (CodeNomad's, for instance) can be attached to the same Houdini together; both write to the same scene, each change checked against its revision. The panel's conversation lives in its project folder: the first Connect there waits while OpenCode opens that folder and loads its plugins. A failed Connect says which step failed and why. Node.js is found on `PATH`; `NEURALNOMADS_HOUDINI_NODE` names another one.

## Limits

Expand Down
Binary file not shown.
8 changes: 4 additions & 4 deletions integrations/houdini/plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@neuralnomads/opencode-houdini",
"version": "0.3.0",
"version": "0.3.1",
"description": "OpenCode for Houdini: read, change and check the open Houdini scene from any OpenCode conversation, with an optional panel inside Houdini.",
"license": "MIT",
"type": "module",
Expand Down Expand Up @@ -61,10 +61,10 @@
"host": {
"app": "houdini",
"protocol": 1,
"range": "^0.3.0",
"range": "^0.3.1",
"appVersions": ">=21.0",
"payload": "host/houdini/opencode_link-0.3.0.zip",
"sha256": "af455684d246060085779f53937e36aabb4c3ce41d146a2a28ec2cd2c1baade7"
"payload": "host/houdini/opencode_link-0.3.1.zip",
"sha256": "7efd8d521a82d7e409251ae89ad6390bfcf99cb85af72b64aa5ead05321a7aa0"
}
}
}
65 changes: 65 additions & 0 deletions integrations/houdini/plugin/src/sidecar-steps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// The panel's Connect steps that do not need OpenCode's client (sidecar.ts): finding this Houdini's offer while the
// service opens the panel's Location, and an error that says which step failed, safe to show in the panel.

// A message of the sidecar's own, safe to show in the panel.
export class PanelError extends Error {}

// How long Connect waits for this Houdini's own offer (it offers itself every 5 s from its start), and for a
// Location OpenCode opens for the panel to load its plugins (tens of seconds in a trial).
export const OFFER_WAIT_MS = 30_000

// An error in one line for the panel: its first line, bounded, without a token, an authorization or a port.
export function briefly(error: unknown) {
const text = String((error as { message?: unknown } | null)?.message ?? error ?? "unknown error")
.split(/\r?\n/)[0]
?.replace(/\b[0-9a-f]{32,}\b/gi, "…")
.replace(/(basic|bearer)\s+\S+/gi, "$1 …")
.replace(/\b(port\s+|:)\d{2,5}\b/gi, "$1…")
.slice(0, 240)
return `${text || "unknown error"}${/[.!?]$/.test(text ?? "") ? "" : "."}`
}

// A failed Connect says which step failed and why, in a line (never a credential): the user knows what to check.
export async function step<T>(doing: string, work: () => Promise<T>): Promise<T> {
try {
return await work()
} catch (error) {
if (error instanceof PanelError) throw error
throw new PanelError(
`Connect failed while ${doing}: ${briefly(error)} Check that OpenCode runs, then choose Connect.`,
)
}
}

type Offer = { label: string; offerID: string }

// This Houdini's offer: the one with its label among the offered hosts (Houdini offers itself; the panel never).
export async function findOffer(
hosts: () => Promise<{ offers?: unknown } | undefined>,
label: string,
wait = { ms: OFFER_WAIT_MS, sleep: (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)) },
): Promise<Offer> {
const until = Date.now() + wait.ms
for (;;) {
let result: { offers?: unknown } | undefined
try {
result = await hosts()
} catch (error) {
// The first call in the panel's folder: OpenCode opens that Location and loads its plugins meanwhile, and the
// integration's RPC is not there yet (a CodeNomad conversation's own Location is long loaded).
if (!/RPC is unavailable/i.test(String((error as { message?: unknown })?.message ?? error)) || Date.now() > until)
throw error
await wait.sleep(1_000)
continue
}
const offers = ((result?.offers ?? []) as Offer[]).filter((offer) => offer.label === label)
if (offers.length > 1)
throw new PanelError(`Several Houdinis offer ${label}: attach this conversation from OpenCode (houdini_hosts).`)
if (offers[0]) return offers[0]
if (Date.now() > until)
throw new PanelError(
"This Houdini does not offer itself to OpenCode (OPENCODE_HOUDINI_OFFER=0, or OpenCode Link not started).",
)
await wait.sleep(1_000)
}
}
48 changes: 16 additions & 32 deletions integrations/houdini/plugin/src/sidecar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { OpenCode } from "@opencode/client"
import { Service } from "@opencode/client/service"
import { rpcDefinition } from "../../../../packages/integration-kit/src/contract.ts"
import { requestHost } from "../../../../packages/integration-kit/src/host-client.ts"
import { briefly, findOffer, PanelError, step } from "./sidecar-steps.ts"

type Channel = {
id: string
Expand All @@ -30,16 +31,10 @@ const options = (c: { directory: string }) => ({
location: { directory: c.directory },
signal: AbortSignal.timeout(3000),
})
// A message of this sidecar's own, safe to show in the panel (SDK and host errors never are).
class PanelError extends Error {}

// How long Connect waits for this Houdini's own offer (it offers itself every 5 s from its start).
const OFFER_WAIT_MS = 8_000

async function api() {
if (client) return client
const endpoint = await Service.discover()
if (!endpoint) throw new Error("Start OpenCode before connecting the panel.")
if (!endpoint) throw new PanelError("Start OpenCode before connecting the panel.")
client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) })
rpc = client.rpc(rpcDefinition("neuralnomads.houdini", "native") as never) as unknown as Rpc
return client
Expand Down Expand Up @@ -69,25 +64,6 @@ function rememberSession(file: string, key: string, session: string, directory:
}
}

// This Houdini's offer: the one with its label among the offered hosts (Houdini offers itself; the panel never).
async function findOffer(c: { directory: string; label: string }) {
const until = Date.now() + OFFER_WAIT_MS
for (;;) {
const result = await rpc.hosts?.({}, options(c))
const offers = ((result?.offers ?? []) as Array<{ label: string; offerID: string }>).filter(
(offer) => offer.label === c.label,
)
if (offers.length > 1)
throw new PanelError(`Several Houdinis offer ${c.label}: attach this conversation from OpenCode (houdini_hosts).`)
if (offers[0]) return offers[0]
if (Date.now() > until)
throw new PanelError(
"This Houdini does not offer itself to OpenCode (OPENCODE_HOUDINI_OFFER=0, or OpenCode Link not started).",
)
await new Promise((resolve) => setTimeout(resolve, 1_000))
}
}

async function attached(c: Channel) {
const read = await rpc.bindingRead?.({ sessionID: c.sessionID }, options(c))
return read?.state === "attached" && (read.binding as { label?: string } | undefined)?.label === c.label
Expand Down Expand Up @@ -132,7 +108,7 @@ async function stream(c: Channel) {
}

async function connect(id: string, params: Record<string, unknown>, fresh: boolean) {
const service = await api()
const service = await step("reaching OpenCode", api)
const previous = channels.get(id)
if (previous) await close(previous)
if (params.host !== "127.0.0.1" || !Number.isInteger(params.port) || !/^[0-9a-f]{64}$/.test(String(params.token)))
Expand Down Expand Up @@ -160,7 +136,11 @@ async function connect(id: string, params: Record<string, unknown>, fresh: boole
}
if (!sessionID) {
const label = String(params.script_name || "Houdini")
sessionID = (await service.session.create({ title: `Houdini: ${label}`, location: { directory } })).id
sessionID = (
await step("creating this file's conversation", () =>
service.session.create({ title: `Houdini: ${label}`, location: { directory } }),
)
).id
}
const c: Channel = {
id,
Expand All @@ -173,8 +153,12 @@ async function connect(id: string, params: Record<string, unknown>, fresh: boole
pending: false,
}
try {
const offer = await findOffer(c)
const result = await rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c))
const offer = await step("finding this Houdini's offer", () =>
findOffer(async () => rpc.hosts?.({}, options(c)), c.label),
)
const result = await step("attaching the conversation to this Houdini", async () =>
rpc.attachHost?.({ offerID: offer.offerID, sessionID: c.sessionID }, options(c)),
)
if (result?.outcome !== "attached") throw new PanelError("Houdini attachment was refused.")
rememberSession(store, key, c.sessionID, c.directory)
channels.set(id, c)
Expand Down Expand Up @@ -241,15 +225,15 @@ async function dispatch(request: Request) {
}
send({ id: request.id, result: {} })
} catch (error) {
// Never forward SDK/host errors: their details can include credentials or endpoints.
// SDK and host errors in one line, without credentials or endpoints (briefly).
send({
channel: request.channel,
event: "error",
data: {
message:
error instanceof PanelError
? error.message
: "Connection or action failed. Check OpenCode and Houdini, then choose Connect.",
: `The panel action failed: ${briefly(error)} Check that OpenCode runs, then choose Connect.`,
},
})
send({ id: request.id, error: { message: "Panel action failed." } })
Expand Down
89 changes: 89 additions & 0 deletions integrations/houdini/test/sidecar-steps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// The panel's Connect (sidecar.ts): its first call in a folder OpenCode is still opening waits for that Location's
// plugins ("RPC is unavailable"), and a failed Connect says which step failed and why, without a credential. Gaffer
// trial: the first Connect failed with "Connection or action failed" next to a CodeNomad conversation attached to
// the same application, and was read as that conversation holding it.

import assert from "node:assert/strict"
import { it } from "node:test"

import { briefly, findOffer, PanelError, step } from "../plugin/src/sidecar-steps.ts"

const TOKEN = "a".repeat(64)
const offers = { offers: [{ offerID: "offer_shot", label: "Houdini: shot.hipnc" }] }

it("Connect waits while OpenCode opens the panel's folder, then finds this Houdini's offer", async () => {
let calls = 0
const slept: number[] = []
const offer = await findOffer(
async () => {
calls += 1
if (calls <= 2) throw new Error("RPC is unavailable: neuralnomads.houdini")
return offers
},
"Houdini: shot.hipnc",
{ ms: 30_000, sleep: async (ms) => void slept.push(ms) },
)
assert.equal(offer.offerID, "offer_shot")
assert.equal(calls, 3)
assert.deepEqual(slept, [1_000, 1_000])
})

it("another error, or an RPC still unavailable at the deadline, ends the search", async () => {
await assert.rejects(
findOffer(async () => Promise.reject(new Error("socket hang up")), "Houdini: shot.hipnc", {
ms: 30_000,
sleep: async () => {},
}),
/socket hang up/,
)
await assert.rejects(
findOffer(
async () => Promise.reject(new Error("RPC is unavailable: neuralnomads.houdini")),
"Houdini: shot.hipnc",
{
ms: -1,
sleep: async () => {},
},
),
/RPC is unavailable/,
)
await assert.rejects(
findOffer(async () => ({ offers: [...offers.offers, ...offers.offers] }), "Houdini: shot.hipnc", {
ms: -1,
sleep: async () => {},
}),
(error: Error) => error instanceof PanelError && /^Several Houdinis offer Houdini: shot\.hipnc/.test(error.message),
)
})

it("a failed Connect says which step failed and why, without a credential", async () => {
await assert.rejects(
step("finding this Houdini's offer", async () => {
throw new Error("RPC is unavailable: neuralnomads.houdini")
}),
(error: Error) =>
error instanceof PanelError &&
error.message ===
"Connect failed while finding this Houdini's offer: RPC is unavailable: neuralnomads.houdini. Check that OpenCode runs, then choose Connect.",
)
await assert.rejects(
step("creating this file's conversation", async () => {
throw new Error(`refused by 127.0.0.1:4096 with Basic ${TOKEN} on port 51396\n at stack`)
}),
(error: Error) => {
assert.equal(
error.message,
"Connect failed while creating this file's conversation: refused by 127.0.0.1:… with Basic … on port …. Check that OpenCode runs, then choose Connect.",
)
return true
},
)
// The panel's own messages pass as they are.
await assert.rejects(
step("reaching OpenCode", async () => {
throw new PanelError("Start OpenCode before connecting the panel.")
}),
(error: Error) => error instanceof PanelError && error.message === "Start OpenCode before connecting the panel.",
)
assert.equal(briefly(new Error(`token ${TOKEN}`)), "token ….")
})
Loading