Power 开发指南

使用 @downcity/city/power 构建由 City 提供的统一 Power。

Power 作者 API 位于 @downcity/city/power。Power 是一个长期实例,不使用按 Agent 创建实例的 工厂函数;需要区分执行范围时读取 PowerContext。

import { Power, create_action } from "@downcity/city/power";

export default class ExamplePower extends Power {
  readonly name = "example";
  readonly title = "Example";
  readonly description = "An example Power.";
  readonly actions = {
    status: create_action({
      description: "Return the current scope.",
      execute: async ({ context }) => ({
        success: true,
        data: {
          agent_id: context.agent.id,
          workspace_id: context.workspace.id,
          session_id: context.session?.id ?? null,
          tool_call_id: context.call.tool_call_id ?? null,
        },
      }),
    }),
  };
}

Workspace 文件使用 context.workspace.files;Power 私有状态使用 context.storage.files; context.session 可以直接 prompt()、stop()、context() 或订阅变化。需要调用其他 Power 时使用 context.city.powers。

宿主可以直接把实例交给 City:

const city = new City({ powers: [new ExamplePower()], workspaces: [workspace] });
city.agents.add(agent);

可安装 Power 的 main 默认导出实例或 { power, main },不再提供 module.create()。Renderer 只通过宿主 action gateway 通信,不能访问 Node、Electron 或 Agent 全量对象。

实例化时注入业务回调

Power 在业务提交点报告自己的变化,应用在构造时注入处理函数。Memory 的工具、界面、Provider 直接操作和后台 Profile 优化共用同一批提交点:

const memory_power = new MemoryPower({
  platform_root_path,
  on_changed: (event) => {
    if (event.kind === "knowledge") {
      application.reload_memory(event.memory_id);
    } else {
      application.reload_profile(event.target, event.agent_id);
    }
  },
});

MemoryChange 包含 operation: written/deleted。knowledge 携带稳定 memory_id;profile 携带 target 和 agent_id(User 为 null)。事件不携带正文、物理路径或 Action 路由信息。每条实际提交的证据或投影分别通知,因此多步操作可能通知多次,后续失败也不撤销先前已写入的事实。删除不存在的记录、重复 Profile 追加及无正文变化的编辑不通知。

回调在持久化成功后调用,同步异常和 Promise rejection 独立记录,不改变数据结果,也不等待回调 Promise。应用可合并刷新,自己决定 IPC 和界面更新。Task 的 on_changed 表达定义提交与执行状态变化;Session 的 on_created/on_removed 保持自己的生命周期协议。

没有通用 action_hooks、PowerOptions 或 SDK invalidate。现有 pipeline/guard/effect 仍用于会话检查点,notifications.publish 用于用户提醒。业务回调随实例持有,没有历史重放或可靠重试,外部进程直接改文件不自动触发。其他 Power 应逐个在自己的业务提交点设计,不能从 Memory 的支持推断所有 Power 都已有实时回调。

测试时重点验证:City 内实例唯一、initialize/dispose 各一次、每次调用获得正确且独立的 PowerContext,以及 Hook 作用域在 Step 结束后释放。