The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as dialogflow from "@distilled.cloud/gcp/dialogflow_v3"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | collectionParent, |
| 13 | DEFAULT_LOCATION, |
| 14 | encodeOwnershipLine, |
| 15 | expandAgent, |
| 16 | fingerprint, |
| 17 | hasOwnershipMarker, |
| 18 | internalLabels, |
| 19 | lastSegment, |
| 20 | locationOf, |
| 21 | namedAgents, |
| 22 | normalizeLocation, |
| 23 | ownedByAlchemy, |
| 24 | parentOf, |
| 25 | parseOwnership, |
| 26 | projectOf, |
| 27 | sameText, |
| 28 | toResourceId, |
| 29 | updateMaskOf, |
| 30 | retryQuota, |
| 31 | } from "./internal.ts"; |
| 32 | |
| 33 | export type PlaybookType = "PLAYBOOK_TYPE_UNSPECIFIED" | "TASK" | "ROUTINE"; |
| 34 | |
| 35 | export type PlaybookStep = { |
| 36 | /** Instruction text for this step. */ |
| 37 | text?: string; |
| 38 | /** Nested steps. */ |
| 39 | steps?: PlaybookStep[]; |
| 40 | }; |
| 41 | |
| 42 | export type PlaybookInstruction = { |
| 43 | /** Free-form guidelines. */ |
| 44 | guidelines?: string; |
| 45 | /** Ordered steps. */ |
| 46 | steps?: PlaybookStep[]; |
| 47 | }; |
| 48 | |
| 49 | export type PlaybookParameterDefinition = { |
| 50 | /** Parameter name. */ |
| 51 | name?: string; |
| 52 | /** Parameter type (`STRING`, `NUMBER`, …). */ |
| 53 | type?: string; |
| 54 | /** Human-readable description. */ |
| 55 | description?: string; |
| 56 | }; |
| 57 | |
| 58 | export type PlaybookLlmModelSettings = { |
| 59 | /** LLM model id. */ |
| 60 | model?: string; |
| 61 | /** Model prompt text. */ |
| 62 | promptText?: string; |
| 63 | }; |
| 64 | |
| 65 | export type AgentsPlaybookProps = { |
| 66 | /** |
| 67 | * Parent agent resource name |
| 68 | * `projects/{project}/locations/{location}/agents/{agent}`. |
| 69 | * Immutable — changing it replaces the playbook. |
| 70 | */ |
| 71 | agent: string; |
| 72 | /** |
| 73 | * Playbook id (the `{playbook}` segment). Server-assigned when omitted. |
| 74 | * Immutable — changing it replaces the playbook. |
| 75 | */ |
| 76 | playbookId?: string; |
| 77 | /** |
| 78 | * Location used when `agent` is an id rather than a resource name. |
| 79 | * Immutable — changing it replaces the playbook. |
| 80 | * @default "global" |
| 81 | */ |
| 82 | location?: string; |
| 83 | /** |
| 84 | * Human-readable name. Playbooks have no labels field, so Alchemy |
| 85 | * stamps ownership into this field and strips it from attributes. |
| 86 | */ |
| 87 | displayName?: string; |
| 88 | /** |
| 89 | * High-level goal of the playbook. |
| 90 | * @default "Handle the user request." |
| 91 | */ |
| 92 | goal?: string; |
| 93 | /** Instruction block (guidelines and steps). */ |
| 94 | instruction?: PlaybookInstruction; |
| 95 | /** |
| 96 | * Playbook kind. |
| 97 | * @default "TASK" |
| 98 | */ |
| 99 | playbookType?: PlaybookType | (string & {}); |
| 100 | /** Referenced tool resource names. */ |
| 101 | referencedTools?: string[]; |
| 102 | /** Referenced playbook resource names. */ |
| 103 | referencedPlaybooks?: string[]; |
| 104 | /** Referenced flow resource names. */ |
| 105 | referencedFlows?: string[]; |
| 106 | /** LLM model settings. */ |
| 107 | llmModelSettings?: PlaybookLlmModelSettings; |
| 108 | /** Inline code block. */ |
| 109 | codeBlock?: { code?: string }; |
| 110 | /** Input parameter definitions. */ |
| 111 | inputParameterDefinitions?: PlaybookParameterDefinition[]; |
| 112 | /** Output parameter definitions. */ |
| 113 | outputParameterDefinitions?: PlaybookParameterDefinition[]; |
| 114 | }; |
| 115 | |
| 116 | export type AgentsPlaybook = Resource< |
| 117 | "GCP.Dialogflow.AgentsPlaybook", |
| 118 | AgentsPlaybookProps, |
| 119 | { |
| 120 | /** Full resource name `.../agents/{agent}/playbooks/{playbook}`. */ |
| 121 | name: string; |
| 122 | /** Playbook id (last path segment). */ |
| 123 | playbookId: string; |
| 124 | /** Parent agent resource name. */ |
| 125 | agent: string; |
| 126 | /** Location id. */ |
| 127 | location: string; |
| 128 | /** Project id. */ |
| 129 | project: string; |
| 130 | /** User display name with the Alchemy ownership prefix stripped. */ |
| 131 | displayName: string | undefined; |
| 132 | /** Goal. */ |
| 133 | goal: string | undefined; |
| 134 | /** Instruction block. */ |
| 135 | instruction: PlaybookInstruction | undefined; |
| 136 | /** Playbook kind. */ |
| 137 | playbookType: string | undefined; |
| 138 | /** Referenced tools. */ |
| 139 | referencedTools: string[]; |
| 140 | /** Referenced playbooks. */ |
| 141 | referencedPlaybooks: string[]; |
| 142 | /** Referenced flows. */ |
| 143 | referencedFlows: string[]; |
| 144 | /** LLM model settings. */ |
| 145 | llmModelSettings: PlaybookLlmModelSettings | undefined; |
| 146 | /** Token count. */ |
| 147 | tokenCount: string | undefined; |
| 148 | /** RFC3339 create timestamp. */ |
| 149 | createTime: string | undefined; |
| 150 | /** RFC3339 update timestamp. */ |
| 151 | updateTime: string | undefined; |
| 152 | }, |
| 153 | never, |
| 154 | Providers |
| 155 | >; |
| 156 | |
| 157 | /** |
| 158 | * A Dialogflow CX playbook (goal-driven LLM workflow). |
| 159 | * |
| 160 | * Playbooks have no labels field — Alchemy stamps ownership into |
| 161 | * `displayName` so `list` / nuke can find them. Parent agent and id are |
| 162 | * immutable. Display name, goal, instruction, type, references, and LLM |
| 163 | * settings update in place. |
| 164 | * |
| 165 | * ### Creating a Playbook |
| 166 | * **Example:** Task playbook |
| 167 | * ```typescript |
| 168 | * const playbook = yield* GCP.Dialogflow.AgentsPlaybook("Support", { |
| 169 | * agent: agentName, |
| 170 | * displayName: "support", |
| 171 | * goal: "Answer the user's support question.", |
| 172 | * }); |
| 173 | * ``` |
| 174 | * |
| 175 | * ### Updating a Playbook |
| 176 | * Change props on the same logical id; the engine keeps the physical id. |
| 177 | * |
| 178 | * **Example:** Narrow the goal |
| 179 | * ```typescript |
| 180 | * const playbook = yield* GCP.Dialogflow.AgentsPlaybook("Support", { |
| 181 | * agent: agentName, |
| 182 | * displayName: "support", |
| 183 | * goal: "Reset the user's password.", |
| 184 | * }); |
| 185 | * ``` |
| 186 | * |
| 187 | * @resource |
| 188 | * @category Dialogflow |
| 189 | */ |
| 190 | export const AgentsPlaybook = Resource<AgentsPlaybook>("GCP.Dialogflow.AgentsPlaybook"); |
| 191 | |
| 192 | export class AgentsPlaybookNotResolved extends Data.TaggedError( |
| 193 | "GCP.Dialogflow.AgentsPlaybookNotResolved", |
| 194 | )<{ |
| 195 | resourceName: string; |
| 196 | }> {} |
| 197 | |
| 198 | const DEFAULT_GOAL = "Handle the user request."; |
| 199 | const DEFAULT_TYPE: PlaybookType = "TASK"; |
| 200 | |
| 201 | const resourceName = (agent: string, playbookId: string) => `${agent}/playbooks/${playbookId}`; |
| 202 | |
| 203 | const stepsOf = ( |
| 204 | steps: dialogflow.GoogleCloudDialogflowCxV3PlaybookStepList | undefined, |
| 205 | ): PlaybookStep[] | undefined => { |
| 206 | if (steps === undefined) return undefined; |
| 207 | return steps.map((step) => ({ |
| 208 | text: step.text, |
| 209 | steps: stepsOf(step.steps), |
| 210 | })); |
| 211 | }; |
| 212 | |
| 213 | const instructionOf = ( |
| 214 | instruction: dialogflow.GoogleCloudDialogflowCxV3PlaybookInstruction | undefined, |
| 215 | ): PlaybookInstruction | undefined => { |
| 216 | if (instruction === undefined) return undefined; |
| 217 | return { |
| 218 | guidelines: instruction.guidelines, |
| 219 | steps: stepsOf(instruction.steps), |
| 220 | }; |
| 221 | }; |
| 222 | |
| 223 | const toAttrs = ( |
| 224 | playbook: dialogflow.GoogleCloudDialogflowCxV3Playbook, |
| 225 | project: string, |
| 226 | agentHint?: string, |
| 227 | ) => { |
| 228 | const name = playbook.name ?? ""; |
| 229 | return { |
| 230 | name, |
| 231 | playbookId: lastSegment(name), |
| 232 | agent: name.includes("/playbooks/") |
| 233 | ? collectionParent(name, "agents") |
| 234 | : (agentHint ?? parentOf(name)), |
| 235 | location: locationOf(name), |
| 236 | project: projectOf(name) || project, |
| 237 | displayName: parseOwnership(playbook.displayName).text, |
| 238 | goal: playbook.goal, |
| 239 | instruction: instructionOf(playbook.instruction), |
| 240 | playbookType: playbook.playbookType, |
| 241 | referencedTools: [...(playbook.referencedTools ?? [])], |
| 242 | referencedPlaybooks: [...(playbook.referencedPlaybooks ?? [])], |
| 243 | referencedFlows: [...(playbook.referencedFlows ?? [])], |
| 244 | llmModelSettings: playbook.llmModelSettings |
| 245 | ? { |
| 246 | model: playbook.llmModelSettings.model, |
| 247 | promptText: playbook.llmModelSettings.promptText, |
| 248 | } |
| 249 | : undefined, |
| 250 | tokenCount: playbook.tokenCount, |
| 251 | createTime: playbook.createTime, |
| 252 | updateTime: playbook.updateTime, |
| 253 | }; |
| 254 | }; |
| 255 | |
| 256 | const getByName = (name: string) => |
| 257 | name.length === 0 |
| 258 | ? Effect.undefined |
| 259 | : dialogflow |
| 260 | .getProjectsLocationsAgentsPlaybooks({ name }) |
| 261 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 262 | |
| 263 | const listAt = (parent: string, project: string) => |
| 264 | dialogflow.listProjectsLocationsAgentsPlaybooks.pages({ parent, pageSize: 100 }).pipe( |
| 265 | Stream.flatMap((page) => Stream.fromIterable(page.playbooks ?? [])), |
| 266 | Stream.filter((playbook) => hasOwnershipMarker(playbook.displayName)), |
| 267 | Stream.map((playbook) => toAttrs(playbook, project, parent)), |
| 268 | Stream.runCollect, |
| 269 | Effect.map((chunk) => Array.from(chunk)), |
| 270 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 271 | ); |
| 272 | |
| 273 | const findByDisplayName = (parent: string, displayName: string) => |
| 274 | dialogflow.listProjectsLocationsAgentsPlaybooks.pages({ parent, pageSize: 100 }).pipe( |
| 275 | Stream.flatMap((page) => Stream.fromIterable(page.playbooks ?? [])), |
| 276 | Stream.filter((playbook) => playbook.displayName === displayName), |
| 277 | Stream.runHead, |
| 278 | Effect.map((option) => (option._tag === "Some" ? option.value : undefined)), |
| 279 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 280 | ); |
| 281 | |
| 282 | export const AgentsPlaybookProvider = () => |
| 283 | Provider.succeed(AgentsPlaybook, { |
| 284 | stables: ["name", "playbookId", "agent", "location", "project", "createTime"], |
| 285 | |
| 286 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 287 | if (!isResolved(news)) return undefined; |
| 288 | const previousAgent = olds?.agent ?? output?.agent; |
| 289 | if (previousAgent !== undefined && news.agent !== previousAgent) { |
| 290 | return { action: "replace" as const, deleteFirst: false }; |
| 291 | } |
| 292 | const previousId = olds?.playbookId ?? output?.playbookId; |
| 293 | if ( |
| 294 | previousId !== undefined && |
| 295 | news.playbookId !== undefined && |
| 296 | news.playbookId !== previousId |
| 297 | ) { |
| 298 | return { action: "replace" as const, deleteFirst: false }; |
| 299 | } |
| 300 | return undefined; |
| 301 | }), |
| 302 | |
| 303 | read: Effect.fn(function* ({ id, olds, output }) { |
| 304 | const env = yield* GcpEnvironment.current; |
| 305 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 306 | const agent = olds?.agent ? expandAgent(olds.agent, env.project, location) : output?.agent; |
| 307 | const playbookId = yield* toResourceId(id, olds?.playbookId, output?.playbookId); |
| 308 | const name = output?.name ?? (agent !== undefined ? resourceName(agent, playbookId) : ""); |
| 309 | let existing = yield* getByName(name); |
| 310 | if (existing === undefined && agent !== undefined) { |
| 311 | const ownership = yield* internalLabels(id); |
| 312 | existing = yield* findByDisplayName( |
| 313 | agent, |
| 314 | encodeOwnershipLine(ownership, olds?.displayName), |
| 315 | ); |
| 316 | } |
| 317 | if (existing === undefined) return undefined; |
| 318 | const attrs = toAttrs(existing, env.project, agent); |
| 319 | return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs); |
| 320 | }), |
| 321 | |
| 322 | list: () => |
| 323 | Effect.gen(function* () { |
| 324 | const env = yield* GcpEnvironment.current; |
| 325 | const agents = yield* namedAgents(env.project); |
| 326 | const pages = yield* Effect.forEach(agents, (agent) => listAt(agent.name, env.project), { |
| 327 | concurrency: 4, |
| 328 | }); |
| 329 | return pages.flat(); |
| 330 | }), |
| 331 | |
| 332 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 333 | const env = yield* GcpEnvironment.current; |
| 334 | const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION); |
| 335 | const agent = expandAgent(news.agent, env.project, location); |
| 336 | const playbookId = yield* toResourceId(id, news.playbookId, output?.playbookId); |
| 337 | const name = output?.name ?? resourceName(agent, playbookId); |
| 338 | const ownership = yield* internalLabels(id); |
| 339 | const displayName = encodeOwnershipLine(ownership, news.displayName); |
| 340 | const goal = news.goal ?? DEFAULT_GOAL; |
| 341 | const playbookType = news.playbookType ?? DEFAULT_TYPE; |
| 342 | const body: dialogflow.GoogleCloudDialogflowCxV3Playbook = { |
| 343 | displayName, |
| 344 | goal, |
| 345 | instruction: news.instruction, |
| 346 | playbookType, |
| 347 | referencedTools: news.referencedTools, |
| 348 | referencedPlaybooks: news.referencedPlaybooks, |
| 349 | referencedFlows: news.referencedFlows, |
| 350 | llmModelSettings: news.llmModelSettings, |
| 351 | codeBlock: news.codeBlock, |
| 352 | inputParameterDefinitions: news.inputParameterDefinitions, |
| 353 | outputParameterDefinitions: news.outputParameterDefinitions, |
| 354 | }; |
| 355 | |
| 356 | let current = yield* getByName(output?.name ?? name); |
| 357 | if (current === undefined) { |
| 358 | current = yield* findByDisplayName(agent, displayName); |
| 359 | } |
| 360 | |
| 361 | if (current === undefined) { |
| 362 | const created = yield* dialogflow |
| 363 | .createProjectsLocationsAgentsPlaybooks({ |
| 364 | parent: agent, |
| 365 | body, |
| 366 | }) |
| 367 | .pipe(Effect.catchTag("Conflict", () => findByDisplayName(agent, displayName))); |
| 368 | current = created ?? undefined; |
| 369 | } |
| 370 | |
| 371 | if (current === undefined) { |
| 372 | return yield* new AgentsPlaybookNotResolved({ resourceName: name }); |
| 373 | } |
| 374 | |
| 375 | const currentName = current.name ?? name; |
| 376 | const displayChanged = (current.displayName ?? "") !== displayName; |
| 377 | const goalChanged = !sameText(current.goal, goal); |
| 378 | const instructionChanged = |
| 379 | fingerprint(instructionOf(current.instruction)) !== fingerprint(news.instruction); |
| 380 | const typeChanged = (current.playbookType ?? DEFAULT_TYPE) !== playbookType; |
| 381 | const toolsChanged = |
| 382 | fingerprint([...(current.referencedTools ?? [])]) !== fingerprint(news.referencedTools); |
| 383 | const playbooksChanged = |
| 384 | fingerprint([...(current.referencedPlaybooks ?? [])]) !== |
| 385 | fingerprint(news.referencedPlaybooks); |
| 386 | const flowsChanged = |
| 387 | fingerprint([...(current.referencedFlows ?? [])]) !== fingerprint(news.referencedFlows); |
| 388 | const llmChanged = |
| 389 | fingerprint(current.llmModelSettings) !== fingerprint(news.llmModelSettings); |
| 390 | const codeChanged = fingerprint(current.codeBlock) !== fingerprint(news.codeBlock); |
| 391 | const inputChanged = |
| 392 | fingerprint(current.inputParameterDefinitions) !== |
| 393 | fingerprint(news.inputParameterDefinitions); |
| 394 | const outputChanged = |
| 395 | fingerprint(current.outputParameterDefinitions) !== |
| 396 | fingerprint(news.outputParameterDefinitions); |
| 397 | |
| 398 | if ( |
| 399 | displayChanged || |
| 400 | goalChanged || |
| 401 | instructionChanged || |
| 402 | typeChanged || |
| 403 | toolsChanged || |
| 404 | playbooksChanged || |
| 405 | flowsChanged || |
| 406 | llmChanged || |
| 407 | codeChanged || |
| 408 | inputChanged || |
| 409 | outputChanged |
| 410 | ) { |
| 411 | current = yield* dialogflow.patchProjectsLocationsAgentsPlaybooks({ |
| 412 | name: currentName, |
| 413 | updateMask: updateMaskOf( |
| 414 | displayChanged ? "display_name" : undefined, |
| 415 | goalChanged ? "goal" : undefined, |
| 416 | instructionChanged ? "instruction" : undefined, |
| 417 | typeChanged ? "playbook_type" : undefined, |
| 418 | toolsChanged ? "referenced_tools" : undefined, |
| 419 | playbooksChanged ? "referenced_playbooks" : undefined, |
| 420 | flowsChanged ? "referenced_flows" : undefined, |
| 421 | llmChanged ? "llm_model_settings" : undefined, |
| 422 | codeChanged ? "code_block" : undefined, |
| 423 | inputChanged ? "input_parameter_definitions" : undefined, |
| 424 | outputChanged ? "output_parameter_definitions" : undefined, |
| 425 | ), |
| 426 | body: { ...body, name: currentName }, |
| 427 | }); |
| 428 | } |
| 429 | |
| 430 | return toAttrs(current, env.project, agent); |
| 431 | }, retryQuota), |
| 432 | |
| 433 | delete: Effect.fn(function* ({ output }) { |
| 434 | yield* dialogflow |
| 435 | .deleteProjectsLocationsAgentsPlaybooks({ name: output.name }) |
| 436 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 437 | }, retryQuota), |
| 438 | }); |