openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,894 lines • 70.6 kB
JavaScript
import { g as readStringValue } from "../../string-coerce-CCIiB4H7.mjs";
import { P as resolveIntegerOption } from "../../number-coercion-D6u-4YD8.mjs";
import { a as resolveGlobalSingleton } from "../../global-singleton-D7yf05nR.mjs";
import { l as isRecord, o as asRecord, t as asNonArrayRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { j as parseAgentSessionKey, x as isCronSessionKey } from "../../session-key-CqAyZeVk.mjs";
import { t as safeEqualSecret } from "../../secret-equal-BogABOFr.mjs";
import { n as jsonResult } from "../../tool-results-CcV0sxnb.mjs";
import { m as readToolStringParam } from "../../common-njQNtpnW.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../security-runtime-C-zE_Zy_.mjs";
import "../../number-runtime-W4chuk8B.mjs";
import { a as cardBoardId, c as cardRunId, et as redactClaimToken, g as latestRunningAttempt, l as cardSessionKey, nt as WORKBOARD_STATUSES, tt as redactDispatchResult } from "../../store-card-helpers-DOLHSumf.mjs";
import { a as MAX_CARDS } from "../../store-constants-CgovXEgF.mjs";
import "../../routing-DmgGYTrU.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../core-D4CovhmH.mjs";
import "../../api-DuZYQOsZ.mjs";
import { _ as resolveWorkboardAgentWorkspace, a as WorkboardStore, c as workboardCardSessionLookupKey, d as WORKBOARD_CARD_TOOL_NAMES, f as WORKBOARD_SESSIONS_BOARD_TOOL_NAMES, g as resolveCommandWorkboardWorkspaceAccess, h as resolveAgentWorkboardWorkspaceRuntime, i as dispatchAndStartWorkboardCards, l as cleanupWorkboardCardWorktree, m as guardWorkboardToolsForWorkspaceAccess, n as registerWorkboardStoreLifecycle, o as normalizeCappedStringList, p as canonicalizeWorkboardWorkspaceAccess, r as resolveWorkboardSqliteWorkerModuleUrl, s as workboardCardMatchesLifecycleLink, t as registerWorkboardGatewayMethods, u as isWorkboardWorktreeCleanupCandidate } from "../../runtime-api-BXfe8iY_.mjs";
import { t as resolveWorkboardCardByIdOrPrefix } from "../../card-lookup-DYBEzjOn.mjs";
import { randomUUID } from "node:crypto";
import { AsyncResource } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { Type } from "typebox";
//#region extensions/workboard/src/automation-nudge.ts
const WORKBOARD_AUTOMATION_NUDGE_DEBOUNCE_MS = 6e4;
const WORKBOARD_AUTOMATION_NUDGE_STATE_KEY = Symbol.for("openclaw.workboard.automationNudgeState");
function clearPendingBoardNudges(e) {
for (const t of e.pendingByBoard.values()) if (t) clearTimeout(t);
e.pendingByBoard.clear();
}
function getWorkboardAutomationNudgeState() {
return resolveGlobalSingleton(WORKBOARD_AUTOMATION_NUDGE_STATE_KEY, () => ({ pendingByBoard: /* @__PURE__ */ new Map() }), (e) => {
e.owner = void 0;
clearPendingBoardNudges(e);
});
}
function isCronOriginSession(e) {
const t = e?.trim();
return t?.startsWith("cron:") === true || isCronSessionKey(t);
}
function createWorkboardAutomationNudgeService(e) {
let t;
const nudgeBoard = async (e, t, n) => {
const r = getWorkboardAutomationNudgeState();
if (r.owner !== n || r.pendingByBoard.has(e)) return;
if (r.pendingByBoard.size >= 2e3) {
n.logger.warn(`workboard automation nudge skipped for board ${e}: debounce map full`);
return;
}
const i = performance.now() + WORKBOARD_AUTOMATION_NUDGE_DEBOUNCE_MS;
r.pendingByBoard.set(e, void 0);
try {
const r = n.getCron?.()?.enqueueRun;
if (!r) throw new Error("Workboard automation scheduler is unavailable");
const i = await r(t, "if-enabled");
if (!i.ok || "ran" in i && !i.ran) {
const r = "reason" in i ? i.reason : "not-run";
n.logger.warn(`workboard automation nudge skipped for board ${e}: job ${t} ${r}`);
return;
}
const a = "runId" in i ? i.runId : void 0;
n.logger.info(`workboard automation nudge requested for board ${e}: job ${t}${a ? ` run ${a}` : ""}`);
} catch (t) {
n.logger.warn(`workboard automation nudge failed for board ${e}: ${String(t)}`);
} finally {
if (r.owner === n) {
const t = setTimeout(() => r.pendingByBoard.delete(e), Math.max(0, i - performance.now()));
t.unref?.();
r.pendingByBoard.set(e, t);
}
}
};
return {
id: "workboard-automation-nudge",
start(e) {
const n = getWorkboardAutomationNudgeState();
clearPendingBoardNudges(n);
n.owner = t = {
logger: e.logger,
getCron: e.getCron
};
},
stop() {
const e = getWorkboardAutomationNudgeState();
if (e.owner !== t) return;
e.owner = t = void 0;
clearPendingBoardNudges(e);
},
async nudge(t) {
const n = getWorkboardAutomationNudgeState().owner;
if (!n || isCronOriginSession(t.sessionKey) || t.cards.length === 0) return;
try {
const r = new Map((await e.store.listBoards()).boards.flatMap((e) => e.automationJobId ? [[e.id, e.automationJobId]] : []));
const i = new Set(t.cards.map((e) => cardBoardId(e)));
await Promise.all([...i].flatMap((e) => {
const t = r.get(e);
return t ? [nudgeBoard(e, t, n)] : [];
}));
} catch (e) {
n.logger.warn(`workboard automation nudge failed: ${String(e)}`);
}
}
};
}
//#endregion
//#region extensions/workboard/src/change-events.ts
function createWorkboardChangeEventService(e) {
return {
id: "workboard-change-events",
async start(t) {
const n = t.gatewayEvents;
if (!n || e.onChange) return;
await e.ready();
e.onChange = (e) => {
n.emit("changed", e, { scope: "operator.read" });
};
e.announceChangeEpoch();
},
async stop() {
e.onChange = void 0;
}
};
}
//#endregion
//#region extensions/workboard/src/command.ts
const ADMIN_SCOPE = "operator.admin";
const WRITE_SCOPE = "operator.write";
function formatCardLine(e) {
const t = e.metadata?.automation?.boardId ?? "default";
const n = e.agentId ? ` @${e.agentId}` : "";
return `${e.id.slice(0, 8)} ${e.status.padEnd(8)} ${e.priority.padEnd(6)} [${t}]${n} ${e.title}`;
}
function formatCardDetails(e) {
const t = [
e.title,
`id: ${e.id}`,
`status: ${e.status}`,
`priority: ${e.priority}`,
`board: ${e.metadata?.automation?.boardId ?? "default"}`
];
if (e.agentId) t.push(`agent: ${e.agentId}`);
if (e.sessionKey) t.push(`session: ${e.sessionKey}`);
if (e.runId) t.push(`run: ${e.runId}`);
if (e.metadata?.archivedAt) t.push("archived: yes (excluded from dispatch)");
if (e.notes) t.push("", e.notes);
return t.join("\n");
}
function requireWriteAccess(e) {
const t = e.gatewayClientScopes;
if (t ? t.includes(ADMIN_SCOPE) || t.includes(WRITE_SCOPE) : e.senderIsOwner === true) return;
return {
text: `This command requires gateway scope: ${WRITE_SCOPE}.`,
isError: true
};
}
function registerWorkboardCommand(e) {
e.api.registerCommand({
name: "workboard",
description: "List, create, inspect, and dispatch Workboard cards.",
acceptsArgs: true,
exposeSenderIsOwner: true,
handler: async (t) => {
const n = e.api;
const r = e.store;
const i = t.args;
const a = t.senderIsOwner;
const o = t.gatewayClientScopes ? void 0 : t.assertOwnerCurrent;
const s = t.gatewayClientScopes;
const resolveAgentWorkspace = (e) => resolveWorkboardAgentWorkspace(t.config, e);
const resolveAgentWorkspaceRuntime = (n, r, i, a, o) => resolveAgentWorkboardWorkspaceRuntime({
config: t.config,
agentId: n,
sessionKey: r,
workspaceDir: i,
modelProvider: a,
modelId: o,
prepareSandboxWorkspaceAuthority: e.api.runtime.sandbox.prepareWorkspaceAuthority
});
const c = resolveCommandWorkboardWorkspaceAccess({
config: t.config,
agentId: t.agentId,
sessionKey: t.sessionKey,
gatewayClientScopes: t.gatewayClientScopes,
resolveSandboxWorkspaceAuthority: e.api.runtime.sandbox.resolveWorkspaceAuthority
});
const [l = "list", ...u] = (i ?? "").trim().split(/\s+/).filter(Boolean);
if (l === "help") return { text: [
"/workboard list",
"/workboard show <card-id>",
"/workboard create <title>",
"/workboard move <card-id> --status <status>",
"/workboard dispatch"
].join("\n") };
if (l === "list") {
const e = (await r.list()).filter((e) => !e.metadata?.archivedAt).slice(0, 12).map(formatCardLine);
return { text: e.length ? e.join("\n") : "No Workboard cards." };
}
if (l === "show" || l === "read") {
const e = u[0];
if (!e) return {
text: "Usage: /workboard show <card-id>",
isError: true
};
const t = await r.list();
const { card: n, error: i } = resolveWorkboardCardByIdOrPrefix(t, e);
return n ? { text: formatCardDetails(n) } : {
text: i,
isError: true
};
}
if (l === "create" || l === "move" || l === "dispatch") {
const e = requireWriteAccess({
senderIsOwner: a,
gatewayClientScopes: s
});
if (e) return e;
}
if (l === "create") {
const e = u.join(" ").trim();
if (!e) return {
text: "Usage: /workboard create <title>",
isError: true
};
const t = await canonicalizeWorkboardWorkspaceAccess(c ?? { unrestricted: true });
const n = await r.create({
title: e,
workspaceAccess: t
}, void 0, o);
return { text: `Created ${n.id.slice(0, 8)} ${n.title}` };
}
if (l === "move") {
const e = u[0];
const t = u.indexOf("--status");
const n = t >= 0 ? u[t + 1] : void 0;
if (!e || !n) return {
text: "Usage: /workboard move <card-id> --status <status>",
isError: true
};
if (!WORKBOARD_STATUSES.includes(n)) return {
text: `status must be one of: ${WORKBOARD_STATUSES.join(", ")}.`,
isError: true
};
const i = await r.list();
const { card: a, error: s } = resolveWorkboardCardByIdOrPrefix(i, e);
if (!a) return {
text: s,
isError: true
};
return { text: formatCardLine(await r.move(a.id, n, void 0, void 0, { assertOwnerCurrent: o })) };
}
if (l === "dispatch") {
const e = c ?? { unrestricted: true };
const t = await dispatchAndStartWorkboardCards({
store: r,
subagent: n.runtime.subagent,
worktrees: n.runtime.worktrees,
options: {
materializeWorktree: true,
resolveAgentWorkspace,
resolveAgentWorkspaceRuntime,
workspaceAccess: e,
assertOwnerCurrent: o
}
});
return { text: [
`dispatch: started=${t.started.length} failures=${t.startFailures.length} promoted=${t.promoted.length} blocked=${t.blocked.length}`,
...t.started.map((e) => `started ${e.cardId.slice(0, 8)} run=${e.runId}`),
...t.startFailures.map((e) => `failed ${e.cardId.slice(0, 8)} ${e.error}`)
].join("\n") };
}
return {
text: `Unknown Workboard action: ${l}`,
isError: true
};
}
});
}
//#endregion
//#region extensions/workboard/src/lifecycle-sync.ts
const WORKBOARD_LIFECYCLE_SWEEP_MS = 6e4;
const WORKBOARD_STALE_SESSION_MS = 18e5;
const WORKBOARD_SESSION_LOOKUP_LIMIT = 2;
const WORKBOARD_WORKTREE_CLEANUP_SWEEP_LIMIT = 32;
const workboardLifecycleGatewayState = resolveGlobalSingleton(Symbol.for("openclaw.workboard.lifecycleGatewayState"), () => ({ ready: false }), (e) => {
e.ready = false;
e.abortSignal = void 0;
e.readSessions = void 0;
});
function sessionProvesPreparedAcceptance(e) {
return e.hasActiveRun === true || e.status === "done" || e.status === "failed" || e.status === "killed" || e.status === "timeout";
}
function needsWorkboardLifecycleReconciliation(e, t) {
if (e.metadata?.archivedAt) return false;
const n = e.metadata?.claim;
const r = e.status === "review" || e.status === "blocked" || e.status === "done";
return Boolean(!r && (e.sessionKey || e.runId || e.execution) || e.status === "running" || e.execution?.status === "running" || latestRunningAttempt(e) || e.metadata?.automation?.launch?.phase === "prepared" || n && (!n.expiresAt || n.expiresAt > t) || e.metadata?.stale);
}
const LIFECYCLE_TARGETS = {
running: {
targetStatus: "running",
executionStatus: "running"
},
succeeded: {
targetStatus: "review",
executionStatus: "review"
},
failed: {
targetStatus: "blocked",
executionStatus: "blocked"
},
idle: {
targetStatus: void 0,
executionStatus: "idle"
},
stale: {
targetStatus: "running",
executionStatus: "running"
}
};
async function syncWorkboardLifecycleEvent(e) {
const t = (await e.store.list()).filter((t) => !t.metadata?.archivedAt && workboardCardMatchesLifecycleLink(t, e.source));
const n = Promise.all(t.map(async (t) => {
return await e.store.syncLifecycle(t.id, {
...LIFECYCLE_TARGETS[e.observation.state],
sourceUpdatedAt: e.observation.sourceUpdatedAt,
stale: e.observation.stale,
now: e.now,
...e.source.sessionKey ? { association: {
...cardSessionKey(t) ? { expectedSessionKey: cardSessionKey(t) } : {},
...cardRunId(t) ? { expectedRunId: cardRunId(t) } : {},
sessionKey: e.source.sessionKey,
...e.source.runId ? { runId: e.source.runId } : {},
acceptedAt: e.observation.sourceUpdatedAt ?? e.now
} } : {}
});
}));
await Promise.all([n, e.onMatched?.({
cards: t,
...e.source.sessionKey ? { sessionKey: e.source.sessionKey } : {}
})]);
return {
cards: t,
count: (await n).filter(Boolean).length
};
}
async function syncWorkboardSubagentEnded(e) {
const t = e.now ?? Date.now();
const n = await syncWorkboardLifecycleEvent({
store: e.store,
source: {
sessionKey: e.event.targetSessionKey,
runId: e.event.runId
},
observation: {
state: e.event.outcome === "ok" ? "succeeded" : "failed",
sourceUpdatedAt: e.event.endedAt ?? t
},
now: t,
...e.onMatched ? { onMatched: e.onMatched } : {}
});
if (e.worktrees) for (const t of n.cards) {
const n = await e.store.get(t.id);
if (n) await cleanupWorkboardCardWorktree({
store: e.store,
worktrees: e.worktrees,
card: n
});
}
return n.count;
}
async function syncWorkboardAgentEnded(e) {
const t = e.now ?? Date.now();
if (!e.context.sessionKey) return 0;
const n = (await e.readSessions({ sessionKey: e.context.sessionKey })).sessions.find((t) => t.key === e.context.sessionKey);
if (!n) return 0;
const r = lifecycleFromSession(n, t);
if (r.state !== "succeeded" && r.state !== "failed") return 0;
return (await syncWorkboardLifecycleEvent({
store: e.store,
source: {
sessionKey: e.context.sessionKey,
runId: e.event.runId ?? e.context.runId
},
observation: r,
now: t,
...e.onMatched ? { onMatched: e.onMatched } : {}
})).count;
}
function lifecycleFromSession(e, t) {
const n = e.updatedAt;
if (e.status === "running" && e.hasActiveRun === false && n !== void 0 && t - n >= WORKBOARD_STALE_SESSION_MS) return {
state: "stale",
sourceUpdatedAt: n,
stale: {
detectedAt: t,
lastSessionUpdatedAt: n,
reason: "Linked session has not reported recent activity."
}
};
if (e.hasActiveRun === true || e.status === "running") return {
state: "running",
sourceUpdatedAt: n
};
if (e.abortedLastRun || e.status === "failed" || e.status === "killed" || e.status === "timeout") return {
state: "failed",
sourceUpdatedAt: n
};
if (e.status === "done") return {
state: "succeeded",
sourceUpdatedAt: n
};
return {
state: "idle",
sourceUpdatedAt: n
};
}
function normalizeSession(e) {
if (!isRecord(e) || typeof e.key !== "string" || !e.key) return;
const t = e.status === "running" || e.status === "done" || e.status === "failed" || e.status === "killed" || e.status === "timeout" ? e.status : void 0;
return {
key: e.key,
...typeof e.updatedAt === "number" && Number.isFinite(e.updatedAt) ? { updatedAt: e.updatedAt } : {},
...t ? { status: t } : {},
...typeof e.hasActiveRun === "boolean" ? { hasActiveRun: e.hasActiveRun } : {},
...e.abortedLastRun === true ? { abortedLastRun: true } : {}
};
}
async function readWorkboardLifecycleSessions(e, t) {
if (!await e.isAvailable()) return {
sessions: [],
complete: false
};
if (parseAgentSessionKey(t.sessionKey)) {
const n = await e.request("sessions.describe", {
key: t.sessionKey,
includeDerivedTitles: false,
includeLastMessage: false
}, { scopes: ["operator.read"] });
if (!isRecord(n) || n.session !== null && !isRecord(n.session)) throw new Error("sessions.describe returned an invalid lifecycle snapshot");
const r = normalizeSession(n.session);
return {
sessions: r ? [r] : [],
complete: true
};
}
if (t.sessionKey.startsWith("subagent:workboard-")) {
const n = t.sweep ?? {};
n.agentIds ??= e.request("agents.list", {}, { scopes: ["operator.read"] }).then((e) => {
if (!isRecord(e) || !Array.isArray(e.agents)) throw new Error("agents.list returned an invalid ownership snapshot");
return e.agents.map((e) => {
if (!isRecord(e) || typeof e.id !== "string" || !e.id) throw new Error("agents.list returned an invalid agent identity");
return e.id;
});
});
const r = [];
for (const i of await n.agentIds) {
const n = await readWorkboardLifecycleSessions(e, { sessionKey: `agent:${i}:${t.sessionKey}` });
if (!n.complete) return {
sessions: [],
complete: false
};
r.push(...n.sessions);
}
return {
sessions: r,
complete: true
};
}
let n = false;
if (t.sessionKey === "unknown") {
const t = await e.request("agents.list", {}, { scopes: ["operator.read"] });
if (!isRecord(t) || typeof t.selectionRequired !== "boolean") throw new Error("agents.list returned an invalid ownership snapshot");
n = !t.selectionRequired;
}
const r = await e.request("sessions.list", {
source: "workboard-lifecycle",
rowMode: "compact",
search: t.sessionKey,
limit: WORKBOARD_SESSION_LOOKUP_LIMIT,
configuredAgentsOnly: true,
archived: "all",
includeGlobal: false,
includeUnknown: n
}, { scopes: ["operator.read"] });
if (!isRecord(r) || !Array.isArray(r.sessions)) throw new Error("sessions.list returned an invalid lifecycle snapshot");
const i = r.sessions.flatMap((e) => {
const t = normalizeSession(e);
return t ? [t] : [];
});
return {
sessions: i,
complete: i.some((e) => e.key === t.sessionKey) || r.sessions.length < WORKBOARD_SESSION_LOOKUP_LIMIT
};
}
function createWorkboardLifecycleService(e) {
let t = 0;
let n;
let begin;
let removeDrainListener;
let r = 0;
let i;
const cleanupWorktrees = async (t, n) => {
if (!e.worktrees) return;
const i = t.filter(isWorkboardWorktreeCleanupCandidate);
const a = r % Math.max(i.length, 1);
const o = [...i.slice(a), ...i.slice(0, a)].slice(0, WORKBOARD_WORKTREE_CLEANUP_SWEEP_LIMIT);
r = i.length === 0 ? 0 : (a + o.length) % i.length;
for (const t of o) try {
await cleanupWorkboardCardWorktree({
store: e.store,
worktrees: e.worktrees,
card: t
});
} catch (e) {
n(`workboard worktree cleanup failed for card ${t.id}: ${String(e)}`);
}
};
const stop = () => {
if (workboardLifecycleGatewayState.readSessions === i) workboardLifecycleGatewayState.readSessions = void 0;
i = void 0;
removeDrainListener?.();
removeDrainListener = void 0;
t += 1;
begin = void 0;
if (n) {
clearTimeout(n);
n = void 0;
}
};
const onGatewayStop = () => {
workboardLifecycleGatewayState.ready = false;
workboardLifecycleGatewayState.abortSignal = void 0;
stop();
};
const beginWhenGatewayReady = () => {
if (!workboardLifecycleGatewayState.ready) return;
removeDrainListener?.();
const e = workboardLifecycleGatewayState.abortSignal;
if (e?.aborted) {
onGatewayStop();
return;
}
e?.addEventListener("abort", onGatewayStop, { once: true });
removeDrainListener = () => e?.removeEventListener("abort", onGatewayStop);
begin?.();
};
return {
id: "workboard-lifecycle-sync",
async readSessions(e) {
const t = workboardLifecycleGatewayState.readSessions;
if (!t) return {
sessions: [],
complete: false
};
return await t(e);
},
start(r) {
const a = ++t;
i = AsyncResource.bind(e.readSessions);
workboardLifecycleGatewayState.readSessions = i;
let o = false;
const onMatched = async (n) => {
if (t === a) await e.onMatched?.(n);
};
const reconcile = async () => {
try {
await e.store.runOperation(async () => {
let n = await e.store.list();
if (t !== a) return;
const i = /* @__PURE__ */ new Map();
const o = Date.now();
const s = {};
for (const e of n.filter((e) => needsWorkboardLifecycleReconciliation(e, o))) {
const t = workboardCardSessionLookupKey(e);
const n = i.get(t) ?? [];
n.push(e);
i.set(t, n);
}
for (const [n, c] of i) try {
const t = await e.readSessions({
sessionKey: n,
sweep: s
});
if (!t.complete) continue;
const r = e.store;
const i = t.sessions;
for (const e of c) {
const t = workboardCardSessionLookupKey(e);
const n = t.startsWith("subagent:workboard-") ? i.filter((e) => e.key.endsWith(`:${t}`)) : [];
const a = i.find((e) => e.key === t) ?? (n.length === 1 ? n[0] : void 0);
if (!a && n.length > 1) continue;
const s = e.metadata?.automation?.launch;
const c = s?.phase === "prepared" && a && sessionProvesPreparedAcceptance(a) ? a.hasActiveRun === true ? Math.max(o, s.preparedAt) : a.updatedAt : void 0;
if (s?.phase === "prepared" && (c === void 0 || c < s.preparedAt)) {
await r.failPreparedLaunch(e.id, {
expectedLaunch: s,
reason: "Gateway did not accept the prepared Workboard session before restart.",
failedAt: o
});
continue;
}
if (!a) continue;
const l = lifecycleFromSession(a, o);
if (await r.syncLifecycle(e.id, {
...LIFECYCLE_TARGETS[l.state],
sourceUpdatedAt: l.sourceUpdatedAt,
stale: l.stale,
now: o,
association: {
...cardSessionKey(e) ? { expectedSessionKey: cardSessionKey(e) } : {},
...cardRunId(e) ? { expectedRunId: cardRunId(e) } : {},
sessionKey: a.key,
...c === void 0 ? {} : { acceptedAt: c }
}
})) {
if (l.state === "succeeded" || l.state === "failed") await onMatched({
cards: [e],
sessionKey: a.key
});
}
}
} catch (e) {
if (t === a) r.logger.warn(`workboard lifecycle sync failed: ${String(e)}`);
}
if (i.size > 0) n = await e.store.list();
if (t === a) await cleanupWorktrees(n, (e) => r.logger.warn(e));
});
} catch (e) {
if (t === a) r.logger.warn(`workboard lifecycle recovery failed: ${String(e)}`);
} finally {
if (t === a) {
n = setTimeout(() => void reconcile(), WORKBOARD_LIFECYCLE_SWEEP_MS);
n.unref?.();
}
}
};
begin = () => {
if (t !== a || o) return;
o = true;
reconcile();
};
beginWhenGatewayReady();
},
stop,
onGatewayStart(e) {
workboardLifecycleGatewayState.ready = true;
workboardLifecycleGatewayState.abortSignal = e;
beginWhenGatewayReady();
},
onGatewayStop
};
}
//#endregion
//#region extensions/workboard/src/sessions-board.ts
function sessionMatchesColumn(e, t) {
if (!t.match) return false;
return (Array.isArray(t.match) ? t.match : [t.match]).some((t) => (t.health === void 0 || e.observerDigest !== void 0 && t.health.includes(e.observerDigest.health)) && (t.run === void 0 || t.run.includes(e.run)) && (t.archived === void 0 || t.archived === e.archived) && (t.pullRequest === void 0 || !e.pullRequestsUnavailable && (e.pullRequests.length === 0 ? t.pullRequest.includes("none") : e.pullRequests.some((e) => t.pullRequest?.includes(e.state)))));
}
function sessionsBoardFallback(e) {
const t = e.sessions.columns.find((e) => e.fallback);
if (!t) throw new Error("Sessions board requires a fallback column.");
return t;
}
function activeState() {
return resolveGlobalSingleton(Symbol.for("openclaw.workboard.sessionsBoardService"), () => ({}), (e) => {
e.owner?.cancel();
e.owner = void 0;
});
}
function sessionSelection(e, t) {
return {
configuredAgentsOnly: true,
includeGlobal: false,
includeUnknown: false,
excludeDock: true,
...e.sessions.scope?.includeAutomation ? {} : {
excludeCron: true,
excludeSystem: true
},
archived: e.sessions.scope?.includeArchived ? "all" : false,
sortBy: "activity",
activeMinutes: Math.max(1, Math.ceil((e.sessions.scope?.maxAgeHours ?? 72) * 60)),
...e.sessions.scope?.agentIds?.length === 1 ? { agentId: e.sessions.scope.agentIds[0] } : {},
...t
};
}
function inScope(e, t, n) {
const r = t.sessions.scope;
return e.key !== t.sessions.agentSessionKey && (!r?.agentIds?.length || r.agentIds.includes(e.agentId)) && (r?.includeArchived === true || !e.archived) && e.lastActivityAt >= n - (r?.maxAgeHours ?? 72) * 36e5;
}
function createOwner(e, t, n) {
const r = e.store.repairSessionPlacements().then((e) => {
if (e.placements) t.logger.info(`Sessions board removed ${e.placements} non-operator placements.`);
if (e.boards) t.logger.info(`Sessions board updated default rules on ${e.boards} boards.`);
});
r.catch((e) => {
t.serviceHealth?.reportFailure(e);
t.logger.error(`Sessions board initialization failed: ${String(e)}`);
});
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Map();
const o = /* @__PURE__ */ new Map();
let s = e.store.sessionsRevision;
let c = false;
let l = false;
let u = false;
let d;
const assertCurrent = () => {
if (c || !n()) throw new Error("Sessions board service is no longer active.");
};
const interactiveAuthority = (e) => () => {
assertCurrent();
e?.assertCurrent();
};
const f = e.gateway.subscribeSessionChanges(({ factsInvalidated: t }) => {
if (c || !l || t === "category") return;
if (s !== e.store.sessionsRevision) o.clear();
e.store.invalidateSessionBoards();
s = e.store.sessionsRevision;
if (d) return;
d = setTimeout(() => {
d = void 0;
if (!c && n()) e.store.announceChangeEpoch();
}, 5e3);
d.unref?.();
});
const project = (e, n, r, a) => {
for (const e of n.missingSessionKeys ?? []) i.delete(e);
const o = /* @__PURE__ */ new Set();
const s = /* @__PURE__ */ new Set();
const c = /* @__PURE__ */ new Map();
for (const t of n.sessions) {
if (t.key === e.sessions.agentSessionKey || t.isMain && !e.sessions.scope?.includeHome) continue;
const n = a?.get(t.key);
if (n?.source === t && !t.unavailable && isDeepStrictEqual(n.pin, r.get(t.key))) {
c.set(t.key, n);
continue;
}
const { isMain: l, unavailable: u, pullRequestsStale: d, ...f } = t;
const p = {
source: t,
facts: f
};
if (u) {
o.add(t.key);
s.add(u);
const e = i.get(t.key);
const n = e?.facts.sessionId === t.sessionId ? e : void 0;
p.facts = n ? n.facts : f;
p.stale = n?.stale;
} else p.stale = t.pullRequestsStale;
c.set(t.key, p);
if (!u) i.set(t.key, p);
}
const l = sessionsBoardFallback(e);
const d = [];
const f = /* @__PURE__ */ new Map();
for (const [t, n] of c) {
const { facts: a, source: o } = n;
if (!inScope(a, e, Date.now())) continue;
if (a.pullRequestsUnavailable || a.pullRequestsRateLimited) {
const e = `${n.stale ? "stale" : "not loaded yet"}${a.pullRequestsRateLimited ? " (GitHub rate limited)" : ""}`;
f.set(e, (f.get(e) ?? 0) + 1);
}
if (n.row) {
d.push(n.row);
continue;
}
const s = !o.unavailable || i.get(t)?.facts.sessionId === o.sessionId;
const u = r.get(o.key);
const p = u?.source === "operator" && e.sessions.columns.some((e) => e.id === u.columnId);
const m = a.pullRequestsUnavailable || a.pullRequestsRateLimited ? {
...a,
pullRequestsUnavailable: !n.stale
} : a;
const h = s ? e.sessions.columns.find((e) => sessionMatchesColumn(m, e)) : void 0;
const g = {
...a,
columnId: p ? u.columnId : (h ?? l).id,
source: p ? "operator" : "state",
reason: p ? u.reason : !s || !h && m.pullRequestsUnavailable ? "facts-unavailable" : h ? "Matched column rules" : "fallback"
};
d.push(g);
c.set(t, {
...n,
pin: u,
row: g
});
}
const p = [];
if (o.size) {
const e = `Session facts are unavailable for ${o.size} sessions: ${[...s].join("; ")}. Showing the last known placement.`;
p.push(e);
if (!u) t.logger.warn(e);
u = true;
} else u = false;
for (const [e, t] of f) p.push(`Pull-request facts for ${t} ${t === 1 ? "session" : "sessions"} are ${e}.`);
return {
complete: o.size === 0 && !n.missingSessionKeys?.length,
facts: c,
snapshot: {
board: e,
columns: e.sessions.columns,
sessions: d,
...n.people !== void 0 ? { people: n.people } : {},
...p.length ? { warning: p.join(" ") } : {}
}
};
};
const read = async (t, n, i) => {
const c = interactiveAuthority(i);
await r;
c();
l = true;
if (s !== e.store.sessionsRevision) {
o.clear();
s = e.store.sessionsRevision;
}
const u = s;
let d = o.get(t);
if (!d) {
d = e.store.getSessionsBoard(t);
if (o.size >= 64) o.delete(o.keys().next().value);
o.set(t, d);
d.catch(() => {
o.delete(t);
});
}
const f = await d;
c();
return e.gateway.withSessionFacts(sessionSelection(f, n), async (r) => {
c();
const i = JSON.stringify([
t,
n,
r.scope ?? r.revision
]);
const o = Date.now();
const s = a.get(i);
let l = s;
if (l && (l.revision !== u || l.sourceRevision !== r.revision || l.expires < o)) l = void 0;
if (!l) {
const n = {
revision: u,
sourceRevision: r.revision,
board: f,
expires: r.activityExpiresAt ?? Infinity,
read: Promise.resolve().then(async () => {
const i = (s?.board === f ? s.placements : void 0) ?? await e.store.listSessionPlacements(t);
n.placements = i;
const { snapshot: a, complete: o, facts: c } = project(f, r, new Map(i.map((e) => [e.sessionKey, e])), isDeepStrictEqual(s?.board.sessions.columns, f.sessions.columns) ? s?.facts : void 0);
const l = (f.sessions.scope?.maxAgeHours ?? 72) * 36e5;
n.expires = a.sessions.reduce((e, t) => Math.min(e, t.lastActivityAt + l), n.expires);
n.facts = o ? c : void 0;
return {
snapshot: {
...a,
revision: {
...u,
boardId: t,
scope: randomUUID()
}
},
complete: o
};
})
};
if (a.size >= 64) a.delete(a.keys().next().value);
a.set(i, n);
l = n;
}
try {
const { snapshot: t, complete: n } = await l.read;
c();
if (!n || e.store.sessionsRevision !== u) a.delete(i);
return t;
} catch (e) {
a.delete(i);
c();
throw e;
}
});
};
const cancel = () => {
c = true;
f();
if (d) clearTimeout(d);
d = void 0;
i.clear();
a.clear();
o.clear();
};
return {
read,
cancel,
async stop() {
cancel();
await r.catch(() => {});
},
async update(t, n, i) {
const a = interactiveAuthority(i);
await r;
a();
return await e.store.updateSessionsBoard(t, n, a);
},
async move(t, n, r, i) {
const a = interactiveAuthority(i);
a();
const o = await read(t, void 0, i);
const s = o.board;
if (!s.sessions.columns.some((e) => e.id === r)) throw new Error("Unknown Sessions board column.");
const c = o.sessions.find((e) => e.key === n);
if (!c) throw new Error("Session is not available in this board's scope.");
if (!(await e.gateway.readSessionFacts({ sessionKeys: [n] })).sessions.find((e) => e.key === n && e.sessionId === c.sessionId && inScope(e, s, Date.now()))) throw new Error("Session is not available in this board's scope.");
const l = (await e.store.listSessionPlacements(t)).find((e) => e.sessionKey === n);
if (!await e.store.writeSessionPlacement(t, {
sessionKey: n,
columnId: r,
source: "operator",
reason: "Moved by operator",
factsHash: "",
updatedAt: Date.now(),
expectedUpdatedAt: l?.updatedAt
}, {
expectedSpec: s.sessions,
assertCurrent: a
})) throw new Error("Sessions board changed. Refresh and retry the move.");
return await read(t, void 0, i);
}
};
}
/** Prepared tool registries delegate to the one running plugin service. */
function createWorkboardSessionsBoardService(e) {
let t;
const current = () => {
const e = activeState().owner;
if (!e) throw new Error("Sessions board service is unavailable.");
return e;
};
return {
id: "workboard-sessions-board",
async start(n) {
const r = activeState();
await r.owner?.stop();
r.owner = void 0;
const i = createOwner(e, n, () => activeState().owner === i);
t = r.owner = i;
},
async stop() {
if (!t) return;
const e = t;
t = void 0;
if (activeState().owner === e) activeState().owner = void 0;
await e.stop();
},
read: (e, t, n) => current().read(e, t, n),
update: (e, t, n) => current().update(e, t, n),
move: (e, t, n, r) => current().move(e, t, n, r)
};
}
//#endregion
//#region extensions/workboard/src/tools-card-mutations.ts
function createWorkboardCardMutations(e, t, n) {
const readParams = async (r, i = false) => {
const a = asRecord(r);
const o = readToolStringParam(a, "id", { required: true });
const s = readStringValue(a.token);
const c = await e.get(o);
if (!c) throw new Error(`card not found: ${o}`);
const l = c.metadata?.claim;
if (l && l.ownerId !== t && !safeEqualSecret(s, l.token)) throw new Error(`card is claimed by ${l.ownerId ?? "another agent"}.`);
if (i && !l) throw new Error("card must be claimed before lifecycle completion.");
return {
record: a,
id: o,
scope: {
ownerId: t,
token: s,
runId: n
}
};
};
const cardMutation = (e, t = false) => async (n, r) => {
const { record: i, id: a, scope: o } = await readParams(r, t);
return jsonResult({ card: redactClaimToken(await e(a, i, o)) });
};
return {
readScopedCardToolParams: (e) => readParams(e),
scopedCardMutation: cardMutation,
claimedCardMutation: (e) => cardMutation(e, true)
};
}
function cardIdField() {
return Type.String({ description: "Workboard card id." });
}
function claimTokenField(e = "Claim token returned by workboard_claim.") {
return Type.Optional(Type.String({ description: e }));
}
function strictObject(e) {
return Type.Object(e, { additionalProperties: false });
}
function workspaceField() {
return Type.Optional(strictObject({
kind: Type.String({ description: "scratch, dir, or worktree." }),
path: Type.Optional(Type.String({ description: "Absolute dir/worktree path." })),
branch: Type.Optional(Type.String({ description: "Optional worktree source base ref. Re-dispatch reuses a retained checkout; use a new card for a different base ref." }))
}));
}
//#endregion
//#region extensions/workboard/src/tools-orchestration.ts
const CardIdSchema$1 = strictObject({
id: cardIdField(),
token: claimTokenField()
});
const ScopedClaimTokenField$1 = claimTokenField("Claim token for claimed cards.");
const OptionalNextStatusField = Type.Optional(Type.String({ description: "Optional next status." }));
const OptionalOperatorNoteField = Type.Optional(Type.String({ description: "Optional operator note." }));
const toolSchemas$1 = {
boards: strictObject({}),
board_create: strictObject({
id: Type.String({ description: "Board id." }),
kind: Type.Optional(Type.Union([Type.Literal("cards"), Type.Literal("sessions")], { description: "Board kind, set only at creation. Default cards." })),
name: Type.Optional(Type.String({ description: "Display name." })),
description: Type.Optional(Type.String({ description: "Board description." })),
icon: Type.Optional(Type.String({ description: "Short icon or label." })),
color: Type.Optional(Type.String({ description: "Display color token." })),
automationJobId: Type.Optional(Type.String({
description: "Owning automation job id.",
minLength: 1,
maxLength: 128
})),
defaultWorkspace: workspaceField(),
orchestration: Type.Optional(strictObject({
autoDecompose: Type.Optional(Type.Boolean({ description: "Mark ready triage cards for decomposition." })),
autoDecomposePerDispatch: Type.Optional(Type.Number({ description: "Maximum orchestration candidates per dispatch." })),
defaultAssignee: Type.Optional(Type.String({ description: "Default assignee." })),
orchestratorProfile: Type.Optional(Type.String({ description: "Orchestrator profile id." }))
}))
}),
board_archive: strictObject({
id: Type.String({ description: "Board id." }),
archived: Type.Optional(Type.Boolean({ description: "Archive when true." }))
}),
board_delete: strictObject({ id: Type.String({ description: "Board id." }) }),
stats: strictObject({ boardId: Type.Optional(Type.String({ description: "Optional board id filter." })) }),
specify: strictObject({
id: Type.String({ description: "Workboard card id." }),
title: Type.Optional(Type.String({ description: "Clarified title." })),
notes: Type.Optional(Type.String({ description: "Clarified notes or acceptance criteria." })),
agentId: Type.Optional(Type.String({ description: "Assigned agent id." })),
priority: Type.Optional(Type.String({ description: "low, normal, high, or urgent." })),
labels: Type.Optional(Type.Array(Type.String(), { description: "Card labels." })),
boardId: Type.Optional(Type.String({ description: "Board id." })),
tenant: Type.Optional(Type.String({ description: "Tenant or routing namespace." })),
skills: Type.Optional(Type.Array(Type.String(), { description: "Suggested skills." })),
workspace: workspaceField(),
maxRuntimeSeconds: Type.Optional(Type.Number({ description: "Runtime budget." })),
maxRetries: Type.Optional(Type.Number({ description: "Retry budget." })),
summary: Type.Optional(Type.String({ description: "Specification summary comment." })),
token: Type.Optional(Type.String({ description: "Claim token for claimed cards." }))
}),
decompose: strictObject({
id: Type.String({ description: "Parent Workboard card id." }),
token: Type.Optional(Type.String({ description: "Claim token for claimed cards." })),
summary: Type.Optional(Type.String({ description: "Decomposition summary." })),
completeParent: Type.Optional(Type.Boolean({ description: "Complete the parent after child creation. Default true." })),
children: Type.Array(strictObject({
title: Type.String({ description: "Child title." }),
notes: Type.Optional(Type.String({ description: "Child notes." })),
agentId: Type.Optional(Type.String({ description: "Assigned agent id." })),
priority: Type.Optional(Type.String({ description: "low, normal, high, or urgent." })),
labels: Type.Optional(Type.Array(Type.String())),
boardId: Type.Optional(Type.String()),
tenant: Type.Optional(Type.String()),
skills: Type.Optional(Type.Array(Type.String())),
workspace: workspaceField(),
maxRuntimeSeconds: Type.Optional(Type.Number()),
maxRetries: Type.Optional(Type.Number()),
idempotencyKey: Type.Optional(Type.String())
}))
}),
notify_subscribe: strictObject({
boardId: Type.Optional(Type.String({ description: "Board id. Default default." })),
cardId: Type.Optional(Type.String({ description: "Card id." })),
sessionKey: Type.Optional(Type.String({ description: "Session key." })),
runId: Type.Optional(Type.String({ description: "Run id." })),
target: Type.Optional(Type.String({ description: "Human-readable target." })),
eventKinds: Type.Optional(Type.Array(Type.String(), { description: "completed, failed, stale." }))
}),
notify_list: strictObject({
boardId: Type.Optional(Type.String({ description: "Board id." })),
cardId: Type.Optional(Type.String({ description: "Card id." }))
}),
notify_events: strictObject({
subscriptionId: Type.Optional(Type.String({ description: "Subscription id." })),
boardId: Type.Optional(Type.String({ description: "Board id." })),
cardId: Type.Optional(Type.String({ description: "Card id." })),
limit: Type.Optional(Type.Number({ description: "Maximum events. Default 50." }))
}),
notify_advance: strictObject({
subscriptionId: Type.String({ description: "Subscription id." }),
limit: Type.Optional(Type.Number({ description: "Maximum events. Default 50." }))
}),
notify_unsubscribe: strictObject({ id: Type.String({ description: "Subscription id." }) }),
promote: strictObject({
id: cardIdField(),
token: ScopedClaimTokenField$1,
force: Type.Optional(Type.Boolean({ description: "Bypass dependency or schedule holds." })),
reason: OptionalOperatorNoteField
}),
reassign: strictObject({
id: cardIdField(),
token: ScopedClaimTokenField$1,
agentId: Type.Optional(Type.String({ description: "New assignee id." })),
status: OptionalNextStatusField,
resetFailures: Type.Optional(Type.Boolean({ description: "Reset failure count." })),
reason: OptionalOperatorNoteField
}),
reclaim: strictObject({
id: cardIdField(),
token: ScopedClaimTokenField$1,
status: OptionalNextStatusField,
reason: OptionalOperatorNoteField
}),
dispatch: strictObject({ boardId: Type.Optional(Type.String({ description: "Optional board id filter." })) }),
worker_log: strictObject({
id: cardIdField(),
level: Type.Optional(Type.String({ description: "info, warning, or error." })),
message: Type.String({ description: "Worker log message." }),
sessionKey: Type.Optional(Type.String({ description: "Linked session key." })),
runId: Type.Optional(Type.String({ description: "Linked run id." })),
token: ScopedClaimTokenField$1
}),
protocol_violation: strictObject({
id: cardIdField(),
detail: Type.Optional(Type.String({ description: "Violation detail." })),
sessionKey: Type.Optional(Type.String({ description: "Linked session key." })),
runId: Type.Optional(Type.String({ description: "Linked run id." })),
token: ScopedClaimTokenField$1
})
};
function createWorkboardOrchestrationTools(e) {
const { store: t, ownerId: n } = e;
const { readScopedCardToolParams: r, scopedCardMutation: i, claimedCardMutation: a } = createWorkboardCardMutations(t, n, e.runId);
return [
{
name: "workboard_boards",
label: "Workboard Boards",
description: "List Workboard board namespaces with active, archived, and status counts.",
parameters: toolSchemas$1.boards,
execute: async () => jsonResult(await t.listBoards())
},
{
name: "workboard_board_create",
label: "Workboard Board Create",
description: "Create or update a Workboard board with persisted SQLite metadata. Choose kind sessions on creation for columns with rules over Gateway-owned session facts; card tools do not apply to Sessions boards. Board kind cannot change after creation.",
parameters: toolSchemas$1.board_create,
execute: async (e, n) => jsonResult({ board: await t.upsertBoard(asNonArrayRecord(n)) })
},
{
name: "workboard_board_archive",
label: "Workboard Board Archive",
description: "Archive or restore persisted Workboard board metadata.",
parameters: toolSchemas$1.board_archive,
execute: async (e, n) => {
const r = asNonArrayRecord(n);
return jsonResult({ board: await t.archiveBoard(r.id, r.archived) });
}
},
{
name: "workboard_board_delete",
label: "Workboard Board Delete",
description: "Delete an empty non-default Workboard board metadata record.",
parameters: toolSchemas$1.board_delete,
execute: async (e, n) => jsonResult(await t.deleteBoard(asNonArrayRecord(n).id))
},
{
name: "workboard_stats",
label: "Workboard Stats",
description: "Summarize Workboard counts by status and assignee for one board or all boards.",
parameters: toolSchemas$1.stats,
execute: async (e, n) => {
const r = asNonArrayRecord(n);
return jsonResult(await t.stats({ boardId: r.boardId }));
}
},
{
name: "workboard_runs",
label: "Workboard Runs",
description: "List persisted Workboard run attempts for one card.",
parameters: CardIdSchema$1,
execute: async (e, n) => {
const r = readToolStringParam(asNonArrayRecord(n), "id", { required: true });
const i = await t.runs(r);
return jsonResult({
...i,
card: redactClaimToken(i.card)
});
}
},
{
name: "workboard_specify",
label: "Workboard Specify",
description: "Turn a rough triage/backlog Workboard card into a specified todo card after reasoning through the requirements.",
parameters: toolSchemas$1.specify,
execute: i((e, n, r) => t.specify(e, n, r))
},
{
name: "workboard_decompose",
label: "Workboard Decompose",
description: "Fan out a Workboard card into linked child cards and optionally complete the parent orchestration card.",
parameters: toolSchemas$1.decompose,
execute: async (e, n) => {
const { record: i, id: a, scope: o } = await r(asNonArrayRecord(n));
const s = await t.decompose(a, i, o);
return jsonResult({
parent: redactClaimToken(s.parent),
children: s.children.map(redactClaimToken)
});
}
},
{
name: "workboard_notify_subscribe",
label: "Workboard Notify Subscribe",
description: "Persist a Workboard notification subscription in the plugin SQLite store.",
parameters: toolSchemas$1.notify_subscribe,
execute: async (e, n) => jsonResult({ subscription: await t.subscribeNotifications(asNonArrayRecord(n)) })
},
{
name: "workboard_notify_list",
label: "Workboard Notify List",
description: "List persisted Workboard notification subscriptions.",
parameters: toolSchemas$1.notify_list,
execute: async (e, n) => jsonResult(await t.listNotificationSubscriptions(asNonArrayRecord(n)))
},
{
name: "workboard_notify_events",
label: "Workboard Notify Events",
description: "Read replay-safe Workboard notification events without advancing cursors.",
parameters: toolSchemas$1.notify_events,
execute: async (e, n) => jsonResult(await t.notificationEvents(asNonArrayRecord(n)))
},
{
name: "workboard_notify_advance",
label: "Workboard Notify Advance",
description: "Read Workboard notification events and advance the subscription cursor.",
parameters: toolSchemas$1.notify_advance,
execute: async (e, n) => jsonResult(await t.advanceNotificationEvents(asNonArrayRecord(n)))
},
{
name: "workboard_notify_unsubscribe",
label: "Workboard Notify Unsubscribe",
description: "Delete a persisted Workboard notification subscription.",
parameters: toolSchemas$1.notify_unsubscribe,
execute: async (e, n) => {
const r = readToolStringParam(asNonArrayRecord(n), "id", { required: true });
return jsonResult(await t.deleteNotificationSubscription(r));
}
},
{
name: "workboard_promote",
label: "Workboard Promote",
description: "Promote a todo card into ready, optionally forcing past dependency or schedule holds. Unblock blocked cards first.",
parameters: toolSchemas$1.promote,
execute: i((e, n, r) => t.promote(e, n, r))
},
{
name: "workboard_reassign",
label: "Workboard Reassign",
description: "Change a card assignee and optionally reset failure state during recovery.",
parameters: toolSchemas$1.reassign,
execute: i((e, n, r) => t.reassign(e, n, r))
},
{
name: "workboard_reclaim",
label: "Workboard Reclaim",
description: "Release a stale claim and stop running attempts so another agent can pick it up.",
parameters: toolSchemas$1.reclaim,
execute: i((e, n, r) => t.reclaim(e, n, r))
},
{
name: "workboard_dispatch",
label: "Workboard Dispatch",
description: "Advance persisted board state without launching workers: promote unblocked cards, reclaim expired claims, and block timed-out runs.",
parameters: toolSchemas$1.dispatch,
execute: async (e, n) => {
const r = asNonArrayRecord(n);
const i = await t.dispatch({ boardId: r.boardId });
return jsonResult(redactDispatchResult(i));
}
},
{
name: "workboard_worker_log",
label: "Workboard Worker Log",
description: "Append a persisted worker log entry to a Workboard card.",
parameters: toolSchemas$1.worker_log,
execute: i((e, n, r) => t.addWorkerLog(e, n, r))
},
{
name: "workboard_protocol_violation",
label: "Workboard Protocol Violation",
description: "Block a card and record a worker protocol violation when work stops without complete/block.",
parameters: toolSchemas$1.protocol_violation,
execute: a((e, n, r) => t.recordProtocolViolation(e, n, r))
}
];
}
//#endregion
//#region extensions/workboard/src/tools.ts
function contextOwner(e) {
return e?.agentId || e?.sessionKey || e?.sessionId || "agent";
}
function summarizeCard(e) {
return {
id: e.id,
title: e.title,
status: e.status,
priority: e.priority,
agentId: e.agentId,
tenant: e.metadata?.automation?.tenant,
boardId: e.metadata?.automation?.boardId ?? "default",
parents: e.metadata?.links?.filter((e) => e.type === "parent" && e.targetCardId).map((e) => e.targetCardId),
children: e.metadata?.links?.filter((e) => e.type === "child" && e.targetCardId).map((e) => e.targetCardId),
claim: e.metadata?.claim ? {
ownerId: e.metadata.claim.ownerId,
claimedAt: e.metadata.claim.claimedAt,
lastHeartbeatAt: e.metadata.claim.lastHeartbeatAt,
expiresAt: e.metadata.claim.expiresAt
} : void 0,
diagnostics: e.metadata?.diagnostics,
archivedAt: e.metadata?.archivedAt,
updatedAt: e.updatedAt
};
}
function redactedProofResult(e) {
const t = e.metadata?.proof?.at(-1)?.id;
if (!t) throw new Error("proof was not retained in card metadata.");
return jsonResult({
card: redactClaimToken(e),
proofId: t
});
}
const ScopedClaimTokenField = claimTokenField("Claim token for claimed cards.");
const CardIdSchema = strictObject({
id: cardIdField(),
token: claimTokenField()
});
const toolSchemas = {
list: strictObject({
status: Type.Optional(Type.String({ description: "Optional card status filter." })),
agentId: Type.Optional(Type.String({ description: "Optional agent id filter." })),
tenant: Type.Optional(Type.String({ description: "Optional tenant filter." })),
boardId: Type.Optional(Type.String({ description: "Optional board id filter." })),
limit: Type.Optional(Type.Number({ description: "Maximum cards to return. Default 50." })),
refreshDiagnostics: Type.Optional(Type.Boolean({ description: "Refresh stored diagnostics before listing." })),
includeArchived: Type.Optional(Type.Boolean({ description: "Include archived cards. Default false." }))
}),
create: strictObject({
title: Type.String({ description: "Card title." }),
notes: Type.Optional(Type.String({ description: "Card notes or acceptance criteria." })),
status: Type.Optional(Type.String({ description: "Initial status." })),
priority: Type.Optional(Type.String({ description: "low, normal, high, or urgent." })),
labels: Type.Optional(Type.Array(Type.String(), { description: "Card labels." })),
agentId: Type.Optional(Type.String({ description: "Assigned agent id." })),
parents: Type.Optional(Type.Array(Type.String(), { description: "Parent card ids." })),
token: Type.Optional(Type.String({ description: "Claim token for claimed parent cards." })),
tenant: Type.Optional(Type.String({ description: "Soft tenant namespace." })),
boardId: Type.Optional(Type.String({ description: "Soft board namespace." })),
createdByCardId: Type.Optional(Type.String({ description: "Parent card that created this card." })),
idempotencyKey: Type.Optional(Type.String({ description: "Reuse this key when retrying to avoid creating a duplicate card." })),
skills: Type.Optional(Type.Array(Type.String(), { description: "Suggested skills." })),
workspace: workspaceField(),
maxRuntimeSeconds: Type.Optional(Type.Number({ description: "Run timeout seconds." })),
maxRetries: Type.Optional(Type.Number({ description: "Retry budget." })),
scheduledAt: Type.Optional(Type.Number({ description: "Unix epoch milliseconds." }))
}),
link: strictObject({
parentId: Type.String({ description: "Parent card id." }),
childId: Type.String({ description: "Child card id." }),
token: Type.Optional(Type.String({ description: "Claim token for claimed parent or child cards." }))
}),
claim: strictObject({
id: cardIdField(),
ttlSeconds: Type.Optional(Type.Number({ description: "Claim TTL in seconds." }))
}),
heartbeat: strictObject({
id: cardIdField(),
token: claimTokenField(),
note: Type.Optional(Type.String({ description: "Optional compact progress note." }))
}),
release: strictObject({
id: cardIdField(),
token: claimTokenField(),
status: Type.Optional(Type.String({ description: "Optional next card status after release." }))
}),
comment: strictObject({
id: cardIdField(),
body: Type.String({ description: "Comment body." }),
token: ScopedClaimTokenField
}),
proof: strictObject({
id: cardIdField(),
status: Type.Optional(Type.String({ description: "passed, failed, skipped, or unknown." })),
label: Type.Optional(Type.String({ description: "Proof label." })),
command: Type.Optional(Type.String({ description: "Command or exact step run." })),
url: Type.Optional(Type.String({ description: "Proof or artifact URL." })),
note: Type.Optional(Type.String({ description: "Short proof note." })),
artifactPath: Type.Optional(Type.String({ description: "Optional local artifact path." })),
token: ScopedClaimTokenField
}),
complete: strictObject({
id: cardIdField(),
token: claimTokenField(),
summary: Type.Optional(Type.String({ description: "Completion summary." })),
proofId: Type.Optional(Type.String({ description: "Proof id returned by workboard_proof when resolving that pending proof." })),
proof: Type.Optional(strictObject({
status: Type.Optional(Type.String({ description: "passed, failed, skipped, or unknown." })),
label: Type.Optional(Type.String({ description: "Proof label." })),
command: Type.Optional(Type.String({ description: "Command or step run." })),
url: Type.Optional(Type.String({ description: "Proof URL." })),
note: Type.Optional(Type.String({ description: "Proof note." }))
})),
artifacts: Type.Optional(Type.Array(strictObject({
label: Type.Optional(Type.String()),
url: Type.Optional(Type.String()),
path: Type.Optional(Type.String()),
mimeType: Type.Optional(Type.String())
}))),
createdCardIds: Type.Optional(Type.Array(Type.String(), { description: "Cards created during this run." }))
}),
attachment_add: strictObject({
id: cardIdField(),
fileName: Type.String({ description: "Attachment file name." }),
contentBase64: Type.String({ description: "Base64 attachment content." }),
mimeType: Type.Optional(Type.String({ description: "Attachment MIME type." })),
note: Type.Optional(Type.String({ description: "Optional attachment note." })),
token: ScopedClaimTokenField
}),
attachment_read: strictObject({ id: Type.String({ description: "Attachment id." }) }),
attachment_delete: strictObject({
id: cardIdField(),
attachmentId: Type.String({ description: "Attachment id." }),
token: ScopedClaimTokenField
}),
block: strictObject({
id: cardIdField(),
token: claimTokenField(),
reason: Type.Optional(Type.String({ description: "Blocker summary." }))
}),
move: strictObject({
id: cardIdField(),
status: Type.Union(WORKBOARD_STATUSES.map((e) => Type.Literal(e)), { description: "Target Workboard status." }),
token: claimTokenField("Claim token for claimed cards.")
})
};
function createWorkboardTools(e) {
const { store: t } = e;
const n = contextOwner(e.context);
const r = e.context?.runId;
const { readScopedCardToolParams: i, scopedCardMutation: a, claimedCardMutation: o } = createWorkboardCardMutations(t, n, r);
const s = [
{
name: "workboard_list",
label: "Workboard List",
description: "List Workboard cards with compact claim and diagnostic state. Use before choosing or routing board work.",
parameters: toolSchemas.list,
execute: async (e, n) => {
const r = n;
if (r.refreshDiagnostics === true) await t.refreshDiagnostics();
const i = typeof r.status === "string" ? r.status : void 0;
const a = typeof r.agentId === "string" ? r.agentId : void 0;
const o = typeof r.tenant === "string" ? r.tenant : void 0;
const s = typeof r.boardId === "string" ? r.boardId : void 0;
const c = resolveIntegerOption(r.limit, 50, {
min: 1,
max: 200
});
const l = (await t.list({ boardId: s })).filter((e) => r.includeArchived === true || !e.metadata?.archivedAt).filter((e) => !i || e.status === i).filter((e) => !a || e.agentId === a).filter((e) => !o || e.metadata?.automation?.tenant === o).slice(0, c).map(summarizeCard);
return jsonResult({ cards: l });
}
},
{
name: "workboard_create",
label: "Workboard Create",
description: "Create a Workboard card, optionally with parent dependencies, tenant, skills, workspace, and key to prevent duplicate requests. Sessions boards do not hold cards; use workboard_sessions_board_read/update/move for them.",
parameters: toolSchemas.create,
execute: async (e, r) => {
const i = r;
normalizeCappedStringList(i.parents, "parents");
return jsonResult({ card: redactClaimToken(await t.create(i, {
ownerId: n,
token: i.token
})) });
}
},
{
name: "workboard_link",
label: "Workboard Link",
description: "Link a parent card to a child card so the child becomes ready only after parents are done.",
parameters: toolSchemas.link,
execute: async (e, r) => {
const i = r;
const a = readToolStringParam(i, "parentId", { required: true });
const o = readToolStringParam(i, "childId", { required: true });
const s = i.token;
return jsonResult({ card: redactClaimToken(await t.linkCards(a, o, {
ownerId: n,
token: s
})) });
}
},
{
name: "workboard_read",
label: "Workboard Read",
description: "Read one Workboard card and return bounded worker context with notes, attempts, comments, proof, links, and diagnostics.",
parameters: CardIdSchema,
execute: async (e, n) => {
const r = readToolStringParam(n, "id", { required: true });
const { card: i, workerContext: a } = await t.readWithWorkerContext(r);
return jsonResult({
card: redactClaimToken(i),
workerContext: a
});
}
},
{
name: "workboard_claim",
label: "Workboard Claim",
description: "Claim a Workboard card for this agent and move backlog/todo cards into running. Returns a claim token for heartbeats and release.",
parameters: toolSchemas.claim,
execute: async (e, r) => {
const i = r;
const a = readToolStringParam(i, "id", { required: true });
const o = await t.claim(a, {
ownerId: n,
ttlSeconds: i.ttlSeconds
});
return jsonResult({
...o,
card: redactClaimToken(o.card)
});
}
},
{
name: "workboard_heartbeat",
label: "Workboard Heartbeat",
description: "Refresh this agent's Workboard claim heartbeat. Use during long-running card work so diagnostics do not mark it stale.",
parameters: toolSchemas.heartbeat,
execute: a((e, n, r) => t.heartbeat(e, {
...r,
note: n.note
}))
},
{
name: "workboard_release",
label: "Workboard Release",
description: "Release this agent's Workboard claim after finishing, pausing, or handing off card work.",
parameters: toolSchemas.release,
execute: a((e, n, r) => t.releaseClaim(e, {
...r,
status: n.status
}))
},
{
name: "workboard_comment",
label: "Workboard Comment",
description: "Append a compact comment to a Workboard card.",
parameters: toolSchemas.comment,
execute: a((e, n, r) => t.addComment(e, { body: n.body }, r))
},
{
name: "workboard_proof",
label: "Workboard Proof",
description: "Attach proof or artifact metadata to a Workboard card after running tests, checks, or producing screenshots/logs. Returns proofId; pass it to workboard_complete when that call reports the terminal status for this proof.",
parameters: toolSchemas.proof,
execute: async (e, n) => {
const { record: r, id: a, scope: o } = await i(n);
return redactedProofResult(typeof r.artifactPath === "string" && r.artifactPath.trim() !== "" || typeof r.url === "string" && r.url.trim() !== "" ? await t.addProofWithArtifact(a, r, {
label: r.label,
path: r.artifactPath,
url: r.url
}, o) : await t.addProof(a, r, o));
}
},
{
name: "workboard_complete",
label: "Workboard Complete",
description: "Complete a claimed Workboard card with a structured summary, proof, artifacts, and created-card manifest.",
parameters: toolSchemas.complete,
execute: o((e, n, r) => t.complete(e, n, r))
},
{
name: "workboard_attachment_add",
label: "Workboard Attachment Add",
description: "Store a small Workboard attachment in plugin SQLite KV and link it to the card.",
parameters: toolSchemas.attachment_add,
execute: a((n, r, i) => t.addAttachment(n, r, i, e.context?.assertInputCommitAllowed))
},
{
name: "workboard_attachment_read",
label: "Workboard Attachment Read",
description: "Read one Workboard attachment from plugin SQLite KV.",
parameters: toolSchemas.attachment_read,
execute: async (e, n) => {
const r = readToolStringParam(n, "id", { required: true });
const i = await t.getAttachment(r);
if (!i) throw new Error(`attachment not found: ${r}`);
return jsonResult(i);
}
},
{
name: "workboard_attachment_delete",
label: "Workboard Attachment Delete",
description: "Delete one Workboard attachment from plugin SQLite KV and the card index.",
parameters: toolSchemas.attachment_delete,
execute: a((e, n, r) => {
const i = readToolStringParam(n, "attachmentId", { required: true });
return t.deleteAttachment(e, i, r);
})
},
{
name: "workboard_block",
label: "Workboard Block",
description: "Block a claimed Workboard card with a durable reason and release the claim.",
parameters: toolSchemas.block,
execute: o((e, n, r) => t.block(e, n, r))
},
{
name: "workboard_unblock",
label: "Workboard Unblock",
description: "Move a blocked Workboard card back to todo after adding enough context.",
parameters: CardIdSchema,
execute: a((e, n, r) => t.unblock(e, r))
},
{
name: "workboard_move",
label: "Workboard Move",
description: "Move a Workboard card to another status. Claimed cards require matching claim scope.",
parameters: toolSchemas.move,
execute: a((e, n, r) => t.move(e, n.status, void 0, r))
},
...createWorkboardOrchestrationTools({
store: t,
ownerId: n,
runId: r
})
];
for (const e of s) {
const n = e.execute;
e.execute = (...e) => t.runOperation(() => n(...e));
}
return s;
}
//#endregion
//#region extensions/workboard/index.ts
const boardIdField = Type.Optional(Type.String({ description: "Board id. May be omitted only when exactly one Sessions board exists." }));
function optionalChoices(e) {
return Type.Optional(Type.Array(Type.Union(e.map((e) => Type.Literal(e)))));
}
const matchRuleSchema = strictObject({
health: optionalChoices([
"on-track",
"grinding",
"stuck",
"waiting-on-user",
"wrapping-up",
"done",
"failed"
]),
run: optionalChoices([
"active",
"idle",
"failed"
]),
pullRequest: optionalChoices([
"none",
"open",
"draft",
"merged",
"closed"
]),
archived: Type.Optional(Type.Boolean())
});
const columnSchema = strictObject({
id: Type.String({
minLength: 1,
maxLength: 48,
pattern: "^[a-z0-9][a-z0-9-]{0,47}$",
description: "Stable column id. Keep this id when renaming the label."
}),
label: Type.String({
minLength: 1,
maxLength: 60
}),
color: Type.Optional(Type.String({ description: "red, blue, green, yellow, purple, orange, pink, or cyan." })),
description: Type.String({
minLength: 1,
maxLength: 400,
description: "Description shown in the column tooltip."
}),
match: Type.Optional(Type.Union([matchRuleSchema, Type.Array(matchRuleSchema, { minItems: 1 })])),
fallback: Type.Optional(Type.Boolean({ description: "Exactly one column must be the unresolved-session fallback." }))
});
var workboard_default = definePluginEntry({
id: "workboard",
name: "Workboard",
description: "Dashboard workboard for agent-owned issues and sessions.",
register(e) {
e.registerCli(async ({ program: t }) => {
const { registerWorkboardCli: n } = await import("../../cli-COgaPb3k.mjs");
n({
program: t,
withStore: async (t) => {
const n = WorkboardStore.openSqlite(resolveWorkboardSqliteWorkerModuleUrl(e.runtimeSource));
try {
return await t(n);
} finally {
await n.close();
}
}
});
}, { descriptors: [{
name: "workboard",
description: "Manage Workboard cards and worker dispatch",
hasSubcommands: true
}] });
if (e.registrationMode === "cli-metadata") return;
const t = WorkboardStore.openSqlite(resolveWorkboardSqliteWorkerModuleUrl(e.runtimeSource), { lazy: e.registrationMode === "tool-discovery" });
const n = [];
registerWorkboardStoreLifecycle(e, t, async () => {
await Promise.all(n.map(async (e) => await e.stop()));
});
const r = createWorkboardChangeEventService(t);
n.push(r);
const i = createWorkboardAutomationNudgeService({ store: t });
n.push(i);
const a = createWorkboardSessionsBoardService({
store: t,
gateway: e.runtime.gateway
});
n.push(a);
const o = createWorkboardLifecycleService({
store: t,
worktrees: e.runtime.worktrees,
readSessions: async (t) => await readWorkboardLifecycleSessions(e.runtime.gateway, t),
onMatched: i.nudge
});
n.push(o);
e.session.controls.registerControlUiDescriptor({
surface: "tab",
id: "workboard",
label: "Workboard",
placement: "route:workboard",
icon: "kanban",
group: "control",
requiredScopes: ["operator.read"]
});
for (const [t, n, r] of [
[
"board",
"Workboard board",
"operator.read"
],
[
"card",
"Workboard card",
"operator.write"
],
[
"mini",
"Workboard summary",
"operator.read"
]
]) e.session.controls.registerControlUiDescriptor({
surface: "widget",
id: t,
label: n,
requiredScopes: [r]
});
registerWorkboardGatewayMethods({
api: e,
store: t,
sessionsBoard: a
});
registerWorkboardCommand({
api: e,
store: t
});
for (const t of [
r,
i,
a,
o
]) e.registerService(t);
e.on("gateway_start", (e, t) => o.onGatewayStart(t.abortSignal));
e.on("gateway_stop", () => o.onGatewayStop());
e.on("subagent_ended", (n) => t.runOperation(async () => {
await syncWorkboardSubagentEnded({
store: t,
worktrees: e.runtime.worktrees,
event: n,
onMatched: i.nudge
});
}));
e.on("agent_end", (e, n) => t.runOperation(async () => {
await syncWorkboardAgentEnded({
store: t,
event: e,
context: n,
readSessions: o.readSessions,
onMatched: i.nudge
});
}));
e.registerTool((n) => guardWorkboardToolsForWorkspaceAccess(createWorkboardTools({
context: n,
store: t
}), n, e.runtime.sandbox.resolveWorkspaceAuthority), {
names: [...WORKBOARD_CARD_TOOL_NAMES],
optional: true
});
e.registerTool({
contextVersion: 2,
create: (e) => {
const n = { assertCurrent: e.assertInvocationCurrent };
const resolveBoardId = async (e) => {
if (e.boardId !== void 0) return readToolStringParam(e, "boardId", { required: true });
const n = (await t.listBoards()).boards.filter((e) => e.kind === "sessions");
const r = n[0];
if (n.length === 1 && r) return r.id;
throw new Error(n.length === 0 ? "No Sessions board exists. Create one with workboard_board_create and kind: \"sessions\"." : "boardId is required when more than one Sessions board exists. Use workboard_boards to choose one.");
};
const r = [
{
name: "workboard_sessions_board_read",
label: "Sessions Board Read",
description: "Read a Sessions board and its session placements. Columns match Gateway-owned session status, observer health, and pull-request facts in order; operator pins take precedence. Card tools do not apply to Sessions boards.",
parameters: strictObject({ boardId: boardIdField }),
execute: async (e, t) => {
const r = asNonArrayRecord(t);
return jsonResult(await a.read(await resolveBoardId(r), void 0, n));
}
},
{
name: "workboard_sessions_board_update",
label: "Sessions Board Update",
description: "Edit a Sessions board's columns, match rules, or scope. columns replaces the full ordered list; preserve ids when renaming labels. All fields in each rule must match; a match array accepts any rule, and the first matching column wins. Exactly one fallback is required. Card tools do not apply to Sessions boards.",
parameters: strictObject({
boardId: boardIdField,
columns: Type.Optional(Type.Array(columnSchema, {
minItems: 2,
maxItems: 12
})),
scope: Type.Optional(strictObject({
agentIds: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
includeArchived: Type.Optional(Type.Boolean()),
includeAutomation: Type.Optional(Type.Boolean({ description: "Include automation (cron) and system sessions. Defaults to false." })),
includeHome: Type.Optional(Type.Boolean({ description: "Include each agent's Home session. Defaults to false." })),
maxAgeHours: Type.Optional(Type.Number({ exclusiveMinimum: 0 }))
}))
}),
execute: async (e, t) => {
const r = asNonArrayRecord(t);
const i = await resolveBoardId(r);
const { boardId: o, ...s } = r;
return jsonResult({ board: await a.update(i, s, n) });
}
},
{
name: "workboard_sessions_board_move",
label: "Sessions Board Move",
description: "Pin a session in a Sessions board column. The pin overrides match rules while the column exists. Card tools do not apply to Sessions boards.",
parameters: strictObject({
boardId: boardIdField,
sessionKey: Type.String({ description: "Exact session key from the board read." }),
columnId: Type.String({ description: "Destination column id from the board read." })
}),
execute: async (e, t) => {
const r = asNonArrayRecord(t);
return jsonResult(await a.move(await resolveBoardId(r), readToolStringParam(r, "sessionKey", { required: true }), readToolStringParam(r, "columnId", { required: true }), n));
}
}
];
for (const e of r) {
const n = e.execute;
e.execute = (...e) => t.runOperation(() => n(...e));
}
return r;
}
}, { names: [...WORKBOARD_SESSIONS_BOARD_TOOL_NAMES] });
}
});
//#endregion
export { workboard_default as default };