* fix(ci): restore browser preview module and onboarding e2e The web bundle imported a browser-preview store that was never added, so production builds and every Playwright signup failed before the shell rendered. Mobile check failed because Expo packages were a patch behind the SDK. Restore the store, type the optional desktop bridge, and walk whichever onboarding step scripted CI actually opens. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): stop the blank web client and the send 500 The core barrel pulled git checkout into the browser, so node:child_process crashed the page before sign-up. Serve that module from a node export instead. Add the missing run tool-call budget columns that threads/send writes. Guard an indexed shell flag for typecheck, and expect the files key the desktop preload already exposes. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): isolate pnpm setup and the takeover membership The Team Computer takeover journey inserted a space member the default-space trigger had already created, so shared Postgres rejected the unique pair. Self-hosted jobs now keep a per-job pnpm home and store, and artifact uploads no longer fail a job that already passed. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): clear typecheck, lint, and unit failures Inbound channel rosters can mark a participant list as authoritative. Answered channel asks stay off the group, and clearing a thread waits until delegated returns land. Lint, unit, and web e2e contracts follow the current shell, composer, and settings. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): align e2e with the shipped shell and onboarding Web E2E still expected older focus buttons, nested project rows, and settings that never opened MCP. Persist the signed-in space, list non-default spaces under Projekte, and keep the quote control on screen. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): open group reply from a revealed hover rail The first user row covered its Reply control until the rail accepted pointer events. The group transcript now reveals that rail, then replies. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): stop the shell render loop and settle computer and mention UI A working bot rewrote preview state on every render, the computer menu never stayed still, and the mention picker did not expose its expanded state or option name. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): stop idle probes hanging and accept a follow-up send Background probes walked every process fd and timed out on the shared runner. Linux now tracks the marker with flock and /proc/locks. A new composer draft can send while an earlier send is still refreshing, and group members stay mentionable. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(adapters): detect background work when flock ids are padded The idle probe compared /proc/locks with an unpadded device key, so majors or minors under 16 never matched. It deleted the live marker and reported idle while the command still held the lock. Probe by taking the lock, and print the cancel key the way the kernel does. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(adapters): stabilize background-work probe tests on self-hosted CI Clear stale marker files before each probe scenario and allow longer polling so launch can acquire flock on busy persistent runners. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): do not block onboarding on spaces list Render the first onboarding step from me and integration setup alone. Resolve the optional skip-to-app redirect after that so Playwright signups are not stuck on the loading shell when spaces.list is slow. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): restore green gates after second main rebase Re-apply biome formatting on Shell/SortableGroup and strict TypeScript assertions in computer-idle tests dropped when skipping the duplicate conflict-resolution commit. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): wait for onboarding bootstrap before E2E proceeds Expose data-onboarding-step on the onboarding shell and have Playwright wait until loading finishes. Ignore ad-hoc screenshot scripts on self-hosted runners so they do not fail lint. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): fall back when onboarding bootstrap stalls Race me/integration setup against a timeout and promote loading to the emoji step after 20s so Playwright is not blocked on a hung RPC. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): render onboarding immediately for E2E signups Start on the emoji step instead of a loading shell that waits on RPC. Bootstrap can still redirect once me and integration setup resolve. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(ci): stabilize web e2e on self-hosted runners Per-job pnpm stores broke node_modules symlinks when setup-node restored cached installs, so Vite could not resolve react during dependency optimization. Keep a runner-scoped store, clear stale Vite caches, and pin Playwright to one worker in CI to reduce onboarding RPC contention. Add Vite resolve aliases for react/react-dom, wait for an interactive onboarding step in E2E helpers, and include the React hook smoke spec from main. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): resolve React aliases through pnpm package layout Root node_modules/react does not exist under pnpm, so Vite aliases pointed at missing paths and broke production builds and the Playwright webServer. Resolve react and react-dom from the web package and map jsx-runtime to the actual entry files. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(core): type the lazy child_process spawn cache Main's lazy require left spawn typed as null after assignment, which broke Typecheck on the rebased branch. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(db): mock git-checkout export path in unit tests Vitest resolves vi.mock against package exports; the .js suffix is not declared for @rakazo/core/git-checkout. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): stabilize E2E after main sidebar and onboarding changes Use first() for duplicate transcript lines, wait for interactive onboarding before model-required assertions, and allow project sidebar to settle after create. Extend the Playwright job timeout so the single-worker suite can finish. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): restore Projekte sidebar and integrations MCP entry Use the default space for Unterhaltungen/Projekte separation instead of the active space header, persist the bootstrapped space in localStorage, wire SettingsOverlay to MCP management, and compare hover tones on inactive rows. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): satisfy biome format on homeSpaceId line Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): align sidebar E2E with nested Projekte shell layout Scope Unterhaltungen assertions to conversation rows only, target project-space Chief actions under .sidebar-projekte, and stabilize hover-tone polling. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix: satisfy lint after main merge (format and unused var) Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): show project-space 1:1 bots in Projekte sidebar Include lone bots in projectSidebarGroups, render bot rows in Projekte, and stabilize E2E for nested sidebar layout and duplicate group entries. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): disambiguate duplicate group sidebar buttons in E2E Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): align spaces and group-chats E2E with Projekte sidebar IA Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): dedupe Projekte sidebar rows and stabilize E2E specs - Deduplicate project space and group-chat entries in projectSidebarGroups - Scope group-chats/spaces E2E clicks to first Projekte match after IA split - Wait for shell ready before mention-picker keyboard test; restore main locators - Fix PrivacySettingsOverlay lint and align biome schema with CLI 2.5.13 Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): restrict project drag handle and stabilize space E2E - Move SortableGroup drag listeners to ProjectDragGrip only so sidebar clicks work - Scope space delete actions to project-space rows; wait for menu in E2E - Switch group settings E2E via direct navigation after unsaved draft check - Merge main (DataTrustPanel) and fix Shell import order for CI lint Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): stabilize message hover Escape assertion in E2E Assert the More menu closes and the hover rail stays visible instead of requiring focus restoration, which is flaky across Chromium builds. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * chore: format apps/api/src/app.ts after main merge Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> * fix(web): stabilize team-computer E2E send after bot switch Wait for shell ready and use the Send button instead of Enter after switching bots and closing the computer overlay. The prior run timed out on threads/send with only an apps/api format commit in between. Co-authored-by: cynarAI <cynarAI@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: cynarAI <cynarAI@users.noreply.github.com>
686 lines
20 KiB
TypeScript
686 lines
20 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import type { Agent, AgentMessage, AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
import {
|
|
type Api,
|
|
clampThinkingLevel,
|
|
type Model,
|
|
type Models,
|
|
type ModelThinkingLevel,
|
|
type SimpleStreamOptions,
|
|
Type,
|
|
} from "@earendil-works/pi-ai";
|
|
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
import type {
|
|
AgentRunRequest,
|
|
AgentRuntimeEvent,
|
|
AgentSteeringMessage,
|
|
AgentToolExecutionResult,
|
|
} from "@rakazo/adapter-kit";
|
|
import { getLogger } from "@rakazo/logging";
|
|
import { DEFAULT_OPENROUTER_MODEL_ID } from "./deployment-model.js";
|
|
import { PiRuntimeCredentialStore, toOAuthCredential } from "./pi-credentials.js";
|
|
import { registerLocalProvider } from "./pi-local-provider.js";
|
|
import {
|
|
OPENAI_COMPATIBLE_PROVIDER_ID,
|
|
registerOpenAiCompatibleCatalog,
|
|
registerOpenAiCompatibleRuntime,
|
|
} from "./pi-openai-compatible-provider.js";
|
|
import {
|
|
billedPromptTokens,
|
|
clipToolResultContent,
|
|
clipToolResultText,
|
|
MODEL_STREAM_MAX_RETRIES,
|
|
MODEL_STREAM_TIMEOUT_MS,
|
|
resolveCompletionMaxTokens,
|
|
} from "./pi-runtime-limits.js";
|
|
|
|
// --- Model catalog ---
|
|
|
|
const REASONING_MODEL_THINKING_LEVEL: ModelThinkingLevel = "medium";
|
|
|
|
let catalogModelsCache: Models | undefined;
|
|
|
|
export function catalogModels(): Models {
|
|
catalogModelsCache ??= registerOpenAiCompatibleCatalog(registerLocalProvider(builtinModels()));
|
|
return catalogModelsCache;
|
|
}
|
|
|
|
export function thinkingLevelFor(
|
|
model: Model<Api>,
|
|
preferred?: ModelThinkingLevel | null,
|
|
): ModelThinkingLevel {
|
|
if (!model.reasoning) return "off";
|
|
if (preferred) return clampThinkingLevel(model, preferred);
|
|
return clampThinkingLevel(model, REASONING_MODEL_THINKING_LEVEL);
|
|
}
|
|
|
|
// --- Tool call budget ---
|
|
|
|
export interface ToolCallBudget {
|
|
count: number;
|
|
exceeded: boolean;
|
|
limit: number;
|
|
inFlight: number;
|
|
}
|
|
|
|
// Optional fuse is process-local. continueRun on another worker starts at zero.
|
|
const toolCallBudgetsByRun = new Map<string, ToolCallBudget>();
|
|
|
|
/** Optional self-host fuse. Unset, empty, or 0 means unlimited (default). */
|
|
export function maxToolCallsPerTurn(env: NodeJS.ProcessEnv = process.env): number {
|
|
const raw = env.MAX_TOOL_CALLS_PER_TURN?.trim();
|
|
if (!raw) return 0;
|
|
const parsed = Number(raw);
|
|
if (!Number.isFinite(parsed) || parsed <= 0) return 0;
|
|
return Math.floor(parsed);
|
|
}
|
|
|
|
export function toolCallBudgetFor(runId: string): ToolCallBudget {
|
|
const existing = toolCallBudgetsByRun.get(runId);
|
|
if (existing) {
|
|
existing.inFlight = 0;
|
|
existing.limit = maxToolCallsPerTurn();
|
|
return existing;
|
|
}
|
|
const budget: ToolCallBudget = {
|
|
count: 0,
|
|
exceeded: false,
|
|
limit: maxToolCallsPerTurn(),
|
|
inFlight: 0,
|
|
};
|
|
if (budget.limit > 0) toolCallBudgetsByRun.set(runId, budget);
|
|
return budget;
|
|
}
|
|
|
|
export function releaseToolCallBudget(runId: string, keepForResume: boolean) {
|
|
if (!keepForResume) toolCallBudgetsByRun.delete(runId);
|
|
}
|
|
|
|
export function maybeAbortToolCallBudget(host: {
|
|
toolCallBudget: ToolCallBudget;
|
|
abortTurn(): void;
|
|
}): void {
|
|
if (host.toolCallBudget.exceeded && host.toolCallBudget.inFlight === 0) {
|
|
host.abortTurn();
|
|
}
|
|
}
|
|
|
|
export function beginToolCall(host: {
|
|
toolCallBudget: ToolCallBudget;
|
|
abortTurn(): void;
|
|
queue: { push(event: AgentRuntimeEvent): void };
|
|
}): boolean {
|
|
const budget = host.toolCallBudget;
|
|
if (budget.limit <= 0) {
|
|
budget.count += 1;
|
|
return true;
|
|
}
|
|
if (budget.exceeded) {
|
|
maybeAbortToolCallBudget(host);
|
|
return false;
|
|
}
|
|
budget.count += 1;
|
|
if (budget.count <= budget.limit) {
|
|
budget.inFlight += 1;
|
|
return true;
|
|
}
|
|
if (!budget.exceeded) {
|
|
budget.exceeded = true;
|
|
host.queue.push({
|
|
type: "progress",
|
|
text: `Stopped: more than ${budget.limit} tool calls in one turn.`,
|
|
});
|
|
}
|
|
maybeAbortToolCallBudget(host);
|
|
return false;
|
|
}
|
|
|
|
export function endToolCall(host: { toolCallBudget: ToolCallBudget; abortTurn(): void }): void {
|
|
host.toolCallBudget.inFlight = Math.max(0, host.toolCallBudget.inFlight - 1);
|
|
maybeAbortToolCallBudget(host);
|
|
}
|
|
|
|
export function toolCallBudgetExceededMessage(limit: number): string {
|
|
return `I stopped after reaching the limit of ${limit} tool calls in this turn. Send another message to continue.`;
|
|
}
|
|
|
|
// --- Model resolution ---
|
|
|
|
export function configuredOpenRouterModel(id: string): Model<"openai-completions"> {
|
|
return {
|
|
id,
|
|
name: id,
|
|
api: "openai-completions",
|
|
provider: "openrouter",
|
|
baseUrl: "https://openrouter.ai/api/v1",
|
|
reasoning: true,
|
|
input: ["text"],
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
contextWindow: 16_384,
|
|
maxTokens: 4_096,
|
|
};
|
|
}
|
|
|
|
export function modelsForRequest(
|
|
request: Pick<AgentRunRequest, "model">,
|
|
provider: string,
|
|
): Models {
|
|
const oauth = request.model.oauth;
|
|
if (oauth) {
|
|
const persist = oauth.persist;
|
|
return registerOpenAiCompatibleCatalog(
|
|
registerLocalProvider(
|
|
builtinModels({
|
|
credentials: new PiRuntimeCredentialStore(
|
|
provider,
|
|
toOAuthCredential(oauth.credential),
|
|
persist ? (next) => persist(next) : undefined,
|
|
),
|
|
}),
|
|
),
|
|
);
|
|
}
|
|
if (
|
|
provider === OPENAI_COMPATIBLE_PROVIDER_ID &&
|
|
request.model.baseUrl &&
|
|
request.model.id.trim()
|
|
) {
|
|
const models = registerOpenAiCompatibleCatalog(registerLocalProvider(builtinModels()));
|
|
return registerOpenAiCompatibleRuntime(models, {
|
|
modelId: request.model.id,
|
|
baseUrl: request.model.baseUrl,
|
|
reasoning: request.model.reasoning,
|
|
acceptsImages: request.model.acceptsImages,
|
|
maxTokens: request.model.maxTokens,
|
|
contextWindow: request.model.contextWindow,
|
|
});
|
|
}
|
|
return catalogModels();
|
|
}
|
|
|
|
export function resolveRuntimeModel(modelConfig: AgentRunRequest["model"]): {
|
|
provider: string;
|
|
modelId: string;
|
|
models: Models;
|
|
model: Model<Api> | undefined;
|
|
apiKey: string | undefined;
|
|
} {
|
|
const provider = modelConfig.provider === "scripted" ? "openrouter" : modelConfig.provider;
|
|
const envDefaultModel = process.env.PI_DEFAULT_MODEL?.trim();
|
|
const envDefaultProvider = process.env.PI_DEFAULT_PROVIDER?.trim() || "openrouter";
|
|
const modelId =
|
|
modelConfig.id === "scripted"
|
|
? envDefaultModel || DEFAULT_OPENROUTER_MODEL_ID
|
|
: modelConfig.id.trim();
|
|
const models = modelsForRequest({ model: modelConfig }, provider);
|
|
let model = models.getModel(provider, modelId);
|
|
if (!model && provider !== "openrouter" && provider !== OPENAI_COMPATIBLE_PROVIDER_ID) {
|
|
model = models.getModel("openrouter", modelId);
|
|
}
|
|
if (
|
|
!model &&
|
|
provider === "openrouter" &&
|
|
envDefaultProvider === "openrouter" &&
|
|
modelId === envDefaultModel
|
|
) {
|
|
model = configuredOpenRouterModel(modelId);
|
|
}
|
|
const apiKey = modelConfig.oauth
|
|
? undefined
|
|
: modelConfig.provider === OPENAI_COMPATIBLE_PROVIDER_ID
|
|
? modelConfig.apiKey || "local"
|
|
: (modelConfig.apiKey ??
|
|
(provider === "openrouter" ? process.env.OPENROUTER_API_KEY : undefined));
|
|
return { provider, modelId, models, model, apiKey };
|
|
}
|
|
|
|
// --- Image helpers ---
|
|
|
|
export function toPiImages(images: AgentRunRequest["currentTurnImages"]) {
|
|
return (images ?? []).map((image) => ({
|
|
type: "image" as const,
|
|
data: Buffer.from(image.data).toString("base64"),
|
|
mimeType: image.mimeType,
|
|
}));
|
|
}
|
|
|
|
// --- Steering message removal ---
|
|
|
|
export function withoutSteeringMessages(
|
|
history: AgentRunRequest["history"],
|
|
steering: AgentSteeringMessage[],
|
|
): AgentRunRequest["history"] {
|
|
if (steering.length === 0) return history;
|
|
const result = [...history];
|
|
let beforeIndex = result.length - 1;
|
|
for (let steeringIndex = steering.length - 1; steeringIndex >= 0; steeringIndex -= 1) {
|
|
const steeringMessage = steering[steeringIndex];
|
|
for (let index = beforeIndex; index >= 0; index -= 1) {
|
|
const message = result[index];
|
|
if (
|
|
message?.role !== "user" ||
|
|
(message.id
|
|
? message.id !== steeringMessage?.messageId
|
|
: message.content !== (steeringMessage?.historyText ?? steeringMessage?.text))
|
|
) {
|
|
continue;
|
|
}
|
|
result.splice(index, 1);
|
|
beforeIndex = index - 1;
|
|
break;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// --- Request secret arguments ---
|
|
|
|
export function prepareRequestSecretArguments(raw: Record<string, unknown>) {
|
|
return {
|
|
label: String(raw.label ?? "Code"),
|
|
purpose: String(raw.purpose ?? "otp"),
|
|
...(raw.connectionId ? { connectionId: String(raw.connectionId) } : {}),
|
|
...(raw.credential ? { credential: raw.credential } : {}),
|
|
...(raw.replace === true ? { replace: true } : {}),
|
|
};
|
|
}
|
|
|
|
// --- Screenshot context pruning ---
|
|
|
|
const DEFAULT_COMPUTER_SCREENSHOTS_TO_KEEP = 2;
|
|
|
|
export function pruneComputerScreenshotContext(
|
|
messages: AgentMessage[],
|
|
maxImagesPerPrompt?: number,
|
|
): AgentMessage[] {
|
|
const imageLimit =
|
|
maxImagesPerPrompt === undefined
|
|
? undefined
|
|
: Number.isFinite(maxImagesPerPrompt)
|
|
? Math.max(0, Math.floor(maxImagesPerPrompt))
|
|
: DEFAULT_COMPUTER_SCREENSHOTS_TO_KEEP;
|
|
let remaining = imageLimit ?? DEFAULT_COMPUTER_SCREENSHOTS_TO_KEEP;
|
|
if (imageLimit !== undefined) {
|
|
const nonScreenshotImages = messages.reduce(
|
|
(count, message) =>
|
|
isComputerScreenshotMessage(message) ? count : count + imagePartCount(message),
|
|
0,
|
|
);
|
|
if (nonScreenshotImages > imageLimit) {
|
|
throw new Error(
|
|
`The configured model image limit is ${imageLimit}, but the prompt contains ${nonScreenshotImages} non-screenshot images.`,
|
|
);
|
|
}
|
|
remaining = imageLimit - nonScreenshotImages;
|
|
}
|
|
let transformed: AgentMessage[] | undefined;
|
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
const message = messages[index];
|
|
if (!isComputerScreenshotMessage(message)) continue;
|
|
const images = imagePartCount(message);
|
|
if (remaining >= images) {
|
|
remaining -= images;
|
|
continue;
|
|
}
|
|
transformed ??= [...messages];
|
|
transformed[index] = {
|
|
...message,
|
|
content: message.content.filter((part) => part.type !== "image"),
|
|
};
|
|
}
|
|
return transformed ?? messages;
|
|
}
|
|
|
|
export function imagePartCount(message: AgentMessage): number {
|
|
if (!("content" in message) || !Array.isArray(message.content)) return 0;
|
|
return message.content.filter(
|
|
(part: unknown) =>
|
|
typeof part === "object" &&
|
|
part !== null &&
|
|
"type" in part &&
|
|
(part as { type?: string }).type === "image",
|
|
).length;
|
|
}
|
|
|
|
export function isComputerScreenshotMessage(
|
|
message: AgentMessage | undefined,
|
|
): message is Extract<AgentMessage, { role: "toolResult" }> {
|
|
if (
|
|
message?.role !== "toolResult" ||
|
|
!message.content.some((part) => (part as { type?: string }).type === "image")
|
|
) {
|
|
return false;
|
|
}
|
|
const details = message.details;
|
|
return Boolean(
|
|
details &&
|
|
typeof details === "object" &&
|
|
"frameId" in details &&
|
|
typeof (details as { frameId?: unknown }).frameId === "string",
|
|
);
|
|
}
|
|
|
|
// --- Type guards ---
|
|
|
|
export function isAgentToolExecutionResult(result: unknown): result is AgentToolExecutionResult {
|
|
if (
|
|
!result ||
|
|
typeof result !== "object" ||
|
|
(result as { kind?: unknown }).kind !== "agent_tool_result" ||
|
|
!("content" in result)
|
|
) {
|
|
return false;
|
|
}
|
|
const content = (result as { content?: unknown }).content;
|
|
return (
|
|
Array.isArray(content) &&
|
|
content.every(
|
|
(item) =>
|
|
item &&
|
|
typeof item === "object" &&
|
|
((item as { type?: unknown }).type === "text" ||
|
|
(item as { type?: unknown }).type === "image"),
|
|
)
|
|
);
|
|
}
|
|
|
|
// --- JSON Schema helpers ---
|
|
|
|
export function jsonSchemaParameters(
|
|
schema: Record<string, unknown>,
|
|
): ReturnType<typeof Type.Object> {
|
|
const alternatives = Array.isArray(schema.oneOf)
|
|
? schema.oneOf
|
|
: Array.isArray(schema.anyOf)
|
|
? schema.anyOf
|
|
: undefined;
|
|
if (alternatives && alternatives.length > 0 && schema.properties == null) {
|
|
return Type.Union(
|
|
alternatives.map((variant) => jsonSchemaParameters(variant as Record<string, unknown>)),
|
|
) as unknown as ReturnType<typeof Type.Object>;
|
|
}
|
|
const properties = (schema.properties ?? {}) as Record<string, unknown>;
|
|
const required = new Set(Array.isArray(schema.required) ? schema.required.map(String) : []);
|
|
const fields: Record<string, ReturnType<typeof Type.Optional>> = {};
|
|
for (const [key, spec] of Object.entries(properties)) {
|
|
const field = jsonField(spec);
|
|
fields[key] = (required.has(key) ? field : Type.Optional(field)) as unknown as ReturnType<
|
|
typeof Type.Optional
|
|
>;
|
|
}
|
|
return schema.additionalProperties === false
|
|
? Type.Object(fields, { additionalProperties: false })
|
|
: Type.Object(fields);
|
|
}
|
|
|
|
export function enumUnion(values: readonly unknown[]) {
|
|
const members = values.map((value) =>
|
|
value === null
|
|
? Type.Null()
|
|
: typeof value === "string" || typeof value === "number" || typeof value === "boolean"
|
|
? Type.Literal(value)
|
|
: undefined,
|
|
);
|
|
return members.every((member) => member !== undefined) ? Type.Union(members) : undefined;
|
|
}
|
|
|
|
export function jsonField(spec: unknown): ReturnType<typeof Type.String> {
|
|
const definition = spec && typeof spec === "object" ? (spec as Record<string, unknown>) : {};
|
|
if (Array.isArray(definition.enum) && definition.enum.length > 0) {
|
|
const union = enumUnion(definition.enum);
|
|
if (union) return union as never;
|
|
}
|
|
if ("const" in definition) {
|
|
const literal = enumUnion([definition.const]);
|
|
if (literal) return literal as never;
|
|
}
|
|
const variants = Array.isArray(definition.oneOf)
|
|
? definition.oneOf
|
|
: Array.isArray(definition.anyOf)
|
|
? definition.anyOf
|
|
: undefined;
|
|
if (variants && variants.length > 0) {
|
|
return Type.Union(variants.map((variant) => jsonField(variant))) as never;
|
|
}
|
|
if (Array.isArray(definition.type) && definition.type.length > 0) {
|
|
return Type.Union(definition.type.map((type) => jsonField({ ...definition, type }))) as never;
|
|
}
|
|
const type = "type" in definition ? String(definition.type) : "string";
|
|
if (type === "null") return Type.Null() as never;
|
|
if (type === "number" || type === "integer") return Type.Number() as never;
|
|
if (type === "boolean") return Type.Boolean() as never;
|
|
if (type === "array") {
|
|
const options: {
|
|
minItems?: number;
|
|
maxItems?: number;
|
|
uniqueItems?: boolean;
|
|
} = {};
|
|
if (typeof definition.minItems === "number") options.minItems = definition.minItems;
|
|
if (typeof definition.maxItems === "number") options.maxItems = definition.maxItems;
|
|
if (definition.uniqueItems === true) options.uniqueItems = true;
|
|
return Type.Array(jsonField(definition.items), options) as never;
|
|
}
|
|
if (type === "object") return jsonSchemaParameters(definition) as never;
|
|
return Type.String();
|
|
}
|
|
|
|
// --- Result helpers ---
|
|
|
|
export function summarizeToolResult(result: unknown) {
|
|
try {
|
|
const text = JSON.stringify(result);
|
|
if (!text) return "ok";
|
|
return clipToolResultText(text);
|
|
} catch {
|
|
return "ok";
|
|
}
|
|
}
|
|
|
|
export function boundAgentToolResult<T>(result: AgentToolResult<T>): AgentToolResult<T> {
|
|
if (!result || !Array.isArray(result.content)) return result;
|
|
return {
|
|
...result,
|
|
content: clipToolResultContent(result.content),
|
|
};
|
|
}
|
|
|
|
export function assistantText(message: unknown): string {
|
|
if (!message || typeof message !== "object" || !("content" in message)) return "";
|
|
const content = (message as { content?: unknown }).content;
|
|
if (typeof content === "string") return content;
|
|
if (!Array.isArray(content)) return "";
|
|
return content
|
|
.map((part) =>
|
|
part && typeof part === "object" && "type" in part && part.type === "text" && "text" in part
|
|
? String(part.text)
|
|
: "",
|
|
)
|
|
.join("");
|
|
}
|
|
|
|
// --- Sanitization ---
|
|
|
|
export function sanitizeSensitiveText(message: string) {
|
|
return message
|
|
.replace(/sk-or-v1-[a-zA-Z0-9]+/g, "[redacted]")
|
|
.replace(/sk-[a-zA-Z0-9-]+/g, "[redacted]")
|
|
.replace(/Bearer\s+[^\s"',;&]+/gi, "Bearer [redacted]")
|
|
.replace(/eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+/g, "[redacted]")
|
|
.replace(/COMPOSIO_API_KEY[=:]?\s*\S+/gi, "COMPOSIO_API_KEY=[redacted]")
|
|
.replace(
|
|
/((?:api[_-]?key|access[_-]?token|password|secret)\s*[=:]\s*)[^\s"',;&]+/gi,
|
|
"$1[redacted]",
|
|
)
|
|
.replace(/((?:auth|authorization)\s*[=:]\s*)(?!Bearer\b)[^\s"',;&]+/gi, "$1[redacted]");
|
|
}
|
|
|
|
export function redactActivityUrl(value: unknown): string {
|
|
const raw = String(value ?? "").trim();
|
|
if (!raw) return raw;
|
|
try {
|
|
const url = new URL(raw);
|
|
url.username = "";
|
|
url.password = "";
|
|
url.search = "";
|
|
url.hash = "";
|
|
return url.toString();
|
|
} catch {
|
|
return "[invalid URL]";
|
|
}
|
|
}
|
|
|
|
export function sanitizeError(message: string) {
|
|
return sanitizeSensitiveText(message);
|
|
}
|
|
|
|
// --- Session ID & provider helpers ---
|
|
|
|
export function conversationSessionId(threadId: string, botId: string, agentId?: string): string {
|
|
return agentId ? `${threadId}:${botId}:${agentId}` : `${threadId}:${botId}`;
|
|
}
|
|
|
|
export function isOpenCodeProvider(provider: string): boolean {
|
|
return provider === "opencode" || provider === "opencode-go";
|
|
}
|
|
|
|
const OPENCODE_SESSION_ERROR = "OpenCode rejected this chat session. Send the message again.";
|
|
|
|
export function looksLikeOpenCodeSessionError(message: string): boolean {
|
|
return (
|
|
/x-opencode-session/i.test(message) ||
|
|
/session\s*(id|header|required|missing|invalid|expired|stale)/i.test(message) ||
|
|
/model is unavailable/i.test(message)
|
|
);
|
|
}
|
|
|
|
export function sanitizeProviderError(provider: string, message: string): string {
|
|
const sanitized = sanitizeError(message);
|
|
if (isOpenCodeProvider(provider) && looksLikeOpenCodeSessionError(sanitized)) {
|
|
return OPENCODE_SESSION_ERROR;
|
|
}
|
|
return sanitized;
|
|
}
|
|
|
|
// --- Queue & gate ---
|
|
|
|
export interface EventQueue {
|
|
push(event: AgentRuntimeEvent): void;
|
|
fail(error: Error): void;
|
|
close(): void;
|
|
iterate(): AsyncIterable<AgentRuntimeEvent>;
|
|
}
|
|
|
|
export function createQueue(): EventQueue {
|
|
const items: AgentRuntimeEvent[] = [];
|
|
let wake: (() => void) | undefined;
|
|
let closed = false;
|
|
let failure: Error | undefined;
|
|
return {
|
|
push(event) {
|
|
items.push(event);
|
|
wake?.();
|
|
},
|
|
fail(error) {
|
|
failure = error;
|
|
closed = true;
|
|
wake?.();
|
|
},
|
|
close() {
|
|
closed = true;
|
|
wake?.();
|
|
},
|
|
async *iterate() {
|
|
while (true) {
|
|
if (items.length) {
|
|
yield items.shift()!;
|
|
continue;
|
|
}
|
|
if (failure) throw failure;
|
|
if (closed) return;
|
|
await new Promise<void>((resolve) => {
|
|
wake = resolve;
|
|
});
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
export function createGate(max: number) {
|
|
let active = 0;
|
|
const waiters: Array<() => void> = [];
|
|
return {
|
|
async acquire() {
|
|
if (active >= max) {
|
|
await new Promise<void>((resolve) => {
|
|
waiters.push(resolve);
|
|
});
|
|
}
|
|
active += 1;
|
|
},
|
|
release() {
|
|
active = Math.max(0, active - 1);
|
|
waiters.shift()?.();
|
|
},
|
|
};
|
|
}
|
|
|
|
// --- Model completion ---
|
|
|
|
export function modelForCompletion(model: Model<Api>, configuredMaxTokens?: number): Model<Api> {
|
|
const maxTokens = resolveCompletionMaxTokens(model.maxTokens, configuredMaxTokens);
|
|
if (maxTokens === model.maxTokens) return model;
|
|
return { ...model, maxTokens };
|
|
}
|
|
|
|
// --- Reliable streaming ---
|
|
|
|
export function reliableStreamOptions(
|
|
model: Pick<Model<Api>, "api" | "provider" | "maxTokens">,
|
|
options?: SimpleStreamOptions,
|
|
configuredMaxTokens?: number,
|
|
): SimpleStreamOptions {
|
|
let next: SimpleStreamOptions = {
|
|
...options,
|
|
timeoutMs: options?.timeoutMs ?? MODEL_STREAM_TIMEOUT_MS,
|
|
maxRetries: options?.maxRetries ?? MODEL_STREAM_MAX_RETRIES,
|
|
maxTokens: resolveCompletionMaxTokens(model.maxTokens, configuredMaxTokens, options?.maxTokens),
|
|
};
|
|
|
|
if (model.provider === "openai-codex" || model.api === "openai-codex-responses") {
|
|
next = { ...next, transport: "sse" };
|
|
}
|
|
|
|
if (isOpenCodeProvider(model.provider)) {
|
|
const sessionId = next.sessionId?.trim() || randomUUID();
|
|
next = {
|
|
...next,
|
|
sessionId,
|
|
headers: {
|
|
"x-opencode-session": sessionId,
|
|
"x-opencode-client": "rakazo",
|
|
...next.headers,
|
|
},
|
|
};
|
|
}
|
|
|
|
return next;
|
|
}
|
|
|
|
// --- Tool host interface ---
|
|
|
|
export interface ToolHost {
|
|
queue: EventQueue;
|
|
request: AgentRunRequest;
|
|
models: Models;
|
|
model: Model<Api>;
|
|
apiKey: string | undefined;
|
|
nestedAgents: Set<Agent>;
|
|
subagentGate: { acquire(): Promise<void>; release(): void };
|
|
toolCallBudget: ToolCallBudget;
|
|
toolCallSeq: { value: number };
|
|
abortTurn(): void;
|
|
signal: AbortSignal;
|
|
depth: number;
|
|
pausePending: boolean;
|
|
}
|