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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,5 @@ Keep the same operation key and body after an uncertain response. Channel creati
Organization member invitations (UAT slice): [API, CLI, recovery and verification status](docs/organization-invitations.md). Use `invite send/list/revoke` from the selected owner's workspace, and `invite inbox/accept` from the recipient's own authenticated account. After acceptance, select the organization with `org use`.

Direct channel guests (next UAT candidate): [isolated guest grants, CLI and acceptance](docs/channel-guests.md). `channel-invite` manages invitations; `guest-channel` opens only accepted channels without joining their organization. This initial path uses the existing user's in-app inbox, with no email delivery claim.

Agent interaction contract and CLI: [Channel Agents](docs/channel-agents.md).
47 changes: 47 additions & 0 deletions apps/cli/lib/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
import { dirname, isAbsolute, resolve } from "node:path";
import { ClientError } from "../../../packages/contracts/instance.ts";
import { parseAgentCredential } from "../../../packages/contracts/agent.ts";
import { checkDiscovery, request, responseJson } from "../../../packages/client/connection.ts";

export function readAgentFile(path: string) {
if (!isAbsolute(path) || typeof process.getuid !== "function") throw new ClientError("PRIVATE_CREDENTIAL_FILE_REQUIRED");
for (let p = resolve(path);; p = dirname(p)) {
if (lstatSync(p).isSymbolicLink()) throw new ClientError("SYMLINK_REFUSED");
if (p === dirname(p)) break;
}
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
try {
const s = fstatSync(fd);
if (!s.isFile() || s.uid !== process.getuid() || (s.mode & 0o077) || s.size > 20000) throw new ClientError("PRIVATE_CREDENTIAL_FILE_REQUIRED");
return parseAgentCredential(JSON.parse(readFileSync(fd, "utf8")));
} finally { closeSync(fd); }
}
export async function agentCommand(args: string[], signal?: AbortSignal) {
const command = args[1]; const options: Record<string, string> = {};
if (!["history", "send"].includes(command)) throw new ClientError("USAGE");
for (let n = 2; n < args.length; n += 2) {
if (!["--credential-file", "--after", "--text-file", "--operation"].includes(args[n]) || args[n+1] === undefined || options[args[n]] !== undefined) throw new ClientError("USAGE");
options[args[n]] = args[n+1];
}
if (!options["--credential-file"]) throw new ClientError("USAGE");
const credential = readAgentFile(options["--credential-file"]);
const { config, actorId, channelId, secret } = credential;
await checkDiscovery(config, signal);
const headers = { Authorization: "Bearer tob_agent_" + actorId + "." + secret, "Content-Type": "application/json" };
const base = config.server + "/api/agent-channels/" + channelId + "/messages";
let response: Response;
if (command === "history") response = await request(base + "?after=" + encodeURIComponent(options["--after"] ?? "0"), { headers }, signal);
else {
if (!options["--text-file"] || !/^[A-Za-z0-9_-]{16,100}$/.test(options["--operation"] ?? "")) throw new ClientError("USAGE");
let text: string; try { text = readFileSync(options["--text-file"], "utf8"); } catch { throw new ClientError("MESSAGE_FILE_UNREADABLE"); }
if (!text.trim() || text.length > 4000) throw new ClientError("INVALID_CHANNEL_INPUT");
response = await request(base, { method: "POST", headers: { ...headers, "Idempotency-Key": options["--operation"] }, body: JSON.stringify({ text }) }, signal);
}
const value = await responseJson(response);
if (!response.ok) {
const code = (value.error as { code?: unknown })?.code;
throw new ClientError(typeof code === "string" && /^[A-Z_]{1,80}$/.test(code) ? code : "AGENT_UNAVAILABLE");
}
return value;
}
33 changes: 31 additions & 2 deletions apps/cli/lib/commands.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { randomBytes } from "node:crypto";
import { agentCommand } from "./agent.ts";
import { setTimeout as sleep } from "node:timers/promises";
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
Expand Down Expand Up @@ -26,6 +28,7 @@ export async function execute(args: string[], rt: Runtime): Promise<unknown> {
for (const path of ["/healthz", "/readyz"]) { const r = await request(new URL(path, url).href); if (!r.ok) throw new ClientError("HEALTH_CHECK_FAILED"); outputs.push(await responseJson(r)); }
return { health: outputs[0], readiness: outputs[1] };
}
if (args[0] === "agent-channel") return agentCommand(args, rt.signal);
const store = new Store(rt.directory ?? join(homedir(), ".config/tob/cli"));
if (args[0] === "instance" && args[1] === "import" && (args.length === 3 || (args.length === 4 && args[3] === "--replace"))) {
const c = readImport(args[2]);
Expand All @@ -48,11 +51,12 @@ export async function execute(args: string[], rt: Runtime): Promise<unknown> {
const isInvitation = args[0] === "invite";
const isGuest = args[0] === "guest-channel";
const isGuestInvite = args[0] === "channel-invite";
const scoped = isOrg || isChannel || isInvitation || isGuest || isGuestInvite;
const isAgent = args[0] === "agent";
const scoped = isAgent || isOrg || isChannel || isInvitation || isGuest || isGuestInvite;
const orgCommand = scoped ? args[1] : undefined;
const options: Record<string, string> = {};
if (scoped) {
if (!(isOrg ? ["list", "create", "use", "show", "update"] : (isInvitation || isGuestInvite) ? ["inbox", "list", "send", "accept", "revoke"] : isGuest ? ["list", "show", "history", "send"] : ["list", "create", "show", "history", "send"]).includes(orgCommand ?? "")) throw new ClientError("USAGE");
if (!(isAgent ? ["list", "create", "revoke"] : isOrg ? ["list", "create", "use", "show", "update"] : (isInvitation || isGuestInvite) ? ["inbox", "list", "send", "accept", "revoke"] : isGuest ? ["list", "show", "history", "send"] : ["list", "create", "show", "history", "send"]).includes(orgCommand ?? "")) throw new ClientError("USAGE");
for (let n = 2; n < args.length; n += 2) {
if (!["--server", "--id", "--name", "--operation", "--description", "--version", "--after", "--org", "--text-file", "--email", "--channel"].includes(args[n]) || args[n+1] === undefined || options[args[n]] !== undefined) throw new ClientError("USAGE");
options[args[n]] = args[n+1];
Expand Down Expand Up @@ -145,6 +149,31 @@ export async function execute(args: string[], rt: Runtime): Promise<unknown> {
}
return value;
};
if (isAgent) {
const orgId = options["--org"] ?? i.organizationId;
const channelId = options["--channel"];
if (!orgId || !/^org_[A-Za-z0-9]+$/.test(orgId) || orgId !== i.organizationId) throw new ClientError("ORGANIZATION_TOKEN_REQUIRED");
if (!channelId || !/^ch_[a-f0-9]{64}$/.test(channelId)) throw new ClientError("INVALID_CHANNEL");
const base = "/" + orgId + "/channels/" + channelId + "/agents";
if (orgCommand === "list") return call(base + (options["--after"] ? "?after=" + encodeURIComponent(options["--after"]) : ""));
if (orgCommand === "revoke") {
if (!/^ag_[a-f0-9]{64}$/.test(options["--id"] ?? "")) throw new ClientError("INVALID_AGENT_INPUT");
return call(base + "/" + options["--id"] + "/revoke", { method: "POST" });
}
const name = options["--name"]?.trim(); const operationId = options["--operation"];
if (!name || name.length > 80 || /[\u0000-\u001f]/.test(name) || !/^[A-Za-z0-9_-]{16,100}$/.test(operationId ?? "")) throw new ClientError("INVALID_AGENT_INPUT");
const actorId = "ag_" + digest(JSON.stringify([channelId, i.userId, operationId]));
const localKey = JSON.stringify([binding, i.userId, channelId, operationId]);
let credential = store.agent(localKey);
if (credential && (credential.name !== name || credential.actorId !== actorId || credential.ownerUserId !== i.userId || credential.channelId !== channelId || credential.organizationId !== orgId || connectionKey(credential.config) !== connectionKey(c))) throw new ClientError("OPERATION_CONFLICT");
if (!credential) {
credential = { version: 1, config: c, organizationId: orgId, channelId, ownerUserId: i.userId, actorId, name, operationId: operationId!, secret: randomBytes(32).toString("hex") };
store.putAgent(localKey, credential);
}
const value = await call(base, { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": operationId! }, body: JSON.stringify({ name, secretHash: digest(credential.secret) }) });
if (value.actorId !== actorId || value.ownerUserId !== i.userId || value.name !== name || !["active", "revoked", "expired"].includes(String(value.state))) throw new ClientError("INVALID_AGENT_RESPONSE");
return { actorId, name, ownerUserId: i.userId, state: value.state, credentialFile: store.agentFile(localKey) };
}
if (isGuestInvite) {
const id = options["--id"];
if (orgCommand === "inbox") return call(options["--after"] ? "?after=" + encodeURIComponent(options["--after"]) : "", {}, "/api/channel-invitations");
Expand Down
6 changes: 5 additions & 1 deletion apps/cli/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdi
import { dirname, isAbsolute, join, resolve } from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { ClientError, parseInstance, type InstanceConfig } from "../../../packages/contracts/instance.ts";
import { parseAgentCredential, type AgentCredential } from "../../../packages/contracts/agent.ts";
export type Session = { version: 1; binding: string; userId: string | null; accessToken: string; refreshToken: string };
export const digest = (text: string) => createHash("sha256").update(text).digest("hex");
export class Store {
Expand All @@ -16,7 +17,7 @@ export class Store {
}
mkdirSync(this.root, { recursive: true, mode: 0o700 });
this.check(this.root, true);
for (const d of ["instances", "sessions", "locks"]) { mkdirSync(join(this.root, d), { recursive: true, mode: 0o700 }); this.check(join(this.root, d), true); }
for (const d of ["instances", "sessions", "locks", "agents"]) { mkdirSync(join(this.root, d), { recursive: true, mode: 0o700 }); this.check(join(this.root, d), true); }
}
private check(path: string, directory = false) {
const s = lstatSync(path);
Expand Down Expand Up @@ -60,6 +61,9 @@ export class Store {
try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); fsyncSync(fd); return await action(); }
finally { closeSync(fd); unlinkSync(path); }
}
agentFile(id: string) { return this.file("agents", id); }
agent(id: string) { const value = this.read(this.agentFile(id)); return value === undefined ? undefined : parseAgentCredential(value); }
putAgent(id: string, credential: AgentCredential) { this.write(this.agentFile(id), credential); }
configs(): InstanceConfig[] { return readdirSync(join(this.root, "instances")).filter(n => /^[a-f0-9]{64}\.json$/.test(n)).map(n => parseInstance(this.read(join(this.root, "instances", n)))); }
config(id: string) { const v = this.read(this.file("instances", id)); return v === undefined ? undefined : parseInstance(v); }
putConfig(c: InstanceConfig) { this.write(this.file("instances", c.instanceId), c); }
Expand Down
11 changes: 11 additions & 0 deletions apps/service/db/channel/migrations/0002_grey_strong_guy.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE TABLE `channel_agent` (
`actor_id` text PRIMARY KEY NOT NULL,
`owner_user_id` text NOT NULL,
`owner_membership_id` text NOT NULL,
`name` text NOT NULL,
`secret_hash` text NOT NULL,
`active` integer NOT NULL,
`history_after` integer NOT NULL,
`created_at` text NOT NULL,
`expires_at` text NOT NULL
);
Loading
Loading