Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
import {
AbsolutePathSchema,
IdSchema,
SKILL_CONTRACT_MAX_CHARS,
SkillContractSchema,
SkillContractWireSchema,
SkillDescriptionSchema,
SkillDocumentBaseSchema,
SkillNameSchema,
SkillParamSchema,
SkillSchema,
SkillVersionSchema,
WorkflowInputValuesSchema,
WorkflowParamValuesSchema,
WorkflowPrecheckFailureSchema,
WorkflowVerificationSchema,
WorkflowWarningSchema,
} from "@pibot/protocol-base";
import { z } from "zod";
/** A Bot lists at most this many workflow skills (its skills are bounded the same way). */
export const WORKFLOW_LIST_MAX = 50;
/** The editor and brain share this exact contract boundary; the wire shape stays opaque below. */
const WorkflowDocumentBaseSchema = SkillDocumentBaseSchema.extend({
contract: SkillContractSchema,
});
export const WorkflowDocumentSchema = WorkflowDocumentBaseSchema.superRefine((document, issues) => {
if (JSON.stringify(document.contract).length > SKILL_CONTRACT_MAX_CHARS)
issues.addIssue({ code: "custom", message: "Contract too large", path: ["contract"] });
});
const WorkflowDocumentWireSchema = WorkflowDocumentBaseSchema.extend({
contract: SkillContractWireSchema,
});
/**
* One skill with a work contract, everything a「运行工作流」form needs: the inputs to ask
* for (`contract.inputs`), the `{param}` defaults and what the program will check. `contract` is
* null when it is invalid (`warnings` says so); the skill still works as an ordinary skill.
*/
export const WorkflowSummarySchema = z.strictObject({
skillId: IdSchema,
name: SkillNameSchema,
description: SkillDescriptionSchema,
enabled: z.boolean(),
version: SkillVersionSchema.nullable(),
verified: WorkflowVerificationSchema.optional(),
contract: SkillContractSchema.nullable(),
params: z.array(SkillParamSchema).max(20),
warnings: z.array(WorkflowWarningSchema).max(7),
});
/**
* One of a group's saved plans (「常用计划」): a member's group workflow saved from a passed
* dynamic plan. Run it with `skills.runWorkflow` and this `botId` / `skillId` in the group.
*/
export const SavedPlanSummarySchema = z.strictObject({
botId: IdSchema,
skillId: IdSchema,
name: SkillNameSchema,
description: SkillDescriptionSchema,
enabled: z.boolean(),
version: SkillVersionSchema.nullable(),
stepCount: z.number().int().min(1).max(20),
estimatedCostUsd: z.number().nonnegative().max(10_000),
});
/** Where a manual run goes: a private chat topic (default: the current one) or a group member. */
const target = z.strictObject({
botId: IdSchema,
groupId: IdSchema.optional(),
/** Private chat topic, or the group's topic; the current one when omitted. */
conversationId: IdSchema.optional(),
});
export const WorkflowStartedSchema = z.strictObject({
status: z.literal("started"),
runId: IdSchema,
conversationId: IdSchema,
userMessageId: IdSchema,
assistantMessageId: IdSchema,
groupId: IdSchema.optional(),
});
/** Pre-checks failed before any model was involved; nothing was sent or started. */
export const WorkflowBlockedSchema = z.strictObject({
status: z.literal("blocked"),
code: z.literal("workflow_precheck_failed"),
failures: z.array(WorkflowPrecheckFailureSchema).min(1).max(12),
});
export const WorkflowOwnersRequiredSchema = z.strictObject({
status: z.literal("owners_required"),
roles: z
.array(
z.strictObject({
role: z.string().min(1).max(64),
candidates: z
.array(z.strictObject({ botId: IdSchema, name: z.string().min(1).max(200) }))
.min(1)
.max(6),
}),
)
.min(1)
.max(20),
});
/**
* Cost estimate before a run, from the app's own budget ledger (no model call): the median
* known cost of the last finished runs of this workflow (same skill and version) for this Bot in
* private chat, or in this group. `estimateUsd` is null without priced history; `capUsd` is the
* contract's cost cap (the ceiling a run may lower, never raise).
*/
export const WORKFLOW_ESTIMATE_SAMPLES = 5;
export const WorkflowEstimateSchema = z.strictObject({
estimateUsd: z.number().nonnegative().finite().nullable(),
samples: z.number().int().min(0).max(WORKFLOW_ESTIMATE_SAMPLES),
capUsd: z.number().positive().max(10_000).nullable(),
});
export const WorkflowMethods = {
/** Creates an owned workflow skill; the folder slug is generated by brain. */
"skills.createWorkflow": {
params: target.omit({ conversationId: true }).extend({
requestId: IdSchema,
document: WorkflowDocumentWireSchema,
/**
* Saving a `groups.plan.template` draft. The brain checks that this is a passed
* dynamic plan of the group before recording the provenance (「常用计划」); error
* `workflow_plan_source_invalid`.
*/
fromPlan: z.strictObject({ workflowRunId: IdSchema }).optional(),
}),
result: SkillSchema,
},
/** The member's effective skills in a group, like its runs use. */
"skills.workflows": {
params: target.omit({ conversationId: true }),
result: z.strictObject({ items: z.array(WorkflowSummarySchema).max(WORKFLOW_LIST_MAX) }),
},
/** The group's saved plans across its members (bounded like `skills.workflows`). */
"skills.savedPlans": {
params: z.strictObject({ groupId: IdSchema }),
result: z.strictObject({ items: z.array(SavedPlanSummarySchema).max(WORKFLOW_LIST_MAX) }),
},
"skills.planSaveState": {
params: z.strictObject({ groupId: IdSchema, workflowRunId: IdSchema }),
result: z.strictObject({ state: z.enum(["available", "saved", "rerun", "unavailable"]) }),
},
"skills.workflowEstimate": {
params: target.omit({ conversationId: true }).extend({ skillId: IdSchema }),
result: WorkflowEstimateSchema,
},
/** Native picker stays behind the brain capability; the renderer never receives host RPCs. */
"skills.pickWorkflowInput": {
params: target.omit({ conversationId: true }).extend({
kind: z.enum(["folder", "file"]),
defaultPath: AbsolutePathSchema.optional(),
}),
result: AbsolutePathSchema.nullable(),
},
/**
* Starts a run of a workflow skill. Errors: `skill_not_found`, `workflow_not_contract`,
* `workflow_contract_invalid`, `workflow_input_unknown`, `workflow_param_unknown` (invalid
* params) and the usual chat admission errors (`busy`, `no_model`, …).
*/
"skills.runWorkflow": {
params: target.extend({
skillId: IdSchema,
params: WorkflowParamValuesSchema.default({}),
inputs: WorkflowInputValuesSchema.default({}),
/**
* Start in a new topic (default). A workflow's state travels in files (this period's
* inputs, the previous period's folder, the receipt), so earlier periods' chat only made
* every request longer (in a real-material trial a coordinator's requests grew from ~14k to ~36k tokens).
*/
freshTopic: z.boolean().default(true),
/**
* This run's cost cap, at most the contract's `budget.costUsd`. Errors:
* `workflow_budget_above_contract` (higher than a declared contract cap).
*/
costCapUsd: z.number().positive().max(10_000).optional(),
ownerOverrides: z
.record(z.string().min(1).max(64), IdSchema)
.refine((value) => Object.keys(value).length <= 20)
.optional(),
}),
result: z.discriminatedUnion("status", [
WorkflowStartedSchema,
WorkflowBlockedSchema,
WorkflowOwnersRequiredSchema,
]),
},
} as const;
export type WorkflowDocument = z.output<typeof WorkflowDocumentSchema>;
export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
export type SavedPlanSummary = z.infer<typeof SavedPlanSummarySchema>;
export type WorkflowEstimate = z.infer<typeof WorkflowEstimateSchema>;
export type WorkflowRunResult = z.infer<(typeof WorkflowMethods)["skills.runWorkflow"]["result"]>;